|
2 | 2 | #
|
3 | 3 | # SPDX-License-Identifier: MIT
|
4 | 4 |
|
| 5 | +from contextlib import suppress |
5 | 6 | from threading import Lock
|
6 | 7 |
|
7 |
| -from stamina import is_active, set_active |
8 |
| -from stamina._config import _Config, _Testing |
| 8 | +from stamina import is_active, is_testing, set_active, set_testing |
| 9 | +from stamina._config import CONFIG, _Config, _Testing |
9 | 10 |
|
10 | 11 |
|
11 | 12 | def test_activate_deactivate():
|
@@ -67,3 +68,49 @@ def test_cap_true_with_none(self):
|
67 | 68 | t = _Testing(100, True)
|
68 | 69 |
|
69 | 70 | assert 100 == t.get_attempts(None)
|
| 71 | + |
| 72 | + def test_context_manager(self): |
| 73 | + """ |
| 74 | + set_testing works as a context manager. |
| 75 | + """ |
| 76 | + assert not is_testing() |
| 77 | + |
| 78 | + with set_testing(True, attempts=3): |
| 79 | + assert is_testing() |
| 80 | + assert 3 == CONFIG.testing.get_attempts(None) |
| 81 | + assert not CONFIG.testing.cap |
| 82 | + |
| 83 | + assert not is_testing() |
| 84 | + |
| 85 | + def test_context_manager_nested(self): |
| 86 | + """ |
| 87 | + set_testing context managers can be nested. |
| 88 | + """ |
| 89 | + assert not is_testing() |
| 90 | + |
| 91 | + with set_testing(True, attempts=3): |
| 92 | + assert is_testing() |
| 93 | + assert CONFIG.testing.attempts == 3 |
| 94 | + |
| 95 | + with set_testing(True, attempts=5, cap=True): |
| 96 | + assert is_testing() |
| 97 | + assert CONFIG.testing.attempts == 5 |
| 98 | + assert CONFIG.testing.cap |
| 99 | + |
| 100 | + assert is_testing() |
| 101 | + assert CONFIG.testing.attempts == 3 |
| 102 | + assert not CONFIG.testing.cap |
| 103 | + |
| 104 | + assert not is_testing() |
| 105 | + |
| 106 | + def test_context_manager_exception(self): |
| 107 | + """ |
| 108 | + set_testing context manager restores state even if an exception occurs. |
| 109 | + """ |
| 110 | + assert not is_testing() |
| 111 | + |
| 112 | + with suppress(ValueError), set_testing(True, attempts=3): |
| 113 | + assert is_testing() |
| 114 | + raise ValueError("test") |
| 115 | + |
| 116 | + assert not is_testing() |
0 commit comments