[Fixed]-Django unit test client response has empty context

5👍

Today I run into the same issue. The second test gets same page has nothing in response.context

I made a research and found that
1) test client uses signals to populate context,
2) my view method is not called for the second test

I turned on a debugger and found that the guilty one is ‘Cache middleware’. Knowing that I found this ticket and this SO question (the latter has a solution).

So, in short: the second request is served from cache, not from a view, thus a view is not executed and test-client doesn’t get the signal and have no ability to populate context.

I can not disable cache middleware for my project, so I added next hack-lines into my settings:

if 'test' in sys.argv:
   CACHE_MIDDLEWARE_SECONDS = 0

Hope this helps someone

👤akava

9👍

It’s because you ran into some error, exited the shell and restarted it.

But you forgot to start environment

from django.test.utils import setup_test_environment
>>> setup_test_environment()

That was my problem. Hope it works…

👤Nabin

1👍

You can also clear cache manually by calling cache.clear() inside a test method:

from django.core.cache import cache
import pytest


class TestPostView:

    @pytest.mark.django_db(transaction=True)
    def test_index_post(self, client, post):
        cache.clear()
        response = client.get('/')

Leave a comment