Skip to content

Commit

Permalink
Fix pendulum.test to properly unwind after an exception
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
njsmith committed Mar 5, 2020
1 parent e4cbd28 commit 2c11502
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
8 changes: 4 additions & 4 deletions pendulum/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,10 @@ def _sign(x):
@contextmanager
def test(mock):
set_test_now(mock)

yield

set_test_now()
try:
yield
finally:
set_test_now()


def set_test_now(test_now=None):
Expand Down
18 changes: 18 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,21 @@ def test_week_ends_at_invalid_value():

with pytest.raises(ValueError):
pendulum.week_ends_at(11)


def test_with_test():
t = pendulum.datetime(2000, 1, 1)

with pendulum.test(t):
assert pendulum.now() == t

assert pendulum.now() != t


# Also make sure that it restores things after an exception
with pytest.raises(RuntimeError):
with pendulum.test(t):
assert pendulum.now() == t
raise RuntimeError

assert pendulum.now() != t

0 comments on commit 2c11502

Please sign in to comment.