12👍
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}}
session.save()
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.
6👍
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.
- How can I create a partial search filter in Django REST framework?
- How to order a Django Rest Framework ManyToMany related field?
- Django admin – how to get all registered models in templatetag?
1👍
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
- Create a separate app for my REST API or place it inside my working app?
- How do I update an object's members using a dict?
- Django – how can I access the form field from inside a custom widget
- Is a varchar 2 more efficient than a varchar 255?
1👍
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
@patch('myapplication.views.render')
def test_(self, mock_render, rf):
request = rf.get('fake-url')
view(request)
context = self.context(mock_render.call_args)
keytotest = 'crch'
assert keytotest == context['keytotest']
- Django transaction management
- Docker Django could not connect to server: Connection refused
- How to thumbnail static files?
-6👍
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/')
response.context