I am trying to test whether a celery task has been started after a request to my django server. I have something like this:
# tasks.py
def add(x, y):
return x + y
# views.py
def home(request): # respond to request at root url
tasks.add.delay(1,2)
return HttpResponse('hello world')
# tests.py
class MyTest(TestCase):
def test_task_triggered(self):
self.client.get('/')
# XXXX HOW TO TEST THAT TASK HAS BEEN TRIGGERED?
How can I test whether or not the task has been started in my unit tests? Obviously, I don’t have direct access to the task id otherwise something like this would work.
More generally, how can you detect celery tasks being triggered from across functions, classes, or modules?
Thanks for your help.
You can use Mock for this (when unit testing). Patch out the
delayattribute on your task, and then check thecalledattribute of the mock. In your example, try something like:The caveat is that once you’ve done this, tasks.add won’t actually be called in this test case, as we’ve replaced it with a mock. This test would simply assert that it’s being called (and you could check
patch_mock.call_args_listto assert it’s being called with the correct arguments)If that’s a deal-breaker – you want to assert in one test case that a task is being called, as well as the impact/side effects of the task – you could experiment with the
wrapsattribute ofmock, which might work:But the other way is probably better, since it better isolates what’s being tested.