Django response context using pytest-django client is always None

Viewed 2125

I'm using pytest-django to test some Django views.

I want to test that the response context contains certain values, but it's always None.

My view:

from django.views.generic import TemplateView

class MyView(TemplateView):
    template_name = 'my_template.html'

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['hello'] = 'hi'
        return context

My test:

def test_context(client):
    response = client.get('/test/')
    print('status', response.status_code)
    print('content', response.content)
    print('context', response.context)

If I run this with the -s flag to see the print statements, the status code is 200, and content contains the rendered template, including the "hi" that's in the context. But context is None.

I thought this client was the same as django.test.Client which should let me see the context... so what am I missing?

I've tried this answer but got

RuntimeError: setup_test_environment() was already called and can't be called again without first calling teardown_test_environment().

1 Answers
Related