I know this questions has already been asked, but none of the answers works for me.
Whenever I try to use the client login in Django tests, it basically gets ignored and I get a redirect to the login page. After a few test I noticed that it logs me in correctly, but kicks me out when I use it.
Here is a stripped down version of my code that still reproduces this.
from django.auth import get_user
# [...]
class MapListViewTest(TestCase):
@classmethod
def setUpTestData(cls):
# Create a user
cls.user = get_user_model().objects.create(username="testuser")
cls.user.set_password("password")
cls.user.save()
# [...]
def setUp(self):
self.client.login(
username=self.user.get_username(), password=self.user.password
)
def test_map_list_view_renders(self):
"""Test that the MapListView renders successfully and includes a list of maps."""
logger.info(get_user(self.client)) # <-- <django.contrib.auth.models.AnonymousUser object at 0x7377d5589540>
self.client.login(
username=self.user.get_username(), password=self.user.password
)
logger.info(get_user(self.client)) # <-- <Profile: testuser>
response = self.client.get(reverse("map_list"), follow=True)
logger.info(get_user(self.client)) # <-- <django.contrib.auth.models.AnonymousUser object at 0x7377d5589540>
self.assertEqual(response.status_code, 200) # <-- OK
self.assertTemplateUsed(response, "map_list.html") # <-- lands on 'account/login.html'
(I put it twice here in the snippet, but it is only in the setUp in the real code)
I don’t know if this is of any relevance, but the redirection changes the address from http://localhost/...
to http://testserver/...
, and I am working in a docker container.
Also, the user model inherits from AbstractUser and has no custom logic on login.