Skip to content

Instantly share code, notes, and snippets.

@jrobichaud
Created May 9, 2017 13:27
Show Gist options
  • Save jrobichaud/f24ed7202f41f271102d86177ea2f3b6 to your computer and use it in GitHub Desktop.
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.
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