I need to test if my user is logged out correctly. When I tried to logout, the test fails.
def test_user_logout(self):
"""Test user logout."""
user = User.objects.create_user(username="test", password="test")
self.logged_in = self.client.force_login(user=user)
response = self.client.post(path=reverse("logout"), follow=True)
self.assertEqual(response.status_code, 200)
self.assertRedirects(response, reverse("login"))
self.assertTrue(user.is_anonymous) # this fails
My view method is:
def user_logout(request):
logout(request)
return redirect("login")
CodePudding user response:
A User
object does not hold if that user is logged in (in any session). Logged in is session-oriented, not user-oriented, so that means that for a given session you are logged in, if the session variables refer to a user. A User
can thus be logged in in multiple sessions at the same time.
For a User
model [Django-doc] object, is_authenticated
[Django-doc] will always be True
, and is_anonymous
[Django-doc] will always be False
, regardless whether there is any session where you have logged in.
Django however has already a LogoutView
view [Django-doc]. It is the responsibility of the developers of Django to test this view effectively. Your logout_view
can thus be replaced with this view. You can set the LOGOUT_REDIRECT_URL
setting [Django-doc] to:
# settings.py
LOGOUT_REDIRECT_URL = 'login'
and then use LogoutView.as_view()
in the urls as view to log out.
Usually it is better to work with logical components that are already implemented by Django, this moves the burden of implementing, testing, maintaining and bugfixing from you to the Django developers, and since a lot of users use these views, it is likely that mistakes will be detected and fixed more effectively.