Search code examples
pythondjangodjango-authentication

Why is user.is_authenticated asserting true after logout


I am trying to write a test for logging out a user in Django. Here is the code:

urls.py

from django.conf.urls import url
from django.contrib import admin
from accounts.views import LoginView, LogoutView


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', LoginView.as_view(), name='login'),
    url(r'^logout/', LogoutView.as_view(), name='logout'),
]

views.py

from django.http import HttpResponseRedirect
from django.contrib.auth import login, logout
from django.views.generic import View


class LogoutView(View):
    def get(self, request):
        logout(request)
        return HttpResponseRedirect('/')

tests.py

from django.test import TestCase, Client
from django.contrib.auth.models import User


class LogoutTest(TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user(
            username='user1',
            email='user1_123@gmail.com',
            password='top_secret123'
        )

    def test_user_logs_out(self):
        self.client.login(email=self.user.email, password=self.user.password)
        self.assertTrue(self.user.is_authenticated)

        response = self.client.get('/logout/')

        self.assertFalse(self.user.is_authenticated)
        self.assertRedirects(response, '/', 302)

The assertion self.assertFalse(self.user.is_authenticated) is failing. Testing through the browser seems to work fine. It seems like the user would not be authenticated after calling logout(). Am I missing something?


Solution

  • It seems like the user would not be authenticated after calling logout(). Am I missing something?

    .is_authenticated [Django-doc] does not check if a user is logged in. Every real User returns always True for is_authenticated. An AnonymousUser [Django-doc] will return False for example. If you thus log out, then request.user will be the AnonymousUser, and thus not be authenticated.

    In other words, if you use request.user.is_authenticated, you will call this on the logged-in user if the session is bounded to a user (you logged in with the browser), and you call this on the AnonymousUser in case the browser did not log in a user/the browser logged out.