7👍
To authenticate the default Django client
, you can use the force_login
method on your client
:
user = create_guest_user()
self.client.force_login(user)
If your site uses Django’s authentication system, you can use the force_login() method to simulate the effect of a user logging into the site. Use this method instead of login() when a test requires a user be logged in and the details of how a user logged in aren’t important.
To follow the redirection (or not) using the test client
, you must use the follow
argument, as described here: https://docs.djangoproject.com/en/1.11/topics/testing/tools/#django.test.Client.get
self.client.get(url, follow=True)
If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.
So your full code should look like this:
from django.test import TestCase
class MyTestCase(TestCase):
def test_mytest(self):
user = create_guest_user()
self.client.force_login(user)
response = self.client.get(reverse('my_view'), follow=True)
# Do your assertions on the response here