Fixed #14503 -- Unified multiple implementations of test cases assert* methods that verify a given exception is raised by a callable throughout the Django test suite.

Replaced them with a new assertRaisesMessage method of a new SimpleTestCase, a lightweight subclass of unittest.TestCase. Both are also available for usage in user tests.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16610 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Ramiro Morales 2011-08-13 00:42:08 +00:00
parent a539d434d9
commit 326949e444
13 changed files with 299 additions and 292 deletions

View File

@ -3,5 +3,6 @@ Django Unit Test and Doctest framework.
""" """
from django.test.client import Client, RequestFactory from django.test.client import Client, RequestFactory
from django.test.testcases import TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.testcases import (TestCase, TransactionTestCase,
SimpleTestCase, skipIfDBFeature, skipUnlessDBFeature)
from django.test.utils import Approximate from django.test.utils import Approximate

View File

@ -21,7 +21,7 @@ from django.utils import simplejson, unittest as ut2
from django.utils.encoding import smart_str from django.utils.encoding import smart_str
__all__ = ('DocTestRunner', 'OutputChecker', 'TestCase', 'TransactionTestCase', __all__ = ('DocTestRunner', 'OutputChecker', 'TestCase', 'TransactionTestCase',
'skipIfDBFeature', 'skipUnlessDBFeature') 'SimpleTestCase', 'skipIfDBFeature', 'skipUnlessDBFeature')
normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s) normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
normalize_decimals = lambda s: re.sub(r"Decimal\('(\d+(\.\d*)?)'\)", lambda m: "Decimal(\"%s\")" % m.groups()[0], s) normalize_decimals = lambda s: re.sub(r"Decimal\('(\d+(\.\d*)?)'\)", lambda m: "Decimal(\"%s\")" % m.groups()[0], s)
@ -235,8 +235,43 @@ class _AssertNumQueriesContext(object):
) )
) )
class SimpleTestCase(ut2.TestCase):
class TransactionTestCase(ut2.TestCase): def save_warnings_state(self):
"""
Saves the state of the warnings module
"""
self._warnings_state = get_warnings_state()
def restore_warnings_state(self):
"""
Restores the sate of the warnings module to the state
saved by save_warnings_state()
"""
restore_warnings_state(self._warnings_state)
def settings(self, **kwargs):
"""
A context manager that temporarily sets a setting and reverts
back to the original value when exiting the context.
"""
return override_settings(**kwargs)
def assertRaisesMessage(self, expected_exception, expected_message,
callable_obj=None, *args, **kwargs):
"""Asserts that the message in a raised exception matches the passe value.
Args:
expected_exception: Exception class expected to be raised.
expected_message: expected error message string value.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.
"""
return self.assertRaisesRegexp(expected_exception,
re.escape(expected_message), callable_obj, *args, **kwargs)
class TransactionTestCase(SimpleTestCase):
# The class we'll use for the test client self.client. # The class we'll use for the test client self.client.
# Can be overridden in derived classes. # Can be overridden in derived classes.
client_class = Client client_class = Client
@ -332,26 +367,6 @@ class TransactionTestCase(ut2.TestCase):
settings.ROOT_URLCONF = self._old_root_urlconf settings.ROOT_URLCONF = self._old_root_urlconf
clear_url_caches() clear_url_caches()
def save_warnings_state(self):
"""
Saves the state of the warnings module
"""
self._warnings_state = get_warnings_state()
def restore_warnings_state(self):
"""
Restores the sate of the warnings module to the state
saved by save_warnings_state()
"""
restore_warnings_state(self._warnings_state)
def settings(self, **kwargs):
"""
A context manager that temporarily sets a setting and reverts
back to the original value when exiting the context.
"""
return override_settings(**kwargs)
def assertRedirects(self, response, expected_url, status_code=302, def assertRedirects(self, response, expected_url, status_code=302,
target_status_code=200, host=None, msg_prefix=''): target_status_code=200, host=None, msg_prefix=''):
"""Asserts that a response redirected to a specific URL, and that the """Asserts that a response redirected to a specific URL, and that the

View File

@ -480,7 +480,7 @@ setting_changed
.. data:: django.test.signals.setting_changed .. data:: django.test.signals.setting_changed
:module: :module:
Sent when some :ref:`settings are overridden <overriding-setting>` with the Sent when some :ref:`settings are overridden <overriding-settings>` with the
:meth:`django.test.TestCase.setting` context manager or the :meth:`django.test.TestCase.setting` context manager or the
:func:`django.test.utils.override_settings` decorator/context manager. :func:`django.test.utils.override_settings` decorator/context manager.

View File

@ -1101,7 +1101,7 @@ TestCase
.. currentmodule:: django.test .. currentmodule:: django.test
Normal Python unit test classes extend a base class of ``unittest.TestCase``. Normal Python unit test classes extend a base class of ``unittest.TestCase``.
Django provides an extension of this base class: Django provides a few extensions of this base class:
.. class:: TestCase() .. class:: TestCase()
@ -1123,6 +1123,8 @@ additions, including:
* Django-specific assertions for testing for things * Django-specific assertions for testing for things
like redirection and form errors. like redirection and form errors.
``TestCase`` inherits from :class:`~django.test.TransactionTestCase`.
.. class:: TransactionTestCase() .. class:: TransactionTestCase()
Django ``TestCase`` classes make use of database transaction facilities, if Django ``TestCase`` classes make use of database transaction facilities, if
@ -1153,6 +1155,7 @@ When running on a database that does not support rollback (e.g. MySQL with the
MyISAM storage engine), ``TestCase`` falls back to initializing the database MyISAM storage engine), ``TestCase`` falls back to initializing the database
by truncating tables and reloading initial data. by truncating tables and reloading initial data.
``TransactionTestCase`` inherits from :class:`~django.test.SimpleTestCase`.
.. note:: .. note::
The ``TestCase`` use of rollback to un-do the effects of the test code The ``TestCase`` use of rollback to un-do the effects of the test code
@ -1166,6 +1169,31 @@ by truncating tables and reloading initial data.
A better long-term fix, that allows the test to take advantage of the A better long-term fix, that allows the test to take advantage of the
speed benefit of ``TestCase``, is to fix the underlying test problem. speed benefit of ``TestCase``, is to fix the underlying test problem.
.. class:: SimpleTestCase()
.. versionadded:: 1.4
A very thin subclass of :class:`unittest.TestCase`, it extends it with some
basic functionality like:
* Saving and restoring the Python warning machinery state.
* Checking that a callable :meth:`raises a certain exeception <TestCase.assertRaisesMessage>`.
If you need any of the other more complex and heavyweight Django-specific
features like:
* The ability to run tests with :ref:`modified settings <overriding-settings>`
* Using the :attr:`~TestCase.client` :class:`~django.test.client.Client`.
* Testing or using the ORM.
* Database :attr:`~TestCase.fixtures`.
* Custom test-time :attr:`URL maps <TestCase.urls>`.
* Test :ref:`skipping based on database backend features <skipping-tests>`.
* Our specialized :ref:`assert* <assertions>` metods.
then you should use :class:`~django.test.TransactionTestCase` or
:class:`~django.test.TestCase` instead.
``SimpleTestCase`` inherits from :class:`django.utils.unittest.TestCase`.
Default test client Default test client
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
@ -1370,7 +1398,7 @@ For example::
This test case will flush *all* the test databases before running This test case will flush *all* the test databases before running
``testIndexPageView``. ``testIndexPageView``.
.. _overriding-setting: .. _overriding-settings:
Overriding settings Overriding settings
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
@ -1402,7 +1430,9 @@ this use case Django provides a standard `Python context manager`_
This example will override the :setting:`LOGIN_URL` setting for the code This example will override the :setting:`LOGIN_URL` setting for the code
in the ``with`` block and reset its value to the previous state afterwards. in the ``with`` block and reset its value to the previous state afterwards.
.. function:: utils.override_settings .. currentmodule:: django.test.utils
.. function:: override_settings
In case you want to override a setting for just one test method or even the In case you want to override a setting for just one test method or even the
whole TestCase class, Django provides the whole TestCase class, Django provides the
@ -1463,9 +1493,13 @@ contents of the test email outbox at the start of each test case.
For more detail on email services during tests, see `Email services`_. For more detail on email services during tests, see `Email services`_.
.. _assertions:
Assertions Assertions
~~~~~~~~~~ ~~~~~~~~~~
.. currentmodule:: django.test
.. versionchanged:: 1.2 .. versionchanged:: 1.2
Addded ``msg_prefix`` argument. Addded ``msg_prefix`` argument.
@ -1474,11 +1508,19 @@ such as ``assertTrue`` and ``assertEqual``, Django's custom ``TestCase`` class
provides a number of custom assertion methods that are useful for testing Web provides a number of custom assertion methods that are useful for testing Web
applications: applications:
The failure messages given by the assertion methods can be customized The failure messages given by most of these assertion methods can be customized
with the ``msg_prefix`` argument. This string will be prefixed to any with the ``msg_prefix`` argument. This string will be prefixed to any failure
failure message generated by the assertion. This allows you to provide message generated by the assertion. This allows you to provide additional
additional details that may help you to identify the location and details that may help you to identify the location and cause of an failure in
cause of an failure in your test suite. your test suite.
.. method:: TestCase.assertRaisesMessage(expected_exception, expected_message, callable_obj=None, *args, **kwargs)
Asserts that execution of callable ``callable_obj`` raised the
``expected_exception`` exception and that such exception has an
``expected_message`` representation. Any other outcome is reported as a
failure. Similar to unittest's ``assertRaisesRegexp`` with the difference
that ``expected_message`` isn't a regular expression.
.. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='') .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='')
@ -1626,9 +1668,13 @@ manually, assign the empty list to ``mail.outbox``::
# Empty the test outbox # Empty the test outbox
mail.outbox = [] mail.outbox = []
.. _skipping-tests:
Skipping tests Skipping tests
-------------- --------------
.. currentmodule:: django.test
.. versionadded:: 1.3 .. versionadded:: 1.3
The unittest library provides the ``@skipIf`` and ``@skipUnless`` The unittest library provides the ``@skipIf`` and ``@skipUnless``
@ -1651,8 +1697,7 @@ features class. See :class:`~django.db.backends.BaseDatabaseFeatures`
class for a full list of database features that can be used as a basis class for a full list of database features that can be used as a basis
for skipping tests. for skipping tests.
skipIfDBFeature .. function:: skipIfDBFeature(feature_name_string)
~~~~~~~~~~~~~~~
Skip the decorated test if the named database feature is supported. Skip the decorated test if the named database feature is supported.
@ -1665,8 +1710,7 @@ it would under MySQL with MyISAM tables)::
def test_transaction_behavior(self): def test_transaction_behavior(self):
# ... conditional test code # ... conditional test code
skipUnlessDBFeature .. function:: skipUnlessDBFeature(feature_name_string)
~~~~~~~~~~~~~~~~~~~
Skip the decorated test if the named database feature is *not* Skip the decorated test if the named database feature is *not*
supported. supported.

View File

@ -19,12 +19,6 @@ class InvalidFields(admin.ModelAdmin):
fields = ['spam'] fields = ['spam']
class ValidationTestCase(TestCase): class ValidationTestCase(TestCase):
def assertRaisesMessage(self, exc, msg, func, *args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
self.assertEqual(msg, str(e))
self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e)))
def test_readonly_and_editable(self): def test_readonly_and_editable(self):
class SongAdmin(admin.ModelAdmin): class SongAdmin(admin.ModelAdmin):

View File

@ -9,13 +9,6 @@ def pks(objects):
class CustomColumnRegression(TestCase): class CustomColumnRegression(TestCase):
def assertRaisesMessage(self, exc, msg, func, *args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
self.assertEqual(msg, str(e))
self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e)))
def setUp(self): def setUp(self):
self.a1 = Author.objects.create(first_name='John', last_name='Smith') self.a1 = Author.objects.create(first_name='John', last_name='Smith')
self.a2 = Author.objects.create(first_name='Peter', last_name='Jones') self.a2 = Author.objects.create(first_name='Peter', last_name='Jones')

View File

@ -22,6 +22,7 @@ from django.core.files.base import ContentFile
from django.core.files.images import get_image_dimensions from django.core.files.images import get_image_dimensions
from django.core.files.storage import FileSystemStorage, get_storage_class from django.core.files.storage import FileSystemStorage, get_storage_class
from django.core.files.uploadedfile import UploadedFile from django.core.files.uploadedfile import UploadedFile
from django.test import SimpleTestCase
from django.utils import unittest from django.utils import unittest
# Try to import PIL in either of the two ways it can end up installed. # Try to import PIL in either of the two ways it can end up installed.
@ -36,14 +37,7 @@ except ImportError:
Image = None Image = None
class GetStorageClassTests(unittest.TestCase): class GetStorageClassTests(SimpleTestCase):
def assertRaisesErrorWithMessage(self, error, message, callable,
*args, **kwargs):
self.assertRaises(error, callable, *args, **kwargs)
try:
callable(*args, **kwargs)
except error, e:
self.assertEqual(message, str(e))
def test_get_filesystem_storage(self): def test_get_filesystem_storage(self):
""" """
@ -57,7 +51,7 @@ class GetStorageClassTests(unittest.TestCase):
""" """
get_storage_class raises an error if the requested import don't exist. get_storage_class raises an error if the requested import don't exist.
""" """
self.assertRaisesErrorWithMessage( self.assertRaisesMessage(
ImproperlyConfigured, ImproperlyConfigured,
"NonExistingStorage isn't a storage module.", "NonExistingStorage isn't a storage module.",
get_storage_class, get_storage_class,
@ -67,7 +61,7 @@ class GetStorageClassTests(unittest.TestCase):
""" """
get_storage_class raises an error if the requested class don't exist. get_storage_class raises an error if the requested class don't exist.
""" """
self.assertRaisesErrorWithMessage( self.assertRaisesMessage(
ImproperlyConfigured, ImproperlyConfigured,
'Storage module "django.core.files.storage" does not define a '\ 'Storage module "django.core.files.storage" does not define a '\
'"NonExistingStorage" class.', '"NonExistingStorage" class.',

View File

@ -393,12 +393,6 @@ class TestFixtures(TestCase):
class NaturalKeyFixtureTests(TestCase): class NaturalKeyFixtureTests(TestCase):
def assertRaisesMessage(self, exc, msg, func, *args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
self.assertEqual(msg, str(e))
self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e)))
def test_nk_deserialize(self): def test_nk_deserialize(self):
""" """

View File

@ -33,7 +33,7 @@ from functools import wraps
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import * from django.forms import *
from django.utils.unittest import TestCase from django.test import SimpleTestCase
def fix_os_paths(x): def fix_os_paths(x):
@ -69,14 +69,7 @@ def verify_exists_urls(existing_urls=()):
return decorator return decorator
class FieldsTests(TestCase): class FieldsTests(SimpleTestCase):
def assertRaisesErrorWithMessage(self, error, message, callable, *args, **kwargs):
self.assertRaises(error, callable, *args, **kwargs)
try:
callable(*args, **kwargs)
except error, e:
self.assertEqual(message, str(e))
def test_field_sets_widget_is_required(self): def test_field_sets_widget_is_required(self):
self.assertTrue(Field(required=True).widget.is_required) self.assertTrue(Field(required=True).widget.is_required)
@ -88,8 +81,8 @@ class FieldsTests(TestCase):
f = CharField() f = CharField()
self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'1', f.clean(1))
self.assertEqual(u'hello', f.clean('hello')) self.assertEqual(u'hello', f.clean('hello'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3])) self.assertEqual(u'[1, 2, 3]', f.clean([1, 2, 3]))
self.assertEqual(f.max_length, None) self.assertEqual(f.max_length, None)
self.assertEqual(f.min_length, None) self.assertEqual(f.min_length, None)
@ -108,14 +101,14 @@ class FieldsTests(TestCase):
f = CharField(max_length=10, required=False) f = CharField(max_length=10, required=False)
self.assertEqual(u'12345', f.clean('12345')) self.assertEqual(u'12345', f.clean('12345'))
self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertEqual(u'1234567890', f.clean('1234567890'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '1234567890a') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '1234567890a')
self.assertEqual(f.max_length, 10) self.assertEqual(f.max_length, 10)
self.assertEqual(f.min_length, None) self.assertEqual(f.min_length, None)
def test_charfield_4(self): def test_charfield_4(self):
f = CharField(min_length=10, required=False) f = CharField(min_length=10, required=False)
self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(''))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345')
self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertEqual(u'1234567890', f.clean('1234567890'))
self.assertEqual(u'1234567890a', f.clean('1234567890a')) self.assertEqual(u'1234567890a', f.clean('1234567890a'))
self.assertEqual(f.max_length, None) self.assertEqual(f.max_length, None)
@ -123,8 +116,8 @@ class FieldsTests(TestCase):
def test_charfield_5(self): def test_charfield_5(self):
f = CharField(min_length=10, required=True) f = CharField(min_length=10, required=True)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 5).']", f.clean, '12345')
self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertEqual(u'1234567890', f.clean('1234567890'))
self.assertEqual(u'1234567890a', f.clean('1234567890a')) self.assertEqual(u'1234567890a', f.clean('1234567890a'))
self.assertEqual(f.max_length, None) self.assertEqual(f.max_length, None)
@ -134,18 +127,18 @@ class FieldsTests(TestCase):
def test_integerfield_1(self): def test_integerfield_1(self):
f = IntegerField() f = IntegerField()
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(1, f.clean('1')) self.assertEqual(1, f.clean('1'))
self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(True, isinstance(f.clean('1'), int))
self.assertEqual(23, f.clean('23')) self.assertEqual(23, f.clean('23'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a') self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a')
self.assertEqual(42, f.clean(42)) self.assertEqual(42, f.clean(42))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 3.14) self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 3.14)
self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean('1 '))
self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1'))
self.assertEqual(1, f.clean(' 1 ')) self.assertEqual(1, f.clean(' 1 '))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a')
self.assertEqual(f.max_value, None) self.assertEqual(f.max_value, None)
self.assertEqual(f.min_value, None) self.assertEqual(f.min_value, None)
@ -158,29 +151,29 @@ class FieldsTests(TestCase):
self.assertEqual(1, f.clean('1')) self.assertEqual(1, f.clean('1'))
self.assertEqual(True, isinstance(f.clean('1'), int)) self.assertEqual(True, isinstance(f.clean('1'), int))
self.assertEqual(23, f.clean('23')) self.assertEqual(23, f.clean('23'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a') self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, 'a')
self.assertEqual(1, f.clean('1 ')) self.assertEqual(1, f.clean('1 '))
self.assertEqual(1, f.clean(' 1')) self.assertEqual(1, f.clean(' 1'))
self.assertEqual(1, f.clean(' 1 ')) self.assertEqual(1, f.clean(' 1 '))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a') self.assertRaisesMessage(ValidationError, "[u'Enter a whole number.']", f.clean, '1a')
self.assertEqual(f.max_value, None) self.assertEqual(f.max_value, None)
self.assertEqual(f.min_value, None) self.assertEqual(f.min_value, None)
def test_integerfield_3(self): def test_integerfield_3(self):
f = IntegerField(max_value=10) f = IntegerField(max_value=10)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(1, f.clean(1)) self.assertEqual(1, f.clean(1))
self.assertEqual(10, f.clean(10)) self.assertEqual(10, f.clean(10))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, 11) self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, 11)
self.assertEqual(10, f.clean('10')) self.assertEqual(10, f.clean('10'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, '11') self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 10.']", f.clean, '11')
self.assertEqual(f.max_value, 10) self.assertEqual(f.max_value, 10)
self.assertEqual(f.min_value, None) self.assertEqual(f.min_value, None)
def test_integerfield_4(self): def test_integerfield_4(self):
f = IntegerField(min_value=10) f = IntegerField(min_value=10)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1)
self.assertEqual(10, f.clean(10)) self.assertEqual(10, f.clean(10))
self.assertEqual(11, f.clean(11)) self.assertEqual(11, f.clean(11))
self.assertEqual(10, f.clean('10')) self.assertEqual(10, f.clean('10'))
@ -190,14 +183,14 @@ class FieldsTests(TestCase):
def test_integerfield_5(self): def test_integerfield_5(self):
f = IntegerField(min_value=10, max_value=20) f = IntegerField(min_value=10, max_value=20)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1) self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 10.']", f.clean, 1)
self.assertEqual(10, f.clean(10)) self.assertEqual(10, f.clean(10))
self.assertEqual(11, f.clean(11)) self.assertEqual(11, f.clean(11))
self.assertEqual(10, f.clean('10')) self.assertEqual(10, f.clean('10'))
self.assertEqual(11, f.clean('11')) self.assertEqual(11, f.clean('11'))
self.assertEqual(20, f.clean(20)) self.assertEqual(20, f.clean(20))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 20.']", f.clean, 21) self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 20.']", f.clean, 21)
self.assertEqual(f.max_value, 20) self.assertEqual(f.max_value, 20)
self.assertEqual(f.min_value, 10) self.assertEqual(f.min_value, 10)
@ -205,19 +198,19 @@ class FieldsTests(TestCase):
def test_floatfield_1(self): def test_floatfield_1(self):
f = FloatField() f = FloatField()
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(1.0, f.clean('1')) self.assertEqual(1.0, f.clean('1'))
self.assertEqual(True, isinstance(f.clean('1'), float)) self.assertEqual(True, isinstance(f.clean('1'), float))
self.assertEqual(23.0, f.clean('23')) self.assertEqual(23.0, f.clean('23'))
self.assertEqual(3.1400000000000001, f.clean('3.14')) self.assertEqual(3.1400000000000001, f.clean('3.14'))
self.assertEqual(3.1400000000000001, f.clean(3.14)) self.assertEqual(3.1400000000000001, f.clean(3.14))
self.assertEqual(42.0, f.clean(42)) self.assertEqual(42.0, f.clean(42))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a')
self.assertEqual(1.0, f.clean('1.0 ')) self.assertEqual(1.0, f.clean('1.0 '))
self.assertEqual(1.0, f.clean(' 1.0')) self.assertEqual(1.0, f.clean(' 1.0'))
self.assertEqual(1.0, f.clean(' 1.0 ')) self.assertEqual(1.0, f.clean(' 1.0 '))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a')
self.assertEqual(f.max_value, None) self.assertEqual(f.max_value, None)
self.assertEqual(f.min_value, None) self.assertEqual(f.min_value, None)
@ -231,8 +224,8 @@ class FieldsTests(TestCase):
def test_floatfield_3(self): def test_floatfield_3(self):
f = FloatField(max_value=1.5, min_value=0.5) f = FloatField(max_value=1.5, min_value=0.5)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4')
self.assertEqual(1.5, f.clean('1.5')) self.assertEqual(1.5, f.clean('1.5'))
self.assertEqual(0.5, f.clean('0.5')) self.assertEqual(0.5, f.clean('0.5'))
self.assertEqual(f.max_value, 1.5) self.assertEqual(f.max_value, 1.5)
@ -242,34 +235,34 @@ class FieldsTests(TestCase):
def test_decimalfield_1(self): def test_decimalfield_1(self):
f = DecimalField(max_digits=4, decimal_places=2) f = DecimalField(max_digits=4, decimal_places=2)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(f.clean('1'), Decimal("1")) self.assertEqual(f.clean('1'), Decimal("1"))
self.assertEqual(True, isinstance(f.clean('1'), Decimal)) self.assertEqual(True, isinstance(f.clean('1'), Decimal))
self.assertEqual(f.clean('23'), Decimal("23")) self.assertEqual(f.clean('23'), Decimal("23"))
self.assertEqual(f.clean('3.14'), Decimal("3.14")) self.assertEqual(f.clean('3.14'), Decimal("3.14"))
self.assertEqual(f.clean(3.14), Decimal("3.14")) self.assertEqual(f.clean(3.14), Decimal("3.14"))
self.assertEqual(f.clean(Decimal('3.14')), Decimal("3.14")) self.assertEqual(f.clean(Decimal('3.14')), Decimal("3.14"))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'NaN') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'NaN')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'Inf') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'Inf')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '-Inf') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '-Inf')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, 'a')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, u'łąść') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, u'łąść')
self.assertEqual(f.clean('1.0 '), Decimal("1.0")) self.assertEqual(f.clean('1.0 '), Decimal("1.0"))
self.assertEqual(f.clean(' 1.0'), Decimal("1.0")) self.assertEqual(f.clean(' 1.0'), Decimal("1.0"))
self.assertEqual(f.clean(' 1.0 '), Decimal("1.0")) self.assertEqual(f.clean(' 1.0 '), Decimal("1.0"))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '1.0a')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '123.45') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '123.45')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '1.234') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '1.234')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 digits before the decimal point.']", f.clean, '123.4') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 digits before the decimal point.']", f.clean, '123.4')
self.assertEqual(f.clean('-12.34'), Decimal("-12.34")) self.assertEqual(f.clean('-12.34'), Decimal("-12.34"))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-123.45') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-123.45')
self.assertEqual(f.clean('-.12'), Decimal("-0.12")) self.assertEqual(f.clean('-.12'), Decimal("-0.12"))
self.assertEqual(f.clean('-00.12'), Decimal("-0.12")) self.assertEqual(f.clean('-00.12'), Decimal("-0.12"))
self.assertEqual(f.clean('-000.12'), Decimal("-0.12")) self.assertEqual(f.clean('-000.12'), Decimal("-0.12"))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '-000.123') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '-000.123')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-000.12345') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 4 digits in total.']", f.clean, '-000.12345')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a number.']", f.clean, '--0.12') self.assertRaisesMessage(ValidationError, "[u'Enter a number.']", f.clean, '--0.12')
self.assertEqual(f.max_digits, 4) self.assertEqual(f.max_digits, 4)
self.assertEqual(f.decimal_places, 2) self.assertEqual(f.decimal_places, 2)
self.assertEqual(f.max_value, None) self.assertEqual(f.max_value, None)
@ -287,8 +280,8 @@ class FieldsTests(TestCase):
def test_decimalfield_3(self): def test_decimalfield_3(self):
f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5')) f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6') self.assertRaisesMessage(ValidationError, "[u'Ensure this value is less than or equal to 1.5.']", f.clean, '1.6')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4') self.assertRaisesMessage(ValidationError, "[u'Ensure this value is greater than or equal to 0.5.']", f.clean, '0.4')
self.assertEqual(f.clean('1.5'), Decimal("1.5")) self.assertEqual(f.clean('1.5'), Decimal("1.5"))
self.assertEqual(f.clean('0.5'), Decimal("0.5")) self.assertEqual(f.clean('0.5'), Decimal("0.5"))
self.assertEqual(f.clean('.5'), Decimal("0.5")) self.assertEqual(f.clean('.5'), Decimal("0.5"))
@ -300,7 +293,7 @@ class FieldsTests(TestCase):
def test_decimalfield_4(self): def test_decimalfield_4(self):
f = DecimalField(decimal_places=2) f = DecimalField(decimal_places=2)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '0.00000001') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 2 decimal places.']", f.clean, '0.00000001')
def test_decimalfield_5(self): def test_decimalfield_5(self):
f = DecimalField(max_digits=3) f = DecimalField(max_digits=3)
@ -310,13 +303,13 @@ class FieldsTests(TestCase):
self.assertEqual(f.clean('0000000.100'), Decimal("0.100")) self.assertEqual(f.clean('0000000.100'), Decimal("0.100"))
# Only leading whole zeros "collapse" to one digit. # Only leading whole zeros "collapse" to one digit.
self.assertEqual(f.clean('000000.02'), Decimal('0.02')) self.assertEqual(f.clean('000000.02'), Decimal('0.02'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 3 digits in total.']", f.clean, '000000.0002') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 3 digits in total.']", f.clean, '000000.0002')
self.assertEqual(f.clean('.002'), Decimal("0.002")) self.assertEqual(f.clean('.002'), Decimal("0.002"))
def test_decimalfield_6(self): def test_decimalfield_6(self):
f = DecimalField(max_digits=2, decimal_places=2) f = DecimalField(max_digits=2, decimal_places=2)
self.assertEqual(f.clean('.01'), Decimal(".01")) self.assertEqual(f.clean('.01'), Decimal(".01"))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure that there are no more than 0 digits before the decimal point.']", f.clean, '1.1') self.assertRaisesMessage(ValidationError, "[u'Ensure that there are no more than 0 digits before the decimal point.']", f.clean, '1.1')
# DateField ################################################################### # DateField ###################################################################
@ -334,10 +327,10 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25, 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('October 25, 2006'))
self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October 2006'))
self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October, 2006')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('25 October, 2006'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-4-31') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-4-31')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '200a-10-25') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '200a-10-25')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '25/10/06') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '25/10/06')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
def test_datefield_2(self): def test_datefield_2(self):
f = DateField(required=False) f = DateField(required=False)
@ -351,9 +344,9 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.date(2006, 10, 25)))
self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30))) self.assertEqual(datetime.date(2006, 10, 25), f.clean(datetime.datetime(2006, 10, 25, 14, 30)))
self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006 10 25')) self.assertEqual(datetime.date(2006, 10, 25), f.clean('2006 10 25'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-10-25') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '2006-10-25')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/2006') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/2006')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/06') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, '10/25/06')
def test_datefield_4(self): def test_datefield_4(self):
# Test whitespace stripping behavior (#5714) # Test whitespace stripping behavior (#5714)
@ -364,7 +357,7 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25 2006 '))
self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25, 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' October 25, 2006 '))
self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 25 October 2006 ')) self.assertEqual(datetime.date(2006, 10, 25), f.clean(' 25 October 2006 '))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ' ') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ' ')
# TimeField ################################################################### # TimeField ###################################################################
@ -374,8 +367,8 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59)))
self.assertEqual(datetime.time(14, 25), f.clean('14:25')) self.assertEqual(datetime.time(14, 25), f.clean('14:25'))
self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59')) self.assertEqual(datetime.time(14, 25, 59), f.clean('14:25:59'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, 'hello')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '1:24 p.m.') self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '1:24 p.m.')
def test_timefield_2(self): def test_timefield_2(self):
f = TimeField(input_formats=['%I:%M %p']) f = TimeField(input_formats=['%I:%M %p'])
@ -383,14 +376,14 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59))) self.assertEqual(datetime.time(14, 25, 59), f.clean(datetime.time(14, 25, 59)))
self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM')) self.assertEqual(datetime.time(4, 25), f.clean('4:25 AM'))
self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM')) self.assertEqual(datetime.time(16, 25), f.clean('4:25 PM'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '14:30:45') self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, '14:30:45')
def test_timefield_3(self): def test_timefield_3(self):
f = TimeField() f = TimeField()
# Test whitespace stripping behavior (#5714) # Test whitespace stripping behavior (#5714)
self.assertEqual(datetime.time(14, 25), f.clean(' 14:25 ')) self.assertEqual(datetime.time(14, 25), f.clean(' 14:25 '))
self.assertEqual(datetime.time(14, 25, 59), f.clean(' 14:25:59 ')) self.assertEqual(datetime.time(14, 25, 59), f.clean(' 14:25:59 '))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ' ') self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ' ')
# DateTimeField ############################################################### # DateTimeField ###############################################################
@ -415,8 +408,8 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30:00'))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('10/25/06 14:30'))
self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean('10/25/06'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, 'hello')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 4:30 p.m.') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 4:30 p.m.')
def test_datetimefield_2(self): def test_datetimefield_2(self):
f = DateTimeField(input_formats=['%Y %m %d %I:%M %p']) f = DateTimeField(input_formats=['%Y %m %d %I:%M %p'])
@ -425,7 +418,7 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59)))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 59, 200), f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200)))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean('2006 10 25 2:30 PM'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 14:30:45') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, '2006-10-25 14:30:45')
def test_datetimefield_3(self): def test_datetimefield_3(self):
f = DateTimeField(required=False) f = DateTimeField(required=False)
@ -444,7 +437,7 @@ class FieldsTests(TestCase):
self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/2006 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/2006 '))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/06 14:30:45 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean(' 10/25/06 14:30:45 '))
self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/06 ')) self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(' 10/25/06 '))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, ' ') self.assertRaisesMessage(ValidationError, "[u'Enter a valid date/time.']", f.clean, ' ')
# RegexField ################################################################## # RegexField ##################################################################
@ -452,65 +445,65 @@ class FieldsTests(TestCase):
f = RegexField('^\d[A-F]\d$') f = RegexField('^\d[A-F]\d$')
self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'2A2', f.clean('2A2'))
self.assertEqual(u'3F3', f.clean('3F3')) self.assertEqual(u'3F3', f.clean('3F3'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
def test_regexfield_2(self): def test_regexfield_2(self):
f = RegexField('^\d[A-F]\d$', required=False) f = RegexField('^\d[A-F]\d$', required=False)
self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'2A2', f.clean('2A2'))
self.assertEqual(u'3F3', f.clean('3F3')) self.assertEqual(u'3F3', f.clean('3F3'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3')
self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(''))
def test_regexfield_3(self): def test_regexfield_3(self):
f = RegexField(re.compile('^\d[A-F]\d$')) f = RegexField(re.compile('^\d[A-F]\d$'))
self.assertEqual(u'2A2', f.clean('2A2')) self.assertEqual(u'2A2', f.clean('2A2'))
self.assertEqual(u'3F3', f.clean('3F3')) self.assertEqual(u'3F3', f.clean('3F3'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '3G3')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, ' 2A2')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '2A2 ')
def test_regexfield_4(self): def test_regexfield_4(self):
f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.') f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.')
self.assertEqual(u'1234', f.clean('1234')) self.assertEqual(u'1234', f.clean('1234'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, '123') self.assertRaisesMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, '123')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, 'abcd') self.assertRaisesMessage(ValidationError, "[u'Enter a four-digit number.']", f.clean, 'abcd')
def test_regexfield_5(self): def test_regexfield_5(self):
f = RegexField('^\d+$', min_length=5, max_length=10) f = RegexField('^\d+$', min_length=5, max_length=10)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).']", f.clean, '123') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).']", f.clean, '123')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).', u'Enter a valid value.']", f.clean, 'abc') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 5 characters (it has 3).', u'Enter a valid value.']", f.clean, 'abc')
self.assertEqual(u'12345', f.clean('12345')) self.assertEqual(u'12345', f.clean('12345'))
self.assertEqual(u'1234567890', f.clean('1234567890')) self.assertEqual(u'1234567890', f.clean('1234567890'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 10 characters (it has 11).']", f.clean, '12345678901')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a') self.assertRaisesMessage(ValidationError, "[u'Enter a valid value.']", f.clean, '12345a')
# EmailField ################################################################## # EmailField ##################################################################
def test_emailfield_1(self): def test_emailfield_1(self):
f = EmailField() f = EmailField()
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(u'person@example.com', f.clean('person@example.com')) self.assertEqual(u'person@example.com', f.clean('person@example.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@invalid-.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@invalid-.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@-invalid.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@-invalid.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.alid-.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.alid-.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.-alid.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@inv-.-alid.com')
self.assertEqual(u'example@valid-----hyphens.com', f.clean('example@valid-----hyphens.com')) self.assertEqual(u'example@valid-----hyphens.com', f.clean('example@valid-----hyphens.com'))
self.assertEqual(u'example@valid-with-hyphens.com', f.clean('example@valid-with-hyphens.com')) self.assertEqual(u'example@valid-with-hyphens.com', f.clean('example@valid-with-hyphens.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'example@.com')
self.assertEqual(u'local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', f.clean('local@domain.with.idn.xyzäöüßabc.part.com')) self.assertEqual(u'local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', f.clean('local@domain.with.idn.xyzäöüßabc.part.com'))
def test_email_regexp_for_performance(self): def test_email_regexp_for_performance(self):
f = EmailField() f = EmailField()
# Check for runaway regex security problem. This will take for-freeking-ever # Check for runaway regex security problem. This will take for-freeking-ever
# if the security fix isn't in place. # if the security fix isn't in place.
self.assertRaisesErrorWithMessage( self.assertRaisesMessage(
ValidationError, ValidationError,
"[u'Enter a valid e-mail address.']", "[u'Enter a valid e-mail address.']",
f.clean, f.clean,
@ -523,39 +516,39 @@ class FieldsTests(TestCase):
self.assertEqual(u'', f.clean(None)) self.assertEqual(u'', f.clean(None))
self.assertEqual(u'person@example.com', f.clean('person@example.com')) self.assertEqual(u'person@example.com', f.clean('person@example.com'))
self.assertEqual(u'example@example.com', f.clean(' example@example.com \t \t ')) self.assertEqual(u'example@example.com', f.clean(' example@example.com \t \t '))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'foo@bar')
def test_emailfield_3(self): def test_emailfield_3(self):
f = EmailField(min_length=10, max_length=15) f = EmailField(min_length=10, max_length=15)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 9).']", f.clean, 'a@foo.com') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 10 characters (it has 9).']", f.clean, 'a@foo.com')
self.assertEqual(u'alf@foo.com', f.clean('alf@foo.com')) self.assertEqual(u'alf@foo.com', f.clean('alf@foo.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 15 characters (it has 20).']", f.clean, 'alf123456788@foo.com') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 15 characters (it has 20).']", f.clean, 'alf123456788@foo.com')
# FileField ################################################################## # FileField ##################################################################
def test_filefield_1(self): def test_filefield_1(self):
f = FileField() f = FileField()
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '', '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '', '')
self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None, '')
self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', '')) self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', ''))
self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', ''), '') self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, SimpleUploadedFile('', ''), '')
self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf')) self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, 'some content that is not a file') self.assertRaisesMessage(ValidationError, "[u'No file was submitted. Check the encoding type on the form.']", f.clean, 'some content that is not a file')
self.assertRaisesErrorWithMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', None)) self.assertRaisesMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', None))
self.assertRaisesErrorWithMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', '')) self.assertRaisesMessage(ValidationError, "[u'The submitted file is empty.']", f.clean, SimpleUploadedFile('name', ''))
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content')))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'))))
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'))))
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf'))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf')))
def test_filefield_2(self): def test_filefield_2(self):
f = FileField(max_length = 5) f = FileField(max_length = 5)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', 'hello world')) self.assertRaisesMessage(ValidationError, "[u'Ensure this filename has at most 5 characters (it has 18).']", f.clean, SimpleUploadedFile('test_maxlength.txt', 'hello world'))
self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf')) self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf')) self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content')))) self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', 'Some File Content'))))
@ -569,8 +562,8 @@ class FieldsTests(TestCase):
def test_urlfield_1(self): def test_urlfield_1(self):
f = URLField() f = URLField()
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(u'http://localhost/', f.clean('http://localhost')) self.assertEqual(u'http://localhost/', f.clean('http://localhost'))
self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertEqual(u'http://example.com/', f.clean('http://example.com'))
self.assertEqual(u'http://example.com./', f.clean('http://example.com.')) self.assertEqual(u'http://example.com./', f.clean('http://example.com.'))
@ -580,17 +573,17 @@ class FieldsTests(TestCase):
self.assertEqual(u'http://subdomain.domain.com/', f.clean('subdomain.domain.com')) self.assertEqual(u'http://subdomain.domain.com/', f.clean('subdomain.domain.com'))
self.assertEqual(u'http://200.8.9.10/', f.clean('http://200.8.9.10')) self.assertEqual(u'http://200.8.9.10/', f.clean('http://200.8.9.10'))
self.assertEqual(u'http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test')) self.assertEqual(u'http://200.8.9.10:8000/test', f.clean('http://200.8.9.10:8000/test'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'com.') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'com.')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, '.') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, '.')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://invalid-.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://invalid-.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://-invalid.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://-invalid.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.alid-.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.alid-.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.-alid.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://inv-.-alid.com')
self.assertEqual(u'http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com')) self.assertEqual(u'http://valid-----hyphens.com/', f.clean('http://valid-----hyphens.com'))
self.assertEqual(u'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah')) self.assertEqual(u'http://some.idn.xyz\xe4\xf6\xfc\xdfabc.domain.com:123/blah', f.clean('http://some.idn.xyzäöüßabc.domain.com:123/blah'))
self.assertEqual(u'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')) self.assertEqual(u'http://www.example.com/s/http://code.djangoproject.com/ticket/13804', f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804'))
@ -598,11 +591,11 @@ class FieldsTests(TestCase):
def test_url_regex_ticket11198(self): def test_url_regex_ticket11198(self):
f = URLField() f = URLField()
# hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed # hangs "forever" if catastrophic backtracking in ticket:#11198 not fixed
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*200,)) self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*200,))
# a second test, to make sure the problem is really addressed, even on # a second test, to make sure the problem is really addressed, even on
# domains that don't fail the domain label length check in the regex # domains that don't fail the domain label length check in the regex
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*60,)) self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://%s' % ("X"*60,))
def test_urlfield_2(self): def test_urlfield_2(self):
f = URLField(required=False) f = URLField(required=False)
@ -610,17 +603,17 @@ class FieldsTests(TestCase):
self.assertEqual(u'', f.clean(None)) self.assertEqual(u'', f.clean(None))
self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertEqual(u'http://example.com/', f.clean('http://example.com'))
self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com')) self.assertEqual(u'http://www.example.com/', f.clean('http://www.example.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'foo')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example.')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://.com')
@verify_exists_urls(('http://www.google.com/',)) @verify_exists_urls(('http://www.google.com/',))
def test_urlfield_3(self): def test_urlfield_3(self):
f = URLField(verify_exists=True) f = URLField(verify_exists=True)
self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com')) self.assertEqual(u'http://www.google.com/', f.clean('http://www.google.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example') self.assertRaisesMessage(ValidationError, "[u'Enter a valid URL.']", f.clean, 'http://example')
self.assertRaises(ValidationError, f.clean, 'http://www.broken.djangoproject.com') # bad domain self.assertRaises(ValidationError, f.clean, 'http://www.broken.djangoproject.com') # bad domain
self.assertRaises(ValidationError, f.clean, 'http://qa-dev.w3.org/link-testsuite/http.php?code=405') # Method not allowed self.assertRaises(ValidationError, f.clean, 'http://qa-dev.w3.org/link-testsuite/http.php?code=405') # Method not allowed
try: try:
@ -641,9 +634,9 @@ class FieldsTests(TestCase):
def test_urlfield_5(self): def test_urlfield_5(self):
f = URLField(min_length=15, max_length=20) f = URLField(min_length=15, max_length=20)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at least 15 characters (it has 13).']", f.clean, 'http://f.com') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at least 15 characters (it has 13).']", f.clean, 'http://f.com')
self.assertEqual(u'http://example.com/', f.clean('http://example.com')) self.assertEqual(u'http://example.com/', f.clean('http://example.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 38).']", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 38).']", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com')
def test_urlfield_6(self): def test_urlfield_6(self):
f = URLField(required=False) f = URLField(required=False)
@ -697,15 +690,15 @@ class FieldsTests(TestCase):
def test_booleanfield_1(self): def test_booleanfield_1(self):
f = BooleanField() f = BooleanField()
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(True, f.clean(True)) self.assertEqual(True, f.clean(True))
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, False) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, False)
self.assertEqual(True, f.clean(1)) self.assertEqual(True, f.clean(1))
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, 0) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, 0)
self.assertEqual(True, f.clean('Django rocks')) self.assertEqual(True, f.clean('Django rocks'))
self.assertEqual(True, f.clean('True')) self.assertEqual(True, f.clean('True'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, 'False') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, 'False')
def test_booleanfield_2(self): def test_booleanfield_2(self):
f = BooleanField(required=False) f = BooleanField(required=False)
@ -726,11 +719,11 @@ class FieldsTests(TestCase):
def test_choicefield_1(self): def test_choicefield_1(self):
f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')])
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'1', f.clean(1))
self.assertEqual(u'1', f.clean('1')) self.assertEqual(u'1', f.clean('1'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3')
def test_choicefield_2(self): def test_choicefield_2(self):
f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
@ -738,12 +731,12 @@ class FieldsTests(TestCase):
self.assertEqual(u'', f.clean(None)) self.assertEqual(u'', f.clean(None))
self.assertEqual(u'1', f.clean(1)) self.assertEqual(u'1', f.clean(1))
self.assertEqual(u'1', f.clean('1')) self.assertEqual(u'1', f.clean('1'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3') self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, '3')
def test_choicefield_3(self): def test_choicefield_3(self):
f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
self.assertEqual(u'J', f.clean('J')) self.assertEqual(u'J', f.clean('J'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. John is not one of the available choices.']", f.clean, 'John') self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. John is not one of the available choices.']", f.clean, 'John')
def test_choicefield_4(self): def test_choicefield_4(self):
f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
@ -753,7 +746,7 @@ class FieldsTests(TestCase):
self.assertEqual(u'3', f.clean('3')) self.assertEqual(u'3', f.clean('3'))
self.assertEqual(u'5', f.clean(5)) self.assertEqual(u'5', f.clean(5))
self.assertEqual(u'5', f.clean('5')) self.assertEqual(u'5', f.clean('5'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, '6') self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, '6')
# TypedChoiceField ############################################################ # TypedChoiceField ############################################################
# TypedChoiceField is just like ChoiceField, except that coerced types will # TypedChoiceField is just like ChoiceField, except that coerced types will
@ -762,7 +755,7 @@ class FieldsTests(TestCase):
def test_typedchoicefield_1(self): def test_typedchoicefield_1(self):
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual(1, f.clean('1')) self.assertEqual(1, f.clean('1'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, '2') self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, '2')
def test_typedchoicefield_2(self): def test_typedchoicefield_2(self):
# Different coercion, same validation. # Different coercion, same validation.
@ -778,9 +771,9 @@ class FieldsTests(TestCase):
# Even more weirdness: if you have a valid choice but your coercion function # Even more weirdness: if you have a valid choice but your coercion function
# can't coerce, you'll still get a validation error. Don't do this! # can't coerce, you'll still get a validation error. Don't do this!
f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, 'B') self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, 'B')
# Required fields require values # Required fields require values
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
def test_typedchoicefield_5(self): def test_typedchoicefield_5(self):
# Non-required fields aren't required # Non-required fields aren't required
@ -842,17 +835,17 @@ class FieldsTests(TestCase):
def test_multiplechoicefield_1(self): def test_multiplechoicefield_1(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')]) f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertEqual([u'1'], f.clean([1])) self.assertEqual([u'1'], f.clean([1]))
self.assertEqual([u'1'], f.clean(['1'])) self.assertEqual([u'1'], f.clean(['1']))
self.assertEqual([u'1', u'2'], f.clean(['1', '2'])) self.assertEqual([u'1', u'2'], f.clean(['1', '2']))
self.assertEqual([u'1', u'2'], f.clean([1, '2'])) self.assertEqual([u'1', u'2'], f.clean([1, '2']))
self.assertEqual([u'1', u'2'], f.clean((1, '2'))) self.assertEqual([u'1', u'2'], f.clean((1, '2')))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, []) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, [])
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, ()) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, ())
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3'])
def test_multiplechoicefield_2(self): def test_multiplechoicefield_2(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
@ -863,10 +856,10 @@ class FieldsTests(TestCase):
self.assertEqual([u'1', u'2'], f.clean(['1', '2'])) self.assertEqual([u'1', u'2'], f.clean(['1', '2']))
self.assertEqual([u'1', u'2'], f.clean([1, '2'])) self.assertEqual([u'1', u'2'], f.clean([1, '2']))
self.assertEqual([u'1', u'2'], f.clean((1, '2'))) self.assertEqual([u'1', u'2'], f.clean((1, '2')))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
self.assertEqual([], f.clean([])) self.assertEqual([], f.clean([]))
self.assertEqual([], f.clean(())) self.assertEqual([], f.clean(()))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3']) self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 3 is not one of the available choices.']", f.clean, ['3'])
def test_multiplechoicefield_3(self): def test_multiplechoicefield_3(self):
f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
@ -876,8 +869,8 @@ class FieldsTests(TestCase):
self.assertEqual([u'1', u'5'], f.clean([1, '5'])) self.assertEqual([u'1', u'5'], f.clean([1, '5']))
self.assertEqual([u'1', u'5'], f.clean(['1', 5])) self.assertEqual([u'1', u'5'], f.clean(['1', 5]))
self.assertEqual([u'1', u'5'], f.clean(['1', '5'])) self.assertEqual([u'1', u'5'], f.clean(['1', '5']))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['6']) self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['6'])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['1','6']) self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 6 is not one of the available choices.']", f.clean, ['1','6'])
# TypedMultipleChoiceField ############################################################ # TypedMultipleChoiceField ############################################################
# TypedMultipleChoiceField is just like MultipleChoiceField, except that coerced types # TypedMultipleChoiceField is just like MultipleChoiceField, except that coerced types
@ -886,7 +879,7 @@ class FieldsTests(TestCase):
def test_typedmultiplechoicefield_1(self): def test_typedmultiplechoicefield_1(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1], f.clean(['1'])) self.assertEqual([1], f.clean(['1']))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['2']) self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['2'])
def test_typedmultiplechoicefield_2(self): def test_typedmultiplechoicefield_2(self):
# Different coercion, same validation. # Different coercion, same validation.
@ -901,15 +894,15 @@ class FieldsTests(TestCase):
def test_typedmultiplechoicefield_4(self): def test_typedmultiplechoicefield_4(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1, -1], f.clean(['1','-1'])) self.assertEqual([1, -1], f.clean(['1','-1']))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['1','2']) self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. 2 is not one of the available choices.']", f.clean, ['1','2'])
def test_typedmultiplechoicefield_5(self): def test_typedmultiplechoicefield_5(self):
# Even more weirdness: if you have a valid choice but your coercion function # Even more weirdness: if you have a valid choice but your coercion function
# can't coerce, you'll still get a validation error. Don't do this! # can't coerce, you'll still get a validation error. Don't do this!
f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int) f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, ['B']) self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. B is not one of the available choices.']", f.clean, ['B'])
# Required fields require values # Required fields require values
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, []) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, [])
def test_typedmultiplechoicefield_6(self): def test_typedmultiplechoicefield_6(self):
# Non-required fields aren't required # Non-required fields aren't required
@ -926,16 +919,16 @@ class FieldsTests(TestCase):
def test_combofield_1(self): def test_combofield_1(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()]) f = ComboField(fields=[CharField(max_length=20), EmailField()])
self.assertEqual(u'test@example.com', f.clean('test@example.com')) self.assertEqual(u'test@example.com', f.clean('test@example.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
def test_combofield_2(self): def test_combofield_2(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False) f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False)
self.assertEqual(u'test@example.com', f.clean('test@example.com')) self.assertEqual(u'test@example.com', f.clean('test@example.com'))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com') self.assertRaisesMessage(ValidationError, "[u'Ensure this value has at most 20 characters (it has 28).']", f.clean, 'longemailaddress@example.com')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail') self.assertRaisesMessage(ValidationError, "[u'Enter a valid e-mail address.']", f.clean, 'not an e-mail')
self.assertEqual(u'', f.clean('')) self.assertEqual(u'', f.clean(''))
self.assertEqual(u'', f.clean(None)) self.assertEqual(u'', f.clean(None))
@ -964,7 +957,7 @@ class FieldsTests(TestCase):
for exp, got in zip(expected, fix_os_paths(f.choices)): for exp, got in zip(expected, fix_os_paths(f.choices)):
self.assertEqual(exp[1], got[1]) self.assertEqual(exp[1], got[1])
self.assertTrue(got[0].endswith(exp[0])) self.assertTrue(got[0].endswith(exp[0]))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Select a valid choice. fields.py is not one of the available choices.']", f.clean, 'fields.py') self.assertRaisesMessage(ValidationError, "[u'Select a valid choice. fields.py is not one of the available choices.']", f.clean, 'fields.py')
assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py') assert fix_os_paths(f.clean(path + 'fields.py')).endswith('/django/forms/fields.py')
def test_filepathfield_3(self): def test_filepathfield_3(self):
@ -1012,12 +1005,12 @@ class FieldsTests(TestCase):
f = SplitDateTimeField() f = SplitDateTimeField()
assert isinstance(f.widget, SplitDateTimeWidget) assert isinstance(f.widget, SplitDateTimeWidget)
self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])) self.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)]))
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, None) self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, None)
self.assertRaisesErrorWithMessage(ValidationError, "[u'This field is required.']", f.clean, '') self.assertRaisesMessage(ValidationError, "[u'This field is required.']", f.clean, '')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there'])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there'])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30'])
def test_splitdatetimefield_2(self): def test_splitdatetimefield_2(self):
f = SplitDateTimeField(required=False) f = SplitDateTimeField(required=False)
@ -1027,10 +1020,10 @@ class FieldsTests(TestCase):
self.assertEqual(None, f.clean('')) self.assertEqual(None, f.clean(''))
self.assertEqual(None, f.clean([''])) self.assertEqual(None, f.clean(['']))
self.assertEqual(None, f.clean(['', ''])) self.assertEqual(None, f.clean(['', '']))
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello') self.assertRaisesMessage(ValidationError, "[u'Enter a list of values.']", f.clean, 'hello')
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.', u'Enter a valid time.']", f.clean, ['hello', 'there'])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', 'there'])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['hello', '07:30'])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', '']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10', ''])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid time.']", f.clean, ['2006-01-10'])
self.assertRaisesErrorWithMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['', '07:30']) self.assertRaisesMessage(ValidationError, "[u'Enter a valid date.']", f.clean, ['', '07:30'])

