I have a Django app that uses the builtin login system.
I'm trying to write a unit test that verifies that the login
url redirects to home
if the user is already authenticated. Meaning, if an already authenticated user tries to visit the login
url, they get redirected to home
.
This is a built-in feature of Django's LoginView
, and I have verified that it is indeed working. However, I'm not sure how to write a unit test for this.
Question: How do I verify that this redirect occurs via unit tests? LoginView
returns a TemplateResponse
, which doesn't have a url
parameter.
What I have so far is this:
from django.test import TestCase
from django.urls import reverse
home = reverse('home')
login = reverse('login')
logout = reverse('logout')
signup = reverse('signup')
USER_CREDS = { some users credentials }
class TestLoginView(TestCase):
def test_login_redirect(self):
self.client.post(signup, USER_CREDS)
self.client.get(logout)
self.client.post(login, USER_CREDS)
response = self.client.get(login)
self.assertRedirects(response, home)
EDIT:
SimpleTestCase.assertRedirects
does not work for TemplateResponse
objects.
TemplateResponse
objects do not contain a url
parameter, which is required for SimpleTestCase.assertRedirect
.
The method raises the following error: AttributeError: 'TemplateResponse' object has no attribute 'url'
This is not the same as the linked question, because the response object from a LoginView
is a TemplateResponse
, not an HttpResponse
.