Last active
August 24, 2020 13:03
-
-
Save fabiocerqueira/00fd7db405de9ac11b41201573da41c9 to your computer and use it in GitHub Desktop.
This example shows the problem using twisted, threads and freezetime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output shows that using the regular freeze_time with decorator does not work, otherwise wrapping it a decorator using context manager just works.