|
| 1 | +from configmanager import Config |
| 2 | + |
| 3 | + |
| 4 | +def test_tracking_context(): |
| 5 | + config = Config({ |
| 6 | + 'greeting': 'Hello, world!', |
| 7 | + 'db': { |
| 8 | + 'user': 'root', |
| 9 | + }, |
| 10 | + }) |
| 11 | + |
| 12 | + ctx1 = config.tracking_context() |
| 13 | + ctx1.push() |
| 14 | + ctx1.pop() |
| 15 | + |
| 16 | + assert ctx1.changes == {} |
| 17 | + |
| 18 | + with config.tracking_context() as ctx2: |
| 19 | + pass |
| 20 | + |
| 21 | + assert ctx2.changes == {} |
| 22 | + |
| 23 | + assert ctx1.changes == {} |
| 24 | + assert ctx1 is not ctx2 |
| 25 | + |
| 26 | + ctx3 = config.tracking_context() |
| 27 | + ctx3.push() |
| 28 | + |
| 29 | + config.greeting.value = 'Hey!' |
| 30 | + assert ctx3.changes == {config.greeting: 'Hey!'} |
| 31 | + |
| 32 | + ctx3.pop() |
| 33 | + assert ctx3.changes == {config.greeting: 'Hey!'} |
| 34 | + |
| 35 | + # ctx3 is no longer tracking changes |
| 36 | + config.greeting.value = 'What is up!' |
| 37 | + assert ctx3.changes == {config.greeting: 'Hey!'} |
| 38 | + |
| 39 | + # neither are ctx1 and ctx2 |
| 40 | + assert ctx1.changes == {} |
| 41 | + assert ctx2.changes == {} |
| 42 | + |
| 43 | + # track in ctx3: |
| 44 | + with ctx3: |
| 45 | + config.db.user.value = 'admin' |
| 46 | + assert ctx3.changes == {config.greeting: 'Hey!', config.db.user: 'admin'} |
| 47 | + assert ctx3.changes == {config.greeting: 'Hey!', config.db.user: 'admin'} |
| 48 | + |
| 49 | + # again, ctx3 is no longer tracking |
| 50 | + config.db.user.value = 'Administrator' |
| 51 | + |
| 52 | + assert ctx3.changes == {config.greeting: 'Hey!', config.db.user: 'admin'} |
| 53 | + |
| 54 | + # neither are ctx1 and ctx2 |
| 55 | + assert ctx1.changes == {} |
| 56 | + assert ctx2.changes == {} |
| 57 | + |
| 58 | + # nested contexts |
| 59 | + |
| 60 | + with ctx1: |
| 61 | + config.db.user.value = 'user-in-ctx1' |
| 62 | + |
| 63 | + with ctx2: |
| 64 | + config.greeting.value = 'greeting-in-ctx2' |
| 65 | + |
| 66 | + config.greeting.value = 'greeting-in-ctx1' |
| 67 | + |
| 68 | + assert ctx1.changes == {config.db.user: 'user-in-ctx1', config.greeting: 'greeting-in-ctx1'} |
| 69 | + assert ctx2.changes == {config.greeting: 'greeting-in-ctx2'} |
0 commit comments