Skip to content

Instantly share code, notes, and snippets.

@russelldavis
Created October 31, 2012 20:32
Show Gist options
  • Save russelldavis/3989658 to your computer and use it in GitHub Desktop.
Save russelldavis/3989658 to your computer and use it in GitHub Desktop.
Context manager for patching python date and time functions for unit tests
# Required because datetime.date is a builtin type that can't be modified
class MockDate(date):
"A wrapper for date that can be mocked for testing."
def __new__(cls, *args, **kwargs):
return date.__new__(date, *args, **kwargs)
# Required because datetime.datetime is a builtin type that can't be modified
class MockDateTime(datetime):
"A wrapper for datetime that can be mocked for testing."
def __new__(cls, *args, **kwargs):
return datetime.__new__(date, *args, **kwargs)
@contextmanager
def time_offset(**kwargs):
"""
Returns a context manager that changes the return value of date and time
functions for it's duration. The value will be an offset from the real time,
specified by kwargs as used by timedelta.
The following functions are patched:
time.time, date.today, datetime.today, datetime.now, datetime.utcnow
"""
time_time = time.time
date_today = date.today
datetime_today = datetime.today
datetime_now = datetime.now
datetime_utcnow = datetime.utcnow
delta = timedelta(**kwargs)
with patch('time.time', lambda: time_time() + delta.total_seconds()), \
patch('datetime.date', MockDate), \
patch('datetime.datetime', MockDateTime), \
patch('datetime.date.today', lambda: date_today() + delta), \
patch('datetime.datetime.today', lambda: datetime_today() + delta), \
patch('datetime.datetime.now', lambda: datetime_now() + delta), \
patch('datetime.datetime.utcnow', lambda: datetime_utcnow() + delta):
yield
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment