Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django response context using pytest-django client is always None

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().

like image 287
Phil Gyford Avatar asked May 31 '26 22:05

Phil Gyford


1 Answers

In the client link you provided, states that the client is an instance of the django.test.Client so in reality it doesn't do anything special there and shouldn't be a problem.

You need to setup your environment as you correctly stated.
Let's have a look at the error now:

from the setup_test_environment() source code:

if hasattr(_TestState, 'saved_data'):
      # Executing this function twice would overwrite the saved values.
      raise RuntimeError(
          "setup_test_environment() was already called and can't be called "
          "again without first calling teardown_test_environment()."
)

And that is what raises your RuntimeError above.

Let's look now at the teardown_test_environment() method:

...
del _TestState.saved_data

So it deletes the culprit of the aforementioned exception.

Thus:

from django.test.utils import teardown_test_environment, setup_test_environment

try:
    # If setup_test_environment haven't been called previously this
    # will produce an AttributeError.
    teardown_test_environment()
except AttributeError:
    pass

setup_test_environment() 

...
like image 80
John Moutafis Avatar answered Jun 02 '26 10:06

John Moutafis