Skip to content

Instantly share code, notes, and snippets.

@fabiocerqueira
Last active August 24, 2020 13:03
Show Gist options
  • Save fabiocerqueira/00fd7db405de9ac11b41201573da41c9 to your computer and use it in GitHub Desktop.
Save fabiocerqueira/00fd7db405de9ac11b41201573da41c9 to your computer and use it in GitHub Desktop.
This example shows the problem using twisted, threads and freezetime
from datetime import datetime
from functools import wraps
from freezegun import freeze_time
from twisted.internet import defer, reactor, threads
def tx_freeze_time(*ft_args, **ft_kwargs):
def decorator(func):
@wraps(func)
@defer.inlineCallbacks
def wrapper(*args, **kwargs):
with freeze_time(*ft_args, **ft_kwargs):
yield func(*args, **kwargs)
return wrapper
return decorator
def run_thread(func):
return threads.deferToThread(func)
def internal_call():
print("int", datetime.utcnow())
return False
@freeze_time("2020-03-14 00:00:00")
@defer.inlineCallbacks
def external_call_buggy():
print("ext", datetime.utcnow())
result = yield run_thread(internal_call)
defer.returnValue(result)
@tx_freeze_time("2020-03-14 00:00:00")
@defer.inlineCallbacks
def external_call():
print("ext", datetime.utcnow())
result = yield run_thread(internal_call)
defer.returnValue(result)
@defer.inlineCallbacks
def main():
print("Version with freeze_time: ")
yield external_call_buggy()
print("Version with tx_freeze_time: ")
yield external_call()
reactor.stop()
if __name__ == "__main__":
reactor.callLater(0, main)
reactor.run()
@fabiocerqueira
Copy link
Author

The output shows that using the regular freeze_time with decorator does not work, otherwise wrapping it a decorator using context manager just works.

$ python  freeze_time_threads.py 
Version with freeze_time:
('ext', FakeDatetime(2020, 3, 14, 0, 0))
('int', datetime.datetime(2020, 8, 24, 13, 2, 8, 732816))
Version with tx_freeze_time:
('ext', FakeDatetime(2020, 3, 14, 0, 0))
('int', FakeDatetime(2020, 3, 14, 0, 0))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment