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

View File

@ -14,7 +14,7 @@ class DummyStorage(object):
self.store.append(message) self.store.append(message)
class ApiTest(SimpleTestCase): class ApiTests(SimpleTestCase):
def setUp(self): def setUp(self):
self.rf = RequestFactory() self.rf = RequestFactory()
self.request = self.rf.request() self.request = self.rf.request()
@ -22,33 +22,23 @@ class ApiTest(SimpleTestCase):
def test_ok(self): def test_ok(self):
msg = 'some message' msg = 'some message'
self.request._messages = self.storage self.request._messages = self.storage
messages.add_message(self.request, messages.DEBUG, msg) messages.add_message(self.request, messages.DEBUG, msg)
self.assertIn(msg, self.storage.store) self.assertIn(msg, self.storage.store)
def test_request_is_none(self): 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 self.request._messages = self.storage
with self.assertRaisesMessage(TypeError, msg):
with self.assertRaises(TypeError): messages.add_message(None, messages.DEBUG, 'some message')
messages.add_message(None, messages.DEBUG, msg) self.assertEqual(self.storage.store, [])
self.assertEqual([], self.storage.store)
def test_middleware_missing(self): def test_middleware_missing(self):
msg = 'some message' msg = 'You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware'
with self.assertRaisesMessage(messages.MessageFailure, msg):
with self.assertRaises(messages.MessageFailure): messages.add_message(self.request, messages.DEBUG, 'some message')
messages.add_message(self.request, messages.DEBUG, msg) self.assertEqual(self.storage.store, [])
self.assertEqual([], self.storage.store)
def test_middleware_missing_silently(self): def test_middleware_missing_silently(self):
msg = 'some message' messages.add_message(self.request, messages.DEBUG, 'some message', fail_silently=True)
self.assertEqual(self.storage.store, [])
messages.add_message(self.request, messages.DEBUG, msg,
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): 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. backend's loaded data cache.
""" """
encoded_data = storage._encode(messages, encode_empty=encode_empty) 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): 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 # Get a list of cookies, excluding ones with a max-age of 0 (because
# they have been marked for deletion). # 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) @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 storage_class = CookieStorage
def stored_messages_count(self, storage, response): def stored_messages_count(self, storage, response):
@ -54,7 +54,7 @@ class CookieTest(BaseTests, SimpleTestCase):
# Set initial data. # Set initial data.
example_messages = ['test', 'me'] example_messages = ['test', 'me']
set_cookie_data(storage, example_messages) 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) self.assertEqual(list(storage), example_messages)
def test_cookie_setings(self): def test_cookie_setings(self):
@ -149,18 +149,14 @@ class CookieTest(BaseTests, SimpleTestCase):
return decoded.message return decoded.message
storage = self.get_storage() storage = self.get_storage()
self.assertIsInstance(encode_decode(mark_safe("<b>Hello Django!</b>")), SafeData)
self.assertIsInstance( self.assertNotIsInstance(encode_decode("<b>Hello Django!</b>"), SafeData)
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): def test_pre_1_5_message_format(self):
""" """
For ticket #22426. Tests whether messages that were set in the cookie Messages that were set in the cookie before the addition of is_safedata
before the addition of is_safedata are decoded correctly. are decoded correctly (#22426).
""" """
# Encode the messages using the current encoder. # Encode the messages using the current encoder.
messages = [Message(constants.INFO, 'message %s') for x in range(5)] messages = [Message(constants.INFO, 'message %s') for x in range(5)]
encoder = MessageEncoder(separators=(',', ':')) 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 from .test_session import set_session_data, stored_session_messages_count
class FallbackTest(BaseTests, SimpleTestCase): class FallbackTests(BaseTests, SimpleTestCase):
storage_class = FallbackStorage storage_class = FallbackStorage
def get_request(self): def get_request(self):
self.session = {} self.session = {}
request = super(FallbackTest, self).get_request() request = super(FallbackTests, self).get_request()
request.session = self.session request.session = self.session
return request return request
@ -43,25 +43,20 @@ class FallbackTest(BaseTests, SimpleTestCase):
request = self.get_request() request = self.get_request()
storage = self.storage_class(request) storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage) cookie_storage = self.get_cookie_storage(storage)
# Set initial cookie data. # Set initial cookie data.
example_messages = [str(i) for i in range(5)] example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, example_messages) set_cookie_data(cookie_storage, example_messages)
# Overwrite the _get method of the fallback storage to prove it is not # Overwrite the _get method of the fallback storage to prove it is not
# used (it would cause a TypeError: 'NoneType' object is not callable). # used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._get = None self.get_session_storage(storage)._get = None
self.assertEqual(list(storage), example_messages) self.assertEqual(list(storage), example_messages)
def test_get_empty(self): def test_get_empty(self):
request = self.get_request() request = self.get_request()
storage = self.storage_class(request) storage = self.storage_class(request)
# Overwrite the _get method of the fallback storage to prove it is not # Overwrite the _get method of the fallback storage to prove it is not
# used (it would cause a TypeError: 'NoneType' object is not callable). # used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._get = None self.get_session_storage(storage)._get = None
self.assertEqual(list(storage), []) self.assertEqual(list(storage), [])
def test_get_fallback(self): def test_get_fallback(self):
@ -74,7 +69,6 @@ class FallbackTest(BaseTests, SimpleTestCase):
example_messages = [str(i) for i in range(5)] example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, example_messages[:4] + [CookieStorage.not_finished]) set_cookie_data(cookie_storage, example_messages[:4] + [CookieStorage.not_finished])
set_session_data(session_storage, example_messages[4:]) set_session_data(session_storage, example_messages[4:])
self.assertEqual(list(storage), example_messages) self.assertEqual(list(storage), example_messages)
def test_get_fallback_only(self): def test_get_fallback_only(self):
@ -82,12 +76,10 @@ class FallbackTest(BaseTests, SimpleTestCase):
storage = self.storage_class(request) storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage) cookie_storage = self.get_cookie_storage(storage)
session_storage = self.get_session_storage(storage) session_storage = self.get_session_storage(storage)
# Set initial cookie and session data. # Set initial cookie and session data.
example_messages = [str(i) for i in range(5)] example_messages = [str(i) for i in range(5)]
set_cookie_data(cookie_storage, [CookieStorage.not_finished], encode_empty=True) set_cookie_data(cookie_storage, [CookieStorage.not_finished], encode_empty=True)
set_session_data(session_storage, example_messages) set_session_data(session_storage, example_messages)
self.assertEqual(list(storage), example_messages) self.assertEqual(list(storage), example_messages)
def test_flush_used_backends(self): def test_flush_used_backends(self):
@ -95,11 +87,9 @@ class FallbackTest(BaseTests, SimpleTestCase):
storage = self.storage_class(request) storage = self.storage_class(request)
cookie_storage = self.get_cookie_storage(storage) cookie_storage = self.get_cookie_storage(storage)
session_storage = self.get_session_storage(storage) session_storage = self.get_session_storage(storage)
# Set initial cookie and session data. # Set initial cookie and session data.
set_cookie_data(cookie_storage, ['cookie', CookieStorage.not_finished]) set_cookie_data(cookie_storage, ['cookie', CookieStorage.not_finished])
set_session_data(session_storage, ['session']) set_session_data(session_storage, ['session'])
# When updating, previously used but no longer needed backends are # When updating, previously used but no longer needed backends are
# flushed. # flushed.
response = self.get_response() response = self.get_response()
@ -118,15 +108,12 @@ class FallbackTest(BaseTests, SimpleTestCase):
""" """
storage = self.get_storage() storage = self.get_storage()
response = self.get_response() response = self.get_response()
# Overwrite the _store method of the fallback storage to prove it isn't # Overwrite the _store method of the fallback storage to prove it isn't
# used (it would cause a TypeError: 'NoneType' object is not callable). # used (it would cause a TypeError: 'NoneType' object is not callable).
self.get_session_storage(storage)._store = None self.get_session_storage(storage)._store = None
for i in range(5): for i in range(5):
storage.add(constants.INFO, str(i) * 100) storage.add(constants.INFO, str(i) * 100)
storage.update(response) storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response) cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 5) self.assertEqual(cookie_storing, 5)
session_storing = self.stored_session_messages_count(storage, response) session_storing = self.stored_session_messages_count(storage, response)
@ -139,13 +126,11 @@ class FallbackTest(BaseTests, SimpleTestCase):
""" """
storage = self.get_storage() storage = self.get_storage()
response = self.get_response() response = self.get_response()
# see comment in CookieTests.test_cookie_max_length()
# see comment in CookieText.test_cookie_max_length
msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37) msg_size = int((CookieStorage.max_cookie_size - 54) / 4.5 - 37)
for i in range(5): for i in range(5):
storage.add(constants.INFO, str(i) * msg_size) storage.add(constants.INFO, str(i) * msg_size)
storage.update(response) storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response) cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 4) self.assertEqual(cookie_storing, 4)
session_storing = self.stored_session_messages_count(storage, response) session_storing = self.stored_session_messages_count(storage, response)
@ -158,10 +143,8 @@ class FallbackTest(BaseTests, SimpleTestCase):
""" """
storage = self.get_storage() storage = self.get_storage()
response = self.get_response() response = self.get_response()
storage.add(constants.INFO, 'x' * 5000) storage.add(constants.INFO, 'x' * 5000)
storage.update(response) storage.update(response)
cookie_storing = self.stored_cookie_messages_count(storage, response) cookie_storing = self.stored_cookie_messages_count(storage, response)
self.assertEqual(cookie_storing, 0) self.assertEqual(cookie_storing, 0)
session_storing = self.stored_session_messages_count(storage, response) 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 from django.contrib.messages.middleware import MessageMiddleware
class MiddlewareTest(unittest.TestCase): class MiddlewareTests(unittest.TestCase):
def setUp(self): def setUp(self):
self.middleware = MessageMiddleware() self.middleware = MessageMiddleware()
def test_response_without_messages(self): def test_response_without_messages(self):
""" """
Makes sure that the response middleware is tolerant of messages not MessageMiddleware is tolerant of messages not existing on request.
existing on request.
""" """
request = http.HttpRequest() request = http.HttpRequest()
response = http.HttpResponse() response = http.HttpResponse()

View File

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

View File

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

View File

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