[Django]-Testing views with pytest, how to mock celery task

2👍

Decision

@patch.object(my_celery_task, 'delay')
@pytest.mark.django_db
def test_create(mock_delay, api_client):    
    response = api_client.post(reverse('withdraw-act-list'), data=request_data, format='json')
    assert response.status_code == 201

I should pass mock_delay as parameter into my test function (as first parameter, it’s important)

1👍

Most likely Celery runs in another thread and your mock in current thread is useless, you need to enable synchronous operations by this option in your test environment:

CELERY_ALWAYS_EAGER = True

and possibly this to get exceptions:

CELERY_EAGER_PROPAGATES = True

Leave a comment