Skip to content

Instantly share code, notes, and snippets.

@CptSpaceToaster
Created August 19, 2019 23:50
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 CptSpaceToaster/b5fe40a9aca09271036e4947ac6b4776 to your computer and use it in GitHub Desktop.
Save CptSpaceToaster/b5fe40a9aca09271036e4947ac6b4776 to your computer and use it in GitHub Desktop.
import datetime
import pytest
from freezegun import freeze_time
@pytest.fixture()
def timeboat():
"""Grab the helm of the timeboat, we're going on an adventure!
Allows the test writer to freeze time so that time.time() returns a controlled value
https://stackoverflow.com/a/28073449/4717806"""
class Timeboat():
"""Timeboat Class"""
@classmethod
def freeze_now(cls, tz=None):
"""Freezes time to whatever now is"""
if tz:
cls.freezegun_ctx = freeze_time(tz.localize(datetime.datetime.now()))
else:
cls.freezegun_ctx = freeze_time(datetime.datetime.now())
cls.freezegun_ctx.start()
@classmethod
def freeze(cls, *args, tz=None, **kwargs):
"""Freezes time at the specified value"""
if tz:
cls.freezegun_ctx = freeze_time(tz.localize(datetime.datetime(*args, **kwargs)))
else:
cls.freezegun_ctx = freeze_time(datetime.datetime(*args, **kwargs))
cls.freezegun_ctx.start()
@classmethod
def unfreeze(cls):
"""Unfreezes time"""
if hasattr(cls, 'freezegun_ctx'):
cls.freezegun_ctx.stop()
del cls.freezegun_ctx
@classmethod
def shift(cls, timedelta=None, **kwargs):
""" Moves time fwd/bwd by the delta"""
cls.freezegun_ctx.stop()
if not timedelta:
timedelta = datetime.timedelta(**kwargs)
cls.freezegun_ctx.time_to_freeze += timedelta
cls.freezegun_ctx.start()
yield Timeboat
Timeboat.unfreeze()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment