Debian Codegraph @

tests/auth_tests/test_login.py

raw
1 from django.contrib import auth
2 from django.contrib.auth.models import AnonymousUser, User
3 from django.http import HttpRequest
4 from django.test import TestCase
5 from django.utils.deprecation import RemovedInDjango61Warning
6
7
8 class TestLogin(TestCase):
9 @classmethod
10 def setUpTestData(cls):
11 cls.user = User.objects.create_user(username="testuser", password="password")
12
13 def setUp(self):
14 self.request = HttpRequest()
15 self.request.session = self.client.session
16
17 def test_user_login(self):
18 auth.login(self.request, self.user)
19 self.assertEqual(self.request.session[auth.SESSION_KEY], str(self.user.pk))
20
21 def test_inactive_user(self):
22 self.user.is_active = False
23 self.user.save(update_fields=["is_active"])
24
25 auth.login(self.request, self.user)
26 self.assertEqual(self.request.session[auth.SESSION_KEY], str(self.user.pk))
27
28 # RemovedInDjango61Warning: When the deprecation ends, replace with:
29 # def test_without_user(self):
30 def test_without_user_no_request_user(self):
31 # RemovedInDjango61Warning: When the deprecation ends, replace with:
32 # with self.assertRaisesMessage(
33 # AttributeError,
34 # "'NoneType' object has no attribute 'get_session_auth_hash'",
35 # ):
36 # auth.login(self.request, None)
37 with (
38 self.assertRaisesMessage(
39 AttributeError,
40 "'HttpRequest' object has no attribute 'user'",
41 ),
42 self.assertWarnsMessage(
43 RemovedInDjango61Warning,
44 "Fallback to request.user when user is None will be removed.",
45 ),
46 ):
47 auth.login(self.request, None)
48
49 # RemovedInDjango61Warning: When the deprecation ends, remove completely.
50 def test_without_user_anonymous_request(self):
51 self.request.user = AnonymousUser()
52 with (
53 self.assertRaisesMessage(
54 AttributeError,
55 "'AnonymousUser' object has no attribute '_meta'",
56 ),
57 self.assertWarnsMessage(
58 RemovedInDjango61Warning,
59 "Fallback to request.user when user is None will be removed.",
60 ),
61 ):
62 auth.login(self.request, None)
63
64 # RemovedInDjango61Warning: When the deprecation ends, remove completely.
65 def test_without_user_authenticated_request(self):
66 self.request.user = self.user
67 self.assertNotIn(auth.SESSION_KEY, self.request.session)
68
69 msg = "Fallback to request.user when user is None will be removed."
70 with self.assertWarnsMessage(RemovedInDjango61Warning, msg):
71 auth.login(self.request, None)
72 self.assertEqual(self.request.session[auth.SESSION_KEY], str(self.user.pk))