I'm using django-q and I'm currently working on adding tests using mock
for my existing tasks. I could easily create tests for each task without depending on django-q but one of my task is calling another async_task
. Here's an example:
import requests
from django_q.tasks import async_task
task_a():
response = requests.get(url)
# process response here
if condition:
async_task('task_b')
task_b():
response = requests.get(another_url)
And here's how I test them:
import requests
from .tasks import task_a
from .mock_responses import task_a_response
@mock.patch.object(requests, "get")
@mock.patch("django_q.tasks.async_task")
def test_async_task(self, mock_async_task, mock_task_a):
mock_task_a.return_value.status_code = 200
mock_task_a.return_value.json.return_value = task_a_response
mock_async_task.return_value = "12345"
# execute the task
task_a()
self.assertTrue(mock_task_a.called)
self.assertTrue(mock_async_task.called)
I know for a fact that async_task
returns the task ID, hence the line, mock_async_task.return_value = "12345"
. However, after running the test, mock_async_task
returns False
and the task is being added into the queue (I could see a bunch of 01:42:59 [Q] INFO Enqueued 1
from the server) which is what I'm trying to avoid. Is there any way to accomplish this?