View File

@ -22,19 +22,6 @@ class BaseQuerysetTest(TestCase):
def assertValueQuerysetEqual(self, qs, values): def assertValueQuerysetEqual(self, qs, values):
return self.assertQuerysetEqual(qs, values, transform=lambda x: x) return self.assertQuerysetEqual(qs, values, transform=lambda x: x)
def assertRaisesMessage(self, exc, msg, func, *args, **kwargs):
try:
func(*args, **kwargs)
except Exception, e:
self.assertEqual(msg, str(e))
self.assertTrue(isinstance(e, exc), "Expected %s, got %s" % (exc, type(e)))
else:
if hasattr(exc, '__name__'):
excName = exc.__name__
else:
excName = str(exc)
raise AssertionError("%s not raised" % excName)
class Queries1Tests(BaseQuerysetTest): class Queries1Tests(BaseQuerysetTest):
def setUp(self): def setUp(self):

View File

@ -1,6 +1,6 @@
from __future__ import with_statement from __future__ import with_statement
from django.test import TestCase, skipUnlessDBFeature from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.utils.unittest import skip from django.utils.unittest import skip
from models import Person from models import Person
@ -48,6 +48,7 @@ class AssertNumQueriesTests(TestCase):
self.client.get("/test_utils/get_person/%s/" % person.pk) self.client.get("/test_utils/get_person/%s/" % person.pk)
self.assertNumQueries(2, test_func) self.assertNumQueries(2, test_func)
class AssertNumQueriesContextManagerTests(TestCase): class AssertNumQueriesContextManagerTests(TestCase):
urls = 'regressiontests.test_utils.urls' urls = 'regressiontests.test_utils.urls'
@ -129,6 +130,15 @@ class SkippingExtraTests(TestCase):
pass pass
class AssertRaisesMsgTest(SimpleTestCase):
def test_special_re_chars(self):
"""assertRaisesMessage shouldn't interpret RE special chars."""
def func1():
raise ValueError("[.*x+]y?")
self.assertRaisesMessage(ValueError, "[.*x+]y?", func1)
__test__ = {"API_TEST": r""" __test__ = {"API_TEST": r"""
# Some checks of the doctest output normalizer. # Some checks of the doctest output normalizer.
# Standard doctests do fairly # Standard doctests do fairly

View File

@ -138,21 +138,13 @@ test_data = (
class NoURLPatternsTests(TestCase): class NoURLPatternsTests(TestCase):
urls = 'regressiontests.urlpatterns_reverse.no_urls' urls = 'regressiontests.urlpatterns_reverse.no_urls'
def assertRaisesErrorWithMessage(self, error, message, callable,
*args, **kwargs):
self.assertRaises(error, callable, *args, **kwargs)
try:
callable(*args, **kwargs)
except error, e:
self.assertEqual(message, str(e))
def test_no_urls_exception(self): def test_no_urls_exception(self):
""" """
RegexURLResolver should raise an exception when no urlpatterns exist. RegexURLResolver should raise an exception when no urlpatterns exist.
""" """
resolver = RegexURLResolver(r'^$', self.urls) resolver = RegexURLResolver(r'^$', self.urls)
self.assertRaisesErrorWithMessage(ImproperlyConfigured, self.assertRaisesMessage(ImproperlyConfigured,
"The included urlconf regressiontests.urlpatterns_reverse.no_urls "\ "The included urlconf regressiontests.urlpatterns_reverse.no_urls "\
"doesn't have any patterns in it", getattr, resolver, 'url_patterns') "doesn't have any patterns in it", getattr, resolver, 'url_patterns')

View File

@ -4,22 +4,12 @@ Tests for stuff in django.utils.datastructures.
import copy import copy
import pickle import pickle
import unittest
from django.test import SimpleTestCase
from django.utils.datastructures import * from django.utils.datastructures import *
class DatastructuresTestCase(unittest.TestCase): class SortedDictTests(SimpleTestCase):
def assertRaisesErrorWithMessage(self, error, message, callable,
*args, **kwargs):
self.assertRaises(error, callable, *args, **kwargs)
try:
callable(*args, **kwargs)
except error, e:
self.assertEqual(message, str(e))
class SortedDictTests(DatastructuresTestCase):
def setUp(self): def setUp(self):
self.d1 = SortedDict() self.d1 = SortedDict()
self.d1[7] = 'seven' self.d1[7] = 'seven'
@ -125,7 +115,7 @@ class SortedDictTests(DatastructuresTestCase):
self.assertEqual(self.d1, {}) self.assertEqual(self.d1, {})
self.assertEqual(self.d1.keyOrder, []) self.assertEqual(self.d1.keyOrder, [])
class MergeDictTests(DatastructuresTestCase): class MergeDictTests(SimpleTestCase):
def test_simple_mergedict(self): def test_simple_mergedict(self):
d1 = {'chris':'cool', 'camri':'cute', 'cotton':'adorable', d1 = {'chris':'cool', 'camri':'cute', 'cotton':'adorable',
@ -179,7 +169,7 @@ class MergeDictTests(DatastructuresTestCase):
('key2', ['value2', 'value3']), ('key2', ['value2', 'value3']),
('key4', ['value5', 'value6'])]) ('key4', ['value5', 'value6'])])
class MultiValueDictTests(DatastructuresTestCase): class MultiValueDictTests(SimpleTestCase):
def test_multivaluedict(self): def test_multivaluedict(self):
d = MultiValueDict({'name': ['Adrian', 'Simon'], d = MultiValueDict({'name': ['Adrian', 'Simon'],
@ -198,7 +188,7 @@ class MultiValueDictTests(DatastructuresTestCase):
# MultiValueDictKeyError: "Key 'lastname' not found in # MultiValueDictKeyError: "Key 'lastname' not found in
# <MultiValueDict: {'position': ['Developer'], # <MultiValueDict: {'position': ['Developer'],
# 'name': ['Adrian', 'Simon']}>" # 'name': ['Adrian', 'Simon']}>"
self.assertRaisesErrorWithMessage(MultiValueDictKeyError, self.assertRaisesMessage(MultiValueDictKeyError,
'"Key \'lastname\' not found in <MultiValueDict: {\'position\':'\ '"Key \'lastname\' not found in <MultiValueDict: {\'position\':'\
' [\'Developer\'], \'name\': [\'Adrian\', \'Simon\']}>"', ' [\'Developer\'], \'name\': [\'Adrian\', \'Simon\']}>"',
d.__getitem__, 'lastname') d.__getitem__, 'lastname')
@ -248,7 +238,7 @@ class MultiValueDictTests(DatastructuresTestCase):
self.assertEqual({}, MultiValueDict().dict()) self.assertEqual({}, MultiValueDict().dict())
class DotExpandedDictTests(DatastructuresTestCase): class DotExpandedDictTests(SimpleTestCase):
def test_dotexpandeddict(self): def test_dotexpandeddict(self):
@ -262,13 +252,13 @@ class DotExpandedDictTests(DatastructuresTestCase):
self.assertEqual(d['person']['2']['firstname'], ['Adrian']) self.assertEqual(d['person']['2']['firstname'], ['Adrian'])
class ImmutableListTests(DatastructuresTestCase): class ImmutableListTests(SimpleTestCase):
def test_sort(self): def test_sort(self):
d = ImmutableList(range(10)) d = ImmutableList(range(10))
# AttributeError: ImmutableList object is immutable. # AttributeError: ImmutableList object is immutable.
self.assertRaisesErrorWithMessage(AttributeError, self.assertRaisesMessage(AttributeError,
'ImmutableList object is immutable.', d.sort) 'ImmutableList object is immutable.', d.sort)
self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)') self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)')
@ -279,11 +269,11 @@ class ImmutableListTests(DatastructuresTestCase):
self.assertEqual(d[1], 1) self.assertEqual(d[1], 1)
# AttributeError: Object is immutable! # AttributeError: Object is immutable!
self.assertRaisesErrorWithMessage(AttributeError, self.assertRaisesMessage(AttributeError,
'Object is immutable!', d.__setitem__, 1, 'test') 'Object is immutable!', d.__setitem__, 1, 'test')
class DictWrapperTests(DatastructuresTestCase): class DictWrapperTests(SimpleTestCase):
def test_dictwrapper(self): def test_dictwrapper(self):
f = lambda x: "*%s" % x f = lambda x: "*%s" % x