2013-11-23 22:35:24 +08:00
|
|
|
from django.contrib import messages
|
2015-04-18 05:38:20 +08:00
|
|
|
from django.test import RequestFactory, SimpleTestCase
|
2013-11-23 22:35:24 +08:00
|
|
|
|
2023-06-15 23:16:46 +08:00
|
|
|
from .utils import DummyStorage
|
2013-11-23 22:35:24 +08:00
|
|
|
|
|
|
|
|
2017-01-05 22:23:39 +08:00
|
|
|
class ApiTests(SimpleTestCase):
|
2018-11-27 03:01:27 +08:00
|
|
|
rf = RequestFactory()
|
|
|
|
|
2013-11-23 22:35:24 +08:00
|
|
|
def setUp(self):
|
|
|
|
self.request = self.rf.request()
|
|
|
|
self.storage = DummyStorage()
|
|
|
|
|
|
|
|
def test_ok(self):
|
|
|
|
msg = "some message"
|
|
|
|
self.request._messages = self.storage
|
|
|
|
messages.add_message(self.request, messages.DEBUG, msg)
|
2023-06-15 23:16:46 +08:00
|
|
|
[message] = self.storage.store
|
|
|
|
self.assertEqual(msg, message.message)
|
2013-11-23 22:35:24 +08:00
|
|
|
|
|
|
|
def test_request_is_none(self):
|
2017-01-05 22:23:39 +08:00
|
|
|
msg = "add_message() argument must be an HttpRequest object, not 'NoneType'."
|
2013-11-23 22:35:24 +08:00
|
|
|
self.request._messages = self.storage
|
2017-01-05 22:23:39 +08:00
|
|
|
with self.assertRaisesMessage(TypeError, msg):
|
|
|
|
messages.add_message(None, messages.DEBUG, "some message")
|
|
|
|
self.assertEqual(self.storage.store, [])
|
2013-11-23 22:35:24 +08:00
|
|
|
|
|
|
|
def test_middleware_missing(self):
|
2017-01-05 22:23:39 +08:00
|
|
|
msg = (
|
|
|
|
"You cannot add messages without installing "
|
|
|
|
"django.contrib.messages.middleware.MessageMiddleware"
|
2022-02-04 15:08:27 +08:00
|
|
|
)
|
2017-01-05 22:23:39 +08:00
|
|
|
with self.assertRaisesMessage(messages.MessageFailure, msg):
|
|
|
|
messages.add_message(self.request, messages.DEBUG, "some message")
|
|
|
|
self.assertEqual(self.storage.store, [])
|
2013-11-23 22:35:24 +08:00
|
|
|
|
|
|
|
def test_middleware_missing_silently(self):
|
2017-01-05 22:23:39 +08:00
|
|
|
messages.add_message(
|
|
|
|
self.request, messages.DEBUG, "some message", fail_silently=True
|
|
|
|
)
|
|
|
|
self.assertEqual(self.storage.store, [])
|
2017-01-10 07:03:10 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class CustomRequest:
|
2017-01-10 07:03:10 +08:00
|
|
|
def __init__(self, request):
|
|
|
|
self._request = request
|
|
|
|
|
|
|
|
def __getattribute__(self, attr):
|
|
|
|
try:
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().__getattribute__(attr)
|
2017-01-10 07:03:10 +08:00
|
|
|
except AttributeError:
|
|
|
|
return getattr(self._request, attr)
|
|
|
|
|
|
|
|
|
|
|
|
class CustomRequestApiTests(ApiTests):
|
|
|
|
"""
|
|
|
|
add_message() should use ducktyping to allow request wrappers such as the
|
|
|
|
one in Django REST framework.
|
|
|
|
"""
|
2022-02-04 03:24:19 +08:00
|
|
|
|
2017-01-10 07:03:10 +08:00
|
|
|
def setUp(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUp()
|
2017-01-10 07:03:10 +08:00
|
|
|
self.request = CustomRequest(self.request)
|