'
+ )
# This one should wrap error groups in the customized way.
form2 = TestForm({'first_name': 'John'}, error_class=CustomErrorList)
diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py
index 6234f5c455..5e4b4269db 100644
--- a/tests/forms_tests/tests/test_fields.py
+++ b/tests/forms_tests/tests/test_fields.py
@@ -117,14 +117,18 @@ class FieldsTests(SimpleTestCase):
f = CharField(max_length=10, required=False)
self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '1234567890a')
+ msg = "'Ensure this value has at most 10 characters (it has 11).'"
+ with self.assertRaisesMessage(ValidationError, msg):
+ f.clean('1234567890a')
self.assertEqual(f.max_length, 10)
self.assertEqual(f.min_length, None)
def test_charfield_4(self):
f = CharField(min_length=10, required=False)
self.assertEqual('', f.clean(''))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345')
+ msg = "'Ensure this value has at least 10 characters (it has 5).'"
+ with self.assertRaisesMessage(ValidationError, msg):
+ f.clean('12345')
self.assertEqual('1234567890', f.clean('1234567890'))
self.assertEqual('1234567890a', f.clean('1234567890a'))
self.assertEqual(f.max_length, None)
@@ -133,7 +137,9 @@ class FieldsTests(SimpleTestCase):
def test_charfield_5(self):
f = CharField(min_length=10, required=True)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 5).'", f.clean, '12345')
+ msg = "'Ensure this value has at least 10 characters (it has 5).'"
+ with self.assertRaisesMessage(ValidationError, msg):
+ f.clean('12345')
self.assertEqual('1234567890', f.clean('1234567890'))
self.assertEqual('1234567890a', f.clean('1234567890a'))
self.assertEqual(f.max_length, None)
@@ -327,7 +333,10 @@ class FieldsTests(SimpleTestCase):
f = FloatField(max_value=1.5, min_value=0.5)
self.assertWidgetRendersTo(f, '')
self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6')
- self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4')
+ self.assertRaisesMessage(
+ ValidationError, "'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(0.5, f.clean('0.5'))
self.assertEqual(f.max_value, 1.5)
@@ -377,16 +386,34 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 1.0'), Decimal("1.0"))
self.assertEqual(f.clean(' 1.0 '), Decimal("1.0"))
self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '1.0a')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '123.45')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '1.234')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 digits before the decimal point.'", f.clean, '123.4')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 4 digits in total.'",
+ f.clean, '123.45'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 2 decimal places.'",
+ f.clean, '1.234'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'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.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-123.45')
+ self.assertRaisesMessage(
+ ValidationError, "'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('-00.12'), Decimal("-0.12"))
self.assertEqual(f.clean('-000.12'), Decimal("-0.12"))
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '-000.123')
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 4 digits in total.'", f.clean, '-000.12345')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 2 decimal places.'",
+ f.clean, '-000.123'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 4 digits in total.'",
+ f.clean, '-000.12345'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a number.'", f.clean, '--0.12')
self.assertEqual(f.max_digits, 4)
self.assertEqual(f.decimal_places, 2)
@@ -407,7 +434,10 @@ class FieldsTests(SimpleTestCase):
f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5'))
self.assertWidgetRendersTo(f, '')
self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'", f.clean, '1.6')
- self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'", f.clean, '0.4')
+ self.assertRaisesMessage(
+ ValidationError, "'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('0.5'), Decimal("0.5"))
self.assertEqual(f.clean('.5'), Decimal("0.5"))
@@ -419,7 +449,10 @@ class FieldsTests(SimpleTestCase):
def test_decimalfield_4(self):
f = DecimalField(decimal_places=2)
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 2 decimal places.'", f.clean, '0.00000001')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 2 decimal places.'",
+ f.clean, '0.00000001'
+ )
def test_decimalfield_5(self):
f = DecimalField(max_digits=3)
@@ -429,13 +462,19 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean('0000000.100'), Decimal("0.100"))
# Only leading whole zeros "collapse" to one digit.
self.assertEqual(f.clean('000000.02'), Decimal('0.02'))
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 3 digits in total.'", f.clean, '000000.0002')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 3 digits in total.'",
+ f.clean, '000000.0002'
+ )
self.assertEqual(f.clean('.002'), Decimal("0.002"))
def test_decimalfield_6(self):
f = DecimalField(max_digits=2, decimal_places=2)
self.assertEqual(f.clean('.01'), Decimal(".01"))
- self.assertRaisesMessage(ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'", f.clean, '1.1')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure that there are no more than 0 digits before the decimal point.'",
+ f.clean, '1.1'
+ )
def test_decimalfield_scientific(self):
f = DecimalField(max_digits=2, decimal_places=2)
@@ -588,8 +627,14 @@ class FieldsTests(SimpleTestCase):
f = DateTimeField()
self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25)))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30)))
- 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),
+ 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, 45, 200), f.clean('2006-10-25 14:30:45.000200'))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45, 200), f.clean('2006-10-25 14:30:45.0002'))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30, 45), f.clean('2006-10-25 14:30:45'))
@@ -613,8 +658,14 @@ class FieldsTests(SimpleTestCase):
f = DateTimeField(input_formats=['%Y %m %d %I:%M %p'])
self.assertEqual(datetime.datetime(2006, 10, 25, 0, 0), f.clean(datetime.date(2006, 10, 25)))
self.assertEqual(datetime.datetime(2006, 10, 25, 14, 30), f.clean(datetime.datetime(2006, 10, 25, 14, 30)))
- 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),
+ 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), f.clean('2006 10 25 2:30 PM'))
self.assertRaisesMessage(ValidationError, "'Enter a valid date/time.'", f.clean, '2006-10-25 14:30:45')
@@ -717,11 +768,22 @@ class FieldsTests(SimpleTestCase):
def test_regexfield_5(self):
f = RegexField('^[0-9]+$', min_length=5, max_length=10)
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'", f.clean, '123')
- six.assertRaisesRegex(self, ValidationError, "'Ensure this value has at least 5 characters \(it has 3\)\.', u?'Enter a valid value\.'", f.clean, 'abc')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at least 5 characters (it has 3).'",
+ f.clean, '123'
+ )
+ six.assertRaisesRegex(
+ self, ValidationError,
+ "'Ensure this value has at least 5 characters \(it has 3\)\.',"
+ " u?'Enter a valid value\.'",
+ f.clean, 'abc'
+ )
self.assertEqual('12345', f.clean('12345'))
self.assertEqual('1234567890', f.clean('1234567890'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 10 characters (it has 11).'", f.clean, '12345678901')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 10 characters (it has 11).'",
+ f.clean, '12345678901'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid value.'", f.clean, '12345a')
def test_regexfield_6(self):
@@ -769,9 +831,15 @@ class FieldsTests(SimpleTestCase):
def test_emailfield_min_max_length(self):
f = EmailField(min_length=10, max_length=15)
self.assertWidgetRendersTo(f, '')
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 10 characters (it has 9).'", f.clean, 'a@foo.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at least 10 characters (it has 9).'",
+ f.clean, 'a@foo.com'
+ )
self.assertEqual('alf@foo.com', f.clean('alf@foo.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 15 characters (it has 20).'", f.clean, 'alf123456788@foo.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 15 characters (it has 20).'",
+ f.clean, 'alf123456788@foo.com'
+ )
# FileField ##################################################################
@@ -783,19 +851,43 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None, '')
self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
- self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''))
- self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, SimpleUploadedFile('', b''), '')
+ self.assertRaisesMessage(
+ ValidationError, "'No file was submitted. Check the encoding type on the form.'",
+ f.clean, SimpleUploadedFile('', b'')
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'No file was submitted. Check the encoding type on the form.'",
+ f.clean, SimpleUploadedFile('', b''), ''
+ )
self.assertEqual('files/test3.pdf', f.clean(None, 'files/test3.pdf'))
- self.assertRaisesMessage(ValidationError, "'No file was submitted. Check the encoding type on the form.'", f.clean, 'some content that is not a file')
- self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', None))
- self.assertRaisesMessage(ValidationError, "'The submitted file is empty.'", f.clean, SimpleUploadedFile('name', b''))
+ self.assertRaisesMessage(
+ ValidationError, "'No file was submitted. Check the encoding type on the form.'",
+ f.clean, 'some content that is not a file'
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'The submitted file is empty.'",
+ f.clean, SimpleUploadedFile('name', None)
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'The submitted file is empty.'",
+ f.clean, SimpleUploadedFile('name', b'')
+ )
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'))))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8')))))
- self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf')))
+ self.assertIsInstance(
+ f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))),
+ SimpleUploadedFile
+ )
+ self.assertIsInstance(
+ f.clean(SimpleUploadedFile('name', b'Some File Content'), 'files/test4.pdf'),
+ SimpleUploadedFile
+ )
def test_filefield_2(self):
f = FileField(max_length=5)
- self.assertRaisesMessage(ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'", f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world'))
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this filename has at most 5 characters (it has 18).'",
+ f.clean, SimpleUploadedFile('test_maxlength.txt', b'hello world')
+ )
self.assertEqual('files/test1.pdf', f.clean('', 'files/test1.pdf'))
self.assertEqual('files/test2.pdf', f.clean(None, 'files/test2.pdf'))
self.assertEqual(SimpleUploadedFile, type(f.clean(SimpleUploadedFile('name', b'Some File Content'))))
@@ -897,8 +989,14 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.alid-.com')
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://inv-.-alid.com')
self.assertEqual('http://valid-----hyphens.com', f.clean('http://valid-----hyphens.com'))
- self.assertEqual('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('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(
+ '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(
+ 'http://www.example.com/s/http://code.djangoproject.com/ticket/13804',
+ f.clean('www.example.com/s/http://code.djangoproject.com/ticket/13804')
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, '[a')
self.assertRaisesMessage(ValidationError, "'Enter a valid URL.'", f.clean, 'http://[a')
@@ -926,9 +1024,15 @@ class FieldsTests(SimpleTestCase):
def test_urlfield_5(self):
f = URLField(min_length=15, max_length=20)
self.assertWidgetRendersTo(f, '')
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 15 characters (it has 12).'", f.clean, 'http://f.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at least 15 characters (it has 12).'",
+ f.clean, 'http://f.com'
+ )
self.assertEqual('http://example.com', f.clean('http://example.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 37).'", f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 20 characters (it has 37).'",
+ f.clean, 'http://abcdefghijklmnopqrstuvwxyz.com'
+ )
def test_urlfield_6(self):
f = URLField(required=False)
@@ -1033,7 +1137,10 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
self.assertEqual('1', f.clean(1))
self.assertEqual('1', f.clean('1'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, '3'
+ )
def test_choicefield_2(self):
f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
@@ -1041,22 +1148,36 @@ class FieldsTests(SimpleTestCase):
self.assertEqual('', f.clean(None))
self.assertEqual('1', f.clean(1))
self.assertEqual('1', f.clean('1'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, '3')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, '3'
+ )
def test_choicefield_3(self):
f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
self.assertEqual('J', f.clean('J'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. John is not one of the available choices.'",
+ f.clean, 'John'
+ )
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'),
+ ]
+ )
self.assertEqual('1', f.clean(1))
self.assertEqual('1', f.clean('1'))
self.assertEqual('3', f.clean(3))
self.assertEqual('3', f.clean('3'))
self.assertEqual('5', f.clean(5))
self.assertEqual('5', f.clean('5'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, '6')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 6 is not one of the available choices.'",
+ f.clean, '6'
+ )
def test_choicefield_callable(self):
choices = lambda: [('J', 'John'), ('P', 'Paul')]
@@ -1093,7 +1214,10 @@ class FieldsTests(SimpleTestCase):
def test_typedchoicefield_1(self):
f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual(1, f.clean('1'))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, '2')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 2 is not one of the available choices.'",
+ f.clean, '2'
+ )
def test_typedchoicefield_2(self):
# Different coercion, same validation.
@@ -1109,7 +1233,10 @@ class FieldsTests(SimpleTestCase):
# 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!
f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, 'B')
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. B is not one of the available choices.'",
+ f.clean, 'B'
+ )
# Required fields require values
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
@@ -1140,11 +1267,14 @@ class FieldsTests(SimpleTestCase):
f = TypedChoiceField(choices=[(1, "1"), (2, "2")], coerce=coerce_func, required=True)
self.assertEqual(Decimal('1.2'), f.clean('2'))
- self.assertRaisesMessage(ValidationError,
- "'This field is required.'", f.clean, '')
- self.assertRaisesMessage(ValidationError,
- "'Select a valid choice. 3 is not one of the available choices.'",
- f.clean, '3')
+ self.assertRaisesMessage(
+ ValidationError, "'This field is required.'",
+ f.clean, ''
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, '3'
+ )
# NullBooleanField ############################################################
@@ -1168,7 +1298,11 @@ class FieldsTests(SimpleTestCase):
hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True)
hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)
f = HiddenNullBooleanForm()
- self.assertHTMLEqual('', str(f))
+ self.assertHTMLEqual(
+ ''
+ '',
+ str(f)
+ )
def test_nullbooleanfield_3(self):
class HiddenNullBooleanForm(Form):
@@ -1218,7 +1352,10 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ())
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, ['3']
+ )
def test_multiplechoicefield_2(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
@@ -1232,18 +1369,29 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
self.assertEqual([], f.clean([]))
self.assertEqual([], f.clean(()))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 3 is not one of the available choices.'",
+ f.clean, ['3']
+ )
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')]
+ )
self.assertEqual(['1'], f.clean([1]))
self.assertEqual(['1'], f.clean(['1']))
self.assertEqual(['1', '5'], f.clean([1, 5]))
self.assertEqual(['1', '5'], f.clean([1, '5']))
self.assertEqual(['1', '5'], f.clean(['1', 5]))
self.assertEqual(['1', '5'], f.clean(['1', '5']))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6'])
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1', '6'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 6 is not one of the available choices.'",
+ f.clean, ['6']
+ )
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 6 is not one of the available choices.'",
+ f.clean, ['1', '6']
+ )
def test_multiplechoicefield_changed(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')])
@@ -1262,7 +1410,10 @@ class FieldsTests(SimpleTestCase):
def test_typedmultiplechoicefield_1(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1], f.clean(['1']))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['2'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 2 is not one of the available choices.'",
+ f.clean, ['2']
+ )
def test_typedmultiplechoicefield_2(self):
# Different coercion, same validation.
@@ -1277,13 +1428,19 @@ class FieldsTests(SimpleTestCase):
def test_typedmultiplechoicefield_4(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1, -1], f.clean(['1', '-1']))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1', '2'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. 2 is not one of the available choices.'",
+ f.clean, ['1', '2']
+ )
def test_typedmultiplechoicefield_5(self):
# 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!
f = TypedMultipleChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. B is not one of the available choices.'", f.clean, ['B'])
+ self.assertRaisesMessage(
+ ValidationError, "'Select a valid choice. B is not one of the available choices.'",
+ f.clean, ['B']
+ )
# Required fields require values
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
@@ -1324,7 +1481,10 @@ class FieldsTests(SimpleTestCase):
def test_combofield_1(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()])
self.assertEqual('test@example.com', f.clean('test@example.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 20 characters (it has 28).'",
+ f.clean, 'longemailaddress@example.com'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
@@ -1332,7 +1492,10 @@ class FieldsTests(SimpleTestCase):
def test_combofield_2(self):
f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False)
self.assertEqual('test@example.com', f.clean('test@example.com'))
- self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'", f.clean, 'longemailaddress@example.com')
+ self.assertRaisesMessage(
+ ValidationError, "'Ensure this value has at most 20 characters (it has 28).'",
+ f.clean, 'longemailaddress@example.com'
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'", f.clean, 'not an email')
self.assertEqual('', f.clean(''))
self.assertEqual('', f.clean(None))
@@ -1362,7 +1525,10 @@ class FieldsTests(SimpleTestCase):
for exp, got in zip(expected, fix_os_paths(f.choices)):
self.assertEqual(exp[1], got[1])
self.assertTrue(got[0].endswith(exp[0]))
- self.assertRaisesMessage(ValidationError, "'Select a valid choice. fields.py is not one of the available choices.'", f.clean, 'fields.py')
+ self.assertRaisesMessage(
+ ValidationError, "'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')
def test_filepathfield_3(self):
@@ -1437,24 +1603,36 @@ class FieldsTests(SimpleTestCase):
from django.forms.widgets import SplitDateTimeWidget
f = SplitDateTimeField()
self.assertIsInstance(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.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
- six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
+ six.assertRaisesRegex(
+ self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'",
+ f.clean, ['hello', 'there']
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
def test_splitdatetimefield_2(self):
f = SplitDateTimeField(required=False)
- 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.assertEqual(datetime.datetime(2006, 1, 10, 7, 30), f.clean(['2006-01-10', '07:30']))
self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean(''))
self.assertIsNone(f.clean(['']))
self.assertIsNone(f.clean(['', '']))
self.assertRaisesMessage(ValidationError, "'Enter a list of values.'", f.clean, 'hello')
- six.assertRaisesRegex(self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'", f.clean, ['hello', 'there'])
+ six.assertRaisesRegex(
+ self, ValidationError, "'Enter a valid date\.', u?'Enter a valid time\.'",
+ f.clean, ['hello', 'there']
+ )
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', 'there'])
self.assertRaisesMessage(ValidationError, "'Enter a valid date.'", f.clean, ['hello', '07:30'])
self.assertRaisesMessage(ValidationError, "'Enter a valid time.'", f.clean, ['2006-01-10', ''])
@@ -1489,7 +1667,10 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4')
- self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertRaisesMessage(
+ ValidationError, "'This is not a valid IPv6 address.'",
+ f.clean, 'foo::223:6cff:fe8a:2e8a'
+ )
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2')
@@ -1518,7 +1699,10 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4')
- self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertRaisesMessage(
+ ValidationError, "'This is not a valid IPv6 address.'",
+ f.clean, 'foo::223:6cff:fe8a:2e8a'
+ )
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2')
@@ -1535,7 +1719,10 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(f.clean(' 2a02::223:6cff:fe8a:2e8a '), '2a02::223:6cff:fe8a:2e8a')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '12345:2:3:4')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3::4')
- self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, 'foo::223:6cff:fe8a:2e8a')
+ self.assertRaisesMessage(
+ ValidationError, "'This is not a valid IPv6 address.'",
+ f.clean, 'foo::223:6cff:fe8a:2e8a'
+ )
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1::2:3:4:5:6:7:8')
self.assertRaisesMessage(ValidationError, "'This is not a valid IPv6 address.'", f.clean, '1:2')
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
index d8cdabae2d..ac96d775a2 100644
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -58,9 +58,18 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(p.cleaned_data["first_name"], 'John')
self.assertEqual(p.cleaned_data["last_name"], 'Lennon')
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
- self.assertHTMLEqual(str(p['first_name']), '')
- self.assertHTMLEqual(str(p['last_name']), '')
- self.assertHTMLEqual(str(p['birthday']), '')
+ self.assertHTMLEqual(
+ str(p['first_name']),
+ ''
+ )
+ self.assertHTMLEqual(
+ str(p['last_name']),
+ ''
+ )
+ self.assertHTMLEqual(
+ str(p['birthday']),
+ ''
+ )
nonexistenterror = "Key u?'nonexistentfield' not found in 'Person'"
with six.assertRaisesRegex(self, KeyError, nonexistenterror):
@@ -72,9 +81,12 @@ class FormsTestCase(SimpleTestCase):
for boundfield in p:
form_output.append(str(boundfield))
- self.assertHTMLEqual('\n'.join(form_output), """
+ self.assertHTMLEqual(
+ '\n'.join(form_output),
+ """
-""")
+"""
+ )
form_output = []
@@ -86,9 +98,15 @@ class FormsTestCase(SimpleTestCase):
['Last name', 'Lennon'],
['Birthday', '1940-10-9']
])
- self.assertHTMLEqual(str(p), """
-
-
""")
+ self.assertHTMLEqual(
+ str(p),
+ """
+
+
+
+
+
"""
+ )
def test_empty_dict(self):
# Empty dictionaries are valid, too.
@@ -99,21 +117,54 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(p.errors['birthday'], ['This field is required.'])
self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {})
- self.assertHTMLEqual(str(p), """
"""
+ )
def test_unbound_form(self):
# If you don't pass any values to the Form's __init__(), or if you pass None,
@@ -128,34 +179,96 @@ class FormsTestCase(SimpleTestCase):
self.fail('Attempts to access cleaned_data when validation fails should fail.')
except AttributeError:
pass
- self.assertHTMLEqual(str(p), """
'
+ )
p = Person({'last_name': 'Lennon'})
self.assertEqual(p.errors['first_name'], ['This field is required.'])
self.assertEqual(p.errors['birthday'], ['This field is required.'])
self.assertFalse(p.is_valid())
- self.assertDictEqual(p.errors, {'birthday': ['This field is required.'], 'first_name': ['This field is required.']})
+ self.assertDictEqual(
+ p.errors,
+ {'birthday': ['This field is required.'], 'first_name': ['This field is required.']}
+ )
self.assertEqual(p.cleaned_data, {'last_name': 'Lennon'})
self.assertEqual(p['first_name'].errors, ['This field is required.'])
- self.assertHTMLEqual(p['first_name'].errors.as_ul(), '
'
+ )
self.assertEqual(p['first_name'].errors.as_text(), '* This field is required.')
p = Person()
@@ -168,7 +281,13 @@ class FormsTestCase(SimpleTestCase):
# Form, even if you pass extra data when you define the Form. In this
# example, we pass a bunch of extra fields to the form constructor,
# but cleaned_data contains only the form's fields.
- data = {'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9', 'extra1': 'hello', 'extra2': 'hello'}
+ data = {
+ 'first_name': 'John',
+ 'last_name': 'Lennon',
+ 'birthday': '1940-10-9',
+ 'extra1': 'hello',
+ 'extra2': 'hello',
+ }
p = Person(data)
self.assertTrue(p.is_valid())
self.assertEqual(p.cleaned_data['first_name'], 'John')
@@ -212,47 +331,84 @@ class FormsTestCase(SimpleTestCase):
# into which the field's name will be inserted. It will also put a
""")
+"""
+ )
# Test iterating on individual radios in a template
t = Template('{% for radio in form.language %}
"""
+ )
def test_multiple_choice_list_data(self):
# Data for a MultipleChoiceField should be a list. QueryDict and
# MultiValueDict conveniently work with this.
class SongForm(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=CheckboxSelectMultiple,
+ )
data = {'name': 'Yesterday', 'composers': ['J', 'P']}
f = SongForm(data)
@@ -619,16 +827,26 @@ class FormsTestCase(SimpleTestCase):
def test_multiple_hidden(self):
class SongForm(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=CheckboxSelectMultiple)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=CheckboxSelectMultiple,
+ )
# The MultipleHiddenInput widget renders multiple values as hidden fields.
class SongFormHidden(Form):
name = CharField()
- composers = MultipleChoiceField(choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')], widget=MultipleHiddenInput)
+ composers = MultipleChoiceField(
+ choices=[('J', 'John Lennon'), ('P', 'Paul McCartney')],
+ widget=MultipleHiddenInput,
+ )
f = SongFormHidden(MultiValueDict(dict(name=['Yesterday'], composers=['J', 'P'])), auto_id=False)
- self.assertHTMLEqual(f.as_ul(), """
Name:
-
""")
+ self.assertHTMLEqual(
+ f.as_ul(),
+ """
Name:
+
+
"""
+ )
# When using CheckboxSelectMultiple, the framework expects a list of input and
# returns a list of input.
@@ -653,17 +871,39 @@ class FormsTestCase(SimpleTestCase):
raise ValidationError("Something's wrong with '%s'" % self.cleaned_data['special_name'])
def clean_special_safe_name(self):
- raise ValidationError(mark_safe("'%s' is a safe string" % self.cleaned_data['special_safe_name']))
+ raise ValidationError(
+ mark_safe("'%s' is a safe string" % self.cleaned_data['special_safe_name'])
+ )
- f = EscapingForm({'special_name': "Nothing to escape", 'special_safe_name': "Nothing to escape"}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), """
<em>Special</em> Field:
Something's wrong with 'Nothing to escape'
-
Special Field:
'Nothing to escape' is a safe string
""")
+ f = EscapingForm({
+ 'special_name':
+ "Nothing to escape",
+ 'special_safe_name': "Nothing to escape",
+ }, auto_id=False)
+ self.assertHTMLEqual(
+ f.as_table(),
+ """
<em>Special</em> Field:
+
Something's wrong with 'Nothing to escape'
+
+
Special Field:
+
'Nothing to escape' is a safe string
+
"""
+ )
f = EscapingForm({
'special_name': "Should escape < & > and ",
'special_safe_name': "Do not escape"
}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), """
<em>Special</em> Field:
Something's wrong with 'Should escape < & > and <script>alert('xss')</script>'
Something's wrong with 'Should escape < & > and
+<script>alert('xss')</script>'
+
+
Special Field:
+
'Do not escape' is a safe string
+
"""
+ )
def test_validating_multiple_fields(self):
# There are a couple of ways to do multiple-field validation. If you want the
@@ -679,7 +919,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput)
def clean_password2(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data['password2']
@@ -717,7 +958,8 @@ class FormsTestCase(SimpleTestCase):
def clean(self):
# Test raising a ValidationError as NON_FIELD_ERRORS.
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
# Test raising ValidationError that targets multiple fields.
@@ -743,23 +985,38 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(f.errors, {})
f = UserRegistration({}, auto_id=False)
- self.assertHTMLEqual(f.as_table(), """
"""
+ )
self.assertEqual(f.errors['username'], ['This field is required.'])
self.assertEqual(f.errors['password1'], ['This field is required.'])
self.assertEqual(f.errors['password2'], ['This field is required.'])
f = UserRegistration({'username': 'adrian', 'password1': 'foo', 'password2': 'bar'}, auto_id=False)
self.assertEqual(f.errors['__all__'], ['Please make sure your passwords match.'])
- self.assertHTMLEqual(f.as_table(), """
"""
+ )
# Instances of a dynamic Form do not persist fields from one Form instance to
# the next.
@@ -887,12 +1155,18 @@ class FormsTestCase(SimpleTestCase):
field_list = [('field1', CharField()), ('field2', CharField())]
my_form = MyForm(field_list=field_list)
- self.assertHTMLEqual(my_form.as_table(), """
"""
+ )
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
p = Person(auto_id='id_%s')
- self.assertHTMLEqual(p.as_table(), """
"""
+ )
# If a field with a HiddenInput has errors, the as_table() and as_ul() output
# will include the error message(s) with the text "(Hidden field [fieldname]) "
# prepended. This message is displayed at the top of the output, regardless of
# its field's order in the form.
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': '1940-10-9'}, auto_id=False)
- self.assertHTMLEqual(p.as_table(), """
(Hidden field hidden_text) This field is required.
+ self.assertHTMLEqual(
+ p.as_table(),
+ """
+
(Hidden field hidden_text) This field is required.
First name:
Last name:
-
Birthday:
""")
- self.assertHTMLEqual(p.as_ul(), """
(Hidden field hidden_text) This field is required.
(Hidden field hidden_text) This field is required.
First name:
Last name:
-
Birthday:
""")
- self.assertHTMLEqual(p.as_p(), """
(Hidden field hidden_text) This field is required.
+
Birthday:
+
"""
+ )
+ self.assertHTMLEqual(
+ p.as_p(),
+ """
(Hidden field hidden_text) This field is required.
First name:
Last name:
-
Birthday:
""")
+
Birthday:
"""
+ )
# A corner case: It's possible for a form to have only HiddenInputs.
class TestForm(Form):
@@ -1145,7 +1471,8 @@ class FormsTestCase(SimpleTestCase):
address = CharField() # no max_length defined here
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username:
+ self.assertHTMLEqual(p.as_ul(),
+ """
Username:
Password:
Realname:
Address:
""")
@@ -1158,7 +1485,8 @@ class FormsTestCase(SimpleTestCase):
password = CharField(max_length=10, widget=PasswordInput)
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username:
+ self.assertHTMLEqual(p.as_ul(),
+ """
Username:
Password:
""")
def test_specifying_labels(self):
@@ -1171,7 +1499,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)')
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Your username:
+ self.assertHTMLEqual(p.as_ul(),
+ """
Your username:
Password1:
Contraseña (de nuevo):
""")
@@ -1184,16 +1513,22 @@ class FormsTestCase(SimpleTestCase):
q4 = CharField(label='Answer this question!')
q5 = CharField(label='The last question. Period.')
- self.assertHTMLEqual(Questions(auto_id=False).as_p(), """
"""
+ )
# If a label is set to the empty string for a field, that field won't get a label.
class UserRegistration(Form):
@@ -1204,8 +1539,11 @@ class FormsTestCase(SimpleTestCase):
self.assertHTMLEqual(p.as_ul(), """
Password:
""")
p = UserRegistration(auto_id='id_%s')
- self.assertHTMLEqual(p.as_ul(), """
-
Password:
""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
+
Password:
"""
+ )
# If label is None, Django will auto-create the label from the field name. This
# is default behavior.
@@ -1214,11 +1552,16 @@ class FormsTestCase(SimpleTestCase):
password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username:
+ self.assertHTMLEqual(p.as_ul(),
+ """
Username:
Password:
""")
p = UserRegistration(auto_id='id_%s')
- self.assertHTMLEqual(p.as_ul(), """
Username:
-
Password:
""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
Username:
+
+
Password:
"""
+ )
def test_label_suffix(self):
# You can specify the 'label_suffix' argument to a Form class to modify the
@@ -1247,7 +1590,12 @@ class FormsTestCase(SimpleTestCase):
Secret answer =
""")
f = FavoriteForm(auto_id=False, label_suffix='\u2192')
- self.assertHTMLEqual(f.as_ul(), '
Favorite color?
\n
Favorite animal\u2192
\n
Secret answer =
')
+ self.assertHTMLEqual(
+ f.as_ul(),
+ '
Favorite color?
\n'
+ '
Favorite animal\u2192
\n'
+ '
Secret answer =
'
+ )
def test_initial_data(self):
# You can specify initial data for a field by using the 'initial' argument to a
@@ -1261,19 +1609,36 @@ class FormsTestCase(SimpleTestCase):
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username:
-
Password:
""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
Username:
+
Password:
"""
+ )
# Here, we're submitting data, so the initial value will *not* be displayed.
p = UserRegistration({}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
"""
+ )
# An 'initial' value is *not* used as a fallback if data is not provided. In this
# example, we don't provide a value for 'username', and the form raises a
@@ -1294,22 +1659,41 @@ class FormsTestCase(SimpleTestCase):
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={'username': 'django'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
"""
+ )
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={'username': 'django'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
"""
+ )
# A dynamic 'initial' value is *not* used as a fallback if data is not provided.
# In this example, we don't provide a value for 'username', and the form raises a
@@ -1325,8 +1709,11 @@ class FormsTestCase(SimpleTestCase):
password = CharField(widget=PasswordInput)
p = UserRegistration(initial={'username': 'babik'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username:
-
Password:
""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
Username:
+
Password:
"""
+ )
def test_callable_initial_data(self):
# The previous technique dealt with raw values as initial data, but it's also
@@ -1351,39 +1738,60 @@ class FormsTestCase(SimpleTestCase):
# Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username:
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
Username:
Password:
Options:
""")
+"""
+ )
# The 'initial' parameter is meaningless if you pass data.
p = UserRegistration({}, initial={'username': initial_django, 'options': initial_options}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
""")
+"""
+ )
# A callable 'initial' value is *not* used as a fallback if data is not provided.
# In this example, we don't provide a value for 'username', and the form raises a
@@ -1397,24 +1805,33 @@ class FormsTestCase(SimpleTestCase):
class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
- options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')], initial=initial_other_options)
+ options = MultipleChoiceField(
+ choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')],
+ initial=initial_other_options,
+ )
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
"""
+ )
# The help text is displayed whether or not data is provided for the form.
p = UserRegistration({'username': 'foo'}, auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username: e.g., user@example.com
-
This field is required.
Password: Wählen Sie mit Bedacht.
""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
Username:
+e.g., user@example.com
+
This field is required.
Password:
+Wählen Sie mit Bedacht.
"""
+ )
# help_text is not displayed for hidden fields. It can be used for documentation
# purposes, though.
@@ -1548,8 +1985,13 @@ class FormsTestCase(SimpleTestCase):
next = CharField(widget=HiddenInput, initial='/', help_text='Redirect destination')
p = UserRegistration(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
Username: e.g., user@example.com
-
Password:
""")
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
Username:
+e.g., user@example.com
+
Password:
+
"""
+ )
def test_subclassing_forms(self):
# You can subclass a Form to add fields. The resulting form subclass will have
@@ -1564,14 +2006,20 @@ class FormsTestCase(SimpleTestCase):
instrument = CharField()
p = Person(auto_id=False)
- self.assertHTMLEqual(p.as_ul(), """
First name:
+ self.assertHTMLEqual(
+ p.as_ul(),
+ """
First name:
Last name:
-
Birthday:
""")
+
Birthday:
"""
+ )
m = Musician(auto_id=False)
- self.assertHTMLEqual(m.as_ul(), """
First name:
+ self.assertHTMLEqual(
+ m.as_ul(),
+ """
First name:
Last name:
Birthday:
-
Instrument:
""")
+
Instrument:
"""
+ )
# Yes, you can subclass multiple forms. The fields are added in the order in
# which the parent classes are listed.
@@ -1612,12 +2060,27 @@ class FormsTestCase(SimpleTestCase):
'person1-birthday': '1940-10-9'
}
p = Person(data, prefix='person1')
- self.assertHTMLEqual(p.as_ul(), """
')
self.assertTrue(f.is_valid())
- f = FileForm(data={}, files={'file1': SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))}, auto_id=False)
+ file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode('utf-8'))
+ f = FileForm(data={}, files={'file1': file1}, auto_id=False)
self.assertHTMLEqual(f.as_table(), '
File1:
')
def test_basic_processing_in_view(self):
@@ -1790,7 +2276,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput)
def clean(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data
@@ -1804,7 +2291,10 @@ class FormsTestCase(SimpleTestCase):
if form.is_valid():
return 'VALID: %r' % sorted(six.iteritems(form.cleaned_data))
- t = Template('
')
+ t = Template(
+ ''
+ )
return t.render(Context({'form': form}))
# Case 1: GET (an empty form, with no errors).)
@@ -1817,18 +2307,27 @@ class FormsTestCase(SimpleTestCase):
""")
# Case 2: POST with erroneous data (a redisplayed form, with errors).)
- self.assertHTMLEqual(my_function('POST', {'username': 'this-is-a-long-username', 'password1': 'foo', 'password2': 'bar'}), """""")
+"""
+ )
# Case 3: POST with valid data (the success message).)
- self.assertEqual(my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}),
- str_prefix("VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]"))
+ self.assertEqual(
+ my_function('POST', {'username': 'adrian', 'password1': 'secret', 'password2': 'secret'}),
+ str_prefix(
+ "VALID: [('password1', %(_)s'secret'), ('password2', %(_)s'secret'), ('username', %(_)s'adrian')]"
+ )
+ )
def test_templates_with_forms(self):
class UserRegistration(Form):
@@ -1837,7 +2336,8 @@ class FormsTestCase(SimpleTestCase):
password2 = CharField(widget=PasswordInput)
def clean(self):
- if self.cleaned_data.get('password1') and self.cleaned_data.get('password2') and self.cleaned_data['password1'] != self.cleaned_data['password2']:
+ if (self.cleaned_data.get('password1') and self.cleaned_data.get('password2')
+ and self.cleaned_data['password1'] != self.cleaned_data['password2']):
raise ValidationError('Please make sure your passwords match.')
return self.cleaned_data
@@ -1859,12 +2359,17 @@ class FormsTestCase(SimpleTestCase):
Password (again):
""")
- self.assertHTMLEqual(t.render(Context({'form': UserRegistration({'username': 'django'}, auto_id=False)})), """""")
+"""
+ )
# Use form.[field].label to output a field's label. You can specify the label for
# a field by using the 'label' argument to a Field class. If you don't specify
@@ -1914,13 +2419,20 @@ class FormsTestCase(SimpleTestCase):