Cosmetic edits for messages_tests.

This commit is contained in:
Tim Graham 2017-01-05 09:23:39 -05:00
parent 944610a86c
commit 0793182694
8 changed files with 45 additions and 86 deletions

View File

@ -11,7 +11,7 @@ from django.utils.translation import ugettext_lazy
def add_level_messages(storage):
"""
Adds 6 messages from different levels (including a custom one) to a storage
Add 6 messages from different levels (including a custom one) to a storage
instance.
"""
storage.add(constants.INFO, 'A generic info message')
@ -27,7 +27,7 @@ class override_settings_tags(override_settings):
super(override_settings_tags, self).enable()
# LEVEL_TAGS is a constant defined in the
# django.contrib.messages.storage.base module, so after changing
# settings.MESSAGE_TAGS, we need to update that constant too.
# settings.MESSAGE_TAGS, update that constant also.
self.old_level_tags = base.LEVEL_TAGS
base.LEVEL_TAGS = utils.get_level_tags()
@ -61,8 +61,7 @@ class BaseTests(object):
}],
ROOT_URLCONF='messages_tests.urls',
MESSAGE_TAGS='',
MESSAGE_STORAGE='%s.%s' % (self.storage_class.__module__,
self.storage_class.__name__),
MESSAGE_STORAGE='%s.%s' % (self.storage_class.__module__, self.storage_class.__name__),
SESSION_SERIALIZER='django.contrib.sessions.serializers.JSONSerializer',
)
self.settings_override.enable()
@ -78,7 +77,7 @@ class BaseTests(object):
def get_storage(self, data=None):
"""
Returns the storage backend, setting its loaded data to the ``data``
Return the storage backend, setting its loaded data to the ``data``
argument.
This method avoids the storage ``_get`` method from getting called so
@ -150,9 +149,8 @@ class BaseTests(object):
@override_settings(MESSAGE_LEVEL=constants.DEBUG)
def test_full_request_response_cycle(self):
"""
With the message middleware enabled, tests that messages are properly
stored and then retrieved across the full request/redirect/response
cycle.
With the message middleware enabled, messages are properly stored and
retrieved across the full request/redirect/response cycle.
"""
data = {
'messages': ['Test message %d' % x for x in range(5)],
@ -269,7 +267,7 @@ class BaseTests(object):
def stored_messages_count(self, storage, response):
"""
Returns the number of messages being stored after a
Return the number of messages being stored after a
``storage.update()`` call.
"""
raise NotImplementedError('This method must be set by a subclass.')
@ -278,9 +276,10 @@ class BaseTests(object):
raise NotImplementedError('This method must be set by a subclass.')
def get_existing_storage(self):
return self.get_storage([Message(constants.INFO, 'Test message 1'),
Message(constants.INFO, 'Test message 2',
extra_tags='tag')])
return self.get_storage([
Message(constants.INFO, 'Test message 1'),
Message(constants.INFO, 'Test message 2', extra_tags='tag'),
])
def test_existing_read(self):
"""
@ -366,8 +365,7 @@ class BaseTests(object):
constants.WARNING: '',
constants.ERROR: 'bad',
29: 'custom',
}
)
})
def test_custom_tags(self):
storage = self.get_storage()
storage.level = 0

View File

@ -14,7 +14,7 @@ class DummyStorage(object):
self.store.append(message)
class ApiTest(SimpleTestCase):
class ApiTests(SimpleTestCase):
def setUp(self):
self.rf = RequestFactory()
self.request = self.rf.request()
@ -22,33 +22,23 @@ class ApiTest(SimpleTestCase):
def test_ok(self):
msg = 'some message'
self.request._messages = self.storage
messages.add_message(self.request, messages.DEBUG, msg)
self.assertIn(msg, self.storage.store)
def test_request_is_none(self):
msg = 'some message'
msg = "add_message() argument must be an HttpRequest object, not 'NoneType'."
self.request._messages = self.storage
with self.assertRaises(TypeError):
messages.add_message(None, messages.DEBUG, msg)
self.assertEqual([], self.storage.store)
with self.assertRaisesMessage(TypeError, msg):
messages.add_message(None, messages.DEBUG, 'some message')
self.assertEqual(self.storage.store, [])
def test_middleware_missing(self):
msg = 'some message'
with self.assertRaises(messages.MessageFailure):
messages.add_message(self.request, messages.DEBUG, msg)
self.assertEqual([], self.storage.store)
msg = 'You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware'
with self.assertRaisesMessage(messages.MessageFailure, msg):
messages.add_message(self.request, messages.DEBUG, 'some message')
self.assertEqual(self.storage.store, [])
def test_middleware_missing_silently(self):
msg = 'some message'
messages.add_message(self.request, messages.DEBUG, msg,
fail_silently=True)
self.assertEqual([], self.storage.store)
messages.add_message(self.request, messages.DEBUG, 'some message', fail_silently=True)
self.assertEqual(self.storage.store, [])

