From 9c19aff7c7561e3a82978a272ecdaad40dda5c00 Mon Sep 17 00:00:00 2001 From: django-bot Date: Thu, 3 Feb 2022 20:24:19 +0100 Subject: Refs #33476 -- Reformatted code with Black. --- tests/forms_tests/field_tests/__init__.py | 4 +- tests/forms_tests/field_tests/test_base.py | 13 +- tests/forms_tests/field_tests/test_booleanfield.py | 47 +- tests/forms_tests/field_tests/test_charfield.py | 100 +- tests/forms_tests/field_tests/test_choicefield.py | 73 +- tests/forms_tests/field_tests/test_combofield.py | 37 +- tests/forms_tests/field_tests/test_datefield.py | 183 +- .../forms_tests/field_tests/test_datetimefield.py | 125 +- tests/forms_tests/field_tests/test_decimalfield.py | 193 +- .../forms_tests/field_tests/test_durationfield.py | 37 +- tests/forms_tests/field_tests/test_emailfield.py | 55 +- tests/forms_tests/field_tests/test_filefield.py | 88 +- .../forms_tests/field_tests/test_filepathfield.py | 105 +- tests/forms_tests/field_tests/test_floatfield.py | 85 +- .../field_tests/test_genericipaddressfield.py | 219 +- tests/forms_tests/field_tests/test_imagefield.py | 74 +- tests/forms_tests/field_tests/test_integerfield.py | 112 +- tests/forms_tests/field_tests/test_jsonfield.py | 71 +- .../field_tests/test_multiplechoicefield.py | 75 +- .../field_tests/test_multivaluefield.py | 115 +- .../field_tests/test_nullbooleanfield.py | 52 +- tests/forms_tests/field_tests/test_regexfield.py | 92 +- tests/forms_tests/field_tests/test_slugfield.py | 23 +- .../field_tests/test_splitdatetimefield.py | 75 +- tests/forms_tests/field_tests/test_timefield.py | 31 +- .../field_tests/test_typedchoicefield.py | 62 +- .../field_tests/test_typedmultiplechoicefield.py | 44 +- tests/forms_tests/field_tests/test_urlfield.py | 116 +- tests/forms_tests/field_tests/test_uuidfield.py | 19 +- tests/forms_tests/models.py | 44 +- tests/forms_tests/tests/__init__.py | 6 +- tests/forms_tests/tests/test_deprecation_forms.py | 67 +- tests/forms_tests/tests/test_error_messages.py | 322 +-- tests/forms_tests/tests/test_forms.py | 2574 ++++++++++++-------- tests/forms_tests/tests/test_formsets.py | 1185 +++++---- tests/forms_tests/tests/test_i18n.py | 62 +- tests/forms_tests/tests/test_input_formats.py | 304 +-- tests/forms_tests/tests/test_media.py | 412 ++-- tests/forms_tests/tests/test_renderers.py | 24 +- tests/forms_tests/tests/test_utils.py | 215 +- tests/forms_tests/tests/test_validators.py | 122 +- tests/forms_tests/tests/test_widgets.py | 11 +- tests/forms_tests/tests/tests.py | 200 +- tests/forms_tests/urls.py | 4 +- tests/forms_tests/views.py | 8 +- tests/forms_tests/widget_tests/base.py | 22 +- .../forms_tests/widget_tests/test_checkboxinput.py | 89 +- .../widget_tests/test_checkboxselectmultiple.py | 100 +- .../widget_tests/test_clearablefileinput.py | 101 +- tests/forms_tests/widget_tests/test_dateinput.py | 43 +- .../forms_tests/widget_tests/test_datetimeinput.py | 74 +- tests/forms_tests/widget_tests/test_fileinput.py | 23 +- tests/forms_tests/widget_tests/test_hiddeninput.py | 8 +- tests/forms_tests/widget_tests/test_input.py | 20 +- .../widget_tests/test_multiplehiddeninput.py | 44 +- tests/forms_tests/widget_tests/test_multiwidget.py | 203 +- .../widget_tests/test_nullbooleanselect.py | 112 +- tests/forms_tests/widget_tests/test_numberinput.py | 9 +- .../forms_tests/widget_tests/test_passwordinput.py | 23 +- tests/forms_tests/widget_tests/test_radioselect.py | 69 +- tests/forms_tests/widget_tests/test_select.py | 375 +-- .../widget_tests/test_selectdatewidget.py | 240 +- .../widget_tests/test_selectmultiple.py | 140 +- .../widget_tests/test_splitdatetimewidget.py | 93 +- .../widget_tests/test_splithiddendatetimewidget.py | 83 +- tests/forms_tests/widget_tests/test_textarea.py | 52 +- tests/forms_tests/widget_tests/test_textinput.py | 79 +- tests/forms_tests/widget_tests/test_timeinput.py | 55 +- tests/forms_tests/widget_tests/test_widget.py | 23 +- 69 files changed, 5893 insertions(+), 4072 deletions(-) (limited to 'tests/forms_tests') diff --git a/tests/forms_tests/field_tests/__init__.py b/tests/forms_tests/field_tests/__init__.py index 4aae30282b..94b2a91242 100644 --- a/tests/forms_tests/field_tests/__init__.py +++ b/tests/forms_tests/field_tests/__init__.py @@ -2,8 +2,8 @@ from django import forms class FormFieldAssertionsMixin: - def assertWidgetRendersTo(self, field, to): class Form(forms.Form): f = field - self.assertHTMLEqual(str(Form()['f']), to) + + self.assertHTMLEqual(str(Form()["f"]), to) diff --git a/tests/forms_tests/field_tests/test_base.py b/tests/forms_tests/field_tests/test_base.py index 4ddbea3414..201e05e47e 100644 --- a/tests/forms_tests/field_tests/test_base.py +++ b/tests/forms_tests/field_tests/test_base.py @@ -3,7 +3,6 @@ from django.test import SimpleTestCase class BasicFieldsTests(SimpleTestCase): - def test_field_sets_widget_is_required(self): self.assertTrue(Field(required=True).widget.is_required) self.assertFalse(Field(required=False).widget.is_required) @@ -23,20 +22,20 @@ class BasicFieldsTests(SimpleTestCase): def test_field_deepcopies_widget_instance(self): class CustomChoiceField(ChoiceField): - widget = Select(attrs={'class': 'my-custom-class'}) + widget = Select(attrs={"class": "my-custom-class"}) class TestForm(Form): field1 = CustomChoiceField(choices=[]) field2 = CustomChoiceField(choices=[]) f = TestForm() - f.fields['field1'].choices = [('1', '1')] - f.fields['field2'].choices = [('2', '2')] - self.assertEqual(f.fields['field1'].widget.choices, [('1', '1')]) - self.assertEqual(f.fields['field2'].widget.choices, [('2', '2')]) + f.fields["field1"].choices = [("1", "1")] + f.fields["field2"].choices = [("2", "2")] + self.assertEqual(f.fields["field1"].widget.choices, [("1", "1")]) + self.assertEqual(f.fields["field2"].widget.choices, [("2", "2")]) class DisabledFieldTests(SimpleTestCase): def test_disabled_field_has_changed_always_false(self): disabled_field = Field(disabled=True) - self.assertFalse(disabled_field.has_changed('x', 'y')) + self.assertFalse(disabled_field.has_changed("x", "y")) diff --git a/tests/forms_tests/field_tests/test_booleanfield.py b/tests/forms_tests/field_tests/test_booleanfield.py index b0153e9e0b..560a0f473b 100644 --- a/tests/forms_tests/field_tests/test_booleanfield.py +++ b/tests/forms_tests/field_tests/test_booleanfield.py @@ -6,11 +6,10 @@ from django.test import SimpleTestCase class BooleanFieldTest(SimpleTestCase): - def test_booleanfield_clean_1(self): f = BooleanField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): - f.clean('') + f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) self.assertTrue(f.clean(True)) @@ -19,25 +18,25 @@ class BooleanFieldTest(SimpleTestCase): self.assertTrue(f.clean(1)) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(0) - self.assertTrue(f.clean('Django rocks')) - self.assertTrue(f.clean('True')) + self.assertTrue(f.clean("Django rocks")) + self.assertTrue(f.clean("True")) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): - f.clean('False') + f.clean("False") def test_booleanfield_clean_2(self): f = BooleanField(required=False) - self.assertIs(f.clean(''), False) + self.assertIs(f.clean(""), False) self.assertIs(f.clean(None), False) self.assertIs(f.clean(True), True) self.assertIs(f.clean(False), False) self.assertIs(f.clean(1), True) self.assertIs(f.clean(0), False) - self.assertIs(f.clean('1'), True) - self.assertIs(f.clean('0'), False) - self.assertIs(f.clean('Django rocks'), True) - self.assertIs(f.clean('False'), False) - self.assertIs(f.clean('false'), False) - self.assertIs(f.clean('FaLsE'), False) + self.assertIs(f.clean("1"), True) + self.assertIs(f.clean("0"), False) + self.assertIs(f.clean("Django rocks"), True) + self.assertIs(f.clean("False"), False) + self.assertIs(f.clean("false"), False) + self.assertIs(f.clean("FaLsE"), False) def test_boolean_picklable(self): self.assertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField) @@ -45,20 +44,20 @@ class BooleanFieldTest(SimpleTestCase): def test_booleanfield_changed(self): f = BooleanField() self.assertFalse(f.has_changed(None, None)) - self.assertFalse(f.has_changed(None, '')) - self.assertFalse(f.has_changed('', None)) - self.assertFalse(f.has_changed('', '')) - self.assertTrue(f.has_changed(False, 'on')) - self.assertFalse(f.has_changed(True, 'on')) - self.assertTrue(f.has_changed(True, '')) + self.assertFalse(f.has_changed(None, "")) + self.assertFalse(f.has_changed("", None)) + self.assertFalse(f.has_changed("", "")) + self.assertTrue(f.has_changed(False, "on")) + self.assertFalse(f.has_changed(True, "on")) + self.assertTrue(f.has_changed(True, "")) # Initial value may have mutated to a string due to show_hidden_initial (#19537) - self.assertTrue(f.has_changed('False', 'on')) + self.assertTrue(f.has_changed("False", "on")) # HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict - self.assertFalse(f.has_changed(False, 'False')) - self.assertFalse(f.has_changed(True, 'True')) - self.assertTrue(f.has_changed(False, 'True')) - self.assertTrue(f.has_changed(True, 'False')) + self.assertFalse(f.has_changed(False, "False")) + self.assertFalse(f.has_changed(True, "True")) + self.assertTrue(f.has_changed(False, "True")) + self.assertTrue(f.has_changed(True, "False")) def test_disabled_has_changed(self): f = BooleanField(disabled=True) - self.assertIs(f.has_changed('True', 'False'), False) + self.assertIs(f.has_changed("True", "False"), False) diff --git a/tests/forms_tests/field_tests/test_charfield.py b/tests/forms_tests/field_tests/test_charfield.py index 352761deec..2c3f9b7ebe 100644 --- a/tests/forms_tests/field_tests/test_charfield.py +++ b/tests/forms_tests/field_tests/test_charfield.py @@ -1,66 +1,63 @@ from django.core.exceptions import ValidationError -from django.forms import ( - CharField, HiddenInput, PasswordInput, Textarea, TextInput, -) +from django.forms import CharField, HiddenInput, PasswordInput, Textarea, TextInput from django.test import SimpleTestCase from . import FormFieldAssertionsMixin class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase): - def test_charfield_1(self): f = CharField() - self.assertEqual('1', f.clean(1)) - self.assertEqual('hello', f.clean('hello')) + self.assertEqual("1", f.clean(1)) + self.assertEqual("hello", f.clean("hello")) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): - f.clean('') - self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) + f.clean("") + self.assertEqual("[1, 2, 3]", f.clean([1, 2, 3])) self.assertIsNone(f.max_length) self.assertIsNone(f.min_length) def test_charfield_2(self): f = CharField(required=False) - self.assertEqual('1', f.clean(1)) - self.assertEqual('hello', f.clean('hello')) - self.assertEqual('', f.clean(None)) - self.assertEqual('', f.clean('')) - self.assertEqual('[1, 2, 3]', f.clean([1, 2, 3])) + self.assertEqual("1", f.clean(1)) + self.assertEqual("hello", f.clean("hello")) + self.assertEqual("", f.clean(None)) + self.assertEqual("", f.clean("")) + self.assertEqual("[1, 2, 3]", f.clean([1, 2, 3])) self.assertIsNone(f.max_length) self.assertIsNone(f.min_length) def test_charfield_3(self): f = CharField(max_length=10, required=False) - self.assertEqual('12345', f.clean('12345')) - self.assertEqual('1234567890', f.clean('1234567890')) + self.assertEqual("12345", f.clean("12345")) + self.assertEqual("1234567890", f.clean("1234567890")) msg = "'Ensure this value has at most 10 characters (it has 11).'" with self.assertRaisesMessage(ValidationError, msg): - f.clean('1234567890a') + f.clean("1234567890a") self.assertEqual(f.max_length, 10) self.assertIsNone(f.min_length) def test_charfield_4(self): f = CharField(min_length=10, required=False) - self.assertEqual('', f.clean('')) + self.assertEqual("", f.clean("")) 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')) + f.clean("12345") + self.assertEqual("1234567890", f.clean("1234567890")) + self.assertEqual("1234567890a", f.clean("1234567890a")) self.assertIsNone(f.max_length) self.assertEqual(f.min_length, 10) def test_charfield_5(self): f = CharField(min_length=10, required=True) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): - f.clean('') + f.clean("") 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')) + f.clean("12345") + self.assertEqual("1234567890", f.clean("1234567890")) + self.assertEqual("1234567890a", f.clean("1234567890a")) self.assertIsNone(f.max_length) self.assertEqual(f.min_length, 10) @@ -70,12 +67,12 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase): raises an exception. """ with self.assertRaises(ValueError): - CharField(min_length='a') + CharField(min_length="a") with self.assertRaises(ValueError): - CharField(max_length='a') - msg = '__init__() takes 1 positional argument but 2 were given' + CharField(max_length="a") + msg = "__init__() takes 1 positional argument but 2 were given" with self.assertRaisesMessage(TypeError, msg): - CharField('a') + CharField("a") def test_charfield_widget_attrs(self): """ @@ -90,22 +87,28 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase): # Return a maxlength attribute equal to max_length. f = CharField(max_length=10) - self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'}) - self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'}) - self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10'}) + self.assertEqual(f.widget_attrs(TextInput()), {"maxlength": "10"}) + self.assertEqual(f.widget_attrs(PasswordInput()), {"maxlength": "10"}) + self.assertEqual(f.widget_attrs(Textarea()), {"maxlength": "10"}) # Return a minlength attribute equal to min_length. f = CharField(min_length=5) - self.assertEqual(f.widget_attrs(TextInput()), {'minlength': '5'}) - self.assertEqual(f.widget_attrs(PasswordInput()), {'minlength': '5'}) - self.assertEqual(f.widget_attrs(Textarea()), {'minlength': '5'}) + self.assertEqual(f.widget_attrs(TextInput()), {"minlength": "5"}) + self.assertEqual(f.widget_attrs(PasswordInput()), {"minlength": "5"}) + self.assertEqual(f.widget_attrs(Textarea()), {"minlength": "5"}) # Return both maxlength and minlength when both max_length and # min_length are set. f = CharField(max_length=10, min_length=5) - self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10', 'minlength': '5'}) - self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10', 'minlength': '5'}) - self.assertEqual(f.widget_attrs(Textarea()), {'maxlength': '10', 'minlength': '5'}) + self.assertEqual( + f.widget_attrs(TextInput()), {"maxlength": "10", "minlength": "5"} + ) + self.assertEqual( + f.widget_attrs(PasswordInput()), {"maxlength": "10", "minlength": "5"} + ) + self.assertEqual( + f.widget_attrs(Textarea()), {"maxlength": "10", "minlength": "5"} + ) self.assertEqual(f.widget_attrs(HiddenInput()), {}) def test_charfield_strip(self): @@ -113,12 +116,12 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase): Values have whitespace stripped but not if strip=False. """ f = CharField() - self.assertEqual(f.clean(' 1'), '1') - self.assertEqual(f.clean('1 '), '1') + self.assertEqual(f.clean(" 1"), "1") + self.assertEqual(f.clean("1 "), "1") f = CharField(strip=False) - self.assertEqual(f.clean(' 1'), ' 1') - self.assertEqual(f.clean('1 '), '1 ') + self.assertEqual(f.clean(" 1"), " 1") + self.assertEqual(f.clean("1 "), "1 ") def test_strip_before_checking_empty(self): """ @@ -126,10 +129,11 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase): converted to the empty value, None. """ f = CharField(required=False, empty_value=None) - self.assertIsNone(f.clean(' ')) + self.assertIsNone(f.clean(" ")) def test_clean_non_string(self): """CharField.clean() calls str(value) before stripping it.""" + class StringWrapper: def __init__(self, v): self.v = v @@ -137,18 +141,20 @@ class CharFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def __str__(self): return self.v - value = StringWrapper(' ') + value = StringWrapper(" ") f1 = CharField(required=False, empty_value=None) self.assertIsNone(f1.clean(value)) f2 = CharField(strip=False) - self.assertEqual(f2.clean(value), ' ') + self.assertEqual(f2.clean(value), " ") def test_charfield_disabled(self): f = CharField(disabled=True) - self.assertWidgetRendersTo(f, '') + self.assertWidgetRendersTo( + f, '' + ) def test_null_characters_prohibited(self): f = CharField() - msg = 'Null characters are not allowed.' + msg = "Null characters are not allowed." with self.assertRaisesMessage(ValidationError, msg): - f.clean('\x00something') + f.clean("\x00something") diff --git a/tests/forms_tests/field_tests/test_choicefield.py b/tests/forms_tests/field_tests/test_choicefield.py index f25e2cedfd..bc580bbf02 100644 --- a/tests/forms_tests/field_tests/test_choicefield.py +++ b/tests/forms_tests/field_tests/test_choicefield.py @@ -7,52 +7,52 @@ from . import FormFieldAssertionsMixin class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase): - def test_choicefield_1(self): - f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')]) + f = ChoiceField(choices=[("1", "One"), ("2", "Two")]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): - f.clean('') + f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) - self.assertEqual('1', f.clean(1)) - self.assertEqual('1', f.clean('1')) + self.assertEqual("1", f.clean(1)) + self.assertEqual("1", f.clean("1")) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): - f.clean('3') + f.clean("3") def test_choicefield_2(self): - f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False) - self.assertEqual('', f.clean('')) - self.assertEqual('', f.clean(None)) - self.assertEqual('1', f.clean(1)) - self.assertEqual('1', f.clean('1')) + f = ChoiceField(choices=[("1", "One"), ("2", "Two")], required=False) + self.assertEqual("", f.clean("")) + self.assertEqual("", f.clean(None)) + self.assertEqual("1", f.clean(1)) + self.assertEqual("1", f.clean("1")) msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): - f.clean('3') + f.clean("3") def test_choicefield_3(self): - f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')]) - self.assertEqual('J', f.clean('J')) + f = ChoiceField(choices=[("J", "John"), ("P", "Paul")]) + self.assertEqual("J", f.clean("J")) msg = "'Select a valid choice. John is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): - f.clean('John') + f.clean("John") def test_choicefield_4(self): f = ChoiceField( choices=[ - ('Numbers', (('1', 'One'), ('2', 'Two'))), - ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other'), + ("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.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")) msg = "'Select a valid choice. 6 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): - f.clean('6') + f.clean("6") def test_choicefield_choices_default(self): f = ChoiceField() @@ -60,9 +60,10 @@ class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase): def test_choicefield_callable(self): def choices(): - return [('J', 'John'), ('P', 'Paul')] + return [("J", "John"), ("P", "Paul")] + f = ChoiceField(choices=choices) - self.assertEqual('J', f.clean('J')) + self.assertEqual("J", f.clean("J")) def test_choicefield_callable_may_evaluate_to_different_values(self): choices = [] @@ -73,29 +74,29 @@ class ChoiceFieldTest(FormFieldAssertionsMixin, SimpleTestCase): class ChoiceFieldForm(Form): choicefield = ChoiceField(choices=choices_as_callable) - choices = [('J', 'John')] + choices = [("J", "John")] form = ChoiceFieldForm() - self.assertEqual([('J', 'John')], list(form.fields['choicefield'].choices)) + self.assertEqual([("J", "John")], list(form.fields["choicefield"].choices)) - choices = [('P', 'Paul')] + choices = [("P", "Paul")] form = ChoiceFieldForm() - self.assertEqual([('P', 'Paul')], list(form.fields['choicefield'].choices)) + self.assertEqual([("P", "Paul")], list(form.fields["choicefield"].choices)) def test_choicefield_disabled(self): - f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True) + f = ChoiceField(choices=[("J", "John"), ("P", "Paul")], disabled=True) self.assertWidgetRendersTo( f, '' + '', ) def test_choicefield_enumeration(self): class FirstNames(models.TextChoices): - JOHN = 'J', 'John' - PAUL = 'P', 'Paul' + JOHN = "J", "John" + PAUL = "P", "Paul" f = ChoiceField(choices=FirstNames.choices) - self.assertEqual(f.clean('J'), 'J') + self.assertEqual(f.clean("J"), "J") msg = "'Select a valid choice. 3 is not one of the available choices.'" with self.assertRaisesMessage(ValidationError, msg): - f.clean('3') + f.clean("3") diff --git a/tests/forms_tests/field_tests/test_combofield.py b/tests/forms_tests/field_tests/test_combofield.py index 481783fe2e..d433fdf2b3 100644 --- a/tests/forms_tests/field_tests/test_combofield.py +++ b/tests/forms_tests/field_tests/test_combofield.py @@ -4,25 +4,34 @@ from django.test import SimpleTestCase class ComboFieldTest(SimpleTestCase): - def test_combofield_1(self): f = ComboField(fields=[CharField(max_length=20), EmailField()]) - self.assertEqual('test@example.com', f.clean('test@example.com')) - with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"): - f.clean('longemailaddress@example.com') - with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): - f.clean('not an email') + self.assertEqual("test@example.com", f.clean("test@example.com")) + with self.assertRaisesMessage( + ValidationError, + "'Ensure this value has at most 20 characters (it has 28).'", + ): + f.clean("longemailaddress@example.com") + with self.assertRaisesMessage( + ValidationError, "'Enter a valid email address.'" + ): + f.clean("not an email") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): - f.clean('') + f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) 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')) - with self.assertRaisesMessage(ValidationError, "'Ensure this value has at most 20 characters (it has 28).'"): - f.clean('longemailaddress@example.com') - with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): - f.clean('not an email') - self.assertEqual('', f.clean('')) - self.assertEqual('', f.clean(None)) + self.assertEqual("test@example.com", f.clean("test@example.com")) + with self.assertRaisesMessage( + ValidationError, + "'Ensure this value has at most 20 characters (it has 28).'", + ): + f.clean("longemailaddress@example.com") + with self.assertRaisesMessage( + ValidationError, "'Enter a valid email address.'" + ): + f.clean("not an email") + self.assertEqual("", f.clean("")) + self.assertEqual("", f.clean(None)) diff --git a/tests/forms_tests/field_tests/test_datefield.py b/tests/forms_tests/field_tests/test_datefield.py index 10d77bf1bb..a9f93f40ed 100644 --- a/tests/forms_tests/field_tests/test_datefield.py +++ b/tests/forms_tests/field_tests/test_datefield.py @@ -11,174 +11,195 @@ class GetDate(Form): class DateFieldTest(SimpleTestCase): - def test_form_field(self): - a = GetDate({'mydate_month': '4', 'mydate_day': '1', 'mydate_year': '2008'}) + a = GetDate({"mydate_month": "4", "mydate_day": "1", "mydate_year": "2008"}) self.assertTrue(a.is_valid()) - self.assertEqual(a.cleaned_data['mydate'], date(2008, 4, 1)) + self.assertEqual(a.cleaned_data["mydate"], date(2008, 4, 1)) # As with any widget that implements get_value_from_datadict(), we must # accept the input from the "as_hidden" rendering as well. self.assertHTMLEqual( - a['mydate'].as_hidden(), + a["mydate"].as_hidden(), '', ) - b = GetDate({'mydate': '2008-4-1'}) + b = GetDate({"mydate": "2008-4-1"}) self.assertTrue(b.is_valid()) - self.assertEqual(b.cleaned_data['mydate'], date(2008, 4, 1)) + self.assertEqual(b.cleaned_data["mydate"], date(2008, 4, 1)) # Invalid dates shouldn't be allowed - c = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'}) + c = GetDate({"mydate_month": "2", "mydate_day": "31", "mydate_year": "2010"}) self.assertFalse(c.is_valid()) - self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']}) + self.assertEqual(c.errors, {"mydate": ["Enter a valid date."]}) # label tag is correctly associated with month dropdown - d = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'}) + d = GetDate({"mydate_month": "1", "mydate_day": "1", "mydate_year": "2010"}) self.assertIn('", ) def test_templates_with_forms(self): class UserRegistration(Form): - username = CharField(max_length=10, help_text=( - "Good luck picking a username that doesn't already exist." - )) + username = CharField( + max_length=10, + help_text=("Good luck picking a username that doesn't already exist."), + ) password1 = CharField(widget=PasswordInput) 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'] + 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.') + raise ValidationError("Please make sure your passwords match.") return self.cleaned_data # There is full flexibility in displaying form fields in a template. @@ -3800,169 +4258,169 @@ class TemplateTests(SimpleTestCase): # responsibility of displaying all the errors, including any that might # not be associated with a particular field. t = Template( - '
' - '{{ form.username.errors.as_ul }}' - '

