test_cookie.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. import json
  2. from django.contrib.messages import constants
  3. from django.contrib.messages.tests.base import BaseTests
  4. from django.contrib.messages.storage.cookie import (CookieStorage,
  5. MessageEncoder, MessageDecoder)
  6. from django.contrib.messages.storage.base import Message
  7. from django.test import TestCase, override_settings
  8. from django.utils.safestring import SafeData, mark_safe
  9. def set_cookie_data(storage, messages, invalid=False, encode_empty=False):
  10. """
  11. Sets ``request.COOKIES`` with the encoded data and removes the storage
  12. backend's loaded data cache.
  13. """
  14. encoded_data = storage._encode(messages, encode_empty=encode_empty)
  15. if invalid:
  16. # Truncate the first character so that the hash is invalid.
  17. encoded_data = encoded_data[1:]
  18. storage.request.COOKIES = {CookieStorage.cookie_name: encoded_data}
  19. if hasattr(storage, '_loaded_data'):
  20. del storage._loaded_data
  21. def stored_cookie_messages_count(storage, response):
  22. """
  23. Returns an integer containing the number of messages stored.
  24. """
  25. # Get a list of cookies, excluding ones with a max-age of 0 (because
  26. # they have been marked for deletion).
  27. cookie = response.cookies.get(storage.cookie_name)
  28. if not cookie or cookie['max-age'] == 0:
  29. return 0
  30. data = storage._decode(cookie.value)
  31. if not data:
  32. return 0
  33. if data[-1] == CookieStorage.not_finished:
  34. data.pop()
  35. return len(data)
  36. @override_settings(SESSION_COOKIE_DOMAIN='.example.com', SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True)
  37. class CookieTest(BaseTests, TestCase):
  38. storage_class = CookieStorage
  39. def stored_messages_count(self, storage, response):
  40. return stored_cookie_messages_count(storage, response)
  41. def test_get(self):
  42. storage = self.storage_class(self.get_request())
  43. # Set initial data.
  44. example_messages = ['test', 'me']
  45. set_cookie_data(storage, example_messages)
  46. # Test that the message actually contains what we expect.
  47. self.assertEqual(list(storage), example_messages)
  48. def test_cookie_setings(self):
  49. """
  50. Ensure that CookieStorage honors SESSION_COOKIE_DOMAIN, SESSION_COOKIE_SECURE and SESSION_COOKIE_HTTPONLY
  51. Refs #15618 and #20972.
  52. """
  53. # Test before the messages have been consumed
  54. storage = self.get_storage()
  55. response = self.get_response()
  56. storage.add(constants.INFO, 'test')
  57. storage.update(response)
  58. self.assertTrue('test' in response.cookies['messages'].value)
  59. self.assertEqual(response.cookies['messages']['domain'], '.example.com')
  60. self.assertEqual(response.cookies['messages']['expires'], '')
  61. self.assertEqual(response.cookies['messages']['secure'], True)
  62. self.assertEqual(response.cookies['messages']['httponly'], True)
  63. # Test deletion of the cookie (storing with an empty value) after the messages have been consumed
  64. storage = self.get_storage()
  65. response = self.get_response()
  66. storage.add(constants.INFO, 'test')
  67. for m in storage:
  68. pass # Iterate through the storage to simulate consumption of messages.
  69. storage.update(response)
  70. self.assertEqual(response.cookies['messages'].value, '')
  71. self.assertEqual(response.cookies['messages']['domain'], '.example.com')
  72. self.assertEqual(response.cookies['messages']['expires'], 'Thu, 01-Jan-1970 00:00:00 GMT')
  73. def test_get_bad_cookie(self):
  74. request = self.get_request()
  75. storage = self.storage_class(request)
  76. # Set initial (invalid) data.
  77. example_messages = ['test', 'me']
  78. set_cookie_data(storage, example_messages, invalid=True)
  79. # Test that the message actually contains what we expect.
  80. self.assertEqual(list(storage), [])
  81. def test_max_cookie_length(self):
  82. """
  83. Tests that, if the data exceeds what is allowed in a cookie, older
  84. messages are removed before saving (and returned by the ``update``
  85. method).
  86. """
  87. storage = self.get_storage()
  88. response = self.get_response()
  89. # When storing as a cookie, the cookie has constant overhead of approx
  90. # 54 chars, and each message has a constant overhead of about 37 chars
  91. # and a variable overhead of zero in the best case. We aim for a message
  92. # size which will fit 4 messages into the cookie, but not 5.
  93. # See also FallbackTest.test_session_fallback
  94. msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37)
  95. for i in range(5):
  96. storage.add(constants.INFO, str(i) * msg_size)
  97. unstored_messages = storage.update(response)
  98. cookie_storing = self.stored_messages_count(storage, response)
  99. self.assertEqual(cookie_storing, 4)
  100. self.assertEqual(len(unstored_messages), 1)
  101. self.assertTrue(unstored_messages[0].message == '0' * msg_size)
  102. def test_json_encoder_decoder(self):
  103. """
  104. Tests that a complex nested data structure containing Message
  105. instances is properly encoded/decoded by the custom JSON
  106. encoder/decoder classes.
  107. """
  108. messages = [
  109. {
  110. 'message': Message(constants.INFO, 'Test message'),
  111. 'message_list': [Message(constants.INFO, 'message %s')
  112. for x in range(5)] + [{'another-message':
  113. Message(constants.ERROR, 'error')}],
  114. },
  115. Message(constants.INFO, 'message %s'),
  116. ]
  117. encoder = MessageEncoder(separators=(',', ':'))
  118. value = encoder.encode(messages)
  119. decoded_messages = json.loads(value, cls=MessageDecoder)
  120. self.assertEqual(messages, decoded_messages)
  121. def test_safedata(self):
  122. """
  123. Tests that a message containing SafeData is keeping its safe status when
  124. retrieved from the message storage.
  125. """
  126. def encode_decode(data):
  127. message = Message(constants.DEBUG, data)
  128. encoded = storage._encode(message)
  129. decoded = storage._decode(encoded)
  130. return decoded.message
  131. storage = self.get_storage()
  132. self.assertIsInstance(
  133. encode_decode(mark_safe("<b>Hello Django!</b>")), SafeData)
  134. self.assertNotIsInstance(
  135. encode_decode("<b>Hello Django!</b>"), SafeData)
  136. def test_pre_1_5_message_format(self):
  137. """
  138. For ticket #22426. Tests whether messages that were set in the cookie
  139. before the addition of is_safedata are decoded correctly.
  140. """
  141. # Encode the messages using the current encoder.
  142. messages = [Message(constants.INFO, 'message %s') for x in range(5)]
  143. encoder = MessageEncoder(separators=(',', ':'))
  144. encoded_messages = encoder.encode(messages)
  145. # Remove the is_safedata flag from the messages in order to imitate
  146. # the behavior of before 1.5 (monkey patching).
  147. encoded_messages = json.loads(encoded_messages)
  148. for obj in encoded_messages:
  149. obj.pop(1)
  150. encoded_messages = json.dumps(encoded_messages, separators=(',', ':'))
  151. # Decode the messages in the old format (without is_safedata)
  152. decoded_messages = json.loads(encoded_messages, cls=MessageDecoder)
  153. self.assertEqual(messages, decoded_messages)