Fixed #15838 -- Promoted assertFieldOutput to a general test utility. Thanks to Ramiro Morales for the patch.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16653 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Russell Keith-Magee 2011-08-23 02:32:37 +00:00
parent 46ef2983ba
commit 2664fa1896
47 changed files with 167 additions and 161 deletions

View File

@ -8,11 +8,14 @@ from xml.dom.minidom import parseString, Node
from django.conf import settings from django.conf import settings
from django.core import mail from django.core import mail
from django.core.exceptions import ValidationError
from django.core.management import call_command from django.core.management import call_command
from django.core.signals import request_started from django.core.signals import request_started
from django.core.urlresolvers import clear_url_caches from django.core.urlresolvers import clear_url_caches
from django.core.validators import EMPTY_VALUES
from django.db import (transaction, connection, connections, DEFAULT_DB_ALIAS, from django.db import (transaction, connection, connections, DEFAULT_DB_ALIAS,
reset_queries) reset_queries)
from django.forms.fields import CharField
from django.http import QueryDict from django.http import QueryDict
from django.test import _doctest as doctest from django.test import _doctest as doctest
from django.test.client import Client from django.test.client import Client
@ -271,6 +274,53 @@ class SimpleTestCase(ut2.TestCase):
return self.assertRaisesRegexp(expected_exception, return self.assertRaisesRegexp(expected_exception,
re.escape(expected_message), callable_obj, *args, **kwargs) re.escape(expected_message), callable_obj, *args, **kwargs)
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=u''):
"""
Asserts that a form field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in EMPTY_VALUES
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **dict(field_kwargs, required=False))
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [u'This field is required.']
for e in EMPTY_VALUES:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({'min_length':2, 'max_length':20})
self.assertTrue(isinstance(fieldclass(*field_args, **field_kwargs), fieldclass))
class TransactionTestCase(SimpleTestCase): 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.
@ -356,8 +406,8 @@ class TransactionTestCase(SimpleTestCase):
# be created with the wrong time). # be created with the wrong time).
# To make sure this doesn't happen, get a clean connection at the # To make sure this doesn't happen, get a clean connection at the
# start of every test. # start of every test.
for connection in connections.all(): for conn in connections.all():
connection.close() conn.close()
def _fixture_teardown(self): def _fixture_teardown(self):
pass pass
@ -552,9 +602,9 @@ class TransactionTestCase(SimpleTestCase):
def assertNumQueries(self, num, func=None, *args, **kwargs): def assertNumQueries(self, num, func=None, *args, **kwargs):
using = kwargs.pop("using", DEFAULT_DB_ALIAS) using = kwargs.pop("using", DEFAULT_DB_ALIAS)
connection = connections[using] conn = connections[using]
context = _AssertNumQueriesContext(self, num, connection) context = _AssertNumQueriesContext(self, num, conn)
if func is None: if func is None:
return context return context

View File

@ -1178,6 +1178,7 @@ basic functionality like:
* Saving and restoring the Python warning machinery state. * Saving and restoring the Python warning machinery state.
* Checking that a callable :meth:`raises a certain exeception <TestCase.assertRaisesMessage>`. * Checking that a callable :meth:`raises a certain exeception <TestCase.assertRaisesMessage>`.
* :meth:`Testing form field rendering <assertFieldOutput>`.
If you need any of the other more complex and heavyweight Django-specific If you need any of the other more complex and heavyweight Django-specific
features like: features like:
@ -1523,6 +1524,26 @@ your test suite.
failure. Similar to unittest's ``assertRaisesRegexp`` with the difference failure. Similar to unittest's ``assertRaisesRegexp`` with the difference
that ``expected_message`` isn't a regular expression. that ``expected_message`` isn't a regular expression.
.. method:: assertFieldOutput(self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value=u'')
Asserts that a form field behaves correctly with various inputs.
:param fieldclass: the class of the field to be tested.
:param valid: a dictionary mapping valid inputs to their expected cleaned
values.
:param invalid: a dictionary mapping invalid inputs to one or more raised
error messages.
:param field_args: the args passed to instantiate the field.
:param field_kwargs: the kwargs passed to instantiate the field.
:param empty_value: the expected clean output for inputs in ``EMPTY_VALUES``.
For example, the following code tests that an ``EmailField`` accepts
"a@a.com" as a valid email address, but rejects "aaa" with a reasonable
error message::
self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Enter a valid e-mail address.']})
.. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='') .. method:: TestCase.assertContains(response, text, count=None, status_code=200, msg_prefix='')
Asserts that a ``Response`` instance produced the given ``status_code`` and Asserts that a ``Response`` instance produced the given ``status_code`` and

View File

@ -1,11 +1 @@
from django.forms import EmailField #
from utils import LocalFlavorTestCase
class AssertFieldOutputTests(LocalFlavorTestCase):
def test_assert_field_output(self):
error_invalid = [u'Enter a valid e-mail address.']
self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid})
self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + [u'Another error']})
self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid})
self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Come on, gimme some well formatted data, dude.']})

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.ar.forms import (ARProvinceSelect, from django.contrib.localflavor.ar.forms import (ARProvinceSelect,
ARPostalCodeField, ARDNIField, ARCUITField) ARPostalCodeField, ARDNIField, ARCUITField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ARLocalFlavorTests(LocalFlavorTestCase): class ARLocalFlavorTests(SimpleTestCase):
def test_ARProvinceSelect(self): def test_ARProvinceSelect(self):
f = ARProvinceSelect() f = ARProvinceSelect()
out = u'''<select name="provincias"> out = u'''<select name="provincias">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.at.forms import (ATZipCodeField, ATStateSelect, from django.contrib.localflavor.at.forms import (ATZipCodeField, ATStateSelect,
ATSocialSecurityNumberField) ATSocialSecurityNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ATLocalFlavorTests(LocalFlavorTestCase): class ATLocalFlavorTests(SimpleTestCase):
def test_ATStateSelect(self): def test_ATStateSelect(self):
f = ATStateSelect() f = ATStateSelect()
out = u'''<select name="bundesland"> out = u'''<select name="bundesland">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.au.forms import (AUPostCodeField, from django.contrib.localflavor.au.forms import (AUPostCodeField,
AUPhoneNumberField, AUStateSelect) AUPhoneNumberField, AUStateSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class AULocalFlavorTests(LocalFlavorTestCase): class AULocalFlavorTests(SimpleTestCase):
def test_AUStateSelect(self): def test_AUStateSelect(self):
f = AUStateSelect() f = AUStateSelect()
out = u'''<select name="state"> out = u'''<select name="state">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.be.forms import (BEPostalCodeField, from django.contrib.localflavor.be.forms import (BEPostalCodeField,
BEPhoneNumberField, BERegionSelect, BEProvinceSelect) BEPhoneNumberField, BERegionSelect, BEProvinceSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class BELocalFlavorTests(LocalFlavorTestCase): class BELocalFlavorTests(SimpleTestCase):
def test_BEPostalCodeField(self): def test_BEPostalCodeField(self):
error_format = [u'Enter a valid postal code in the range and format 1XXX - 9XXX.'] error_format = [u'Enter a valid postal code in the range and format 1XXX - 9XXX.']
valid = { valid = {

View File

@ -2,10 +2,10 @@ from django.contrib.localflavor.br.forms import (BRZipCodeField,
BRCNPJField, BRCPFField, BRPhoneNumberField, BRStateSelect, BRCNPJField, BRCPFField, BRPhoneNumberField, BRStateSelect,
BRStateChoiceField) BRStateChoiceField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class BRLocalFlavorTests(LocalFlavorTestCase): class BRLocalFlavorTests(SimpleTestCase):
def test_BRZipCodeField(self): def test_BRZipCodeField(self):
error_format = [u'Enter a zip code in the format XXXXX-XXX.'] error_format = [u'Enter a zip code in the format XXXXX-XXX.']
valid = { valid = {

View File

@ -4,10 +4,10 @@ from django.contrib.localflavor.ca.forms import (CAPostalCodeField,
CAPhoneNumberField, CAProvinceField, CAProvinceSelect, CAPhoneNumberField, CAProvinceField, CAProvinceSelect,
CASocialInsuranceNumberField) CASocialInsuranceNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class CALocalFlavorTests(LocalFlavorTestCase): class CALocalFlavorTests(SimpleTestCase):
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings( warnings.filterwarnings(

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.ch.forms import (CHZipCodeField, from django.contrib.localflavor.ch.forms import (CHZipCodeField,
CHPhoneNumberField, CHIdentityCardNumberField, CHStateSelect) CHPhoneNumberField, CHIdentityCardNumberField, CHStateSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class CHLocalFlavorTests(LocalFlavorTestCase): class CHLocalFlavorTests(SimpleTestCase):
def test_CHStateSelect(self): def test_CHStateSelect(self):
f = CHStateSelect() f = CHStateSelect()
out = u'''<select name="state"> out = u'''<select name="state">

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.cl.forms import CLRutField, CLRegionSelect from django.contrib.localflavor.cl.forms import CLRutField, CLRegionSelect
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class CLLocalFlavorTests(LocalFlavorTestCase): class CLLocalFlavorTests(SimpleTestCase):
def test_CLRegionSelect(self): def test_CLRegionSelect(self):
f = CLRegionSelect() f = CLRegionSelect()
out = u'''<select name="foo"> out = u'''<select name="foo">

View File

@ -2,9 +2,9 @@
from django.contrib.localflavor.cn.forms import (CNProvinceSelect, from django.contrib.localflavor.cn.forms import (CNProvinceSelect,
CNPostCodeField, CNIDCardField, CNPhoneNumberField, CNCellNumberField) CNPostCodeField, CNIDCardField, CNPhoneNumberField, CNCellNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class CNLocalFlavorTests(LocalFlavorTestCase): class CNLocalFlavorTests(SimpleTestCase):
def test_CNProvinceSelect(self): def test_CNProvinceSelect(self):
f = CNProvinceSelect() f = CNProvinceSelect()
correct_output = u'''<select name="provinces"> correct_output = u'''<select name="provinces">

View File

@ -1,8 +1,8 @@
from django.contrib.localflavor.co.forms import CODepartmentSelect from django.contrib.localflavor.co.forms import CODepartmentSelect
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class COLocalFlavorTests(LocalFlavorTestCase): class COLocalFlavorTests(SimpleTestCase):
def test_CODepartmentSelect(self): def test_CODepartmentSelect(self):
d = CODepartmentSelect() d = CODepartmentSelect()
out = u"""<select name="department"> out = u"""<select name="department">

View File

@ -4,10 +4,10 @@ from django.contrib.localflavor.cz.forms import (CZPostalCodeField,
CZRegionSelect, CZBirthNumberField, CZICNumberField) CZRegionSelect, CZBirthNumberField, CZICNumberField)
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class CZLocalFlavorTests(LocalFlavorTestCase): class CZLocalFlavorTests(SimpleTestCase):
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings( warnings.filterwarnings(

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.de.forms import (DEZipCodeField, DEStateSelect, from django.contrib.localflavor.de.forms import (DEZipCodeField, DEStateSelect,
DEIdentityCardNumberField) DEIdentityCardNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class DELocalFlavorTests(LocalFlavorTestCase): class DELocalFlavorTests(SimpleTestCase):
def test_DEStateSelect(self): def test_DEStateSelect(self):
f = DEStateSelect() f = DEStateSelect()
out = u'''<select name="states"> out = u'''<select name="states">

View File

@ -1,8 +1,8 @@
from django.contrib.localflavor.ec.forms import ECProvinceSelect from django.contrib.localflavor.ec.forms import ECProvinceSelect
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ECLocalFlavorTests(LocalFlavorTestCase): class ECLocalFlavorTests(SimpleTestCase):
def test_ECProvinceSelect(self): def test_ECProvinceSelect(self):
p = ECProvinceSelect() p = ECProvinceSelect()
out = u"""<select name="province"> out = u"""<select name="province">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.es.forms import (ESPostalCodeField, ESPhoneNumberField, from django.contrib.localflavor.es.forms import (ESPostalCodeField, ESPhoneNumberField,
ESIdentityCardNumberField, ESCCCField, ESRegionSelect, ESProvinceSelect) ESIdentityCardNumberField, ESCCCField, ESRegionSelect, ESProvinceSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ESLocalFlavorTests(LocalFlavorTestCase): class ESLocalFlavorTests(SimpleTestCase):
def test_ESRegionSelect(self): def test_ESRegionSelect(self):
f = ESRegionSelect() f = ESRegionSelect()
out = u'''<select name="regions"> out = u'''<select name="regions">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.fi.forms import (FIZipCodeField, from django.contrib.localflavor.fi.forms import (FIZipCodeField,
FISocialSecurityNumber, FIMunicipalitySelect) FISocialSecurityNumber, FIMunicipalitySelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class FILocalFlavorTests(LocalFlavorTestCase): class FILocalFlavorTests(SimpleTestCase):
def test_FIMunicipalitySelect(self): def test_FIMunicipalitySelect(self):
f = FIMunicipalitySelect() f = FIMunicipalitySelect()
out = u'''<select name="municipalities"> out = u'''<select name="municipalities">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.fr.forms import (FRZipCodeField, from django.contrib.localflavor.fr.forms import (FRZipCodeField,
FRPhoneNumberField, FRDepartmentSelect) FRPhoneNumberField, FRDepartmentSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class FRLocalFlavorTests(LocalFlavorTestCase): class FRLocalFlavorTests(SimpleTestCase):
def test_FRZipCodeField(self): def test_FRZipCodeField(self):
error_format = [u'Enter a zip code in the format XXXXX.'] error_format = [u'Enter a zip code in the format XXXXX.']
valid = { valid = {

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.gb.forms import GBPostcodeField from django.contrib.localflavor.gb.forms import GBPostcodeField
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class GBLocalFlavorTests(LocalFlavorTestCase): class GBLocalFlavorTests(SimpleTestCase):
def test_GBPostcodeField(self): def test_GBPostcodeField(self):
error_invalid = [u'Enter a valid postcode.'] error_invalid = [u'Enter a valid postcode.']
valid = { valid = {

View File

@ -2,10 +2,10 @@ import datetime
from django.contrib.localflavor.generic.forms import DateField, DateTimeField from django.contrib.localflavor.generic.forms import DateField, DateTimeField
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class GenericLocalFlavorTests(LocalFlavorTestCase): class GenericLocalFlavorTests(SimpleTestCase):
def test_GenericDateField(self): def test_GenericDateField(self):
error_invalid = [u'Enter a valid date.'] error_invalid = [u'Enter a valid date.']
valid = { valid = {

View File

@ -4,9 +4,9 @@ from django.contrib.localflavor.hr.forms import (HRCountySelect,
HRLicensePlateField, HRPostalCodeField, HROIBField, HRJMBGField, HRLicensePlateField, HRPostalCodeField, HROIBField, HRJMBGField,
HRJMBAGField) HRJMBAGField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class HRLocalFlavorTests(LocalFlavorTestCase): class HRLocalFlavorTests(SimpleTestCase):
def test_HRCountySelect(self): def test_HRCountySelect(self):
f = HRCountySelect() f = HRCountySelect()
out = u'''<select name="county"> out = u'''<select name="county">

View File

@ -4,10 +4,10 @@ from django.contrib.localflavor.id.forms import (IDPhoneNumberField,
IDPostCodeField, IDNationalIdentityNumberField, IDLicensePlateField, IDPostCodeField, IDNationalIdentityNumberField, IDLicensePlateField,
IDProvinceSelect, IDLicensePlatePrefixSelect) IDProvinceSelect, IDLicensePlatePrefixSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class IDLocalFlavorTests(LocalFlavorTestCase): class IDLocalFlavorTests(SimpleTestCase):
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings( warnings.filterwarnings(

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.ie.forms import IECountySelect from django.contrib.localflavor.ie.forms import IECountySelect
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class IELocalFlavorTests(LocalFlavorTestCase): class IELocalFlavorTests(SimpleTestCase):
def test_IECountySelect(self): def test_IECountySelect(self):
f = IECountySelect() f = IECountySelect()
out = u'''<select name="counties"> out = u'''<select name="counties">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.il.forms import (ILPostalCodeField, from django.contrib.localflavor.il.forms import (ILPostalCodeField,
ILIDNumberField) ILIDNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ILLocalFlavorTests(LocalFlavorTestCase): class ILLocalFlavorTests(SimpleTestCase):
def test_ILPostalCodeField(self): def test_ILPostalCodeField(self):
error_format = [u'Enter a postal code in the format XXXXX'] error_format = [u'Enter a postal code in the format XXXXX']
valid = { valid = {

View File

@ -1,11 +1,11 @@
from django.contrib.localflavor.in_.forms import (INZipCodeField, from django.contrib.localflavor.in_.forms import (INZipCodeField,
INStateField, INStateSelect, INPhoneNumberField) INStateField, INStateSelect, INPhoneNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class INLocalFlavorTests(LocalFlavorTestCase): class INLocalFlavorTests(SimpleTestCase):
def test_INPhoneNumberField(self): def test_INPhoneNumberField(self):
error_format = [u'Phone numbers must be in 02X-8X or 03X-7X or 04X-6X format.'] error_format = [u'Phone numbers must be in 02X-8X or 03X-7X or 04X-6X format.']
valid = { valid = {

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.is_.forms import (ISIdNumberField, from django.contrib.localflavor.is_.forms import (ISIdNumberField,
ISPhoneNumberField, ISPostalCodeSelect) ISPhoneNumberField, ISPostalCodeSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ISLocalFlavorTests(LocalFlavorTestCase): class ISLocalFlavorTests(SimpleTestCase):
def test_ISPostalCodeSelect(self): def test_ISPostalCodeSelect(self):
f = ISPostalCodeSelect() f = ISPostalCodeSelect()
out = u'''<select name="foo"> out = u'''<select name="foo">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.it.forms import (ITZipCodeField, ITRegionSelect, from django.contrib.localflavor.it.forms import (ITZipCodeField, ITRegionSelect,
ITSocialSecurityNumberField, ITVatNumberField) ITSocialSecurityNumberField, ITVatNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ITLocalFlavorTests(LocalFlavorTestCase): class ITLocalFlavorTests(SimpleTestCase):
def test_ITRegionSelect(self): def test_ITRegionSelect(self):
f = ITRegionSelect() f = ITRegionSelect()
out = u'''<select name="regions"> out = u'''<select name="regions">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.jp.forms import (JPPostalCodeField, from django.contrib.localflavor.jp.forms import (JPPostalCodeField,
JPPrefectureSelect) JPPrefectureSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class JPLocalFlavorTests(LocalFlavorTestCase): class JPLocalFlavorTests(SimpleTestCase):
def test_JPPrefectureSelect(self): def test_JPPrefectureSelect(self):
f = JPPrefectureSelect() f = JPPrefectureSelect()
out = u'''<select name="prefecture"> out = u'''<select name="prefecture">

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.kw.forms import KWCivilIDNumberField from django.contrib.localflavor.kw.forms import KWCivilIDNumberField
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class KWLocalFlavorTests(LocalFlavorTestCase): class KWLocalFlavorTests(SimpleTestCase):
def test_KWCivilIDNumberField(self): def test_KWCivilIDNumberField(self):
error_invalid = [u'Enter a valid Kuwaiti Civil ID number'] error_invalid = [u'Enter a valid Kuwaiti Civil ID number']
valid = { valid = {

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.mk.forms import ( from django.contrib.localflavor.mk.forms import (
MKIdentityCardNumberField, MKMunicipalitySelect, UMCNField) MKIdentityCardNumberField, MKMunicipalitySelect, UMCNField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class MKLocalFlavorTests(LocalFlavorTestCase): class MKLocalFlavorTests(SimpleTestCase):
def test_MKIdentityCardNumberField(self): def test_MKIdentityCardNumberField(self):
error_invalid = [u'Identity card numbers must contain either 4 to 7 ' error_invalid = [u'Identity card numbers must contain either 4 to 7 '

View File

@ -2,10 +2,10 @@
from django.contrib.localflavor.mx.forms import (MXZipCodeField, MXRFCField, from django.contrib.localflavor.mx.forms import (MXZipCodeField, MXRFCField,
MXStateSelect, MXCURPField) MXStateSelect, MXCURPField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class MXLocalFlavorTests(LocalFlavorTestCase): class MXLocalFlavorTests(SimpleTestCase):
def test_MXStateSelect(self): def test_MXStateSelect(self):
f = MXStateSelect() f = MXStateSelect()
out = u'''<select name="state"> out = u'''<select name="state">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.nl.forms import (NLPhoneNumberField, from django.contrib.localflavor.nl.forms import (NLPhoneNumberField,
NLZipCodeField, NLSoFiNumberField, NLProvinceSelect) NLZipCodeField, NLSoFiNumberField, NLProvinceSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class NLLocalFlavorTests(LocalFlavorTestCase): class NLLocalFlavorTests(SimpleTestCase):
def test_NLProvinceSelect(self): def test_NLProvinceSelect(self):
f = NLProvinceSelect() f = NLProvinceSelect()
out = u'''<select name="provinces"> out = u'''<select name="provinces">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.pl.forms import (PLProvinceSelect, from django.contrib.localflavor.pl.forms import (PLProvinceSelect,
PLCountySelect, PLPostalCodeField, PLNIPField, PLPESELField, PLNationalIDCardNumberField, PLREGONField) PLCountySelect, PLPostalCodeField, PLNIPField, PLPESELField, PLNationalIDCardNumberField, PLREGONField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class PLLocalFlavorTests(LocalFlavorTestCase): class PLLocalFlavorTests(SimpleTestCase):
def test_PLProvinceSelect(self): def test_PLProvinceSelect(self):
f = PLProvinceSelect() f = PLProvinceSelect()
out = u'''<select name="voivodeships"> out = u'''<select name="voivodeships">

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.pt.forms import PTZipCodeField, PTPhoneNumberField from django.contrib.localflavor.pt.forms import PTZipCodeField, PTPhoneNumberField
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class PTLocalFlavorTests(LocalFlavorTestCase): class PTLocalFlavorTests(SimpleTestCase):
def test_PTZipCodeField(self): def test_PTZipCodeField(self):
error_format = [u'Enter a zip code in the format XXXX-XXX.'] error_format = [u'Enter a zip code in the format XXXX-XXX.']
valid = { valid = {

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.py.forms import (PyDepartmentSelect, from django.contrib.localflavor.py.forms import (PyDepartmentSelect,
PyNumberedDepartmentSelect) PyNumberedDepartmentSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class PYLocalFlavorTests(LocalFlavorTestCase): class PYLocalFlavorTests(SimpleTestCase):
def test_PyDepartmentSelect(self): def test_PyDepartmentSelect(self):
py = PyDepartmentSelect() py = PyDepartmentSelect()
out = u'''<select name="department"> out = u'''<select name="department">

View File

@ -3,10 +3,10 @@ from django.contrib.localflavor.ro.forms import (ROCIFField, ROCNPField,
ROCountyField, ROCountySelect, ROIBANField, ROPhoneNumberField, ROCountyField, ROCountySelect, ROIBANField, ROPhoneNumberField,
ROPostalCodeField) ROPostalCodeField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ROLocalFlavorTests(LocalFlavorTestCase): class ROLocalFlavorTests(SimpleTestCase):
def test_ROCountySelect(self): def test_ROCountySelect(self):
f = ROCountySelect() f = ROCountySelect()
out = u'''<select name="county"> out = u'''<select name="county">

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.ru.forms import * from django.contrib.localflavor.ru.forms import *
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class RULocalFlavorTests(LocalFlavorTestCase): class RULocalFlavorTests(SimpleTestCase):
def test_RUPassportNumberField(self): def test_RUPassportNumberField(self):
error = [u'Enter a passport number in the format XXXX XXXXXX.'] error = [u'Enter a passport number in the format XXXX XXXXXX.']

View File

@ -4,10 +4,10 @@ from django.contrib.localflavor.se.forms import (SECountySelect,
SEPostalCodeField) SEPostalCodeField)
import datetime import datetime
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class SELocalFlavorTests(LocalFlavorTestCase): class SELocalFlavorTests(SimpleTestCase):
def setUp(self): def setUp(self):
# Mocking datetime.date to make sure # Mocking datetime.date to make sure

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.sk.forms import (SKRegionSelect, from django.contrib.localflavor.sk.forms import (SKRegionSelect,
SKPostalCodeField, SKDistrictSelect) SKPostalCodeField, SKDistrictSelect)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class SKLocalFlavorTests(LocalFlavorTestCase): class SKLocalFlavorTests(SimpleTestCase):
def test_SKRegionSelect(self): def test_SKRegionSelect(self):
f = SKRegionSelect() f = SKRegionSelect()
out = u'''<select name="regions"> out = u'''<select name="regions">

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.us.forms import (USZipCodeField, from django.contrib.localflavor.us.forms import (USZipCodeField,
USPhoneNumberField, USStateField, USStateSelect, USSocialSecurityNumberField) USPhoneNumberField, USStateField, USStateSelect, USSocialSecurityNumberField)
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class USLocalFlavorTests(LocalFlavorTestCase): class USLocalFlavorTests(SimpleTestCase):
def test_USStateSelect(self): def test_USStateSelect(self):
f = USStateSelect() f = USStateSelect()
out = u'''<select name="state"> out = u'''<select name="state">

View File

@ -1,64 +0,0 @@
from __future__ import with_statement
from django.core.exceptions import ValidationError
from django.core.validators import EMPTY_VALUES
from django.forms.fields import CharField
from django.test.utils import get_warnings_state, restore_warnings_state
from django.utils.unittest import TestCase
class LocalFlavorTestCase(TestCase):
# NOTE: These are copied from the TestCase Django uses for tests which
# access the database
def save_warnings_state(self):
self._warnings_state = get_warnings_state()
def restore_warnings_state(self):
restore_warnings_state(self._warnings_state)
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
field_kwargs=None, empty_value=u''):
"""
Asserts that a field behaves correctly with various inputs.
Args:
fieldclass: the class of the field to be tested.
valid: a dictionary mapping valid inputs to their expected
cleaned values.
invalid: a dictionary mapping invalid inputs to one or more
raised error messages.
field_args: the args passed to instantiate the field
field_kwargs: the kwargs passed to instantiate the field
empty_value: the expected clean output for inputs in EMPTY_VALUES
"""
if field_args is None:
field_args = []
if field_kwargs is None:
field_kwargs = {}
required = fieldclass(*field_args, **field_kwargs)
optional = fieldclass(*field_args, **dict(field_kwargs, required=False))
# test valid inputs
for input, output in valid.items():
self.assertEqual(required.clean(input), output)
self.assertEqual(optional.clean(input), output)
# test invalid inputs
for input, errors in invalid.items():
with self.assertRaises(ValidationError) as context_manager:
required.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
with self.assertRaises(ValidationError) as context_manager:
optional.clean(input)
self.assertEqual(context_manager.exception.messages, errors)
# test required inputs
error_required = [u'This field is required.']
for e in EMPTY_VALUES:
with self.assertRaises(ValidationError) as context_manager:
required.clean(e)
self.assertEqual(context_manager.exception.messages, error_required)
self.assertEqual(optional.clean(e), empty_value)
# test that max_length and min_length are always accepted
if issubclass(fieldclass, CharField):
field_kwargs.update({'min_length':2, 'max_length':20})
self.assertTrue(isinstance(fieldclass(*field_args, **field_kwargs), fieldclass))

View File

@ -1,10 +1,10 @@
from django.contrib.localflavor.uy.forms import UYDepartamentSelect, UYCIField from django.contrib.localflavor.uy.forms import UYDepartamentSelect, UYCIField
from django.contrib.localflavor.uy.util import get_validation_digit from django.contrib.localflavor.uy.util import get_validation_digit
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class UYLocalFlavorTests(LocalFlavorTestCase): class UYLocalFlavorTests(SimpleTestCase):
def test_UYDepartmentSelect(self): def test_UYDepartmentSelect(self):
f = UYDepartamentSelect() f = UYDepartamentSelect()
out = u'''<select name="departamentos"> out = u'''<select name="departamentos">

View File

@ -1,9 +1,9 @@
from django.contrib.localflavor.za.forms import ZAIDField, ZAPostCodeField from django.contrib.localflavor.za.forms import ZAIDField, ZAPostCodeField
from utils import LocalFlavorTestCase from django.test import SimpleTestCase
class ZALocalFlavorTests(LocalFlavorTestCase): class ZALocalFlavorTests(SimpleTestCase):
def test_ZAIDField(self): def test_ZAIDField(self):
error_invalid = [u'Enter a valid South African ID number'] error_invalid = [u'Enter a valid South African ID number']
valid = { valid = {

View File

@ -1,4 +1,3 @@
from localflavor import AssertFieldOutputTests
from localflavor.ar import ARLocalFlavorTests from localflavor.ar import ARLocalFlavorTests
from localflavor.at import ATLocalFlavorTests from localflavor.at import ATLocalFlavorTests
from localflavor.au import AULocalFlavorTests from localflavor.au import AULocalFlavorTests

View File

@ -53,5 +53,4 @@ from regressiontests.forms.localflavortests import (
USLocalFlavorTests, USLocalFlavorTests,
UYLocalFlavorTests, UYLocalFlavorTests,
ZALocalFlavorTests, ZALocalFlavorTests,
AssertFieldOutputTests,
) )

View File

@ -1,5 +1,6 @@
from __future__ import with_statement from __future__ import with_statement
from django.forms import EmailField
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.utils.unittest import skip from django.utils.unittest import skip
@ -139,6 +140,16 @@ class AssertRaisesMsgTest(SimpleTestCase):
self.assertRaisesMessage(ValueError, "[.*x+]y?", func1) self.assertRaisesMessage(ValueError, "[.*x+]y?", func1)
class AssertFieldOutputTests(SimpleTestCase):
def test_assert_field_output(self):
error_invalid = [u'Enter a valid e-mail address.']
self.assertFieldOutput(EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid})
self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': error_invalid + [u'Another error']})
self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'Wrong output'}, {'aaa': error_invalid})
self.assertRaises(AssertionError, self.assertFieldOutput, EmailField, {'a@a.com': 'a@a.com'}, {'aaa': [u'Come on, gimme some well formatted data, dude.']})
__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