' - '{{ form.password1.errors.as_ul }}' - '

' - '{{ form.password2.errors.as_ul }}' - '

' + "" + "{{ form.username.errors.as_ul }}" + "

" + "{{ form.password1.errors.as_ul }}" + "

" + "{{ form.password2.errors.as_ul }}" + "

" '' - '
' + "" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( - t.render(Context({'form': f})), - '
' - '

' - '

' - '

' '' - '
', + "", ) - f = UserRegistration({'username': 'django'}, auto_id=False) + f = UserRegistration({"username": "django"}, auto_id=False) self.assertHTMLEqual( - t.render(Context({'form': f})), - '
' - '

' + "

" '

' - '

' '' - '

' '' - '
', + "", ) # Use form.[field].label to output a field's label. 'label' for a field # can by specified by using the 'label' argument to a Field class. If # 'label' is not specified, Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. t = Template( - '
' - '

' - '

' - '

' + "" + "

" + "

" + "

" '' - '
' + "" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( - t.render(Context({'form': f})), - '
' - '

' - '

' - '

' '' - '
', + "", ) # Use form.[field].label_tag to output a field's label with a \n

", ) # Translated error messages - with translation.override('ru'): + with translation.override("ru"): f = SomeForm({}) self.assertHTMLEqual( f.as_p(), '\n' - '

' + "\u041e\u0431\u044f\u0437\u0430\u0442\u0435\u043b\u044c" + "\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.\n" + "

" '

\n
\n' + "En tied\xe4
\n" '
\n
\n

' + "Nainen\n

