Skip to content

Commit 4acc84f

Browse files
njsmithSébastien Eustace
authored andcommitted
Fix pendulum.test to properly unwind after an exception
Previously, if an exception occurred inside a 'with pendulum.test(...)' block, then the monkeypatch would remain in place instead of being un-done. This could cause confusing results, as one failing test could cause other tests to run with an unexpected mock in place and cause other failures.
1 parent 74859ae commit 4acc84f

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

pendulum/helpers.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,10 @@ def _sign(x):
174174
@contextmanager
175175
def test(mock): # type: (pendulum.DateTime) -> Iterator[None]
176176
set_test_now(mock)
177-
178-
yield
179-
180-
set_test_now()
177+
try:
178+
yield
179+
finally:
180+
set_test_now()
181181

182182

183183
def set_test_now(test_now=None): # type: (Optional[pendulum.DateTime]) -> None

tests/test_helpers.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,3 +190,20 @@ def test_week_ends_at_invalid_value():
190190

191191
with pytest.raises(ValueError):
192192
pendulum.week_ends_at(11)
193+
194+
195+
def test_with_test():
196+
t = pendulum.datetime(2000, 1, 1)
197+
198+
with pendulum.test(t):
199+
assert pendulum.now() == t
200+
201+
assert pendulum.now() != t
202+
203+
# Also make sure that it restores things after an exception
204+
with pytest.raises(RuntimeError):
205+
with pendulum.test(t):
206+
assert pendulum.now() == t
207+
raise RuntimeError
208+
209+
assert pendulum.now() != t

0 commit comments

Comments
 (0)