Debian Codegraph @

tests/messages_tests/test_cookie.py

raw
1 import json
2 import random
3 from unittest import TestCase
4
5 from django.conf import settings
6 from django.contrib.messages import Message, constants
7 from django.contrib.messages.storage.cookie import (
8 CookieStorage,
9 MessageDecoder,
10 MessageEncoder,
11 bisect_keep_left,
12 bisect_keep_right,
13 )
14 from django.test import SimpleTestCase, override_settings
15 from django.utils.crypto import get_random_string
16 from django.utils.safestring import SafeData, mark_safe
17
18 from .base import BaseTests
19
20
21 def set_cookie_data(storage, messages, invalid=False, encode_empty=False):
22 """
23 Set ``request.COOKIES`` with the encoded data and remove the storage
24 backend's loaded data cache.
25 """
26 encoded_data = storage._encode(messages, encode_empty=encode_empty)
27 if invalid:
28 # Truncate the first character so that the hash is invalid.
29 encoded_data = encoded_data[1:]
30 storage.request.COOKIES = {CookieStorage.cookie_name: encoded_data}
31 if hasattr(storage, "_loaded_data"):
32 del storage._loaded_data
33
34
35 def stored_cookie_messages_count(storage, response):
36 """
37 Return an integer containing the number of messages stored.
38 """
39 # Get a list of cookies, excluding ones with a max-age of 0 (because
40 # they have been marked for deletion).
41 cookie = response.cookies.get(storage.cookie_name)
42 if not cookie or cookie["max-age"] == 0:
43 return 0
44 data = storage._decode(cookie.value)
45 if not data:
46 return 0
47 if data[-1] == CookieStorage.not_finished:
48 data.pop()
49 return len(data)
50
51
52 @override_settings(
53 SESSION_COOKIE_DOMAIN=".example.com",
54 SESSION_COOKIE_SECURE=True,
55 SESSION_COOKIE_HTTPONLY=True,
56 )
57 class CookieTests(BaseTests, SimpleTestCase):
58 storage_class = CookieStorage
59
60 def stored_messages_count(self, storage, response):
61 return stored_cookie_messages_count(storage, response)
62
63 def encode_decode(self, *args, **kwargs):
64 storage = self.get_storage()
65 message = [Message(constants.DEBUG, *args, **kwargs)]
66 encoded = storage._encode(message)
67 return storage._decode(encoded)[0]
68
69 def test_get(self):
70 storage = self.storage_class(self.get_request())
71 # Set initial data.
72 example_messages = ["test", "me"]
73 set_cookie_data(storage, example_messages)
74 # The message contains what's expected.
75 self.assertEqual(list(storage), example_messages)
76
77 @override_settings(SESSION_COOKIE_SAMESITE="Strict")
78 def test_cookie_settings(self):
79 """
80 CookieStorage honors SESSION_COOKIE_DOMAIN, SESSION_COOKIE_SECURE, and
81 SESSION_COOKIE_HTTPONLY (#15618, #20972).
82 """
83 # Test before the messages have been consumed
84 storage = self.get_storage()
85 response = self.get_response()
86 storage.add(constants.INFO, "test")
87 storage.update(response)
88 messages = storage._decode(response.cookies["messages"].value)
89 self.assertEqual(len(messages), 1)
90 self.assertEqual(messages[0].message, "test")
91 self.assertEqual(response.cookies["messages"]["domain"], ".example.com")
92 self.assertEqual(response.cookies["messages"]["expires"], "")
93 self.assertIs(response.cookies["messages"]["secure"], True)
94 self.assertIs(response.cookies["messages"]["httponly"], True)
95 self.assertEqual(response.cookies["messages"]["samesite"], "Strict")
96
97 # Deletion of the cookie (storing with an empty value) after the
98 # messages have been consumed.
99 storage = self.get_storage()
100 response = self.get_response()
101 storage.add(constants.INFO, "test")
102 for m in storage:
103 pass # Iterate through the storage to simulate consumption of messages.
104 storage.update(response)
105 self.assertEqual(response.cookies["messages"].value, "")
106 self.assertEqual(response.cookies["messages"]["domain"], ".example.com")
107 self.assertEqual(
108 response.cookies["messages"]["expires"], "Thu, 01 Jan 1970 00:00:00 GMT"
109 )
110 self.assertEqual(
111 response.cookies["messages"]["samesite"],
112 settings.SESSION_COOKIE_SAMESITE,
113 )
114
115 def test_get_bad_cookie(self):
116 request = self.get_request()
117 storage = self.storage_class(request)
118 # Set initial (invalid) data.
119 example_messages = ["test", "me"]
120 set_cookie_data(storage, example_messages, invalid=True)
121 # The message actually contains what we expect.
122 self.assertEqual(list(storage), [])
123
124 def test_max_cookie_length(self):
125 """
126 If the data exceeds what is allowed in a cookie, older messages are
127 removed before saving (and returned by the ``update`` method).
128 """
129 storage = self.get_storage()
130 response = self.get_response()
131
132 # When storing as a cookie, the cookie has constant overhead of approx
133 # 54 chars, and each message has a constant overhead of about 37 chars
134 # and a variable overhead of zero in the best case. We aim for a message
135 # size which will fit 4 messages into the cookie, but not 5.
136 # See also FallbackTest.test_session_fallback
137 msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37)
138 first_msg = None
139 # Generate the same (tested) content every time that does not get run
140 # through zlib compression.
141 random.seed(42)
142 for i in range(5):
143 msg = get_random_string(msg_size)
144 storage.add(constants.INFO, msg)
145 if i == 0:
146 first_msg = msg
147 unstored_messages = storage.update(response)
148
149 cookie_storing = self.stored_messages_count(storage, response)
150 self.assertEqual(cookie_storing, 4)
151
152 self.assertEqual(len(unstored_messages), 1)
153 self.assertEqual(unstored_messages[0].message, first_msg)
154
155 def test_message_rfc6265(self):
156 non_compliant_chars = ["\\", ",", ";", '"']
157 messages = ["\\te,st", ';m"e', "\u2019", '123"NOTRECEIVED"']
158 storage = self.get_storage()
159 encoded = storage._encode(messages)
160 for illegal in non_compliant_chars:
161 self.assertEqual(encoded.find(illegal), -1)
162
163 def test_json_encoder_decoder(self):
164 """
165 A complex nested data structure containing Message
166 instances is properly encoded/decoded by the custom JSON
167 encoder/decoder classes.
168 """
169 messages = [
170 {
171 "message": Message(constants.INFO, "Test message"),
172 "message_list": [
173 Message(constants.INFO, "message %s") for x in range(5)
174 ]
175 + [{"another-message": Message(constants.ERROR, "error")}],
176 },
177 Message(constants.INFO, "message %s"),
178 ]
179 encoder = MessageEncoder()
180 value = encoder.encode(messages)
181 decoded_messages = json.loads(value, cls=MessageDecoder)
182 self.assertEqual(messages, decoded_messages)
183
184 def test_safedata(self):
185 """
186 A message containing SafeData is keeping its safe status when
187 retrieved from the message storage.
188 """
189 self.assertIsInstance(
190 self.encode_decode(mark_safe("<b>Hello Django!</b>")).message,
191 SafeData,
192 )
193 self.assertNotIsInstance(
194 self.encode_decode("<b>Hello Django!</b>").message,
195 SafeData,
196 )
197
198 def test_extra_tags(self):
199 """
200 A message's extra_tags attribute is correctly preserved when retrieved
201 from the message storage.
202 """
203 for extra_tags in ["", None, "some tags"]:
204 with self.subTest(extra_tags=extra_tags):
205 self.assertEqual(
206 self.encode_decode("message", extra_tags=extra_tags).extra_tags,
207 extra_tags,
208 )
209
210
211 class BisectTests(TestCase):
212 def test_bisect_keep_left(self):
213 self.assertEqual(bisect_keep_left([1, 1, 1], fn=lambda arr: sum(arr) != 2), 2)
214 self.assertEqual(bisect_keep_left([1, 1, 1], fn=lambda arr: sum(arr) != 0), 0)
215 self.assertEqual(bisect_keep_left([], fn=lambda arr: sum(arr) != 0), 0)
216
217 def test_bisect_keep_right(self):
218 self.assertEqual(bisect_keep_right([1, 1, 1], fn=lambda arr: sum(arr) != 2), 1)
219 self.assertEqual(
220 bisect_keep_right([1, 1, 1, 1], fn=lambda arr: sum(arr) != 2), 2
221 )
222 self.assertEqual(
223 bisect_keep_right([1, 1, 1, 1, 1], fn=lambda arr: sum(arr) != 1), 4
224 )
225 self.assertEqual(bisect_keep_right([], fn=lambda arr: sum(arr) != 0), 0)