Skip to content

Instantly share code, notes, and snippets.

@ctheune
Created February 3, 2015 13:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctheune/45c118a2be815009ba00 to your computer and use it in GitHub Desktop.
Save ctheune/45c118a2be815009ba00 to your computer and use it in GitHub Desktop.
Timetravel in unit tests
def test_something(now):
# now is a mock returned by a custom pytest fixture
with TimeTravel(now, datetime(2010, 1, 1)):
do_something_in_the_past()
do_something_at_the_regular_mocked_time()
class TimeTravel(object):
def __init__(self, mock, whereto):
self.mock = mock
self.whereto = whereto
def __enter__(self):
self.old = self.mock.return_value
self.mock.return_value = self.whereto
def __exit__(self, exc_type, exc_value, exc_tb):
self.mock.return_value = self.old
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment