[memory-box] Mocking celery tasks with pytest and pytest.mock

“memory-box” is just a little personal series where I’ll share some useful snippets

# examples/views.py
from examples.tasks import send_document
from examples.forms import ExampleForm

class ExampleCreateView(CreateView):
form_class = ExampleForm

def form_valid(self, form):
# ...
send_document.delay(example.id)
# ....
# examples/tests.py
import pytest

@pytest.mark.django_db
def test_create_example(mocker, client):
# ....
mock_task = mocker.patch("examples.tasks.send_document.delay")
url = reverse("examples:example_create")

response = client.post(url, data=form_data)

mock_task.assert_called()