View File

@ -13,7 +13,7 @@ from .base import BaseTests
def set_cookie_data(storage, messages, invalid=False, encode_empty=False):
"""
Sets ``request.COOKIES`` with the encoded data and removes the storage
Set ``request.COOKIES`` with the encoded data and remove the storage
backend's loaded data cache.
"""
encoded_data = storage._encode(messages, encode_empty=encode_empty)
@ -27,7 +27,7 @@ def set_cookie_data(storage, messages, invalid=False, encode_empty=False):
def stored_cookie_messages_count(storage, response):
"""
Returns an integer containing the number of messages stored.
Return an integer containing the number of messages stored.
"""
# Get a list of cookies, excluding ones with a max-age of 0 (because
# they have been marked for deletion).
@ -43,7 +43,7 @@ def stored_cookie_messages_count(storage, response):
@override_settings(SESSION_COOKIE_DOMAIN='.example.com', SESSION_COOKIE_SECURE=True, SESSION_COOKIE_HTTPONLY=True)
class CookieTest(BaseTests, SimpleTestCase):
class CookieTests(BaseTests, SimpleTestCase):
storage_class = CookieStorage
def stored_messages_count(self, storage, response):
@ -54,7 +54,7 @@ class CookieTest(BaseTests, SimpleTestCase):
# Set initial data.
example_messages = ['test', 'me']
set_cookie_data(storage, example_messages)
# The message actually contains what we expect.
# The message contains what's expected.
self.assertEqual(list(storage), example_messages)
def test_cookie_setings(self):
@ -149,18 +149,14 @@ class CookieTest(BaseTests, SimpleTestCase):
return decoded.message
storage = self.get_storage()
self.assertIsInstance(
encode_decode(mark_safe("<b>Hello Django!</b>")), SafeData)
self.assertNotIsInstance(
encode_decode("<b>Hello Django!</b>"), SafeData)
self.assertIsInstance(encode_decode(mark_safe("<b>Hello Django!</b>")), SafeData)
self.assertNotIsInstance(encode_decode("<b>Hello Django!</b>"), SafeData)
def test_pre_1_5_message_format(self):
"""
For ticket #22426. Tests whether messages that were set in the cookie
before the addition of is_safedata are decoded correctly.
Messages that were set in the cookie before the addition of is_safedata
are decoded correctly (#22426).
"""
# Encode the messages using the current encoder.
messages = [Message(constants.INFO, 'message %s') for x in range(5)]
encoder = MessageEncoder(separators=(',', ':'))

View File

