Created
May 9, 2017 13:27
-
-
Save jrobichaud/f24ed7202f41f271102d86177ea2f3b6 to your computer and use it in GitHub Desktop.
Context manager to allow to run scheduled tasks "synced" during tests. The calls will run just when leaving the "with" statement.
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 unittest import mock | |
class SyncScheduledTasks: | |
patch = None | |
calls = None | |
def __init__(self): | |
self.calls = [] | |
self.patch = None | |
def __enter__(self): | |
# noinspection PyUnusedLocal | |
def schedule(func_name, *args, **kwargs): | |
# noinspection PyProtectedMember | |
self.calls.append( | |
( | |
mock._importer(func_name), | |
args, | |
) | |
) | |
self.patch = mock.patch('django_q.tasks.schedule', new=schedule) | |
self.patch.start() | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
try: | |
if not len(self.calls): | |
raise AssertionError("'django_q.tasks.schedule' was not called") | |
for func, args in self.calls: | |
func(*args) | |
finally: | |
self.patch.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment