[Solved]-Can i access the response context of a view tested without the test client?


The RequestFactory does not touch the Django middleware, and as such, you will not generate a context (i.e. no ContextManager middleware).

If you want to test the context, you should use the test client. You can still manipulate the construction of the request in the test client either using mock or simply saving your session ahead of time in the test, such as:

from django.test import Client
c = Client()
session = c.session
session['backend'] = 'facebook'
session['kwargs'] = {'username':'Chuck Norris','response':{'id':1}}

Now when you load the view with the test client, you’ll be using the session as you set it, and when you use response = c.get('/yourURL/'), you can then reference the response context using response.context as desired.


The “response.context” is incorrect for new django versions but you can use response.context_data to get the same context that passed to TemplateResponse.



Though this is an old post, I suppose this tip can be of help. You can look into using TemplateResponse (or SimpleTemplateResponse) which can be substituted for render or render_to_response.

The Django docs has more on this


Yes, you can. You have to patch render.

I’m using pytest-django

class Test:
    def context(self, call_args):
        args, kwargs = call_args
        request_mock, template, context = args
        return context

    def test_(self, mock_render, rf):
        request = rf.get('fake-url')
        context = self.context(mock_render.call_args)

        keytotest = 'crch'
        assert keytotest == context['keytotest']


context (sic!) can be found in Response class. As you see it says it’s HTTPResponse you get back from the view function. This happened because you’ve called it directly. Call this function via test client and it will be okay.

response = client.get('/fobarbaz/')

Leave a comment