@ -9,12 +9,12 @@ from .test_cookie import set_cookie_data, stored_cookie_messages_count
from .test_session import set_session_data, stored_session_messages_count
class FallbackTest(BaseTests, SimpleTestCase):
class FallbackTests(BaseTests, SimpleTestCase):
storage_class = FallbackStorage
def get_request(self):
self.session = {}
request = super(FallbackTest, self).get_request()
request = super(FallbackTests, self).get_request()
request.session = self.session
return request
@ -43,25 +43,20 @@ class FallbackTest(BaseTests, SimpleTestCase):
request = self.get_request()
storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage)
# Set initial cookie data.
example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, example_messages)
# Overwrite the _get method of the fallback storage to prove it is not
# used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._get = None
self.assertEqual(list(storage), example_messages)
def test_get_empty(self):
request = self.get_request()
storage = self.storage_class(request)
# Overwrite the _get method of the fallback storage to prove it is not
# used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._get = None
self.assertEqual(list(storage), [])
def test_get_fallback(self):
@ -74,7 +69,6 @@ class FallbackTest(BaseTests, SimpleTestCase):
example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, example_messages[:4] + [CookieStorage.not_finished])
set_session_data(session_storage, example_messages[4:])
self.assertEqual(list(storage), example_messages)
def test_get_fallback_only(self):
@ -82,12 +76,10 @@ class FallbackTest(BaseTests, SimpleTestCase):
storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage)
session_storage = self.get_session_storage(storage)
# Set initial cookie and session data.
example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, [CookieStorage.not_finished], encode_empty=True)
set_session_data(session_storage, example_messages)
self.assertEqual(list(storage), example_messages)
def test_flush_used_backends(self):
@ -95,11 +87,9 @@ class FallbackTest(BaseTests, SimpleTestCase):
storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage)
session_storage = self.get_session_storage(storage)
# Set initial cookie and session data.
set_cookie_data(cookie_storage, ['cookie', CookieStorage.not_finished])
set_session_data(session_storage, ['session'])
# When updating, previously used but no longer needed backends are
# flushed.
response = self.get_response()
@ -118,15 +108,12 @@ class FallbackTest(BaseTests, SimpleTestCase):
"""
storage = self.get_storage()
response = self.get_response()
# Overwrite the _store method of the fallback storage to prove it isn't
# used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._store = None
for i in range(5):
storage.add(constants.INFO, str(i) * 100)
storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 5)
session_storing = self.stored_session_messages_count(storage, response)
@ -139,13 +126,11 @@ class FallbackTest(BaseTests, SimpleTestCase):
"""
storage = self.get_storage()
response = self.get_response()
# see comment in CookieText.test_cookie_max_length
# see comment in CookieTests.test_cookie_max_length()
msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37)
for i in range(5):
storage.add(constants.INFO, str(i) * msg_size)
storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 4)
session_storing = self.stored_session_messages_count(storage, response)
@ -158,10 +143,8 @@ class FallbackTest(BaseTests, SimpleTestCase):
"""
storage = self.get_storage()
response = self.get_response()
storage.add(constants.INFO, 'x' * 5000)
storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 0)
session_storing = self.stored_session_messages_count(storage, response)

View File

@ -4,15 +4,14 @@ from django import http
from django.contrib.messages.middleware import MessageMiddleware
class MiddlewareTest(unittest.TestCase):
class MiddlewareTests(unittest.TestCase):
def setUp(self):
self.middleware = MessageMiddleware()
def test_response_without_messages(self):
"""
Makes sure that the response middleware is tolerant of messages not
existing on request.
MessageMiddleware is tolerant of messages not existing on request.
"""
request = http.HttpRequest()
response = http.HttpResponse()

View File

@ -8,9 +8,7 @@ from .urls import ContactFormViewWithMsg
class SuccessMessageMixinTests(SimpleTestCase):
def test_set_messages_success(self):
author = {'name': 'John Doe',
'slug': 'success-msg'}
author = {'name': 'John Doe', 'slug': 'success-msg'}
add_url = reverse('add_success_msg')
req = self.client.post(add_url, author)
self.assertIn(ContactFormViewWithMsg.success_message % author,
req.cookies['messages'].value)
self.assertIn(ContactFormViewWithMsg.success_message % author, req.cookies['messages'].value)

View File

@ -22,12 +22,12 @@ def stored_session_messages_count(storage):
return len(data)
class SessionTest(BaseTests, TestCase):
class SessionTests(BaseTests, TestCase):
storage_class = SessionStorage
def get_request(self):
self.session = {}
request = super(SessionTest, self).get_request()
request = super(SessionTests, self).get_request()
request.session = self.session
return request

View File

@ -24,27 +24,22 @@ TEMPLATE = """{% if messages %}
@never_cache
def add(request, message_type):
# don't default to False here, because we want to test that it defaults
# to False if unspecified
# Don't default to False here to test that it defaults to False if
# unspecified.
fail_silently = request.POST.get('fail_silently', None)
for msg in request.POST.getlist('messages'):
if fail_silently is not None:
getattr(messages, message_type)(request, msg,
fail_silently=fail_silently)
getattr(messages, message_type)(request, msg, fail_silently=fail_silently)
else:
getattr(messages, message_type)(request, msg)
show_url = reverse('show_message')
return HttpResponseRedirect(show_url)
return HttpResponseRedirect(reverse('show_message'))
@never_cache
def add_template_response(request, message_type):
for msg in request.POST.getlist('messages'):
getattr(messages, message_type)(request, msg)
show_url = reverse('show_template_response')
return HttpResponseRedirect(show_url)
return HttpResponseRedirect(reverse('show_template_response'))
@never_cache