2012-12-21 09:01:03 +00:00
|
|
|
from django.contrib.messages import constants
|
|
|
|
from django.contrib.messages.storage.base import Message
|
2009-12-09 16:57:23 +00:00
|
|
|
from django.contrib.messages.storage.session import SessionStorage
|
2019-10-23 06:04:14 +00:00
|
|
|
from django.http import HttpRequest
|
2013-04-03 03:42:00 +00:00
|
|
|
from django.test import TestCase
|
2015-01-28 12:35:27 +00:00
|
|
|
from django.utils.safestring import SafeData, mark_safe
|
2009-12-09 16:57:23 +00:00
|
|
|
|
2015-02-10 13:30:35 +00:00
|
|
|
from .base import BaseTests
|
|
|
|
|
2009-12-09 16:57:23 +00:00
|
|
|
|
|
|
|
def set_session_data(storage, messages):
|
|
|
|
"""
|
|
|
|
Sets the messages into the backend request's session and remove the
|
|
|
|
backend's loaded data cache.
|
|
|
|
"""
|
2013-08-22 00:12:19 +00:00
|
|
|
storage.request.session[storage.session_key] = storage.serialize_messages(messages)
|
2009-12-09 16:57:23 +00:00
|
|
|
if hasattr(storage, '_loaded_data'):
|
|
|
|
del storage._loaded_data
|
|
|
|
|
|
|
|
|
|
|
|
def stored_session_messages_count(storage):
|
2013-08-22 00:12:19 +00:00
|
|
|
data = storage.deserialize_messages(storage.request.session.get(storage.session_key, []))
|
2009-12-09 16:57:23 +00:00
|
|
|
return len(data)
|
|
|
|
|
|
|
|
|
2017-01-05 14:23:39 +00:00
|
|
|
class SessionTests(BaseTests, TestCase):
|
2009-12-09 16:57:23 +00:00
|
|
|
storage_class = SessionStorage
|
|
|
|
|
|
|
|
def get_request(self):
|
|
|
|
self.session = {}
|
2017-01-21 13:13:44 +00:00
|
|
|
request = super().get_request()
|
2009-12-09 16:57:23 +00:00
|
|
|
request.session = self.session
|
|
|
|
return request
|
|
|
|
|
|
|
|
def stored_messages_count(self, storage, response):
|
|
|
|
return stored_session_messages_count(storage)
|
|
|
|
|
2019-10-23 06:04:14 +00:00
|
|
|
def test_no_session(self):
|
|
|
|
msg = (
|
|
|
|
'The session-based temporary message storage requires session '
|
|
|
|
'middleware to be installed, and come before the message '
|
|
|
|
'middleware in the MIDDLEWARE list.'
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(AssertionError, msg):
|
|
|
|
self.storage_class(HttpRequest())
|
|
|
|
|
2009-12-09 16:57:23 +00:00
|
|
|
def test_get(self):
|
|
|
|
storage = self.storage_class(self.get_request())
|
|
|
|
example_messages = ['test', 'me']
|
|
|
|
set_session_data(storage, example_messages)
|
|
|
|
self.assertEqual(list(storage), example_messages)
|
2012-12-21 09:01:03 +00:00
|
|
|
|
|
|
|
def test_safedata(self):
|
|
|
|
"""
|
2016-10-27 07:53:39 +00:00
|
|
|
A message containing SafeData keeps its safe status when retrieved from
|
|
|
|
the message storage.
|
2012-12-21 09:01:03 +00:00
|
|
|
"""
|
|
|
|
storage = self.get_storage()
|
|
|
|
message = Message(constants.DEBUG, mark_safe("<b>Hello Django!</b>"))
|
|
|
|
set_session_data(storage, [message])
|
|
|
|
self.assertIsInstance(list(storage)[0].message, SafeData)
|