", ) def test_select_translated_text(self): # Deep copying translated text shouldn't raise an error. class CopyForm(Form): - degree = IntegerField(widget=Select(choices=((1, gettext_lazy('test')),))) + degree = IntegerField(widget=Select(choices=((1, gettext_lazy("test")),))) CopyForm() diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py index 7b9da02a0c..3ac28b1b30 100644 --- a/tests/forms_tests/tests/test_input_formats.py +++ b/tests/forms_tests/tests/test_input_formats.py @@ -11,7 +11,7 @@ class LocalizedTimeTests(SimpleTestCase): def setUp(self): # nl/formats.py has customized TIME_INPUT_FORMATS: # ['%H:%M:%S', '%H.%M:%S', '%H.%M', '%H:%M'] - activate('nl') + activate("nl") def tearDown(self): deactivate() @@ -21,18 +21,18 @@ class LocalizedTimeTests(SimpleTestCase): f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result - result = f.clean('13:30:05') + result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) - self.assertEqual(text, '13:30:05') + self.assertEqual(text, "13:30:05") # Parse a time in a valid, but non-default format, get a parsed result - result = f.clean('13:30') + result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -40,7 +40,7 @@ class LocalizedTimeTests(SimpleTestCase): self.assertEqual(text, "13:30:00") # ISO formats are accepted, even if not specified in formats.py - result = f.clean('13:30:05.000155') + result = f.clean("13:30:05.000155") self.assertEqual(result, time(13, 30, 5, 155)) def test_localized_timeField(self): @@ -48,18 +48,18 @@ class LocalizedTimeTests(SimpleTestCase): f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result - result = f.clean('13:30:05') + result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) - self.assertEqual(text, '13:30:05') + self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13:30') + result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -71,12 +71,12 @@ class LocalizedTimeTests(SimpleTestCase): f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30.05') + result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -84,7 +84,7 @@ class LocalizedTimeTests(SimpleTestCase): self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30') + result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -96,12 +96,12 @@ class LocalizedTimeTests(SimpleTestCase): f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30.05') + result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -109,7 +109,7 @@ class LocalizedTimeTests(SimpleTestCase): self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30') + result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -125,18 +125,18 @@ class CustomTimeInputFormatsTests(SimpleTestCase): f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('1:30:05 PM') + result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) - self.assertEqual(text, '01:30:05 PM') + self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid, but non-default format, get a parsed result - result = f.clean('1:30 PM') + result = f.clean("1:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -148,18 +148,18 @@ class CustomTimeInputFormatsTests(SimpleTestCase): f = forms.TimeField(localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('1:30:05 PM') + result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) - self.assertEqual(text, '01:30:05 PM') + self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result - result = f.clean('01:30 PM') + result = f.clean("01:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -171,12 +171,12 @@ class CustomTimeInputFormatsTests(SimpleTestCase): f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30.05') + result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -184,7 +184,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase): self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30') + result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -196,12 +196,12 @@ class CustomTimeInputFormatsTests(SimpleTestCase): f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30.05') + result = f.clean("13.30.05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -209,7 +209,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase): self.assertEqual(text, "01:30:05 PM") # Parse a time in a valid format, get a parsed result - result = f.clean('13.30') + result = f.clean("13.30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -223,10 +223,10 @@ class SimpleTimeFormatTests(SimpleTestCase): f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result - result = f.clean('13:30:05') + result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -234,7 +234,7 @@ class SimpleTimeFormatTests(SimpleTestCase): self.assertEqual(text, "13:30:05") # Parse a time in a valid, but non-default format, get a parsed result - result = f.clean('13:30') + result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -246,10 +246,10 @@ class SimpleTimeFormatTests(SimpleTestCase): f = forms.TimeField() # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM') + f.clean("1:30:05 PM") # Parse a time in a valid format, get a parsed result - result = f.clean('13:30:05') + result = f.clean("13:30:05") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -257,7 +257,7 @@ class SimpleTimeFormatTests(SimpleTestCase): self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('13:30') + result = f.clean("13:30") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -269,10 +269,10 @@ class SimpleTimeFormatTests(SimpleTestCase): f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"]) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('1:30:05 PM') + result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -280,7 +280,7 @@ class SimpleTimeFormatTests(SimpleTestCase): self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('1:30 PM') + result = f.clean("1:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -292,10 +292,10 @@ class SimpleTimeFormatTests(SimpleTestCase): f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True) # Parse a time in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05') + f.clean("13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('1:30:05 PM') + result = f.clean("1:30:05 PM") self.assertEqual(result, time(13, 30, 5)) # The parsed result does a round trip to the same format @@ -303,7 +303,7 @@ class SimpleTimeFormatTests(SimpleTestCase): self.assertEqual(text, "13:30:05") # Parse a time in a valid format, get a parsed result - result = f.clean('1:30 PM') + result = f.clean("1:30 PM") self.assertEqual(result, time(13, 30, 0)) # The parsed result does a round trip to default format @@ -313,7 +313,7 @@ class SimpleTimeFormatTests(SimpleTestCase): class LocalizedDateTests(SimpleTestCase): def setUp(self): - activate('de') + activate("de") def tearDown(self): deactivate() @@ -323,21 +323,21 @@ class LocalizedDateTests(SimpleTestCase): f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('21/12/2010') + f.clean("21/12/2010") # ISO formats are accepted, even if not specified in formats.py - self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21)) + self.assertEqual(f.clean("2010-12-21"), date(2010, 12, 21)) # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010') + result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip text = f.widget.format_value(result) - self.assertEqual(text, '21.12.2010') + self.assertEqual(text, "21.12.2010") # Parse a date in a valid, but non-default format, get a parsed result - result = f.clean('21.12.10') + result = f.clean("21.12.10") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -349,18 +349,18 @@ class LocalizedDateTests(SimpleTestCase): f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('21/12/2010') + f.clean("21/12/2010") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010') + result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) - self.assertEqual(text, '21.12.2010') + self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.10') + result = f.clean("21.12.10") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -372,14 +372,14 @@ class LocalizedDateTests(SimpleTestCase): f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") with self.assertRaises(ValidationError): - f.clean('21/12/2010') + f.clean("21/12/2010") with self.assertRaises(ValidationError): - f.clean('21.12.2010') + f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12.21.2010') + result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -387,7 +387,7 @@ class LocalizedDateTests(SimpleTestCase): self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12-21-2010') + result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -399,14 +399,14 @@ class LocalizedDateTests(SimpleTestCase): f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") with self.assertRaises(ValidationError): - f.clean('21/12/2010') + f.clean("21/12/2010") with self.assertRaises(ValidationError): - f.clean('21.12.2010') + f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12.21.2010') + result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -414,7 +414,7 @@ class LocalizedDateTests(SimpleTestCase): self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12-21-2010') + result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -430,18 +430,18 @@ class CustomDateInputFormatsTests(SimpleTestCase): f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010') + result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip text = f.widget.format_value(result) - self.assertEqual(text, '21.12.2010') + self.assertEqual(text, "21.12.2010") # Parse a date in a valid, but non-default format, get a parsed result - result = f.clean('21-12-2010') + result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -453,18 +453,18 @@ class CustomDateInputFormatsTests(SimpleTestCase): f = forms.DateField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010') + result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) - self.assertEqual(text, '21.12.2010') + self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('21-12-2010') + result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -476,12 +476,12 @@ class CustomDateInputFormatsTests(SimpleTestCase): f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('21.12.2010') + f.clean("21.12.2010") with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('12.21.2010') + result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -489,7 +489,7 @@ class CustomDateInputFormatsTests(SimpleTestCase): self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12-21-2010') + result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -501,12 +501,12 @@ class CustomDateInputFormatsTests(SimpleTestCase): f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('21.12.2010') + f.clean("21.12.2010") with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('12.21.2010') + result = f.clean("12.21.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -514,7 +514,7 @@ class CustomDateInputFormatsTests(SimpleTestCase): self.assertEqual(text, "21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12-21-2010') + result = f.clean("12-21-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -528,10 +528,10 @@ class SimpleDateFormatTests(SimpleTestCase): f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('21.12.2010') + f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('2010-12-21') + result = f.clean("2010-12-21") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -539,7 +539,7 @@ class SimpleDateFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21") # Parse a date in a valid, but non-default format, get a parsed result - result = f.clean('12/21/2010') + result = f.clean("12/21/2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -551,10 +551,10 @@ class SimpleDateFormatTests(SimpleTestCase): f = forms.DateField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('21.12.2010') + f.clean("21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('2010-12-21') + result = f.clean("2010-12-21") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -562,7 +562,7 @@ class SimpleDateFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('12/21/2010') + result = f.clean("12/21/2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -574,10 +574,10 @@ class SimpleDateFormatTests(SimpleTestCase): f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010') + result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -585,7 +585,7 @@ class SimpleDateFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('21-12-2010') + result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -597,10 +597,10 @@ class SimpleDateFormatTests(SimpleTestCase): f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010-12-21') + f.clean("2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010') + result = f.clean("21.12.2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to the same format @@ -608,7 +608,7 @@ class SimpleDateFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21") # Parse a date in a valid format, get a parsed result - result = f.clean('21-12-2010') + result = f.clean("21-12-2010") self.assertEqual(result, date(2010, 12, 21)) # The parsed result does a round trip to default format @@ -618,7 +618,7 @@ class SimpleDateFormatTests(SimpleTestCase): class LocalizedDateTimeTests(SimpleTestCase): def setUp(self): - activate('de') + activate("de") def tearDown(self): deactivate() @@ -628,21 +628,23 @@ class LocalizedDateTimeTests(SimpleTestCase): f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM 21/12/2010') + f.clean("1:30:05 PM 21/12/2010") # ISO formats are accepted, even if not specified in formats.py - self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010, 12, 21, 13, 30, 5)) + self.assertEqual( + f.clean("2010-12-21 13:30:05"), datetime(2010, 12, 21, 13, 30, 5) + ) # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010 13:30:05') + result = f.clean("21.12.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) - self.assertEqual(text, '21.12.2010 13:30:05') + self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid, but non-default format, get a parsed result - result = f.clean('21.12.2010 13:30') + result = f.clean("21.12.2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -654,18 +656,18 @@ class LocalizedDateTimeTests(SimpleTestCase): f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('1:30:05 PM 21/12/2010') + f.clean("1:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010 13:30:05') + result = f.clean("21.12.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) - self.assertEqual(text, '21.12.2010 13:30:05') + self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('21.12.2010 13:30') + result = f.clean("21.12.2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -677,14 +679,14 @@ class LocalizedDateTimeTests(SimpleTestCase): f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010-12-21 13:30:05 13:30:05') + f.clean("2010-12-21 13:30:05 13:30:05") with self.assertRaises(ValidationError): - f.clean('1:30:05 PM 21/12/2010') + f.clean("1:30:05 PM 21/12/2010") with self.assertRaises(ValidationError): - f.clean('13:30:05 21.12.2010') + f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('13.30.05 12.21.2010') + result = f.clean("13.30.05 12.21.2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format @@ -692,7 +694,7 @@ class LocalizedDateTimeTests(SimpleTestCase): self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('13.30 12-21-2010') + result = f.clean("13.30 12-21-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -701,21 +703,23 @@ class LocalizedDateTimeTests(SimpleTestCase): def test_localized_dateTimeField_with_inputformat(self): "Localized DateTimeFields with manually specified input formats can accept those formats" - f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True) + f = forms.DateTimeField( + input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True + ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010/12/21 13:30:05') + f.clean("2010/12/21 13:30:05") with self.assertRaises(ValidationError): - f.clean('1:30:05 PM 21/12/2010') + f.clean("1:30:05 PM 21/12/2010") with self.assertRaises(ValidationError): - f.clean('13:30:05 21.12.2010') + f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('13.30.05 12.21.2010') + result = f.clean("13.30.05 12.21.2010") self.assertEqual(datetime(2010, 12, 21, 13, 30, 5), result) # ISO format is always valid. self.assertEqual( - f.clean('2010-12-21 13:30:05'), + f.clean("2010-12-21 13:30:05"), datetime(2010, 12, 21, 13, 30, 5), ) # The parsed result does a round trip to the same format @@ -723,7 +727,7 @@ class LocalizedDateTimeTests(SimpleTestCase): self.assertEqual(text, "21.12.2010 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('13.30 12-21-2010') + result = f.clean("13.30 12-21-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -739,18 +743,18 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010/12/21 13:30:05') + f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('1:30:05 PM 21/12/2010') + result = f.clean("1:30:05 PM 21/12/2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip text = f.widget.format_value(result) - self.assertEqual(text, '01:30:05 PM 21/12/2010') + self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid, but non-default format, get a parsed result - result = f.clean('1:30 PM 21-12-2010') + result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -762,18 +766,18 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): f = forms.DateTimeField(localize=True) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010/12/21 13:30:05') + f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('1:30:05 PM 21/12/2010') + result = f.clean("1:30:05 PM 21/12/2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format text = f.widget.format_value(result) - self.assertEqual(text, '01:30:05 PM 21/12/2010') + self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result - result = f.clean('1:30 PM 21-12-2010') + result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -785,12 +789,12 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"]) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05 21.12.2010') + f.clean("13:30:05 21.12.2010") with self.assertRaises(ValidationError): - f.clean('2010/12/21 13:30:05') + f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('12.21.2010 13:30:05') + result = f.clean("12.21.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format @@ -798,7 +802,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12-21-2010 13:30') + result = f.clean("12-21-2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -807,15 +811,17 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): def test_localized_dateTimeField_with_inputformat(self): "Localized DateTimeFields with manually specified input formats can accept those formats" - f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True) + f = forms.DateTimeField( + input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True + ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05 21.12.2010') + f.clean("13:30:05 21.12.2010") with self.assertRaises(ValidationError): - f.clean('2010/12/21 13:30:05') + f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('12.21.2010 13:30:05') + result = f.clean("12.21.2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format @@ -823,7 +829,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): self.assertEqual(text, "01:30:05 PM 21/12/2010") # Parse a date in a valid format, get a parsed result - result = f.clean('12-21-2010 13:30') + result = f.clean("12-21-2010 13:30") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -837,10 +843,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase): f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05 21.12.2010') + f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('2010-12-21 13:30:05') + result = f.clean("2010-12-21 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format @@ -848,7 +854,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid, but non-default format, get a parsed result - result = f.clean('12/21/2010 13:30:05') + result = f.clean("12/21/2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to default format @@ -860,10 +866,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase): f = forms.DateTimeField() # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('13:30:05 21.12.2010') + f.clean("13:30:05 21.12.2010") # Parse a date in a valid format, get a parsed result - result = f.clean('2010-12-21 13:30:05') + result = f.clean("2010-12-21 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format @@ -871,7 +877,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('12/21/2010 13:30:05') + result = f.clean("12/21/2010 13:30:05") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to default format @@ -880,13 +886,15 @@ class SimpleDateTimeFormatTests(SimpleTestCase): def test_dateTimeField_with_inputformat(self): "DateTimeFields with manually specified input formats can accept those formats" - f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"]) + f = forms.DateTimeField( + input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"] + ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010/12/21 13:30:05') + f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('1:30:05 PM 21.12.2010') + result = f.clean("1:30:05 PM 21.12.2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format @@ -894,7 +902,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('1:30 PM 21-12-2010') + result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format @@ -903,13 +911,15 @@ class SimpleDateTimeFormatTests(SimpleTestCase): def test_localized_dateTimeField_with_inputformat(self): "Localized DateTimeFields with manually specified input formats can accept those formats" - f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True) + f = forms.DateTimeField( + input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True + ) # Parse a date in an unaccepted format; get an error with self.assertRaises(ValidationError): - f.clean('2010/12/21 13:30:05') + f.clean("2010/12/21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('1:30:05 PM 21.12.2010') + result = f.clean("1:30:05 PM 21.12.2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) # The parsed result does a round trip to the same format @@ -917,7 +927,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase): self.assertEqual(text, "2010-12-21 13:30:05") # Parse a date in a valid format, get a parsed result - result = f.clean('1:30 PM 21-12-2010') + result = f.clean("1:30 PM 21-12-2010") self.assertEqual(result, datetime(2010, 12, 21, 13, 30)) # The parsed result does a round trip to default format diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py index d145560d9b..59fd74f4c9 100644 --- a/tests/forms_tests/tests/test_media.py +++ b/tests/forms_tests/tests/test_media.py @@ -4,7 +4,7 @@ from django.test import SimpleTestCase, override_settings @override_settings( - STATIC_URL='http://media.example.com/static/', + STATIC_URL="http://media.example.com/static/", ) class FormsMediaTestCase(SimpleTestCase): """Tests for the media handling on widgets and forms""" @@ -12,8 +12,12 @@ class FormsMediaTestCase(SimpleTestCase): def test_construction(self): # Check construction of media objects m = Media( - css={'all': ('path/to/css1', '/path/to/css2')}, - js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'), + css={"all": ("path/to/css1", "/path/to/css2")}, + js=( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ), ) self.assertEqual( str(m), @@ -21,19 +25,21 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) self.assertEqual( repr(m), "Media(css={'all': ['path/to/css1', '/path/to/css2']}, " - "js=['/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'])" + "js=['/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'])", ) class Foo: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) m3 = Media(Foo) self.assertEqual( @@ -42,7 +48,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # A widget can exist without a media definition @@ -50,7 +56,7 @@ class FormsMediaTestCase(SimpleTestCase): pass w = MyWidget() - self.assertEqual(str(w.media), '') + self.assertEqual(str(w.media), "") def test_media_dsl(self): ############################################################### @@ -62,10 +68,12 @@ class FormsMediaTestCase(SimpleTestCase): # with the value of settings.MEDIA_URL class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) w1 = MyWidget1() self.assertEqual( @@ -74,21 +82,21 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # Media objects can be interrogated by media type self.assertEqual( - str(w1.media['css']), + str(w1.media["css"]), """ -""" +""", ) self.assertEqual( - str(w1.media['js']), + str(w1.media["js"]), """ -""" +""", ) def test_combine_media(self): @@ -96,24 +104,22 @@ class FormsMediaTestCase(SimpleTestCase): # once. Duplicated media definitions are ignored. class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget2(TextInput): class Media: - css = { - 'all': ('/path/to/css2', '/path/to/css3') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("/path/to/css2", "/path/to/css3")} + js = ("/path/to/js1", "/path/to/js4") class MyWidget3(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css3') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("path/to/css1", "/path/to/css3")} + js = ("/path/to/js1", "/path/to/js4") w1 = MyWidget1() w2 = MyWidget2() @@ -126,7 +132,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # media addition hasn't affected the original objects @@ -136,7 +142,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # Regression check for #12879: specifying the same CSS or JS file @@ -144,23 +150,29 @@ class FormsMediaTestCase(SimpleTestCase): # only being included once. class MyWidget4(TextInput): class Media: - css = {'all': ('/path/to/css1', '/path/to/css1')} - js = ('/path/to/js1', '/path/to/js1') + css = {"all": ("/path/to/css1", "/path/to/css1")} + js = ("/path/to/js1", "/path/to/js1") w4 = MyWidget4() - self.assertEqual(str(w4.media), """ -""") + self.assertEqual( + str(w4.media), + """ +""", + ) def test_media_deduplication(self): # A deduplication test applied directly to a Media object, to confirm # that the deduplication doesn't only happen at the point of merging # two or more media objects. media = Media( - css={'all': ('/path/to/css1', '/path/to/css1')}, - js=('/path/to/js1', '/path/to/js1'), + css={"all": ("/path/to/css1", "/path/to/css1")}, + js=("/path/to/js1", "/path/to/js1"), + ) + self.assertEqual( + str(media), + """ +""", ) - self.assertEqual(str(media), """ -""") def test_media_property(self): ############################################################### @@ -170,38 +182,53 @@ class FormsMediaTestCase(SimpleTestCase): # Widget media can be defined as a property class MyWidget4(TextInput): def _media(self): - return Media(css={'all': ('/some/path',)}, js=('/some/js',)) + return Media(css={"all": ("/some/path",)}, js=("/some/js",)) + media = property(_media) w4 = MyWidget4() - self.assertEqual(str(w4.media), """ -""") + self.assertEqual( + str(w4.media), + """ +""", + ) # Media properties can reference the media of their parents class MyWidget5(MyWidget4): def _media(self): - return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) + return super().media + Media( + css={"all": ("/other/path",)}, js=("/other/js",) + ) + media = property(_media) w5 = MyWidget5() - self.assertEqual(str(w5.media), """ + self.assertEqual( + str(w5.media), + """ -""") +""", + ) def test_media_property_parent_references(self): # Media properties can reference the media of their parents, # even if the parent media was defined using a class class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget6(MyWidget1): def _media(self): - return super().media + Media(css={'all': ('/other/path',)}, js=('/other/js',)) + return super().media + Media( + css={"all": ("/other/path",)}, js=("/other/js",) + ) + media = property(_media) w6 = MyWidget6() @@ -213,7 +240,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) def test_media_inheritance(self): @@ -224,10 +251,12 @@ class FormsMediaTestCase(SimpleTestCase): # If a widget extends another but provides no media definition, it inherits the parent widget's media class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget7(MyWidget1): pass @@ -239,16 +268,14 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # If a widget extends another but defines media, it extends the parent widget's media by default class MyWidget8(MyWidget1): class Media: - css = { - 'all': ('/path/to/css3', 'path/to/css1') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("/path/to/css3", "path/to/css1")} + js = ("/path/to/js1", "/path/to/js4") w8 = MyWidget8() self.assertEqual( @@ -259,7 +286,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) def test_media_inheritance_from_property(self): @@ -267,22 +294,23 @@ class FormsMediaTestCase(SimpleTestCase): # even if the parent defined media using a property. class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget4(TextInput): def _media(self): - return Media(css={'all': ('/some/path',)}, js=('/some/js',)) + return Media(css={"all": ("/some/path",)}, js=("/some/js",)) + media = property(_media) class MyWidget9(MyWidget4): class Media: - css = { - 'all': ('/other/path',) - } - js = ('/other/js',) + css = {"all": ("/other/path",)} + js = ("/other/js",) w9 = MyWidget9() self.assertEqual( @@ -290,40 +318,41 @@ class FormsMediaTestCase(SimpleTestCase): """ -""" +""", ) # A widget can disable media inheritance by specifying 'extend=False' class MyWidget10(MyWidget1): class Media: extend = False - css = { - 'all': ('/path/to/css3', 'path/to/css1') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("/path/to/css3", "path/to/css1")} + js = ("/path/to/js1", "/path/to/js4") w10 = MyWidget10() - self.assertEqual(str(w10.media), """ + self.assertEqual( + str(w10.media), + """ -""") +""", + ) def test_media_inheritance_extends(self): # A widget can explicitly enable full media inheritance by specifying 'extend=True' class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget11(MyWidget1): class Media: extend = True - css = { - 'all': ('/path/to/css3', 'path/to/css1') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("/path/to/css3", "path/to/css1")} + js = ("/path/to/js1", "/path/to/js4") w11 = MyWidget11() self.assertEqual( @@ -334,25 +363,25 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) def test_media_inheritance_single_type(self): # A widget can enable inheritance of one media type by specifying extend as a tuple class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget12(MyWidget1): class Media: - extend = ('css',) - css = { - 'all': ('/path/to/css3', 'path/to/css1') - } - js = ('/path/to/js1', '/path/to/js4') + extend = ("css",) + css = {"all": ("/path/to/css3", "path/to/css1")} + js = ("/path/to/js1", "/path/to/js4") w12 = MyWidget12() self.assertEqual( @@ -361,7 +390,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) def test_multi_media(self): @@ -373,11 +402,11 @@ class FormsMediaTestCase(SimpleTestCase): class MultimediaWidget(TextInput): class Media: css = { - 'screen, print': ('/file1', '/file2'), - 'screen': ('/file3',), - 'print': ('/file4',) + "screen, print": ("/file1", "/file2"), + "screen": ("/file3",), + "print": ("/file4",), } - js = ('/path/to/js1', '/path/to/js4') + js = ("/path/to/js1", "/path/to/js4") multimedia = MultimediaWidget() self.assertEqual( @@ -387,7 +416,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) def test_multi_widget(self): @@ -397,24 +426,22 @@ class FormsMediaTestCase(SimpleTestCase): class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget2(TextInput): class Media: - css = { - 'all': ('/path/to/css2', '/path/to/css3') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("/path/to/css2", "/path/to/css3")} + js = ("/path/to/js1", "/path/to/js4") class MyWidget3(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css3') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("path/to/css1", "/path/to/css3")} + js = ("/path/to/js1", "/path/to/js4") # MultiWidgets have a default media definition that gets all the # media from the component widgets @@ -432,7 +459,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) def test_form_media(self): @@ -442,29 +469,28 @@ class FormsMediaTestCase(SimpleTestCase): class MyWidget1(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css2') - } - js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3') + css = {"all": ("path/to/css1", "/path/to/css2")} + js = ( + "/path/to/js1", + "http://media.other.com/path/to/js2", + "https://secure.other.com/path/to/js3", + ) class MyWidget2(TextInput): class Media: - css = { - 'all': ('/path/to/css2', '/path/to/css3') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("/path/to/css2", "/path/to/css3")} + js = ("/path/to/js1", "/path/to/js4") class MyWidget3(TextInput): class Media: - css = { - 'all': ('path/to/css1', '/path/to/css3') - } - js = ('/path/to/js1', '/path/to/js4') + css = {"all": ("path/to/css1", "/path/to/css3")} + js = ("/path/to/js1", "/path/to/js4") # You can ask a form for the media required by its widgets. class MyForm(Form): field1 = CharField(max_length=20, widget=MyWidget1()) field2 = CharField(max_length=20, widget=MyWidget2()) + f1 = MyForm() self.assertEqual( str(f1.media), @@ -474,12 +500,13 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # Form media can be combined to produce a single media definition. class AnotherForm(Form): field3 = CharField(max_length=20, widget=MyWidget3()) + f2 = AnotherForm() self.assertEqual( str(f1.media + f2.media), @@ -489,7 +516,7 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # Forms can also define media, following the same rules as widgets. @@ -498,10 +525,9 @@ class FormsMediaTestCase(SimpleTestCase): field2 = CharField(max_length=20, widget=MyWidget2()) class Media: - js = ('/some/form/javascript',) - css = { - 'all': ('/some/form/css',) - } + js = ("/some/form/javascript",) + css = {"all": ("/some/form/css",)} + f3 = FormWithMedia() self.assertEqual( str(f3.media), @@ -513,12 +539,14 @@ class FormsMediaTestCase(SimpleTestCase): -""" +""", ) # Media works in templates self.assertEqual( - Template("{{ form.media.js }}{{ form.media.css }}").render(Context({'form': f3})), + Template("{{ form.media.js }}{{ form.media.css }}").render( + Context({"form": f3}) + ), """ @@ -527,12 +555,12 @@ class FormsMediaTestCase(SimpleTestCase): """ -""" +""", ) def test_html_safe(self): - media = Media(css={'all': ['/path/to/css']}, js=['/path/to/js']) - self.assertTrue(hasattr(Media, '__html__')) + media = Media(css={"all": ["/path/to/css"]}, js=["/path/to/js"]) + self.assertTrue(hasattr(Media, "__html__")) self.assertEqual(str(media), media.__html__()) def test_merge(self): @@ -544,7 +572,10 @@ class FormsMediaTestCase(SimpleTestCase): (([1, 2], [1, 3]), [1, 2, 3]), (([1, 2], [3, 2]), [1, 3, 2]), (([1, 2], [1, 2]), [1, 2]), - ([[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]], [1, 5, 8, 2, 6, 3, 7, 9]), + ( + [[1, 2], [1, 3], [2, 3], [5, 7], [5, 6], [6, 7, 9], [8, 9]], + [1, 5, 8, 2, 6, 3, 7, 9], + ), ((), []), (([1, 2],), [1, 2]), ) @@ -553,7 +584,7 @@ class FormsMediaTestCase(SimpleTestCase): self.assertEqual(Media.merge(*lists), expected) def test_merge_warning(self): - msg = 'Detected duplicate Media files in an opposite order: [1, 2], [2, 1]' + msg = "Detected duplicate Media files in an opposite order: [1, 2], [2, 1]" with self.assertWarnsMessage(RuntimeWarning, msg): self.assertEqual(Media.merge([1, 2], [2, 1]), [1, 2]) @@ -561,51 +592,60 @@ class FormsMediaTestCase(SimpleTestCase): """ The relative order of scripts is preserved in a three-way merge. """ - widget1 = Media(js=['color-picker.js']) - widget2 = Media(js=['text-editor.js']) - widget3 = Media(js=['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) + widget1 = Media(js=["color-picker.js"]) + widget2 = Media(js=["text-editor.js"]) + widget3 = Media( + js=["text-editor.js", "text-editor-extras.js", "color-picker.js"] + ) merged = widget1 + widget2 + widget3 - self.assertEqual(merged._js, ['text-editor.js', 'text-editor-extras.js', 'color-picker.js']) + self.assertEqual( + merged._js, ["text-editor.js", "text-editor-extras.js", "color-picker.js"] + ) def test_merge_js_three_way2(self): # The merge prefers to place 'c' before 'b' and 'g' before 'h' to # preserve the original order. The preference 'c'->'b' is overridden by # widget3's media, but 'g'->'h' survives in the final ordering. - widget1 = Media(js=['a', 'c', 'f', 'g', 'k']) - widget2 = Media(js=['a', 'b', 'f', 'h', 'k']) - widget3 = Media(js=['b', 'c', 'f', 'k']) + widget1 = Media(js=["a", "c", "f", "g", "k"]) + widget2 = Media(js=["a", "b", "f", "h", "k"]) + widget3 = Media(js=["b", "c", "f", "k"]) merged = widget1 + widget2 + widget3 - self.assertEqual(merged._js, ['a', 'b', 'c', 'f', 'g', 'h', 'k']) + self.assertEqual(merged._js, ["a", "b", "c", "f", "g", "h", "k"]) def test_merge_css_three_way(self): - widget1 = Media(css={'screen': ['c.css'], 'all': ['d.css', 'e.css']}) - widget2 = Media(css={'screen': ['a.css']}) - widget3 = Media(css={'screen': ['a.css', 'b.css', 'c.css'], 'all': ['e.css']}) - widget4 = Media(css={'all': ['d.css', 'e.css'], 'screen': ['c.css']}) + widget1 = Media(css={"screen": ["c.css"], "all": ["d.css", "e.css"]}) + widget2 = Media(css={"screen": ["a.css"]}) + widget3 = Media(css={"screen": ["a.css", "b.css", "c.css"], "all": ["e.css"]}) + widget4 = Media(css={"all": ["d.css", "e.css"], "screen": ["c.css"]}) merged = widget1 + widget2 # c.css comes before a.css because widget1 + widget2 establishes this # order. - self.assertEqual(merged._css, {'screen': ['c.css', 'a.css'], 'all': ['d.css', 'e.css']}) + self.assertEqual( + merged._css, {"screen": ["c.css", "a.css"], "all": ["d.css", "e.css"]} + ) merged = merged + widget3 # widget3 contains an explicit ordering of c.css and a.css. - self.assertEqual(merged._css, {'screen': ['a.css', 'b.css', 'c.css'], 'all': ['d.css', 'e.css']}) + self.assertEqual( + merged._css, + {"screen": ["a.css", "b.css", "c.css"], "all": ["d.css", "e.css"]}, + ) # Media ordering does not matter. merged = widget1 + widget4 - self.assertEqual(merged._css, {'screen': ['c.css'], 'all': ['d.css', 'e.css']}) + self.assertEqual(merged._css, {"screen": ["c.css"], "all": ["d.css", "e.css"]}) def test_add_js_deduplication(self): - widget1 = Media(js=['a', 'b', 'c']) - widget2 = Media(js=['a', 'b']) - widget3 = Media(js=['a', 'c', 'b']) + widget1 = Media(js=["a", "b", "c"]) + widget2 = Media(js=["a", "b"]) + widget3 = Media(js=["a", "c", "b"]) merged = widget1 + widget1 - self.assertEqual(merged._js_lists, [['a', 'b', 'c']]) - self.assertEqual(merged._js, ['a', 'b', 'c']) + self.assertEqual(merged._js_lists, [["a", "b", "c"]]) + self.assertEqual(merged._js, ["a", "b", "c"]) merged = widget1 + widget2 - self.assertEqual(merged._js_lists, [['a', 'b', 'c'], ['a', 'b']]) - self.assertEqual(merged._js, ['a', 'b', 'c']) + self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "b"]]) + self.assertEqual(merged._js, ["a", "b", "c"]) # Lists with items in a different order are preserved when added. merged = widget1 + widget3 - self.assertEqual(merged._js_lists, [['a', 'b', 'c'], ['a', 'c', 'b']]) + self.assertEqual(merged._js_lists, [["a", "b", "c"], ["a", "c", "b"]]) msg = ( "Detected duplicate Media files in an opposite order: " "['a', 'b', 'c'], ['a', 'c', 'b']" @@ -614,25 +654,31 @@ class FormsMediaTestCase(SimpleTestCase): merged._js def test_add_css_deduplication(self): - widget1 = Media(css={'screen': ['a.css'], 'all': ['b.css']}) - widget2 = Media(css={'screen': ['c.css']}) - widget3 = Media(css={'screen': ['a.css'], 'all': ['b.css', 'c.css']}) - widget4 = Media(css={'screen': ['a.css'], 'all': ['c.css', 'b.css']}) + widget1 = Media(css={"screen": ["a.css"], "all": ["b.css"]}) + widget2 = Media(css={"screen": ["c.css"]}) + widget3 = Media(css={"screen": ["a.css"], "all": ["b.css", "c.css"]}) + widget4 = Media(css={"screen": ["a.css"], "all": ["c.css", "b.css"]}) merged = widget1 + widget1 - self.assertEqual(merged._css_lists, [{'screen': ['a.css'], 'all': ['b.css']}]) - self.assertEqual(merged._css, {'screen': ['a.css'], 'all': ['b.css']}) + self.assertEqual(merged._css_lists, [{"screen": ["a.css"], "all": ["b.css"]}]) + self.assertEqual(merged._css, {"screen": ["a.css"], "all": ["b.css"]}) merged = widget1 + widget2 - self.assertEqual(merged._css_lists, [ - {'screen': ['a.css'], 'all': ['b.css']}, - {'screen': ['c.css']}, - ]) - self.assertEqual(merged._css, {'screen': ['a.css', 'c.css'], 'all': ['b.css']}) + self.assertEqual( + merged._css_lists, + [ + {"screen": ["a.css"], "all": ["b.css"]}, + {"screen": ["c.css"]}, + ], + ) + self.assertEqual(merged._css, {"screen": ["a.css", "c.css"], "all": ["b.css"]}) merged = widget3 + widget4 # Ordering within lists is preserved. - self.assertEqual(merged._css_lists, [ - {'screen': ['a.css'], 'all': ['b.css', 'c.css']}, - {'screen': ['a.css'], 'all': ['c.css', 'b.css']} - ]) + self.assertEqual( + merged._css_lists, + [ + {"screen": ["a.css"], "all": ["b.css", "c.css"]}, + {"screen": ["a.css"], "all": ["c.css", "b.css"]}, + ], + ) msg = ( "Detected duplicate Media files in an opposite order: " "['b.css', 'c.css'], ['c.css', 'b.css']" @@ -641,8 +687,8 @@ class FormsMediaTestCase(SimpleTestCase): merged._css def test_add_empty(self): - media = Media(css={'screen': ['a.css']}, js=['a']) + media = Media(css={"screen": ["a.css"]}, js=["a"]) empty_media = Media() merged = media + empty_media - self.assertEqual(merged._css_lists, [{'screen': ['a.css']}]) - self.assertEqual(merged._js_lists, [['a']]) + self.assertEqual(merged._css_lists, [{"screen": ["a.css"]}]) + self.assertEqual(merged._js_lists, [["a"]]) diff --git a/tests/forms_tests/tests/test_renderers.py b/tests/forms_tests/tests/test_renderers.py index 47452fa489..3e973ad8fc 100644 --- a/tests/forms_tests/tests/test_renderers.py +++ b/tests/forms_tests/tests/test_renderers.py @@ -2,7 +2,10 @@ import os import unittest from django.forms.renderers import ( - BaseRenderer, DjangoTemplates, Jinja2, TemplatesSetting, + BaseRenderer, + DjangoTemplates, + Jinja2, + TemplatesSetting, ) from django.test import SimpleTestCase @@ -13,38 +16,39 @@ except ImportError: class SharedTests: - expected_widget_dir = 'templates' + expected_widget_dir = "templates" def test_installed_apps_template_found(self): """Can find a custom template in INSTALLED_APPS.""" renderer = self.renderer() # Found because forms_tests is . - tpl = renderer.get_template('forms_tests/custom_widget.html') + tpl = renderer.get_template("forms_tests/custom_widget.html") expected_path = os.path.abspath( os.path.join( os.path.dirname(__file__), - '..', - self.expected_widget_dir + '/forms_tests/custom_widget.html', + "..", + self.expected_widget_dir + "/forms_tests/custom_widget.html", ) ) self.assertEqual(tpl.origin.name, expected_path) class BaseTemplateRendererTests(SimpleTestCase): - def test_get_renderer(self): - with self.assertRaisesMessage(NotImplementedError, 'subclasses must implement get_template()'): - BaseRenderer().get_template('') + with self.assertRaisesMessage( + NotImplementedError, "subclasses must implement get_template()" + ): + BaseRenderer().get_template("") class DjangoTemplatesTests(SharedTests, SimpleTestCase): renderer = DjangoTemplates -@unittest.skipIf(jinja2 is None, 'jinja2 required') +@unittest.skipIf(jinja2 is None, "jinja2 required") class Jinja2Tests(SharedTests, SimpleTestCase): renderer = Jinja2 - expected_widget_dir = 'jinja2' + expected_widget_dir = "jinja2" class TemplatesSettingTests(SharedTests, SimpleTestCase): diff --git a/tests/forms_tests/tests/test_utils.py b/tests/forms_tests/tests/test_utils.py index e0e9a0e22e..c4a2e5c651 100644 --- a/tests/forms_tests/tests/test_utils.py +++ b/tests/forms_tests/tests/test_utils.py @@ -16,28 +16,31 @@ class FormsUtilsTestCase(SimpleTestCase): # flatatt # ########### - self.assertEqual(flatatt({'id': "header"}), ' id="header"') - self.assertEqual(flatatt({'class': "news", 'title': "Read this"}), ' class="news" title="Read this"') + self.assertEqual(flatatt({"id": "header"}), ' id="header"') self.assertEqual( - flatatt({'class': "news", 'title': "Read this", 'required': "required"}), - ' class="news" required="required" title="Read this"' + flatatt({"class": "news", "title": "Read this"}), + ' class="news" title="Read this"', ) self.assertEqual( - flatatt({'class': "news", 'title': "Read this", 'required': True}), - ' class="news" title="Read this" required' + flatatt({"class": "news", "title": "Read this", "required": "required"}), + ' class="news" required="required" title="Read this"', ) self.assertEqual( - flatatt({'class': "news", 'title': "Read this", 'required': False}), - ' class="news" title="Read this"' + flatatt({"class": "news", "title": "Read this", "required": True}), + ' class="news" title="Read this" required', ) - self.assertEqual(flatatt({'class': None}), '') - self.assertEqual(flatatt({}), '') + self.assertEqual( + flatatt({"class": "news", "title": "Read this", "required": False}), + ' class="news" title="Read this"', + ) + self.assertEqual(flatatt({"class": None}), "") + self.assertEqual(flatatt({}), "") def test_flatatt_no_side_effects(self): """ flatatt() does not modify the dict passed in. """ - attrs = {'foo': 'bar', 'true': True, 'false': False} + attrs = {"foo": "bar", "true": True, "false": False} attrs_copy = copy.copy(attrs) self.assertEqual(attrs, attrs_copy) @@ -58,46 +61,62 @@ class FormsUtilsTestCase(SimpleTestCase): # Can take a string. self.assertHTMLEqual( str(ErrorList(ValidationError("There was an error.").messages)), - '' + '', ) # Can take a Unicode string. self.assertHTMLEqual( str(ErrorList(ValidationError("Not \u03C0.").messages)), - '' + '', ) # Can take a lazy string. self.assertHTMLEqual( str(ErrorList(ValidationError(gettext_lazy("Error.")).messages)), - '' + '', ) # Can take a list. self.assertHTMLEqual( str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), - '' + '', ) # Can take a dict. self.assertHTMLEqual( - str(ErrorList(sorted(ValidationError({'error_1': "1. Error one.", 'error_2': "2. Error two."}).messages))), - '' + str( + ErrorList( + sorted( + ValidationError( + {"error_1": "1. Error one.", "error_2": "2. Error two."} + ).messages + ) + ) + ), + '', ) # Can take a mixture in a list. self.assertHTMLEqual( - str(ErrorList(sorted(ValidationError([ - "1. First error.", - "2. Not \u03C0.", - gettext_lazy("3. Error."), - { - 'error_1': "4. First dict error.", - 'error_2': "5. Second dict error.", - }, - ]).messages))), + str( + ErrorList( + sorted( + ValidationError( + [ + "1. First error.", + "2. Not \u03C0.", + gettext_lazy("3. Error."), + { + "error_1": "4. First dict error.", + "error_2": "5. Second dict error.", + }, + ] + ).messages + ) + ) + ), '' + "
  • 1. First error.
  • " + "
  • 2. Not π.
  • " + "
  • 3. Error.
  • " + "
  • 4. First dict error.
  • " + "
  • 5. Second dict error.
  • " + "", ) class VeryBadError: @@ -107,7 +126,7 @@ class FormsUtilsTestCase(SimpleTestCase): # Can take a non-string. self.assertHTMLEqual( str(ErrorList(ValidationError(VeryBadError()).messages)), - '' + '', ) # Escapes non-safe input but not input marked safe. @@ -115,36 +134,38 @@ class FormsUtilsTestCase(SimpleTestCase): self.assertHTMLEqual( str(ErrorList([example])), '' + "<a href="http://www.example.com/">example</a>", ) self.assertHTMLEqual( str(ErrorList([mark_safe(example)])), '' + 'example', ) self.assertHTMLEqual( - str(ErrorDict({'name': example})), + str(ErrorDict({"name": example})), '' + "<a href="http://www.example.com/">example</a>", ) self.assertHTMLEqual( - str(ErrorDict({'name': mark_safe(example)})), + str(ErrorDict({"name": mark_safe(example)})), '' + 'example', ) def test_error_dict_copy(self): e = ErrorDict() - e['__all__'] = ErrorList([ - ValidationError( - message='message %(i)s', - params={'i': 1}, - ), - ValidationError( - message='message %(i)s', - params={'i': 2}, - ), - ]) + e["__all__"] = ErrorList( + [ + ValidationError( + message="message %(i)s", + params={"i": 1}, + ), + ValidationError( + message="message %(i)s", + params={"i": 2}, + ), + ] + ) e_copy = copy.copy(e) self.assertEqual(e, e_copy) @@ -155,56 +176,70 @@ class FormsUtilsTestCase(SimpleTestCase): def test_error_dict_html_safe(self): e = ErrorDict() - e['username'] = 'Invalid username.' - self.assertTrue(hasattr(ErrorDict, '__html__')) + e["username"] = "Invalid username." + self.assertTrue(hasattr(ErrorDict, "__html__")) self.assertEqual(str(e), e.__html__()) def test_error_list_html_safe(self): - e = ErrorList(['Invalid username.']) - self.assertTrue(hasattr(ErrorList, '__html__')) + e = ErrorList(["Invalid username."]) + self.assertTrue(hasattr(ErrorList, "__html__")) self.assertEqual(str(e), e.__html__()) def test_error_dict_is_dict(self): self.assertIsInstance(ErrorDict(), dict) def test_error_dict_is_json_serializable(self): - init_errors = ErrorDict([ - ('__all__', ErrorList([ - ValidationError('Sorry this form only works on leap days.') - ])), - ('name', ErrorList([ValidationError('This field is required.')])), - ]) - min_value_error_list = ErrorList([ - ValidationError('Ensure this value is greater than or equal to 0.') - ]) + init_errors = ErrorDict( + [ + ( + "__all__", + ErrorList( + [ValidationError("Sorry this form only works on leap days.")] + ), + ), + ("name", ErrorList([ValidationError("This field is required.")])), + ] + ) + min_value_error_list = ErrorList( + [ValidationError("Ensure this value is greater than or equal to 0.")] + ) e = ErrorDict( init_errors, - date=ErrorList([ - ErrorDict({ - 'day': min_value_error_list, - 'month': min_value_error_list, - 'year': min_value_error_list, - }), - ]), - ) - e['renderer'] = ErrorList([ - ValidationError( - 'Select a valid choice. That choice is not one of the ' - 'available choices.' + date=ErrorList( + [ + ErrorDict( + { + "day": min_value_error_list, + "month": min_value_error_list, + "year": min_value_error_list, + } + ), + ] ), - ]) - self.assertJSONEqual(json.dumps(e), { - '__all__': ['Sorry this form only works on leap days.'], - 'name': ['This field is required.'], - 'date': [ - { - 'day': ['Ensure this value is greater than or equal to 0.'], - 'month': ['Ensure this value is greater than or equal to 0.'], - 'year': ['Ensure this value is greater than or equal to 0.'], - }, - ], - 'renderer': [ - 'Select a valid choice. That choice is not one of the ' - 'available choices.' - ], - }) + ) + e["renderer"] = ErrorList( + [ + ValidationError( + "Select a valid choice. That choice is not one of the " + "available choices." + ), + ] + ) + self.assertJSONEqual( + json.dumps(e), + { + "__all__": ["Sorry this form only works on leap days."], + "name": ["This field is required."], + "date": [ + { + "day": ["Ensure this value is greater than or equal to 0."], + "month": ["Ensure this value is greater than or equal to 0."], + "year": ["Ensure this value is greater than or equal to 0."], + }, + ], + "renderer": [ + "Select a valid choice. That choice is not one of the " + "available choices." + ], + }, + ) diff --git a/tests/forms_tests/tests/test_validators.py b/tests/forms_tests/tests/test_validators.py index 2f26bbfbb7..731e1c9817 100644 --- a/tests/forms_tests/tests/test_validators.py +++ b/tests/forms_tests/tests/test_validators.py @@ -16,40 +16,42 @@ class TestFieldWithValidators(TestCase): validators=[ validators.validate_integer, validators.validate_email, - ] + ], ) string = forms.CharField( max_length=50, validators=[ validators.RegexValidator( - regex='^[a-zA-Z]*$', + regex="^[a-zA-Z]*$", message="Letters only.", ) - ] + ], ) ignore_case_string = forms.CharField( max_length=50, validators=[ validators.RegexValidator( - regex='^[a-z]*$', + regex="^[a-z]*$", message="Letters only.", flags=re.IGNORECASE, ) - ] + ], ) - form = UserForm({ - 'full_name': 'not int nor mail', - 'string': '2 is not correct', - 'ignore_case_string': "IgnORE Case strIng", - }) + form = UserForm( + { + "full_name": "not int nor mail", + "string": "2 is not correct", + "ignore_case_string": "IgnORE Case strIng", + } + ) with self.assertRaises(ValidationError) as e: - form.fields['full_name'].clean('not int nor mail') + form.fields["full_name"].clean("not int nor mail") self.assertEqual(2, len(e.exception.messages)) self.assertFalse(form.is_valid()) - self.assertEqual(form.errors['string'], ["Letters only."]) - self.assertEqual(form.errors['string'], ["Letters only."]) + self.assertEqual(form.errors["string"], ["Letters only."]) + self.assertEqual(form.errors["string"], ["Letters only."]) def test_field_validators_can_be_any_iterable(self): class UserForm(forms.Form): @@ -58,39 +60,42 @@ class TestFieldWithValidators(TestCase): validators=( validators.validate_integer, validators.validate_email, - ) + ), ) - form = UserForm({'full_name': 'not int nor mail'}) + form = UserForm({"full_name": "not int nor mail"}) self.assertFalse(form.is_valid()) - self.assertEqual(form.errors['full_name'], ['Enter a valid integer.', 'Enter a valid email address.']) + self.assertEqual( + form.errors["full_name"], + ["Enter a valid integer.", "Enter a valid email address."], + ) class ValidatorCustomMessageTests(TestCase): def test_value_placeholder_with_char_field(self): cases = [ - (validators.validate_integer, '-42.5', 'invalid'), - (validators.validate_email, 'a', 'invalid'), - (validators.validate_email, 'a@b\n.com', 'invalid'), - (validators.validate_email, 'a\n@b.com', 'invalid'), - (validators.validate_slug, '你 好', 'invalid'), - (validators.validate_unicode_slug, '你 好', 'invalid'), - (validators.validate_ipv4_address, '256.1.1.1', 'invalid'), - (validators.validate_ipv6_address, '1:2', 'invalid'), - (validators.validate_ipv46_address, '256.1.1.1', 'invalid'), - (validators.validate_comma_separated_integer_list, 'a,b,c', 'invalid'), - (validators.int_list_validator(), '-1,2,3', 'invalid'), - (validators.MaxLengthValidator(10), 11 * 'x', 'max_length'), - (validators.MinLengthValidator(10), 9 * 'x', 'min_length'), - (validators.URLValidator(), 'no_scheme', 'invalid'), - (validators.URLValidator(), 'http://test[.com', 'invalid'), - (validators.URLValidator(), 'http://[::1:2::3]/', 'invalid'), + (validators.validate_integer, "-42.5", "invalid"), + (validators.validate_email, "a", "invalid"), + (validators.validate_email, "a@b\n.com", "invalid"), + (validators.validate_email, "a\n@b.com", "invalid"), + (validators.validate_slug, "你 好", "invalid"), + (validators.validate_unicode_slug, "你 好", "invalid"), + (validators.validate_ipv4_address, "256.1.1.1", "invalid"), + (validators.validate_ipv6_address, "1:2", "invalid"), + (validators.validate_ipv46_address, "256.1.1.1", "invalid"), + (validators.validate_comma_separated_integer_list, "a,b,c", "invalid"), + (validators.int_list_validator(), "-1,2,3", "invalid"), + (validators.MaxLengthValidator(10), 11 * "x", "max_length"), + (validators.MinLengthValidator(10), 9 * "x", "min_length"), + (validators.URLValidator(), "no_scheme", "invalid"), + (validators.URLValidator(), "http://test[.com", "invalid"), + (validators.URLValidator(), "http://[::1:2::3]/", "invalid"), ( validators.URLValidator(), - 'http://' + '.'.join(['a' * 35 for _ in range(9)]), - 'invalid', + "http://" + ".".join(["a" * 35 for _ in range(9)]), + "invalid", ), - (validators.RegexValidator('[0-9]+'), 'xxxxxx', 'invalid'), + (validators.RegexValidator("[0-9]+"), "xxxxxx", "invalid"), ] for validator, value, code in cases: if isinstance(validator, types.FunctionType): @@ -98,71 +103,74 @@ class ValidatorCustomMessageTests(TestCase): else: name = type(validator).__name__ with self.subTest(name, value=value): + class MyForm(forms.Form): field = forms.CharField( validators=[validator], - error_messages={code: '%(value)s'}, + error_messages={code: "%(value)s"}, ) - form = MyForm({'field': value}) + form = MyForm({"field": value}) self.assertIs(form.is_valid(), False) - self.assertEqual(form.errors, {'field': [value]}) + self.assertEqual(form.errors, {"field": [value]}) def test_value_placeholder_with_null_character(self): class MyForm(forms.Form): field = forms.CharField( - error_messages={'null_characters_not_allowed': '%(value)s'}, + error_messages={"null_characters_not_allowed": "%(value)s"}, ) - form = MyForm({'field': 'a\0b'}) + form = MyForm({"field": "a\0b"}) self.assertIs(form.is_valid(), False) - self.assertEqual(form.errors, {'field': ['a\x00b']}) + self.assertEqual(form.errors, {"field": ["a\x00b"]}) def test_value_placeholder_with_integer_field(self): cases = [ - (validators.MaxValueValidator(0), 1, 'max_value'), - (validators.MinValueValidator(0), -1, 'min_value'), - (validators.URLValidator(), '1', 'invalid'), + (validators.MaxValueValidator(0), 1, "max_value"), + (validators.MinValueValidator(0), -1, "min_value"), + (validators.URLValidator(), "1", "invalid"), ] for validator, value, code in cases: with self.subTest(type(validator).__name__, value=value): + class MyForm(forms.Form): field = forms.IntegerField( validators=[validator], - error_messages={code: '%(value)s'}, + error_messages={code: "%(value)s"}, ) - form = MyForm({'field': value}) + form = MyForm({"field": value}) self.assertIs(form.is_valid(), False) - self.assertEqual(form.errors, {'field': [str(value)]}) + self.assertEqual(form.errors, {"field": [str(value)]}) def test_value_placeholder_with_decimal_field(self): cases = [ - ('NaN', 'invalid'), - ('123', 'max_digits'), - ('0.12', 'max_decimal_places'), - ('12', 'max_whole_digits'), + ("NaN", "invalid"), + ("123", "max_digits"), + ("0.12", "max_decimal_places"), + ("12", "max_whole_digits"), ] for value, code in cases: with self.subTest(value=value): + class MyForm(forms.Form): field = forms.DecimalField( max_digits=2, decimal_places=1, - error_messages={code: '%(value)s'}, + error_messages={code: "%(value)s"}, ) - form = MyForm({'field': value}) + form = MyForm({"field": value}) self.assertIs(form.is_valid(), False) - self.assertEqual(form.errors, {'field': [value]}) + self.assertEqual(form.errors, {"field": [value]}) def test_value_placeholder_with_file_field(self): class MyForm(forms.Form): field = forms.FileField( validators=[validators.validate_image_file_extension], - error_messages={'invalid_extension': '%(value)s'}, + error_messages={"invalid_extension": "%(value)s"}, ) - form = MyForm(files={'field': SimpleUploadedFile('myfile.txt', b'abc')}) + form = MyForm(files={"field": SimpleUploadedFile("myfile.txt", b"abc")}) self.assertIs(form.is_valid(), False) - self.assertEqual(form.errors, {'field': ['myfile.txt']}) + self.assertEqual(form.errors, {"field": ["myfile.txt"]}) diff --git a/tests/forms_tests/tests/test_widgets.py b/tests/forms_tests/tests/test_widgets.py index f429f92547..e28c1f2462 100644 --- a/tests/forms_tests/tests/test_widgets.py +++ b/tests/forms_tests/tests/test_widgets.py @@ -5,18 +5,21 @@ from django.urls import reverse from ..models import Article -@override_settings(ROOT_URLCONF='forms_tests.urls') +@override_settings(ROOT_URLCONF="forms_tests.urls") class LiveWidgetTests(AdminSeleniumTestCase): - available_apps = ['forms_tests'] + AdminSeleniumTestCase.available_apps + available_apps = ["forms_tests"] + AdminSeleniumTestCase.available_apps def test_textarea_trailing_newlines(self): """ A roundtrip on a ModelForm doesn't alter the TextField value """ from selenium.webdriver.common.by import By + article = Article.objects.create(content="\nTst\n") - self.selenium.get(self.live_server_url + reverse('article_form', args=[article.pk])) - self.selenium.find_element(By.ID, 'submit').click() + self.selenium.get( + self.live_server_url + reverse("article_form", args=[article.pk]) + ) + self.selenium.find_element(By.ID, "submit").click() article = Article.objects.get(pk=article.pk) self.assertEqual(article.content, "\r\nTst\r\n") diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py index 24ae09a800..5a860037e5 100644 --- a/tests/forms_tests/tests/tests.py +++ b/tests/forms_tests/tests/tests.py @@ -7,8 +7,13 @@ from django.forms.models import ModelFormMetaclass from django.test import SimpleTestCase, TestCase from ..models import ( - BoundaryModel, ChoiceFieldModel, ChoiceModel, ChoiceOptionModel, Defaults, - FileModel, OptionalMultiChoiceModel, + BoundaryModel, + ChoiceFieldModel, + ChoiceModel, + ChoiceOptionModel, + Defaults, + FileModel, + OptionalMultiChoiceModel, ) from . import jinja2_tests @@ -16,39 +21,39 @@ from . import jinja2_tests class ChoiceFieldForm(ModelForm): class Meta: model = ChoiceFieldModel - fields = '__all__' + fields = "__all__" class OptionalMultiChoiceModelForm(ModelForm): class Meta: model = OptionalMultiChoiceModel - fields = '__all__' + fields = "__all__" class ChoiceFieldExclusionForm(ModelForm): multi_choice = CharField(max_length=50) class Meta: - exclude = ['multi_choice'] + exclude = ["multi_choice"] model = ChoiceFieldModel class EmptyCharLabelChoiceForm(ModelForm): class Meta: model = ChoiceModel - fields = ['name', 'choice'] + fields = ["name", "choice"] class EmptyIntegerLabelChoiceForm(ModelForm): class Meta: model = ChoiceModel - fields = ['name', 'choice_integer'] + fields = ["name", "choice_integer"] class EmptyCharLabelNoneChoiceForm(ModelForm): class Meta: model = ChoiceModel - fields = ['name', 'choice_string_w_none'] + fields = ["name", "choice_string_w_none"] class FileForm(Form): @@ -59,31 +64,36 @@ class TestTicket14567(TestCase): """ The return values of ModelMultipleChoiceFields are QuerySets """ + def test_empty_queryset_return(self): "If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned." - option = ChoiceOptionModel.objects.create(name='default') - form = OptionalMultiChoiceModelForm({'multi_choice_optional': '', 'multi_choice': [option.pk]}) + option = ChoiceOptionModel.objects.create(name="default") + form = OptionalMultiChoiceModelForm( + {"multi_choice_optional": "", "multi_choice": [option.pk]} + ) self.assertTrue(form.is_valid()) # The empty value is a QuerySet - self.assertIsInstance(form.cleaned_data['multi_choice_optional'], models.query.QuerySet) + self.assertIsInstance( + form.cleaned_data["multi_choice_optional"], models.query.QuerySet + ) # While we're at it, test whether a QuerySet is returned if there *is* a value. - self.assertIsInstance(form.cleaned_data['multi_choice'], models.query.QuerySet) + self.assertIsInstance(form.cleaned_data["multi_choice"], models.query.QuerySet) class ModelFormCallableModelDefault(TestCase): def test_no_empty_option(self): "If a model's ForeignKey has blank=False and a default, no empty option is created (Refs #10792)." - option = ChoiceOptionModel.objects.create(name='default') + option = ChoiceOptionModel.objects.create(name="default") - choices = list(ChoiceFieldForm().fields['choice'].choices) + choices = list(ChoiceFieldForm().fields["choice"].choices) self.assertEqual(len(choices), 1) self.assertEqual(choices[0], (option.pk, str(option))) def test_callable_initial_value(self): "The initial value for a callable default returning a queryset is the pk (refs #13769)" - ChoiceOptionModel.objects.create(id=1, name='default') - ChoiceOptionModel.objects.create(id=2, name='option 2') - ChoiceOptionModel.objects.create(id=3, name='option 3') + ChoiceOptionModel.objects.create(id=1, name="default") + ChoiceOptionModel.objects.create(id=2, name="option 2") + ChoiceOptionModel.objects.create(id=3, name="option 3") self.assertHTMLEqual( ChoiceFieldForm().as_p(), """

    """ +

    """, ) def test_initial_instance_value(self): "Initial instances for model fields may also be instances (refs #7287)" - ChoiceOptionModel.objects.create(id=1, name='default') - obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') - obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') + ChoiceOptionModel.objects.create(id=1, name="default") + obj2 = ChoiceOptionModel.objects.create(id=2, name="option 2") + obj3 = ChoiceOptionModel.objects.create(id=3, name="option 3") self.assertHTMLEqual( - ChoiceFieldForm(initial={ - 'choice': obj2, - 'choice_int': obj2, - 'multi_choice': [obj2, obj3], - 'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"), - }).as_p(), + ChoiceFieldForm( + initial={ + "choice": obj2, + "choice_int": obj2, + "multi_choice": [obj2, obj3], + "multi_choice_int": ChoiceOptionModel.objects.exclude( + name="default" + ), + } + ).as_p(), """

    -

    """ +

    """, ) class FormsModelTestCase(TestCase): def test_unicode_filename(self): # FileModel with Unicode filename and data ######################### - file1 = SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह'.encode()) - f = FileForm(data={}, files={'file1': file1}, auto_id=False) + file1 = SimpleUploadedFile( + "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() + ) + f = FileForm(data={}, files={"file1": file1}, auto_id=False) self.assertTrue(f.is_valid()) - self.assertIn('file1', f.cleaned_data) - m = FileModel.objects.create(file=f.cleaned_data['file1']) - self.assertEqual(m.file.name, 'tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt') + self.assertIn("file1", f.cleaned_data) + m = FileModel.objects.create(file=f.cleaned_data["file1"]) + self.assertEqual( + m.file.name, + "tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt", + ) m.delete() def test_boundary_conditions(self): @@ -165,13 +184,13 @@ class FormsModelTestCase(TestCase): class BoundaryForm(ModelForm): class Meta: model = BoundaryModel - fields = '__all__' + fields = "__all__" - f = BoundaryForm({'positive_integer': 100}) + f = BoundaryForm({"positive_integer": 100}) self.assertTrue(f.is_valid()) - f = BoundaryForm({'positive_integer': 0}) + f = BoundaryForm({"positive_integer": 0}) self.assertTrue(f.is_valid()) - f = BoundaryForm({'positive_integer': -100}) + f = BoundaryForm({"positive_integer": -100}) self.assertFalse(f.is_valid()) def test_formfield_initial(self): @@ -181,22 +200,26 @@ class FormsModelTestCase(TestCase): class DefaultsForm(ModelForm): class Meta: model = Defaults - fields = '__all__' + fields = "__all__" - self.assertEqual(DefaultsForm().fields['name'].initial, 'class default value') - self.assertEqual(DefaultsForm().fields['def_date'].initial, datetime.date(1980, 1, 1)) - self.assertEqual(DefaultsForm().fields['value'].initial, 42) - r1 = DefaultsForm()['callable_default'].as_widget() - r2 = DefaultsForm()['callable_default'].as_widget() + self.assertEqual(DefaultsForm().fields["name"].initial, "class default value") + self.assertEqual( + DefaultsForm().fields["def_date"].initial, datetime.date(1980, 1, 1) + ) + self.assertEqual(DefaultsForm().fields["value"].initial, 42) + r1 = DefaultsForm()["callable_default"].as_widget() + r2 = DefaultsForm()["callable_default"].as_widget() self.assertNotEqual(r1, r2) # In a ModelForm that is passed an instance, the initial values come from the # instance's values, not the model's defaults. - foo_instance = Defaults(name='instance value', def_date=datetime.date(1969, 4, 4), value=12) + foo_instance = Defaults( + name="instance value", def_date=datetime.date(1969, 4, 4), value=12 + ) instance_form = DefaultsForm(instance=foo_instance) - self.assertEqual(instance_form.initial['name'], 'instance value') - self.assertEqual(instance_form.initial['def_date'], datetime.date(1969, 4, 4)) - self.assertEqual(instance_form.initial['value'], 12) + self.assertEqual(instance_form.initial["name"], "instance value") + self.assertEqual(instance_form.initial["def_date"], datetime.date(1969, 4, 4)) + self.assertEqual(instance_form.initial["value"], 12) from django.forms import CharField @@ -205,13 +228,15 @@ class FormsModelTestCase(TestCase): class Meta: model = Defaults - exclude = ['name', 'callable_default'] + exclude = ["name", "callable_default"] - f = ExcludingForm({'name': 'Hello', 'value': 99, 'def_date': datetime.date(1999, 3, 2)}) + f = ExcludingForm( + {"name": "Hello", "value": 99, "def_date": datetime.date(1999, 3, 2)} + ) self.assertTrue(f.is_valid()) - self.assertEqual(f.cleaned_data['name'], 'Hello') + self.assertEqual(f.cleaned_data["name"], "Hello") obj = f.save() - self.assertEqual(obj.name, 'class default value') + self.assertEqual(obj.name, "class default value") self.assertEqual(obj.value, 99) self.assertEqual(obj.def_date, datetime.date(1999, 3, 2)) @@ -221,19 +246,20 @@ class RelatedModelFormTests(SimpleTestCase): """ Test for issue 10405 """ + class A(models.Model): ref = models.ForeignKey("B", models.CASCADE) class Meta: model = A - fields = '__all__' + fields = "__all__" msg = ( "Cannot create form field for 'ref' yet, because " "its related model 'B' has not been loaded yet" ) with self.assertRaisesMessage(ValueError, msg): - ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta}) + ModelFormMetaclass("Form", (ModelForm,), {"Meta": Meta}) class B(models.Model): pass @@ -242,6 +268,7 @@ class RelatedModelFormTests(SimpleTestCase): """ Test for issue 10405 """ + class C(models.Model): ref = models.ForeignKey("D", models.CASCADE) @@ -250,38 +277,45 @@ class RelatedModelFormTests(SimpleTestCase): class Meta: model = C - fields = '__all__' + fields = "__all__" - self.assertTrue(issubclass(ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta}), ModelForm)) + self.assertTrue( + issubclass( + ModelFormMetaclass("Form", (ModelForm,), {"Meta": Meta}), ModelForm + ) + ) class ManyToManyExclusionTestCase(TestCase): def test_m2m_field_exclusion(self): # Issue 12337. save_instance should honor the passed-in exclude keyword. - opt1 = ChoiceOptionModel.objects.create(id=1, name='default') - opt2 = ChoiceOptionModel.objects.create(id=2, name='option 2') - opt3 = ChoiceOptionModel.objects.create(id=3, name='option 3') + opt1 = ChoiceOptionModel.objects.create(id=1, name="default") + opt2 = ChoiceOptionModel.objects.create(id=2, name="option 2") + opt3 = ChoiceOptionModel.objects.create(id=3, name="option 3") initial = { - 'choice': opt1, - 'choice_int': opt1, + "choice": opt1, + "choice_int": opt1, } data = { - 'choice': opt2.pk, - 'choice_int': opt2.pk, - 'multi_choice': 'string data!', - 'multi_choice_int': [opt1.pk], + "choice": opt2.pk, + "choice_int": opt2.pk, + "multi_choice": "string data!", + "multi_choice_int": [opt1.pk], } instance = ChoiceFieldModel.objects.create(**initial) instance.multi_choice.set([opt2, opt3]) instance.multi_choice_int.set([opt2, opt3]) form = ChoiceFieldExclusionForm(data=data, instance=instance) self.assertTrue(form.is_valid()) - self.assertEqual(form.cleaned_data['multi_choice'], data['multi_choice']) + self.assertEqual(form.cleaned_data["multi_choice"], data["multi_choice"]) form.save() - self.assertEqual(form.instance.choice.pk, data['choice']) - self.assertEqual(form.instance.choice_int.pk, data['choice_int']) + self.assertEqual(form.instance.choice.pk, data["choice"]) + self.assertEqual(form.instance.choice_int.pk, data["choice_int"]) self.assertEqual(list(form.instance.multi_choice.all()), [opt2, opt3]) - self.assertEqual([obj.pk for obj in form.instance.multi_choice_int.all()], data['multi_choice_int']) + self.assertEqual( + [obj.pk for obj in form.instance.multi_choice_int.all()], + data["multi_choice_int"], + ) class EmptyLabelTestCase(TestCase): @@ -294,7 +328,7 @@ class EmptyLabelTestCase(TestCase): -

    """ +

    """, ) def test_empty_field_char_none(self): @@ -307,25 +341,27 @@ class EmptyLabelTestCase(TestCase): -

    """ +

    """, ) def test_save_empty_label_forms(self): # Saving a form with a blank choice results in the expected # value being stored in the database. tests = [ - (EmptyCharLabelNoneChoiceForm, 'choice_string_w_none', None), - (EmptyIntegerLabelChoiceForm, 'choice_integer', None), - (EmptyCharLabelChoiceForm, 'choice', ''), + (EmptyCharLabelNoneChoiceForm, "choice_string_w_none", None), + (EmptyIntegerLabelChoiceForm, "choice_integer", None), + (EmptyCharLabelChoiceForm, "choice", ""), ] for form, key, expected in tests: with self.subTest(form=form): - f = form({'name': 'some-key', key: ''}) + f = form({"name": "some-key", key: ""}) self.assertTrue(f.is_valid()) m = f.save() self.assertEqual(expected, getattr(m, key)) - self.assertEqual('No Preference', getattr(m, 'get_{}_display'.format(key))()) + self.assertEqual( + "No Preference", getattr(m, "get_{}_display".format(key))() + ) def test_empty_field_integer(self): f = EmptyIntegerLabelChoiceForm() @@ -337,16 +373,16 @@ class EmptyLabelTestCase(TestCase): -

    """ +

    """, ) def test_get_display_value_on_none(self): - m = ChoiceModel.objects.create(name='test', choice='', choice_integer=None) + m = ChoiceModel.objects.create(name="test", choice="", choice_integer=None) self.assertIsNone(m.choice_integer) - self.assertEqual('No Preference', m.get_choice_integer_display()) + self.assertEqual("No Preference", m.get_choice_integer_display()) def test_html_rendering_of_prepopulated_models(self): - none_model = ChoiceModel(name='none-test', choice_integer=None) + none_model = ChoiceModel(name="none-test", choice_integer=None) f = EmptyIntegerLabelChoiceForm(instance=none_model) self.assertHTMLEqual( f.as_p(), @@ -357,10 +393,10 @@ class EmptyLabelTestCase(TestCase): -

    """ +

    """, ) - foo_model = ChoiceModel(name='foo-test', choice_integer=1) + foo_model = ChoiceModel(name="foo-test", choice_integer=1) f = EmptyIntegerLabelChoiceForm(instance=foo_model) self.assertHTMLEqual( f.as_p(), @@ -371,7 +407,7 @@ class EmptyLabelTestCase(TestCase): -

    """ +

    """, ) diff --git a/tests/forms_tests/urls.py b/tests/forms_tests/urls.py index 7e27927099..4063568a81 100644 --- a/tests/forms_tests/urls.py +++ b/tests/forms_tests/urls.py @@ -3,6 +3,6 @@ from django.urls import path from .views import ArticleFormView, form_view urlpatterns = [ - path('form_view/', form_view, name='form_view'), - path('model_form//', ArticleFormView.as_view(), name='article_form'), + path("form_view/", form_view, name="form_view"), + path("model_form//", ArticleFormView.as_view(), name="article_form"), ] diff --git a/tests/forms_tests/views.py b/tests/forms_tests/views.py index 20f1bf161d..b03472824d 100644 --- a/tests/forms_tests/views.py +++ b/tests/forms_tests/views.py @@ -11,12 +11,12 @@ class ArticleForm(forms.ModelForm): class Meta: model = Article - fields = '__all__' + fields = "__all__" class ArticleFormView(UpdateView): model = Article - success_url = '/' + success_url = "/" form_class = ArticleForm @@ -24,6 +24,6 @@ def form_view(request): class Form(forms.Form): number = forms.FloatField() - template = Template('{{ form }}') - context = Context({'form': Form()}) + template = Template("{{ form }}") + context = Context({"form": Form()}) return HttpResponse(template.render(context)) diff --git a/tests/forms_tests/widget_tests/base.py b/tests/forms_tests/widget_tests/base.py index 339d78bc71..c29099abf2 100644 --- a/tests/forms_tests/widget_tests/base.py +++ b/tests/forms_tests/widget_tests/base.py @@ -8,24 +8,32 @@ except ImportError: class WidgetTest(SimpleTestCase): - beatles = (('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')) + beatles = (("J", "John"), ("P", "Paul"), ("G", "George"), ("R", "Ringo")) @classmethod def setUpClass(cls): cls.django_renderer = DjangoTemplates() cls.jinja2_renderer = Jinja2() if jinja2 else None - cls.renderers = [cls.django_renderer] + ([cls.jinja2_renderer] if cls.jinja2_renderer else []) + cls.renderers = [cls.django_renderer] + ( + [cls.jinja2_renderer] if cls.jinja2_renderer else [] + ) super().setUpClass() - def check_html(self, widget, name, value, html='', attrs=None, strict=False, **kwargs): + def check_html( + self, widget, name, value, html="", attrs=None, strict=False, **kwargs + ): assertEqual = self.assertEqual if strict else self.assertHTMLEqual if self.jinja2_renderer: - output = widget.render(name, value, attrs=attrs, renderer=self.jinja2_renderer, **kwargs) + output = widget.render( + name, value, attrs=attrs, renderer=self.jinja2_renderer, **kwargs + ) # Django escapes quotes with '"' while Jinja2 uses '"'. - output = output.replace('"', '"') + output = output.replace(""", """) # Django escapes single quotes with ''' while Jinja2 uses '''. - output = output.replace(''', ''') + output = output.replace("'", "'") assertEqual(output, html) - output = widget.render(name, value, attrs=attrs, renderer=self.django_renderer, **kwargs) + output = widget.render( + name, value, attrs=attrs, renderer=self.django_renderer, **kwargs + ) assertEqual(output, html) diff --git a/tests/forms_tests/widget_tests/test_checkboxinput.py b/tests/forms_tests/widget_tests/test_checkboxinput.py index 8dba2178c9..0f65e876df 100644 --- a/tests/forms_tests/widget_tests/test_checkboxinput.py +++ b/tests/forms_tests/widget_tests/test_checkboxinput.py @@ -7,18 +7,26 @@ class CheckboxInputTest(WidgetTest): widget = CheckboxInput() def test_render_empty(self): - self.check_html(self.widget, 'is_cool', '', html='') + self.check_html( + self.widget, "is_cool", "", html='' + ) def test_render_none(self): - self.check_html(self.widget, 'is_cool', None, html='') + self.check_html( + self.widget, "is_cool", None, html='' + ) def test_render_false(self): - self.check_html(self.widget, 'is_cool', False, html='') + self.check_html( + self.widget, "is_cool", False, html='' + ) def test_render_true(self): self.check_html( - self.widget, 'is_cool', True, - html='' + self.widget, + "is_cool", + True, + html='', ) def test_render_value(self): @@ -27,7 +35,9 @@ class CheckboxInputTest(WidgetTest): checkbox and set the 'value' attribute. """ self.check_html( - self.widget, 'is_cool', 'foo', + self.widget, + "is_cool", + "foo", html='', ) @@ -36,11 +46,15 @@ class CheckboxInputTest(WidgetTest): Integers are handled by value, not as booleans (#17114). """ self.check_html( - self.widget, 'is_cool', 0, + self.widget, + "is_cool", + 0, html='', ) self.check_html( - self.widget, 'is_cool', 1, + self.widget, + "is_cool", + 1, html='', ) @@ -49,30 +63,43 @@ class CheckboxInputTest(WidgetTest): You can pass 'check_test' to the constructor. This is a callable that takes the value and returns True if the box should be checked. """ - widget = CheckboxInput(check_test=lambda value: value.startswith('hello')) - self.check_html(widget, 'greeting', '', html=( - '' - )) - self.check_html(widget, 'greeting', 'hello', html=( - '' - )) - self.check_html(widget, 'greeting', 'hello there', html=( - '' - )) - self.check_html(widget, 'greeting', 'hello & goodbye', html=( - '' - )) + widget = CheckboxInput(check_test=lambda value: value.startswith("hello")) + self.check_html( + widget, "greeting", "", html=('') + ) + self.check_html( + widget, + "greeting", + "hello", + html=(''), + ) + self.check_html( + widget, + "greeting", + "hello there", + html=( + '' + ), + ) + self.check_html( + widget, + "greeting", + "hello & goodbye", + html=( + '' + ), + ) def test_render_check_exception(self): """ Calling check_test() shouldn't swallow exceptions (#17888). """ widget = CheckboxInput( - check_test=lambda value: value.startswith('hello'), + check_test=lambda value: value.startswith("hello"), ) with self.assertRaises(AttributeError): - widget.render('greeting', True) + widget.render("greeting", True) def test_value_from_datadict(self): """ @@ -80,17 +107,19 @@ class CheckboxInputTest(WidgetTest): the data dictionary (because HTML form submission doesn't send any result for unchecked checkboxes). """ - self.assertFalse(self.widget.value_from_datadict({}, {}, 'testing')) + self.assertFalse(self.widget.value_from_datadict({}, {}, "testing")) def test_value_from_datadict_string_int(self): - value = self.widget.value_from_datadict({'testing': '0'}, {}, 'testing') + value = self.widget.value_from_datadict({"testing": "0"}, {}, "testing") self.assertIs(value, True) def test_value_omitted_from_data(self): - self.assertIs(self.widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False) - self.assertIs(self.widget.value_omitted_from_data({}, {}, 'field'), False) + self.assertIs( + self.widget.value_omitted_from_data({"field": "value"}, {}, "field"), False + ) + self.assertIs(self.widget.value_omitted_from_data({}, {}, "field"), False) def test_get_context_does_not_mutate_attrs(self): - attrs = {'checked': False} - self.widget.get_context('name', True, attrs) - self.assertIs(attrs['checked'], False) + attrs = {"checked": False} + self.widget.get_context("name", True, attrs) + self.assertIs(attrs["checked"], False) diff --git a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py index 65025ed748..35db8192ef 100644 --- a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py +++ b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py @@ -11,31 +11,45 @@ class CheckboxSelectMultipleTest(WidgetTest): widget = CheckboxSelectMultiple def test_render_value(self): - self.check_html(self.widget(choices=self.beatles), 'beatles', ['J'], html=""" + self.check_html( + self.widget(choices=self.beatles), + "beatles", + ["J"], + html="""
    - """) + """, + ) def test_render_value_multiple(self): - self.check_html(self.widget(choices=self.beatles), 'beatles', ['J', 'P'], html=""" + self.check_html( + self.widget(choices=self.beatles), + "beatles", + ["J", "P"], + html="""
    - """) + """, + ) def test_render_none(self): """ If the value is None, none of the options are selected, even if the choices have an empty option. """ - self.check_html(self.widget(choices=(('', 'Unknown'),) + self.beatles), 'beatles', None, html=""" + self.check_html( + self.widget(choices=(("", "Unknown"),) + self.beatles), + "beatles", + None, + html="""
    @@ -43,13 +57,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
    - """) + """, + ) def test_nested_choices(self): nested_choices = ( - ('unknown', 'Unknown'), - ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), - ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), + ("unknown", "Unknown"), + ("Audio", (("vinyl", "Vinyl"), ("cd", "CD"))), + ("Video", (("vhs", "VHS"), ("dvd", "DVD"))), ) html = """
    @@ -71,15 +86,18 @@ class CheckboxSelectMultipleTest(WidgetTest):
    """ self.check_html( - self.widget(choices=nested_choices), 'nestchoice', ('vinyl', 'dvd'), - attrs={'id': 'media'}, html=html, + self.widget(choices=nested_choices), + "nestchoice", + ("vinyl", "dvd"), + attrs={"id": "media"}, + html=html, ) def test_nested_choices_without_id(self): nested_choices = ( - ('unknown', 'Unknown'), - ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), - ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), + ("unknown", "Unknown"), + ("Audio", (("vinyl", "Vinyl"), ("cd", "CD"))), + ("Video", (("vhs", "VHS"), ("dvd", "DVD"))), ) html = """
    @@ -95,13 +113,18 @@ class CheckboxSelectMultipleTest(WidgetTest):
    """ - self.check_html(self.widget(choices=nested_choices), 'nestchoice', ('vinyl', 'dvd'), html=html) + self.check_html( + self.widget(choices=nested_choices), + "nestchoice", + ("vinyl", "dvd"), + html=html, + ) def test_separate_ids(self): """ Each input gets a separate ID. """ - choices = [('a', 'A'), ('b', 'B'), ('c', 'C')] + choices = [("a", "A"), ("b", "B"), ("c", "C")] html = """
    @@ -113,13 +136,21 @@ class CheckboxSelectMultipleTest(WidgetTest):
    """ - self.check_html(self.widget(choices=choices), 'letters', ['a', 'c'], attrs={'id': 'abc'}, html=html) + self.check_html( + self.widget(choices=choices), + "letters", + ["a", "c"], + attrs={"id": "abc"}, + html=html, + ) def test_separate_ids_constructor(self): """ Each input gets a separate ID when the ID is passed to the constructor. """ - widget = CheckboxSelectMultiple(attrs={'id': 'abc'}, choices=[('a', 'A'), ('b', 'B'), ('c', 'C')]) + widget = CheckboxSelectMultiple( + attrs={"id": "abc"}, choices=[("a", "A"), ("b", "B"), ("c", "C")] + ) html = """
    @@ -131,14 +162,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
    """ - self.check_html(widget, 'letters', ['a', 'c'], html=html) + self.check_html(widget, "letters", ["a", "c"], html=html) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_doesnt_localize_input_value(self): choices = [ - (1, 'One'), - (1000, 'One thousand'), - (1000000, 'One million'), + (1, "One"), + (1000, "One thousand"), + (1000000, "One million"), ] html = """
    @@ -147,11 +178,11 @@ class CheckboxSelectMultipleTest(WidgetTest):
    """ - self.check_html(self.widget(choices=choices), 'numbers', None, html=html) + self.check_html(self.widget(choices=choices), "numbers", None, html=html) choices = [ - (datetime.time(0, 0), 'midnight'), - (datetime.time(12, 0), 'noon'), + (datetime.time(0, 0), "midnight"), + (datetime.time(12, 0), "noon"), ] html = """
    @@ -159,7 +190,7 @@ class CheckboxSelectMultipleTest(WidgetTest):
    """ - self.check_html(self.widget(choices=choices), 'times', None, html=html) + self.check_html(self.widget(choices=choices), "times", None, html=html) def test_use_required_attribute(self): widget = self.widget(choices=self.beatles) @@ -167,22 +198,25 @@ class CheckboxSelectMultipleTest(WidgetTest): # to be checked instead of at least one. self.assertIs(widget.use_required_attribute(None), False) self.assertIs(widget.use_required_attribute([]), False) - self.assertIs(widget.use_required_attribute(['J', 'P']), False) + self.assertIs(widget.use_required_attribute(["J", "P"]), False) def test_value_omitted_from_data(self): widget = self.widget(choices=self.beatles) - self.assertIs(widget.value_omitted_from_data({}, {}, 'field'), False) - self.assertIs(widget.value_omitted_from_data({'field': 'value'}, {}, 'field'), False) + self.assertIs(widget.value_omitted_from_data({}, {}, "field"), False) + self.assertIs( + widget.value_omitted_from_data({"field": "value"}, {}, "field"), False + ) def test_label(self): """ CheckboxSelectMultiple doesn't contain 'for="field_0"' in the