/tests/regressiontests/forms/localflavor/utils.py
Python | 51 lines | 45 code | 4 blank | 2 comment | 0 complexity | 79d26e8bd6204cb882b3cc160a833039 MD5 | raw file
Possible License(s): BSD-3-Clause
1from django.core.exceptions import ValidationError 2from django.core.validators import EMPTY_VALUES 3from django.test.utils import get_warnings_state, restore_warnings_state 4from django.utils.unittest import TestCase 5 6 7class LocalFlavorTestCase(TestCase): 8 # NOTE: These are copied from the TestCase Django uses for tests which 9 # access the database 10 def save_warnings_state(self): 11 self._warnings_state = get_warnings_state() 12 13 def restore_warnings_state(self): 14 restore_warnings_state(self._warnings_state) 15 16 def assertFieldOutput(self, fieldclass, valid, invalid, field_args=[], 17 field_kwargs={}, empty_value=u''): 18 """ 19 Asserts that a field behaves correctly with various inputs. 20 21 Args: 22 fieldclass: the class of the field to be tested. 23 valid: a dictionary mapping valid inputs to their expected 24 cleaned values. 25 invalid: a dictionary mapping invalid inputs to one or more 26 raised error messages. 27 field_args: the args passed to instantiate the field 28 field_kwargs: the kwargs passed to instantiate the field 29 empty_value: the expected clean output for inputs in EMPTY_VALUES 30 31 """ 32 required = fieldclass(*field_args, **field_kwargs) 33 optional = fieldclass(*field_args, **dict(field_kwargs, required=False)) 34 # test valid inputs 35 for input, output in valid.items(): 36 self.assertEqual(required.clean(input), output) 37 self.assertEqual(optional.clean(input), output) 38 # test invalid inputs 39 for input, errors in invalid.items(): 40 self.assertRaisesRegexp(ValidationError, unicode(errors), 41 required.clean, input 42 ) 43 self.assertRaisesRegexp(ValidationError, unicode(errors), 44 optional.clean, input 45 ) 46 # test required inputs 47 error_required = u'This field is required' 48 for e in EMPTY_VALUES: 49 self.assertRaisesRegexp(ValidationError, error_required, 50 required.clean, e) 51 self.assertEqual(optional.clean(e), empty_value)