summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorMariusz Felisiak <felisiak.mariusz@gmail.com>2022-02-08 12:27:04 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2022-02-08 19:25:02 +0100
commit3278c31fa59b41d03aea167f4cf85f4ddf7f848d (patch)
tree0c80b4868391296335580242c8e65052a4f62a6b /tests
parent6a682b38e75d4c975b4c4493565a59f1bc14397c (diff)
[4.0.x] Refs #33476 -- Refactored code to strictly match 88 characters line length.
Backport of 7119f40c9881666b6f9b5cf7df09ee1d21cc8344 from main.
Diffstat (limited to 'tests')
-rw-r--r--tests/admin_changelist/tests.py3
-rw-r--r--tests/admin_checks/tests.py11
-rw-r--r--tests/admin_docs/test_views.py20
-rw-r--r--tests/admin_filters/tests.py5
-rw-r--r--tests/admin_inlines/tests.py102
-rw-r--r--tests/admin_registration/tests.py5
-rw-r--r--tests/admin_scripts/tests.py467
-rw-r--r--tests/admin_utils/tests.py3
-rw-r--r--tests/admin_views/test_actions.py9
-rw-r--r--tests/admin_views/tests.py214
-rw-r--r--tests/admin_widgets/tests.py47
-rw-r--r--tests/aggregation/tests.py26
-rw-r--r--tests/aggregation_regress/tests.py43
-rw-r--r--tests/annotations/tests.py10
-rw-r--r--tests/app_loading/tests.py20
-rw-r--r--tests/apps/tests.py5
-rw-r--r--tests/auth_tests/test_checks.py10
-rw-r--r--tests/auth_tests/test_forms.py49
-rw-r--r--tests/auth_tests/test_hashers.py3
-rw-r--r--tests/auth_tests/test_management.py26
-rw-r--r--tests/auth_tests/test_views.py5
-rw-r--r--tests/auth_tests/urls.py4
-rw-r--r--tests/backends/mysql/tests.py3
-rw-r--r--tests/backends/oracle/tests.py6
-rw-r--r--tests/backends/test_utils.py5
-rw-r--r--tests/backends/tests.py12
-rw-r--r--tests/basic/tests.py5
-rw-r--r--tests/cache/tests.py15
-rw-r--r--tests/check_framework/test_model_field_deprecation.py5
-rw-r--r--tests/check_framework/test_security.py4
-rw-r--r--tests/check_framework/test_translation.py5
-rw-r--r--tests/check_framework/test_urls.py18
-rw-r--r--tests/contenttypes_tests/test_checks.py7
-rw-r--r--tests/csrf_tests/tests.py8
-rw-r--r--tests/csrf_tests/views.py4
-rw-r--r--tests/custom_lookups/tests.py27
-rw-r--r--tests/db_functions/datetime/test_extract_trunc.py5
-rw-r--r--tests/db_functions/text/test_sha224.py4
-rw-r--r--tests/db_functions/text/test_sha256.py4
-rw-r--r--tests/db_functions/text/test_sha384.py18
-rw-r--r--tests/delete/tests.py8
-rw-r--r--tests/delete_regress/tests.py4
-rw-r--r--tests/expressions/tests.py10
-rw-r--r--tests/expressions_window/tests.py3
-rw-r--r--tests/extra_regress/tests.py3
-rw-r--r--tests/file_storage/tests.py5
-rw-r--r--tests/file_uploads/tests.py20
-rw-r--r--tests/files/tests.py3
-rw-r--r--tests/filtered_relation/tests.py4
-rw-r--r--tests/fixtures/tests.py564
-rw-r--r--tests/fixtures_regress/tests.py39
-rw-r--r--tests/flatpages_tests/test_csrf.py10
-rw-r--r--tests/flatpages_tests/test_forms.py8
-rw-r--r--tests/flatpages_tests/test_middleware.py10
-rw-r--r--tests/flatpages_tests/test_templatetags.py18
-rw-r--r--tests/flatpages_tests/test_views.py10
-rw-r--r--tests/foreign_object/test_forms.py3
-rw-r--r--tests/foreign_object/tests.py16
-rw-r--r--tests/forms_tests/field_tests/test_booleanfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_decimalfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_emailfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_floatfield.py6
-rw-r--r--tests/forms_tests/field_tests/test_multivaluefield.py9
-rw-r--r--tests/forms_tests/field_tests/test_nullbooleanfield.py9
-rw-r--r--tests/forms_tests/field_tests/test_urlfield.py3
-rw-r--r--tests/forms_tests/models.py7
-rw-r--r--tests/forms_tests/tests/test_forms.py919
-rw-r--r--tests/forms_tests/tests/test_formsets.py72
-rw-r--r--tests/forms_tests/tests/test_i18n.py37
-rw-r--r--tests/forms_tests/tests/test_input_formats.py50
-rw-r--r--tests/forms_tests/tests/test_media.py244
-rw-r--r--tests/forms_tests/tests/test_utils.py6
-rw-r--r--tests/forms_tests/tests/tests.py234
-rw-r--r--tests/forms_tests/widget_tests/test_checkboxinput.py3
-rw-r--r--tests/forms_tests/widget_tests/test_checkboxselectmultiple.py100
-rw-r--r--tests/forms_tests/widget_tests/test_clearablefileinput.py14
-rw-r--r--tests/forms_tests/widget_tests/test_datetimeinput.py5
-rw-r--r--tests/forms_tests/widget_tests/test_multiplehiddeninput.py23
-rw-r--r--tests/forms_tests/widget_tests/test_multiwidget.py6
-rw-r--r--tests/forms_tests/widget_tests/test_numberinput.py3
-rw-r--r--tests/forms_tests/widget_tests/test_radioselect.py91
-rw-r--r--tests/forms_tests/widget_tests/test_select.py12
-rw-r--r--tests/forms_tests/widget_tests/test_selectdatewidget.py3
-rw-r--r--tests/forms_tests/widget_tests/test_textarea.py6
-rw-r--r--tests/forms_tests/widget_tests/test_textinput.py13
-rw-r--r--tests/generic_inline_admin/tests.py38
-rw-r--r--tests/generic_relations/test_forms.py123
-rw-r--r--tests/generic_relations/tests.py8
-rw-r--r--tests/generic_views/test_dates.py15
-rw-r--r--tests/get_object_or_404/tests.py15
-rw-r--r--tests/get_or_create/tests.py5
-rw-r--r--tests/gis_tests/distapp/tests.py45
-rw-r--r--tests/gis_tests/gdal_tests/test_ds.py7
-rw-r--r--tests/gis_tests/gdal_tests/test_geom.py3
-rw-r--r--tests/gis_tests/gdal_tests/test_raster.py15
-rw-r--r--tests/gis_tests/gdal_tests/test_srs.py30
-rw-r--r--tests/gis_tests/geoadmin_deprecated/tests.py14
-rw-r--r--tests/gis_tests/geoapp/test_functions.py24
-rw-r--r--tests/gis_tests/geoapp/tests.py10
-rw-r--r--tests/gis_tests/geogapp/tests.py5
-rw-r--r--tests/gis_tests/geos_tests/test_geos.py6
-rw-r--r--tests/gis_tests/inspectapp/tests.py6
-rw-r--r--tests/gis_tests/layermap/models.py3
-rw-r--r--tests/gis_tests/layermap/tests.py5
-rw-r--r--tests/gis_tests/relatedapp/tests.py18
-rw-r--r--tests/gis_tests/test_geoforms.py3
-rw-r--r--tests/gis_tests/test_spatialrefsys.py14
-rw-r--r--tests/handlers/tests.py12
-rw-r--r--tests/httpwrappers/tests.py10
-rw-r--r--tests/humanize_tests/tests.py3
-rw-r--r--tests/i18n/patterns/tests.py20
-rw-r--r--tests/i18n/test_extraction.py17
-rw-r--r--tests/i18n/test_percents.py31
-rw-r--r--tests/i18n/tests.py54
-rw-r--r--tests/indexes/tests.py3
-rw-r--r--tests/inline_formsets/tests.py5
-rw-r--r--tests/inspectdb/tests.py18
-rw-r--r--tests/introspection/tests.py6
-rw-r--r--tests/invalid_models_tests/test_deprecated_fields.py6
-rw-r--r--tests/invalid_models_tests/test_models.py9
-rw-r--r--tests/invalid_models_tests/test_ordinary_fields.py3
-rw-r--r--tests/invalid_models_tests/test_relative_fields.py74
-rw-r--r--tests/logging_tests/tests.py6
-rw-r--r--tests/lookup/tests.py11
-rw-r--r--tests/m2m_regress/tests.py9
-rw-r--r--tests/m2m_through_regress/tests.py36
-rw-r--r--tests/mail/tests.py23
-rw-r--r--tests/managers_regress/tests.py3
-rw-r--r--tests/many_to_many/tests.py5
-rw-r--r--tests/many_to_one/tests.py17
-rw-r--r--tests/messages_tests/test_api.py5
-rw-r--r--tests/messages_tests/test_cookie.py3
-rw-r--r--tests/middleware/tests.py10
-rw-r--r--tests/middleware_exceptions/tests.py3
-rw-r--r--tests/migrations/test_autodetector.py13
-rw-r--r--tests/migrations/test_commands.py44
-rw-r--r--tests/migrations/test_graph.py27
-rw-r--r--tests/migrations/test_loader.py10
-rw-r--r--tests/migrations/test_operations.py47
-rw-r--r--tests/migrations/test_optimizer.py6
-rw-r--r--tests/migrations/test_state.py28
-rw-r--r--tests/migrations/test_writer.py6
-rw-r--r--tests/model_fields/test_durationfield.py5
-rw-r--r--tests/model_fields/test_foreignkey.py8
-rw-r--r--tests/model_forms/test_modelchoicefield.py27
-rw-r--r--tests/model_forms/tests.py384
-rw-r--r--tests/model_formsets/tests.py284
-rw-r--r--tests/model_formsets_regress/tests.py10
-rw-r--r--tests/model_regress/tests.py2
-rw-r--r--tests/modeladmin/test_checks.py19
-rw-r--r--tests/multiple_database/tests.py53
-rw-r--r--tests/null_queries/tests.py5
-rw-r--r--tests/one_to_one/tests.py10
-rw-r--r--tests/pagination/tests.py5
-rw-r--r--tests/postgres_tests/test_array.py38
-rw-r--r--tests/postgres_tests/test_constraints.py3
-rw-r--r--tests/postgres_tests/test_indexes.py3
-rw-r--r--tests/postgres_tests/test_introspection.py15
-rw-r--r--tests/postgres_tests/test_ranges.py26
-rw-r--r--tests/prefetch_related/test_uuid.py6
-rw-r--r--tests/prefetch_related/tests.py6
-rw-r--r--tests/proxy_models/tests.py10
-rw-r--r--tests/queries/tests.py14
-rw-r--r--tests/raw_query/tests.py13
-rw-r--r--tests/requests/test_data_upload_settings.py3
-rw-r--r--tests/requests/tests.py13
-rwxr-xr-xtests/runtests.py9
-rw-r--r--tests/schema/tests.py6
-rw-r--r--tests/select_for_update/tests.py5
-rw-r--r--tests/select_related/tests.py9
-rw-r--r--tests/serializers/test_xml.py7
-rw-r--r--tests/serializers/tests.py5
-rw-r--r--tests/sessions_tests/tests.py3
-rw-r--r--tests/signals/tests.py5
-rw-r--r--tests/sitemaps_tests/test_generic.py25
-rw-r--r--tests/sitemaps_tests/test_http.py102
-rw-r--r--tests/sitemaps_tests/test_https.py26
-rw-r--r--tests/sitemaps_tests/test_utils.py5
-rw-r--r--tests/staticfiles_tests/test_checks.py5
-rw-r--r--tests/staticfiles_tests/test_forms.py13
-rw-r--r--tests/staticfiles_tests/test_management.py12
-rw-r--r--tests/staticfiles_tests/test_storage.py3
-rw-r--r--tests/template_backends/test_django.py8
-rw-r--r--tests/template_tests/filter_tests/test_addslashes.py5
-rw-r--r--tests/template_tests/filter_tests/test_autoescape.py8
-rw-r--r--tests/template_tests/filter_tests/test_capfirst.py5
-rw-r--r--tests/template_tests/filter_tests/test_center.py5
-rw-r--r--tests/template_tests/filter_tests/test_chaining.py22
-rw-r--r--tests/template_tests/filter_tests/test_cut.py12
-rw-r--r--tests/template_tests/filter_tests/test_default.py4
-rw-r--r--tests/template_tests/filter_tests/test_escape.py4
-rw-r--r--tests/template_tests/filter_tests/test_first.py4
-rw-r--r--tests/template_tests/filter_tests/test_floatformat.py5
-rw-r--r--tests/template_tests/filter_tests/test_force_escape.py17
-rw-r--r--tests/template_tests/filter_tests/test_json_script.py3
-rw-r--r--tests/template_tests/filter_tests/test_length_is.py24
-rw-r--r--tests/template_tests/filter_tests/test_linebreaks.py5
-rw-r--r--tests/template_tests/filter_tests/test_linebreaksbr.py5
-rw-r--r--tests/template_tests/filter_tests/test_linenumbers.py5
-rw-r--r--tests/template_tests/filter_tests/test_ljust.py5
-rw-r--r--tests/template_tests/filter_tests/test_lower.py4
-rw-r--r--tests/template_tests/filter_tests/test_make_list.py5
-rw-r--r--tests/template_tests/filter_tests/test_phone2numeric.py5
-rw-r--r--tests/template_tests/filter_tests/test_random.py4
-rw-r--r--tests/template_tests/filter_tests/test_rjust.py5
-rw-r--r--tests/template_tests/filter_tests/test_safeseq.py5
-rw-r--r--tests/template_tests/filter_tests/test_slice.py5
-rw-r--r--tests/template_tests/filter_tests/test_slugify.py4
-rw-r--r--tests/template_tests/filter_tests/test_stringformat.py5
-rw-r--r--tests/template_tests/filter_tests/test_striptags.py11
-rw-r--r--tests/template_tests/filter_tests/test_truncatewords.py5
-rw-r--r--tests/template_tests/filter_tests/test_unordered_list.py21
-rw-r--r--tests/template_tests/filter_tests/test_upper.py4
-rw-r--r--tests/template_tests/filter_tests/test_urlize.py88
-rw-r--r--tests/template_tests/filter_tests/test_urlizetrunc.py30
-rw-r--r--tests/template_tests/filter_tests/test_wordcount.py5
-rw-r--r--tests/template_tests/filter_tests/test_wordwrap.py29
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_blocktranslate.py184
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_available_languages.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_current_language.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_translate.py31
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py5
-rw-r--r--tests/template_tests/syntax_tests/test_autoescape.py18
-rw-r--r--tests/template_tests/syntax_tests/test_cache.py18
-rw-r--r--tests/template_tests/syntax_tests/test_cycle.py22
-rw-r--r--tests/template_tests/syntax_tests/test_exceptions.py8
-rw-r--r--tests/template_tests/syntax_tests/test_extends.py49
-rw-r--r--tests/template_tests/syntax_tests/test_for.py65
-rw-r--r--tests/template_tests/syntax_tests/test_if.py32
-rw-r--r--tests/template_tests/syntax_tests/test_if_changed.py53
-rw-r--r--tests/template_tests/syntax_tests/test_include.py17
-rw-r--r--tests/template_tests/syntax_tests/test_invalid_string.py4
-rw-r--r--tests/template_tests/syntax_tests/test_load.py24
-rw-r--r--tests/template_tests/syntax_tests/test_named_endblock.py4
-rw-r--r--tests/template_tests/syntax_tests/test_resetcycle.py4
-rw-r--r--tests/template_tests/syntax_tests/test_spaceless.py16
-rw-r--r--tests/template_tests/syntax_tests/test_static.py13
-rw-r--r--tests/template_tests/syntax_tests/test_verbatim.py8
-rw-r--r--tests/template_tests/templatetags/inclusion.py13
-rw-r--r--tests/template_tests/test_custom.py88
-rw-r--r--tests/template_tests/test_extends.py29
-rw-r--r--tests/template_tests/test_parser.py3
-rw-r--r--tests/test_client/tests.py13
-rw-r--r--tests/test_client_regress/tests.py95
-rw-r--r--tests/test_client_regress/views.py3
-rw-r--r--tests/test_runner/test_discover_runner.py9
-rw-r--r--tests/test_utils/tests.py10
-rw-r--r--tests/timezones/tests.py14
-rw-r--r--tests/transactions/tests.py11
-rw-r--r--tests/unmanaged_models/tests.py3
-rw-r--r--tests/urlpatterns_reverse/tests.py23
-rw-r--r--tests/user_commands/tests.py2
-rw-r--r--tests/utils_tests/test_autoreload.py11
-rw-r--r--tests/utils_tests/test_html.py27
-rw-r--r--tests/utils_tests/test_jslex.py7
-rw-r--r--tests/utils_tests/test_lazyobject.py3
-rw-r--r--tests/utils_tests/test_text.py9
-rw-r--r--tests/validation/test_error_messages.py28
-rw-r--r--tests/view_tests/tests/test_csrf.py4
-rw-r--r--tests/view_tests/tests/test_debug.py21
-rw-r--r--tests/view_tests/tests/test_defaults.py7
-rw-r--r--tests/view_tests/tests/test_i18n.py3
-rw-r--r--tests/view_tests/views.py24
-rw-r--r--tests/wsgi/tests.py6
266 files changed, 5079 insertions, 2424 deletions
diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py
index 7bc8f6146b..d9c29290b6 100644
--- a/tests/admin_changelist/tests.py
+++ b/tests/admin_changelist/tests.py
@@ -1151,7 +1151,8 @@ class ChangeListTests(TestCase):
self.assertEqual(result.id, counter)
custom_site.unregister(OrderedObject)
- # When no order is defined at all, use the model's default ordering (i.e. 'number')
+ # When no order is defined at all, use the model's default ordering
+ # (i.e. 'number').
check_results_order(ascending=True)
# When an order field is defined but multiple records have the same
diff --git a/tests/admin_checks/tests.py b/tests/admin_checks/tests.py
index a2372ba0d2..2646837bbc 100644
--- a/tests/admin_checks/tests.py
+++ b/tests/admin_checks/tests.py
@@ -564,7 +564,8 @@ class SystemChecksTestCase(SimpleTestCase):
errors = SongAdmin(Song, AdminSite()).check()
expected = [
checks.Error(
- "'ct_field' references 'nonexistent', which is not a field on 'admin_checks.Influence'.",
+ "'ct_field' references 'nonexistent', which is not a field on "
+ "'admin_checks.Influence'.",
obj=InfluenceInline,
id="admin.E302",
)
@@ -587,7 +588,8 @@ class SystemChecksTestCase(SimpleTestCase):
errors = SongAdmin(Song, AdminSite()).check()
expected = [
checks.Error(
- "'ct_fk_field' references 'nonexistent', which is not a field on 'admin_checks.Influence'.",
+ "'ct_fk_field' references 'nonexistent', which is not a field on "
+ "'admin_checks.Influence'.",
obj=InfluenceInline,
id="admin.E303",
)
@@ -865,8 +867,9 @@ class SystemChecksTestCase(SimpleTestCase):
errors = FieldsetBookAdmin(Book, AdminSite()).check()
expected = [
checks.Error(
- "The value of 'fieldsets[1][1][\"fields\"]' cannot include the ManyToManyField "
- "'authors', because that field manually specifies a relationship model.",
+ "The value of 'fieldsets[1][1][\"fields\"]' cannot include the "
+ "ManyToManyField 'authors', because that field manually specifies a "
+ "relationship model.",
obj=FieldsetBookAdmin,
id="admin.E013",
)
diff --git a/tests/admin_docs/test_views.py b/tests/admin_docs/test_views.py
index 99a5ad3488..504f03dff3 100644
--- a/tests/admin_docs/test_views.py
+++ b/tests/admin_docs/test_views.py
@@ -54,7 +54,8 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
response = self.client.get(reverse("django-admindocs-views-index"))
self.assertContains(
response,
- '<h3><a href="/admindocs/views/django.contrib.admindocs.views.BaseAdminDocsView/">/admindocs/</a></h3>',
+ '<h3><a href="/admindocs/views/django.contrib.admindocs.views.'
+ 'BaseAdminDocsView/">/admindocs/</a></h3>',
html=True,
)
self.assertContains(response, "Views by namespace test")
@@ -73,7 +74,9 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
response = self.client.get(reverse("django-admindocs-views-index"))
self.assertContains(
response,
- '<h3><a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">/admin/</a></h3>',
+ "<h3>"
+ '<a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">'
+ "/admin/</a></h3>",
html=True,
)
@@ -118,7 +121,8 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
response = self.client.get(reverse("django-admindocs-models-index"))
self.assertContains(
response,
- '<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)</h2>',
+ '<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)'
+ "</h2>",
html=True,
)
@@ -380,11 +384,15 @@ class TestModelDetailView(TestDataMixin, AdminDocsTestCase):
def test_model_docstring_renders_correctly(self):
summary = (
- '<h2 class="subhead"><p>Stores information about a person, related to <a class="reference external" '
- 'href="/admindocs/models/myapp.company/">myapp.Company</a>.</p></h2>'
+ '<h2 class="subhead"><p>Stores information about a person, related to '
+ '<a class="reference external" href="/admindocs/models/myapp.company/">'
+ "myapp.Company</a>.</p></h2>"
)
subheading = "<p><strong>Notes</strong></p>"
- body = '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this object.</p>'
+ body = (
+ '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this '
+ "object.</p>"
+ )
model_body = (
'<dl class="docutils"><dt><tt class="'
'docutils literal">company</tt></dt><dd>Field storing <a class="'
diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py
index 42748a7b1c..753b206642 100644
--- a/tests/admin_filters/tests.py
+++ b/tests/admin_filters/tests.py
@@ -1244,7 +1244,10 @@ class ListFiltersTests(TestCase):
modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site)
request = self.request_factory.get("/", {})
request.user = self.alfred
- msg = "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'."
+ msg = (
+ "The list filter 'DecadeListFilterWithoutParameter' does not specify a "
+ "'parameter_name'."
+ )
with self.assertRaisesMessage(ImproperlyConfigured, msg):
modeladmin.get_changelist_instance(request)
diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py
index 8daab1becf..3bd3c881d4 100644
--- a/tests/admin_inlines/tests.py
+++ b/tests/admin_inlines/tests.py
@@ -206,10 +206,12 @@ class TestInline(TestDataMixin, TestCase):
response = self.client.post(
reverse("admin:admin_inlines_titlecollection_add"), data
)
- # Here colspan is "4": two fields (title1 and title2), one hidden field and the delete checkbox.
+ # Here colspan is "4": two fields (title1 and title2), one hidden field
+ # and the delete checkbox.
self.assertContains(
response,
- '<tr class="row-form-errors"><td colspan="4"><ul class="errorlist nonfield">'
+ '<tr class="row-form-errors"><td colspan="4">'
+ '<ul class="errorlist nonfield">'
"<li>The two titles must be the same</li></ul></td></tr>",
)
@@ -225,7 +227,10 @@ class TestInline(TestDataMixin, TestCase):
)
def test_callable_lookup(self):
- """Admin inline should invoke local callable when its name is listed in readonly_fields"""
+ """
+ Admin inline should invoke local callable when its name is listed in
+ readonly_fields.
+ """
response = self.client.get(reverse("admin:admin_inlines_poll_add"))
# Add parent object view should have the child inlines section
self.assertContains(
@@ -323,7 +328,8 @@ class TestInline(TestDataMixin, TestCase):
"""
self.client.force_login(self.view_only_user)
url = reverse(
- "stacked_inline_hidden_field_in_group_admin:admin_inlines_someparentmodel_change",
+ "stacked_inline_hidden_field_in_group_admin:"
+ "admin_inlines_someparentmodel_change",
args=(self.parent.pk,),
)
response = self.client.get(url)
@@ -354,7 +360,8 @@ class TestInline(TestDataMixin, TestCase):
"""
self.client.force_login(self.view_only_user)
url = reverse(
- "stacked_inline_hidden_field_on_single_line_admin:admin_inlines_someparentmodel_change",
+ "stacked_inline_hidden_field_on_single_line_admin:"
+ "admin_inlines_someparentmodel_change",
args=(self.parent.pk,),
)
response = self.client.get(url)
@@ -424,12 +431,14 @@ class TestInline(TestDataMixin, TestCase):
)
self.assertContains(
response,
- '<input type="hidden" name="-1-0-capo_famiglia" id="id_-1-0-capo_famiglia">',
+ '<input type="hidden" name="-1-0-capo_famiglia" '
+ 'id="id_-1-0-capo_famiglia">',
html=True,
)
self.assertContains(
response,
- '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" maxlength="100">',
+ '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" '
+ 'maxlength="100">',
html=True,
)
self.assertContains(
@@ -437,12 +446,14 @@ class TestInline(TestDataMixin, TestCase):
)
self.assertContains(
response,
- '<input type="hidden" name="-2-0-capo_famiglia" id="id_-2-0-capo_famiglia">',
+ '<input type="hidden" name="-2-0-capo_famiglia" '
+ 'id="id_-2-0-capo_famiglia">',
html=True,
)
self.assertContains(
response,
- '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" maxlength="100">',
+ '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" '
+ 'maxlength="100">',
html=True,
)
@@ -870,7 +881,8 @@ class TestInlinePermissions(TestCase):
cls.author_change_url = reverse(
"admin:admin_inlines_author_change", args=(author.id,)
)
- # Get the ID of the automatically created intermediate model for the Author-Book m2m
+ # Get the ID of the automatically created intermediate model for the
+ # Author-Book m2m.
author_book_auto_m2m_intermediate = Author.books.through.objects.get(
author=author, book=cls.book
)
@@ -1011,7 +1023,8 @@ class TestInlinePermissions(TestCase):
self.assertContains(response, "<p>%s</p>" % self.book)
self.assertNotContains(
response,
- '<input type="checkbox" name="Author_books-0-DELETE" id="id_Author_books-0-DELETE">',
+ '<input type="checkbox" name="Author_books-0-DELETE" '
+ 'id="id_Author_books-0-DELETE">',
html=True,
)
@@ -1066,8 +1079,8 @@ class TestInlinePermissions(TestCase):
)
self.assertNotContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
@@ -1082,19 +1095,21 @@ class TestInlinePermissions(TestCase):
# Just the one form for existing instances
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
# max-num 0 means we can't add new ones
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" name="inner2_set-MAX_NUM_FORMS">',
+ '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" '
+ 'name="inner2_set-MAX_NUM_FORMS">',
html=True,
)
# TabularInline
@@ -1123,13 +1138,14 @@ class TestInlinePermissions(TestCase):
# One form for existing instance and three extra for new
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
@@ -1148,13 +1164,14 @@ class TestInlinePermissions(TestCase):
# One form for existing instance only, no new
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
@@ -1178,13 +1195,14 @@ class TestInlinePermissions(TestCase):
# One form for existing instance only, three for new
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
@@ -1247,7 +1265,10 @@ class TestReadOnlyChangeViewInlinePermissions(TestCase):
self.assertContains(
response, '<div class="readonly">%s</div>' % self.poll.name, html=True
)
- input = '<input type="text" name="name" value="%s" class="vTextField" maxlength="40" required id="id_name">'
+ input = (
+ '<input type="text" name="name" value="%s" class="vTextField" '
+ 'maxlength="40" required id="id_name">'
+ )
self.assertNotContains(response, input % self.poll.name, html=True)
def test_inlines_are_rendered_as_read_only(self):
@@ -1284,7 +1305,8 @@ class TestReadOnlyChangeViewInlinePermissions(TestCase):
response = self.client.get(self.change_url)
self.assertNotContains(
response,
- '<input type="checkbox" name="question_set-0-DELETE" id="id_question_set-0-DELETE">',
+ '<input type="checkbox" name="question_set-0-DELETE" '
+ 'id="id_question_set-0-DELETE">',
html=True,
)
@@ -1672,7 +1694,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(
len(
self.selenium.find_elements_by_css_selector(
- ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-first_name]"
+ ".dynamic-profile_set#profile_set-0 "
+ "input[name=profile_set-0-first_name]"
)
),
1,
@@ -1680,7 +1703,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(
len(
self.selenium.find_elements_by_css_selector(
- ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-last_name]"
+ ".dynamic-profile_set#profile_set-0 "
+ "input[name=profile_set-0-last_name]"
)
),
1,
@@ -1703,7 +1727,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(
len(
self.selenium.find_elements_by_css_selector(
- ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-first_name]"
+ ".dynamic-profile_set#profile_set-1 "
+ "input[name=profile_set-1-first_name]"
)
),
1,
@@ -1711,7 +1736,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(
len(
self.selenium.find_elements_by_css_selector(
- ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-last_name]"
+ ".dynamic-profile_set#profile_set-1 "
+ "input[name=profile_set-1-last_name]"
)
),
1,
@@ -1731,7 +1757,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(
len(
self.selenium.find_elements_by_css_selector(
- ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-first_name]"
+ ".dynamic-profile_set#profile_set-2 "
+ "input[name=profile_set-2-first_name]"
)
),
1,
@@ -1739,7 +1766,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.assertEqual(
len(
self.selenium.find_elements_by_css_selector(
- ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-last_name]"
+ ".dynamic-profile_set#profile_set-2 "
+ "input[name=profile_set-2-last_name]"
)
),
1,
@@ -1858,10 +1886,12 @@ class SeleniumTests(AdminSeleniumTestCase):
# Click on a few delete buttons
self.selenium.find_element_by_css_selector(
- "form#profilecollection_form tr.dynamic-profile_set#profile_set-1 td.delete a"
+ "form#profilecollection_form "
+ "tr.dynamic-profile_set#profile_set-1 td.delete a"
).click()
self.selenium.find_element_by_css_selector(
- "form#profilecollection_form tr.dynamic-profile_set#profile_set-2 td.delete a"
+ "form#profilecollection_form "
+ "tr.dynamic-profile_set#profile_set-2 td.delete a"
).click()
# The rows are gone and the IDs have been re-sequenced
self.assertEqual(
diff --git a/tests/admin_registration/tests.py b/tests/admin_registration/tests.py
index 12fc98b1cc..25f317d322 100644
--- a/tests/admin_registration/tests.py
+++ b/tests/admin_registration/tests.py
@@ -43,7 +43,10 @@ class TestRegistration(SimpleTestCase):
pass
self.site.register(Person, PersonAdmin)
- msg = "The model Person is already registered with 'admin_registration.PersonAdmin'."
+ msg = (
+ "The model Person is already registered with "
+ "'admin_registration.PersonAdmin'."
+ )
with self.assertRaisesMessage(admin.sites.AlreadyRegistered, msg):
self.site.register(Person, PersonAdmin)
diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py
index b879dfd6b1..df435dc12a 100644
--- a/tests/admin_scripts/tests.py
+++ b/tests/admin_scripts/tests.py
@@ -194,21 +194,30 @@ class DjangoAdminNoSettings(AdminScriptTestCase):
"A series of tests for django-admin when there is no settings.py file."
def test_builtin_command(self):
- "no settings: django-admin builtin commands fail with an error when no settings provided"
+ """
+ no settings: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_bad_settings(self):
- "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ no settings: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ no settings: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
@@ -236,42 +245,60 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase):
self.write_settings("settings.py")
def test_builtin_command(self):
- "default: django-admin builtin commands fail with an error when no settings provided"
+ """
+ default: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "default: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ default: django-admin builtin commands succeed if settings are provided
+ as argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "default: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ default: django-admin builtin commands succeed if settings are provided
+ in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "default: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ default: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "default: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ default: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "default: django-admin can't execute user commands if it isn't provided settings"
+ """
+ default: django-admin can't execute user commands if it isn't provided
+ settings.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -279,14 +306,20 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "default: django-admin can execute user commands if settings are provided as argument"
+ """
+ default: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "default: django-admin can execute user commands if settings are provided in environment"
+ """
+ default: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
@@ -312,42 +345,60 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "fulldefault: django-admin builtin commands fail with an error when no settings provided"
+ """
+ fulldefault: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "fulldefault: django-admin builtin commands succeed if a settings file is provided"
+ """
+ fulldefault: django-admin builtin commands succeed if a settings file
+ is provided.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "fulldefault: django-admin builtin commands succeed if the environment contains settings"
+ """
+ fulldefault: django-admin builtin commands succeed if the environment
+ contains settings.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ fulldefault: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ fulldefault: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "fulldefault: django-admin can't execute user commands unless settings are provided"
+ """
+ fulldefault: django-admin can't execute user commands unless settings
+ are provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -355,14 +406,20 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "fulldefault: django-admin can execute user commands if settings are provided as argument"
+ """
+ fulldefault: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "fulldefault: django-admin can execute user commands if settings are provided in environment"
+ """
+ fulldefault: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
@@ -382,35 +439,50 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "minimal: django-admin builtin commands fail with an error when no settings provided"
+ """
+ minimal: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "minimal: django-admin builtin commands fail if settings are provided as argument"
+ """
+ minimal: django-admin builtin commands fail if settings are provided as
+ argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_environment(self):
- "minimal: django-admin builtin commands fail if settings are provided in the environment"
+ """
+ minimal: django-admin builtin commands fail if settings are provided in
+ the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_bad_settings(self):
- "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ minimal: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ minimal: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
@@ -425,14 +497,20 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "minimal: django-admin can't execute user commands, even if settings are provided as argument"
+ """
+ minimal: django-admin can't execute user commands, even if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_environment(self):
- "minimal: django-admin can't execute user commands, even if settings are provided in environment"
+ """
+ minimal: django-admin can't execute user commands, even if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(out)
@@ -450,42 +528,60 @@ class DjangoAdminAlternateSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "alternate: django-admin builtin commands fail with an error when no settings provided"
+ """
+ alternate: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "alternate: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "alternate: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "alternate: django-admin can't execute user commands unless settings are provided"
+ """
+ alternate: django-admin can't execute user commands unless settings
+ are provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -493,14 +589,20 @@ class DjangoAdminAlternateSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "alternate: django-admin can execute user commands if settings are provided as argument"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.alternate_settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "alternate: django-admin can execute user commands if settings are provided in environment"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
@@ -523,41 +625,59 @@ class DjangoAdminMultipleSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "alternate: django-admin builtin commands fail with an error when no settings provided"
+ """
+ alternate: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "alternate: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "alternate: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "alternate: django-admin can't execute user commands unless settings are provided"
+ """
+ alternate: django-admin can't execute user commands unless settings are
+ provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -565,14 +685,20 @@ class DjangoAdminMultipleSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "alternate: django-admin can execute user commands if settings are provided as argument"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.alternate_settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "alternate: django-admin can execute user commands if settings are provided in environment"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
@@ -624,27 +750,39 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
self.assertIn("name = 'こんにちは'", content)
def test_builtin_command(self):
- "directory: django-admin builtin commands fail with an error when no settings provided"
+ """
+ directory: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_bad_settings(self):
- "directory: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ directory: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "directory: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ directory: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "directory: django-admin can't execute user commands unless settings are provided"
+ """
+ directory: django-admin can't execute user commands unless settings are
+ provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -652,14 +790,20 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_builtin_with_settings(self):
- "directory: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ directory: django-admin builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "directory: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ directory: django-admin builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
@@ -689,7 +833,10 @@ class ManageNoSettings(AdminScriptTestCase):
"A series of tests for manage.py when there is no settings.py file."
def test_builtin_command(self):
- "no settings: manage.py builtin commands fail with an error when no settings provided"
+ """
+ no settings: manage.py builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
@@ -698,14 +845,20 @@ class ManageNoSettings(AdminScriptTestCase):
)
def test_builtin_with_bad_settings(self):
- "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ no settings: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ no settings: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -722,56 +875,80 @@ class ManageDefaultSettings(AdminScriptTestCase):
self.write_settings("settings.py")
def test_builtin_command(self):
- "default: manage.py builtin commands succeed when default settings are appropriate"
+ """
+ default: manage.py builtin commands succeed when default settings are
+ appropriate.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_settings(self):
- "default: manage.py builtin commands succeed if settings are provided as argument"
+ """
+ default: manage.py builtin commands succeed if settings are provided as
+ argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "default: manage.py builtin commands succeed if settings are provided in the environment"
+ """
+ default: manage.py builtin commands succeed if settings are provided in
+ the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist"
+ """
+ default: manage.py builtin commands succeed if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "default: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ default: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "default: manage.py can execute user commands when default settings are appropriate"
+ """
+ default: manage.py can execute user commands when default settings are
+ appropriate.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
- "default: manage.py can execute user commands when settings are provided as argument"
+ """
+ default: manage.py can execute user commands when settings are provided
+ as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "default: manage.py can execute user commands when settings are provided in environment"
+ """
+ default: manage.py can execute user commands when settings are provided
+ in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
@@ -791,56 +968,80 @@ class ManageFullPathDefaultSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "fulldefault: manage.py builtin commands succeed when default settings are appropriate"
+ """
+ fulldefault: manage.py builtin commands succeed when default settings
+ are appropriate.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_settings(self):
- "fulldefault: manage.py builtin commands succeed if settings are provided as argument"
+ """
+ fulldefault: manage.py builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "fulldefault: manage.py builtin commands succeed if settings are provided in the environment"
+ """
+ fulldefault: manage.py builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist"
+ """
+ fulldefault: manage.py builtin commands succeed if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ fulldefault: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "fulldefault: manage.py can execute user commands when default settings are appropriate"
+ """
+ fulldefault: manage.py can execute user commands when default settings
+ are appropriate.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
- "fulldefault: manage.py can execute user commands when settings are provided as argument"
+ """
+ fulldefault: manage.py can execute user commands when settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "fulldefault: manage.py can execute user commands when settings are provided in environment"
+ """
+ fulldefault: manage.py can execute user commands when settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
@@ -859,7 +1060,10 @@ class ManageMinimalSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "minimal: manage.py builtin commands fail with an error when no settings provided"
+ """
+ minimal: manage.py builtin commands fail with an error when no settings
+ provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
@@ -873,21 +1077,30 @@ class ManageMinimalSettings(AdminScriptTestCase):
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_environment(self):
- "minimal: manage.py builtin commands fail if settings are provided in the environment"
+ """
+ minimal: manage.py builtin commands fail if settings are provided in
+ the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_bad_settings(self):
- "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ minimal: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ minimal: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -901,14 +1114,20 @@ class ManageMinimalSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "minimal: manage.py can't execute user commands, even if settings are provided as argument"
+ """
+ minimal: manage.py can't execute user commands, even if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_environment(self):
- "minimal: manage.py can't execute user commands, even if settings are provided in environment"
+ """
+ minimal: manage.py can't execute user commands, even if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(out)
@@ -925,7 +1144,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "alternate: manage.py builtin commands fail with an error when no default settings provided"
+ """
+ alternate: manage.py builtin commands fail with an error when no
+ default settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
@@ -941,21 +1163,30 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.assertNoOutput(err)
def test_builtin_with_environment(self):
- "alternate: manage.py builtin commands work if settings are provided in the environment"
+ """
+ alternate: manage.py builtin commands work if settings are provided in
+ the environment
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "alternate_settings")
self.assertOutput(out, SYSTEM_CHECK_MSG)
self.assertNoOutput(err)
def test_builtin_with_bad_settings(self):
- "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ alternate: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ alternate: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -971,7 +1202,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
)
def test_custom_command_with_settings(self):
- "alternate: manage.py can execute user commands if settings are provided as argument"
+ """
+ alternate: manage.py can execute user commands if settings are provided
+ as argument
+ """
args = ["noargs_command", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertOutput(
@@ -983,7 +1217,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.assertNoOutput(err)
def test_custom_command_with_environment(self):
- "alternate: manage.py can execute user commands if settings are provided in environment"
+ """
+ alternate: manage.py can execute user commands if settings are provided
+ in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "alternate_settings")
self.assertOutput(
@@ -995,7 +1232,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.assertNoOutput(err)
def test_custom_command_output_color(self):
- "alternate: manage.py output syntax color can be deactivated with the `--no-color` option"
+ """
+ alternate: manage.py output syntax color can be deactivated with the
+ `--no-color` option.
+ """
args = ["noargs_command", "--no-color", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertOutput(
@@ -1022,35 +1262,50 @@ class ManageMultipleSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "multiple: manage.py builtin commands fail with an error when no settings provided"
+ """
+ multiple: manage.py builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_settings(self):
- "multiple: manage.py builtin commands succeed if settings are provided as argument"
+ """
+ multiple: manage.py builtin commands succeed if settings are provided
+ as argument.
+ """
args = ["check", "--settings=alternate_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "multiple: manage.py can execute builtin commands if settings are provided in the environment"
+ """
+ multiple: manage.py can execute builtin commands if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ multiple: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ multiple: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -1064,14 +1319,20 @@ class ManageMultipleSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "multiple: manage.py can execute user commands if settings are provided as argument"
+ """
+ multiple: manage.py can execute user commands if settings are provided
+ as argument.
+ """
args = ["noargs_command", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "multiple: manage.py can execute user commands if settings are provided in environment"
+ """
+ multiple: manage.py can execute user commands if settings are provided
+ in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "alternate_settings")
self.assertNoOutput(err)
@@ -2099,7 +2360,9 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
]
def test_wrong_args(self):
- "Make sure passing the wrong kinds of arguments outputs an error and prints usage"
+ """
+ Passing the wrong kinds of arguments outputs an error and prints usage.
+ """
out, err = self.run_django_admin(["startproject"])
self.assertNoOutput(out)
self.assertOutput(err, "usage:")
@@ -2158,7 +2421,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertFalse(os.path.exists(testproject_dir))
def test_simple_project_different_directory(self):
- "Make sure the startproject management command creates a project in a specific directory"
+ """
+ The startproject management command creates a project in a specific
+ directory.
+ """
args = ["startproject", "testproject", "othertestproject"]
testproject_dir = os.path.join(self.test_dir, "othertestproject")
os.mkdir(testproject_dir)
@@ -2177,7 +2443,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
)
def test_custom_project_template(self):
- "Make sure the startproject management command is able to use a different project template"
+ """
+ The startproject management command is able to use a different project
+ template.
+ """
template_path = os.path.join(custom_templates_dir, "project_template")
args = ["startproject", "--template", template_path, "customtestproject"]
testproject_dir = os.path.join(self.test_dir, "customtestproject")
@@ -2199,7 +2468,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
def test_custom_project_template_from_tarball_by_path(self):
- "Make sure the startproject management command is able to use a different project template from a tarball"
+ """
+ The startproject management command is able to use a different project
+ template from a tarball.
+ """
template_path = os.path.join(custom_templates_dir, "project_template.tgz")
args = ["startproject", "--template", template_path, "tarballtestproject"]
testproject_dir = os.path.join(self.test_dir, "tarballtestproject")
@@ -2210,7 +2482,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
def test_custom_project_template_from_tarball_to_alternative_location(self):
- "Startproject can use a project template from a tarball and create it in a specified location"
+ """
+ Startproject can use a project template from a tarball and create it in
+ a specified location.
+ """
template_path = os.path.join(custom_templates_dir, "project_template.tgz")
args = [
"startproject",
@@ -2243,7 +2518,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
def test_project_template_tarball_url(self):
- "Startproject management command handles project template tar/zip balls from non-canonical urls"
+ """ "
+ Startproject management command handles project template tar/zip balls
+ from non-canonical urls.
+ """
template_url = (
"%s/custom_templates/project_template.tgz/" % self.live_server_url
)
@@ -2665,7 +2943,8 @@ class MainModule(AdminScriptTestCase):
out, err = self.run_test(["-m", "django", "help"])
self.assertOutput(
out,
- "Type 'python -m django help <subcommand>' for help on a specific subcommand.",
+ "Type 'python -m django help <subcommand>' for help on a specific "
+ "subcommand.",
)
diff --git a/tests/admin_utils/tests.py b/tests/admin_utils/tests.py
index 27fe049274..a2ef3b1942 100644
--- a/tests/admin_utils/tests.py
+++ b/tests/admin_utils/tests.py
@@ -379,7 +379,8 @@ class UtilsTests(SimpleTestCase):
)
self.assertHTMLEqual(
helpers.AdminField(form, "cb", is_first=False).label_tag(),
- '<label for="id_cb" class="vCheckboxLabel required inline"><i>cb</i></label>',
+ '<label for="id_cb" class="vCheckboxLabel required inline">'
+ "<i>cb</i></label>",
)
# normal strings needs to be escaped
diff --git a/tests/admin_views/test_actions.py b/tests/admin_views/test_actions.py
index 2bdcff44ae..ec690f5692 100644
--- a/tests/admin_views/test_actions.py
+++ b/tests/admin_views/test_actions.py
@@ -314,7 +314,9 @@ action)</option>
self.assertContains(
response,
"jquery.min.js",
- msg_prefix="jQuery missing from admin pages for model with no admin actions",
+ msg_prefix=(
+ "jQuery missing from admin pages for model with no admin actions"
+ ),
)
def test_action_column_class(self):
@@ -365,7 +367,10 @@ action)</option>
response = self.client.post(url, action_data)
self.assertRedirects(response, url, fetch_redirect_response=False)
response = self.client.get(response.url)
- msg = "Items must be selected in order to perform actions on them. No items have been changed."
+ msg = (
+ "Items must be selected in order to perform actions on them. No items have "
+ "been changed."
+ )
self.assertContains(response, msg)
self.assertEqual(Subscriber.objects.count(), 2)
diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index 96069d977e..e7ff999b5d 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -1071,34 +1071,38 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
)
self.assertEqual(response.status_code, 400)
- # #23839 - Primary key should always be allowed, even if the referenced model isn't registered.
+ # Primary key should always be allowed, even if the referenced model
+ # isn't registered.
response = self.client.get(
reverse("admin:admin_views_notreferenced_changelist"), {TO_FIELD_VAR: "id"}
)
self.assertEqual(response.status_code, 200)
- # #23915 - Specifying a field referenced by another model though a m2m should be allowed.
+ # Specifying a field referenced by another model though a m2m should be
+ # allowed.
response = self.client.get(
reverse("admin:admin_views_recipe_changelist"), {TO_FIELD_VAR: "rname"}
)
self.assertEqual(response.status_code, 200)
- # #23604, #23915 - Specifying a field referenced through a reverse m2m relationship should be allowed.
+ # Specifying a field referenced through a reverse m2m relationship
+ # should be allowed.
response = self.client.get(
reverse("admin:admin_views_ingredient_changelist"), {TO_FIELD_VAR: "iname"}
)
self.assertEqual(response.status_code, 200)
- # #23329 - Specifying a field that is not referred by any other model directly registered
- # to this admin site but registered through inheritance should be allowed.
+ # Specifying a field that is not referred by any other model directly
+ # registered to this admin site but registered through inheritance
+ # should be allowed.
response = self.client.get(
reverse("admin:admin_views_referencedbyparent_changelist"),
{TO_FIELD_VAR: "name"},
)
self.assertEqual(response.status_code, 200)
- # #23431 - Specifying a field that is only referred to by a inline of a registered
- # model should be allowed.
+ # Specifying a field that is only referred to by a inline of a
+ # registered model should be allowed.
response = self.client.get(
reverse("admin:admin_views_referencedbyinline_changelist"),
{TO_FIELD_VAR: "name"},
@@ -1137,7 +1141,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
ForeignKey 'limit_choices_to' should be allowed, otherwise raw_id_fields
can break.
"""
- # Filters should be allowed if they are defined on a ForeignKey pointing to this model
+ # Filters should be allowed if they are defined on a ForeignKey
+ # pointing to this model.
url = "%s?leader__name=Palin&leader__age=27" % reverse(
"admin:admin_views_inquisition_changelist"
)
@@ -1168,7 +1173,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
self.assertNotContains(
response,
reverse("admin:password_change"),
- msg_prefix='The "change password" link should not be displayed if a user does not have a usable password.',
+ msg_prefix=(
+ 'The "change password" link should not be displayed if a user does not '
+ "have a usable password."
+ ),
)
def test_change_view_with_show_delete_extra_context(self):
@@ -1412,8 +1420,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
- # Put this app's and the shared tests templates dirs in DIRS to take precedence
- # over the admin's templates dir.
+ # Put this app's and the shared tests templates dirs in DIRS to
+ # take precedence over the admin's templates dir.
"DIRS": [
os.path.join(os.path.dirname(__file__), "templates"),
os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates"),
@@ -2256,7 +2264,10 @@ class AdminViewPermissionsTest(TestCase):
self.assertNotContains(
addpage,
change_list_link,
- msg_prefix="User restricted to add permission is given link to change list view in breadcrumbs.",
+ msg_prefix=(
+ "User restricted to add permission is given link to change list view "
+ "in breadcrumbs."
+ ),
)
post = self.client.post(reverse("admin:admin_views_article_add"), add_dict)
self.assertRedirects(post, self.index_url)
@@ -2282,7 +2293,10 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(
addpage,
change_list_link,
- msg_prefix="Unrestricted user is not given link to change list view in breadcrumbs.",
+ msg_prefix=(
+ "Unrestricted user is not given link to change list view in "
+ "breadcrumbs."
+ ),
)
post = self.client.post(reverse("admin:admin_views_article_add"), add_dict)
self.assertRedirects(post, reverse("admin:admin_views_article_changelist"))
@@ -2359,7 +2373,8 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(response, "<label>Extra form field:</label>")
self.assertContains(
response,
- '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>',
+ '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close'
+ "</a>",
)
self.assertEqual(response.context["title"], "View article")
post = self.client.post(article_change_url, change_dict)
@@ -2391,13 +2406,16 @@ class AdminViewPermissionsTest(TestCase):
Article.objects.get(pk=self.a1.pk).content, "<p>edited article</p>"
)
- # one error in form should produce singular error message, multiple errors plural
+ # one error in form should produce singular error message, multiple
+ # errors plural.
change_dict["title"] = ""
post = self.client.post(article_change_url, change_dict)
self.assertContains(
post,
"Please correct the error below.",
- msg_prefix="Singular error message not found in response to post with one error",
+ msg_prefix=(
+ "Singular error message not found in response to post with one error"
+ ),
)
change_dict["content"] = ""
@@ -2405,7 +2423,10 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(
post,
"Please correct the errors below.",
- msg_prefix="Plural error message not found in response to post with multiple errors",
+ msg_prefix=(
+ "Plural error message not found in response to post with multiple "
+ "errors"
+ ),
)
self.client.get(reverse("admin:logout"))
@@ -2504,7 +2525,8 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(response, "<h1>View article</h1>")
self.assertContains(
response,
- '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>',
+ '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close'
+ "</a>",
)
def test_change_view_save_as_new(self):
@@ -2855,13 +2877,15 @@ class AdminViewPermissionsTest(TestCase):
)
self.client.force_login(self.adduser)
- # The user can't change sections yet, so they shouldn't see the "change section" link.
+ # The user can't change sections yet, so they shouldn't see the
+ # "change section" link.
url = reverse("admin:admin_views_article_add")
change_link_text = "change_id_section"
response = self.client.get(url)
self.assertFalse(get_change_related(response))
self.assertNotContains(response, change_link_text)
- # Allow the user to change sections too. Now they can see the "change section" link.
+ # Allow the user to change sections too. Now they can see the
+ # "change section" link.
user = User.objects.get(username="adduser")
perm = get_perm(Section, get_permission_codename("change", Section._meta))
user.user_permissions.add(perm)
@@ -2883,13 +2907,15 @@ class AdminViewPermissionsTest(TestCase):
)
self.client.force_login(self.adduser)
- # The user can't delete sections yet, so they shouldn't see the "delete section" link.
+ # The user can't delete sections yet, so they shouldn't see the
+ # "delete section" link.
url = reverse("admin:admin_views_article_add")
delete_link_text = "delete_id_sub_section"
response = self.client.get(url)
self.assertFalse(get_delete_related(response))
self.assertNotContains(response, delete_link_text)
- # Allow the user to delete sections too. Now they can see the "delete section" link.
+ # Allow the user to delete sections too. Now they can see the
+ # "delete section" link.
user = User.objects.get(username="adduser")
perm = get_perm(Section, get_permission_codename("delete", Section._meta))
user.user_permissions.add(perm)
@@ -3061,7 +3087,8 @@ class AdminViewPermissionsTest(TestCase):
)
self.assertContains(
response,
- '<li class="success">The article “Fun &amp; games” was added successfully.</li>',
+ '<li class="success">The article “Fun &amp; games” was added successfully.'
+ "</li>",
html=True,
)
@@ -3298,7 +3325,8 @@ class AdminViewDeletedObjectsTest(TestCase):
)
self.assertContains(
response,
- "your account doesn't have permission to delete the following types of objects",
+ "your account doesn't have permission to delete the following types of "
+ "objects",
)
self.assertContains(response, "<li>plot details</li>")
@@ -3565,7 +3593,10 @@ class AdminViewStringPrimaryKeyTest(TestCase):
self.assertContains(response, escape(self.pk))
def test_changelist_to_changeform_link(self):
- "Link to the changeform of the object in changelist should use reverse() and be quoted -- #18072"
+ """
+ Link to the changeform of the object in changelist should use reverse()
+ and be quoted.
+ """
response = self.client.get(
reverse("admin:admin_views_modelwithstringprimarykey_changelist")
)
@@ -3581,7 +3612,10 @@ class AdminViewStringPrimaryKeyTest(TestCase):
self.assertContains(response, should_contain)
def test_recentactions_link(self):
- "The link from the recent actions list referring to the changeform of the object should be quoted"
+ """
+ The link from the recent actions list referring to the changeform of
+ the object should be quoted.
+ """
response = self.client.get(reverse("admin:index"))
link = reverse(
"admin:admin_views_modelwithstringprimarykey_change", args=(quote(self.pk),)
@@ -3590,7 +3624,10 @@ class AdminViewStringPrimaryKeyTest(TestCase):
self.assertContains(response, should_contain)
def test_deleteconfirmation_link(self):
- "The link from the delete confirmation page referring back to the changeform of the object should be quoted"
+ """ "
+ The link from the delete confirmation page referring back to the
+ changeform of the object should be quoted.
+ """
url = reverse(
"admin:admin_views_modelwithstringprimarykey_delete", args=(quote(self.pk),)
)
@@ -3785,10 +3822,14 @@ class AdminViewUnicodeTest(TestCase):
"chapter_set-MAX_NUM_FORMS": "0",
"chapter_set-0-id": self.chap1.pk,
"chapter_set-0-title": "Norske bostaver æøå skaper problemer",
- "chapter_set-0-content": "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;",
+ "chapter_set-0-content": (
+ "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;"
+ ),
"chapter_set-1-id": self.chap2.id,
"chapter_set-1-title": "Kjærlighet.",
- "chapter_set-1-content": "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;",
+ "chapter_set-1-content": (
+ "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;"
+ ),
"chapter_set-2-id": self.chap3.id,
"chapter_set-2-title": "Need a title.",
"chapter_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;",
@@ -4212,8 +4253,8 @@ class AdminViewListEditable(TestCase):
response,
'<div class="hiddenfields">\n'
'<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">'
- '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n</div>'
- % (story2.id, story1.id),
+ '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n'
+ "</div>" % (story2.id, story1.id),
html=True,
)
self.assertContains(response, '<td class="field-id">%d</td>' % story1.id, 1)
@@ -4242,8 +4283,8 @@ class AdminViewListEditable(TestCase):
response,
'<div class="hiddenfields">\n'
'<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">'
- '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n</div>'
- % (story2.id, story1.id),
+ '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n'
+ "</div>" % (story2.id, story1.id),
html=True,
)
self.assertContains(
@@ -5054,7 +5095,9 @@ class AdminInlineTests(TestCase):
self.assertEqual(Widget.objects.all()[0].name, "Widget 1 Updated")
def test_explicit_autofield_inline(self):
- "A model with an explicit autofield primary key can be saved as inlines. Regression for #8093"
+ """
+ A model with an explicit autofield primary key can be saved as inlines.
+ """
# First add a new inline
self.post_data["grommet_set-0-name"] = "Grommet 1"
collector_url = reverse(
@@ -5491,7 +5534,8 @@ class SeleniumTests(AdminSeleniumTestCase):
self.select_option("#id_relatedprepopulated_set-1-status", "option two")
self.selenium.find_element_by_id("id_relatedprepopulated_set-1-name").send_keys(
" now you haVe anöther sŤāÇkeð inline with a very ... "
- "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog text... "
+ "loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog "
+ "text... "
)
slug1 = self.selenium.find_element_by_id(
"id_relatedprepopulated_set-1-slug1"
@@ -5582,7 +5626,10 @@ class SeleniumTests(AdminSeleniumTestCase):
)
RelatedPrepopulated.objects.get(
# 75 characters in name field
- name=" now you haVe anöther sŤāÇkeð inline with a very ... loooooooooooooooooo",
+ name=(
+ " now you haVe anöther sŤāÇkeð inline with a very ... "
+ "loooooooooooooooooo"
+ ),
pubdate="1999-01-25",
status="option two",
slug1="now-you-have-another-stacked-inline-with-a-very-lo",
@@ -5969,17 +6016,20 @@ class ReadonlyTest(AdminFieldExtractionMixin, TestCase):
self.assertContains(response, '<div class="help">', 3)
self.assertContains(
response,
- '<div class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</div>',
+ '<div class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)'
+ "</div>",
html=True,
)
self.assertContains(
response,
- '<div class="help">Some help text for the content (with Unicode ŠĐĆŽćžšđ)</div>',
+ '<div class="help">Some help text for the content (with Unicode ŠĐĆŽćžšđ)'
+ "</div>",
html=True,
)
self.assertContains(
response,
- '<div class="help">Some help text for the date (with Unicode ŠĐĆŽćžšđ)</div>',
+ '<div class="help">Some help text for the date (with Unicode ŠĐĆŽćžšđ)'
+ "</div>",
html=True,
)
@@ -6414,7 +6464,10 @@ class UserAdminTest(TestCase):
)
def test_user_fk_add_popup(self):
- """User addition through a FK popup should return the appropriate JavaScript response."""
+ """
+ User addition through a FK popup should return the appropriate
+ JavaScript response.
+ """
response = self.client.get(reverse("admin:admin_views_album_add"))
self.assertContains(response, reverse("admin:auth_user_add"))
self.assertContains(
@@ -6439,7 +6492,10 @@ class UserAdminTest(TestCase):
self.assertContains(response, "&quot;obj&quot;: &quot;newuser&quot;")
def test_user_fk_change_popup(self):
- """User change through a FK popup should return the appropriate JavaScript response."""
+ """
+ User change through a FK popup should return the appropriate JavaScript
+ response.
+ """
response = self.client.get(reverse("admin:admin_views_album_add"))
self.assertContains(
response, reverse("admin:auth_user_change", args=("__fk__",))
@@ -6471,7 +6527,10 @@ class UserAdminTest(TestCase):
self.assertContains(response, "&quot;action&quot;: &quot;change&quot;")
def test_user_fk_delete_popup(self):
- """User deletion through a FK popup should return the appropriate JavaScript response."""
+ """
+ User deletion through a FK popup should return the appropriate
+ JavaScript response.
+ """
response = self.client.get(reverse("admin:admin_views_album_add"))
self.assertContains(
response, reverse("admin:auth_user_delete", args=("__fk__",))
@@ -6681,8 +6740,8 @@ class CSSTest(TestCase):
def test_changelist_field_classes(self):
"""
- Cells of the change list table should contain the field name in their class attribute
- Refs #11195.
+ Cells of the change list table should contain the field name in their
+ class attribute.
"""
Podcast.objects.create(name="Django Dose", release_date=datetime.date.today())
response = self.client.get(reverse("admin:admin_views_podcast_changelist"))
@@ -7175,33 +7234,27 @@ class AdminKeepChangeListFiltersTests(TestCase):
"admin:auth_user_change", args=(self.joepublicuser.pk,)
)
self.assertURLEqual(
- "http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0".format(
- change_user_url
- ),
- "http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0".format(
- change_user_url
- ),
+ "http://testserver{}?_changelist_filters="
+ "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url),
+ "http://testserver{}?_changelist_filters="
+ "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url),
)
# Test inequality.
with self.assertRaises(AssertionError):
self.assertURLEqual(
- "http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0".format(
- change_user_url
- ),
- "http://testserver{}?_changelist_filters=is_staff__exact%3D1%26is_superuser__exact%3D1".format(
- change_user_url
- ),
+ "http://testserver{}?_changelist_filters="
+ "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url),
+ "http://testserver{}?_changelist_filters="
+ "is_staff__exact%3D1%26is_superuser__exact%3D1".format(change_user_url),
)
# Ignore scheme and host.
self.assertURLEqual(
- "http://testserver{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0".format(
- change_user_url
- ),
- "{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0".format(
- change_user_url
- ),
+ "http://testserver{}?_changelist_filters="
+ "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url),
+ "{}?_changelist_filters="
+ "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url),
)
# Ignore ordering of querystring.
@@ -7216,12 +7269,10 @@ class AdminKeepChangeListFiltersTests(TestCase):
# Ignore ordering of _changelist_filters.
self.assertURLEqual(
- "{}?_changelist_filters=is_staff__exact%3D0%26is_superuser__exact%3D0".format(
- change_user_url
- ),
- "{}?_changelist_filters=is_superuser__exact%3D0%26is_staff__exact%3D0".format(
- change_user_url
- ),
+ "{}?_changelist_filters="
+ "is_staff__exact%3D0%26is_superuser__exact%3D0".format(change_user_url),
+ "{}?_changelist_filters="
+ "is_superuser__exact%3D0%26is_staff__exact%3D0".format(change_user_url),
)
def get_changelist_filters(self):
@@ -7531,7 +7582,10 @@ class AdminViewOnSiteTests(TestCase):
self.assertFormError(
response, "adminform", "some_required_info", ["This field is required."]
)
- msg = "The form 'adminform' in context 0 does not contain the non-field error 'Error'"
+ msg = (
+ "The form 'adminform' in context 0 does not contain the non-field error "
+ "'Error'"
+ )
with self.assertRaisesMessage(AssertionError, msg):
self.assertFormError(response, "adminform", None, ["Error"])
self.assertFormsetError(
@@ -7540,10 +7594,14 @@ class AdminViewOnSiteTests(TestCase):
0,
None,
[
- "Children must share a family name with their parents in this contrived test case"
+ "Children must share a family name with their parents in this "
+ "contrived test case"
],
)
- msg = "The formset 'inline_admin_formset' in context 22 does not contain any non-form errors."
+ msg = (
+ "The formset 'inline_admin_formset' in context 22 does not contain any "
+ "non-form errors."
+ )
with self.assertRaisesMessage(AssertionError, msg):
self.assertFormsetError(
response, "inline_admin_formset", None, None, ["Error"]
@@ -7585,7 +7643,8 @@ class AdminViewOnSiteTests(TestCase):
0,
None,
[
- "Children must share a family name with their parents in this contrived test case"
+ "Children must share a family name with their parents in this "
+ "contrived test case"
],
)
@@ -7604,7 +7663,8 @@ class AdminViewOnSiteTests(TestCase):
admin.check(),
[
Error(
- "The value of 'view_on_site' must be a callable or a boolean value.",
+ "The value of 'view_on_site' must be a callable or a boolean "
+ "value.",
obj=CityAdmin,
id="admin.E025",
),
@@ -7941,7 +8001,7 @@ class AdminSiteFinalCatchAllPatternTests(TestCase):
response = self.client.get(unknown_url)
self.assertEqual(response.status_code, 404)
- def test_known_url_redirects_login_if_not_authenticated_without_final_catch_all_view(
+ def test_known_url_redirects_login_if_not_auth_without_final_catch_all_view(
self,
):
known_url = reverse("admin10:admin_views_article_changelist")
@@ -7950,7 +8010,7 @@ class AdminSiteFinalCatchAllPatternTests(TestCase):
response, "%s?next=%s" % (reverse("admin10:login"), known_url)
)
- def test_known_url_missing_slash_redirects_with_slash_if_not_authenticated_without_final_catch_all_view(
+ def test_known_url_missing_slash_redirects_with_slash_if_not_auth_no_catch_all_view(
self,
):
known_url = reverse("admin10:admin_views_article_changelist")
@@ -7964,14 +8024,14 @@ class AdminSiteFinalCatchAllPatternTests(TestCase):
response = self.client.get(url[:-1])
self.assertRedirects(response, url, status_code=301)
- def test_url_without_trailing_slash_if_not_authenticated_without_final_catch_all_view(
+ def test_url_no_trailing_slash_if_not_auth_without_final_catch_all_view(
self,
):
url = reverse("admin10:article_extra_json")
response = self.client.get(url)
self.assertRedirects(response, "%s?next=%s" % (reverse("admin10:login"), url))
- def test_unkown_url_without_trailing_slash_if_not_authenticated_without_final_catch_all_view(
+ def test_unknown_url_no_trailing_slash_if_not_auth_without_final_catch_all_view(
self,
):
url = reverse("admin10:article_extra_json")[:-1]
diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py
index 8fb53f3372..c921b4abcd 100644
--- a/tests/admin_widgets/tests.py
+++ b/tests/admin_widgets/tests.py
@@ -313,7 +313,8 @@ class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase):
self.assertContains(
response,
- "Select a valid choice. That choice is not one of the available choices.",
+ "Select a valid choice. That choice is not one of the available "
+ "choices.",
)
def test_url_params_from_lookup_dict_any_iterable(self):
@@ -362,13 +363,15 @@ class AdminDateWidgetTest(SimpleTestCase):
w = widgets.AdminDateWidget()
self.assertHTMLEqual(
w.render("test", datetime(2007, 12, 1, 9, 30)),
- '<input value="2007-12-01" type="text" class="vDateField" name="test" size="10">',
+ '<input value="2007-12-01" type="text" class="vDateField" name="test" '
+ 'size="10">',
)
# pass attrs to widget
w = widgets.AdminDateWidget(attrs={"size": 20, "class": "myDateField"})
self.assertHTMLEqual(
w.render("test", datetime(2007, 12, 1, 9, 30)),
- '<input value="2007-12-01" type="text" class="myDateField" name="test" size="20">',
+ '<input value="2007-12-01" type="text" class="myDateField" name="test" '
+ 'size="20">',
)
@@ -377,13 +380,15 @@ class AdminTimeWidgetTest(SimpleTestCase):
w = widgets.AdminTimeWidget()
self.assertHTMLEqual(
w.render("test", datetime(2007, 12, 1, 9, 30)),
- '<input value="09:30:00" type="text" class="vTimeField" name="test" size="8">',
+ '<input value="09:30:00" type="text" class="vTimeField" name="test" '
+ 'size="8">',
)
# pass attrs to widget
w = widgets.AdminTimeWidget(attrs={"size": 20, "class": "myTimeField"})
self.assertHTMLEqual(
w.render("test", datetime(2007, 12, 1, 9, 30)),
- '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20">',
+ '<input value="09:30:00" type="text" class="myTimeField" name="test" '
+ 'size="20">',
)
@@ -485,7 +490,8 @@ class AdminURLWidgetTest(SimpleTestCase):
)
self.assertEqual(
HREF_RE.search(output)[1],
- "http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22",
+ "http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)"
+ "%3C/script%3E%22",
)
self.assertEqual(
TEXT_RE.search(output)[1],
@@ -494,7 +500,8 @@ class AdminURLWidgetTest(SimpleTestCase):
)
self.assertEqual(
VALUE_RE.search(output)[1],
- "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;",
+ "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;"
+ "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;",
)
@@ -503,12 +510,14 @@ class AdminUUIDWidgetTests(SimpleTestCase):
w = widgets.AdminUUIDInputWidget()
self.assertHTMLEqual(
w.render("test", "550e8400-e29b-41d4-a716-446655440000"),
- '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" class="vUUIDField" name="test">',
+ '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" '
+ 'class="vUUIDField" name="test">',
)
w = widgets.AdminUUIDInputWidget(attrs={"class": "myUUIDInput"})
self.assertHTMLEqual(
w.render("test", "550e8400-e29b-41d4-a716-446655440000"),
- '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" class="myUUIDInput" name="test">',
+ '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" '
+ 'class="myUUIDInput" name="test">',
)
@@ -676,7 +685,8 @@ class ForeignKeyRawIdWidgetTest(TestCase):
)
self.assertHTMLEqual(
w.render("test", child_of_hidden.parent_id, attrs={}),
- '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField">'
+ '<input type="text" name="test" value="93" '
+ ' class="vForeignKeyRawIdAdminField">'
'<a href="/admin_widgets/inventory/?_to_field=barcode" '
'class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
'&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">'
@@ -689,8 +699,9 @@ class ForeignKeyRawIdWidgetTest(TestCase):
self.assertHTMLEqual(
w.render("test", None),
'<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n'
- '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;_to_field=artist_ptr" '
- 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>',
+ '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;'
+ '_to_field=artist_ptr" class="related-lookup" id="lookup_id_test" '
+ 'title="Lookup"></a>',
)
def test_render_fk_as_pk_model(self):
@@ -718,8 +729,10 @@ class ManyToManyRawIdWidgetTest(TestCase):
self.assertHTMLEqual(
w.render("test", [m1.pk, m2.pk], attrs={}),
(
- '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField">'
- '<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
+ '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" '
+ ' class="vManyToManyRawIdAdminField">'
+ '<a href="/admin_widgets/member/" class="related-lookup" '
+ ' id="lookup_id_test" title="Lookup"></a>'
)
% {"m1pk": m1.pk, "m2pk": m2.pk},
)
@@ -727,8 +740,10 @@ class ManyToManyRawIdWidgetTest(TestCase):
self.assertHTMLEqual(
w.render("test", [m1.pk]),
(
- '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
- '<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
+ '<input type="text" name="test" value="%(m1pk)s" '
+ ' class="vManyToManyRawIdAdminField">'
+ '<a href="/admin_widgets/member/" class="related-lookup" '
+ ' id="lookup_id_test" title="Lookup"></a>'
)
% {"m1pk": m1.pk},
)
diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
index 98e5f8124b..bdc73b1049 100644
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -140,7 +140,10 @@ class AggregateTestCase(TestCase):
)
cls.b6 = Book.objects.create(
isbn="155860191",
- name="Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ name=(
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp"
+ ),
pages=946,
rating=5.0,
price=Decimal("75.00"),
@@ -249,7 +252,8 @@ class AggregateTestCase(TestCase):
"Practical Django Projects",
"Python Web Development with Django",
"Artificial Intelligence: A Modern Approach",
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp",
],
lambda b: b.name,
)
@@ -326,7 +330,8 @@ class AggregateTestCase(TestCase):
[
("Artificial Intelligence: A Modern Approach", 2),
(
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp",
1,
),
("Practical Django Projects", 1),
@@ -380,7 +385,8 @@ class AggregateTestCase(TestCase):
[
("Artificial Intelligence: A Modern Approach", 7),
(
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp",
9,
),
("Practical Django Projects", 3),
@@ -418,7 +424,9 @@ class AggregateTestCase(TestCase):
"id": self.b1.id,
"isbn": "159059725",
"mean_age": 34.5,
- "name": "The Definitive Guide to Django: Web Development Done Right",
+ "name": (
+ "The Definitive Guide to Django: Web Development Done Right"
+ ),
"pages": 447,
"price": Approximate(Decimal("30")),
"pubdate": datetime.date(2007, 12, 6),
@@ -467,7 +475,9 @@ class AggregateTestCase(TestCase):
"id": self.b1.id,
"isbn": "159059725",
"mean_age": 34.5,
- "name": "The Definitive Guide to Django: Web Development Done Right",
+ "name": (
+ "The Definitive Guide to Django: Web Development Done Right"
+ ),
"pages": 447,
"price": Approximate(Decimal("30")),
"pubdate": datetime.date(2007, 12, 6),
@@ -1476,7 +1486,9 @@ class AggregateTestCase(TestCase):
[
{"name": "Practical Django Projects", "min_age": 34},
{
- "name": "The Definitive Guide to Django: Web Development Done Right",
+ "name": (
+ "The Definitive Guide to Django: Web Development Done Right"
+ ),
"min_age": 29,
},
],
diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py
index ae7e4a0be5..7b92b6d271 100644
--- a/tests/aggregation_regress/tests.py
+++ b/tests/aggregation_regress/tests.py
@@ -123,7 +123,10 @@ class AggregationTests(TestCase):
)
cls.b6 = HardbackBook.objects.create(
isbn="155860191",
- name="Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ name=(
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp"
+ ),
pages=946,
rating=5.0,
price=Decimal("75.00"),
@@ -824,7 +827,8 @@ class AggregationTests(TestCase):
[
"Practical Django Projects",
"The Definitive Guide to Django: Web Development Done Right",
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp",
"Artificial Intelligence: A Modern Approach",
"Python Web Development with Django",
"Sams Teach Yourself Django in 24 Hours",
@@ -952,8 +956,8 @@ class AggregationTests(TestCase):
Book.objects.annotate(contact_id=F("publisher_id"))
def test_values_queryset_non_conflict(self):
- # Regression for #14707 -- If you're using a values query set, some potential conflicts are avoided.
-
+ # If you're using a values query set, some potential conflicts are
+ # avoided.
# age is a field on Author, so it shouldn't be allowed as an aggregate.
# But age isn't included in values(), so it is.
results = (
@@ -1015,7 +1019,8 @@ class AggregationTests(TestCase):
books.all(),
[
"Artificial Intelligence: A Modern Approach",
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp",
"Practical Django Projects",
"Python Web Development with Django",
"Sams Teach Yourself Django in 24 Hours",
@@ -1107,7 +1112,10 @@ class AggregationTests(TestCase):
{"n_authors": 2, "name": "Artificial Intelligence: A Modern Approach"},
{
"n_authors": 1,
- "name": "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "name": (
+ "Paradigms of Artificial Intelligence Programming: Case "
+ "Studies in Common Lisp"
+ ),
},
],
)
@@ -1123,7 +1131,10 @@ class AggregationTests(TestCase):
{"n_authors": 2, "name": "Artificial Intelligence: A Modern Approach"},
{
"n_authors": 1,
- "name": "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "name": (
+ "Paradigms of Artificial Intelligence Programming: Case "
+ "Studies in Common Lisp"
+ ),
},
],
)
@@ -1462,7 +1473,8 @@ class AggregationTests(TestCase):
num_authors=Count("authors")
)
_, _, grouping = results.query.get_compiler(using="default").pre_sql_setup()
- # In the case of `group_by_selected_pks` we also group by contact.id because of the select_related.
+ # In the case of `group_by_selected_pks` we also group by contact.id
+ # because of the select_related.
self.assertEqual(
len(grouping), 1 if connection.features.allows_group_by_pk else 2
)
@@ -1474,7 +1486,8 @@ class AggregationTests(TestCase):
[
("Artificial Intelligence: A Modern Approach", 2),
(
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp",
1,
),
("Practical Django Projects", 1),
@@ -1497,7 +1510,8 @@ class AggregationTests(TestCase):
[
("Artificial Intelligence: A Modern Approach", 2),
(
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case "
+ "Studies in Common Lisp",
1,
),
("Practical Django Projects", 1),
@@ -1553,14 +1567,16 @@ class AggregationTests(TestCase):
[
("Artificial Intelligence: A Modern Approach", 2),
(
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case "
+ "Studies in Common Lisp",
1,
),
("Practical Django Projects", 1),
("Python Web Development with Django", 3),
("Sams Teach Yourself Django in 24 Hours", 1),
(
- "The Definitive Guide to Django: Web Development Done Right",
+ "The Definitive Guide to Django: Web Development Done "
+ "Right",
2,
),
],
@@ -1614,7 +1630,8 @@ class AggregationTests(TestCase):
[
("Practical Django Projects", 2),
(
- "Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp",
1,
),
("Artificial Intelligence: A Modern Approach", 0),
diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py
index ba833fd441..e589b4ddc0 100644
--- a/tests/annotations/tests.py
+++ b/tests/annotations/tests.py
@@ -119,7 +119,10 @@ class NonAggregateAnnotationTestCase(TestCase):
)
cls.b6 = Book.objects.create(
isbn="155860191",
- name="Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ name=(
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp"
+ ),
pages=946,
rating=5.0,
price=Decimal("75.00"),
@@ -1101,7 +1104,10 @@ class AliasTests(TestCase):
contact=cls.a4,
publisher=p1,
pubdate=datetime.date(1991, 10, 15),
- name="Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp",
+ name=(
+ "Paradigms of Artificial Intelligence Programming: Case Studies in "
+ "Common Lisp"
+ ),
)
cls.b1.authors.add(cls.a1, cls.a2)
cls.b2.authors.add(cls.a3)
diff --git a/tests/app_loading/tests.py b/tests/app_loading/tests.py
index e28b8dce07..1499115386 100644
--- a/tests/app_loading/tests.py
+++ b/tests/app_loading/tests.py
@@ -22,7 +22,10 @@ class EggLoadingTest(SimpleTestCase):
del apps.all_models["app_with_models"]
def test_egg2(self):
- """Loading an app from an egg that has no models returns no models (and no error)"""
+ """
+ Loading an app from an egg that has no models returns no models (and no
+ error).
+ """
egg_name = "%s/nomodelapp.egg" % self.egg_dir
with extend_sys_path(egg_name):
with self.settings(INSTALLED_APPS=["app_no_models"]):
@@ -31,7 +34,10 @@ class EggLoadingTest(SimpleTestCase):
del apps.all_models["app_no_models"]
def test_egg3(self):
- """Models module can be loaded from an app located under an egg's top-level package"""
+ """
+ Models module can be loaded from an app located under an egg's
+ top-level package.
+ """
egg_name = "%s/omelet.egg" % self.egg_dir
with extend_sys_path(egg_name):
with self.settings(INSTALLED_APPS=["omelet.app_with_models"]):
@@ -40,7 +46,10 @@ class EggLoadingTest(SimpleTestCase):
del apps.all_models["app_with_models"]
def test_egg4(self):
- """Loading an app with no models from under the top-level egg package generates no error"""
+ """
+ Loading an app with no models from under the top-level egg package
+ generates no error.
+ """
egg_name = "%s/omelet.egg" % self.egg_dir
with extend_sys_path(egg_name):
with self.settings(INSTALLED_APPS=["omelet.app_no_models"]):
@@ -49,7 +58,10 @@ class EggLoadingTest(SimpleTestCase):
del apps.all_models["app_no_models"]
def test_egg5(self):
- """Loading an app from an egg that has an import error in its models module raises that error"""
+ """
+ Loading an app from an egg that has an import error in its models
+ module raises that error.
+ """
egg_name = "%s/brokenapp.egg" % self.egg_dir
with extend_sys_path(egg_name):
with self.assertRaisesMessage(ImportError, "modelz"):
diff --git a/tests/apps/tests.py b/tests/apps/tests.py
index bf3c25ab0b..00b1aa50b9 100644
--- a/tests/apps/tests.py
+++ b/tests/apps/tests.py
@@ -83,7 +83,10 @@ class AppsTests(SimpleTestCase):
with self.assertRaises(ImportError):
with self.settings(INSTALLED_APPS=["there is no such app"]):
pass
- msg = "Cannot import 'there is no such app'. Check that 'apps.apps.NoSuchApp.name' is correct."
+ msg = (
+ "Cannot import 'there is no such app'. Check that "
+ "'apps.apps.NoSuchApp.name' is correct."
+ )
with self.assertRaisesMessage(ImproperlyConfigured, msg):
with self.settings(INSTALLED_APPS=["apps.apps.NoSuchApp"]):
pass
diff --git a/tests/auth_tests/test_checks.py b/tests/auth_tests/test_checks.py
index cd19fbcc9b..5757946f95 100644
--- a/tests/auth_tests/test_checks.py
+++ b/tests/auth_tests/test_checks.py
@@ -89,7 +89,10 @@ class UserModelChecksTests(SimpleTestCase):
checks.Warning(
"'CustomUserNonUniqueUsername.username' is named as "
"the 'USERNAME_FIELD', but it is not unique.",
- hint="Ensure that your authentication backend(s) can handle non-unique usernames.",
+ hint=(
+ "Ensure that your authentication backend(s) can handle "
+ "non-unique usernames."
+ ),
obj=CustomUserNonUniqueUsername,
id="auth.W004",
),
@@ -264,8 +267,9 @@ class ModelsPermissionsChecksTests(SimpleTestCase):
errors,
[
checks.Error(
- "The verbose_name of model 'auth_tests.Checked' must be at most 244 "
- "characters for its builtin permission names to be at most 255 characters.",
+ "The verbose_name of model 'auth_tests.Checked' must be at most "
+ "244 characters for its builtin permission names to be at most 255 "
+ "characters.",
obj=Checked,
id="auth.E007",
),
diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py
index 1713d367c3..ea52254123 100644
--- a/tests/auth_tests/test_forms.py
+++ b/tests/auth_tests/test_forms.py
@@ -174,10 +174,15 @@ class UserCreationFormTest(TestDataMixin, TestCase):
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
{
- "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
+ "NAME": (
+ "django.contrib.auth.password_validation.MinimumLengthValidator"
+ ),
"OPTIONS": {
"min_length": 12,
},
@@ -259,7 +264,10 @@ class UserCreationFormTest(TestDataMixin, TestCase):
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
]
)
@@ -267,13 +275,18 @@ class UserCreationFormTest(TestDataMixin, TestCase):
form = UserCreationForm()
self.assertEqual(
form.fields["password1"].help_text,
- "<ul><li>Your password can’t be too similar to your other personal information.</li></ul>",
+ "<ul><li>"
+ "Your password can’t be too similar to your other personal information."
+ "</li></ul>",
)
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
]
)
@@ -610,10 +623,15 @@ class SetPasswordFormTest(TestDataMixin, TestCase):
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
{
- "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
+ "NAME": (
+ "django.contrib.auth.password_validation.MinimumLengthValidator"
+ ),
"OPTIONS": {
"min_length": 12,
},
@@ -651,10 +669,15 @@ class SetPasswordFormTest(TestDataMixin, TestCase):
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
{
- "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
+ "NAME": (
+ "django.contrib.auth.password_validation.MinimumLengthValidator"
+ ),
"OPTIONS": {
"min_length": 12,
},
@@ -663,7 +686,8 @@ class SetPasswordFormTest(TestDataMixin, TestCase):
)
def test_help_text_translation(self):
french_help_texts = [
- "Votre mot de passe ne peut pas trop ressembler à vos autres informations personnelles.",
+ "Votre mot de passe ne peut pas trop ressembler à vos autres informations "
+ "personnelles.",
"Votre mot de passe doit contenir au minimum 12 caractères.",
]
form = SetPasswordForm(self.u1)
@@ -1129,7 +1153,10 @@ class ReadOnlyPasswordHashTest(SimpleTestCase):
)
def test_render(self):
widget = ReadOnlyPasswordHashWidget()
- value = "pbkdf2_sha256$100000$a6Pucb1qSFcD$WmCkn9Hqidj48NVe5x0FEM6A9YiOqQcl/83m2Z5udm0="
+ value = (
+ "pbkdf2_sha256$100000$a6Pucb1qSFcD$WmCkn9Hqidj48NVe5x0FEM6A9YiOqQcl/83m2Z5u"
+ "dm0="
+ )
self.assertHTMLEqual(
widget.render("name", value, {"id": "id_password"}),
"""
diff --git a/tests/auth_tests/test_hashers.py b/tests/auth_tests/test_hashers.py
index a1cff1ffa6..76144c19a0 100644
--- a/tests/auth_tests/test_hashers.py
+++ b/tests/auth_tests/test_hashers.py
@@ -390,7 +390,8 @@ class TestUtilsHashPass(SimpleTestCase):
encoded = hasher.encode("lètmein", "seasalt2")
self.assertEqual(
encoded,
- "pbkdf2_sha256$320000$seasalt2$BRr4pYNIQDsLFP+u4dzjs7pFuWJEin4lFMMoO9wBYvo=",
+ "pbkdf2_sha256$320000$seasalt2$BRr4pYNIQDsLFP+u4dzjs7pFuWJEin4lFMM"
+ "oO9wBYvo=",
)
self.assertTrue(hasher.verify("lètmein", encoded))
diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py
index 72d4d9a251..49a64edf50 100644
--- a/tests/auth_tests/test_management.py
+++ b/tests/auth_tests/test_management.py
@@ -202,7 +202,8 @@ class ChangepasswordManagementCommandTestCase(TestCase):
self.assertEqual(
command_output,
- "Changing password for user 'joe'\nPassword changed successfully for user 'joe'",
+ "Changing password for user 'joe'\n"
+ "Password changed successfully for user 'joe'",
)
self.assertTrue(User.objects.get(username="joe").check_password("not qwerty"))
@@ -267,7 +268,8 @@ class MultiDBChangepasswordManagementCommandTestCase(TestCase):
self.assertEqual(
command_output,
- "Changing password for user 'joe'\nPassword changed successfully for user 'joe'",
+ "Changing password for user 'joe'\n"
+ "Password changed successfully for user 'joe'",
)
self.assertTrue(
User.objects.using("other").get(username="joe").check_password("not qwerty")
@@ -748,7 +750,10 @@ class CreatesuperuserManagementCommandTestCase(TestCase):
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
]
)
@@ -793,7 +798,10 @@ class CreatesuperuserManagementCommandTestCase(TestCase):
AUTH_USER_MODEL="auth_tests.CustomUser",
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
],
)
@@ -840,7 +848,10 @@ class CreatesuperuserManagementCommandTestCase(TestCase):
AUTH_USER_MODEL="auth_tests.CustomUser",
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
],
)
@@ -1057,7 +1068,10 @@ class CreatesuperuserManagementCommandTestCase(TestCase):
stdout=new_io,
stderr=new_io,
)
- msg = "Error: That username is already taken.\nSuperuser created successfully."
+ msg = (
+ "Error: That username is already taken.\n"
+ "Superuser created successfully."
+ )
self.assertEqual(new_io.getvalue().strip(), msg)
test(self)
diff --git a/tests/auth_tests/test_views.py b/tests/auth_tests/test_views.py
index 5ba05e8a00..38e2234416 100644
--- a/tests/auth_tests/test_views.py
+++ b/tests/auth_tests/test_views.py
@@ -172,7 +172,10 @@ class PasswordResetTest(AuthViewsTestCase):
self.assertIn("<html>", message.get_payload(1).get_payload())
def test_email_found_custom_from(self):
- "Email is sent if a valid email address is provided for password reset when a custom from_email is provided."
+ """
+ Email is sent if a valid email address is provided for password reset
+ when a custom from_email is provided.
+ """
response = self.client.post(
"/password_reset_from_email/", {"email": "staffmember@example.com"}
)
diff --git a/tests/auth_tests/urls.py b/tests/auth_tests/urls.py
index 9f8cd14bdd..99fa22e4f4 100644
--- a/tests/auth_tests/urls.py
+++ b/tests/auth_tests/urls.py
@@ -148,7 +148,9 @@ urlpatterns = auth_urlpatterns + [
"reset/post_reset_login_custom_backend/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(
post_reset_login=True,
- post_reset_login_backend="django.contrib.auth.backends.AllowAllUsersModelBackend",
+ post_reset_login_backend=(
+ "django.contrib.auth.backends.AllowAllUsersModelBackend"
+ ),
),
),
path("reset/missing_parameters/", views.PasswordResetConfirmView.as_view()),
diff --git a/tests/backends/mysql/tests.py b/tests/backends/mysql/tests.py
index 6ea289e151..139b363bf4 100644
--- a/tests/backends/mysql/tests.py
+++ b/tests/backends/mysql/tests.py
@@ -40,7 +40,8 @@ class IsolationLevelTests(TestCase):
def get_isolation_level(connection):
with connection.cursor() as cursor:
cursor.execute(
- "SHOW VARIABLES WHERE variable_name IN ('transaction_isolation', 'tx_isolation')"
+ "SHOW VARIABLES "
+ "WHERE variable_name IN ('transaction_isolation', 'tx_isolation')"
)
return cursor.fetchone()[1].replace("-", " ")
diff --git a/tests/backends/oracle/tests.py b/tests/backends/oracle/tests.py
index 185488a5b8..d191d98066 100644
--- a/tests/backends/oracle/tests.py
+++ b/tests/backends/oracle/tests.py
@@ -86,9 +86,9 @@ class TransactionalTests(TransactionTestCase):
with self.assertRaisesMessage(
DatabaseError,
(
- 'The database did not return a new row id. Probably "ORA-1403: '
- 'no data found" was raised internally but was hidden by the '
- "Oracle OCI library (see https://code.djangoproject.com/ticket/28859)."
+ 'The database did not return a new row id. Probably "ORA-1403: no '
+ 'data found" was raised internally but was hidden by the Oracle '
+ "OCI library (see https://code.djangoproject.com/ticket/28859)."
),
):
Square.objects.create(root=2, square=4)
diff --git a/tests/backends/test_utils.py b/tests/backends/test_utils.py
index 1b830eaced..03d4b036fd 100644
--- a/tests/backends/test_utils.py
+++ b/tests/backends/test_utils.py
@@ -130,7 +130,10 @@ class CursorWrapperTests(TransactionTestCase):
@skipIfDBFeature("supports_callproc_kwargs")
def test_unsupported_callproc_kparams_raises_error(self):
- msg = "Keyword parameters for callproc are not supported on this database backend."
+ msg = (
+ "Keyword parameters for callproc are not supported on this database "
+ "backend."
+ )
with self.assertRaisesMessage(NotSupportedError, msg):
with connection.cursor() as cursor:
cursor.callproc("test_procedure", [], {"P_I": 1})
diff --git a/tests/backends/tests.py b/tests/backends/tests.py
index c6c79b4bf7..28e00a04ca 100644
--- a/tests/backends/tests.py
+++ b/tests/backends/tests.py
@@ -128,7 +128,10 @@ class LastExecutedQueryTest(TestCase):
class ParameterHandlingTest(TestCase):
def test_bad_parameter_count(self):
- "An executemany call with too many/not enough parameters will raise an exception (Refs #12612)"
+ """
+ An executemany call with too many/not enough parameters will raise an
+ exception.
+ """
with connection.cursor() as cursor:
query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (
connection.introspection.identifier_converter("backends_square"),
@@ -152,7 +155,7 @@ class LongNameTest(TransactionTestCase):
available_apps = ["backends"]
def test_sequence_name_length_limits_create(self):
- """Test creation of model with long name and long pk name doesn't error. Ref #8901"""
+ """Creation of model with long name and long pk name doesn't error."""
VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create()
def test_sequence_name_length_limits_m2m(self):
@@ -517,7 +520,10 @@ class BackendTestCase(TransactionTestCase):
cursor.execute("SELECT 3" + new_connection.features.bare_select_suffix)
cursor.execute("SELECT 4" + new_connection.features.bare_select_suffix)
- msg = "Limit for query logging exceeded, only the last 3 queries will be returned."
+ msg = (
+ "Limit for query logging exceeded, only the last 3 queries will be "
+ "returned."
+ )
with self.assertWarnsMessage(UserWarning, msg):
self.assertEqual(3, len(new_connection.queries))
diff --git a/tests/basic/tests.py b/tests/basic/tests.py
index 1f17ee10f6..f3dd038051 100644
--- a/tests/basic/tests.py
+++ b/tests/basic/tests.py
@@ -801,7 +801,10 @@ class ModelRefreshTests(TestCase):
def test_lookup_in_fields(self):
s = SelfRef.objects.create()
- msg = 'Found "__" in fields argument. Relations and transforms are not allowed in fields.'
+ msg = (
+ 'Found "__" in fields argument. Relations and transforms are not allowed '
+ "in fields."
+ )
with self.assertRaisesMessage(ValueError, msg):
s.refresh_from_db(fields=["foo__bar"])
diff --git a/tests/cache/tests.py b/tests/cache/tests.py
index 51ca4c37f9..7764b92597 100644
--- a/tests/cache/tests.py
+++ b/tests/cache/tests.py
@@ -1761,9 +1761,9 @@ class FileBasedCacheTests(BaseCacheTests, TestCase):
def setUp(self):
super().setUp()
self.dirname = self.mkdtemp()
- # Caches location cannot be modified through override_settings / modify_settings,
- # hence settings are manipulated directly here and the setting_changed signal
- # is triggered manually.
+ # Caches location cannot be modified through override_settings /
+ # modify_settings, hence settings are manipulated directly here and the
+ # setting_changed signal is triggered manually.
for cache_params in settings.CACHES.values():
cache_params["LOCATION"] = self.dirname
setting_changed.send(self.__class__, setting="CACHES", enter=False)
@@ -2160,7 +2160,8 @@ class CacheUtils(SimpleTestCase):
def test_patch_cache_control(self):
tests = (
- # Initial Cache-Control, kwargs to patch_cache_control, expected Cache-Control parts
+ # Initial Cache-Control, kwargs to patch_cache_control, expected
+ # Cache-Control parts.
(None, {"private": True}, {"private"}),
("", {"private": True}, {"private"}),
# no-cache.
@@ -2541,9 +2542,9 @@ class CacheMiddlewareTest(SimpleTestCase):
def test_constructor(self):
"""
- Ensure the constructor is correctly distinguishing between usage of CacheMiddleware as
- Middleware vs. usage of CacheMiddleware as view decorator and setting attributes
- appropriately.
+ The constructor is correctly distinguishing between usage of
+ CacheMiddleware as Middleware vs. usage of CacheMiddleware as view
+ decorator and setting attributes appropriately.
"""
# If only one argument is passed in construction, it's being used as
# middleware.
diff --git a/tests/check_framework/test_model_field_deprecation.py b/tests/check_framework/test_model_field_deprecation.py
index 668553c04e..50cca0ed8a 100644
--- a/tests/check_framework/test_model_field_deprecation.py
+++ b/tests/check_framework/test_model_field_deprecation.py
@@ -64,7 +64,10 @@ class TestRemovedField(SimpleTestCase):
model.check(),
[
checks.Error(
- msg="MyField has been removed except for support in historical migrations.",
+ msg=(
+ "MyField has been removed except for support in historical "
+ "migrations."
+ ),
obj=Model._meta.get_field("name"),
id="fields.EXXX",
)
diff --git a/tests/check_framework/test_security.py b/tests/check_framework/test_security.py
index d73e9075e8..30c4135373 100644
--- a/tests/check_framework/test_security.py
+++ b/tests/check_framework/test_security.py
@@ -502,7 +502,9 @@ class CSRFFailureViewTest(SimpleTestCase):
)
@override_settings(
- CSRF_FAILURE_VIEW="check_framework.test_security.failure_view_with_invalid_signature",
+ CSRF_FAILURE_VIEW=(
+ "check_framework.test_security.failure_view_with_invalid_signature"
+ ),
)
def test_failure_view_invalid_signature(self):
msg = (
diff --git a/tests/check_framework/test_translation.py b/tests/check_framework/test_translation.py
index b20ed90860..cba38af2ff 100644
--- a/tests/check_framework/test_translation.py
+++ b/tests/check_framework/test_translation.py
@@ -75,7 +75,10 @@ class TranslationCheckTests(SimpleTestCase):
self.assertEqual(check_setting_languages_bidi(None), [])
def test_invalid_languages_bidi(self):
- msg = "You have provided an invalid language code in the LANGUAGES_BIDI setting: %r."
+ msg = (
+ "You have provided an invalid language code in the LANGUAGES_BIDI setting: "
+ "%r."
+ )
for tag in self.invalid_tags:
with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]):
self.assertEqual(
diff --git a/tests/check_framework/test_urls.py b/tests/check_framework/test_urls.py
index 6315f8834d..a9038c6f13 100644
--- a/tests/check_framework/test_urls.py
+++ b/tests/check_framework/test_urls.py
@@ -52,9 +52,9 @@ class CheckUrlConfigTests(SimpleTestCase):
self.assertRegex(
warning.msg,
(
- r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) is "
- r"invalid. Ensure that urlpatterns is a list of path\(\) and/or re_path\(\) "
- r"instances\.$"
+ r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) "
+ r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or "
+ r"re_path\(\) instances\.$"
),
)
@@ -66,9 +66,9 @@ class CheckUrlConfigTests(SimpleTestCase):
self.assertRegex(
warning.msg,
(
- r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) is "
- r"invalid. Ensure that urlpatterns is a list of path\(\) and/or re_path\(\) "
- r"instances\.$"
+ r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) "
+ r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or "
+ r"re_path\(\) instances\.$"
),
)
@@ -211,7 +211,8 @@ class CheckCustomErrorHandlersTests(SimpleTestCase):
Error(
"The custom handler{} view 'check_framework.urls."
"bad_function_based_error_handlers.bad_handler' "
- "does not take the correct number of arguments (request{}).".format(
+ "does not take the correct number of arguments "
+ "(request{}).".format(
code, ", exception" if num_params == 2 else ""
),
id="urls.E007",
@@ -254,7 +255,8 @@ class CheckCustomErrorHandlersTests(SimpleTestCase):
]
hints = [
"Could not import '{}'. View does not exist in module django.views.",
- "Could not import '{}'. Parent module django.invalid_module does not exist.",
+ "Could not import '{}'. Parent module django.invalid_module does not "
+ "exist.",
"No module named 'invalid_module'",
"Could not import '{}'. The path must be fully qualified.",
]
diff --git a/tests/contenttypes_tests/test_checks.py b/tests/contenttypes_tests/test_checks.py
index b3f4a0f4ba..bd36c569a1 100644
--- a/tests/contenttypes_tests/test_checks.py
+++ b/tests/contenttypes_tests/test_checks.py
@@ -60,7 +60,8 @@ class GenericForeignKeyTests(SimpleTestCase):
Model.content_object.check(),
[
checks.Error(
- "'Model.content_type' is not a ForeignKey to 'contenttypes.ContentType'.",
+ "'Model.content_type' is not a ForeignKey to "
+ "'contenttypes.ContentType'.",
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
@@ -221,7 +222,9 @@ class GenericRelationTests(SimpleTestCase):
"Field defines a relation with the model "
"'contenttypes_tests.SwappedModel', "
"which has been swapped out.",
- hint="Update the relation to point at 'settings.TEST_SWAPPED_MODEL'.",
+ hint=(
+ "Update the relation to point at 'settings.TEST_SWAPPED_MODEL'."
+ ),
obj=Model.rel.field,
id="fields.E301",
)
diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py
index cf0945b745..224f830c70 100644
--- a/tests/csrf_tests/tests.py
+++ b/tests/csrf_tests/tests.py
@@ -711,14 +711,18 @@ class CsrfViewMiddlewareTestMixin(CsrfFunctionTestMixin):
self.assertContains(response, malformed_referer_msg, status_code=403)
# missing scheme
# >>> urlparse('//example.com/')
- # ParseResult(scheme='', netloc='example.com', path='/', params='', query='', fragment='')
+ # ParseResult(
+ # scheme='', netloc='example.com', path='/', params='', query='', fragment='',
+ # )
req.META["HTTP_REFERER"] = "//example.com/"
self._check_referer_rejects(mw, req)
response = mw.process_view(req, post_form_view, (), {})
self.assertContains(response, malformed_referer_msg, status_code=403)
# missing netloc
# >>> urlparse('https://')
- # ParseResult(scheme='https', netloc='', path='', params='', query='', fragment='')
+ # ParseResult(
+ # scheme='https', netloc='', path='', params='', query='', fragment='',
+ # )
req.META["HTTP_REFERER"] = "https://"
self._check_referer_rejects(mw, req)
response = mw.process_view(req, post_form_view, (), {})
diff --git a/tests/csrf_tests/views.py b/tests/csrf_tests/views.py
index 35c7fb95d6..2e8f0fcb0f 100644
--- a/tests/csrf_tests/views.py
+++ b/tests/csrf_tests/views.py
@@ -64,7 +64,9 @@ def post_form_view(request):
"""Return a POST form (without a token)."""
return HttpResponse(
content="""
-<html><body><h1>\u00a1Unicode!<form method="post"><input type="text"></form></body></html>
+<html>
+<body><h1>\u00a1Unicode!<form method="post"><input type="text"></form></body>
+</html>
"""
)
diff --git a/tests/custom_lookups/tests.py b/tests/custom_lookups/tests.py
index 2af145595e..1cf99b8300 100644
--- a/tests/custom_lookups/tests.py
+++ b/tests/custom_lookups/tests.py
@@ -512,8 +512,10 @@ class YearLteTests(TestCase):
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params + lhs_params + rhs_params
return (
- "%(lhs)s >= str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
- "AND %(lhs)s <= str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
+ "%(lhs)s >= "
+ "str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
+ "AND %(lhs)s <= "
+ "str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
@@ -525,12 +527,12 @@ class YearLteTests(TestCase):
finally:
delattr(YearExact, "as_" + connection.vendor)
try:
- # The other way is to subclass the original lookup and register the subclassed
- # lookup instead of the original.
+ # The other way is to subclass the original lookup and register the
+ # subclassed lookup instead of the original.
class CustomYearExact(YearExact):
- # This method should be named "as_mysql" for MySQL, "as_postgresql" for postgres
- # and so on, but as we don't know which DB we are running on, we need to use
- # setattr.
+ # This method should be named "as_mysql" for MySQL,
+ # "as_postgresql" for postgres and so on, but as we don't know
+ # which DB we are running on, we need to use setattr.
def as_custom_sql(self, compiler, connection):
lhs_sql, lhs_params = self.process_lhs(
compiler, connection, self.lhs.lhs
@@ -538,8 +540,10 @@ class YearLteTests(TestCase):
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params + lhs_params + rhs_params
return (
- "%(lhs)s >= str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
- "AND %(lhs)s <= str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
+ "%(lhs)s >= "
+ "str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
+ "AND %(lhs)s <= "
+ "str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
@@ -584,7 +588,10 @@ class LookupTransformCallOrderTests(SimpleTestCase):
def test_call_order(self):
with register_lookup(models.DateField, TrackCallsYearTransform):
# junk lookup - tries lookup, then transform, then fails
- msg = "Unsupported lookup 'junk' for IntegerField or join on the field not permitted."
+ msg = (
+ "Unsupported lookup 'junk' for IntegerField or join on the field not "
+ "permitted."
+ )
with self.assertRaisesMessage(FieldError, msg):
Author.objects.filter(birthdate__testyear__junk=2012)
self.assertEqual(
diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py
index 18f6895bd4..7d94b39fb3 100644
--- a/tests/db_functions/datetime/test_extract_trunc.py
+++ b/tests/db_functions/datetime/test_extract_trunc.py
@@ -247,7 +247,10 @@ class DateFunctionTests(TestCase):
with self.assertRaisesMessage(ValueError, "lookup_name must be provided"):
Extract("start_datetime")
- msg = "Extract input expression must be DateField, DateTimeField, TimeField, or DurationField."
+ msg = (
+ "Extract input expression must be DateField, DateTimeField, TimeField, or "
+ "DurationField."
+ )
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(extracted=Extract("name", "hour")))
diff --git a/tests/db_functions/text/test_sha224.py b/tests/db_functions/text/test_sha224.py
index 83c30a3091..a6254f43e3 100644
--- a/tests/db_functions/text/test_sha224.py
+++ b/tests/db_functions/text/test_sha224.py
@@ -46,7 +46,9 @@ class SHA224Tests(TestCase):
def test_transform(self):
with register_lookup(CharField, SHA224):
authors = Author.objects.filter(
- alias__sha224="a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70",
+ alias__sha224=(
+ "a61303c220731168452cb6acf3759438b1523e768f464e3704e12f70"
+ ),
).values_list("alias", flat=True)
self.assertSequenceEqual(authors, ["John Smith"])
diff --git a/tests/db_functions/text/test_sha256.py b/tests/db_functions/text/test_sha256.py
index d6f431fdf6..b399dbecd3 100644
--- a/tests/db_functions/text/test_sha256.py
+++ b/tests/db_functions/text/test_sha256.py
@@ -44,6 +44,8 @@ class SHA256Tests(TestCase):
def test_transform(self):
with register_lookup(CharField, SHA256):
authors = Author.objects.filter(
- alias__sha256="ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a",
+ alias__sha256=(
+ "ef61a579c907bbed674c0dbcbcf7f7af8f851538eef7b8e58c5bee0b8cfdac4a"
+ ),
).values_list("alias", flat=True)
self.assertSequenceEqual(authors, ["John Smith"])
diff --git a/tests/db_functions/text/test_sha384.py b/tests/db_functions/text/test_sha384.py
index cac72d54ce..250cadda4a 100644
--- a/tests/db_functions/text/test_sha384.py
+++ b/tests/db_functions/text/test_sha384.py
@@ -31,11 +31,16 @@ class SHA384Tests(TestCase):
self.assertSequenceEqual(
authors,
[
- "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e53b9967b80d77d4f5c2982cbc8",
- "72202c8005492016cc670219cce82d47d6d2d4273464c742ab5811d691b1e82a7489549e3a73ffa119694f90678ba2e3",
- "eda87fae41e59692c36c49e43279c8111a00d79122a282a944e8ba9a403218f049a48326676a43c7ba378621175853b0",
- "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b",
- "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"
+ "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e"
+ "53b9967b80d77d4f5c2982cbc8",
+ "72202c8005492016cc670219cce82d47d6d2d4273464c742ab5811d691b1e82a748954"
+ "9e3a73ffa119694f90678ba2e3",
+ "eda87fae41e59692c36c49e43279c8111a00d79122a282a944e8ba9a403218f049a483"
+ "26676a43c7ba378621175853b0",
+ "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede"
+ "bfe76f65fbd51ad2f14898b95b",
+ "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede"
+ "bfe76f65fbd51ad2f14898b95b"
if connection.features.interprets_empty_strings_as_nulls
else None,
],
@@ -45,7 +50,8 @@ class SHA384Tests(TestCase):
with register_lookup(CharField, SHA384):
authors = Author.objects.filter(
alias__sha384=(
- "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7b57e53b9967b80d77d4f5c2982cbc8"
+ "9df976bfbcf96c66fbe5cba866cd4deaa8248806f15b69c4010a404112906e4ca7"
+ "b57e53b9967b80d77d4f5c2982cbc8"
),
).values_list("alias", flat=True)
self.assertSequenceEqual(authors, ["John Smith"])
diff --git a/tests/delete/tests.py b/tests/delete/tests.py
index 778943c96f..b8e9f7ebcd 100644
--- a/tests/delete/tests.py
+++ b/tests/delete/tests.py
@@ -132,8 +132,9 @@ class OnDeleteTests(TestCase):
self.assertEqual(cm.exception.protected_objects, {a})
def test_do_nothing(self):
- # Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model,
- # so we connect to pre_delete and set the fk to a known value.
+ # Testing DO_NOTHING is a bit harder: It would raise IntegrityError for
+ # a normal model, so we connect to pre_delete and set the fk to a known
+ # value.
replacement_r = R.objects.create()
def check_do_nothing(sender, **kwargs):
@@ -502,7 +503,8 @@ class DeletionTests(TestCase):
# One query for Avatar.objects.all() and then one related fast delete for
# each batch.
fetches_to_mem = 1 + batches
- # The Avatar objects are going to be deleted in batches of GET_ITERATOR_CHUNK_SIZE
+ # The Avatar objects are going to be deleted in batches of
+ # GET_ITERATOR_CHUNK_SIZE.
queries = fetches_to_mem + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE
self.assertNumQueries(queries, Avatar.objects.all().delete)
self.assertFalse(Avatar.objects.exists())
diff --git a/tests/delete_regress/tests.py b/tests/delete_regress/tests.py
index 6872cdc3d8..c9d0ff8d0a 100644
--- a/tests/delete_regress/tests.py
+++ b/tests/delete_regress/tests.py
@@ -159,7 +159,9 @@ class DeleteCascadeTransactionTests(TransactionTestCase):
class LargeDeleteTests(TestCase):
def test_large_deletes(self):
- "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs"
+ """
+ If the number of objects > chunk size, deletion still occurs.
+ """
for x in range(300):
Book.objects.create(pagecount=x + 100)
# attach a signal to make sure we will not fast-delete
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py
index 5209261c37..58c851f975 100644
--- a/tests/expressions/tests.py
+++ b/tests/expressions/tests.py
@@ -319,7 +319,10 @@ class BasicExpressionsTests(TestCase):
def test_object_create_with_aggregate(self):
# Aggregates are not allowed when inserting new data
- msg = "Aggregate functions are not allowed in this query (num_employees=Max(Value(1)))."
+ msg = (
+ "Aggregate functions are not allowed in this query "
+ "(num_employees=Max(Value(1)))."
+ )
with self.assertRaisesMessage(FieldError, msg):
Company.objects.create(
name="Company",
@@ -1050,9 +1053,10 @@ class IterableLookupInnerExpressionsTests(TestCase):
@unittest.skipUnless(
connection.vendor == "sqlite",
- "This defensive test only works on databases that don't validate parameter types",
+ "This defensive test only works on databases that don't validate parameter "
+ "types",
)
- def test_complex_expressions_do_not_introduce_sql_injection_via_untrusted_string_inclusion(
+ def test_expressions_not_introduce_sql_injection_via_untrusted_string_inclusion(
self,
):
"""
diff --git a/tests/expressions_window/tests.py b/tests/expressions_window/tests.py
index df019d4c18..5c29f1bae5 100644
--- a/tests/expressions_window/tests.py
+++ b/tests/expressions_window/tests.py
@@ -1309,7 +1309,8 @@ class NonQueryWindowTests(SimpleTestCase):
)
self.assertEqual(
repr(Window(expression=Avg("salary"), order_by=F("department").asc())),
- "<Window: Avg(F(salary)) OVER (ORDER BY OrderBy(F(department), descending=False))>",
+ "<Window: Avg(F(salary)) OVER "
+ "(ORDER BY OrderBy(F(department), descending=False))>",
)
def test_window_frame_repr(self):
diff --git a/tests/extra_regress/tests.py b/tests/extra_regress/tests.py
index 51ba601c1d..da403df98c 100644
--- a/tests/extra_regress/tests.py
+++ b/tests/extra_regress/tests.py
@@ -36,7 +36,8 @@ class ExtraRegressTests(TestCase):
# Queryset to match most recent revision:
qs = RevisionableModel.objects.extra(
where=[
- "%(table)s.id IN (SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)"
+ "%(table)s.id IN "
+ "(SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)"
% {
"table": RevisionableModel._meta.db_table,
}
diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py
index 6d6949ef01..f7bbb343d6 100644
--- a/tests/file_storage/tests.py
+++ b/tests/file_storage/tests.py
@@ -953,7 +953,10 @@ class FieldCallableFileStorageTests(SimpleTestCase):
class NotStorage:
pass
- msg = "FileField.storage must be a subclass/instance of django.core.files.storage.Storage"
+ msg = (
+ "FileField.storage must be a subclass/instance of "
+ "django.core.files.storage.Storage"
+ )
for invalid_type in (NotStorage, str, list, set, tuple):
with self.subTest(invalid_type=invalid_type):
with self.assertRaisesMessage(TypeError, msg):
diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py
index 1530924cc4..7b2ae32542 100644
--- a/tests/file_uploads/tests.py
+++ b/tests/file_uploads/tests.py
@@ -198,8 +198,8 @@ class FileUploadTests(TestCase):
"\r\n".join(
[
"--" + client.BOUNDARY,
- "Content-Disposition: form-data; name=\"file_unicode\"; filename*=UTF-8''%s"
- % quote(UNICODE_FILENAME),
+ 'Content-Disposition: form-data; name="file_unicode"; '
+ "filename*=UTF-8''%s" % quote(UNICODE_FILENAME),
"Content-Type: application/octet-stream",
"",
"You got pwnd.\r\n",
@@ -228,8 +228,8 @@ class FileUploadTests(TestCase):
"\r\n".join(
[
"--" + client.BOUNDARY,
- "Content-Disposition: form-data; name*=UTF-8''file_unicode; filename*=UTF-8''%s"
- % quote(UNICODE_FILENAME),
+ "Content-Disposition: form-data; name*=UTF-8''file_unicode; "
+ "filename*=UTF-8''%s" % quote(UNICODE_FILENAME),
"Content-Type: application/octet-stream",
"",
"You got pwnd.\r\n",
@@ -679,7 +679,8 @@ class FileUploadTests(TestCase):
self.assertNotEqual(
str(err),
str(reference_error),
- "Caught a repeated exception that'll cause an infinite loop in file uploads.",
+ "Caught a repeated exception that'll cause an infinite loop in "
+ "file uploads.",
)
except Exception as err:
# CustomUploadError is the error that should have been raised
@@ -696,7 +697,8 @@ class FileUploadTests(TestCase):
vars = {"boundary": "oUrBoUnDaRyStRiNg"}
post_data = [
"--%(boundary)s",
- 'Content-Disposition: form-data; name="file_field"; filename="MiXeD_cAsE.txt"',
+ 'Content-Disposition: form-data; name="file_field"; '
+ 'filename="MiXeD_cAsE.txt"',
"Content-Type: application/octet-stream",
"",
"file contents\n",
@@ -880,7 +882,8 @@ class MultiParserTests(SimpleTestCase):
def test_rfc2231_parsing(self):
test_data = (
(
- b"Content-Type: application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A",
+ b"Content-Type: application/x-stuff; "
+ b"title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A",
"This is ***fun***",
),
(
@@ -903,7 +906,8 @@ class MultiParserTests(SimpleTestCase):
"""
test_data = (
(
- b"Content-Type: application/x-stuff; title*='This%20is%20%2A%2A%2Afun%2A%2A%2A",
+ b"Content-Type: application/x-stuff; "
+ b"title*='This%20is%20%2A%2A%2Afun%2A%2A%2A",
b"'This%20is%20%2A%2A%2Afun%2A%2A%2A",
),
(b"Content-Type: application/x-stuff; title*='foo.html", b"'foo.html"),
diff --git a/tests/files/tests.py b/tests/files/tests.py
index c86b53bbd3..9777d09e1c 100644
--- a/tests/files/tests.py
+++ b/tests/files/tests.py
@@ -351,7 +351,8 @@ class InconsistentGetImageDimensionsBug(unittest.TestCase):
def test_bug_19457(self):
"""
Regression test for #19457
- get_image_dimensions fails on some pngs, while Image.size is working good on them
+ get_image_dimensions() fails on some PNGs, while Image.size is working
+ good on them.
"""
img_path = os.path.join(os.path.dirname(__file__), "magic.png")
size = images.get_image_dimensions(img_path)
diff --git a/tests/filtered_relation/tests.py b/tests/filtered_relation/tests.py
index bf099f763a..790a90d9e2 100644
--- a/tests/filtered_relation/tests.py
+++ b/tests/filtered_relation/tests.py
@@ -877,7 +877,9 @@ class FilteredRelationAnalyticalAggregationTests(TestCase):
recent_sales__currency__rates_from__rate_date=F(
"recent_sales__sale_date"
),
- recent_sales__currency__rates_from__to_currency=self.usd,
+ recent_sales__currency__rates_from__to_currency=(
+ self.usd
+ ),
),
),
)
diff --git a/tests/fixtures/tests.py b/tests/fixtures/tests.py
index 094f07e979..e66007d2d4 100644
--- a/tests/fixtures/tests.py
+++ b/tests/fixtures/tests.py
@@ -145,83 +145,111 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# Dump the current contents of the database as a JSON fixture
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# Try just dumping the contents of fixtures.Category
self._dumpdata_assert(
["fixtures.Category"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", '
- '"title": "News Stories"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}]',
)
# ...and just fixtures.Article
self._dumpdata_assert(
["fixtures.Article"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": '
- '"Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# ...and both
self._dumpdata_assert(
["fixtures.Category", "fixtures.Article"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", '
- '"title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has '
- 'no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", '
- '"fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# Specify a specific model twice
self._dumpdata_assert(
["fixtures.Article", "fixtures.Article"],
(
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": '
- '"Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]'
),
)
# Specify a dump that specifies Article both explicitly and implicitly
self._dumpdata_assert(
["fixtures.Article", "fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# Specify a dump that specifies Article both explicitly and implicitly,
# but lists the app first (#22025).
self._dumpdata_assert(
["fixtures", "fixtures.Article"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# Same again, but specify in the reverse order
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no '
- 'place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields":'
- ' {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# Specify one model from one application, and an entire other application.
self._dumpdata_assert(
["fixtures.Category", "sites"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": '
- '"example.com"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 1, "model": "sites.site", "fields": '
+ '{"domain": "example.com", "name": "example.com"}}]',
)
- # Load fixture 2. JSON file imported by default. Overwrites some existing objects
+ # Load fixture 2. JSON file imported by default. Overwrites some
+ # existing objects.
management.call_command("loaddata", "fixture2.json", verbosity=0)
self.assertSequenceEqual(
Article.objects.values_list("headline", flat=True),
@@ -275,7 +303,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
self.assertQuerysetEqual(
Visa.objects.all(),
[
- "<Visa: Django Reinhardt Can add user, Can change user, Can delete user>",
+ "<Visa: Django Reinhardt Can add user, Can change user, Can delete "
+ "user>",
"<Visa: Stephane Grappelli Can add user>",
"<Visa: Prince >",
],
@@ -288,7 +317,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
self.assertQuerysetEqual(
Visa.objects.all(),
[
- "<Visa: Django Reinhardt Can add user, Can change user, Can delete user>",
+ "<Visa: Django Reinhardt Can add user, Can change user, Can delete "
+ "user>",
"<Visa: Stephane Grappelli Can add user, Can delete user>",
'<Visa: Artist formerly known as "Prince" Can change user>',
],
@@ -310,102 +340,176 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# By default, you get raw keys on dumpdata
self._dumpdata_assert(
["fixtures.book"],
- '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]',
+ '[{"pk": 1, "model": "fixtures.book", "fields": '
+ '{"name": "Music for all ages", "authors": [3, 1]}}]',
)
# But you can get natural keys if you ask for them and they are available
self._dumpdata_assert(
["fixtures.book"],
- '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist '
- 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
+ '[{"pk": 1, "model": "fixtures.book", "fields": '
+ '{"name": "Music for all ages", "authors": '
+ '[["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
natural_foreign_keys=True,
)
- # You can also omit the primary keys for models that we can get later with natural keys.
+ # You can also omit the primary keys for models that we can get later
+ # with natural keys.
self._dumpdata_assert(
["fixtures.person"],
- '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, {"fields": {"name": "Stephane '
- 'Grappelli"}, "model": "fixtures.person"}, {"fields": {"name": "Artist formerly known as '
- '\\"Prince\\""}, "model": "fixtures.person"}]',
+ '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, '
+ '{"fields": {"name": "Stephane Grappelli"}, "model": "fixtures.person"}, '
+ '{"fields": {"name": "Artist formerly known as \\"Prince\\""}, '
+ '"model": "fixtures.person"}]',
natural_primary_keys=True,
)
# Dump the current contents of the database as a JSON fixture
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is '
- 'great!", "pub_date": "2006-06-16T11:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}, {"pk": 4, '
- '"model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": '
- '"2006-06-16T15:00:00"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML '
- 'identified as leading cause of cancer", "pub_date": "2006-06-16T16:00:00"}}, {"pk": 1, "model": '
- '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": '
- '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": '
- '"legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", '
- '"article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": '
- '{"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 1, '
- '"model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": '
- '"fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", '
- '"fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.visa", '
- '"fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], '
- '["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": '
- '"fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", '
- '"user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person":'
- ' ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, '
- '{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist '
- 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker on TV is great!", '
+ '"pub_date": "2006-06-16T11:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}, '
+ '{"pk": 4, "model": "fixtures.article", "fields": '
+ '{"headline": "Django conquers world!", '
+ '"pub_date": "2006-06-16T15:00:00"}}, '
+ '{"pk": 5, "model": "fixtures.article", "fields": '
+ '{"headline": "XML identified as leading cause of cancer", '
+ '"pub_date": "2006-06-16T16:00:00"}}, '
+ '{"pk": 1, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "copyright", '
+ '"tagged_id": 3}}, '
+ '{"pk": 2, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "legal", '
+ '"tagged_id": 3}}, '
+ '{"pk": 3, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "django", '
+ '"tagged_id": 4}}, '
+ '{"pk": 4, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "world domination", '
+ '"tagged_id": 4}}, '
+ '{"pk": 1, "model": "fixtures.person", '
+ '"fields": {"name": "Django Reinhardt"}}, '
+ '{"pk": 2, "model": "fixtures.person", '
+ '"fields": {"name": "Stephane Grappelli"}}, '
+ '{"pk": 3, "model": "fixtures.person", '
+ '"fields": {"name": "Artist formerly known as \\"Prince\\""}}, '
+ '{"pk": 1, "model": "fixtures.visa", '
+ '"fields": {"person": ["Django Reinhardt"], "permissions": '
+ '[["add_user", "auth", "user"], ["change_user", "auth", "user"], '
+ '["delete_user", "auth", "user"]]}}, '
+ '{"pk": 2, "model": "fixtures.visa", "fields": '
+ '{"person": ["Stephane Grappelli"], "permissions": '
+ '[["add_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, '
+ '{"pk": 3, "model": "fixtures.visa", "fields": '
+ '{"person": ["Artist formerly known as \\"Prince\\""], "permissions": '
+ '[["change_user", "auth", "user"]]}}, '
+ '{"pk": 1, "model": "fixtures.book", "fields": '
+ '{"name": "Music for all ages", "authors": '
+ '[["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
natural_foreign_keys=True,
)
# Dump the current contents of the database as an XML fixture
self._dumpdata_assert(
["fixtures"],
- '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" '
- 'model="fixtures.category"><field type="CharField" name="title">News Stories</field><field '
- 'type="TextField" name="description">Latest news stories</field></object><object pk="2" '
- 'model="fixtures.article"><field type="CharField" name="headline">Poker on TV is great!</field><field '
- 'type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field></object><object pk="3" '
- 'model="fixtures.article"><field type="CharField" name="headline">Copyright is fine the way it '
- 'is</field><field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field></object><object '
- 'pk="4" model="fixtures.article"><field type="CharField" name="headline">Django conquers world!'
- '</field><field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field></object><object '
- 'pk="5" model="fixtures.article"><field type="CharField" name="headline">XML identified as leading '
- 'cause of cancer</field><field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field>'
- '</object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field>'
- '<field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures'
- '</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3'
- '</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">legal'
- '</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>'
- 'fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" '
- 'name="tagged_id">3</field></object><object pk="3" model="fixtures.tag"><field type="CharField" '
- 'name="name">django</field><field to="contenttypes.contenttype" name="tagged_type" '
- 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field '
- 'type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="4" model="fixtures.tag">'
- '<field type="CharField" name="name">world domination</field><field to="contenttypes.contenttype" '
- 'name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field>'
- '<field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="1" '
- 'model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object>'
- '<object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli'
- '</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">'
- 'Artist formerly known as "Prince"</field></object><object pk="1" model="fixtures.visa"><field '
- 'to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Django Reinhardt</natural></field>'
- '<field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user'
- "</natural><natural>auth</natural><natural>user</natural></object><object><natural>change_user"
- "</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user"
- '</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="2" '
- 'model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Stephane'
- ' Grappelli</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel">'
- "<object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object>"
- "<natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field>"
- '</object><object pk="3" model="fixtures.visa"><field to="fixtures.person" name="person" '
- 'rel="ManyToOneRel"><natural>Artist formerly known as "Prince"</natural></field><field '
- 'to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>change_user</natural>'
- '<natural>auth</natural><natural>user</natural></object></field></object><object pk="1" '
- 'model="fixtures.book"><field type="CharField" name="name">Music for all ages</field><field '
- 'to="fixtures.person" name="authors" rel="ManyToManyRel"><object><natural>Artist formerly known as '
- '"Prince"</natural></object><object><natural>Django Reinhardt</natural></object></field></object>'
- "</django-objects>",
+ '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0">'
+ '<object pk="1" model="fixtures.category">'
+ '<field type="CharField" name="title">News Stories</field>'
+ '<field type="TextField" name="description">Latest news stories</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.article">'
+ '<field type="CharField" name="headline">Poker on TV is great!</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.article">'
+ '<field type="CharField" name="headline">Copyright is fine the way it is'
+ "</field>"
+ '<field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field>'
+ "</object>"
+ '<object pk="4" model="fixtures.article">'
+ '<field type="CharField" name="headline">Django conquers world!</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field>'
+ "</object>"
+ '<object pk="5" model="fixtures.article">'
+ '<field type="CharField" name="headline">'
+ "XML identified as leading cause of cancer</field>"
+ '<field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.tag">'
+ '<field type="CharField" name="name">copyright</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.tag">'
+ '<field type="CharField" name="name">legal</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field></object>'
+ '<object pk="3" model="fixtures.tag">'
+ '<field type="CharField" name="name">django</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">4</field>'
+ "</object>"
+ '<object pk="4" model="fixtures.tag">'
+ '<field type="CharField" name="name">world domination</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">4</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.person">'
+ '<field type="CharField" name="name">Django Reinhardt</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.person">'
+ '<field type="CharField" name="name">Stephane Grappelli</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.person">'
+ '<field type="CharField" name="name">Artist formerly known as "Prince"'
+ "</field>"
+ "</object>"
+ '<object pk="1" model="fixtures.visa">'
+ '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
+ "<natural>Django Reinhardt</natural></field>"
+ '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
+ "<object><natural>add_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object><object><natural>change_user</natural>"
+ "<natural>auth</natural><natural>user</natural></object>"
+ "<object><natural>delete_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object></field>"
+ "</object>"
+ '<object pk="2" model="fixtures.visa">'
+ '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
+ "<natural>Stephane Grappelli</natural></field>"
+ '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
+ "<object><natural>add_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object>"
+ "<object><natural>delete_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object></field>"
+ "</object>"
+ '<object pk="3" model="fixtures.visa">'
+ '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
+ '<natural>Artist formerly known as "Prince"</natural></field>'
+ '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
+ "<object><natural>change_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object></field>"
+ "</object>"
+ '<object pk="1" model="fixtures.book">'
+ '<field type="CharField" name="name">Music for all ages</field>'
+ '<field to="fixtures.person" name="authors" rel="ManyToManyRel">'
+ '<object><natural>Artist formerly known as "Prince"</natural></object>'
+ "<object><natural>Django Reinhardt</natural></object></field>"
+ "</object></django-objects>",
format="xml",
natural_foreign_keys=True,
)
@@ -418,33 +522,37 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# Excluding fixtures app should only leave sites
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]',
+ '[{"pk": 1, "model": "sites.site", "fields": '
+ '{"domain": "example.com", "name": "example.com"}}]',
exclude_list=["fixtures"],
)
# Excluding fixtures.Article/Book should leave fixtures.Category
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, '
- '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}]',
+ '[{"pk": 1, "model": "sites.site", '
+ '"fields": {"domain": "example.com", "name": "example.com"}}, '
+ '{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}]',
exclude_list=["fixtures.Article", "fixtures.Book"],
)
# Excluding fixtures and fixtures.Article/Book should be a no-op
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, '
- '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}]',
+ '[{"pk": 1, "model": "sites.site", '
+ '"fields": {"domain": "example.com", "name": "example.com"}}, '
+ '{"pk": 1, "model": "fixtures.category", '
+ '"fields": {"description": "Latest news stories", '
+ '"title": "News Stories"}}]',
exclude_list=["fixtures.Article", "fixtures.Book"],
)
# Excluding sites and fixtures.Article/Book should only leave fixtures.Category
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}]',
exclude_list=["fixtures.Article", "fixtures.Book", "sites"],
)
@@ -486,8 +594,9 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# even those normally filtered by the manager
self._dumpdata_assert(
["fixtures.Spy"],
- '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": '
- '"fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk),
+ '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, '
+ '{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]'
+ % (spy2.pk, spy1.pk),
use_base_manager=True,
)
@@ -496,15 +605,19 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture2.json", verbosity=0)
self._dumpdata_assert(
["fixtures.Article"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": '
- '"Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", '
+ '"fields": {"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
self._dumpdata_assert(
["fixtures.Article"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
+ '[{"pk": 2, "model": "fixtures.article", '
+ '"fields": {"headline": "Poker has no place on ESPN", '
'"pub_date": "2006-06-16T12:00:00"}}]',
primary_keys="2",
)
@@ -514,9 +627,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
):
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
@@ -525,9 +641,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
):
self._dumpdata_assert(
"",
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
@@ -536,9 +655,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
):
self._dumpdata_assert(
["fixtures.Article", "fixtures.category"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
@@ -561,10 +683,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json",
)
@@ -572,10 +698,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.gz",
)
@@ -584,10 +714,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.bz2",
)
@@ -596,10 +730,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.lzma",
)
@@ -608,10 +746,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.xz",
)
@@ -621,10 +763,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
with self.assertWarnsMessage(RuntimeWarning, msg):
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.zip",
)
@@ -679,8 +825,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
warnings.simplefilter("always")
self._dumpdata_assert(
["fixtures.ProxySpy", "fixtures.Spy"],
- '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]'
- % spy.pk,
+ '[{"pk": %d, "model": "fixtures.spy", '
+ '"fields": {"cover_blown": false}}]' % spy.pk,
)
self.assertEqual(len(warning_list), 0)
@@ -743,7 +889,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture5", verbosity=0)
def test_db_loading(self):
- # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly
+ # Load db fixtures 1 and 2. These will load using the 'default'
+ # database identifier implicitly.
management.call_command("loaddata", "db_fixture_1", verbosity=0)
management.call_command("loaddata", "db_fixture_2", verbosity=0)
self.assertSequenceEqual(
@@ -809,7 +956,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
)
def test_loading_using(self):
- # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly
+ # Load fixtures 1 and 2. These will load using the 'default' database
+ # identifier explicitly.
management.call_command(
"loaddata", "db_fixture_1", verbosity=0, database="default"
)
@@ -825,7 +973,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
)
def test_unmatched_identifier_loading(self):
- # Try to load db fixture 3. This won't load because the database identifier doesn't match
+ # Db fixture 3 won't load because the database identifier doesn't
+ # match.
with self.assertRaisesMessage(
CommandError, "No fixture named 'db_fixture_3' found."
):
@@ -857,14 +1006,23 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# Dump the current contents of the database as a JSON fixture
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}, {"pk": 1, "model": '
- '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": '
- '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": '
- '"law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django '
- 'Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, '
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}, '
+ '{"pk": 1, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "copyright", '
+ '"tagged_id": 3}}, '
+ '{"pk": 2, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "law", "tagged_id": 3}}, '
+ '{"pk": 1, "model": "fixtures.person", "fields": '
+ '{"name": "Django Reinhardt"}}, '
+ '{"pk": 2, "model": "fixtures.person", "fields": '
+ '{"name": "Stephane Grappelli"}}, '
'{"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}]',
natural_foreign_keys=True,
)
@@ -872,23 +1030,42 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# Dump the current contents of the database as an XML fixture
self._dumpdata_assert(
["fixtures"],
- '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" '
- 'model="fixtures.category"><field type="CharField" name="title">News Stories</field><field '
- 'type="TextField" name="description">Latest news stories</field></object><object pk="2" '
- 'model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field>'
- '<field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" '
- 'model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field>'
- '<field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" '
- 'model="fixtures.tag"><field type="CharField" name="name">copyright</field><field '
- 'to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural>'
- '<natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field>'
- '</object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field '
- 'to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural>'
- '<natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field>'
- '</object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt'
- '</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane '
- 'Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">'
- "Prince</field></object></django-objects>",
+ '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0">'
+ '<object pk="1" model="fixtures.category">'
+ '<field type="CharField" name="title">News Stories</field>'
+ '<field type="TextField" name="description">Latest news stories</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.article">'
+ '<field type="CharField" name="headline">Poker has no place on ESPN</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.article">'
+ '<field type="CharField" name="headline">Time to reform copyright</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.tag">'
+ '<field type="CharField" name="name">copyright</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural>'
+ "<natural>article</natural></field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.tag">'
+ '<field type="CharField" name="name">law</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural>'
+ "<natural>article</natural></field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.person">'
+ '<field type="CharField" name="name">Django Reinhardt</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.person">'
+ '<field type="CharField" name="name">Stephane Grappelli</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.person">'
+ '<field type="CharField" name="name">Prince</field>'
+ "</object></django-objects>",
format="xml",
natural_foreign_keys=True,
)
@@ -1024,10 +1201,14 @@ class FixtureTransactionTests(DumpDataAssertMixin, TransactionTestCase):
# Dump the current contents of the database as a JSON fixture
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# Load fixture 4 (compressed), using format discovery
@@ -1108,7 +1289,8 @@ class ForwardReferenceTests(DumpDataAssertMixin, TestCase):
self._dumpdata_assert(
["fixtures"],
'[{"model": "fixtures.naturalkeything", '
- '"fields": {"key": "t1", "other_thing": null, "other_things": [["t2"], ["t3"]]}}, '
+ '"fields": {"key": "t1", "other_thing": null, '
+ '"other_things": [["t2"], ["t3"]]}}, '
'{"model": "fixtures.naturalkeything", '
'"fields": {"key": "t2", "other_thing": null, "other_things": []}}, '
'{"model": "fixtures.naturalkeything", '
diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py
index 318c9a3a14..61dd12754c 100644
--- a/tests/fixtures_regress/tests.py
+++ b/tests/fixtures_regress/tests.py
@@ -209,7 +209,10 @@ class TestFixtures(TestCase):
Test for ticket #4371 -- Loading data of an unknown format should fail
Validate that error conditions are caught correctly
"""
- msg = "Problem installing fixture 'bad_fix.ture1': unkn is not a known serialization format."
+ msg = (
+ "Problem installing fixture 'bad_fix.ture1': unkn is not a known "
+ "serialization format."
+ )
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
@@ -438,14 +441,14 @@ class TestFixtures(TestCase):
)
self.assertJSONEqual(
out.getvalue(),
- """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
- % widget.pk,
+ '[{"pk": %d, "model": "fixtures_regress.widget", '
+ '"fields": {"name": "grommet"}}]' % widget.pk,
)
@skipUnlessDBFeature("supports_forward_references")
def test_loaddata_works_when_fixture_has_forward_refs(self):
"""
- Regression for #3615 - Forward references cause fixtures not to load in MySQL (InnoDB)
+ Forward references cause fixtures not to load in MySQL (InnoDB).
"""
management.call_command(
"loaddata",
@@ -457,7 +460,7 @@ class TestFixtures(TestCase):
def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
"""
- Regression for #3615 - Ensure data with nonexistent child key references raises error
+ Data with nonexistent child key references raises error.
"""
with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"):
management.call_command(
@@ -489,9 +492,13 @@ class TestFixtures(TestCase):
def test_loaddata_no_fixture_specified(self):
"""
- Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line.
+ Error is quickly reported when no fixtures is provided in the command
+ line.
"""
- msg = "No database fixture specified. Please provide the path of at least one fixture in the command line."
+ msg = (
+ "No database fixture specified. Please provide the path of at least one "
+ "fixture in the command line."
+ )
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
@@ -648,10 +655,13 @@ class NaturalKeyFixtureTests(TestCase):
self.assertJSONEqual(
out.getvalue(),
"""
- [{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"},
- {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"},
+ [{"fields": {"main": null, "name": "Amazon"},
+ "model": "fixtures_regress.store"},
+ {"fields": {"main": null, "name": "Borders"},
+ "model": "fixtures_regress.store"},
{"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"},
- {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]],
+ {"pk": 1, "model": "fixtures_regress.book",
+ "fields": {"stores": [["Amazon"], ["Borders"]],
"name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
""",
)
@@ -770,9 +780,12 @@ class NaturalKeyFixtureTests(TestCase):
self.assertQuerysetEqual(
books,
[
- "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>",
- "<Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>",
- "<Book: Permutation City by Greg Egan (available at Angus and Robertson)>",
+ "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, "
+ "Borders)>",
+ "<Book: Ender's Game by Orson Scott Card (available at Collins "
+ "Bookstore)>",
+ "<Book: Permutation City by Greg Egan (available at Angus and "
+ "Robertson)>",
],
transform=repr,
)
diff --git a/tests/flatpages_tests/test_csrf.py b/tests/flatpages_tests/test_csrf.py
index d26546876e..62ac5f9a14 100644
--- a/tests/flatpages_tests/test_csrf.py
+++ b/tests/flatpages_tests/test_csrf.py
@@ -105,12 +105,18 @@ class FlatpageCSRFTests(TestCase):
self.assertEqual(response.status_code, 404)
def test_post_view_flatpage(self):
- "POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)"
+ """
+ POSTing to a flatpage served through a view will raise a CSRF error if
+ no token is provided.
+ """
response = self.client.post("/flatpage_root/flatpage/")
self.assertEqual(response.status_code, 403)
def test_post_fallback_flatpage(self):
- "POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)"
+ """
+ POSTing to a flatpage served by the middleware will raise a CSRF error
+ if no token is provided.
+ """
response = self.client.post("/flatpage/")
self.assertEqual(response.status_code, 403)
diff --git a/tests/flatpages_tests/test_forms.py b/tests/flatpages_tests/test_forms.py
index 7f56549235..00caf01960 100644
--- a/tests/flatpages_tests/test_forms.py
+++ b/tests/flatpages_tests/test_forms.py
@@ -91,7 +91,10 @@ class FlatpageAdminFormTests(TestCase):
)
def test_flatpage_admin_form_url_uniqueness_validation(self):
- "The flatpage admin form correctly enforces url uniqueness among flatpages of the same site"
+ """
+ The flatpage admin form correctly enforces url uniqueness among
+ flatpages of the same site.
+ """
data = dict(url="/myflatpage1/", **self.form_data)
FlatpageForm(data=data).save()
@@ -105,7 +108,8 @@ class FlatpageAdminFormTests(TestCase):
f.errors,
{
"__all__": [
- "Flatpage with url /myflatpage1/ already exists for site example.com"
+ "Flatpage with url /myflatpage1/ already exists for site "
+ "example.com"
]
},
)
diff --git a/tests/flatpages_tests/test_middleware.py b/tests/flatpages_tests/test_middleware.py
index 193c8232bf..581947e9f6 100644
--- a/tests/flatpages_tests/test_middleware.py
+++ b/tests/flatpages_tests/test_middleware.py
@@ -113,7 +113,10 @@ class FlatpageMiddlewareTests(TestDataMixin, TestCase):
self.assertContains(response, "<p>Isn't it sekrit!</p>")
def test_fallback_flatpage_special_chars(self):
- "A flatpage with special chars in the URL can be served by the fallback middleware"
+ """
+ A flatpage with special chars in the URL can be served by the fallback
+ middleware.
+ """
fp = FlatPage.objects.create(
url="/some.very_special~chars-here/",
title="A very special page",
@@ -171,7 +174,10 @@ class FlatpageMiddlewareAppendSlashTests(TestDataMixin, TestCase):
self.assertEqual(response.status_code, 404)
def test_redirect_fallback_flatpage_special_chars(self):
- "A flatpage with special chars in the URL can be served by the fallback middleware and should add a slash"
+ """
+ A flatpage with special chars in the URL can be served by the fallback
+ middleware and should add a slash.
+ """
fp = FlatPage.objects.create(
url="/some.very_special~chars-here/",
title="A very special page",
diff --git a/tests/flatpages_tests/test_templatetags.py b/tests/flatpages_tests/test_templatetags.py
index 1c7bc4d38a..eb36ee375b 100644
--- a/tests/flatpages_tests/test_templatetags.py
+++ b/tests/flatpages_tests/test_templatetags.py
@@ -61,7 +61,10 @@ class FlatpageTemplateTagTests(TestCase):
self.assertEqual(out, "A Flatpage,A Nested Flatpage,")
def test_get_flatpages_tag_for_anon_user(self):
- "The flatpage template tag retrieves unregistered flatpages for an anonymous user"
+ """
+ The flatpage template tag retrieves unregistered flatpages for an
+ anonymous user.
+ """
out = Template(
"{% load flatpages %}"
"{% get_flatpages for anonuser as flatpages %}"
@@ -97,7 +100,10 @@ class FlatpageTemplateTagTests(TestCase):
self.assertEqual(out, "A Nested Flatpage,")
def test_get_flatpages_with_prefix_for_anon_user(self):
- "The flatpage template tag retrieves unregistered prefixed flatpages for an anonymous user"
+ """
+ The flatpage template tag retrieves unregistered prefixed flatpages for
+ an anonymous user.
+ """
out = Template(
"{% load flatpages %}"
"{% get_flatpages '/location/' for anonuser as location_flatpages %}"
@@ -108,7 +114,10 @@ class FlatpageTemplateTagTests(TestCase):
self.assertEqual(out, "A Nested Flatpage,")
def test_get_flatpages_with_prefix_for_user(self):
- "The flatpage template tag retrieve prefixed flatpages for an authenticated user"
+ """
+ The flatpage template tag retrieve prefixed flatpages for an
+ authenticated user.
+ """
me = User.objects.create_user("testuser", "test@example.com", "s3krit")
out = Template(
"{% load flatpages %}"
@@ -156,5 +165,6 @@ class FlatpageTemplateTagTests(TestCase):
render("{% load flatpages %}{% get_flatpages for user as flatpages asdf %}")
with self.assertRaisesMessage(TemplateSyntaxError, msg):
render(
- "{% load flatpages %}{% get_flatpages prefix for user as flatpages asdf %}"
+ "{% load flatpages %}"
+ "{% get_flatpages prefix for user as flatpages asdf %}"
)
diff --git a/tests/flatpages_tests/test_views.py b/tests/flatpages_tests/test_views.py
index 2a01587a7a..24ad07d35a 100644
--- a/tests/flatpages_tests/test_views.py
+++ b/tests/flatpages_tests/test_views.py
@@ -146,7 +146,10 @@ class FlatpageViewAppendSlashTests(TestDataMixin, TestCase):
self.assertEqual(response.status_code, 404)
def test_redirect_fallback_flatpage(self):
- "A fallback flatpage won't be served if the middleware is disabled and should not add a slash"
+ """
+ A fallback flatpage won't be served if the middleware is disabled and
+ should not add a slash.
+ """
response = self.client.get("/flatpage")
self.assertEqual(response.status_code, 404)
@@ -159,7 +162,10 @@ class FlatpageViewAppendSlashTests(TestDataMixin, TestCase):
self.assertEqual(response.status_code, 404)
def test_redirect_view_flatpage_special_chars(self):
- "A flatpage with special chars in the URL can be served through a view and should add a slash"
+ """
+ A flatpage with special chars in the URL can be served through a view
+ and should add a slash.
+ """
fp = FlatPage.objects.create(
url="/some.very_special~chars-here/",
title="A very special page",
diff --git a/tests/foreign_object/test_forms.py b/tests/foreign_object/test_forms.py
index 61f8f42295..a3ad74d28b 100644
--- a/tests/foreign_object/test_forms.py
+++ b/tests/foreign_object/test_forms.py
@@ -15,7 +15,8 @@ class FormsTests(TestCase):
fields = "__all__"
def test_foreign_object_form(self):
- # A very crude test checking that the non-concrete fields do not get form fields.
+ # A very crude test checking that the non-concrete fields do not get
+ # form fields.
form = FormsTests.ArticleForm()
self.assertIn("id_pub_date", form.as_table())
self.assertNotIn("active_translation", form.as_table())
diff --git a/tests/foreign_object/tests.py b/tests/foreign_object/tests.py
index 99206e837f..6d5b8343cc 100644
--- a/tests/foreign_object/tests.py
+++ b/tests/foreign_object/tests.py
@@ -77,7 +77,8 @@ class MultiColumnFKTests(TestCase):
group_id=self.cia.id,
)
- # Creating an invalid membership because it has a different country has the person
+ # Creating an invalid membership because it has a different country has
+ # the person.
Membership.objects.create(
membership_country_id=self.soviet_union.id,
person_id=self.bob.id,
@@ -287,7 +288,7 @@ class MultiColumnFKTests(TestCase):
membership_country=self.usa, person=self.jim, group=self.cia
)
- # Let's check to make sure that it worked. Bob and Jim should be members of the CIA.
+ # Bob and Jim should be members of the CIA.
self.assertQuerysetEqual(
self.cia.members.all(), ["Bob", "Jim"], attrgetter("name")
@@ -313,7 +314,8 @@ class MultiColumnFKTests(TestCase):
# We start out by making sure that the Group 'CIA' has no members.
self.assertQuerysetEqual(self.cia.members.all(), [])
- # Something adds jane to group CIA but Jane is in Soviet Union which isn't CIA's country
+ # Something adds jane to group CIA but Jane is in Soviet Union which
+ # isn't CIA's country.
Membership.objects.create(
membership_country=self.usa, person=self.jane, group=self.cia
)
@@ -325,7 +327,8 @@ class MultiColumnFKTests(TestCase):
# We start out by making sure that Jane has no groups.
self.assertQuerysetEqual(self.jane.groups.all(), [])
- # Something adds jane to group CIA but Jane is in Soviet Union which isn't CIA's country
+ # Something adds jane to group CIA but Jane is in Soviet Union which
+ # isn't CIA's country.
Membership.objects.create(
membership_country=self.usa, person=self.jane, group=self.cia
)
@@ -350,8 +353,9 @@ class MultiColumnFKTests(TestCase):
def test_m2m_through_on_self_ignores_mismatch_columns(self):
self.assertQuerysetEqual(self.jane.friends.all(), [])
- # Note that we use ids instead of instances. This is because instances on ForeignObject
- # properties will set all related field off of the given instance
+ # Note that we use ids instead of instances. This is because instances
+ # on ForeignObject properties will set all related field off of the
+ # given instance.
Friendship.objects.create(
from_friend_id=self.jane.id,
to_friend_id=self.george.id,
diff --git a/tests/forms_tests/field_tests/test_booleanfield.py b/tests/forms_tests/field_tests/test_booleanfield.py
index 560a0f473b..d6b5121b10 100644
--- a/tests/forms_tests/field_tests/test_booleanfield.py
+++ b/tests/forms_tests/field_tests/test_booleanfield.py
@@ -52,7 +52,8 @@ class BooleanFieldTest(SimpleTestCase):
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"))
- # HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict
+ # 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"))
diff --git a/tests/forms_tests/field_tests/test_decimalfield.py b/tests/forms_tests/field_tests/test_decimalfield.py
index 6e49a41341..119a74292c 100644
--- a/tests/forms_tests/field_tests/test_decimalfield.py
+++ b/tests/forms_tests/field_tests/test_decimalfield.py
@@ -105,7 +105,8 @@ class DecimalFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
)
self.assertWidgetRendersTo(
f,
- '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" required>',
+ '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" '
+ "required>",
)
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is less than or equal to 1.5.'"
diff --git a/tests/forms_tests/field_tests/test_emailfield.py b/tests/forms_tests/field_tests/test_emailfield.py
index d1d52dd608..869a1aacc5 100644
--- a/tests/forms_tests/field_tests/test_emailfield.py
+++ b/tests/forms_tests/field_tests/test_emailfield.py
@@ -49,7 +49,8 @@ class EmailFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
f = EmailField(min_length=10, max_length=15)
self.assertWidgetRendersTo(
f,
- '<input id="id_f" type="email" name="f" maxlength="15" minlength="10" required>',
+ '<input id="id_f" type="email" name="f" maxlength="15" minlength="10" '
+ "required>",
)
with self.assertRaisesMessage(
ValidationError,
diff --git a/tests/forms_tests/field_tests/test_floatfield.py b/tests/forms_tests/field_tests/test_floatfield.py
index 194cce4c10..3ee8644534 100644
--- a/tests/forms_tests/field_tests/test_floatfield.py
+++ b/tests/forms_tests/field_tests/test_floatfield.py
@@ -52,7 +52,8 @@ class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
f = FloatField(max_value=1.5, min_value=0.5)
self.assertWidgetRendersTo(
f,
- '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" required>',
+ '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" '
+ "required>",
)
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is less than or equal to 1.5.'"
@@ -71,7 +72,8 @@ class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
f = FloatField(widget=NumberInput(attrs={"step": 0.01, "max": 1.0, "min": 0.0}))
self.assertWidgetRendersTo(
f,
- '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" required>',
+ '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" '
+ "required>",
)
def test_floatfield_localized(self):
diff --git a/tests/forms_tests/field_tests/test_multivaluefield.py b/tests/forms_tests/field_tests/test_multivaluefield.py
index da94206f4d..74e126deb2 100644
--- a/tests/forms_tests/field_tests/test_multivaluefield.py
+++ b/tests/forms_tests/field_tests/test_multivaluefield.py
@@ -183,15 +183,18 @@ class MultiValueFieldTest(SimpleTestCase):
form.as_table(),
"""
<tr><th><label for="id_field1_0">Field1:</label></th>
- <td><input type="text" name="field1_0" value="some text" id="id_field1_0" required>
+ <td><input type="text" name="field1_0" value="some text" id="id_field1_0"
+ required>
<select multiple name="field1_1" id="id_field1_1" required>
<option value="J" selected>John</option>
<option value="P" selected>Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>
- <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" required>
- <input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" required></td></tr>
+ <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0"
+ required>
+ <input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1"
+ required></td></tr>
""",
)
diff --git a/tests/forms_tests/field_tests/test_nullbooleanfield.py b/tests/forms_tests/field_tests/test_nullbooleanfield.py
index 5b632c8de3..c1e120c0bb 100644
--- a/tests/forms_tests/field_tests/test_nullbooleanfield.py
+++ b/tests/forms_tests/field_tests/test_nullbooleanfield.py
@@ -27,9 +27,11 @@ class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
f = HiddenNullBooleanForm()
self.assertHTMLEqual(
- '<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1">'
- '<input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2">',
str(f),
+ '<input type="hidden" name="hidden_nullbool1" value="True" '
+ 'id="id_hidden_nullbool1">'
+ '<input type="hidden" name="hidden_nullbool2" value="False" '
+ 'id="id_hidden_nullbool2">',
)
def test_nullbooleanfield_3(self):
@@ -69,7 +71,8 @@ class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
self.assertTrue(f.has_changed(True, False))
self.assertTrue(f.has_changed(True, None))
self.assertTrue(f.has_changed(True, False))
- # HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict
+ # 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.assertFalse(f.has_changed(None, ""))
diff --git a/tests/forms_tests/field_tests/test_urlfield.py b/tests/forms_tests/field_tests/test_urlfield.py
index f74c6567c1..e0afd4a7e7 100644
--- a/tests/forms_tests/field_tests/test_urlfield.py
+++ b/tests/forms_tests/field_tests/test_urlfield.py
@@ -99,7 +99,8 @@ class URLFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
f = URLField(min_length=15, max_length=20)
self.assertWidgetRendersTo(
f,
- '<input id="id_f" type="url" name="f" maxlength="20" minlength="15" required>',
+ '<input id="id_f" type="url" name="f" maxlength="20" minlength="15" '
+ "required>",
)
with self.assertRaisesMessage(
ValidationError,
diff --git a/tests/forms_tests/models.py b/tests/forms_tests/models.py
index ae212f332d..d6d0725b32 100644
--- a/tests/forms_tests/models.py
+++ b/tests/forms_tests/models.py
@@ -56,8 +56,11 @@ class ChoiceModel(models.Model):
class ChoiceOptionModel(models.Model):
- """Destination for ChoiceFieldModel's ForeignKey.
- Can't reuse ChoiceModel because error_message tests require that it have no instances."""
+ """
+ Destination for ChoiceFieldModel's ForeignKey.
+ Can't reuse ChoiceModel because error_message tests require that it have no
+ instances.
+ """
name = models.CharField(max_length=10)
diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py
index d5833b972e..233a3a622d 100644
--- a/tests/forms_tests/tests/test_forms.py
+++ b/tests/forms_tests/tests/test_forms.py
@@ -100,18 +100,24 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
self.assertHTMLEqual(
str(p["first_name"]),
- '<input type="text" name="first_name" value="John" id="id_first_name" required>',
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required>",
)
self.assertHTMLEqual(
str(p["last_name"]),
- '<input type="text" name="last_name" value="Lennon" id="id_last_name" required>',
+ '<input type="text" name="last_name" value="Lennon" id="id_last_name" '
+ "required>",
)
self.assertHTMLEqual(
str(p["birthday"]),
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required>",
)
- msg = "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, first_name, last_name."
+ msg = (
+ "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, "
+ "first_name, last_name."
+ )
with self.assertRaisesMessage(KeyError, msg):
p["nonexistentfield"]
@@ -142,12 +148,17 @@ class FormsTestCase(SimpleTestCase):
)
self.assertHTMLEqual(
str(p),
- """<tr><th><label for="id_first_name">First name:</label></th><td>
-<input type="text" name="first_name" value="John" id="id_first_name" required></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td>
-<input type="text" name="last_name" value="Lennon" id="id_last_name" required></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td>
-<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></td></tr>""",
+ """
+ <tr><th><label for="id_first_name">First name:</label></th><td>
+ <input type="text" name="first_name" value="John" id="id_first_name"
+ required></td></tr>
+ <tr><th><label for="id_last_name">Last name:</label></th><td>
+ <input type="text" name="last_name" value="Lennon" id="id_last_name"
+ required></td></tr>
+ <tr><th><label for="id_birthday">Birthday:</label></th><td>
+ <input type="text" name="birthday" value="1940-10-9" id="id_birthday"
+ required></td></tr>
+ """,
)
def test_empty_dict(self):
@@ -275,33 +286,41 @@ class FormsTestCase(SimpleTestCase):
self.assertHTMLEqual(
p.as_table(),
'<tr><th><label for="id_first_name">First name:</label></th><td>'
- '<input type="text" name="first_name" value="John" id="id_first_name" required></td></tr>\n'
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required></td></tr>\n"
'<tr><th><label for="id_last_name">Last name:</label>'
'</th><td><input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"'
'id="id_last_name" required></td></tr>\n'
'<tr><th><label for="id_birthday">Birthday:</label></th><td>'
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></td></tr>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required></td></tr>",
)
self.assertHTMLEqual(
p.as_ul(),
'<li><label for="id_first_name">First name:</label> '
- '<input type="text" name="first_name" value="John" id="id_first_name" required></li>\n'
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required></li>\n"
'<li><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
- 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required></li>\n'
+ 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
+ 'id="id_last_name" required></li>\n'
'<li><label for="id_birthday">Birthday:</label> '
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></li>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required></li>",
)
self.assertHTMLEqual(
p.as_p(),
'<p><label for="id_first_name">First name:</label> '
- '<input type="text" name="first_name" value="John" id="id_first_name" required></p>\n'
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required></p>\n"
'<p><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
- 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required></p>\n'
+ 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
+ 'id="id_last_name" required></p>\n'
'<p><label for="id_birthday">Birthday:</label> '
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></p>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required></p>",
)
p = Person({"last_name": "Lennon"})
@@ -356,11 +375,11 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9))
def test_optional_data(self):
- # cleaned_data will include a key and value for *all* fields defined in the Form,
- # even if the Form's data didn't include a value for fields that are not
- # required. In this example, the data dictionary doesn't include a value for the
- # "nick_name" field, but cleaned_data includes it. For CharFields, it's set to the
- # empty string.
+ # cleaned_data will include a key and value for *all* fields defined in
+ # the Form, even if the Form's data didn't include a value for fields
+ # that are not required. In this example, the data dictionary doesn't
+ # include a value for the "nick_name" field, but cleaned_data includes
+ # it. For CharFields, it's set to the empty string.
class OptionalPersonForm(Form):
first_name = CharField()
last_name = CharField()
@@ -387,10 +406,10 @@ class FormsTestCase(SimpleTestCase):
self.assertEqual(f.cleaned_data["last_name"], "Lennon")
def test_auto_id(self):
- # "auto_id" tells the Form to add an "id" attribute to each form element.
- # If it's a string that contains '%s', Django will use that as a format string
- # into which the field's name will be inserted. It will also put a <label> around
- # the human-readable labels for a field.
+ # "auto_id" tells the Form to add an "id" attribute to each form
+ # element. If it's a string that contains '%s', Django will use that as
+ # a format string into which the field's name will be inserted. It will
+ # also put a <label> around the human-readable labels for a field.
p = Person(auto_id="%s_id")
self.assertHTMLEqual(
p.as_table(),
@@ -727,18 +746,21 @@ class FormsTestCase(SimpleTestCase):
</div></li>""",
)
- # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
- # gets a distinct ID, formed by appending an underscore plus the button's
- # zero-based index.
+ # Regarding auto_id and <label>, RadioSelect is a special case. Each
+ # radio button gets a distinct ID, formed by appending an underscore
+ # plus the button's zero-based index.
f = FrameworkForm(auto_id="id_%s")
self.assertHTMLEqual(
str(f["language"]),
- """<div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div>""",
+ """
+ <div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div>""",
)
# When RadioSelect is used with auto_id, and the whole form is printed
@@ -747,33 +769,47 @@ Java</label></div>
# accessibility for screen reader users.
self.assertHTMLEqual(
f.as_table(),
- """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" required></td></tr>
-<tr><th><label>Language:</label></th><td><div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div></td></tr>""",
+ """
+ <tr><th><label for="id_name">Name:</label></th><td>
+ <input type="text" name="name" id="id_name" required></td></tr>
+ <tr><th><label>Language:</label></th><td><div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div></td></tr>""",
)
self.assertHTMLEqual(
f.as_ul(),
- """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li>
-<li><label>Language:</label> <div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div></li>""",
+ """
+ <li><label for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></li>
+ <li><label>Language:</label> <div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div></li>
+ """,
)
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p>
-<p><label>Language:</label> <div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></p>
+ <p><label>Language:</label> <div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div></p>
+ """,
)
def test_form_with_iterable_boundfield(self):
@@ -798,10 +834,17 @@ Java</label></div>
)
self.assertHTMLEqual(
"\n".join("<div>%s</div>" % bf for bf in f["name"]),
- """<div><label><input type="radio" name="name" value="john" required> John</label></div>
-<div><label><input type="radio" name="name" value="paul" required> Paul</label></div>
-<div><label><input type="radio" name="name" value="george" required> George</label></div>
-<div><label><input type="radio" name="name" value="ringo" required> Ringo</label></div>""",
+ """
+ <div><label>
+ <input type="radio" name="name" value="john" required> John</label></div>
+ <div><label>
+ <input type="radio" name="name" value="paul" required> Paul</label></div>
+ <div><label>
+ <input type="radio" name="name" value="george" required> George
+ </label></div>
+ <div><label>
+ <input type="radio" name="name" value="ringo" required> Ringo</label></div>
+ """,
)
def test_form_with_iterable_boundfield_id(self):
@@ -857,7 +900,7 @@ Java</label></div>
fields = list(BeatleForm(auto_id=False)["name"])
self.assertEqual(len(fields), 4)
- self.assertEqual(fields[0].id_for_label, None)
+ self.assertIsNone(fields[0].id_for_label)
self.assertEqual(fields[0].choice_label, "John")
self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>')
self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>')
@@ -1019,7 +1062,8 @@ Java</label></div>
self.assertTrue(f.is_valid())
self.assertHTMLEqual(
str(f["when"]),
- '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" required>'
+ '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" '
+ "required>"
'<input type="text" name="when_1" value="01:01" id="id_when_1" required>',
)
self.assertHTMLEqual(
@@ -1033,26 +1077,38 @@ Java</label></div>
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
- """<div>
-<div><label><input type="checkbox" name="composers" value="J"> John Lennon</label></div>
-<div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div>
+ <div><label><input type="checkbox" name="composers" value="J">
+ John Lennon</label></div>
+ <div><label><input type="checkbox" name="composers" value="P">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
f = SongForm({"composers": ["J"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
- """<div>
-<div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div>
-<div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div>
+ <div><label><input checked type="checkbox" name="composers" value="J">
+ John Lennon</label></div>
+ <div><label><input type="checkbox" name="composers" value="P">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
f = SongForm({"composers": ["J", "P"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
- """<div>
-<div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div>
-<div><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div>
+ <div><label><input checked type="checkbox" name="composers" value="J">
+ John Lennon</label></div>
+ <div><label><input checked type="checkbox" name="composers" value="P">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
def test_checkbox_auto_id(self):
@@ -1069,12 +1125,16 @@ Java</label></div>
f = SongForm(auto_id="%s_id")
self.assertHTMLEqual(
str(f["composers"]),
- """<div id="composers_id">
-<div><label for="composers_id_0">
-<input type="checkbox" name="composers" value="J" id="composers_id_0"> John Lennon</label></div>
-<div><label for="composers_id_1">
-<input type="checkbox" name="composers" value="P" id="composers_id_1"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div id="composers_id">
+ <div><label for="composers_id_0">
+ <input type="checkbox" name="composers" value="J" id="composers_id_0">
+ John Lennon</label></div>
+ <div><label for="composers_id_1">
+ <input type="checkbox" name="composers" value="P" id="composers_id_1">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
def test_multiple_choice_list_data(self):
@@ -1179,12 +1239,18 @@ Java</label></div>
)
self.assertHTMLEqual(
f.as_table(),
- """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
-<ul class="errorlist"><li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul>
-<input type="text" name="special_name" value="Nothing to escape" required></td></tr>
-<tr><th><em>Special</em> Field:</th><td>
-<ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul>
-<input type="text" name="special_safe_name" value="Nothing to escape" required></td></tr>""",
+ """
+ <tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
+ <ul class="errorlist">
+ <li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul>
+ <input type="text" name="special_name" value="Nothing to escape" required>
+ </td></tr>
+ <tr><th><em>Special</em> Field:</th><td>
+ <ul class="errorlist">
+ <li>'<b>Nothing to escape</b>' is a safe string</li></ul>
+ <input type="text" name="special_safe_name" value="Nothing to escape"
+ required></td></tr>
+ """,
)
f = EscapingForm(
{
@@ -1195,24 +1261,29 @@ Java</label></div>
)
self.assertHTMLEqual(
f.as_table(),
- """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
-<ul class="errorlist"><li>Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and
-&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>
-<input type="text" name="special_name"
-value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required></td></tr>
-<tr><th><em>Special</em> Field:</th><td>
-<ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>
-<input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>""",
+ "<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>"
+ '<ul class="errorlist"><li>'
+ "Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and "
+ "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>"
+ '<input type="text" name="special_name" value="Should escape &lt; &amp; '
+ '&gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required>'
+ "</td></tr>"
+ "<tr><th><em>Special</em> Field:</th><td>"
+ '<ul class="errorlist">'
+ "<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>"
+ '<input type="text" name="special_safe_name" '
+ 'value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>',
)
def test_validating_multiple_fields(self):
- # There are a couple of ways to do multiple-field validation. If you want the
- # validation message to be associated with a particular field, implement the
- # clean_XXX() method on the Form, where XXX is the field name. As in
- # Field.clean(), the clean_XXX() method should return the cleaned value. In the
- # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
- # of all the data that has been cleaned *so far*, in order by the fields,
- # including the current field (e.g., the field XXX if you're in clean_XXX()).
+ # There are a couple of ways to do multiple-field validation. If you
+ # want the validation message to be associated with a particular field,
+ # implement the clean_XXX() method on the Form, where XXX is the field
+ # name. As in Field.clean(), the clean_XXX() method should return the
+ # cleaned value. In the clean_XXX() method, you have access to
+ # self.cleaned_data, which is a dictionary of all the data that has
+ # been cleaned *so far*, in order by the fields, including the current
+ # field (e.g., the field XXX if you're in clean_XXX()).
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
@@ -1322,19 +1393,30 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
self.assertHTMLEqual(
f.as_table(),
- """<tr><td colspan="2">
-<ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
-<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" required></td></tr>
-<tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr>
-<tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr>""",
+ """
+ <tr><td colspan="2">
+ <ul class="errorlist nonfield">
+ <li>Please make sure your passwords match.</li></ul></td></tr>
+ <tr><th>Username:</th><td>
+ <input type="text" name="username" value="adrian" maxlength="10" required>
+ </td></tr>
+ <tr><th>Password1:</th><td>
+ <input type="password" name="password1" required></td></tr>
+ <tr><th>Password2:</th><td>
+ <input type="password" name="password2" required></td></tr>
+ """,
)
self.assertHTMLEqual(
f.as_ul(),
- """<li><ul class="errorlist nonfield">
-<li>Please make sure your passwords match.</li></ul></li>
-<li>Username: <input type="text" name="username" value="adrian" maxlength="10" required></li>
-<li>Password1: <input type="password" name="password1" required></li>
-<li>Password2: <input type="password" name="password2" required></li>""",
+ """
+ <li><ul class="errorlist nonfield">
+ <li>Please make sure your passwords match.</li></ul></li>
+ <li>Username:
+ <input type="text" name="username" value="adrian" maxlength="10" required>
+ </li>
+ <li>Password1: <input type="password" name="password1" required></li>
+ <li>Password2: <input type="password" name="password2" required></li>
+ """,
)
f = UserRegistration(
@@ -1509,9 +1591,14 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" required></td></tr>""",
+ """
+ <tr><th>First name:</th><td>
+ <input type="text" name="first_name" required></td></tr>
+ <tr><th>Last name:</th><td>
+ <input type="text" name="last_name" required></td></tr>
+ <tr><th>Birthday:</th><td>
+ <input type="text" name="birthday" required></td></tr>
+ """,
)
# Instances of a dynamic Form do not persist fields from one Form instance to
@@ -1527,15 +1614,19 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""",
+ """
+ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
+ <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
+ """,
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>""",
+ """
+ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
+ <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
+ """,
)
class MyForm(Form):
@@ -1552,19 +1643,27 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr>
-<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr>
-<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""",
+ """
+ <tr><th>Default field 1:</th><td>
+ <input type="text" name="default_field_1" required></td></tr>
+ <tr><th>Default field 2:</th><td>
+ <input type="text" name="default_field_2" required></td></tr>
+ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
+ <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
+ """,
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr>
-<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr>
-<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>""",
+ """
+ <tr><th>Default field 1:</th><td>
+ <input type="text" name="default_field_1" required></td></tr>
+ <tr><th>Default field 2:</th><td>
+ <input type="text" name="default_field_2" required></td></tr>
+ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
+ <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
+ """,
)
# Similarly, changes to field attributes do not persist from one Form instance
@@ -1692,22 +1791,33 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr>
-<tr><th>Birthday:</th>
-<td><input type="text" name="birthday" required><input type="hidden" name="hidden_text"></td></tr>""",
+ """
+ <tr><th>First name:</th><td><input type="text" name="first_name" required>
+ </td></tr>
+ <tr><th>Last name:</th><td><input type="text" name="last_name" required>
+ </td></tr>
+ <tr><th>Birthday:</th>
+ <td><input type="text" name="birthday" required>
+ <input type="hidden" name="hidden_text"></td></tr>
+ """,
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>First name: <input type="text" name="first_name" required></li>
-<li>Last name: <input type="text" name="last_name" required></li>
-<li>Birthday: <input type="text" name="birthday" required><input type="hidden" name="hidden_text"></li>""",
+ """
+ <li>First name: <input type="text" name="first_name" required></li>
+ <li>Last name: <input type="text" name="last_name" required></li>
+ <li>Birthday: <input type="text" name="birthday" required>
+ <input type="hidden" name="hidden_text"></li>
+ """,
)
self.assertHTMLEqual(
p.as_p(),
- """<p>First name: <input type="text" name="first_name" required></p>
-<p>Last name: <input type="text" name="last_name" required></p>
-<p>Birthday: <input type="text" name="birthday" required><input type="hidden" name="hidden_text"></p>""",
+ """
+ <p>First name: <input type="text" name="first_name" required></p>
+ <p>Last name: <input type="text" name="last_name" required></p>
+ <p>Birthday: <input type="text" name="birthday" required>
+ <input type="hidden" name="hidden_text"></p>
+ """,
)
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
@@ -1753,28 +1863,44 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
self.assertHTMLEqual(
p.as_table(),
- """<tr><td colspan="2">
-<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
-<tr><th>First name:</th><td><input type="text" name="first_name" value="John" required></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" required></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" required>
-<input type="hidden" name="hidden_text"></td></tr>""",
+ """
+ <tr><td colspan="2">
+ <ul class="errorlist nonfield"><li>
+ (Hidden field hidden_text) This field is required.</li></ul></td></tr>
+ <tr><th>First name:</th><td>
+ <input type="text" name="first_name" value="John" required></td></tr>
+ <tr><th>Last name:</th><td>
+ <input type="text" name="last_name" value="Lennon" required></td></tr>
+ <tr><th>Birthday:</th><td>
+ <input type="text" name="birthday" value="1940-10-9" required>
+ <input type="hidden" name="hidden_text"></td></tr>
+ """,
)
self.assertHTMLEqual(
p.as_ul(),
- """<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
-<li>First name: <input type="text" name="first_name" value="John" required></li>
-<li>Last name: <input type="text" name="last_name" value="Lennon" required></li>
-<li>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
-<input type="hidden" name="hidden_text"></li>""",
+ """
+ <li><ul class="errorlist nonfield"><li>
+ (Hidden field hidden_text) This field is required.</li></ul></li>
+ <li>First name: <input type="text" name="first_name" value="John" required>
+ </li>
+ <li>Last name: <input type="text" name="last_name" value="Lennon" required>
+ </li>
+ <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
+ <input type="hidden" name="hidden_text"></li>
+ """,
)
self.assertHTMLEqual(
p.as_p(),
- """<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul>
-<p>First name: <input type="text" name="first_name" value="John" required></p>
-<p>Last name: <input type="text" name="last_name" value="Lennon" required></p>
-<p>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
-<input type="hidden" name="hidden_text"></p>""",
+ """
+ <ul class="errorlist nonfield"><li>
+ (Hidden field hidden_text) This field is required.</li></ul>
+ <p>First name: <input type="text" name="first_name" value="John" required>
+ </p>
+ <p>Last name: <input type="text" name="last_name" value="Lennon" required>
+ </p>
+ <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
+ <input type="hidden" name="hidden_text"></p>
+ """,
)
# A corner case: It's possible for a form to have only HiddenInputs.
@@ -1816,20 +1942,11 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = TestForm(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
-<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
-<tr><th>Field5:</th><td><input type="text" name="field5" required></td></tr>
-<tr><th>Field6:</th><td><input type="text" name="field6" required></td></tr>
-<tr><th>Field7:</th><td><input type="text" name="field7" required></td></tr>
-<tr><th>Field8:</th><td><input type="text" name="field8" required></td></tr>
-<tr><th>Field9:</th><td><input type="text" name="field9" required></td></tr>
-<tr><th>Field10:</th><td><input type="text" name="field10" required></td></tr>
-<tr><th>Field11:</th><td><input type="text" name="field11" required></td></tr>
-<tr><th>Field12:</th><td><input type="text" name="field12" required></td></tr>
-<tr><th>Field13:</th><td><input type="text" name="field13" required></td></tr>
-<tr><th>Field14:</th><td><input type="text" name="field14" required></td></tr>""",
+ "".join(
+ f"<tr><th>Field{i}:</th><td>"
+ f'<input type="text" name="field{i}" required></td></tr>'
+ for i in range(1, 15)
+ ),
)
def test_explicit_field_order(self):
@@ -1893,15 +2010,20 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" maxlength="10" required></li>
-<li>Realname: <input type="text" name="realname" maxlength="10" required></li>
-<li>Address: <input type="text" name="address" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" maxlength="10" required>
+ </li>
+ <li>Password: <input type="password" name="password" maxlength="10"
+ required></li>
+ <li>Realname: <input type="text" name="realname" maxlength="10" required>
+ </li>
+ <li>Address: <input type="text" name="address" required></li>
+ """,
)
- # If you specify a custom "attrs" that includes the "maxlength" attribute,
- # the Field's max_length attribute will override whatever "maxlength" you specify
- # in "attrs".
+ # If you specify a custom "attrs" that includes the "maxlength"
+ # attribute, the Field's max_length attribute will override whatever
+ # "maxlength" you specify in "attrs".
class UserRegistration(Form):
username = CharField(
max_length=10, widget=TextInput(attrs={"maxlength": 20})
@@ -1927,9 +2049,13 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Your username: <input type="text" name="username" maxlength="10" required></li>
-<li>Password1: <input type="password" name="password1" required></li>
-<li>Contraseña (de nuevo): <input type="password" name="password2" required></li>""",
+ """
+ <li>Your username:
+ <input type="text" name="username" maxlength="10" required></li>
+ <li>Password1: <input type="password" name="password1" required></li>
+ <li>Contraseña (de nuevo):
+ <input type="password" name="password2" required></li>
+ """,
)
# Labels for as_* methods will only end in a colon if they don't end in other
@@ -1951,14 +2077,22 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
self.assertHTMLEqual(
Questions().as_p(),
- """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p>
-<p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p>
-<p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p>
-<p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p>
-<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p>""",
+ """
+ <p><label for="id_q1">The first question:</label>
+ <input type="text" name="q1" id="id_q1" required></p>
+ <p><label for="id_q2">What is your name?</label>
+ <input type="text" name="q2" id="id_q2" required></p>
+ <p><label for="id_q3">The answer to life is:</label>
+ <input type="text" name="q3" id="id_q3" required></p>
+ <p><label for="id_q4">Answer this question!</label>
+ <input type="text" name="q4" id="id_q4" required></p>
+ <p><label for="id_q5">The last question. Period.</label>
+ <input type="text" name="q5" id="id_q5" required></p>
+ """,
)
- # If a label is set to the empty string for a field, that field won't get a label.
+ # If a label is set to the empty string for a field, that field won't
+ # get a label.
class UserRegistration(Form):
username = CharField(max_length=10, label="")
password = CharField(widget=PasswordInput)
@@ -1972,9 +2106,13 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
- """<li> <input id="id_username" type="text" name="username" maxlength="10" required></li>
-<li><label for="id_password">Password:</label>
-<input type="password" name="password" id="id_password" required></li>""",
+ """
+ <li>
+ <input id="id_username" type="text" name="username" maxlength="10" required>
+ </li>
+ <li><label for="id_password">Password:</label>
+ <input type="password" name="password" id="id_password" required></li>
+ """,
)
# If label is None, Django will auto-create the label from the field name. This
@@ -1999,11 +2137,12 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
def test_label_suffix(self):
- # You can specify the 'label_suffix' argument to a Form class to modify the
- # punctuation symbol used at the end of a label. By default, the colon (:) is
- # used, and is only appended to the label if the label doesn't already end with a
- # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
- # be appended regardless of the last character of the label.
+ # You can specify the 'label_suffix' argument to a Form class to modify
+ # the punctuation symbol used at the end of a label. By default, the
+ # colon (:) is used, and is only appended to the label if the label
+ # doesn't already end with a punctuation symbol: ., !, ? or :. If you
+ # specify a different suffix, it will be appended regardless of the
+ # last character of the label.
class FavoriteForm(Form):
color = CharField(label="Favorite color?")
animal = CharField(label="Favorite animal")
@@ -2037,7 +2176,8 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
self.assertHTMLEqual(
f.as_ul(),
'<li>Favorite color? <input type="text" name="color" required></li>\n'
- '<li>Favorite animal\u2192 <input type="text" name="animal" required></li>\n'
+ "<li>Favorite animal\u2192 "
+ '<input type="text" name="animal" required></li>\n'
'<li>Secret answer = <input type="text" name="answer" required></li>',
)
@@ -2055,8 +2195,11 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
# Here, we're submitting data, so the initial value will *not* be displayed.
@@ -2079,14 +2222,18 @@ Password: <input type="password" name="password" required></li>""",
p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>
-Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="foo" maxlength="10"
+ required></li>
+ <li><ul class="errorlist"><li>This field is required.</li></ul>
+ Password: <input type="password" name="password" required></li>
+ """,
)
- # An 'initial' value is *not* used as a fallback if data is not provided. In this
- # example, we don't provide a value for 'username', and the form raises a
- # validation error rather than using the initial value for 'username'.
+ # An 'initial' value is *not* used as a fallback if data is not
+ # provided. In this example, we don't provide a value for 'username',
+ # and the form raises a validation error rather than using the initial
+ # value for 'username'.
p = UserRegistration({"password": "secret"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
@@ -2105,14 +2252,20 @@ Password: <input type="password" name="password" required></li>""",
p = UserRegistration(initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
p = UserRegistration(initial={"username": "stephane"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="stephane"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
# The 'initial' parameter is meaningless if you pass data.
@@ -2139,20 +2292,24 @@ Password: <input type="password" name="password" required></li>""",
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>
-Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="foo" maxlength="10"
+ required></li>
+ <li><ul class="errorlist"><li>This field is required.</li></ul>
+ Password: <input type="password" name="password" required></li>
+ """,
)
# A dynamic 'initial' value is *not* used as a fallback if data is not provided.
- # In this example, we don't provide a value for 'username', and the form raises a
- # validation error rather than using the initial value for 'username'.
+ # In this example, we don't provide a value for 'username', and the
+ # form raises a validation error rather than using the initial value
+ # for 'username'.
p = UserRegistration({"password": "secret"}, initial={"username": "django"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
- # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
- # then the latter will get precedence.
+ # If a Form defines 'initial' *and* 'initial' is passed as a parameter
+ # to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
@@ -2160,8 +2317,11 @@ Password: <input type="password" name="password" required></li>""",
p = UserRegistration(initial={"username": "babik"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="babik"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
def test_callable_initial_data(self):
@@ -2194,13 +2354,16 @@ Password: <input type="password" name="password" required></li>""",
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f" selected>foo</option>
-<option value="b" selected>bar</option>
-<option value="w">whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f" selected>foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w">whiz</option>
+ </select></li>
+ """,
)
# The 'initial' parameter is meaningless if you pass data.
@@ -2245,19 +2408,23 @@ Options: <select multiple name="options" required>
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>
-Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f" selected>foo</option>
-<option value="b" selected>bar</option>
-<option value="w">whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="foo" maxlength="10"
+ required></li>
+ <li><ul class="errorlist"><li>This field is required.</li></ul>
+ Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f" selected>foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w">whiz</option>
+ </select></li>
+ """,
)
- # A callable 'initial' value is *not* used as a fallback if data is not provided.
- # In this example, we don't provide a value for 'username', and the form raises a
- # validation error rather than using the initial value for 'username'.
+ # A callable 'initial' value is *not* used as a fallback if data is not
+ # provided. In this example, we don't provide a value for 'username',
+ # and the form raises a validation error rather than using the initial
+ # value for 'username'.
p = UserRegistration(
{"password": "secret"},
initial={"username": initial_django, "options": initial_options},
@@ -2265,8 +2432,8 @@ Password: <input type="password" name="password" required></li>
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
- # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
- # then the latter will get precedence.
+ # If a Form defines 'initial' *and* 'initial' is passed as a parameter
+ # to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
@@ -2278,13 +2445,16 @@ Password: <input type="password" name="password" required></li>
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f">foo</option>
-<option value="b" selected>bar</option>
-<option value="w" selected>whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f">foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w" selected>whiz</option>
+ </select></li>
+ """,
)
p = UserRegistration(
initial={"username": initial_stephane, "options": initial_options},
@@ -2292,13 +2462,16 @@ Password: <input type="password" name="password" required></li>
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f" selected>foo</option>
-<option value="b" selected>bar</option>
-<option value="w">whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="stephane"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f" selected>foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w">whiz</option>
+ </select></li>
+ """,
)
def test_get_initial_for_field(self):
@@ -2531,7 +2704,8 @@ Password: <input type="password" name="password" required></li>
self.assertEqual(form.changed_data, [])
def test_help_text(self):
- # You can specify descriptive text for a field by using the 'help_text' argument)
+ # You can specify descriptive text for a field by using the 'help_text'
+ # argument.
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., user@example.com")
password = CharField(
@@ -2555,10 +2729,13 @@ Password: <input type="password" name="password" required></li>
)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required><br>
-<span class="helptext">e.g., user@example.com</span></td></tr>
-<tr><th>Password:</th><td><input type="password" name="password" required><br>
-<span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""",
+ """
+ <tr><th>Username:</th><td>
+ <input type="text" name="username" maxlength="10" required><br>
+ <span class="helptext">e.g., user@example.com</span></td></tr>
+ <tr><th>Password:</th><td><input type="password" name="password" required>
+ <br>
+ <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""",
)
# The help text is displayed whether or not data is provided for the form.
@@ -2678,13 +2855,14 @@ Password: <input type="password" name="password" required>
)
def test_forms_with_prefixes(self):
- # Sometimes it's necessary to have multiple forms display on the same HTML page,
- # or multiple copies of the same form. We can accomplish this with form prefixes.
- # Pass the keyword argument 'prefix' to the Form constructor to use this feature.
- # This value will be prepended to each HTML form field name. One way to think
- # about this is "namespaces for HTML forms". Notice that in the data argument,
- # each field's key has the prefix, in this case 'person1', prepended to the
- # actual field name.
+ # Sometimes it's necessary to have multiple forms display on the same
+ # HTML page, or multiple copies of the same form. We can accomplish
+ # this with form prefixes. Pass the keyword argument 'prefix' to the
+ # Form constructor to use this feature. This value will be prepended to
+ # each HTML form field name. One way to think about this is "namespaces
+ # for HTML forms". Notice that in the data argument, each field's key
+ # has the prefix, in this case 'person1', prepended to the actual field
+ # name.
class Person(Form):
first_name = CharField()
last_name = CharField()
@@ -2698,24 +2876,32 @@ Password: <input type="password" name="password" required>
p = Person(data, prefix="person1")
self.assertHTMLEqual(
p.as_ul(),
- """<li><label for="id_person1-first_name">First name:</label>
-<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required></li>
-<li><label for="id_person1-last_name">Last name:</label>
-<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required></li>
-<li><label for="id_person1-birthday">Birthday:</label>
-<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li>""",
+ """
+ <li><label for="id_person1-first_name">First name:</label>
+ <input type="text" name="person1-first_name" value="John"
+ id="id_person1-first_name" required></li>
+ <li><label for="id_person1-last_name">Last name:</label>
+ <input type="text" name="person1-last_name" value="Lennon"
+ id="id_person1-last_name" required></li>
+ <li><label for="id_person1-birthday">Birthday:</label>
+ <input type="text" name="person1-birthday" value="1940-10-9"
+ id="id_person1-birthday" required></li>
+ """,
)
self.assertHTMLEqual(
str(p["first_name"]),
- '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required>',
+ '<input type="text" name="person1-first_name" value="John" '
+ 'id="id_person1-first_name" required>',
)
self.assertHTMLEqual(
str(p["last_name"]),
- '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required>',
+ '<input type="text" name="person1-last_name" value="Lennon" '
+ 'id="id_person1-last_name" required>',
)
self.assertHTMLEqual(
str(p["birthday"]),
- '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required>',
+ '<input type="text" name="person1-birthday" value="1940-10-9" '
+ 'id="id_person1-birthday" required>',
)
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
@@ -2787,12 +2973,17 @@ Password: <input type="password" name="password" required>
p = Person(prefix="foo")
self.assertHTMLEqual(
p.as_ul(),
- """<li><label for="id_foo-prefix-first_name">First name:</label>
-<input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required></li>
-<li><label for="id_foo-prefix-last_name">Last name:</label>
-<input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required></li>
-<li><label for="id_foo-prefix-birthday">Birthday:</label>
-<input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li>""",
+ """
+ <li><label for="id_foo-prefix-first_name">First name:</label>
+ <input type="text" name="foo-prefix-first_name"
+ id="id_foo-prefix-first_name" required></li>
+ <li><label for="id_foo-prefix-last_name">Last name:</label>
+ <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name"
+ required></li>
+ <li><label for="id_foo-prefix-birthday">Birthday:</label>
+ <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday"
+ required></li>
+ """,
)
data = {
"foo-prefix-first_name": "John",
@@ -2907,15 +3098,16 @@ Password: <input type="password" name="password" required>
)
def test_forms_with_file_fields(self):
- # FileFields are a special case because they take their data from the request.FILES,
- # not request.POST.
+ # FileFields are a special case because they take their data from the
+ # request.FILES, not request.POST.
class FileForm(Form):
file1 = FileField()
f = FileForm(auto_id=False)
self.assertHTMLEqual(
f.as_table(),
- '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>',
+ "<tr><th>File1:</th><td>"
+ '<input type="file" name="file1" required></td></tr>',
)
f = FileForm(data={}, files={}, auto_id=False)
@@ -2954,7 +3146,8 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
f.as_table(),
- '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>',
+ "<tr><th>File1:</th><td>"
+ '<input type="file" name="file1" required></td></tr>',
)
self.assertTrue(f.is_valid())
@@ -2964,7 +3157,8 @@ Password: <input type="password" name="password" required>
f = FileForm(data={}, files={"file1": file1}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
- '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>',
+ "<tr><th>File1:</th><td>"
+ '<input type="file" name="file1" required></td></tr>',
)
# A required file field with initial data should not contain the
@@ -3084,9 +3278,10 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
MyForm().as_table(),
- '<tr><th><label for="id_field1">Field1:</label></th>'
- '<td><input id="id_field1" type="text" name="field1" maxlength="50" required>'
- '<input type="hidden" name="initial-field1" id="initial-id_field1"></td></tr>',
+ '<tr><th><label for="id_field1">Field1:</label></th><td>'
+ '<input id="id_field1" type="text" name="field1" maxlength="50" required>'
+ '<input type="hidden" name="initial-field1" id="initial-id_field1">'
+ "</td></tr>",
)
def test_error_html_required_html_classes(self):
@@ -3102,34 +3297,46 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
p.as_ul(),
- """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
-<label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li>
-<li class="required"><label class="required" for="id_is_cool">Is cool:</label>
-<select name="is_cool" id="id_is_cool">
-<option value="unknown" selected>Unknown</option>
-<option value="true">Yes</option>
-<option value="false">No</option>
-</select></li>
-<li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li>
-<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
-<label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""",
+ """
+ <li class="required error"><ul class="errorlist">
+ <li>This field is required.</li></ul>
+ <label class="required" for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></li>
+ <li class="required">
+ <label class="required" for="id_is_cool">Is cool:</label>
+ <select name="is_cool" id="id_is_cool">
+ <option value="unknown" selected>Unknown</option>
+ <option value="true">Yes</option>
+ <option value="false">No</option>
+ </select></li>
+ <li><label for="id_email">Email:</label>
+ <input type="email" name="email" id="id_email"></li>
+ <li class="required error"><ul class="errorlist">
+ <li>This field is required.</li></ul>
+ <label class="required" for="id_age">Age:</label>
+ <input type="number" name="age" id="id_age" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
- """<ul class="errorlist"><li>This field is required.</li></ul>
-<p class="required error"><label class="required" for="id_name">Name:</label>
-<input type="text" name="name" id="id_name" required></p>
-<p class="required"><label class="required" for="id_is_cool">Is cool:</label>
-<select name="is_cool" id="id_is_cool">
-<option value="unknown" selected>Unknown</option>
-<option value="true">Yes</option>
-<option value="false">No</option>
-</select></p>
-<p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p>
-<ul class="errorlist"><li>This field is required.</li></ul>
-<p class="required error"><label class="required" for="id_age">Age:</label>
-<input type="number" name="age" id="id_age" required></p>""",
+ """
+ <ul class="errorlist"><li>This field is required.</li></ul>
+ <p class="required error">
+ <label class="required" for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></p>
+ <p class="required">
+ <label class="required" for="id_is_cool">Is cool:</label>
+ <select name="is_cool" id="id_is_cool">
+ <option value="unknown" selected>Unknown</option>
+ <option value="true">Yes</option>
+ <option value="false">No</option>
+ </select></p>
+ <p><label for="id_email">Email:</label>
+ <input type="email" name="email" id="id_email"></p>
+ <ul class="errorlist"><li>This field is required.</li></ul>
+ <p class="required error"><label class="required" for="id_age">Age:</label>
+ <input type="number" name="age" id="id_age" required></p>
+ """,
)
self.assertHTMLEqual(
@@ -3394,10 +3601,14 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
form.as_p(),
"""
- <p>Phone1:<input type="text" name="phone1_0" required><input type="text" name="phone1_1" required></p>
- <p>Phone2:<input type="text" name="phone2_0"><input type="text" name="phone2_1"></p>
- <p>Phone3:<input type="text" name="phone3_0" required><input type="text" name="phone3_1"></p>
- <p>Phone4:<input type="text" name="phone4_0"><input type="text" name="phone4_1"></p>
+ <p>Phone1:<input type="text" name="phone1_0" required>
+ <input type="text" name="phone1_1" required></p>
+ <p>Phone2:<input type="text" name="phone2_0">
+ <input type="text" name="phone2_1"></p>
+ <p>Phone3:<input type="text" name="phone3_0" required>
+ <input type="text" name="phone3_1"></p>
+ <p>Phone4:<input type="text" name="phone4_0">
+ <input type="text" name="phone4_1"></p>
""",
)
@@ -3585,7 +3796,8 @@ Password: <input type="password" name="password" required>
control = [
'<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>',
'<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>',
- '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul></li>',
+ '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>'
+ "</li>",
]
for error in control:
self.assertInHTML(error, errors)
@@ -3689,10 +3901,14 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
p.as_p(),
- """<ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul>
-<p><label for="id_first_name">First name:</label>
-<input id="id_first_name" name="first_name" type="text" value="John" required>
-<input id="id_last_name" name="last_name" type="hidden"></p>""",
+ """
+ <ul class="errorlist nonfield">
+ <li>(Hidden field last_name) This field is required.</li></ul>
+ <p><label for="id_first_name">First name:</label>
+ <input id="id_first_name" name="first_name" type="text" value="John"
+ required>
+ <input id="id_last_name" name="last_name" type="hidden"></p>
+ """,
)
self.assertHTMLEqual(
p.as_table(),
@@ -3738,11 +3954,18 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
p.as_table(),
- """<tr><td colspan="2"><ul class="errorlist nonfield"><li>Generic validation error</li></ul></td></tr>
-<tr><th><label for="id_first_name">First name:</label></th><td>
-<input id="id_first_name" name="first_name" type="text" value="John" required></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td>
-<input id="id_last_name" name="last_name" type="text" value="Lennon" required></td></tr>""",
+ """
+ <tr><td colspan="2"><ul class="errorlist nonfield">
+ <li>Generic validation error</li></ul></td></tr>
+ <tr><th><label for="id_first_name">First name:</label></th><td>
+ <input id="id_first_name" name="first_name" type="text" value="John"
+ required>
+ </td></tr>
+ <tr><th><label for="id_last_name">Last name:</label></th><td>
+ <input id="id_last_name" name="last_name" type="text" value="Lennon"
+ required>
+ </td></tr>
+ """,
)
def test_error_escaping(self):
@@ -3759,7 +3982,8 @@ Password: <input type="password" name="password" required>
form.is_valid()
self.assertHTMLEqual(
form.as_ul(),
- '<li><ul class="errorlist nonfield"><li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>'
+ '<li><ul class="errorlist nonfield">'
+ "<li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>"
'<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>'
'<label for="id_visible">Visible:</label> '
'<input type="text" name="visible" value="b" id="id_visible" required>'
@@ -3774,14 +3998,16 @@ Password: <input type="password" name="password" required>
p = Person()
self.assertEqual(
repr(p),
- "<Person bound=False, valid=Unknown, fields=(first_name;last_name;birthday)>",
+ "<Person bound=False, valid=Unknown, "
+ "fields=(first_name;last_name;birthday)>",
)
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
)
self.assertEqual(
repr(p),
- "<Person bound=True, valid=Unknown, fields=(first_name;last_name;birthday)>",
+ "<Person bound=True, valid=Unknown, "
+ "fields=(first_name;last_name;birthday)>",
)
p.is_valid()
self.assertEqual(
@@ -3894,9 +4120,12 @@ Password: <input type="password" name="password" required>
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
- '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" required></p>'
- '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>'
- '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
+ '<p><label for="id_f1">F1:</label>'
+ '<input id="id_f1" maxlength="30" name="f1" type="text" required></p>'
+ '<p><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
+ '<p><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></p>"
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
@@ -3907,8 +4136,10 @@ Password: <input type="password" name="password" required>
form.as_ul(),
'<li><label for="id_f1">F1:</label> '
'<input id="id_f1" maxlength="30" name="f1" type="text" required></li>'
- '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>'
- '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
+ '<li><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
+ '<li><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></li>"
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
@@ -3918,13 +4149,15 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
- '<td><input id="id_f1" maxlength="30" name="f1" type="text" required></td></tr>'
+ '<td><input id="id_f1" maxlength="30" name="f1" type="text" required>'
+ "</td></tr>"
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th>'
'<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></td></tr>"
- '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">'
+ '<tr><th><label for="id_f4">F4:</label></th><td>'
+ '<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
@@ -3941,10 +4174,12 @@ Password: <input type="password" name="password" required>
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
- '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></p>'
- '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>'
- '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
- "</textarea></p>"
+ '<p><label for="id_f1">F1:</label>'
+ '<input id="id_f1" maxlength="30" name="f1" type="text"></p>'
+ '<p><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
+ '<p><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>'
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
@@ -3952,10 +4187,12 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
form.as_ul(),
- '<li><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></li>'
- '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>'
- '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
- "</textarea></li>"
+ '<li><label for="id_f1">F1:</label>'
+ '<input id="id_f1" maxlength="30" name="f1" type="text"></li>'
+ '<li><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
+ '<li><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>'
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
@@ -3967,9 +4204,11 @@ Password: <input type="password" name="password" required>
'<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>'
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
- '<tr><th><label for="id_f3">F3:</label></th><td><textarea cols="40" id="id_f3" name="f3" rows="10">'
+ '<tr><th><label for="id_f3">F3:</label></th><td>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10">'
"</textarea></td></tr>"
- '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">'
+ '<tr><th><label for="id_f4">F4:</label></th><td>'
+ '<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py
index c37e95a071..8634b3df29 100644
--- a/tests/forms_tests/tests/test_formsets.py
+++ b/tests/forms_tests/tests/test_formsets.py
@@ -641,7 +641,8 @@ class FormsFormsetTestCase(SimpleTestCase):
def test_formsets_with_ordering(self):
"""
formset_factory's can_order argument adds an integer field to each
- form. When form validation succeeds, [form.cleaned_data for form in formset.forms]
+ form. When form validation succeeds,
+ [form.cleaned_data for form in formset.forms]
will have the data in the correct order specified by the ordering
fields. If a number is duplicated in the set of ordering fields, for
instance form 0 and form 3 are both marked as 1, then the form index
@@ -943,10 +944,13 @@ class FormsFormsetTestCase(SimpleTestCase):
formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Fernet and Coke"}])
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td><input type="text" name="form-0-name" value="Fernet and Coke"
+ id="id_form-0-name"></td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>
+ """,
)
def test_max_num_zero(self):
@@ -972,10 +976,14 @@ class FormsFormsetTestCase(SimpleTestCase):
formset = LimitedFavoriteDrinkFormSet(initial=initial)
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td><input id="id_form-0-name" name="form-0-name" type="text"
+ value="Fernet and Coke"></td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td><input id="id_form-1-name" name="form-1-name" type="text"
+ value="Bloody Mary"></td></tr>
+ """,
)
def test_more_initial_than_max_num(self):
@@ -994,12 +1002,20 @@ class FormsFormsetTestCase(SimpleTestCase):
formset = LimitedFavoriteDrinkFormSet(initial=initial)
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></td></tr>
-<tr><th><label for="id_form-2-name">Name:</label></th>
-<td><input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td>
+ <input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic">
+ </td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td>
+ <input id="id_form-1-name" name="form-1-name" type="text"
+ value="Bloody Mary"></td></tr>
+ <tr><th><label for="id_form-2-name">Name:</label></th>
+ <td>
+ <input id="id_form-2-name" name="form-2-name" type="text"
+ value="Jack and Coke"></td></tr>
+ """,
)
def test_default_absolute_max(self):
@@ -1077,10 +1093,13 @@ class FormsFormsetTestCase(SimpleTestCase):
formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Gin Tonic"}])
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td>
+ <input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name">
+ </td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>""",
)
def test_management_form_prefix(self):
@@ -1454,7 +1473,8 @@ class FormsetAsTagTests(SimpleTestCase):
self.formset.as_p(),
self.management_form_html
+ (
- '<p>Choice: <input type="text" name="choices-0-choice" value="Calexico"></p>'
+ "<p>Choice: "
+ '<input type="text" name="choices-0-choice" value="Calexico"></p>'
'<p>Votes: <input type="number" name="choices-0-votes" value="100"></p>'
),
)
@@ -1464,8 +1484,10 @@ class FormsetAsTagTests(SimpleTestCase):
self.formset.as_ul(),
self.management_form_html
+ (
- '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li>'
- '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>'
+ "<li>Choice: "
+ '<input type="text" name="choices-0-choice" value="Calexico"></li>'
+ "<li>Votes: "
+ '<input type="number" name="choices-0-votes" value="100"></li>'
),
)
@@ -1535,8 +1557,10 @@ class TestIsBoundBehavior(SimpleTestCase):
"<li>(Hidden field TOTAL_FORMS) Enter a whole number.</li>"
"<li>(Hidden field INITIAL_FORMS) Enter a whole number.</li>"
"</ul>"
- '<input type="hidden" name="form-TOTAL_FORMS" value="two" id="id_form-TOTAL_FORMS">'
- '<input type="hidden" name="form-INITIAL_FORMS" value="one" id="id_form-INITIAL_FORMS">'
+ '<input type="hidden" name="form-TOTAL_FORMS" value="two" '
+ 'id="id_form-TOTAL_FORMS">'
+ '<input type="hidden" name="form-INITIAL_FORMS" value="one" '
+ 'id="id_form-INITIAL_FORMS">'
'<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">'
'<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">'
"</td></tr>\n",
diff --git a/tests/forms_tests/tests/test_i18n.py b/tests/forms_tests/tests/test_i18n.py
index f7a4aabbf8..ea6a8e104b 100644
--- a/tests/forms_tests/tests/test_i18n.py
+++ b/tests/forms_tests/tests/test_i18n.py
@@ -22,21 +22,25 @@ class FormsI18nTests(SimpleTestCase):
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_username">username:</label>'
- '<input id="id_username" type="text" name="username" maxlength="10" required></p>',
+ '<input id="id_username" type="text" name="username" maxlength="10" '
+ "required></p>",
)
- # Translations are done at rendering time, so multi-lingual apps can define forms)
+ # Translations are done at rendering time, so multi-lingual apps can
+ # define forms.
with translation.override("de"):
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_username">Benutzername:</label>'
- '<input id="id_username" type="text" name="username" maxlength="10" required></p>',
+ '<input id="id_username" type="text" name="username" maxlength="10" '
+ "required></p>",
)
with translation.override("pl"):
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_username">nazwa u\u017cytkownika:</label>'
- '<input id="id_username" type="text" name="username" maxlength="10" required></p>',
+ '<input id="id_username" type="text" name="username" maxlength="10" '
+ "required></p>",
)
def test_non_ascii_label(self):
@@ -70,13 +74,13 @@ class FormsI18nTests(SimpleTestCase):
"<p><label>\xc5\xf8\xdf:</label>"
'<div id="id_somechoice">\n'
'<div><label for="id_somechoice_0">'
- '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required> '
- "En tied\xe4</label></div>\n"
+ '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" '
+ "required> En tied\xe4</label></div>\n"
'<div><label for="id_somechoice_1">'
- '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required> '
- 'Mies</label></div>\n<div><label for="id_somechoice_2">'
- '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required> '
- "Nainen</label></div>\n</div></p>",
+ '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" '
+ 'required> Mies</label></div>\n<div><label for="id_somechoice_2">'
+ '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" '
+ "required> Nainen</label></div>\n</div></p>",
)
# Translated error messages
@@ -89,13 +93,14 @@ class FormsI18nTests(SimpleTestCase):
"\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n"
"<p><label>\xc5\xf8\xdf:</label>"
' <div id="id_somechoice">\n<div><label for="id_somechoice_0">'
- '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required> '
- "En tied\xe4</label></div>\n"
+ '<input type="radio" id="id_somechoice_0" value="\xc5" '
+ 'name="somechoice" required> En tied\xe4</label></div>\n'
'<div><label for="id_somechoice_1">'
- '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required> '
- 'Mies</label></div>\n<div><label for="id_somechoice_2">'
- '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required> '
- "Nainen</label></div>\n</div></p>",
+ '<input type="radio" id="id_somechoice_1" value="\xf8" '
+ 'name="somechoice" required> Mies</label></div>\n<div>'
+ '<label for="id_somechoice_2">'
+ '<input type="radio" id="id_somechoice_2" value="\xdf" '
+ 'name="somechoice" required> Nainen</label></div>\n</div></p>',
)
def test_select_translated_text(self):
diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py
index 3ac28b1b30..cd3817d421 100644
--- a/tests/forms_tests/tests/test_input_formats.py
+++ b/tests/forms_tests/tests/test_input_formats.py
@@ -92,7 +92,10 @@ class LocalizedTimeTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
def test_localized_timeField_with_inputformat(self):
- "Localized TimeFields with manually specified input formats can accept those formats"
+ """
+ Localized TimeFields with manually specified input formats can accept
+ those formats.
+ """
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):
@@ -192,7 +195,10 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:00 PM")
def test_localized_timeField_with_inputformat(self):
- "Localized TimeFields with manually specified input formats can accept those formats"
+ """
+ Localized TimeFields with manually specified input formats can accept
+ those formats.
+ """
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):
@@ -288,7 +294,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
def test_localized_timeField_with_inputformat(self):
- "Localized TimeFields with manually specified input formats can accept those formats"
+ """
+ Localized TimeFields with manually specified input formats can accept
+ those formats.
+ """
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):
@@ -395,7 +404,10 @@ class LocalizedDateTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
def test_localized_dateField_with_inputformat(self):
- "Localized DateFields with manually specified input formats can accept those formats"
+ """
+ Localized DateFields with manually specified input formats can accept
+ those formats.
+ """
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):
@@ -497,7 +509,10 @@ class CustomDateInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
def test_localized_dateField_with_inputformat(self):
- "Localized DateFields with manually specified input formats can accept those formats"
+ """
+ Localized DateFields with manually specified input formats can accept
+ those formats.
+ """
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):
@@ -593,7 +608,10 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
def test_localized_dateField_with_inputformat(self):
- "Localized DateFields with manually specified input formats can accept those formats"
+ """
+ Localized DateFields with manually specified input formats can accept
+ those formats.
+ """
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):
@@ -702,7 +720,10 @@ class LocalizedDateTimeTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010 13:30:00")
def test_localized_dateTimeField_with_inputformat(self):
- "Localized DateTimeFields with manually specified input formats can accept those formats"
+ """
+ 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
)
@@ -810,7 +831,10 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:00 PM 21/12/2010")
def test_localized_dateTimeField_with_inputformat(self):
- "Localized DateTimeFields with manually specified input formats can accept those formats"
+ """
+ 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
)
@@ -862,7 +886,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:05")
def test_localized_dateTimeField(self):
- "Localized DateTimeFields in a non-localized environment act as unlocalized widgets"
+ """
+ Localized DateTimeFields in a non-localized environment act as
+ unlocalized widgets.
+ """
f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -910,7 +937,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:00")
def test_localized_dateTimeField_with_inputformat(self):
- "Localized DateTimeFields with manually specified input formats can accept those formats"
+ """
+ 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
)
diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py
index fe229599f4..5439e161c1 100644
--- a/tests/forms_tests/tests/test_media.py
+++ b/tests/forms_tests/tests/test_media.py
@@ -21,16 +21,18 @@ class FormsMediaTestCase(SimpleTestCase):
)
self.assertEqual(
str(m),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
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:
@@ -44,11 +46,12 @@ class FormsMediaTestCase(SimpleTestCase):
m3 = Media(Foo)
self.assertEqual(
str(m3),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# A widget can exist without a media definition
@@ -78,18 +81,20 @@ class FormsMediaTestCase(SimpleTestCase):
w1 = MyWidget1()
self.assertEqual(
str(w1.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Media objects can be interrogated by media type
self.assertEqual(
str(w1.media["css"]),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">',
)
self.assertEqual(
@@ -126,23 +131,25 @@ class FormsMediaTestCase(SimpleTestCase):
w3 = MyWidget3()
self.assertEqual(
str(w1.media + w2.media + w3.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# media addition hasn't affected the original objects
self.assertEqual(
str(w1.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Regression check for #12879: specifying the same CSS or JS file
@@ -234,13 +241,14 @@ class FormsMediaTestCase(SimpleTestCase):
w6 = MyWidget6()
self.assertEqual(
str(w6.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/other/path" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="/other/js"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/other/path" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/other/js"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
def test_media_inheritance(self):
@@ -248,7 +256,8 @@ class FormsMediaTestCase(SimpleTestCase):
# Inheritance of media
###############################################################
- # If a widget extends another but provides no media definition, it inherits the parent widget's media
+ # 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")}
@@ -264,14 +273,16 @@ class FormsMediaTestCase(SimpleTestCase):
w7 = MyWidget7()
self.assertEqual(
str(w7.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
- # If a widget extends another but defines media, it extends the parent widget's media by default
+ # 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")}
@@ -280,18 +291,19 @@ class FormsMediaTestCase(SimpleTestCase):
w8 = MyWidget8()
self.assertEqual(
str(w8.media),
- """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
def test_media_inheritance_from_property(self):
- # If a widget extends another but defines media, it extends the parents widget's media,
- # even if the parent defined media using a property.
+ # If a widget extends another but defines media, it extends the parents
+ # widget's media, even if the parent defined media using a property.
class MyWidget1(TextInput):
class Media:
css = {"all": ("path/to/css1", "/path/to/css2")}
@@ -331,14 +343,16 @@ class FormsMediaTestCase(SimpleTestCase):
w10 = MyWidget10()
self.assertEqual(
str(w10.media),
- """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="/path/to/js4"></script>""",
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/path/to/js4"></script>',
)
def test_media_inheritance_extends(self):
- # A widget can explicitly enable full media inheritance by specifying 'extend=True'
+ # 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")}
@@ -357,17 +371,19 @@ class FormsMediaTestCase(SimpleTestCase):
w11 = MyWidget11()
self.assertEqual(
str(w11.media),
- """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
def test_media_inheritance_single_type(self):
- # A widget can enable inheritance of one media type by specifying extend as a tuple
+ # 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")}
@@ -386,11 +402,12 @@ class FormsMediaTestCase(SimpleTestCase):
w12 = MyWidget12()
self.assertEqual(
str(w12.media),
- """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="/path/to/js4"></script>""",
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/path/to/js4"></script>',
)
def test_multi_media(self):
@@ -453,13 +470,14 @@ class FormsMediaTestCase(SimpleTestCase):
mymulti = MyMultiWidget()
self.assertEqual(
str(mymulti.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
def test_form_media(self):
@@ -494,13 +512,14 @@ class FormsMediaTestCase(SimpleTestCase):
f1 = MyForm()
self.assertEqual(
str(f1.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Form media can be combined to produce a single media definition.
@@ -510,13 +529,14 @@ class FormsMediaTestCase(SimpleTestCase):
f2 = AnotherForm()
self.assertEqual(
str(f1.media + f2.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Forms can also define media, following the same rules as widgets.
@@ -531,15 +551,17 @@ class FormsMediaTestCase(SimpleTestCase):
f3 = FormWithMedia()
self.assertEqual(
str(f3.media),
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/some/form/css" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="/some/form/javascript"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/some/form/css" type="text/css" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/some/form/javascript"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Media works in templates
@@ -547,15 +569,17 @@ class FormsMediaTestCase(SimpleTestCase):
Template("{{ form.media.js }}{{ form.media.css }}").render(
Context({"form": f3})
),
- """<script src="/path/to/js1"></script>
-<script src="/some/form/javascript"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>"""
- """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/some/form/css" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">""",
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/some/form/javascript"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>'
+ '<link href="http://media.example.com/static/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/some/form/css" type="text/css" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet">',
)
def test_html_safe(self):
diff --git a/tests/forms_tests/tests/test_utils.py b/tests/forms_tests/tests/test_utils.py
index c4a2e5c651..a921a924b6 100644
--- a/tests/forms_tests/tests/test_utils.py
+++ b/tests/forms_tests/tests/test_utils.py
@@ -134,7 +134,8 @@ class FormsUtilsTestCase(SimpleTestCase):
self.assertHTMLEqual(
str(ErrorList([example])),
'<ul class="errorlist"><li>Example of link: '
- "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>",
+ "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;"
+ "</li></ul>",
)
self.assertHTMLEqual(
str(ErrorList([mark_safe(example)])),
@@ -144,7 +145,8 @@ class FormsUtilsTestCase(SimpleTestCase):
self.assertHTMLEqual(
str(ErrorDict({"name": example})),
'<ul class="errorlist"><li>nameExample of link: '
- "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>",
+ "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;"
+ "</li></ul>",
)
self.assertHTMLEqual(
str(ErrorDict({"name": mark_safe(example)})),
diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py
index 6a3219c60c..a6ebabcc73 100644
--- a/tests/forms_tests/tests/tests.py
+++ b/tests/forms_tests/tests/tests.py
@@ -66,7 +66,10 @@ class TestTicket14567(TestCase):
"""
def test_empty_queryset_return(self):
- "If a model's ManyToManyField has blank=True and is saved with no data, a queryset is returned."
+ """
+ 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]}
@@ -82,7 +85,10 @@ class TestTicket14567(TestCase):
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)."
+ """
+ If a model's ForeignKey has blank=False and a default, no empty option
+ is created.
+ """
option = ChoiceOptionModel.objects.create(name="default")
choices = list(ChoiceFieldForm().fields["choice"].choices)
@@ -90,34 +96,52 @@ class ModelFormCallableModelDefault(TestCase):
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)"
+ """
+ The initial value for a callable default returning a queryset is the
+ pk.
+ """
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(),
- """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice" value="1" id="initial-id_choice"></p>
-<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int">
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int"></p>
-<p><label for="id_multi_choice">Multi choice:</label>
-<select multiple name="multi_choice" id="id_multi_choice" required>
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0"></p>
-<p><label for="id_multi_choice_int">Multi choice int:</label>
-<select multiple name="multi_choice_int" id="id_multi_choice_int" required>
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0"></p>""",
+ """
+ <p><label for="id_choice">Choice:</label>
+ <select name="choice" id="id_choice">
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice" value="1" id="initial-id_choice">
+ </p>
+ <p><label for="id_choice_int">Choice int:</label>
+ <select name="choice_int" id="id_choice_int">
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice_int" value="1"
+ id="initial-id_choice_int">
+ </p>
+ <p><label for="id_multi_choice">Multi choice:</label>
+ <select multiple name="multi_choice" id="id_multi_choice" required>
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice" value="1"
+ id="initial-id_multi_choice_0">
+ </p>
+ <p><label for="id_multi_choice_int">Multi choice int:</label>
+ <select multiple name="multi_choice_int" id="id_multi_choice_int" required>
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice_int" value="1"
+ id="initial-id_multi_choice_int_0">
+ </p>
+ """,
)
def test_initial_instance_value(self):
@@ -136,30 +160,47 @@ class ModelFormCallableModelDefault(TestCase):
),
}
).as_p(),
- """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice" value="2" id="initial-id_choice"></p>
-<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int">
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int"></p>
-<p><label for="id_multi_choice">Multi choice:</label>
-<select multiple name="multi_choice" id="id_multi_choice" required>
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3" selected>ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0">
-<input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1"></p>
-<p><label for="id_multi_choice_int">Multi choice int:</label>
-<select multiple name="multi_choice_int" id="id_multi_choice_int" required>
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3" selected>ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0">
-<input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1"></p>""",
+ """
+ <p><label for="id_choice">Choice:</label>
+ <select name="choice" id="id_choice">
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice" value="2" id="initial-id_choice">
+ </p>
+ <p><label for="id_choice_int">Choice int:</label>
+ <select name="choice_int" id="id_choice_int">
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice_int" value="2"
+ id="initial-id_choice_int">
+ </p>
+ <p><label for="id_multi_choice">Multi choice:</label>
+ <select multiple name="multi_choice" id="id_multi_choice" required>
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3" selected>ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice" value="2"
+ id="initial-id_multi_choice_0">
+ <input type="hidden" name="initial-multi_choice" value="3"
+ id="initial-id_multi_choice_1">
+ </p>
+ <p><label for="id_multi_choice_int">Multi choice int:</label>
+ <select multiple name="multi_choice_int" id="id_multi_choice_int" required>
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3" selected>ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice_int" value="2"
+ id="initial-id_multi_choice_int_0">
+ <input type="hidden" name="initial-multi_choice_int" value="3"
+ id="initial-id_multi_choice_int_1">
+ </p>
+ """,
)
@@ -194,9 +235,8 @@ class FormsModelTestCase(TestCase):
self.assertFalse(f.is_valid())
def test_formfield_initial(self):
- # Formfield initial values ########
- # If the model has default values for some fields, they are used as the formfield
- # initial values.
+ # If the model has default values for some fields, they are used as the
+ # formfield initial values.
class DefaultsForm(ModelForm):
class Meta:
model = Defaults
@@ -323,25 +363,32 @@ class EmptyLabelTestCase(TestCase):
f = EmptyCharLabelChoiceForm()
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required></p>
-<p><label for="id_choice">Choice:</label> <select id="id_choice" name="choice">
-<option value="" selected>No Preference</option>
-<option value="f">Foo</option>
-<option value="b">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text" required></p>
+ <p><label for="id_choice">Choice:</label>
+ <select id="id_choice" name="choice">
+ <option value="" selected>No Preference</option>
+ <option value="f">Foo</option>
+ <option value="b">Bar</option>
+ </select></p>
+ """,
)
def test_empty_field_char_none(self):
f = EmptyCharLabelNoneChoiceForm()
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required></p>
-<p><label for="id_choice_string_w_none">Choice string w none:</label>
-<select id="id_choice_string_w_none" name="choice_string_w_none">
-<option value="" selected>No Preference</option>
-<option value="f">Foo</option>
-<option value="b">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text" required></p>
+ <p><label for="id_choice_string_w_none">Choice string w none:</label>
+ <select id="id_choice_string_w_none" name="choice_string_w_none">
+ <option value="" selected>No Preference</option>
+ <option value="f">Foo</option>
+ <option value="b">Bar</option>
+ </select></p>
+ """,
)
def test_save_empty_label_forms(self):
@@ -367,13 +414,16 @@ class EmptyLabelTestCase(TestCase):
f = EmptyIntegerLabelChoiceForm()
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required></p>
-<p><label for="id_choice_integer">Choice integer:</label>
-<select id="id_choice_integer" name="choice_integer">
-<option value="" selected>No Preference</option>
-<option value="1">Foo</option>
-<option value="2">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text" required></p>
+ <p><label for="id_choice_integer">Choice integer:</label>
+ <select id="id_choice_integer" name="choice_integer">
+ <option value="" selected>No Preference</option>
+ <option value="1">Foo</option>
+ <option value="2">Bar</option>
+ </select></p>
+ """,
)
def test_get_display_value_on_none(self):
@@ -386,28 +436,36 @@ class EmptyLabelTestCase(TestCase):
f = EmptyIntegerLabelChoiceForm(instance=none_model)
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label>
-<input id="id_name" maxlength="10" name="name" type="text" value="none-test" required></p>
-<p><label for="id_choice_integer">Choice integer:</label>
-<select id="id_choice_integer" name="choice_integer">
-<option value="" selected>No Preference</option>
-<option value="1">Foo</option>
-<option value="2">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text"
+ value="none-test" required>
+ </p>
+ <p><label for="id_choice_integer">Choice integer:</label>
+ <select id="id_choice_integer" name="choice_integer">
+ <option value="" selected>No Preference</option>
+ <option value="1">Foo</option>
+ <option value="2">Bar</option>
+ </select></p>
+ """,
)
foo_model = ChoiceModel(name="foo-test", choice_integer=1)
f = EmptyIntegerLabelChoiceForm(instance=foo_model)
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label>
-<input id="id_name" maxlength="10" name="name" type="text" value="foo-test" required></p>
-<p><label for="id_choice_integer">Choice integer:</label>
-<select id="id_choice_integer" name="choice_integer">
-<option value="">No Preference</option>
-<option value="1" selected>Foo</option>
-<option value="2">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text"
+ value="foo-test" required>
+ </p>
+ <p><label for="id_choice_integer">Choice integer:</label>
+ <select id="id_choice_integer" name="choice_integer">
+ <option value="">No Preference</option>
+ <option value="1" selected>Foo</option>
+ <option value="2">Bar</option>
+ </select></p>
+ """,
)
diff --git a/tests/forms_tests/widget_tests/test_checkboxinput.py b/tests/forms_tests/widget_tests/test_checkboxinput.py
index 0f65e876df..c30aadbbb1 100644
--- a/tests/forms_tests/widget_tests/test_checkboxinput.py
+++ b/tests/forms_tests/widget_tests/test_checkboxinput.py
@@ -86,7 +86,8 @@ class CheckboxInputTest(WidgetTest):
"greeting",
"hello & goodbye",
html=(
- '<input checked type="checkbox" name="greeting" value="hello &amp; goodbye">'
+ '<input checked type="checkbox" name="greeting" '
+ 'value="hello &amp; goodbye">'
),
)
diff --git a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py
index 0e720022b2..3b8b9e2ff2 100644
--- a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py
+++ b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py
@@ -17,10 +17,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
["J"],
html="""
<div>
- <div><label><input checked type="checkbox" name="beatles" value="J"> John</label></div>
- <div><label><input type="checkbox" name="beatles" value="P"> Paul</label></div>
- <div><label><input type="checkbox" name="beatles" value="G"> George</label></div>
- <div><label><input type="checkbox" name="beatles" value="R"> Ringo</label></div>
+ <div><label><input checked type="checkbox" name="beatles" value="J"> John
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="P"> Paul
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="G"> George
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="R"> Ringo
+ </label></div>
</div>
""",
)
@@ -32,10 +36,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
["J", "P"],
html="""
<div>
- <div><label><input checked type="checkbox" name="beatles" value="J"> John</label></div>
- <div><label><input checked type="checkbox" name="beatles" value="P"> Paul</label></div>
- <div><label><input type="checkbox" name="beatles" value="G"> George</label></div>
- <div><label><input type="checkbox" name="beatles" value="R"> Ringo</label></div>
+ <div><label><input checked type="checkbox" name="beatles" value="J"> John
+ </label></div>
+ <div><label><input checked type="checkbox" name="beatles" value="P"> Paul
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="G"> George
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="R"> Ringo
+ </label></div>
</div>
""",
)
@@ -51,11 +59,16 @@ class CheckboxSelectMultipleTest(WidgetTest):
None,
html="""
<div>
- <div><label><input type="checkbox" name="beatles" value=""> Unknown</label></div>
- <div><label><input type="checkbox" name="beatles" value="J"> John</label></div>
- <div><label><input type="checkbox" name="beatles" value="P"> Paul</label></div>
- <div><label><input type="checkbox" name="beatles" value="G"> George</label></div>
- <div><label><input type="checkbox" name="beatles" value="R"> Ringo</label></div>
+ <div><label><input type="checkbox" name="beatles" value=""> Unknown
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="J"> John
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="P"> Paul
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="G"> George
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="R"> Ringo
+ </label></div>
</div>
""",
)
@@ -69,19 +82,24 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div id="media">
<div> <label for="media_0">
- <input type="checkbox" name="nestchoice" value="unknown" id="media_0"> Unknown</label></div>
+ <input type="checkbox" name="nestchoice" value="unknown" id="media_0"> Unknown
+ </label></div>
<div>
<label>Audio</label>
<div> <label for="media_1_0">
- <input checked type="checkbox" name="nestchoice" value="vinyl" id="media_1_0"> Vinyl</label></div>
+ <input checked type="checkbox" name="nestchoice" value="vinyl" id="media_1_0">
+ Vinyl</label></div>
<div> <label for="media_1_1">
- <input type="checkbox" name="nestchoice" value="cd" id="media_1_1"> CD</label></div>
+ <input type="checkbox" name="nestchoice" value="cd" id="media_1_1"> CD
+ </label></div>
</div><div>
<label>Video</label>
<div> <label for="media_2_0">
- <input type="checkbox" name="nestchoice" value="vhs" id="media_2_0"> VHS</label></div>
+ <input type="checkbox" name="nestchoice" value="vhs" id="media_2_0"> VHS
+ </label></div>
<div> <label for="media_2_1">
- <input type="checkbox" name="nestchoice" value="dvd" id="media_2_1" checked> DVD</label></div>
+ <input type="checkbox" name="nestchoice" value="dvd" id="media_2_1" checked> DVD
+ </label></div>
</div>
</div>
"""
@@ -101,15 +119,21 @@ class CheckboxSelectMultipleTest(WidgetTest):
)
html = """
<div>
- <div> <label><input type="checkbox" name="nestchoice" value="unknown"> Unknown</label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="unknown"> Unknown</label></div>
<div>
<label>Audio</label>
- <div> <label><input checked type="checkbox" name="nestchoice" value="vinyl"> Vinyl</label></div>
- <div> <label><input type="checkbox" name="nestchoice" value="cd"> CD</label></div>
+ <div> <label>
+ <input checked type="checkbox" name="nestchoice" value="vinyl"> Vinyl
+ </label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="cd"> CD</label></div>
</div><div>
<label>Video</label>
- <div> <label><input type="checkbox" name="nestchoice" value="vhs"> VHS</label></div>
- <div> <label><input type="checkbox" name="nestchoice" value="dvd"checked> DVD</label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="vhs"> VHS</label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="dvd"checked> DVD</label></div>
</div>
</div>
"""
@@ -128,11 +152,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div id="abc">
<div>
- <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
+ <label for="abc_0">
+ <input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
</div>
- <div><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
+ <div><label for="abc_1">
+ <input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
<div>
- <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
+ <label for="abc_2">
+ <input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
</div>
</div>
"""
@@ -154,11 +181,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div id="abc">
<div>
- <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
+ <label for="abc_0">
+ <input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
</div>
- <div><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
+ <div><label for="abc_1">
+ <input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
<div>
- <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
+ <label for="abc_2">
+ <input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
</div>
</div>
"""
@@ -174,8 +204,10 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div>
<div><label><input type="checkbox" name="numbers" value="1"> One</label></div>
- <div><label><input type="checkbox" name="numbers" value="1000"> One thousand</label></div>
- <div><label><input type="checkbox" name="numbers" value="1000000"> One million</label></div>
+ <div><label>
+ <input type="checkbox" name="numbers" value="1000"> One thousand</label></div>
+ <div><label>
+ <input type="checkbox" name="numbers" value="1000000"> One million</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "numbers", None, html=html)
@@ -186,8 +218,10 @@ class CheckboxSelectMultipleTest(WidgetTest):
]
html = """
<div>
- <div><label><input type="checkbox" name="times" value="00:00:00"> midnight</label></div>
- <div><label><input type="checkbox" name="times" value="12:00:00"> noon</label></div>
+ <div><label>
+ <input type="checkbox" name="times" value="00:00:00"> midnight</label></div>
+ <div><label>
+ <input type="checkbox" name="times" value="12:00:00"> noon</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "times", None, html=html)
diff --git a/tests/forms_tests/widget_tests/test_clearablefileinput.py b/tests/forms_tests/widget_tests/test_clearablefileinput.py
index 03fe34306b..630ff79486 100644
--- a/tests/forms_tests/widget_tests/test_clearablefileinput.py
+++ b/tests/forms_tests/widget_tests/test_clearablefileinput.py
@@ -56,12 +56,14 @@ class ClearableFileInputTest(WidgetTest):
StrangeFieldFile(),
html=(
"""
- Currently: <a href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en">
- something&lt;div onclick=&quot;alert(&#x27;oops&#x27;)&quot;&gt;.jpg</a>
- <input type="checkbox" name="my&lt;div&gt;file-clear" id="my&lt;div&gt;file-clear_id">
- <label for="my&lt;div&gt;file-clear_id">Clear</label><br>
- Change: <input type="file" name="my&lt;div&gt;file">
- """
+ Currently:
+ <a href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en">
+ something&lt;div onclick=&quot;alert(&#x27;oops&#x27;)&quot;&gt;.jpg</a>
+ <input type="checkbox" name="my&lt;div&gt;file-clear"
+ id="my&lt;div&gt;file-clear_id">
+ <label for="my&lt;div&gt;file-clear_id">Clear</label><br>
+ Change: <input type="file" name="my&lt;div&gt;file">
+ """
),
)
diff --git a/tests/forms_tests/widget_tests/test_datetimeinput.py b/tests/forms_tests/widget_tests/test_datetimeinput.py
index 5795660f30..e9bb77eb69 100644
--- a/tests/forms_tests/widget_tests/test_datetimeinput.py
+++ b/tests/forms_tests/widget_tests/test_datetimeinput.py
@@ -85,7 +85,10 @@ class DateTimeInputTest(WidgetTest):
self.widget,
"date",
d,
- html='<input type="text" name="date" value="2007-09-17 12:51:34">',
+ html=(
+ '<input type="text" name="date" '
+ 'value="2007-09-17 12:51:34">'
+ ),
)
with translation.override("es"):
self.check_html(
diff --git a/tests/forms_tests/widget_tests/test_multiplehiddeninput.py b/tests/forms_tests/widget_tests/test_multiplehiddeninput.py
index d0ad188929..9498b756e9 100644
--- a/tests/forms_tests/widget_tests/test_multiplehiddeninput.py
+++ b/tests/forms_tests/widget_tests/test_multiplehiddeninput.py
@@ -31,7 +31,10 @@ class MultipleHiddenInputTest(WidgetTest):
"email",
["test@example.com"],
attrs={"class": "fun"},
- html='<input type="hidden" name="email" value="test@example.com" class="fun">',
+ html=(
+ '<input type="hidden" name="email" value="test@example.com" '
+ 'class="fun">'
+ ),
)
def test_render_attrs_multiple(self):
@@ -41,7 +44,8 @@ class MultipleHiddenInputTest(WidgetTest):
["test@example.com", "foo@example.com"],
attrs={"class": "fun"},
html=(
- '<input type="hidden" name="email" value="test@example.com" class="fun">\n'
+ '<input type="hidden" name="email" value="test@example.com" '
+ 'class="fun">\n'
'<input type="hidden" name="email" value="foo@example.com" class="fun">'
),
)
@@ -53,15 +57,19 @@ class MultipleHiddenInputTest(WidgetTest):
widget,
"email",
["foo@example.com"],
- html='<input type="hidden" class="fun" value="foo@example.com" name="email">',
+ html=(
+ '<input type="hidden" class="fun" value="foo@example.com" name="email">'
+ ),
)
self.check_html(
widget,
"email",
["foo@example.com", "test@example.com"],
html=(
- '<input type="hidden" class="fun" value="foo@example.com" name="email">\n'
- '<input type="hidden" class="fun" value="test@example.com" name="email">'
+ '<input type="hidden" class="fun" value="foo@example.com" '
+ 'name="email">\n'
+ '<input type="hidden" class="fun" value="test@example.com" '
+ 'name="email">'
),
)
self.check_html(
@@ -69,7 +77,10 @@ class MultipleHiddenInputTest(WidgetTest):
"email",
["foo@example.com"],
attrs={"class": "special"},
- html='<input type="hidden" class="special" value="foo@example.com" name="email">',
+ html=(
+ '<input type="hidden" class="special" value="foo@example.com" '
+ 'name="email">'
+ ),
)
def test_render_empty(self):
diff --git a/tests/forms_tests/widget_tests/test_multiwidget.py b/tests/forms_tests/widget_tests/test_multiwidget.py
index c3f676e3f7..a89082c4a6 100644
--- a/tests/forms_tests/widget_tests/test_multiwidget.py
+++ b/tests/forms_tests/widget_tests/test_multiwidget.py
@@ -143,7 +143,8 @@ class MultiWidgetTest(WidgetTest):
attrs={"id": "foo"},
html=(
'<input id="foo_0" type="text" class="big" value="john" name="name_0">'
- '<input id="foo_1" type="text" class="small" value="lennon" name="name_1">'
+ '<input id="foo_1" type="text" class="small" value="lennon" '
+ 'name="name_1">'
),
)
@@ -161,7 +162,8 @@ class MultiWidgetTest(WidgetTest):
["john", "lennon"],
html=(
'<input id="bar_0" type="text" class="big" value="john" name="name_0">'
- '<input id="bar_1" type="text" class="small" value="lennon" name="name_1">'
+ '<input id="bar_1" type="text" class="small" value="lennon" '
+ 'name="name_1">'
),
)
diff --git a/tests/forms_tests/widget_tests/test_numberinput.py b/tests/forms_tests/widget_tests/test_numberinput.py
index a6427e6e37..15df02db4f 100644
--- a/tests/forms_tests/widget_tests/test_numberinput.py
+++ b/tests/forms_tests/widget_tests/test_numberinput.py
@@ -12,5 +12,6 @@ class NumberInputTests(WidgetTest):
widget,
"name",
"value",
- '<input type="number" name="name" value="value" max="12345" min="1234" step="9999">',
+ '<input type="number" name="name" value="value" max="12345" min="1234" '
+ 'step="9999">',
)
diff --git a/tests/forms_tests/widget_tests/test_radioselect.py b/tests/forms_tests/widget_tests/test_radioselect.py
index 89e4022f1c..5aa4c194de 100644
--- a/tests/forms_tests/widget_tests/test_radioselect.py
+++ b/tests/forms_tests/widget_tests/test_radioselect.py
@@ -18,9 +18,11 @@ class RadioSelectTest(WidgetTest):
html="""
<div>
<div><label><input type="radio" name="beatle" value=""> ------</label></div>
- <div><label><input checked type="radio" name="beatle" value="J"> John</label></div>
+ <div><label>
+ <input checked type="radio" name="beatle" value="J"> John</label></div>
<div><label><input type="radio" name="beatle" value="P"> Paul</label></div>
- <div><label><input type="radio" name="beatle" value="G"> George</label></div>
+ <div><label>
+ <input type="radio" name="beatle" value="G"> George</label></div>
<div><label><input type="radio" name="beatle" value="R"> Ringo</label></div>
</div>
""",
@@ -35,19 +37,28 @@ class RadioSelectTest(WidgetTest):
html = """
<div id="media">
<div>
- <label for="media_0"><input type="radio" name="nestchoice" value="unknown" id="media_0"> Unknown</label></div>
+ <label for="media_0">
+ <input type="radio" name="nestchoice" value="unknown" id="media_0"> Unknown
+ </label></div>
<div>
<label>Audio</label>
<div>
- <label for="media_1_0"><input type="radio" name="nestchoice" value="vinyl" id="media_1_0"> Vinyl</label></div>
- <div> <label for="media_1_1"><input type="radio" name="nestchoice" value="cd" id="media_1_1"> CD</label></div>
+ <label for="media_1_0">
+ <input type="radio" name="nestchoice" value="vinyl" id="media_1_0"> Vinyl
+ </label></div>
+ <div> <label for="media_1_1">
+ <input type="radio" name="nestchoice" value="cd" id="media_1_1"> CD
+ </label></div>
</div><div>
<label>Video</label>
<div>
- <label for="media_2_0"><input type="radio" name="nestchoice" value="vhs" id="media_2_0"> VHS</label></div>
+ <label for="media_2_0">
+ <input type="radio" name="nestchoice" value="vhs" id="media_2_0"> VHS
+ </label></div>
<div>
- <label for="media_2_1"><input type="radio" name="nestchoice" value="dvd" id="media_2_1" checked> DVD</label>
- </div>
+ <label for="media_2_1">
+ <input type="radio" name="nestchoice" value="dvd" id="media_2_1" checked> DVD
+ </label></div>
</div>
</div>
"""
@@ -68,11 +79,15 @@ class RadioSelectTest(WidgetTest):
html = """
<div id="foo">
<div>
- <label for="foo_0"><input checked type="radio" id="foo_0" value="J" name="beatle"> John</label>
+ <label for="foo_0">
+ <input checked type="radio" id="foo_0" value="J" name="beatle"> John</label>
</div>
- <div><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle"> Paul</label></div>
- <div><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle"> George</label></div>
- <div><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle"> Ringo</label></div>
+ <div><label for="foo_1">
+ <input type="radio" id="foo_1" value="P" name="beatle"> Paul</label></div>
+ <div><label for="foo_2">
+ <input type="radio" id="foo_2" value="G" name="beatle"> George</label></div>
+ <div><label for="foo_3">
+ <input type="radio" id="foo_3" value="R" name="beatle"> Ringo</label></div>
</div>
"""
self.check_html(widget, "beatle", "J", html=html)
@@ -85,11 +100,15 @@ class RadioSelectTest(WidgetTest):
html = """
<div id="bar">
<div>
- <label for="bar_0"><input checked type="radio" id="bar_0" value="J" name="beatle"> John</label>
+ <label for="bar_0">
+ <input checked type="radio" id="bar_0" value="J" name="beatle"> John</label>
</div>
- <div><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle"> Paul</label></div>
- <div><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle"> George</label></div>
- <div><label for="bar_3"><input type="radio" id="bar_3" value="R" name="beatle"> Ringo</label></div>
+ <div><label for="bar_1">
+ <input type="radio" id="bar_1" value="P" name="beatle"> Paul</label></div>
+ <div><label for="bar_2">
+ <input type="radio" id="bar_2" value="G" name="beatle"> George</label></div>
+ <div><label for="bar_3">
+ <input type="radio" id="bar_3" value="R" name="beatle"> Ringo</label></div>
</div>
"""
self.check_html(
@@ -107,10 +126,15 @@ class RadioSelectTest(WidgetTest):
"""
html = """
<div class="bar">
- <div><label><input checked type="radio" class="bar" value="J" name="beatle"> John</label></div>
- <div><label><input type="radio" class="bar" value="P" name="beatle"> Paul</label></div>
- <div><label><input type="radio" class="bar" value="G" name="beatle"> George</label></div>
- <div><label><input type="radio" class="bar" value="R" name="beatle"> Ringo</label></div>
+ <div><label>
+ <input checked type="radio" class="bar" value="J" name="beatle"> John</label>
+ </div>
+ <div><label>
+ <input type="radio" class="bar" value="P" name="beatle"> Paul</label></div>
+ <div><label>
+ <input type="radio" class="bar" value="G" name="beatle"> George</label></div>
+ <div><label>
+ <input type="radio" class="bar" value="R" name="beatle"> Ringo</label></div>
</div>
"""
self.check_html(
@@ -131,8 +155,10 @@ class RadioSelectTest(WidgetTest):
html = """
<div>
<div><label><input type="radio" name="number" value="1"> One</label></div>
- <div><label><input type="radio" name="number" value="1000"> One thousand</label></div>
- <div><label><input type="radio" name="number" value="1000000"> One million</label></div>
+ <div><label>
+ <input type="radio" name="number" value="1000"> One thousand</label></div>
+ <div><label>
+ <input type="radio" name="number" value="1000000"> One million</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "number", None, html=html)
@@ -143,8 +169,10 @@ class RadioSelectTest(WidgetTest):
]
html = """
<div>
- <div><label><input type="radio" name="time" value="00:00:00"> midnight</label></div>
- <div><label><input type="radio" name="time" value="12:00:00"> noon</label></div>
+ <div><label>
+ <input type="radio" name="time" value="00:00:00"> midnight</label></div>
+ <div><label>
+ <input type="radio" name="time" value="12:00:00"> noon</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "time", None, html=html)
@@ -158,11 +186,16 @@ class RadioSelectTest(WidgetTest):
["J"],
html="""
<div>
- <div><label><input type="radio" name="beatle_0" value=""> ------</label></div>
- <div><label><input checked type="radio" name="beatle_0" value="J"> John</label></div>
- <div><label><input type="radio" name="beatle_0" value="P"> Paul</label></div>
- <div><label><input type="radio" name="beatle_0" value="G"> George</label></div>
- <div><label><input type="radio" name="beatle_0" value="R"> Ringo</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value=""> ------</label></div>
+ <div><label>
+ <input checked type="radio" name="beatle_0" value="J"> John</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value="P"> Paul</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value="G"> George</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value="R"> Ringo</label></div>
</div>
""",
)
diff --git a/tests/forms_tests/widget_tests/test_select.py b/tests/forms_tests/widget_tests/test_select.py
index e78feeb110..8a40bd8b6a 100644
--- a/tests/forms_tests/widget_tests/test_select.py
+++ b/tests/forms_tests/widget_tests/test_select.py
@@ -227,12 +227,16 @@ class SelectTest(WidgetTest):
"email",
"ŠĐĆŽćžšđ",
html=(
- """<select name="email">
- <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected>
+ """
+ <select name="email">
+ <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"
+ selected>
\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111
</option>
- <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>
- </select>"""
+ <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111
+ </option>
+ </select>
+ """
),
)
diff --git a/tests/forms_tests/widget_tests/test_selectdatewidget.py b/tests/forms_tests/widget_tests/test_selectdatewidget.py
index de0c35cd5b..9192e4c1f1 100644
--- a/tests/forms_tests/widget_tests/test_selectdatewidget.py
+++ b/tests/forms_tests/widget_tests/test_selectdatewidget.py
@@ -520,7 +520,8 @@ class SelectDateWidgetTest(WidgetTest):
""",
)
- # Even with an invalid date, the widget should reflect the entered value (#17401).
+ # Even with an invalid date, the widget should reflect the entered
+ # value.
self.assertEqual(w.render("mydate", "2010-02-30").count("selected"), 3)
# Years before 1900 should work.
diff --git a/tests/forms_tests/widget_tests/test_textarea.py b/tests/forms_tests/widget_tests/test_textarea.py
index e92dfc51f4..e7695ab018 100644
--- a/tests/forms_tests/widget_tests/test_textarea.py
+++ b/tests/forms_tests/widget_tests/test_textarea.py
@@ -47,7 +47,8 @@ class TextareaTest(WidgetTest):
"msg",
'some "quoted" & ampersanded value',
html=(
- '<textarea rows="10" cols="40" name="msg">some &quot;quoted&quot; &amp; ampersanded value</textarea>'
+ '<textarea rows="10" cols="40" name="msg">'
+ "some &quot;quoted&quot; &amp; ampersanded value</textarea>"
),
)
@@ -57,6 +58,7 @@ class TextareaTest(WidgetTest):
"msg",
mark_safe("pre &quot;quoted&quot; value"),
html=(
- '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value</textarea>'
+ '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value'
+ "</textarea>"
),
)
diff --git a/tests/forms_tests/widget_tests/test_textinput.py b/tests/forms_tests/widget_tests/test_textinput.py
index 52ffabec65..efd0cfed4b 100644
--- a/tests/forms_tests/widget_tests/test_textinput.py
+++ b/tests/forms_tests/widget_tests/test_textinput.py
@@ -48,7 +48,10 @@ class TextInputTest(WidgetTest):
self.widget,
"email",
'some "quoted" & ampersanded value',
- html='<input type="text" name="email" value="some &quot;quoted&quot; &amp; ampersanded value">',
+ html=(
+ '<input type="text" name="email" '
+ 'value="some &quot;quoted&quot; &amp; ampersanded value">'
+ ),
)
def test_render_custom_attrs(self):
@@ -57,7 +60,9 @@ class TextInputTest(WidgetTest):
"email",
"test@example.com",
attrs={"class": "fun"},
- html='<input type="text" name="email" value="test@example.com" class="fun">',
+ html=(
+ '<input type="text" name="email" value="test@example.com" class="fun">'
+ ),
)
def test_render_unicode(self):
@@ -81,7 +86,9 @@ class TextInputTest(WidgetTest):
widget,
"email",
"foo@example.com",
- html='<input type="email" class="fun" value="foo@example.com" name="email">',
+ html=(
+ '<input type="email" class="fun" value="foo@example.com" name="email">'
+ ),
)
def test_attrs_precedence(self):
diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py
index 7bb9686b6b..c90cf41224 100644
--- a/tests/generic_inline_admin/tests.py
+++ b/tests/generic_inline_admin/tests.py
@@ -74,22 +74,19 @@ class GenericAdminViewTest(TestDataMixin, TestCase):
"""
A smoke test to ensure POST on edit_view works.
"""
+ prefix = "generic_inline_admin-media-content_type-object_id"
post_data = {
"name": "This Week in Django",
# inline data
- "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": "3",
- "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": "2",
- "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": "0",
- "generic_inline_admin-media-content_type-object_id-0-id": str(
- self.mp3_media_pk
- ),
- "generic_inline_admin-media-content_type-object_id-0-url": "http://example.com/podcast.mp3",
- "generic_inline_admin-media-content_type-object_id-1-id": str(
- self.png_media_pk
- ),
- "generic_inline_admin-media-content_type-object_id-1-url": "http://example.com/logo.png",
- "generic_inline_admin-media-content_type-object_id-2-id": "",
- "generic_inline_admin-media-content_type-object_id-2-url": "",
+ f"{prefix}-TOTAL_FORMS": "3",
+ f"{prefix}-INITIAL_FORMS": "2",
+ f"{prefix}-MAX_NUM_FORMS": "0",
+ f"{prefix}-0-id": str(self.mp3_media_pk),
+ f"{prefix}-0-url": "http://example.com/podcast.mp3",
+ f"{prefix}-1-id": str(self.png_media_pk),
+ f"{prefix}-1-url": "http://example.com/logo.png",
+ f"{prefix}-2-id": "",
+ f"{prefix}-2-url": "",
}
url = reverse(
"admin:generic_inline_admin_episode_change", args=(self.episode_pk,)
@@ -264,17 +261,16 @@ class GenericInlineAdminWithUniqueTogetherTest(TestDataMixin, TestCase):
def test_add(self):
category_id = Category.objects.create(name="male").pk
+ prefix = "generic_inline_admin-phonenumber-content_type-object_id"
post_data = {
"name": "John Doe",
# inline data
- "generic_inline_admin-phonenumber-content_type-object_id-TOTAL_FORMS": "1",
- "generic_inline_admin-phonenumber-content_type-object_id-INITIAL_FORMS": "0",
- "generic_inline_admin-phonenumber-content_type-object_id-MAX_NUM_FORMS": "0",
- "generic_inline_admin-phonenumber-content_type-object_id-0-id": "",
- "generic_inline_admin-phonenumber-content_type-object_id-0-phone_number": "555-555-5555",
- "generic_inline_admin-phonenumber-content_type-object_id-0-category": str(
- category_id
- ),
+ f"{prefix}-TOTAL_FORMS": "1",
+ f"{prefix}-INITIAL_FORMS": "0",
+ f"{prefix}-MAX_NUM_FORMS": "0",
+ f"{prefix}-0-id": "",
+ f"{prefix}-0-phone_number": "555-555-5555",
+ f"{prefix}-0-category": str(category_id),
}
response = self.client.get(reverse("admin:generic_inline_admin_contact_add"))
self.assertEqual(response.status_code, 200)
diff --git a/tests/generic_relations/test_forms.py b/tests/generic_relations/test_forms.py
index 78c146e22a..00df254745 100644
--- a/tests/generic_relations/test_forms.py
+++ b/tests/generic_relations/test_forms.py
@@ -32,26 +32,46 @@ class GenericInlineFormsetTests(TestCase):
formset = GenericFormSet()
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
-Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text"
-name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
-<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id"
-id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>""",
+ """
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-0-tag"
+ maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-0-id"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
+ """,
)
formset = GenericFormSet(instance=Animal())
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
-Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
-type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"><input type="hidden"
-name="generic_relations-taggeditem-content_type-object_id-0-id"
-id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>""",
+ """
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-0-tag"
+ maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-0-id"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
+ """,
)
platypus = Animal.objects.create(
common_name="Platypus",
@@ -63,32 +83,54 @@ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>""",
tagged_item_id = TaggedItem.objects.get(tag="shiny", object_id=platypus.id).id
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label>
-<input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text"
-name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
-<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id"
-value="%s" id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-1-tag">Tag:</label>
-<input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text"
-name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">
-<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id"
-id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>"""
+ """
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-0-tag"
+ value="shiny" maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-0-id"
+ value="%s"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-1-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-1-tag"
+ maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-1-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-1-id"
+ id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>
+ """
% tagged_item_id,
)
lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo")
formset = GenericFormSet(instance=lion, prefix="x")
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_x-0-tag">Tag:</label>
-<input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50"></p>
-<p><label for="id_x-0-DELETE">Delete:</label> <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE">
-<input type="hidden" name="x-0-id" id="id_x-0-id"></p>""",
+ """
+ <p><label for="id_x-0-tag">Tag:</label>
+ <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50"></p>
+ <p><label for="id_x-0-DELETE">Delete:</label>
+ <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE">
+ <input type="hidden" name="x-0-id" id="id_x-0-id"></p>
+ """,
)
def test_options(self):
@@ -108,7 +150,9 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>"""
self.assertEqual(len(formset.forms), 5)
self.assertHTMLEqual(
formset.forms[0].as_p(),
- '<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="%s" '
+ '<input type="hidden" '
+ 'name="generic_relations-taggeditem-content_type-object_id-0-id" '
+ 'value="%s" '
'id="id_generic_relations-taggeditem-content_type-object_id-0-id">'
% harmless.pk,
)
@@ -166,7 +210,10 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>"""
class BadModel(models.Model):
content_type = models.PositiveIntegerField()
- msg = "fk_name 'generic_relations.BadModel.content_type' is not a ForeignKey to ContentType"
+ msg = (
+ "fk_name 'generic_relations.BadModel.content_type' is not a ForeignKey to "
+ "ContentType"
+ )
with self.assertRaisesMessage(Exception, msg):
generic_inlineformset_factory(BadModel, TaggedItemForm)
diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py
index 6c6b0d1611..7c49e218dd 100644
--- a/tests/generic_relations/tests.py
+++ b/tests/generic_relations/tests.py
@@ -285,7 +285,10 @@ class GenericRelationsTests(TestCase):
def test_add_rejects_unsaved_objects(self):
t1 = TaggedItem(content_object=self.quartz, tag="shiny")
- msg = "<TaggedItem: shiny> instance isn't saved. Use bulk=False or save the object first."
+ msg = (
+ "<TaggedItem: shiny> instance isn't saved. Use bulk=False or save the "
+ "object first."
+ )
with self.assertRaisesMessage(ValueError, msg):
self.bacon.tags.add(t1)
@@ -443,7 +446,8 @@ class GenericRelationsTests(TestCase):
self.assertEqual(ValuableTaggedItem.objects.count(), 0)
def test_gfk_manager(self):
- # GenericForeignKey should not use the default manager (which may filter objects) #16048
+ # GenericForeignKey should not use the default manager (which may
+ # filter objects).
tailless = Gecko.objects.create(has_tail=False)
tag = TaggedItem.objects.create(content_object=tailless, tag="lizard")
self.assertEqual(tag.content_object, tailless)
diff --git a/tests/generic_views/test_dates.py b/tests/generic_views/test_dates.py
index a826d5498d..9edcf8f688 100644
--- a/tests/generic_views/test_dates.py
+++ b/tests/generic_views/test_dates.py
@@ -278,7 +278,8 @@ class YearArchiveViewTests(TestDataMixin, TestCase):
self.assertTemplateUsed(res, "generic_views/book_archive_year.html")
def test_year_view_custom_sort_order(self):
- # Zebras comes after Dreaming by name, but before on '-pubdate' which is the default sorting
+ # Zebras comes after Dreaming by name, but before on '-pubdate' which
+ # is the default sorting.
Book.objects.create(
name="Zebras for Dummies", pages=600, pubdate=datetime.date(2006, 9, 1)
)
@@ -797,12 +798,14 @@ class DayArchiveViewTests(TestDataMixin, TestCase):
)
res = self.client.get("/dates/booksignings/2008/apr/2/")
self.assertEqual(res.status_code, 200)
- # 2008-04-02T00:00:00+03:00 (beginning of day) > 2008-04-01T22:00:00+00:00 (book signing event date)
+ # 2008-04-02T00:00:00+03:00 (beginning of day) >
+ # 2008-04-01T22:00:00+00:00 (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/")
self.assertEqual(res.status_code, 200)
- # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 (book signing event date)
+ # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00
+ # (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/")
@@ -898,12 +901,14 @@ class DateDetailViewTests(TestDataMixin, TestCase):
)
res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk)
self.assertEqual(res.status_code, 200)
- # 2008-04-02T00:00:00+03:00 (beginning of day) > 2008-04-01T22:00:00+00:00 (book signing event date)
+ # 2008-04-02T00:00:00+03:00 (beginning of day) >
+ # 2008-04-01T22:00:00+00:00 (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk)
self.assertEqual(res.status_code, 200)
- # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 (book signing event date)
+ # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00
+ # (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk)
diff --git a/tests/get_object_or_404/tests.py b/tests/get_object_or_404/tests.py
index 4f2566a3a4..7f83c2c7a2 100644
--- a/tests/get_object_or_404/tests.py
+++ b/tests/get_object_or_404/tests.py
@@ -70,19 +70,28 @@ class GetObjectOr404Tests(TestCase):
def test_bad_class(self):
# Given an argument klass that is not a Model, Manager, or Queryset
# raises a helpful ValueError message
- msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'."
+ msg = (
+ "First argument to get_object_or_404() must be a Model, Manager, or "
+ "QuerySet, not 'str'."
+ )
with self.assertRaisesMessage(ValueError, msg):
get_object_or_404("Article", title__icontains="Run")
class CustomClass:
pass
- msg = "First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'CustomClass'."
+ msg = (
+ "First argument to get_object_or_404() must be a Model, Manager, or "
+ "QuerySet, not 'CustomClass'."
+ )
with self.assertRaisesMessage(ValueError, msg):
get_object_or_404(CustomClass, title__icontains="Run")
# Works for lists too
- msg = "First argument to get_list_or_404() must be a Model, Manager, or QuerySet, not 'list'."
+ msg = (
+ "First argument to get_list_or_404() must be a Model, Manager, or "
+ "QuerySet, not 'list'."
+ )
with self.assertRaisesMessage(ValueError, msg):
get_list_or_404([Article], title__icontains="Run")
diff --git a/tests/get_or_create/tests.py b/tests/get_or_create/tests.py
index a774e50bba..a2821187b2 100644
--- a/tests/get_or_create/tests.py
+++ b/tests/get_or_create/tests.py
@@ -678,7 +678,10 @@ class InvalidCreateArgumentsTests(TransactionTestCase):
)
def test_property_attribute_without_setter_kwargs(self):
- msg = "Cannot resolve keyword 'name_in_all_caps' into field. Choices are: id, name, tags"
+ msg = (
+ "Cannot resolve keyword 'name_in_all_caps' into field. Choices are: id, "
+ "name, tags"
+ )
with self.assertRaisesMessage(FieldError, msg):
Thing.objects.update_or_create(
name_in_all_caps="FRANK", defaults={"name": "Frank"}
diff --git a/tests/gis_tests/distapp/tests.py b/tests/gis_tests/distapp/tests.py
index a28a698a81..84b58b345b 100644
--- a/tests/gis_tests/distapp/tests.py
+++ b/tests/gis_tests/distapp/tests.py
@@ -128,9 +128,6 @@ class DistanceTest(TestCase):
@skipUnlessDBFeature("supports_distances_lookups")
def test_distance_lookups(self):
- """
- Test the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types.
- """
# Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole'
# (thus, Houston and Southside place will be excluded as tested in
# the `test02_dwithin` above).
@@ -316,7 +313,10 @@ class DistanceTest(TestCase):
def test_mysql_geodetic_distance_error(self):
if not connection.ops.mysql:
self.skipTest("This is a MySQL-specific test.")
- msg = "Only numeric values of degree units are allowed on geodetic distance queries."
+ msg = (
+ "Only numeric values of degree units are allowed on geodetic distance "
+ "queries."
+ )
with self.assertRaisesMessage(ValueError, msg):
AustraliaCity.objects.filter(
point__distance_lte=(Point(0, 0), D(m=100))
@@ -440,7 +440,10 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
lagrange = GEOSGeometry("POINT(-96.876369 29.905320)", 4326)
# Reference distances in feet and in meters. Got these values from
# using the provided raw SQL statements.
- # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140))
+ # SELECT ST_Distance(
+ # point,
+ # ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140)
+ # )
# FROM distapp_southtexascity;
m_distances = [
147075.069813,
@@ -453,7 +456,10 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
165337.758878,
139196.085105,
]
- # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278))
+ # SELECT ST_Distance(
+ # point,
+ # ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278)
+ # )
# FROM distapp_southtexascityft;
ft_distances = [
482528.79154625,
@@ -494,7 +500,10 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326)
# Reference query:
- # SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326))
+ # SELECT ST_distance_sphere(
+ # point,
+ # ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326)
+ # )
# FROM distapp_australiacity ORDER BY name;
distances = [
1120954.92533513,
@@ -523,9 +532,16 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
tol = 2 if connection.ops.oracle else 4
# Got the reference distances using the raw SQL statements:
- # SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326),
- # 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
- # SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326))
+ # SELECT ST_distance_spheroid(
+ # point,
+ # ST_GeomFromText('POINT(151.231341 -33.952685)', 4326),
+ # 'SPHEROID["WGS 84",6378137.0,298.257223563]'
+ # )
+ # FROM distapp_australiacity WHERE (NOT (id = 11));
+ # SELECT ST_distance_sphere(
+ # point,
+ # ST_GeomFromText('POINT(151.231341 -33.952685)', 4326)
+ # )
# FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere
spheroid_distances = [
60504.0628957201,
@@ -688,8 +704,10 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
Test the `Length` function.
"""
# Reference query (should use `length_spheroid`).
- # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
- # AUTHORITY["EPSG","7030"]]');
+ # SELECT ST_length_spheroid(
+ # ST_GeomFromText('<wkt>', 4326)
+ # 'SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]]'
+ # );
len_m1 = 473504.769553813
len_m2 = 4617.668
@@ -723,7 +741,8 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
Test the `Perimeter` function.
"""
# Reference query:
- # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
+ # SELECT ST_Perimeter(distapp_southtexaszipcode.poly)
+ # FROM distapp_southtexaszipcode;
perim_m = [
18404.3550889361,
15627.2108551001,
diff --git a/tests/gis_tests/gdal_tests/test_ds.py b/tests/gis_tests/gdal_tests/test_ds.py
index 1ba72e67d0..fd58644b25 100644
--- a/tests/gis_tests/gdal_tests/test_ds.py
+++ b/tests/gis_tests/gdal_tests/test_ds.py
@@ -118,7 +118,7 @@ class DataSourceTest(SimpleTestCase):
# Loading up the data source
ds = DataSource(source.ds)
- # Making sure the layer count is what's expected (only 1 layer in a SHP file)
+ # The layer count is what's expected (only 1 layer in a SHP file).
self.assertEqual(1, len(ds))
# Making sure GetName works
@@ -191,8 +191,9 @@ class DataSourceTest(SimpleTestCase):
for i, fid in enumerate(source.fids):
feat = layer[fid]
self.assertEqual(fid, feat.fid)
- # Maybe this should be in the test below, but we might as well test
- # the feature values here while in this loop.
+ # Maybe this should be in the test below, but we might
+ # as well test the feature values here while in this
+ # loop.
for fld_name, fld_value in source.field_values.items():
self.assertEqual(fld_value[i], feat.get(fld_name))
diff --git a/tests/gis_tests/gdal_tests/test_geom.py b/tests/gis_tests/gdal_tests/test_geom.py
index cb4588450c..175ec3c7da 100644
--- a/tests/gis_tests/gdal_tests/test_geom.py
+++ b/tests/gis_tests/gdal_tests/test_geom.py
@@ -618,7 +618,8 @@ class OGRGeomTest(SimpleTestCase, TestDataMixin):
self.assertEqual(
OGRGeometry("POINT(0 0)"),
OGRGeometry.from_gml(
- '<gml:Point gml:id="p21" srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
+ '<gml:Point gml:id="p21" '
+ 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
' <gml:pos srsDimension="2">0 0</gml:pos>'
"</gml:Point>"
),
diff --git a/tests/gis_tests/gdal_tests/test_raster.py b/tests/gis_tests/gdal_tests/test_raster.py
index 795fdd079f..fd59b57313 100644
--- a/tests/gis_tests/gdal_tests/test_raster.py
+++ b/tests/gis_tests/gdal_tests/test_raster.py
@@ -384,11 +384,16 @@ class GDALRasterTests(SimpleTestCase):
]:
self.assertIn(line, info_lines)
for line in [
- r'Upper Left \( 511700.468, 435103.377\) \( 82d51\'46.1\d"W, 27d55\' 1.5\d"N\)',
- r'Lower Left \( 511700.468, 417703.377\) \( 82d51\'52.0\d"W, 27d45\'37.5\d"N\)',
- r'Upper Right \( 528000.468, 435103.377\) \( 82d41\'48.8\d"W, 27d54\'56.3\d"N\)',
- r'Lower Right \( 528000.468, 417703.377\) \( 82d41\'55.5\d"W, 27d45\'32.2\d"N\)',
- r'Center \( 519850.468, 426403.377\) \( 82d46\'50.6\d"W, 27d50\'16.9\d"N\)',
+ r"Upper Left \( 511700.468, 435103.377\) "
+ r'\( 82d51\'46.1\d"W, 27d55\' 1.5\d"N\)',
+ r"Lower Left \( 511700.468, 417703.377\) "
+ r'\( 82d51\'52.0\d"W, 27d45\'37.5\d"N\)',
+ r"Upper Right \( 528000.468, 435103.377\) "
+ r'\( 82d41\'48.8\d"W, 27d54\'56.3\d"N\)',
+ r"Lower Right \( 528000.468, 417703.377\) "
+ r'\( 82d41\'55.5\d"W, 27d45\'32.2\d"N\)',
+ r"Center \( 519850.468, 426403.377\) "
+ r'\( 82d46\'50.6\d"W, 27d50\'16.9\d"N\)',
]:
self.assertRegex(infos, line)
# CRS (skip the name because string depends on the GDAL/Proj versions).
diff --git a/tests/gis_tests/gdal_tests/test_srs.py b/tests/gis_tests/gdal_tests/test_srs.py
index e257c59245..dcb5f056e8 100644
--- a/tests/gis_tests/gdal_tests/test_srs.py
+++ b/tests/gis_tests/gdal_tests/test_srs.py
@@ -45,7 +45,8 @@ srlist = (
),
),
TestSRS(
- 'PROJCS["NAD83 / Texas South Central",GEOGCS["NAD83",DATUM["North_American_Datum_1983",'
+ 'PROJCS["NAD83 / Texas South Central",'
+ 'GEOGCS["NAD83",DATUM["North_American_Datum_1983",'
'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],'
'AUTHORITY["EPSG","6269"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],'
'UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],'
@@ -78,13 +79,18 @@ srlist = (
TestSRS(
'PROJCS["NAD83 / Texas South Central (ftUS)",'
'GEOGCS["NAD83",DATUM["North_American_Datum_1983",'
- 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],AUTHORITY["EPSG","6269"]],'
+ 'SPHEROID["GRS 1980",6378137,298.257222101,AUTHORITY["EPSG","7019"]],'
+ 'AUTHORITY["EPSG","6269"]],'
'PRIMEM["Greenwich",0],'
'UNIT["Degree",0.0174532925199433]],PROJECTION["Lambert_Conformal_Conic_2SP"],'
- 'PARAMETER["false_easting",1968500],PARAMETER["false_northing",13123333.3333333],'
- 'PARAMETER["central_meridian",-99],PARAMETER["standard_parallel_1",28.3833333333333],'
- 'PARAMETER["standard_parallel_2",30.2833333333333],PARAMETER["latitude_of_origin",27.8333333333333],'
- 'UNIT["US survey foot",0.304800609601219],AXIS["Easting",EAST],AXIS["Northing",NORTH]]',
+ 'PARAMETER["false_easting",1968500],'
+ 'PARAMETER["false_northing",13123333.3333333],'
+ 'PARAMETER["central_meridian",-99],'
+ 'PARAMETER["standard_parallel_1",28.3833333333333],'
+ 'PARAMETER["standard_parallel_2",30.2833333333333],'
+ 'PARAMETER["latitude_of_origin",27.8333333333333],'
+ 'UNIT["US survey foot",0.304800609601219],AXIS["Easting",EAST],'
+ 'AXIS["Northing",NORTH]]',
epsg=None,
projected=True,
geographic=False,
@@ -122,7 +128,8 @@ well_known = (
TestSRS(
'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,'
'AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],'
- 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,'
+ 'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],'
+ 'UNIT["degree",0.01745329251994328,'
'AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]',
wk="WGS84",
name="WGS 84",
@@ -324,13 +331,16 @@ class SpatialRefTest(SimpleTestCase):
wkt = (
'PROJCS["DHDN / Soldner 39 Langschoß",'
'GEOGCS["DHDN",DATUM["Deutsches_Hauptdreiecksnetz",'
- 'SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],AUTHORITY["EPSG","6314"]],'
+ 'SPHEROID["Bessel 1841",6377397.155,299.1528128,AUTHORITY["EPSG","7004"]],'
+ 'AUTHORITY["EPSG","6314"]],'
'PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],'
'UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],'
'AUTHORITY["EPSG","4314"]],PROJECTION["Cassini_Soldner"],'
- 'PARAMETER["latitude_of_origin",50.66738711],PARAMETER["central_meridian",6.28935703],'
+ 'PARAMETER["latitude_of_origin",50.66738711],'
+ 'PARAMETER["central_meridian",6.28935703],'
'PARAMETER["false_easting",0],PARAMETER["false_northing",0],'
- 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",NORTH],AXIS["Y",EAST],AUTHORITY["mj10777.de","187939"]]'
+ 'UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",NORTH],AXIS["Y",EAST],'
+ 'AUTHORITY["mj10777.de","187939"]]'
)
srs = SpatialReference(wkt)
srs_list = [srs, srs.clone()]
diff --git a/tests/gis_tests/geoadmin_deprecated/tests.py b/tests/gis_tests/geoadmin_deprecated/tests.py
index a2049827a1..dd3e3af069 100644
--- a/tests/gis_tests/geoadmin_deprecated/tests.py
+++ b/tests/gis_tests/geoadmin_deprecated/tests.py
@@ -16,15 +16,18 @@ class GeoAdminTest(SimpleTestCase):
self.assertTrue(any(geoadmin.openlayers_url in js for js in admin_js))
def test_olmap_OSM_rendering(self):
- delete_all_btn = """<a href="javascript:geodjango_point.clearFeatures()">Delete all Features</a>"""
-
+ delete_all_btn = (
+ '<a href="javascript:geodjango_point.clearFeatures()">Delete all Features'
+ "</a>"
+ )
original_geoadmin = site._registry[City]
params = original_geoadmin.get_map_widget(City._meta.get_field("point")).params
result = original_geoadmin.get_map_widget(
City._meta.get_field("point")
)().render("point", Point(-79.460734, 40.18476), params)
self.assertIn(
- """geodjango_point.layers.base = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");""",
+ "geodjango_point.layers.base = "
+ 'new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");',
result,
)
@@ -50,8 +53,9 @@ class GeoAdminTest(SimpleTestCase):
"point", Point(-79.460734, 40.18476)
)
self.assertIn(
- """geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", """
- """"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic', format: 'image/jpeg'});""",
+ 'geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", '
+ '"http://vmap0.tiles.osgeo.org/wms/vmap0", '
+ "{layers: 'basic', format: 'image/jpeg'});",
result,
)
diff --git a/tests/gis_tests/geoapp/test_functions.py b/tests/gis_tests/geoapp/test_functions.py
index 076e51b7a2..b632d2cf61 100644
--- a/tests/gis_tests/geoapp/test_functions.py
+++ b/tests/gis_tests/geoapp/test_functions.py
@@ -36,12 +36,14 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
'{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}'
)
victoria_json = json.loads(
- '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
+ '{"type":"Point",'
+ '"bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
'"coordinates":[-123.305196,48.462611]}'
)
chicago_json = json.loads(
'{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},'
- '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}'
+ '"bbox":[-87.65018,41.85039,-87.65018,41.85039],'
+ '"coordinates":[-87.65018,41.85039]}'
)
if "crs" in connection.features.unsupported_geojson_options:
del houston_json["crs"]
@@ -131,8 +133,10 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
if connection.ops.oracle:
# No precision parameter for Oracle :-/
gml_regex = re.compile(
- r'^<gml:Point srsName="EPSG:4326" xmlns:gml="http://www.opengis.net/gml">'
- r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ '
+ r'^<gml:Point srsName="EPSG:4326" '
+ r'xmlns:gml="http://www.opengis.net/gml">'
+ r'<gml:coordinates decimal="\." cs="," ts=" ">'
+ r"-104.60925\d+,38.25500\d+ "
r"</gml:coordinates></gml:Point>"
)
else:
@@ -588,7 +592,8 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
# to pass into GEOS `equals_exact`.
tol = 0.000000001
- # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country"
+ # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1))
+ # FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr("MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))")
self.assertTrue(
@@ -600,7 +605,8 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
)
)
- # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country"
+ # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23))
+ # FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr(
"MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))"
@@ -614,10 +620,12 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
)
)
- # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country"
+ # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23))
+ # FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr(
- "MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))"
+ "MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,"
+ "12.45 43.87,12.4 43.87)))"
)
self.assertTrue(
ref.equals_exact(
diff --git a/tests/gis_tests/geoapp/tests.py b/tests/gis_tests/geoapp/tests.py
index 33d209bcdb..6acf6e150b 100644
--- a/tests/gis_tests/geoapp/tests.py
+++ b/tests/gis_tests/geoapp/tests.py
@@ -301,8 +301,8 @@ class GeoLookupTest(TestCase):
ks = State.objects.get(poly__contains=lawrence.point)
self.assertEqual("Kansas", ks.name)
- # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas)
- # are not contained in Texas or New Zealand.
+ # Pueblo and Oklahoma City (even though OK City is within the bounding
+ # box of Texas) are not contained in Texas or New Zealand.
self.assertEqual(
len(Country.objects.filter(mpoly__contains=pueblo.point)), 0
) # Query w/GEOSGeometry object
@@ -597,8 +597,10 @@ class GeoQuerySetTest(TestCase):
Testing the `Extent` aggregate.
"""
# Reference query:
- # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');`
- # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
+ # SELECT ST_extent(point)
+ # FROM geoapp_city
+ # WHERE (name='Houston' or name='Dallas');`
+ # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
expected = (
-96.8016128540039,
29.7633724212646,
diff --git a/tests/gis_tests/geogapp/tests.py b/tests/gis_tests/geogapp/tests.py
index 819b86545f..ae12d26706 100644
--- a/tests/gis_tests/geogapp/tests.py
+++ b/tests/gis_tests/geogapp/tests.py
@@ -39,7 +39,10 @@ class GeographyTest(TestCase):
self.assertEqual(["Dallas", "Houston", "Oklahoma City"], cities)
def test04_invalid_operators_functions(self):
- "Ensuring exceptions are raised for operators & functions invalid on geography fields."
+ """
+ Exceptions are raised for operators & functions invalid on geography
+ fields.
+ """
if not connection.ops.postgis:
self.skipTest("This is a PostGIS-specific test.")
# Only a subset of the geometry functions & operator are available
diff --git a/tests/gis_tests/geos_tests/test_geos.py b/tests/gis_tests/geos_tests/test_geos.py
index 3cdc5d5451..e92c0c65ba 100644
--- a/tests/gis_tests/geos_tests/test_geos.py
+++ b/tests/gis_tests/geos_tests/test_geos.py
@@ -800,7 +800,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
buf_ring = buf[j]
self.assertEqual(len(exp_ring), len(buf_ring))
for k in range(len(exp_ring)):
- # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
+ # Asserting the X, Y of each point are almost equal (due to
+ # floating point imprecision).
self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
@@ -1489,7 +1490,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(
GEOSGeometry("POINT(0 0)"),
GEOSGeometry.from_gml(
- '<gml:Point gml:id="p21" srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
+ '<gml:Point gml:id="p21" '
+ 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
' <gml:pos srsDimension="2">0 0</gml:pos>'
"</gml:Point>"
),
diff --git a/tests/gis_tests/inspectapp/tests.py b/tests/gis_tests/inspectapp/tests.py
index a47a8dcf2b..5017a489d7 100644
--- a/tests/gis_tests/inspectapp/tests.py
+++ b/tests/gis_tests/inspectapp/tests.py
@@ -135,7 +135,8 @@ class OGRInspectTest(SimpleTestCase):
self.assertTrue(
model_def.startswith(
- "# This is an auto-generated Django model module created by ogrinspect.\n"
+ "# This is an auto-generated Django model module created by "
+ "ogrinspect.\n"
"from django.contrib.gis.db import models\n"
"\n"
"\n"
@@ -143,7 +144,8 @@ class OGRInspectTest(SimpleTestCase):
)
)
- # The ordering of model fields might vary depending on several factors (version of GDAL, etc.)
+ # The ordering of model fields might vary depending on several factors
+ # (version of GDAL, etc.).
if connection.vendor == "sqlite":
# SpatiaLite introspection is somewhat lacking (#29461).
self.assertIn(" f_decimal = models.CharField(max_length=0)", model_def)
diff --git a/tests/gis_tests/layermap/models.py b/tests/gis_tests/layermap/models.py
index 953332539a..02a8914f02 100644
--- a/tests/gis_tests/layermap/models.py
+++ b/tests/gis_tests/layermap/models.py
@@ -92,7 +92,8 @@ class DoesNotAllowNulls(models.Model):
# Mapping dictionaries for the models above.
co_mapping = {
"name": "Name",
- # ForeignKey's use another mapping dictionary for the _related_ Model (State in this case).
+ # ForeignKey's use another mapping dictionary for the _related_ Model
+ # (State in this case).
"state": {"name": "State"},
"mpoly": "MULTIPOLYGON", # Will convert POLYGON features into MULTIPOLYGONS.
}
diff --git a/tests/gis_tests/layermap/tests.py b/tests/gis_tests/layermap/tests.py
index a7aafcc60c..89e430d2c9 100644
--- a/tests/gis_tests/layermap/tests.py
+++ b/tests/gis_tests/layermap/tests.py
@@ -151,7 +151,10 @@ class LayerMapTest(TestCase):
self.assertEqual(n, qs.count())
def test_layermap_unique_multigeometry_fk(self):
- "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings."
+ """
+ The `unique`, and `transform`, geometry collection conversion, and
+ ForeignKey mappings.
+ """
# All the following should work.
# Telling LayerMapping that we want no transformations performed on the data.
diff --git a/tests/gis_tests/relatedapp/tests.py b/tests/gis_tests/relatedapp/tests.py
index 48f9c12b69..d93fe3b76b 100644
--- a/tests/gis_tests/relatedapp/tests.py
+++ b/tests/gis_tests/relatedapp/tests.py
@@ -104,7 +104,9 @@ class RelatedGeoModelTest(TestCase):
self.assertEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3})
def test05_select_related_fk_to_subclass(self):
- "Testing that calling select_related on a query over a model with an FK to a model subclass works"
+ """
+ select_related on a query over a model with an FK to a model subclass.
+ """
# Regression test for #9752.
list(DirectoryEntry.objects.all().select_related())
@@ -282,9 +284,13 @@ class RelatedGeoModelTest(TestCase):
Testing the `Collect` aggregate.
"""
# Reference query:
- # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
- # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
- # WHERE "relatedapp_city"."state" = 'TX';
+ # SELECT AsText(ST_Collect("relatedapp_location"."point"))
+ # FROM "relatedapp_city"
+ # LEFT OUTER JOIN
+ # "relatedapp_location" ON (
+ # "relatedapp_city"."location_id" = "relatedapp_location"."id"
+ # )
+ # WHERE "relatedapp_city"."state" = 'TX';
ref_geom = GEOSGeometry(
"MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,"
"-95.363151 29.763374,-96.801611 32.782057)"
@@ -299,7 +305,9 @@ class RelatedGeoModelTest(TestCase):
self.assertTrue(ref_geom.equals(coll))
def test15_invalid_select_related(self):
- "Testing doing select_related on the related name manager of a unique FK. See #13934."
+ """
+ select_related on the related name manager of a unique FK.
+ """
qs = Article.objects.select_related("author__article")
# This triggers TypeError when `get_default_columns` has no `local_only`
# keyword. The TypeError is swallowed if QuerySet is actually
diff --git a/tests/gis_tests/test_geoforms.py b/tests/gis_tests/test_geoforms.py
index 949ad46a41..cef88d7115 100644
--- a/tests/gis_tests/test_geoforms.py
+++ b/tests/gis_tests/test_geoforms.py
@@ -96,7 +96,8 @@ class GeometryFieldTest(SimpleTestCase):
"MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))",
"BLAH(0 0, 1 1)",
'{"type": "FeatureCollection", "features": ['
- '{"geometry": {"type": "Point", "coordinates": [508375, 148905]}, "type": "Feature"}]}',
+ '{"geometry": {"type": "Point", "coordinates": [508375, 148905]}, '
+ '"type": "Feature"}]}',
]
fld = forms.GeometryField()
# to_python returns the same GEOSGeometry for a WKT
diff --git a/tests/gis_tests/test_spatialrefsys.py b/tests/gis_tests/test_spatialrefsys.py
index e23ea2ba2a..7151e8d3d6 100644
--- a/tests/gis_tests/test_spatialrefsys.py
+++ b/tests/gis_tests/test_spatialrefsys.py
@@ -12,7 +12,10 @@ test_srs = (
# Only the beginning, because there are differences depending on installed libs
"srtext": 'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84"',
# +ellps=WGS84 has been removed in the 4326 proj string in proj-4.8
- "proj_re": r"\+proj=longlat (\+ellps=WGS84 )?(\+datum=WGS84 |\+towgs84=0,0,0,0,0,0,0 )\+no_defs ?",
+ "proj_re": (
+ r"\+proj=longlat (\+ellps=WGS84 )?(\+datum=WGS84 |\+towgs84=0,0,0,0,0,0,0 )"
+ r"\+no_defs ?"
+ ),
"spheroid": "WGS 84",
"name": "WGS 84",
"geographic": True,
@@ -46,9 +49,12 @@ test_srs = (
'PROJCS["NAD83 / Texas South Central",GEOGCS["NAD83",'
'DATUM["North_American_Datum_1983",SPHEROID["GRS 1980"'
),
- "proj_re": r"\+proj=lcc (\+lat_1=30.28333333333333? |\+lat_2=28.38333333333333? |\+lat_0=27.83333333333333? |"
- r"\+lon_0=-99 ){4}\+x_0=600000 \+y_0=4000000 (\+ellps=GRS80 )?"
- r"(\+datum=NAD83 |\+towgs84=0,0,0,0,0,0,0 )?\+units=m \+no_defs ?",
+ "proj_re": (
+ r"\+proj=lcc (\+lat_1=30.28333333333333? |\+lat_2=28.38333333333333? "
+ r"|\+lat_0=27.83333333333333? |"
+ r"\+lon_0=-99 ){4}\+x_0=600000 \+y_0=4000000 (\+ellps=GRS80 )?"
+ r"(\+datum=NAD83 |\+towgs84=0,0,0,0,0,0,0 )?\+units=m \+no_defs ?"
+ ),
"spheroid": "GRS 1980",
"name": "NAD83 / Texas South Central",
"geographic": False,
diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py
index c987b1d472..1e2da4672b 100644
--- a/tests/handlers/tests.py
+++ b/tests/handlers/tests.py
@@ -44,11 +44,14 @@ class HandlerTests(SimpleTestCase):
b"want=caf%C3%A9", # This is the proper way to encode 'café'
b"want=caf\xc3\xa9", # UA forgot to quote bytes
b"want=caf%E9", # UA quoted, but not in UTF-8
- b"want=caf\xe9", # UA forgot to convert Latin-1 to UTF-8 and to quote (typical of MSIE)
+ # UA forgot to convert Latin-1 to UTF-8 and to quote (typical of
+ # MSIE).
+ b"want=caf\xe9",
]
got = []
for raw_query_string in raw_query_strings:
- # Simulate http.server.BaseHTTPRequestHandler.parse_request handling of raw request
+ # Simulate http.server.BaseHTTPRequestHandler.parse_request
+ # handling of raw request.
environ["QUERY_STRING"] = str(raw_query_string, "iso-8859-1")
request = WSGIRequest(environ)
got.append(request.GET["want"])
@@ -219,7 +222,10 @@ class HandlerRequestTests(SimpleTestCase):
self.client.get("/")
def test_no_response(self):
- msg = "The view %s didn't return an HttpResponse object. It returned None instead."
+ msg = (
+ "The view %s didn't return an HttpResponse object. It returned None "
+ "instead."
+ )
tests = (
("/no_response_fbv/", "handlers.views.no_response"),
("/no_response_cbv/", "handlers.views.NoResponse.__call__"),
diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py
index ef1dd8e1e7..f68524a484 100644
--- a/tests/httpwrappers/tests.py
+++ b/tests/httpwrappers/tests.py
@@ -532,7 +532,10 @@ class HttpResponseSubclassesTests(SimpleTestCase):
def test_redirect_repr(self):
response = HttpResponseRedirect("/redirected/")
- expected = '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/redirected/">'
+ expected = (
+ '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", '
+ 'url="/redirected/">'
+ )
self.assertEqual(repr(response), expected)
def test_invalid_redirect_repr(self):
@@ -545,7 +548,10 @@ class HttpResponseSubclassesTests(SimpleTestCase):
DisallowedRedirect, "Unsafe redirect to URL with protocol 'ssh'"
):
HttpResponseRedirect.__init__(response, "ssh://foo")
- expected = '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="ssh://foo">'
+ expected = (
+ '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", '
+ 'url="ssh://foo">'
+ )
self.assertEqual(repr(response), expected)
def test_not_modified(self):
diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py
index 3993b07ab5..0925238008 100644
--- a/tests/humanize_tests/tests.py
+++ b/tests/humanize_tests/tests.py
@@ -520,7 +520,8 @@ class HumanizeTests(SimpleTestCase):
orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime
try:
- # Choose a language with different naturaltime-past/naturaltime-future translations
+ # Choose a language with different
+ # naturaltime-past/naturaltime-future translations.
with translation.override("cs"):
self.humanize_tester(test_list, result_list, "naturaltime")
finally:
diff --git a/tests/i18n/patterns/tests.py b/tests/i18n/patterns/tests.py
index eeb41e7d27..db04e9a1a4 100644
--- a/tests/i18n/patterns/tests.py
+++ b/tests/i18n/patterns/tests.py
@@ -436,9 +436,13 @@ class URLTagTests(URLTestCaseBase):
def test_args(self):
tpl = Template(
- """{% load i18n %}
- {% language 'nl' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
- {% language 'pt-br' %}{% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}"""
+ """
+ {% load i18n %}
+ {% language 'nl' %}
+ {% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
+ {% language 'pt-br' %}
+ {% url 'no-prefix-translated-slug' 'apo' %}{% endlanguage %}
+ """
)
self.assertEqual(
tpl.render(Context({})).strip().split(),
@@ -447,9 +451,13 @@ class URLTagTests(URLTestCaseBase):
def test_kwargs(self):
tpl = Template(
- """{% load i18n %}
- {% language 'nl' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
- {% language 'pt-br' %}{% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}"""
+ """
+ {% load i18n %}
+ {% language 'nl' %}
+ {% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
+ {% language 'pt-br' %}
+ {% url 'no-prefix-translated-slug' slug='apo' %}{% endlanguage %}
+ """
)
self.assertEqual(
tpl.render(Context({})).strip().split(),
diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index 451434cc46..b9c8b4209c 100644
--- a/tests/i18n/test_extraction.py
+++ b/tests/i18n/test_extraction.py
@@ -108,7 +108,8 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
r"""
self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py')
- verifies that the django.po file has a gettext-style location comment of the form
+ verifies that the django.po file has a gettext-style location comment
+ of the form
`#: dirA/dirB/foo.py:42`
@@ -128,14 +129,16 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
def assertRecentlyModified(self, path):
"""
- Assert that file was recently modified (modification time was less than 10 seconds ago).
+ Assert that file was recently modified (modification time was less than
+ 10 seconds ago).
"""
delta = time.time() - os.stat(path).st_mtime
self.assertLess(delta, 10, "%s was recently modified" % path)
def assertNotRecentlyModified(self, path):
"""
- Assert that file was not recently modified (modification time was more than 10 seconds ago).
+ Assert that file was not recently modified (modification time was more
+ than 10 seconds ago).
"""
delta = time.time() - os.stat(path).st_mtime
self.assertGreater(delta, 10, "%s wasn't recently modified" % path)
@@ -443,7 +446,8 @@ class BasicExtractorTests(ExtractorTests):
mocked_popen_wrapper.return_value = (
"xgettext (GNU gettext-tools) 0.18.1\n"
"Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n"
- "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n"
+ "License GPLv3+: GNU GPL version 3 or later "
+ "<http://gnu.org/licenses/gpl.html>\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n"
"Written by Ulrich Drepper.\n",
@@ -773,7 +777,10 @@ class LocationCommentsTests(ExtractorTests):
CommandError is raised when using makemessages --add-location with
gettext < 0.19.
"""
- msg = "The --add-location option requires gettext 0.19 or later. You have 0.18.99."
+ msg = (
+ "The --add-location option requires gettext 0.19 or later. You have "
+ "0.18.99."
+ )
with self.assertRaisesMessage(CommandError, msg):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="full"
diff --git a/tests/i18n/test_percents.py b/tests/i18n/test_percents.py
index f1dce0c7c6..412b013001 100644
--- a/tests/i18n/test_percents.py
+++ b/tests/i18n/test_percents.py
@@ -87,7 +87,8 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
expected = "Littérale avec un symbole de pour cent à la fin %"
trans_tpl = Template(
- '{% load i18n %}{% translate "Literal with a percent symbol at the end %" %}'
+ "{% load i18n %}"
+ '{% translate "Literal with a percent symbol at the end %" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
@@ -101,7 +102,8 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
expected = "Pour cent littérale % avec un symbole au milieu"
trans_tpl = Template(
- '{% load i18n %}{% translate "Literal with a percent % symbol in the middle" %}'
+ "{% load i18n %}"
+ '{% translate "Literal with a percent % symbol in the middle" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
@@ -124,13 +126,17 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
)
self.assertEqual(block_tpl.render(Context({})), "Il est de 100%")
block_tpl = Template(
- '{% load i18n %}{% blocktranslate context "female" %}It is 100%{% endblocktranslate %}'
+ "{% load i18n %}"
+ '{% blocktranslate context "female" %}It is 100%{% endblocktranslate %}'
)
self.assertEqual(block_tpl.render(Context({})), "Elle est de 100%")
def test_translates_with_string_that_look_like_fmt_spec_with_trans(self):
# tests "%s"
- expected = "On dirait un spec str fmt %s mais ne devrait pas être interprété comme plus disponible"
+ expected = (
+ "On dirait un spec str fmt %s mais ne devrait pas être interprété comme "
+ "plus disponible"
+ )
trans_tpl = Template(
'{% load i18n %}{% translate "Looks like a str fmt spec %s but '
'should not be interpreted as such" %}'
@@ -143,21 +149,28 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
self.assertEqual(block_tpl.render(Context({})), expected)
# tests "% o"
- expected = "On dirait un spec str fmt % o mais ne devrait pas être interprété comme plus disponible"
+ expected = (
+ "On dirait un spec str fmt % o mais ne devrait pas être interprété comme "
+ "plus disponible"
+ )
trans_tpl = Template(
- '{% load i18n %}{% translate "Looks like a str fmt spec % o but should not be '
+ "{% load i18n %}"
+ '{% translate "Looks like a str fmt spec % o but should not be '
'interpreted as such" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
- "{% load i18n %}{% blocktranslate %}Looks like a str fmt spec % o but should not be "
+ "{% load i18n %}"
+ "{% blocktranslate %}Looks like a str fmt spec % o but should not be "
"interpreted as such{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_multiple_percent_signs(self):
- expected = "1 % signe pour cent, signes %% 2 pour cent, trois signes de pourcentage %%%"
-
+ expected = (
+ "1 % signe pour cent, signes %% 2 pour cent, trois signes de pourcentage "
+ "%%%"
+ )
trans_tpl = Template(
'{% load i18n %}{% translate "1 percent sign %, 2 percent signs %%, '
'3 percent signs %%%" %}'
diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index b8df529b13..eec10f80fd 100644
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -648,7 +648,8 @@ class FormattingTests(SimpleTestCase):
thousand_sep=",",
),
)
- # This unusual grouping/force_grouping combination may be triggered by the intcomma filter (#17414)
+ # This unusual grouping/force_grouping combination may be triggered
+ # by the intcomma filter.
self.assertEqual(
"10000",
nformat(
@@ -1119,10 +1120,12 @@ class FormattingTests(SimpleTestCase):
'<option value="6">\u0418\u044e\u043d\u044c</option>'
'<option value="7">\u0418\u044e\u043b\u044c</option>'
'<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>'
- '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>'
+ '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c'
+ "</option>"
'<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>'
'<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>'
- '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>'
+ '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c'
+ "</option>"
"</select>"
'<select name="mydate_year" id="id_mydate_year">'
'<option value="">---</option>'
@@ -1333,13 +1336,17 @@ class FormattingTests(SimpleTestCase):
self.assertHTMLEqual(
form6.as_ul(),
'<li><label for="id_name">Name:</label>'
- '<input id="id_name" type="text" name="name" value="acme" maxlength="50" required></li>'
+ '<input id="id_name" type="text" name="name" value="acme" '
+ ' maxlength="50" required></li>'
'<li><label for="id_date_added">Date added:</label>'
- '<input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" required></li>'
+ '<input type="text" name="date_added" value="31.12.2009 06:00:00" '
+ ' id="id_date_added" required></li>'
'<li><label for="id_cents_paid">Cents paid:</label>'
- '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" required></li>'
+ '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" '
+ " required></li>"
'<li><label for="id_products_delivered">Products delivered:</label>'
- '<input type="text" name="products_delivered" value="12000" id="id_products_delivered" required>'
+ '<input type="text" name="products_delivered" value="12000" '
+ ' id="id_products_delivered" required>'
"</li>",
)
self.assertEqual(
@@ -1516,7 +1523,8 @@ class FormattingTests(SimpleTestCase):
{"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)}
)
template1 = Template(
- "{% load l10n %}{% localize %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; "
+ "{% load l10n %}{% localize %}"
+ "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; "
"{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}"
)
template2 = Template(
@@ -1589,7 +1597,7 @@ class FormattingTests(SimpleTestCase):
def test_localized_as_text_as_hidden_input(self):
"""
- Tests if form input with 'as_hidden' or 'as_text' is correctly localized. Ticket #18777
+ Form input with 'as_hidden' or 'as_text' is correctly localized.
"""
self.maxDiff = 1200
@@ -1598,10 +1606,12 @@ class FormattingTests(SimpleTestCase):
"{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}"
)
template_as_text = Template(
- "{% load l10n %}{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}"
+ "{% load l10n %}"
+ "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}"
)
template_as_hidden = Template(
- "{% load l10n %}{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}"
+ "{% load l10n %}"
+ "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}"
)
form = CompanyForm(
{
@@ -1616,18 +1626,24 @@ class FormattingTests(SimpleTestCase):
self.assertHTMLEqual(
template.render(context),
- '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required>;'
- '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required>',
+ '<input id="id_date_added" name="date_added" type="text" '
+ 'value="31.12.2009 06:00:00" required>;'
+ '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
+ "required>",
)
self.assertHTMLEqual(
template_as_text.render(context),
- '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required>;'
- ' <input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required>',
+ '<input id="id_date_added" name="date_added" type="text" '
+ 'value="31.12.2009 06:00:00" required>;'
+ '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
+ "required>",
)
self.assertHTMLEqual(
template_as_hidden.render(context),
- '<input id="id_date_added" name="date_added" type="hidden" value="31.12.2009 06:00:00">;'
- '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47">',
+ '<input id="id_date_added" name="date_added" type="hidden" '
+ 'value="31.12.2009 06:00:00">;'
+ '<input id="id_cents_paid" name="cents_paid" type="hidden" '
+ 'value="59,47">',
)
def test_format_arbitrary_settings(self):
@@ -1979,8 +1995,8 @@ class ResolutionOrderI18NTests(SimpleTestCase):
self.assertIn(
msgstr,
result,
- "The string '%s' isn't in the translation of '%s'; the actual result is '%s'."
- % (msgstr, msgid, result),
+ "The string '%s' isn't in the translation of '%s'; the actual result is "
+ "'%s'." % (msgstr, msgid, result),
)
diff --git a/tests/indexes/tests.py b/tests/indexes/tests.py
index 80202f37ed..59cad6cc39 100644
--- a/tests/indexes/tests.py
+++ b/tests/indexes/tests.py
@@ -346,7 +346,8 @@ class SchemaIndexesMySQLTests(TransactionTestCase):
self.assertEqual(
index_sql,
[
- "CREATE INDEX `indexes_articletranslation_article_no_constraint_id_d6c0806b` "
+ "CREATE INDEX "
+ "`indexes_articletranslation_article_no_constraint_id_d6c0806b` "
"ON `indexes_articletranslation` (`article_no_constraint_id`)"
],
)
diff --git a/tests/inline_formsets/tests.py b/tests/inline_formsets/tests.py
index 758d472a85..1ae9b3f760 100644
--- a/tests/inline_formsets/tests.py
+++ b/tests/inline_formsets/tests.py
@@ -127,7 +127,10 @@ class InlineFormsetFactoryTest(TestCase):
Child has two ForeignKeys to Parent, so if we don't specify which one
to use for the inline formset, we should get an exception.
"""
- msg = "'inline_formsets.Child' has more than one ForeignKey to 'inline_formsets.Parent'."
+ msg = (
+ "'inline_formsets.Child' has more than one ForeignKey to "
+ "'inline_formsets.Parent'."
+ )
with self.assertRaisesMessage(ValueError, msg):
inlineformset_factory(Parent, Child)
diff --git a/tests/inspectdb/tests.py b/tests/inspectdb/tests.py
index 4aab89ae71..fe02528d54 100644
--- a/tests/inspectdb/tests.py
+++ b/tests/inspectdb/tests.py
@@ -57,7 +57,10 @@ class InspectDBTestCase(TestCase):
self.assertNotIn("InspectdbPeopledata", output)
def make_field_type_asserter(self):
- """Call inspectdb and return a function to validate a field type in its output"""
+ """
+ Call inspectdb and return a function to validate a field type in its
+ output.
+ """
out = StringIO()
call_command("inspectdb", "inspectdb_columntypes", stdout=out)
output = out.getvalue()
@@ -233,13 +236,16 @@ class InspectDBTestCase(TestCase):
output,
msg=error_message,
)
- # As InspectdbPeople model is defined after InspectdbMessage, it should be quoted
+ # As InspectdbPeople model is defined after InspectdbMessage, it should
+ # be quoted.
self.assertIn(
- "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, db_column='from_id')",
+ "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, "
+ "db_column='from_id')",
output,
)
self.assertIn(
- "people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, primary_key=True)",
+ "people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, "
+ "primary_key=True)",
output,
)
self.assertIn(
@@ -315,7 +321,9 @@ class InspectDBTestCase(TestCase):
self.assertIn("class InspectdbSpecialTableName(models.Model):", output)
def test_managed_models(self):
- """By default the command generates models with `Meta.managed = False` (#14305)"""
+ """
+ By default the command generates models with `Meta.managed = False`.
+ """
out = StringIO()
call_command("inspectdb", "inspectdb_columntypes", stdout=out)
output = out.getvalue()
diff --git a/tests/introspection/tests.py b/tests/introspection/tests.py
index def0339d8a..2b62b8646e 100644
--- a/tests/introspection/tests.py
+++ b/tests/introspection/tests.py
@@ -227,8 +227,10 @@ class IntrospectionTests(TransactionTestCase):
formatting.
"""
create_table_statements = [
- "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY(art_id) REFERENCES {}(id));",
- "CREATE TABLE track(id, art_id INTEGER, FOREIGN KEY (art_id) REFERENCES {}(id));",
+ "CREATE TABLE track(id, art_id INTEGER, "
+ "FOREIGN KEY(art_id) REFERENCES {}(id));",
+ "CREATE TABLE track(id, art_id INTEGER, "
+ "FOREIGN KEY (art_id) REFERENCES {}(id));",
]
for statement in create_table_statements:
with connection.cursor() as cursor:
diff --git a/tests/invalid_models_tests/test_deprecated_fields.py b/tests/invalid_models_tests/test_deprecated_fields.py
index fee5fb39f8..3f3953496c 100644
--- a/tests/invalid_models_tests/test_deprecated_fields.py
+++ b/tests/invalid_models_tests/test_deprecated_fields.py
@@ -37,7 +37,11 @@ class DeprecatedFieldsTests(SimpleTestCase):
checks.Error(
"CommaSeparatedIntegerField is removed except for support in "
"historical migrations.",
- hint="Use CharField(validators=[validate_comma_separated_integer_list]) instead.",
+ hint=(
+ "Use "
+ "CharField(validators=[validate_comma_separated_integer_list]) "
+ "instead."
+ ),
obj=CommaSeparatedIntegerModel._meta.get_field("csi"),
id="fields.E901",
)
diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py
index 6daa14f0ad..5ea830d0ec 100644
--- a/tests/invalid_models_tests/test_models.py
+++ b/tests/invalid_models_tests/test_models.py
@@ -228,7 +228,8 @@ class UniqueTogetherTests(SimpleTestCase):
Model.check(),
[
Error(
- "'unique_together' refers to the nonexistent field 'missing_field'.",
+ "'unique_together' refers to the nonexistent field "
+ "'missing_field'.",
obj=Model,
id="models.E012",
),
@@ -1452,7 +1453,8 @@ class OtherModelTests(SimpleTestCase):
Model.check(),
[
Error(
- "The model cannot have more than one field with 'primary_key=True'.",
+ "The model cannot have more than one field with "
+ "'primary_key=True'.",
obj=Model,
id="models.E026",
)
@@ -1469,7 +1471,8 @@ class OtherModelTests(SimpleTestCase):
Model.check(),
[
Error(
- "'TEST_SWAPPED_MODEL_BAD_VALUE' is not of the form 'app_label.app_name'.",
+ "'TEST_SWAPPED_MODEL_BAD_VALUE' is not of the form "
+ "'app_label.app_name'.",
id="models.E001",
),
],
diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py
index ba63cb2903..ef7f845a33 100644
--- a/tests/invalid_models_tests/test_ordinary_fields.py
+++ b/tests/invalid_models_tests/test_ordinary_fields.py
@@ -750,7 +750,8 @@ class FilePathFieldTests(SimpleTestCase):
field.check(),
[
Error(
- "FilePathFields must have either 'allow_files' or 'allow_folders' set to True.",
+ "FilePathFields must have either 'allow_files' or 'allow_folders' "
+ "set to True.",
obj=field,
id="fields.E140",
),
diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py
index 00eb988883..3c854af783 100644
--- a/tests/invalid_models_tests/test_relative_fields.py
+++ b/tests/invalid_models_tests/test_relative_fields.py
@@ -343,7 +343,10 @@ class RelativeFieldTests(SimpleTestCase):
"foreign keys to 'Person', which is ambiguous. You must specify "
"which two foreign keys Django should use via the through_fields "
"keyword argument.",
- hint="Use through_fields to specify which two foreign keys Django should use.",
+ hint=(
+ "Use through_fields to specify which two foreign keys Django "
+ "should use."
+ ),
obj=InvalidRelationship,
id="fields.E333",
),
@@ -425,7 +428,8 @@ class RelativeFieldTests(SimpleTestCase):
field.check(),
[
Error(
- "'Target.bad' must be unique because it is referenced by a foreign key.",
+ "'Target.bad' must be unique because it is referenced by a foreign "
+ "key.",
hint=(
"Add unique=True to this field or add a UniqueConstraint "
"(without condition) in the model Meta.constraints."
@@ -448,7 +452,8 @@ class RelativeFieldTests(SimpleTestCase):
field.check(),
[
Error(
- "'Target.bad' must be unique because it is referenced by a foreign key.",
+ "'Target.bad' must be unique because it is referenced by a foreign "
+ "key.",
hint=(
"Add unique=True to this field or add a UniqueConstraint "
"(without condition) in the model Meta.constraints."
@@ -532,7 +537,8 @@ class RelativeFieldTests(SimpleTestCase):
field.check(),
[
Error(
- "No subset of the fields 'country_id', 'city_id' on model 'Person' is unique.",
+ "No subset of the fields 'country_id', 'city_id' on model 'Person' "
+ "is unique.",
hint=(
"Mark a single field as unique=True or add a set of "
"fields to a unique constraint (via unique_together or a "
@@ -627,7 +633,10 @@ class RelativeFieldTests(SimpleTestCase):
[
Error(
"Field specifies on_delete=SET_NULL, but cannot be null.",
- hint="Set null=True argument on the field, or change the on_delete rule.",
+ hint=(
+ "Set null=True argument on the field, or change the on_delete "
+ "rule."
+ ),
obj=field,
id="fields.E320",
),
@@ -668,7 +677,10 @@ class RelativeFieldTests(SimpleTestCase):
[
Error(
"Primary keys must not have null=True.",
- hint="Set null=False on the field, or remove primary_key=True argument.",
+ hint=(
+ "Set null=False on the field, or remove primary_key=True "
+ "argument."
+ ),
obj=field,
id="fields.E007",
),
@@ -802,7 +814,10 @@ class RelativeFieldTests(SimpleTestCase):
Error(
"The name '%s' is invalid related_name for field Child%s.parent"
% (invalid_related_name, invalid_related_name),
- hint="Related name must be a valid Python identifier or end with a '+'",
+ hint=(
+ "Related name must be a valid Python identifier or end "
+ "with a '+'"
+ ),
obj=field,
id="fields.E306",
),
@@ -861,12 +876,14 @@ class RelativeFieldTests(SimpleTestCase):
field.check(),
[
Error(
- "The to_field 'a' doesn't exist on the related model 'invalid_models_tests.Parent'.",
+ "The to_field 'a' doesn't exist on the related model "
+ "'invalid_models_tests.Parent'.",
obj=field,
id="fields.E312",
),
Error(
- "The to_field 'b' doesn't exist on the related model 'invalid_models_tests.Parent'.",
+ "The to_field 'b' doesn't exist on the related model "
+ "'invalid_models_tests.Parent'.",
obj=field,
id="fields.E312",
),
@@ -889,8 +906,9 @@ class RelativeFieldTests(SimpleTestCase):
field.check(),
[
Error(
- "Field defines a relation with model 'invalid_models_tests.Parent', "
- "which is either not installed, or is abstract.",
+ "Field defines a relation with model "
+ "'invalid_models_tests.Parent', which is either not installed, or "
+ "is abstract.",
id="fields.E300",
obj=field,
),
@@ -1814,13 +1832,19 @@ class M2mThroughFieldsTests(SimpleTestCase):
[
Error(
"'Invitation.invitee' is not a foreign key to 'Event'.",
- hint="Did you mean one of the following foreign keys to 'Event': event?",
+ hint=(
+ "Did you mean one of the following foreign keys to 'Event': "
+ "event?"
+ ),
obj=field,
id="fields.E339",
),
Error(
"'Invitation.event' is not a foreign key to 'Fan'.",
- hint="Did you mean one of the following foreign keys to 'Fan': invitee, inviter?",
+ hint=(
+ "Did you mean one of the following foreign keys to 'Fan': "
+ "invitee, inviter?"
+ ),
obj=field,
id="fields.E339",
),
@@ -1853,14 +1877,22 @@ class M2mThroughFieldsTests(SimpleTestCase):
field.check(from_model=Event),
[
Error(
- "The intermediary model 'invalid_models_tests.Invitation' has no field 'invalid_field_1'.",
- hint="Did you mean one of the following foreign keys to 'Event': event?",
+ "The intermediary model 'invalid_models_tests.Invitation' has no "
+ "field 'invalid_field_1'.",
+ hint=(
+ "Did you mean one of the following foreign keys to 'Event': "
+ "event?"
+ ),
obj=field,
id="fields.E338",
),
Error(
- "The intermediary model 'invalid_models_tests.Invitation' has no field 'invalid_field_2'.",
- hint="Did you mean one of the following foreign keys to 'Fan': invitee, inviter?",
+ "The intermediary model 'invalid_models_tests.Invitation' has no "
+ "field 'invalid_field_2'.",
+ hint=(
+ "Did you mean one of the following foreign keys to 'Fan': "
+ "invitee, inviter?"
+ ),
obj=field,
id="fields.E338",
),
@@ -1894,7 +1926,10 @@ class M2mThroughFieldsTests(SimpleTestCase):
"Field specifies 'through_fields' but does not provide the names "
"of the two link fields that should be used for the relation "
"through model 'invalid_models_tests.Invitation'.",
- hint="Make sure you specify 'through_fields' as through_fields=('field1', 'field2')",
+ hint=(
+ "Make sure you specify 'through_fields' as "
+ "through_fields=('field1', 'field2')"
+ ),
obj=field,
id="fields.E337",
),
@@ -1968,7 +2003,8 @@ class M2mThroughFieldsTests(SimpleTestCase):
field.check(from_model=Child),
[
Error(
- "No subset of the fields 'a', 'b', 'd' on model 'Parent' is unique.",
+ "No subset of the fields 'a', 'b', 'd' on model 'Parent' is "
+ "unique.",
hint=(
"Mark a single field as unique=True or add a set of "
"fields to a unique constraint (via unique_together or a "
diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py
index 05e6a6bede..ec6b1338be 100644
--- a/tests/logging_tests/tests.py
+++ b/tests/logging_tests/tests.py
@@ -271,7 +271,8 @@ class AdminEmailHandlerTest(SimpleTestCase):
self.assertEqual(mail.outbox[0].to, ["admin@example.com"])
self.assertEqual(
mail.outbox[0].subject,
- "-SuperAwesomeSubject-ERROR: Custom message that says 'ping' and 'pong'",
+ "-SuperAwesomeSubject-ERROR: "
+ "Custom message that says 'ping' and 'pong'",
)
finally:
# Restore original filters
@@ -309,7 +310,8 @@ class AdminEmailHandlerTest(SimpleTestCase):
self.assertEqual(mail.outbox[0].to, ["admin@example.com"])
self.assertEqual(
mail.outbox[0].subject,
- "-SuperAwesomeSubject-ERROR (internal IP): Custom message that says 'ping' and 'pong'",
+ "-SuperAwesomeSubject-ERROR (internal IP): "
+ "Custom message that says 'ping' and 'pong'",
)
finally:
# Restore original filters
diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py
index 5add905ce2..55c2907761 100644
--- a/tests/lookup/tests.py
+++ b/tests/lookup/tests.py
@@ -792,9 +792,9 @@ class LookupTests(TestCase):
Tag.objects.filter(articles__foo="bar")
def test_regex(self):
- # Create some articles with a bit more interesting headlines for testing field lookups:
- for a in Article.objects.all():
- a.delete()
+ # Create some articles with a bit more interesting headlines for
+ # testing field lookups.
+ Article.objects.all().delete()
now = datetime.now()
Article.objects.bulk_create(
[
@@ -975,7 +975,10 @@ class LookupTests(TestCase):
"""
A lookup query containing non-fields raises the proper exception.
"""
- msg = "Unsupported lookup 'blahblah' for CharField or join on the field not permitted."
+ msg = (
+ "Unsupported lookup 'blahblah' for CharField or join on the field not "
+ "permitted."
+ )
with self.assertRaisesMessage(FieldError, msg):
Article.objects.filter(headline__blahblah=99)
with self.assertRaisesMessage(FieldError, msg):
diff --git a/tests/m2m_regress/tests.py b/tests/m2m_regress/tests.py
index 2444794742..c8ecfebfe1 100644
--- a/tests/m2m_regress/tests.py
+++ b/tests/m2m_regress/tests.py
@@ -42,10 +42,11 @@ class M2MRegressionTests(TestCase):
def test_internal_related_name_not_in_error_msg(self):
# The secret internal related names for self-referential many-to-many
# fields shouldn't appear in the list when an error is made.
- with self.assertRaisesMessage(
- FieldError,
- "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling",
- ):
+ msg = (
+ "Choices are: id, name, references, related, selfreferchild, "
+ "selfreferchildsibling"
+ )
+ with self.assertRaisesMessage(FieldError, msg):
SelfRefer.objects.filter(porcupine="fred")
def test_m2m_inheritance_symmetry(self):
diff --git a/tests/m2m_through_regress/tests.py b/tests/m2m_through_regress/tests.py
index 1c362657db..eae151546b 100644
--- a/tests/m2m_through_regress/tests.py
+++ b/tests/m2m_through_regress/tests.py
@@ -71,7 +71,12 @@ class M2MThroughSerializationTestCase(TestCase):
def test_serialization(self):
"m2m-through models aren't serialized as m2m fields. Refs #8134"
- pks = {"p_pk": self.bob.pk, "g_pk": self.roll.pk, "m_pk": self.bob_roll.pk}
+ pks = {
+ "p_pk": self.bob.pk,
+ "g_pk": self.roll.pk,
+ "m_pk": self.bob_roll.pk,
+ "app_label": "m2m_through_regress",
+ }
out = StringIO()
management.call_command(
@@ -79,10 +84,12 @@ class M2MThroughSerializationTestCase(TestCase):
)
self.assertJSONEqual(
out.getvalue().strip(),
- '[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", "fields": {"person": %(p_pk)s, "price": '
- '100, "group": %(g_pk)s}}, {"pk": %(p_pk)s, "model": "m2m_through_regress.person", "fields": {"name": '
- '"Bob"}}, {"pk": %(g_pk)s, "model": "m2m_through_regress.group", "fields": {"name": "Roll"}}]'
- % pks,
+ '[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", '
+ '"fields": {"person": %(p_pk)s, "price": 100, "group": %(g_pk)s}}, '
+ '{"pk": %(p_pk)s, "model": "m2m_through_regress.person", '
+ '"fields": {"name": "Bob"}}, '
+ '{"pk": %(g_pk)s, "model": "m2m_through_regress.group", '
+ '"fields": {"name": "Roll"}}]' % pks,
)
out = StringIO()
@@ -94,15 +101,15 @@ class M2MThroughSerializationTestCase(TestCase):
"""
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
- <object pk="%(m_pk)s" model="m2m_through_regress.membership">
- <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field>
- <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field>
+ <object pk="%(m_pk)s" model="%(app_label)s.membership">
+ <field to="%(app_label)s.person" name="person" rel="ManyToOneRel">%(p_pk)s</field>
+ <field to="%(app_label)s.group" name="group" rel="ManyToOneRel">%(g_pk)s</field>
<field type="IntegerField" name="price">100</field>
</object>
- <object pk="%(p_pk)s" model="m2m_through_regress.person">
+ <object pk="%(p_pk)s" model="%(app_label)s.person">
<field type="CharField" name="name">Bob</field>
</object>
- <object pk="%(g_pk)s" model="m2m_through_regress.group">
+ <object pk="%(g_pk)s" model="%(app_label)s.group">
<field type="CharField" name="name">Roll</field>
</object>
</django-objects>
@@ -223,7 +230,10 @@ class ThroughLoadDataTestCase(TestCase):
)
self.assertJSONEqual(
out.getvalue().strip(),
- '[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user"'
- ': 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, '
- '"model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]',
+ '[{"pk": 1, "model": "m2m_through_regress.usermembership", '
+ '"fields": {"price": 100, "group": 1, "user": 1}}, '
+ '{"pk": 1, "model": "m2m_through_regress.person", '
+ '"fields": {"name": "Guido"}}, '
+ '{"pk": 1, "model": "m2m_through_regress.group", '
+ '"fields": {"name": "Python Core Group"}}]',
)
diff --git a/tests/mail/tests.py b/tests/mail/tests.py
index 309be47059..51e26cc6be 100644
--- a/tests/mail/tests.py
+++ b/tests/mail/tests.py
@@ -295,8 +295,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
Test for space continuation character in long (ASCII) subject headers (#7747)
"""
email = EmailMessage(
- "Long subject lines that get wrapped should contain a space "
- "continuation character to get expected behavior in Outlook and Thunderbird",
+ "Long subject lines that get wrapped should contain a space continuation "
+ "character to get expected behavior in Outlook and Thunderbird",
"Content",
"from@example.com",
["to@example.com"],
@@ -367,7 +367,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
)
- # If we don't set the To header manually, it should default to the `to` argument to the constructor
+ # If we don't set the To header manually, it should default to the `to`
+ # argument to the constructor.
email = EmailMessage(
"Subject",
"Content",
@@ -558,7 +559,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
)
self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.")
- # Make sure MIME attachments also works correctly with other encodings than utf-8
+ # MIME attachments works correctly with other encodings than utf-8.
text_content = "Firstname Sürname is a great guy."
html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>"
msg = EmailMultiAlternatives(
@@ -790,7 +791,10 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
)
if sys.platform == "win32":
- msg = "_getfullpathname: path should be string, bytes or os.PathLike, not object"
+ msg = (
+ "_getfullpathname: path should be string, bytes or os.PathLike, not "
+ "object"
+ )
else:
msg = "expected str, bytes or os.PathLike object, not object"
with self.assertRaisesMessage(TypeError, msg):
@@ -871,7 +875,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
self.assertIn(b"Content-Transfer-Encoding: 7bit", msg.message().as_bytes())
# Ticket #11212
- # Shouldn't use quoted printable, should detect it can represent content with 7 bit data
+ # Shouldn't use quoted printable, should detect it can represent
+ # content with 7 bit data.
msg = EmailMessage(
"Subject",
"Body with only ASCII characters.",
@@ -882,7 +887,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
s = msg.message().as_bytes()
self.assertIn(b"Content-Transfer-Encoding: 7bit", s)
- # Shouldn't use quoted printable, should detect it can represent content with 8 bit data
+ # Shouldn't use quoted printable, should detect it can represent
+ # content with 8 bit data.
msg = EmailMessage(
"Subject",
"Body with latin characters: àáä.",
@@ -1182,7 +1188,8 @@ class BaseEmailBackendTests(HeadersCheckMixin):
def get_mailbox_content(self):
raise NotImplementedError(
- "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() method"
+ "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() "
+ "method"
)
def flush_mailbox(self):
diff --git a/tests/managers_regress/tests.py b/tests/managers_regress/tests.py
index 8a67b9f685..33192a1699 100644
--- a/tests/managers_regress/tests.py
+++ b/tests/managers_regress/tests.py
@@ -152,7 +152,8 @@ class ManagersRegressionTests(TestCase):
relation.m2m.add(related)
t = Template(
- "{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}{{ related.test_m2m.all.0 }}"
+ "{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}"
+ "{{ related.test_m2m.all.0 }}"
)
self.assertEqual(
diff --git a/tests/many_to_many/tests.py b/tests/many_to_many/tests.py
index 3d393b5711..53e870ddad 100644
--- a/tests/many_to_many/tests.py
+++ b/tests/many_to_many/tests.py
@@ -57,7 +57,10 @@ class ManyToManyTests(TestCase):
)
# Adding an object of the wrong type raises TypeError
- msg = "'Publication' instance expected, got <Article: Django lets you create web apps easily>"
+ msg = (
+ "'Publication' instance expected, got <Article: Django lets you create web "
+ "apps easily>"
+ )
with self.assertRaisesMessage(TypeError, msg):
with transaction.atomic():
a6.publications.add(a5)
diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py
index 8fca4d691f..b8b040eff6 100644
--- a/tests/many_to_one/tests.py
+++ b/tests/many_to_one/tests.py
@@ -84,7 +84,10 @@ class ManyToOneTests(TestCase):
new_article2 = Article(
headline="Paul's story", pub_date=datetime.date(2006, 1, 17)
)
- msg = "<Article: Paul's story> instance isn't saved. Use bulk=False or save the object first."
+ msg = (
+ "<Article: Paul's story> instance isn't saved. Use bulk=False or save the "
+ "object first."
+ )
with self.assertRaisesMessage(ValueError, msg):
self.r.article_set.add(new_article2)
@@ -268,7 +271,8 @@ class ManyToOneTests(TestCase):
),
[new_article1, self.a],
)
- # The underlying query only makes one join when a related table is referenced twice.
+ # The underlying query only makes one join when a related table is
+ # referenced twice.
queryset = Article.objects.filter(
reporter__first_name__exact="John", reporter__last_name__exact="Smith"
)
@@ -284,7 +288,8 @@ class ManyToOneTests(TestCase):
),
[new_article1, self.a],
)
- # ... and should work fine with the string that comes out of forms.Form.cleaned_data
+ # ... and should work fine with the string that comes out of
+ # forms.Form.cleaned_data.
self.assertQuerysetEqual(
(
Article.objects.filter(reporter__first_name__exact="John").extra(
@@ -632,11 +637,13 @@ class ManyToOneTests(TestCase):
# Creation using keyword argument and unsaved related instance (#8070).
p = Parent()
- msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'."
+ msg = (
+ "save() prohibited to prevent data loss due to unsaved related object "
+ "'parent'."
+ )
with self.assertRaisesMessage(ValueError, msg):
Child.objects.create(parent=p)
- msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'."
with self.assertRaisesMessage(ValueError, msg):
ToFieldChild.objects.create(parent=p)
diff --git a/tests/messages_tests/test_api.py b/tests/messages_tests/test_api.py
index dcd98f085c..40283d4153 100644
--- a/tests/messages_tests/test_api.py
+++ b/tests/messages_tests/test_api.py
@@ -35,7 +35,10 @@ class ApiTests(SimpleTestCase):
self.assertEqual(self.storage.store, [])
def test_middleware_missing(self):
- msg = "You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware"
+ msg = (
+ "You cannot add messages without installing "
+ "django.contrib.messages.middleware.MessageMiddleware"
+ )
with self.assertRaisesMessage(messages.MessageFailure, msg):
messages.add_message(self.request, messages.DEBUG, "some message")
self.assertEqual(self.storage.store, [])
diff --git a/tests/messages_tests/test_cookie.py b/tests/messages_tests/test_cookie.py
index eb89bf5e99..f4b99e5ae8 100644
--- a/tests/messages_tests/test_cookie.py
+++ b/tests/messages_tests/test_cookie.py
@@ -88,7 +88,8 @@ class CookieTests(BaseTests, SimpleTestCase):
self.assertIs(response.cookies["messages"]["httponly"], True)
self.assertEqual(response.cookies["messages"]["samesite"], "Strict")
- # Test deletion of the cookie (storing with an empty value) after the messages have been consumed
+ # Deletion of the cookie (storing with an empty value) after the
+ # messages have been consumed.
storage = self.get_storage()
response = self.get_response()
storage.add(constants.INFO, "test")
diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py
index c3e93236a6..cb40b36321 100644
--- a/tests/middleware/tests.py
+++ b/tests/middleware/tests.py
@@ -240,7 +240,8 @@ class CommonMiddlewareTest(SimpleTestCase):
r = CommonMiddleware(get_response_404)(request)
self.assertIsNotNone(
r,
- "CommonMiddleware failed to return APPEND_SLASH redirect using request.urlconf",
+ "CommonMiddleware failed to return APPEND_SLASH redirect using "
+ "request.urlconf",
)
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, "/customurlconf/slash/")
@@ -278,7 +279,8 @@ class CommonMiddlewareTest(SimpleTestCase):
r = CommonMiddleware(get_response_404)(request)
self.assertIsNotNone(
r,
- "CommonMiddleware failed to return APPEND_SLASH redirect using request.urlconf",
+ "CommonMiddleware failed to return APPEND_SLASH redirect using "
+ "request.urlconf",
)
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, "/customurlconf/needsquoting%23/")
@@ -454,7 +456,7 @@ class BrokenLinkEmailsMiddlewareTest(SimpleTestCase):
self.assertEqual(len(mail.outbox), 1)
@override_settings(APPEND_SLASH=True)
- def test_referer_equal_to_requested_url_without_trailing_slash_when_append_slash_is_set(
+ def test_referer_equal_to_requested_url_without_trailing_slash_with_append_slash(
self,
):
self.req.path = self.req.path_info = "/regular_url/that/does/not/exist/"
@@ -463,7 +465,7 @@ class BrokenLinkEmailsMiddlewareTest(SimpleTestCase):
self.assertEqual(len(mail.outbox), 0)
@override_settings(APPEND_SLASH=False)
- def test_referer_equal_to_requested_url_without_trailing_slash_when_append_slash_is_unset(
+ def test_referer_equal_to_requested_url_without_trailing_slash_with_no_append_slash(
self,
):
self.req.path = self.req.path_info = "/regular_url/that/does/not/exist/"
diff --git a/tests/middleware_exceptions/tests.py b/tests/middleware_exceptions/tests.py
index b3b611e23f..5752d1911c 100644
--- a/tests/middleware_exceptions/tests.py
+++ b/tests/middleware_exceptions/tests.py
@@ -197,7 +197,8 @@ class MiddlewareNotUsedTests(SimpleTestCase):
self.client.get("/middleware_exceptions/view/")
self.assertEqual(
cm.records[0].getMessage(),
- "MiddlewareNotUsed('middleware_exceptions.tests.MyMiddlewareWithExceptionMessage'): spam eggs",
+ "MiddlewareNotUsed('middleware_exceptions.tests."
+ "MyMiddlewareWithExceptionMessage'): spam eggs",
)
@override_settings(
diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py
index 9f29d5f95f..cc23d2f810 100644
--- a/tests/migrations/test_autodetector.py
+++ b/tests/migrations/test_autodetector.py
@@ -1098,7 +1098,8 @@ class AutodetectorTests(TestCase):
for attr, value in attrs.items():
if getattr(field, attr, None) != value:
self.fail(
- "Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, got %r):\n%s"
+ "Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, "
+ "got %r):\n%s"
% (
app_label,
migration.name,
@@ -2351,7 +2352,8 @@ class AutodetectorTests(TestCase):
validators=[
RegexValidator(
re.compile("^[-a-zA-Z0-9_]+\\Z"),
- "Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.",
+ "Enter a valid “slug” consisting of letters, numbers, "
+ "underscores or hyphens.",
"invalid",
)
],
@@ -2380,7 +2382,8 @@ class AutodetectorTests(TestCase):
validators=[
RegexValidator(
re.compile("^[a-z]+\\Z", 32),
- "Enter a valid “slug” consisting of letters, numbers, underscores or hyphens.",
+ "Enter a valid “slug” consisting of letters, numbers, "
+ "underscores or hyphens.",
"invalid",
)
],
@@ -4104,7 +4107,9 @@ class AutodetectorTests(TestCase):
self.assertOperationAttributes(changes, app_label, 0, 2, name="restaurant")
def test_multiple_bases(self):
- """#23956 - Inheriting models doesn't move *_ptr fields into AddField operations."""
+ """
+ Inheriting models doesn't move *_ptr fields into AddField operations.
+ """
A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))])
B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))])
C = ModelState("app", "C", [], bases=("app.A", "app.B"))
diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py
index 5d6a859664..2896edf172 100644
--- a/tests/migrations/test_commands.py
+++ b/tests/migrations/test_commands.py
@@ -269,7 +269,9 @@ class MigrateTests(MigrationTestBase):
with override_settings(
MIGRATION_MODULES={
- "migrations": "migrations.test_fake_initial_case_insensitive.fake_initial",
+ "migrations": (
+ "migrations.test_fake_initial_case_insensitive.fake_initial"
+ ),
}
):
out = io.StringIO()
@@ -486,7 +488,8 @@ class MigrateTests(MigrationTestBase):
self.assertEqual(
"[ ] migrations.0001_initial\n"
"[ ] migrations.0003_third ... (migrations.0001_initial)\n"
- "[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
+ "[ ] migrations.0002_second ... (migrations.0001_initial, "
+ "migrations.0003_third)\n",
out.getvalue().lower(),
)
call_command("migrate", "migrations", "0003", verbosity=0)
@@ -505,7 +508,8 @@ class MigrateTests(MigrationTestBase):
self.assertEqual(
"[x] migrations.0001_initial\n"
"[x] migrations.0003_third ... (migrations.0001_initial)\n"
- "[ ] migrations.0002_second ... (migrations.0001_initial, migrations.0003_third)\n",
+ "[ ] migrations.0002_second ... (migrations.0001_initial, "
+ "migrations.0003_third)\n",
out.getvalue().lower(),
)
@@ -833,13 +837,15 @@ class MigrateTests(MigrationTestBase):
self.assertGreater(
index_tx_end,
index_op_desc_unique_together,
- "Transaction end not found or found before operation description (unique_together)",
+ "Transaction end not found or found before operation description "
+ "(unique_together)",
)
self.assertGreater(
index_op_desc_author,
index_tx_start,
- "Operation description (author) not found or found before transaction start",
+ "Operation description (author) not found or found before transaction "
+ "start",
)
self.assertGreater(
index_create_table,
@@ -849,12 +855,14 @@ class MigrateTests(MigrationTestBase):
self.assertGreater(
index_op_desc_tribble,
index_create_table,
- "Operation description (tribble) not found or found before CREATE TABLE (author)",
+ "Operation description (tribble) not found or found before CREATE TABLE "
+ "(author)",
)
self.assertGreater(
index_op_desc_unique_together,
index_op_desc_tribble,
- "Operation description (unique_together) not found or found before operation description (tribble)",
+ "Operation description (unique_together) not found or found before "
+ "operation description (tribble)",
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
@@ -886,17 +894,20 @@ class MigrateTests(MigrationTestBase):
self.assertGreater(
index_op_desc_unique_together,
index_tx_start,
- "Operation description (unique_together) not found or found before transaction start",
+ "Operation description (unique_together) not found or found before "
+ "transaction start",
)
self.assertGreater(
index_op_desc_tribble,
index_op_desc_unique_together,
- "Operation description (tribble) not found or found before operation description (unique_together)",
+ "Operation description (tribble) not found or found before operation "
+ "description (unique_together)",
)
self.assertGreater(
index_op_desc_author,
index_op_desc_tribble,
- "Operation description (author) not found or found before operation description (tribble)",
+ "Operation description (author) not found or found before operation "
+ "description (tribble)",
)
self.assertGreater(
@@ -1171,7 +1182,10 @@ class MigrateTests(MigrationTestBase):
"""
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0002_second")
- msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
+ msg = (
+ "Migration migrations.0002_second is applied before its dependency "
+ "migrations.0001_initial"
+ )
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
call_command("migrate")
applied_migrations = recorder.applied_migrations()
@@ -2107,7 +2121,10 @@ class MakeMigrationsTests(MigrationTestBase):
"""
recorder = MigrationRecorder(connection)
recorder.record_applied("migrations", "0002_second")
- msg = "Migration migrations.0002_second is applied before its dependency migrations.0001_initial"
+ msg = (
+ "Migration migrations.0002_second is applied before its dependency "
+ "migrations.0001_initial"
+ )
with self.temporary_migration_module(module="migrations.test_migrations"):
with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
call_command("makemigrations")
@@ -2227,7 +2244,8 @@ class SquashMigrationsTests(MigrationTestBase):
"Created new squashed migration %s\n"
" You should commit this migration but leave the old ones in place;\n"
" the new migration will be used for new installs. Once you are sure\n"
- " all instances of the codebase have applied the migrations you squashed,\n"
+ " all instances of the codebase have applied the migrations you "
+ "squashed,\n"
" you can delete them.\n" % squashed_migration_file,
)
diff --git a/tests/migrations/test_graph.py b/tests/migrations/test_graph.py
index f62b44180a..a9efb172d9 100644
--- a/tests/migrations/test_graph.py
+++ b/tests/migrations/test_graph.py
@@ -240,7 +240,10 @@ class GraphTests(SimpleTestCase):
graph.add_node(("app_b", "0001"), None)
graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_a", "0002"))
graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001"))
- msg = "Migration app_a.0001 dependencies reference nonexistent parent node ('app_b', '0002')"
+ msg = (
+ "Migration app_a.0001 dependencies reference nonexistent parent node "
+ "('app_b', '0002')"
+ )
with self.assertRaisesMessage(NodeNotFoundError, msg):
graph.add_dependency("app_a.0001", ("app_a", "0001"), ("app_b", "0002"))
@@ -251,7 +254,10 @@ class GraphTests(SimpleTestCase):
# Build graph
graph = MigrationGraph()
graph.add_node(("app_a", "0001"), None)
- msg = "Migration app_a.0002 dependencies reference nonexistent child node ('app_a', '0002')"
+ msg = (
+ "Migration app_a.0002 dependencies reference nonexistent child node "
+ "('app_a', '0002')"
+ )
with self.assertRaisesMessage(NodeNotFoundError, msg):
graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001"))
@@ -261,7 +267,10 @@ class GraphTests(SimpleTestCase):
graph.add_dependency(
"app_a.0001", ("app_a", "0001"), ("app_b", "0002"), skip_validation=True
)
- msg = "Migration app_a.0001 dependencies reference nonexistent parent node ('app_b', '0002')"
+ msg = (
+ "Migration app_a.0001 dependencies reference nonexistent parent node "
+ "('app_b', '0002')"
+ )
with self.assertRaisesMessage(NodeNotFoundError, msg):
graph.validate_consistency()
@@ -271,7 +280,10 @@ class GraphTests(SimpleTestCase):
graph.add_dependency(
"app_b.0002", ("app_a", "0001"), ("app_b", "0002"), skip_validation=True
)
- msg = "Migration app_b.0002 dependencies reference nonexistent child node ('app_a', '0001')"
+ msg = (
+ "Migration app_b.0002 dependencies reference nonexistent child node "
+ "('app_a', '0001')"
+ )
with self.assertRaisesMessage(NodeNotFoundError, msg):
graph.validate_consistency()
@@ -323,8 +335,8 @@ class GraphTests(SimpleTestCase):
)
# Try replacing before replacement node exists.
msg = (
- "Unable to find replacement node ('app_a', '0001_squashed_0002'). It was either"
- " never added to the migration graph, or has been removed."
+ "Unable to find replacement node ('app_a', '0001_squashed_0002'). It was "
+ "either never added to the migration graph, or has been removed."
)
with self.assertRaisesMessage(NodeNotFoundError, msg):
graph.remove_replaced_nodes(
@@ -387,7 +399,8 @@ class GraphTests(SimpleTestCase):
child_node = graph.node_map[("app_b", "0001")]
self.assertIn(child_node, replaced_node.children)
self.assertIn(replaced_node, child_node.parents)
- # Ensure child dependency hasn't also gotten remapped to the other replaced node.
+ # Child dependency hasn't also gotten remapped to the other replaced
+ # node.
other_replaced_node = graph.node_map[("app_a", "0001")]
self.assertNotIn(child_node, other_replaced_node.children)
self.assertNotIn(other_replaced_node, child_node.parents)
diff --git a/tests/migrations/test_loader.py b/tests/migrations/test_loader.py
index de70c4d981..847b937d5a 100644
--- a/tests/migrations/test_loader.py
+++ b/tests/migrations/test_loader.py
@@ -127,7 +127,7 @@ class LoaderTests(TestCase):
)
def test_load_unmigrated_dependency(self):
"""
- Makes sure the loader can load migrations with a dependency on an unmigrated app.
+ The loader can load migrations with a dependency on an unmigrated app.
"""
# Load and test the plan
migration_loader = MigrationLoader(connection)
@@ -430,10 +430,10 @@ class LoaderTests(TestCase):
# However, starting at 3 or 4, nonexistent migrations would be needed.
msg = (
- "Migration migrations.6_auto depends on nonexistent node ('migrations', '5_auto'). "
- "Django tried to replace migration migrations.5_auto with any of "
- "[migrations.3_squashed_5] but wasn't able to because some of the replaced "
- "migrations are already applied."
+ "Migration migrations.6_auto depends on nonexistent node "
+ "('migrations', '5_auto'). Django tried to replace migration "
+ "migrations.5_auto with any of [migrations.3_squashed_5] but wasn't able "
+ "to because some of the replaced migrations are already applied."
)
self.record_applied(recorder, "migrations", "3_auto")
diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py
index 74a3906f1a..a72285a321 100644
--- a/tests/migrations/test_operations.py
+++ b/tests/migrations/test_operations.py
@@ -26,7 +26,8 @@ class OperationTests(OperationTestBase):
def test_create_model(self):
"""
Tests the CreateModel operation.
- Most other tests use this operation as part of setup, so check failures here first.
+ Most other tests use this operation as part of setup, so check failures
+ here first.
"""
operation = migrations.CreateModel(
"Pony",
@@ -97,7 +98,10 @@ class OperationTests(OperationTestBase):
"test_crmo.pony",
),
)
- message = "Found duplicate value migrations.unicodemodel in CreateModel bases argument."
+ message = (
+ "Found duplicate value migrations.unicodemodel in CreateModel bases "
+ "argument."
+ )
with self.assertRaisesMessage(ValueError, message):
migrations.CreateModel(
"Pony",
@@ -125,7 +129,10 @@ class OperationTests(OperationTestBase):
"migrations.UnicodeModel",
),
)
- message = "Found duplicate value <class 'django.db.models.base.Model'> in CreateModel bases argument."
+ message = (
+ "Found duplicate value <class 'django.db.models.base.Model'> in "
+ "CreateModel bases argument."
+ )
with self.assertRaisesMessage(ValueError, message):
migrations.CreateModel(
"Pony",
@@ -135,7 +142,10 @@ class OperationTests(OperationTestBase):
models.Model,
),
)
- message = "Found duplicate value <class 'migrations.test_operations.Mixin'> in CreateModel bases argument."
+ message = (
+ "Found duplicate value <class 'migrations.test_operations.Mixin'> in "
+ "CreateModel bases argument."
+ )
with self.assertRaisesMessage(ValueError, message):
migrations.CreateModel(
"Pony",
@@ -838,7 +848,8 @@ class OperationTests(OperationTestBase):
.remote_field.model,
new_state.models["test_rmwsc", "rider"].fields["pony"].remote_field.model,
)
- # Before running the migration we have a table for Shetland Pony, not Little Horse
+ # Before running the migration we have a table for Shetland Pony, not
+ # Little Horse.
self.assertTableExists("test_rmwsc_shetlandpony")
self.assertTableNotExists("test_rmwsc_littlehorse")
if connection.features.supports_foreign_keys:
@@ -1734,7 +1745,8 @@ class OperationTests(OperationTestBase):
def test_alter_field_pk(self):
"""
- Tests the AlterField operation on primary keys (for things like PostgreSQL's SERIAL weirdness)
+ The AlterField operation on primary keys (things like PostgreSQL's
+ SERIAL weirdness).
"""
project_state = self.set_up_test_model("test_alflpk")
# Test the state alteration
@@ -2076,7 +2088,7 @@ class OperationTests(OperationTestBase):
self.assertEqual(id_null, fk_null)
@skipUnlessDBFeature("supports_foreign_keys")
- def test_alter_field_reloads_state_on_fk_with_to_field_related_name_target_type_change(
+ def test_alter_field_reloads_state_fk_with_to_field_related_name_target_type_change(
self,
):
app_label = "test_alflrsfkwtflrnttc"
@@ -3240,7 +3252,8 @@ class OperationTests(OperationTestBase):
)
self.assertEqual(
gt_operation.describe(),
- "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from model Pony",
+ "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from "
+ "model Pony",
)
# Test state alteration
new_state = project_state.clone()
@@ -3897,12 +3910,17 @@ class OperationTests(OperationTestBase):
project_state = self.set_up_test_model("test_runsql")
# Create the operation
operation = migrations.RunSQL(
- # Use a multi-line string with a comment to test splitting on SQLite and MySQL respectively
+ # Use a multi-line string with a comment to test splitting on
+ # SQLite and MySQL respectively.
"CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n"
- "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'i love ponies'); -- this is magic!\n"
- "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, 'i love django');\n"
- "UPDATE i_love_ponies SET special_thing = 'Ponies' WHERE special_thing LIKE '%%ponies';"
- "UPDATE i_love_ponies SET special_thing = 'Django' WHERE special_thing LIKE '%django';",
+ "INSERT INTO i_love_ponies (id, special_thing) "
+ "VALUES (1, 'i love ponies'); -- this is magic!\n"
+ "INSERT INTO i_love_ponies (id, special_thing) "
+ "VALUES (2, 'i love django');\n"
+ "UPDATE i_love_ponies SET special_thing = 'Ponies' "
+ "WHERE special_thing LIKE '%%ponies';"
+ "UPDATE i_love_ponies SET special_thing = 'Django' "
+ "WHERE special_thing LIKE '%django';",
# Run delete queries to test for parameter substitution failure
# reported in #23426
"DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';"
@@ -4144,7 +4162,8 @@ class OperationTests(OperationTestBase):
self.assertEqual(definition[1], [])
self.assertEqual(sorted(definition[2]), ["code", "reverse_code"])
- # Also test reversal fails, with an operation identical to above but without reverse_code set
+ # Also test reversal fails, with an operation identical to above but
+ # without reverse_code set.
no_reverse_operation = migrations.RunPython(inner_method)
self.assertFalse(no_reverse_operation.reversible)
with connection.schema_editor() as editor:
diff --git a/tests/migrations/test_optimizer.py b/tests/migrations/test_optimizer.py
index b69563ebab..59dd401a3c 100644
--- a/tests/migrations/test_optimizer.py
+++ b/tests/migrations/test_optimizer.py
@@ -238,9 +238,9 @@ class OptimizerTests(SimpleTestCase):
def test_optimize_through_create(self):
"""
- We should be able to optimize away create/delete through a create or delete
- of a different model, but only if the create operation does not mention the model
- at all.
+ We should be able to optimize away create/delete through a create or
+ delete of a different model, but only if the create operation does not
+ mention the model at all.
"""
# These should work
self.assertOptimizesTo(
diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py
index dfb17ae7d8..25f325246f 100644
--- a/tests/migrations/test_state.py
+++ b/tests/migrations/test_state.py
@@ -957,9 +957,11 @@ class StateTests(SimpleTestCase):
project_state.add_model(ModelState.from_model(Book))
msg = (
"The field migrations.Book.author was declared with a lazy reference "
- "to 'migrations.author', but app 'migrations' doesn't provide model 'author'.\n"
+ "to 'migrations.author', but app 'migrations' doesn't provide model "
+ "'author'.\n"
"The field migrations.Book.publisher was declared with a lazy reference "
- "to 'migrations.publisher', but app 'migrations' doesn't provide model 'publisher'."
+ "to 'migrations.publisher', but app 'migrations' doesn't provide model "
+ "'publisher'."
)
with self.assertRaisesMessage(ValueError, msg):
project_state.apps
@@ -969,9 +971,11 @@ class StateTests(SimpleTestCase):
project_state.add_model(ModelState.from_model(Magazine))
msg = (
"The field migrations.Magazine.authors was declared with a lazy reference "
- "to 'migrations.author', but app 'migrations' doesn't provide model 'author'.\n"
- "The field migrations.Magazine_authors.author was declared with a lazy reference "
- "to 'migrations.author', but app 'migrations' doesn't provide model 'author'."
+ "to 'migrations.author', but app 'migrations' doesn't provide model "
+ "'author'.\n"
+ "The field migrations.Magazine_authors.author was declared with a lazy "
+ "reference to 'migrations.author', but app 'migrations' doesn't provide "
+ "model 'author'."
)
with self.assertRaisesMessage(ValueError, msg):
project_state.apps
@@ -980,13 +984,17 @@ class StateTests(SimpleTestCase):
project_state.add_model(ModelState.from_model(Book))
msg = (
"The field migrations.Book.author was declared with a lazy reference "
- "to 'migrations.author', but app 'migrations' doesn't provide model 'author'.\n"
+ "to 'migrations.author', but app 'migrations' doesn't provide model "
+ "'author'.\n"
"The field migrations.Book.publisher was declared with a lazy reference "
- "to 'migrations.publisher', but app 'migrations' doesn't provide model 'publisher'.\n"
+ "to 'migrations.publisher', but app 'migrations' doesn't provide model "
+ "'publisher'.\n"
"The field migrations.Magazine.authors was declared with a lazy reference "
- "to 'migrations.author', but app 'migrations' doesn't provide model 'author'.\n"
- "The field migrations.Magazine_authors.author was declared with a lazy reference "
- "to 'migrations.author', but app 'migrations' doesn't provide model 'author'."
+ "to 'migrations.author', but app 'migrations' doesn't provide model "
+ "'author'.\n"
+ "The field migrations.Magazine_authors.author was declared with a lazy "
+ "reference to 'migrations.author', but app 'migrations' doesn't provide "
+ "model 'author'."
)
with self.assertRaisesMessage(ValueError, msg):
project_state.apps
diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py
index b0931c9b2d..93a874fc9d 100644
--- a/tests/migrations/test_writer.py
+++ b/tests/migrations/test_writer.py
@@ -624,7 +624,8 @@ class WriterTests(SimpleTestCase):
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(
string,
- "django.core.validators.RegexValidator('^[0-9]+$', flags=re.RegexFlag['DOTALL'])",
+ "django.core.validators.RegexValidator('^[0-9]+$', "
+ "flags=re.RegexFlag['DOTALL'])",
)
self.serialize_round_trip(validator)
@@ -633,7 +634,8 @@ class WriterTests(SimpleTestCase):
string = MigrationWriter.serialize(validator)[0]
self.assertEqual(
string,
- "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', 'invalid')",
+ "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', "
+ "'invalid')",
)
self.serialize_round_trip(validator)
diff --git a/tests/model_fields/test_durationfield.py b/tests/model_fields/test_durationfield.py
index f4e13711d6..2fd9984613 100644
--- a/tests/model_fields/test_durationfield.py
+++ b/tests/model_fields/test_durationfield.py
@@ -51,7 +51,10 @@ class TestQuerying(TestCase):
class TestSerialization(SimpleTestCase):
- test_data = '[{"fields": {"field": "1 01:00:00"}, "model": "model_fields.durationmodel", "pk": null}]'
+ test_data = (
+ '[{"fields": {"field": "1 01:00:00"}, "model": "model_fields.durationmodel", '
+ '"pk": null}]'
+ )
def test_dumping(self):
instance = DurationModel(field=datetime.timedelta(days=1, hours=1))
diff --git a/tests/model_fields/test_foreignkey.py b/tests/model_fields/test_foreignkey.py
index 2c15dea720..a5b646ae86 100644
--- a/tests/model_fields/test_foreignkey.py
+++ b/tests/model_fields/test_foreignkey.py
@@ -40,8 +40,12 @@ class ForeignKeyTests(TestCase):
model = FKUniqueTrue()
expected_warnings = [
checks.Warning(
- "Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.",
- hint="ForeignKey(unique=True) is usually better served by a OneToOneField.",
+ "Setting unique=True on a ForeignKey has the same effect as using a "
+ "OneToOneField.",
+ hint=(
+ "ForeignKey(unique=True) is usually better served by a "
+ "OneToOneField."
+ ),
obj=FKUniqueTrue.fk_field.field,
id="fields.W342",
)
diff --git a/tests/model_forms/test_modelchoicefield.py b/tests/model_forms/test_modelchoicefield.py
index 8c3909f8a8..1ecba4437e 100644
--- a/tests/model_forms/test_modelchoicefield.py
+++ b/tests/model_forms/test_modelchoicefield.py
@@ -56,7 +56,10 @@ class ModelChoiceFieldTests(TestCase):
# instantiated. This proves clean() checks the database during clean()
# rather than caching it at instantiation time.
Category.objects.get(url="4th").delete()
- msg = "['Select a valid choice. That choice is not one of the available choices.']"
+ msg = (
+ "['Select a valid choice. That choice is not one of the available "
+ "choices.']"
+ )
with self.assertRaisesMessage(ValidationError, msg):
f.clean(c4.id)
@@ -64,7 +67,10 @@ class ModelChoiceFieldTests(TestCase):
f = forms.ModelChoiceField(Category.objects.all())
self.assertEqual(f.clean(self.c1), self.c1)
# An instance of incorrect model.
- msg = "['Select a valid choice. That choice is not one of the available choices.']"
+ msg = (
+ "['Select a valid choice. That choice is not one of the available "
+ "choices.']"
+ )
with self.assertRaisesMessage(ValidationError, msg):
f.clean(Book.objects.create())
@@ -379,11 +385,18 @@ class ModelChoiceFieldTests(TestCase):
field = CustomModelMultipleChoiceField(Category.objects.all())
self.assertHTMLEqual(
field.widget.render("name", []),
- """<div>
-<div><label><input type="checkbox" name="name" value="%d" data-slug="entertainment">Entertainment</label></div>
-<div><label><input type="checkbox" name="name" value="%d" data-slug="test">A test</label></div>
-<div><label><input type="checkbox" name="name" value="%d" data-slug="third-test">Third</label></div>
-</div>"""
+ """
+ <div><div>
+ <label><input type="checkbox" name="name" value="%d"
+ data-slug="entertainment">Entertainment
+ </label></div>
+ <div><label>
+ <input type="checkbox" name="name" value="%d" data-slug="test">A test
+ </label></div>
+ <div><label>
+ <input type="checkbox" name="name" value="%d" data-slug="third-test">Third
+ </label></div></div>
+ """
% (self.c1.pk, self.c2.pk, self.c3.pk),
)
diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
index 096c3aae63..a615d4516d 100644
--- a/tests/model_forms/tests.py
+++ b/tests/model_forms/tests.py
@@ -251,7 +251,8 @@ class ModelFormBaseTest(TestCase):
def test_empty_fields_to_construct_instance(self):
"""
- No fields should be set on a model instance if construct_instance receives fields=().
+ No fields should be set on a model instance if construct_instance
+ receives fields=().
"""
form = modelform_factory(Person, fields="__all__")({"name": "John Doe"})
self.assertTrue(form.is_valid())
@@ -498,8 +499,11 @@ class ModelFormBaseTest(TestCase):
fields = ["nonexistent"]
def test_limit_fields_with_string(self):
- expected_msg = "CategoryForm.Meta.fields cannot be a string. Did you mean to type: ('url',)?"
- with self.assertRaisesMessage(TypeError, expected_msg):
+ msg = (
+ "CategoryForm.Meta.fields cannot be a string. Did you mean to type: "
+ "('url',)?"
+ )
+ with self.assertRaisesMessage(TypeError, msg):
class CategoryForm(forms.ModelForm):
class Meta:
@@ -523,8 +527,11 @@ class ModelFormBaseTest(TestCase):
self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug", "url"])
def test_exclude_fields_with_string(self):
- expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?"
- with self.assertRaisesMessage(TypeError, expected_msg):
+ msg = (
+ "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: "
+ "('url',)?"
+ )
+ with self.assertRaisesMessage(TypeError, msg):
class CategoryForm(forms.ModelForm):
class Meta:
@@ -923,11 +930,13 @@ class TestFieldOverridesByFormMeta(SimpleTestCase):
form = FieldOverridesByFormMetaForm()
self.assertHTMLEqual(
str(form["name"]),
- '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" required></textarea>',
+ '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" '
+ "required></textarea>",
)
self.assertHTMLEqual(
str(form["url"]),
- '<input id="id_url" type="text" class="url" name="url" maxlength="40" required>',
+ '<input id="id_url" type="text" class="url" name="url" maxlength="40" '
+ "required>",
)
self.assertHTMLEqual(
str(form["slug"]),
@@ -1380,7 +1389,9 @@ class UniqueTest(TestCase):
class Meta(PriceForm.Meta):
error_messages = {
NON_FIELD_ERRORS: {
- "unique_together": "%(model_name)s's %(field_labels)s not unique.",
+ "unique_together": (
+ "%(model_name)s's %(field_labels)s not unique."
+ ),
}
}
@@ -1446,9 +1457,14 @@ class ModelFormBasicTests(TestCase):
)
self.assertHTMLEqual(
str(f.as_ul()),
- """<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" required></li>
-<li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" required></li>
-<li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" required></li>""",
+ """
+ <li><label for="id_name">Name:</label>
+ <input id="id_name" type="text" name="name" maxlength="20" required></li>
+ <li><label for="id_slug">Slug:</label>
+ <input id="id_slug" type="text" name="slug" maxlength="20" required></li>
+ <li><label for="id_url">The URL:</label>
+ <input id="id_url" type="text" name="url" maxlength="40" required></li>
+ """,
)
self.assertHTMLEqual(
str(f["name"]),
@@ -1476,26 +1492,32 @@ class ModelFormBasicTests(TestCase):
)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" required></li>
-<li>Writer: <select name="writer" required>
-<option value="" selected>---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></li>
-<li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li>
-<li>Categories: <select multiple name="categories">
-<option value="%s" selected>Entertainment</option>
-<option value="%s" selected>It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></li>
-<li>Status: <select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></li>"""
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="Your headline here" maxlength="50"
+ required>
+ </li>
+ <li>Slug: <input type="text" name="slug" maxlength="50" required></li>
+ <li>Pub date: <input type="text" name="pub_date" required></li>
+ <li>Writer: <select name="writer" required>
+ <option value="" selected>---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></li>
+ <li>Article:
+ <textarea rows="10" cols="40" name="article" required></textarea></li>
+ <li>Categories: <select multiple name="categories">
+ <option value="%s" selected>Entertainment</option>
+ <option value="%s" selected>It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></li>
+ <li>Status: <select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></li>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -1504,8 +1526,12 @@ class ModelFormBasicTests(TestCase):
f = RoykoForm(auto_id=False, instance=self.w_royko)
self.assertHTMLEqual(
str(f),
- """<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" required><br>
- <span class="helptext">Use both first and last names.</span></td></tr>""",
+ """
+ <tr><th>Name:</th><td>
+ <input type="text" name="name" value="Mike Royko" maxlength="50" required>
+ <br>
+ <span class="helptext">Use both first and last names.</span></td></tr>
+ """,
)
art = Article.objects.create(
@@ -1520,26 +1546,35 @@ class ModelFormBasicTests(TestCase):
f = ArticleForm(auto_id=False, instance=art)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>
-<li>Writer: <select name="writer" required>
-<option value="">---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s" selected>Mike Royko</option>
-</select></li>
-<li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
-<li>Categories: <select multiple name="categories">
-<option value="%s">Entertainment</option>
-<option value="%s">It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></li>
-<li>Status: <select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></li>"""
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="Test article" maxlength="50"
+ required>
+ </li>
+ <li>Slug:
+ <input type="text" name="slug" value="test-article" maxlength="50" required>
+ </li>
+ <li>Pub date:
+ <input type="text" name="pub_date" value="1988-01-04" required></li>
+ <li>Writer: <select name="writer" required>
+ <option value="">---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s" selected>Mike Royko</option>
+ </select></li>
+ <li>Article:
+ <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
+ <li>Categories: <select multiple name="categories">
+ <option value="%s">Entertainment</option>
+ <option value="%s">It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></li>
+ <li>Status: <select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></li>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -1562,7 +1597,7 @@ class ModelFormBasicTests(TestCase):
def test_m2m_initial_callable(self):
"""
- Regression for #10349: A callable can be provided as the initial value for an m2m field
+ A callable can be provided as the initial value for an m2m field.
"""
self.maxDiff = 1200
self.create_basic_data()
@@ -1635,7 +1670,8 @@ class ModelFormBasicTests(TestCase):
self.assertEqual(
f.errors["slug"],
[
- "Enter a valid “slug” consisting of letters, numbers, underscores or hyphens."
+ "Enter a valid “slug” consisting of letters, numbers, underscores or "
+ "hyphens."
],
)
self.assertEqual(f.cleaned_data, {"url": "foo"})
@@ -1654,26 +1690,32 @@ class ModelFormBasicTests(TestCase):
f = ArticleForm(auto_id=False)
self.assertHTMLEqual(
str(f),
- """<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr>
-<tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" required></td></tr>
-<tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr>
-<tr><th>Writer:</th><td><select name="writer" required>
-<option value="" selected>---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></td></tr>
-<tr><th>Article:</th><td><textarea rows="10" cols="40" name="article" required></textarea></td></tr>
-<tr><th>Categories:</th><td><select multiple name="categories">
-<option value="%s">Entertainment</option>
-<option value="%s">It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></td></tr>
-<tr><th>Status:</th><td><select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></td></tr>"""
+ """
+ <tr><th>Headline:</th><td>
+ <input type="text" name="headline" maxlength="50" required></td></tr>
+ <tr><th>Slug:</th><td>
+ <input type="text" name="slug" maxlength="50" required></td></tr>
+ <tr><th>Pub date:</th><td>
+ <input type="text" name="pub_date" required></td></tr>
+ <tr><th>Writer:</th><td><select name="writer" required>
+ <option value="" selected>---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></td></tr>
+ <tr><th>Article:</th><td>
+ <textarea rows="10" cols="40" name="article" required></textarea></td></tr>
+ <tr><th>Categories:</th><td><select multiple name="categories">
+ <option value="%s">Entertainment</option>
+ <option value="%s">It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></td></tr>
+ <tr><th>Status:</th><td><select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></td></tr>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -1690,26 +1732,35 @@ class ModelFormBasicTests(TestCase):
f = ArticleForm(auto_id=False, instance=new_art)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>
-<li>Writer: <select name="writer" required>
-<option value="">---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s" selected>Mike Royko</option>
-</select></li>
-<li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
-<li>Categories: <select multiple name="categories">
-<option value="%s" selected>Entertainment</option>
-<option value="%s">It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></li>
-<li>Status: <select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></li>"""
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="New headline" maxlength="50"
+ required>
+ </li>
+ <li>Slug:
+ <input type="text" name="slug" value="new-headline" maxlength="50" required>
+ </li>
+ <li>Pub date:
+ <input type="text" name="pub_date" value="1988-01-04" required></li>
+ <li>Writer: <select name="writer" required>
+ <option value="">---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s" selected>Mike Royko</option>
+ </select></li>
+ <li>Article:
+ <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
+ <li>Categories: <select multiple name="categories">
+ <option value="%s" selected>Entertainment</option>
+ <option value="%s">It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></li>
+ <li>Status: <select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></li>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -1728,8 +1779,12 @@ class ModelFormBasicTests(TestCase):
f = PartialArticleForm(auto_id=False)
self.assertHTMLEqual(
str(f),
- """<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr>
-<tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr>""",
+ """
+ <tr><th>Headline:</th><td>
+ <input type="text" name="headline" maxlength="50" required></td></tr>
+ <tr><th>Pub date:</th><td>
+ <input type="text" name="pub_date" required></td></tr>
+ """,
)
class PartialArticleFormWithSlug(forms.ModelForm):
@@ -1756,9 +1811,18 @@ class ModelFormBasicTests(TestCase):
)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>""",
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="New headline" maxlength="50"
+ required>
+ </li>
+ <li>Slug:
+ <input type="text" name="slug" value="new-headline" maxlength="50"
+ required>
+ </li>
+ <li>Pub date:
+ <input type="text" name="pub_date" value="1988-01-04" required></li>
+ """,
)
self.assertTrue(f.is_valid())
new_art = f.save()
@@ -1785,7 +1849,8 @@ class ModelFormBasicTests(TestCase):
new_art.categories.order_by("name"), [self.c1, self.c2]
)
- # Now, submit form data with no categories. This deletes the existing categories.
+ # Now, submit form data with no categories. This deletes the existing
+ # categories.
form_data["categories"] = []
f = ArticleForm(form_data, instance=new_art)
new_art = f.save()
@@ -1823,9 +1888,9 @@ class ModelFormBasicTests(TestCase):
)
def test_custom_form_fields(self):
- # Here, we define a custom ModelForm. Because it happens to have the same fields as
- # the Category model, we can just call the form's save() to apply its changes to an
- # existing Category instance.
+ # Here, we define a custom ModelForm. Because it happens to have the
+ # same fields as the Category model, we can just call the form's save()
+ # to apply its changes to an existing Category instance.
class ShortCategory(forms.ModelForm):
name = forms.CharField(max_length=5)
slug = forms.CharField(max_length=5)
@@ -1949,7 +2014,8 @@ class ModelFormBasicTests(TestCase):
form.errors,
{
"writer": [
- "Select a valid choice. That choice is not one of the available choices."
+ "Select a valid choice. That choice is not one of the available "
+ "choices."
]
},
)
@@ -2222,7 +2288,8 @@ class ModelOneToOneFieldTests(TestCase):
def test_modelform_subclassed_model(self):
class BetterWriterForm(forms.ModelForm):
class Meta:
- # BetterWriter model is a subclass of Writer with an additional `score` field
+ # BetterWriter model is a subclass of Writer with an additional
+ # `score` field.
model = BetterWriter
fields = "__all__"
@@ -2259,12 +2326,16 @@ class ModelOneToOneFieldTests(TestCase):
form = WriterProfileForm()
self.assertHTMLEqual(
form.as_p(),
- """<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required>
-<option value="" selected>---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></p>
-<p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" required></p>"""
+ """
+ <p><label for="id_writer">Writer:</label>
+ <select name="writer" id="id_writer" required>
+ <option value="" selected>---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></p>
+ <p><label for="id_age">Age:</label>
+ <input type="number" name="age" id="id_age" min="0" required></p>
+ """
% (
self.w_woodward.pk,
self.w_royko.pk,
@@ -2282,13 +2353,16 @@ class ModelOneToOneFieldTests(TestCase):
form = WriterProfileForm(instance=instance)
self.assertHTMLEqual(
form.as_p(),
- """<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required>
-<option value="">---------</option>
-<option value="%s" selected>Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></p>
-<p><label for="id_age">Age:</label>
-<input type="number" name="age" value="65" id="id_age" min="0" required></p>"""
+ """
+ <p><label for="id_writer">Writer:</label>
+ <select name="writer" id="id_writer" required>
+ <option value="">---------</option>
+ <option value="%s" selected>Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></p>
+ <p><label for="id_age">Age:</label>
+ <input type="number" name="age" value="65" id="id_age" min="0" required>
+ </p>"""
% (
self.w_woodward.pk,
self.w_royko.pk,
@@ -2496,7 +2570,8 @@ class FileAndImageFieldTests(TestCase):
instance = f.save()
self.assertEqual(instance.file.name, "tests/test3.txt")
- # Instance can be edited w/out re-uploading the file and existing file should be preserved.
+ # Instance can be edited w/out re-uploading the file and existing file
+ # should be preserved.
f = TextFileForm({"description": "New Description"}, instance=instance)
f.fields["file"].required = False
self.assertTrue(f.is_valid())
@@ -2603,8 +2678,9 @@ class FileAndImageFieldTests(TestCase):
self.assertEqual(instance.width, 16)
self.assertEqual(instance.height, 16)
- # Edit an instance that already has the (required) image defined in the model. This will not
- # save the image again, but leave it exactly as it is.
+ # Edit an instance that already has the (required) image defined in the
+ # model. This will not save the image again, but leave it exactly as it
+ # is.
f = ImageFileForm(data={"description": "Look, it changed"}, instance=instance)
self.assertTrue(f.is_valid())
@@ -2700,7 +2776,8 @@ class FileAndImageFieldTests(TestCase):
self.assertEqual(instance.width, 48)
self.assertEqual(instance.height, 32)
instance.delete()
- # Test callable upload_to behavior that's dependent on the value of another field in the model
+ # Callable upload_to behavior that's dependent on the value of another
+ # field in the model.
f = ImageFileForm(
data={"description": "And a final one", "path": "foo"},
files={"image": SimpleUploadedFile("test4.png", image_data)},
@@ -2736,7 +2813,8 @@ class ModelOtherFieldTests(SimpleTestCase):
bif.errors,
{
"biggie": [
- "Ensure this value is greater than or equal to -9223372036854775808."
+ "Ensure this value is greater than or equal to "
+ "-9223372036854775808."
]
},
)
@@ -2785,7 +2863,10 @@ class ModelOtherFieldTests(SimpleTestCase):
# 'created', non-editable, is excluded by default
self.assertNotIn("created", ArticleForm().fields)
- msg = "'created' cannot be specified for Article model form as it is a non-editable field"
+ msg = (
+ "'created' cannot be specified for Article model form as it is a "
+ "non-editable field"
+ )
with self.assertRaisesMessage(FieldError, msg):
class InvalidArticleForm(forms.ModelForm):
@@ -2795,7 +2876,7 @@ class ModelOtherFieldTests(SimpleTestCase):
def test_http_prefixing(self):
"""
- If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613)
+ If the http:// prefix is omitted on form input, the field adds it again.
"""
class HomepageForm(forms.ModelForm):
@@ -2936,11 +3017,15 @@ class OtherModelFormTests(TestCase):
self.maxDiff = 1024
self.assertHTMLEqual(
form.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" required></p>
- <p><label for="id_colours">Colours:</label>
- <select multiple name="colours" id="id_colours" required>
- <option value="%(blue_pk)s">Blue</option>
- </select></p>"""
+ """
+ <p>
+ <label for="id_name">Name:</label>
+ <input id="id_name" type="text" name="name" maxlength="50" required></p>
+ <p><label for="id_colours">Colours:</label>
+ <select multiple name="colours" id="id_colours" required>
+ <option value="%(blue_pk)s">Blue</option>
+ </select></p>
+ """
% {"blue_pk": colour.pk},
)
@@ -2957,19 +3042,27 @@ class OtherModelFormTests(TestCase):
form.as_p(),
"""
<p><label for="id_title">Title:</label>
- <input id="id_title" maxlength="30" name="title" type="text" required></p>
+ <input id="id_title" maxlength="30" name="title" type="text" required>
+ </p>
<p><label for="id_date_published">Date published:</label>
- <input id="id_date_published" name="date_published" type="text" value="{0}" required>
- <input id="initial-id_date_published" name="initial-date_published" type="hidden" value="{0}"></p>
+ <input id="id_date_published" name="date_published" type="text" value="{0}"
+ required>
+ <input id="initial-id_date_published" name="initial-date_published"
+ type="hidden" value="{0}">
+ </p>
<p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode">
- <option value="di" selected>direct</option>
- <option value="de">delayed</option></select>
- <input id="initial-id_mode" name="initial-mode" type="hidden" value="di"></p>
- <p><label for="id_category">Category:</label> <select id="id_category" name="category">
- <option value="1">Games</option>
- <option value="2">Comics</option>
- <option value="3" selected>Novel</option></select>
- <input id="initial-id_category" name="initial-category" type="hidden" value="3">
+ <option value="di" selected>direct</option>
+ <option value="de">delayed</option></select>
+ <input id="initial-id_mode" name="initial-mode" type="hidden" value="di">
+ </p>
+ <p>
+ <label for="id_category">Category:</label>
+ <select id="id_category" name="category">
+ <option value="1">Games</option>
+ <option value="2">Comics</option>
+ <option value="3" selected>Novel</option></select>
+ <input id="initial-id_category" name="initial-category" type="hidden"
+ value="3">
""".format(
today_str
),
@@ -3013,7 +3106,8 @@ class ModelFormCustomErrorTests(SimpleTestCase):
self.assertFalse(form.is_valid())
self.assertHTMLEqual(
str(form.errors["name1"]),
- '<ul class="errorlist"><li>Model.clean() error messages (simpler syntax).</li></ul>',
+ '<ul class="errorlist">'
+ "<li>Model.clean() error messages (simpler syntax).</li></ul>",
)
data = {"name1": "GLOBAL_ERROR", "name2": "ABC"}
form = CustomErrorMessageForm(data)
@@ -3289,7 +3383,9 @@ class LimitChoicesToTests(TestCase):
class FormFieldCallbackTests(SimpleTestCase):
def test_baseform_with_widgets_in_meta(self):
- """Regression for #13095: Using base forms with widgets defined in Meta should not raise errors."""
+ """
+ Using base forms with widgets defined in Meta should not raise errors.
+ """
widget = forms.Textarea()
class BaseForm(forms.ModelForm):
diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py
index f10a7d92db..b2b0976a2b 100644
--- a/tests/model_formsets/tests.py
+++ b/tests/model_formsets/tests.py
@@ -189,7 +189,7 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_form-2-name">Name:</label>'
- ' <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">'
+ '<input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">'
'<input type="hidden" name="form-2-id" id="id_form-2-id"></p>',
)
@@ -229,14 +229,16 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_form-0-name">Name:</label>'
- '<input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100">'
+ '<input id="id_form-0-name" type="text" name="form-0-name" '
+ 'value="Arthur Rimbaud" maxlength="100">'
'<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id"></p>'
% author2.id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_form-1-name">Name:</label>'
- '<input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100">'
+ '<input id="id_form-1-name" type="text" name="form-1-name" '
+ 'value="Charles Baudelaire" maxlength="100">'
'<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id"></p>'
% author1.id,
)
@@ -313,8 +315,8 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[3].as_p(),
'<p><label for="id_form-3-name">Name:</label>'
- '<input id="id_form-3-name" type="text" name="form-3-name" maxlength="100"></p>'
- '<p><label for="id_form-3-DELETE">Delete:</label>'
+ '<input id="id_form-3-name" type="text" name="form-3-name" maxlength="100">'
+ '</p><p><label for="id_form-3-DELETE">Delete:</label>'
'<input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE">'
'<input type="hidden" name="form-3-id" id="id_form-3-id"></p>',
)
@@ -565,10 +567,11 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_form-0-name">Name:</label>'
- '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100"></p>'
- '<p><label for="id_form-0-write_speed">Write speed:</label>'
+ '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100">'
+ '</p><p><label for="id_form-0-write_speed">Write speed:</label>'
'<input type="number" name="form-0-write_speed" id="id_form-0-write_speed">'
- '<input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr"></p>',
+ '<input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr">'
+ "</p>",
)
data = {
@@ -593,19 +596,22 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_form-0-name">Name:</label>'
- '<input id="id_form-0-name" type="text" name="form-0-name" value="Ernest Hemingway" maxlength="100"></p>'
+ '<input id="id_form-0-name" type="text" name="form-0-name" '
+ 'value="Ernest Hemingway" maxlength="100"></p>'
'<p><label for="id_form-0-write_speed">Write speed:</label>'
- '<input type="number" name="form-0-write_speed" value="10" id="id_form-0-write_speed">'
- '<input type="hidden" name="form-0-author_ptr" value="%d" id="id_form-0-author_ptr"></p>'
- % hemingway_id,
+ '<input type="number" name="form-0-write_speed" value="10" '
+ 'id="id_form-0-write_speed">'
+ '<input type="hidden" name="form-0-author_ptr" value="%d" '
+ 'id="id_form-0-author_ptr"></p>' % hemingway_id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_form-1-name">Name:</label>'
- '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100"></p>'
- '<p><label for="id_form-1-write_speed">Write speed:</label>'
+ '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100">'
+ '</p><p><label for="id_form-1-write_speed">Write speed:</label>'
'<input type="number" name="form-1-write_speed" id="id_form-1-write_speed">'
- '<input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr"></p>',
+ '<input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr">'
+ "</p>",
)
data = {
@@ -637,24 +643,31 @@ class ModelFormsetTest(TestCase):
self.assertEqual(len(formset.forms), 3)
self.assertHTMLEqual(
formset.forms[0].as_p(),
- '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" '
- 'name="book_set-0-title" maxlength="100"><input type="hidden" name="book_set-0-author" value="%d" '
- 'id="id_book_set-0-author"><input type="hidden" name="book_set-0-id" id="id_book_set-0-id">'
+ '<p><label for="id_book_set-0-title">Title:</label>'
+ '<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-0-author" value="%d" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" id="id_book_set-0-id">'
"</p>" % author.id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
- '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">'
+ '<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-1-author" value="%d" '
+ 'id="id_book_set-1-author">'
'<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>'
% author.id,
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
- '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">'
+ '<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-2-author" value="%d" '
+ 'id="id_book_set-2-author">'
'<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>'
% author.id,
)
@@ -693,8 +706,10 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_book_set-0-title">Title:</label>'
'<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
'value="Les Fleurs du Mal" maxlength="100">'
- '<input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author">'
- '<input type="hidden" name="book_set-0-id" value="%d" id="id_book_set-0-id"></p>'
+ '<input type="hidden" name="book_set-0-author" value="%d" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" value="%d" '
+ 'id="id_book_set-0-id"></p>'
% (
author.id,
book1.id,
@@ -703,16 +718,20 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
- '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">'
+ '<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-1-author" value="%d" '
+ 'id="id_book_set-1-author">'
'<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>'
% author.id,
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
- '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">'
+ '<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-2-author" value="%d" '
+ 'id="id_book_set-2-author">'
'<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>'
% author.id,
)
@@ -782,7 +801,8 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_test-0-title">Title:</label>'
- '<input id="id_test-0-title" type="text" name="test-0-title" maxlength="100">'
+ '<input id="id_test-0-title" type="text" name="test-0-title" '
+ 'maxlength="100">'
'<input type="hidden" name="test-0-author" id="id_test-0-author">'
'<input type="hidden" name="test-0-id" id="id_test-0-id"></p>',
)
@@ -790,7 +810,8 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_test-1-title">Title:</label>'
- '<input id="id_test-1-title" type="text" name="test-1-title" maxlength="100">'
+ '<input id="id_test-1-title" type="text" name="test-1-title" '
+ 'maxlength="100">'
'<input type="hidden" name="test-1-author" id="id_test-1-author">'
'<input type="hidden" name="test-1-id" id="id_test-1-id"></p>',
)
@@ -820,9 +841,12 @@ class ModelFormsetTest(TestCase):
)
data = {
- "bookwithcustompk_set-TOTAL_FORMS": "1", # the number of forms rendered
- "bookwithcustompk_set-INITIAL_FORMS": "0", # the number of forms with initial data
- "bookwithcustompk_set-MAX_NUM_FORMS": "", # the max number of forms
+ # The number of forms rendered.
+ "bookwithcustompk_set-TOTAL_FORMS": "1",
+ # The number of forms with initial data.
+ "bookwithcustompk_set-INITIAL_FORMS": "0",
+ # The max number of forms.
+ "bookwithcustompk_set-MAX_NUM_FORMS": "",
"bookwithcustompk_set-0-my_pk": "77777",
"bookwithcustompk_set-0-title": "Les Fleurs du Mal",
}
@@ -864,9 +888,12 @@ class ModelFormsetTest(TestCase):
)
data = {
- "alternatebook_set-TOTAL_FORMS": "1", # the number of forms rendered
- "alternatebook_set-INITIAL_FORMS": "0", # the number of forms with initial data
- "alternatebook_set-MAX_NUM_FORMS": "", # the max number of forms
+ # The number of forms rendered.
+ "alternatebook_set-TOTAL_FORMS": "1",
+ # The number of forms with initial data.
+ "alternatebook_set-INITIAL_FORMS": "0",
+ # The max number of forms.
+ "alternatebook_set-MAX_NUM_FORMS": "",
"alternatebook_set-0-title": "Flowers of Evil",
"alternatebook_set-0-notes": "English translation of Les Fleurs du Mal",
}
@@ -895,9 +922,12 @@ class ModelFormsetTest(TestCase):
author = Author.objects.create(pk=1, name="Charles Baudelaire")
data = {
- "bookwithoptionalalteditor_set-TOTAL_FORMS": "2", # the number of forms rendered
- "bookwithoptionalalteditor_set-INITIAL_FORMS": "0", # the number of forms with initial data
- "bookwithoptionalalteditor_set-MAX_NUM_FORMS": "", # the max number of forms
+ # The number of forms rendered.
+ "bookwithoptionalalteditor_set-TOTAL_FORMS": "2",
+ # The number of forms with initial data.
+ "bookwithoptionalalteditor_set-INITIAL_FORMS": "0",
+ # The max number of forms.
+ "bookwithoptionalalteditor_set-MAX_NUM_FORMS": "",
"bookwithoptionalalteditor_set-0-author": "1",
"bookwithoptionalalteditor_set-0-title": "Les Fleurs du Mal",
"bookwithoptionalalteditor_set-1-author": "1",
@@ -965,37 +995,47 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_book_set-0-title">Title:</label>'
'<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
'value="Les Paradis Artificiels" maxlength="100">'
- '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">'
- '<input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id"></p>',
+ '<input type="hidden" name="book_set-0-author" value="1" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id">'
+ "</p>",
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
'<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
'value="Les Fleurs du Mal" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">'
- '<input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id"></p>',
+ '<input type="hidden" name="book_set-1-author" value="1" '
+ 'id="id_book_set-1-author">'
+ '<input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id">'
+ "</p>",
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
'<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
'value="Flowers of Evil" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">'
- '<input type="hidden" name="book_set-2-id" value="3" id="id_book_set-2-id"></p>',
+ '<input type="hidden" name="book_set-2-author" value="1" '
+ 'id="id_book_set-2-author">'
+ '<input type="hidden" name="book_set-2-id" value="3" '
+ 'id="id_book_set-2-id"></p>',
)
self.assertHTMLEqual(
formset.forms[3].as_p(),
'<p><label for="id_book_set-3-title">Title:</label>'
- '<input id="id_book_set-3-title" type="text" name="book_set-3-title" maxlength="100">'
- '<input type="hidden" name="book_set-3-author" value="1" id="id_book_set-3-author">'
+ '<input id="id_book_set-3-title" type="text" name="book_set-3-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-3-author" value="1" '
+ 'id="id_book_set-3-author">'
'<input type="hidden" name="book_set-3-id" id="id_book_set-3-id"></p>',
)
self.assertHTMLEqual(
formset.forms[4].as_p(),
'<p><label for="id_book_set-4-title">Title:</label>'
- '<input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100">'
- '<input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author">'
+ '<input id="id_book_set-4-title" type="text" name="book_set-4-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-4-author" value="1" '
+ 'id="id_book_set-4-author">'
'<input type="hidden" name="book_set-4-id" id="id_book_set-4-id"></p>',
)
@@ -1022,21 +1062,27 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_book_set-0-title">Title:</label>'
'<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
'value="Flowers of Evil" maxlength="100">'
- '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">'
- '<input type="hidden" name="book_set-0-id" value="3" id="id_book_set-0-id"></p>',
+ '<input type="hidden" name="book_set-0-author" value="1" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" value="3" '
+ 'id="id_book_set-0-id"></p>',
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
- '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">'
+ '<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-1-author" value="1" '
+ 'id="id_book_set-1-author">'
'<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>',
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
- '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">'
+ '<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-2-author" value="1" '
+ 'id="id_book_set-2-author">'
'<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>',
)
@@ -1103,10 +1149,12 @@ class ModelFormsetTest(TestCase):
self.assertEqual(len(formset.forms), 1)
self.assertHTMLEqual(
formset.forms[0].as_p(),
- '<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" '
- 'name="form-0-my_pk" maxlength="10"></p>'
+ '<p><label for="id_form-0-my_pk">My pk:</label>'
+ '<input id="id_form-0-my_pk" type="text" name="form-0-my_pk" '
+ 'maxlength="10"></p>'
'<p><label for="id_form-0-some_field">Some field:</label>'
- '<input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100"></p>',
+ '<input id="id_form-0-some_field" type="text" name="form-0-some_field" '
+ 'maxlength="100"></p>',
)
# Custom primary keys with ForeignKey, OneToOneField and AutoField ############
@@ -1121,16 +1169,22 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_owner_set-0-name">Name:</label>'
- '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" maxlength="100">'
- '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">'
- '<input type="hidden" name="owner_set-0-auto_id" id="id_owner_set-0-auto_id"></p>',
+ '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-0-place" value="1" '
+ 'id="id_owner_set-0-place">'
+ '<input type="hidden" name="owner_set-0-auto_id" '
+ 'id="id_owner_set-0-auto_id"></p>',
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_owner_set-1-name">Name:</label>'
- '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">'
- '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">'
- '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>',
+ '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-1-place" value="1" '
+ 'id="id_owner_set-1-place">'
+ '<input type="hidden" name="owner_set-1-auto_id" '
+ 'id="id_owner_set-1-auto_id"></p>',
)
data = {
@@ -1155,24 +1209,32 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_owner_set-0-name">Name:</label>'
- '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" value="Joe Perry" maxlength="100">'
- '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">'
- '<input type="hidden" name="owner_set-0-auto_id" value="%d" id="id_owner_set-0-auto_id"></p>'
- % owner1.auto_id,
+ '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" '
+ 'value="Joe Perry" maxlength="100">'
+ '<input type="hidden" name="owner_set-0-place" value="1" '
+ 'id="id_owner_set-0-place">'
+ '<input type="hidden" name="owner_set-0-auto_id" value="%d" '
+ 'id="id_owner_set-0-auto_id"></p>' % owner1.auto_id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_owner_set-1-name">Name:</label>'
- '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">'
- '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">'
- '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>',
+ '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-1-place" value="1" '
+ 'id="id_owner_set-1-place">'
+ '<input type="hidden" name="owner_set-1-auto_id" '
+ 'id="id_owner_set-1-auto_id"></p>',
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_owner_set-2-name">Name:</label>'
- '<input id="id_owner_set-2-name" type="text" name="owner_set-2-name" maxlength="100">'
- '<input type="hidden" name="owner_set-2-place" value="1" id="id_owner_set-2-place">'
- '<input type="hidden" name="owner_set-2-auto_id" id="id_owner_set-2-auto_id"></p>',
+ '<input id="id_owner_set-2-name" type="text" name="owner_set-2-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-2-place" value="1" '
+ 'id="id_owner_set-2-place">'
+ '<input type="hidden" name="owner_set-2-auto_id" '
+ 'id="id_owner_set-2-auto_id"></p>',
)
data = {
@@ -1194,8 +1256,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(owner2.name, "Jack Berry")
self.assertEqual(owner2.place.name, "Giordanos")
- # Ensure a custom primary key that is a ForeignKey or OneToOneField get rendered for the user to choose.
-
+ # A custom primary key that is a ForeignKey or OneToOneField get
+ # rendered for the user to choose.
FormSet = modelformset_factory(OwnerProfile, fields="__all__")
formset = FormSet()
self.assertHTMLEqual(
@@ -1222,9 +1284,10 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_ownerprofile-0-age">Age:</label>'
- '<input type="number" name="ownerprofile-0-age" id="id_ownerprofile-0-age" min="0">'
- '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>'
- % owner1.auto_id,
+ '<input type="number" name="ownerprofile-0-age" '
+ 'id="id_ownerprofile-0-age" min="0">'
+ '<input type="hidden" name="ownerprofile-0-owner" value="%d" '
+ 'id="id_ownerprofile-0-owner"></p>' % owner1.auto_id,
)
data = {
@@ -1247,9 +1310,10 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_ownerprofile-0-age">Age:</label>'
- '<input type="number" name="ownerprofile-0-age" value="54" id="id_ownerprofile-0-age" min="0">'
- '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>'
- % owner1.auto_id,
+ '<input type="number" name="ownerprofile-0-age" value="54" '
+ 'id="id_ownerprofile-0-age" min="0">'
+ '<input type="hidden" name="ownerprofile-0-owner" value="%d" '
+ 'id="id_ownerprofile-0-owner"></p>' % owner1.auto_id,
)
data = {
@@ -1282,11 +1346,15 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_location_set-0-lat">Lat:</label>'
- '<input id="id_location_set-0-lat" type="text" name="location_set-0-lat" maxlength="100"></p>'
- '<p><label for="id_location_set-0-lon">Lon:</label> '
- '<input id="id_location_set-0-lon" type="text" name="location_set-0-lon" maxlength="100">'
- '<input type="hidden" name="location_set-0-place" value="1" id="id_location_set-0-place">'
- '<input type="hidden" name="location_set-0-id" id="id_location_set-0-id"></p>',
+ '<input id="id_location_set-0-lat" type="text" name="location_set-0-lat" '
+ 'maxlength="100"></p>'
+ '<p><label for="id_location_set-0-lon">Lon:</label>'
+ '<input id="id_location_set-0-lon" type="text" name="location_set-0-lon" '
+ 'maxlength="100">'
+ '<input type="hidden" name="location_set-0-place" value="1" '
+ 'id="id_location_set-0-place">'
+ '<input type="hidden" name="location_set-0-id" '
+ 'id="id_location_set-0-id"></p>',
)
def test_foreign_keys_in_parents(self):
@@ -1511,13 +1579,16 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_membership_set-0-date_joined">Date joined:</label>'
'<input type="text" name="membership_set-0-date_joined" '
'value="__DATETIME__" id="id_membership_set-0-date_joined">'
- '<input type="hidden" name="initial-membership_set-0-date_joined" value="__DATETIME__" '
+ '<input type="hidden" name="initial-membership_set-0-date_joined" '
+ 'value="__DATETIME__" '
'id="initial-membership_set-0-id_membership_set-0-date_joined"></p>'
'<p><label for="id_membership_set-0-karma">Karma:</label>'
- '<input type="number" name="membership_set-0-karma" id="id_membership_set-0-karma">'
- '<input type="hidden" name="membership_set-0-person" value="%d" id="id_membership_set-0-person">'
- '<input type="hidden" name="membership_set-0-id" id="id_membership_set-0-id"></p>'
- % person.id,
+ '<input type="number" name="membership_set-0-karma" '
+ 'id="id_membership_set-0-karma">'
+ '<input type="hidden" name="membership_set-0-person" value="%d" '
+ 'id="id_membership_set-0-person">'
+ '<input type="hidden" name="membership_set-0-id" '
+ 'id="id_membership_set-0-id"></p>' % person.id,
)
# test for validation with callable defaults. Validations rely on hidden fields
@@ -1701,12 +1772,14 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for price and quantity, which must be unique."
+ "Please correct the duplicate data for price and quantity, which must "
+ "be unique."
],
)
- # Only the price field is specified, this should skip any unique checks since
- # the unique_together is not fulfilled. This will fail with a KeyError if broken.
+ # Only the price field is specified, this should skip any unique
+ # checks since the unique_together is not fulfilled. This will fail
+ # with a KeyError if broken.
FormSet = modelformset_factory(Price, fields=("price",), extra=2)
data = {
"form-TOTAL_FORMS": "2",
@@ -1765,7 +1838,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for title which must be unique for the date in posted."
+ "Please correct the duplicate data for title which must be unique for "
+ "the date in posted."
],
)
self.assertEqual(
@@ -1791,7 +1865,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for slug which must be unique for the year in posted."
+ "Please correct the duplicate data for slug which must be unique for "
+ "the year in posted."
],
)
@@ -1813,7 +1888,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for subtitle which must be unique for the month in posted."
+ "Please correct the duplicate data for subtitle which must be unique "
+ "for the month in posted."
],
)
@@ -1885,7 +1961,8 @@ class ModelFormsetTest(TestCase):
[
{
"id": [
- "Select a valid choice. That choice is not one of the available choices."
+ "Select a valid choice. That choice is not one of the "
+ "available choices."
]
}
],
@@ -1906,7 +1983,8 @@ class ModelFormsetTest(TestCase):
[
{
"id": [
- "Select a valid choice. That choice is not one of the available choices."
+ "Select a valid choice. That choice is not one of the "
+ "available choices."
]
}
],
@@ -1925,7 +2003,8 @@ class TestModelFormsetOverridesTroughFormMeta(TestCase):
form = PoetFormSet.form()
self.assertHTMLEqual(
str(form["name"]),
- '<input id="id_name" maxlength="100" type="text" class="poet" name="name" required>',
+ '<input id="id_name" maxlength="100" type="text" class="poet" name="name" '
+ "required>",
)
def test_inlineformset_factory_widgets(self):
@@ -1936,7 +2015,8 @@ class TestModelFormsetOverridesTroughFormMeta(TestCase):
form = BookFormSet.form()
self.assertHTMLEqual(
str(form["title"]),
- '<input class="book" id="id_title" maxlength="100" name="title" type="text" required>',
+ '<input class="book" id="id_title" maxlength="100" name="title" '
+ 'type="text" required>',
)
def test_modelformset_factory_labels_overrides(self):
diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py
index 696235a948..7767ec48a2 100644
--- a/tests/model_formsets_regress/tests.py
+++ b/tests/model_formsets_regress/tests.py
@@ -24,7 +24,9 @@ from .models import (
class InlineFormsetTests(TestCase):
def test_formset_over_to_field(self):
- "A formset over a ForeignKey with a to_field can be saved. Regression for #10243"
+ """
+ A formset over a ForeignKey with a to_field can be saved.
+ """
Form = modelform_factory(User, fields="__all__")
FormSet = inlineformset_factory(User, UserSite, fields="__all__")
@@ -100,7 +102,9 @@ class InlineFormsetTests(TestCase):
self.fail("Errors found on formset:%s" % form_set.errors)
def test_formset_over_inherited_model(self):
- "A formset over a ForeignKey with a to_field can be saved. Regression for #11120"
+ """
+ A formset over a ForeignKey with a to_field can be saved.
+ """
Form = modelform_factory(Restaurant, fields="__all__")
FormSet = inlineformset_factory(Restaurant, Manager, fields="__all__")
@@ -418,7 +422,7 @@ class BaseCustomDeleteFormSet(BaseFormSet):
class FormfieldShouldDeleteFormTests(TestCase):
"""
- Regression for #14099: BaseModelFormSet should use ModelFormSet method _should_delete_form
+ BaseModelFormSet should use ModelFormSet method _should_delete_form.
"""
class BaseCustomDeleteModelFormSet(BaseModelFormSet, BaseCustomDeleteFormSet):
diff --git a/tests/model_regress/tests.py b/tests/model_regress/tests.py
index eec8fa36eb..10dfbabcd9 100644
--- a/tests/model_regress/tests.py
+++ b/tests/model_regress/tests.py
@@ -217,7 +217,7 @@ class ModelTests(TestCase):
def test_chained_fks(self):
"""
- Regression for #18432: Chained foreign keys with to_field produce incorrect query
+ Chained foreign keys with to_field produce incorrect query.
"""
m1 = Model1.objects.create(pkey=1000)
diff --git a/tests/modeladmin/test_checks.py b/tests/modeladmin/test_checks.py
index c74c35f76f..e4ad0636a6 100644
--- a/tests/modeladmin/test_checks.py
+++ b/tests/modeladmin/test_checks.py
@@ -413,7 +413,8 @@ class RadioFieldsCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or admin.VERTICAL.",
+ "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or "
+ "admin.VERTICAL.",
"admin.E024",
)
@@ -466,8 +467,9 @@ class PrepopulatedFieldsCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'prepopulated_fields[\"slug\"][0]' refers to 'non_existent_field', "
- "which is not a field of 'modeladmin.ValidationTestModel'.",
+ "The value of 'prepopulated_fields[\"slug\"][0]' refers to "
+ "'non_existent_field', which is not a field of "
+ "'modeladmin.ValidationTestModel'.",
"admin.E030",
)
@@ -496,8 +498,9 @@ class PrepopulatedFieldsCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'prepopulated_fields' refers to 'best_friend', which must not be "
- "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.",
+ "The value of 'prepopulated_fields' refers to 'best_friend', which must "
+ "not be a DateTimeField, a ForeignKey, a OneToOneField, or a "
+ "ManyToManyField.",
"admin.E028",
)
@@ -606,7 +609,8 @@ class ListDisplayLinksCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'list_display_links[0]' refers to 'name', which is not defined in 'list_display'.",
+ "The value of 'list_display_links[0]' refers to 'name', which is not "
+ "defined in 'list_display'.",
"admin.E111",
)
@@ -1170,7 +1174,8 @@ class FkNameCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "'modeladmin.ValidationTestInlineModel' has no field named 'non_existent_field'.",
+ "'modeladmin.ValidationTestInlineModel' has no field named "
+ "'non_existent_field'.",
"admin.E202",
invalid_obj=ValidationTestInline,
)
diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
index 3f5548d761..2dc894b858 100644
--- a/tests/multiple_database/tests.py
+++ b/tests/multiple_database/tests.py
@@ -216,7 +216,8 @@ class QueryTestCase(TestCase):
dive = Book.objects.using("other").get(title="Dive into Python")
mark = Person.objects.using("other").get(name="Mark Pilgrim")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(
list(dive.authors.all().values_list("name", flat=True)), ["Mark Pilgrim"]
)
@@ -597,7 +598,8 @@ class QueryTestCase(TestCase):
chris = Person.objects.using("other").get(name="Chris Mills")
dive = Book.objects.using("other").get(title="Dive into Python")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(
list(chris.edited.values_list("title", flat=True)), ["Dive into Python"]
)
@@ -743,7 +745,10 @@ class QueryTestCase(TestCase):
marty.edited.add(dive)
def test_foreign_key_deletion(self):
- "Cascaded deletions of Foreign Key relations issue queries on the right database"
+ """
+ Cascaded deletions of Foreign Key relations issue queries on the right
+ database.
+ """
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Pet.objects.using("other").create(name="Fido", owner=mark)
@@ -843,7 +848,8 @@ class QueryTestCase(TestCase):
alice_profile = UserProfile.objects.using("default").get(flavor="chocolate")
bob_profile = UserProfile.objects.using("other").get(flavor="crunchy frog")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(alice_profile.user.username, "alice")
self.assertEqual(bob_profile.user.username, "bob")
@@ -976,7 +982,8 @@ class QueryTestCase(TestCase):
# Reget the objects to clear caches
dive = Book.objects.using("other").get(title="Dive into Python")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(
list(dive.reviews.all().values_list("source", flat=True)), ["Python Weekly"]
)
@@ -1090,7 +1097,10 @@ class QueryTestCase(TestCase):
)
def test_generic_key_cross_database_protection(self):
- "Operations that involve sharing generic key objects across databases raise an error"
+ """
+ Operations that involve sharing generic key objects across databases
+ raise an error.
+ """
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
@@ -1171,7 +1181,10 @@ class QueryTestCase(TestCase):
)
def test_generic_key_deletion(self):
- "Cascaded deletions of Generic Key relations issue queries on the right database"
+ """
+ Cascaded deletions of Generic Key relations issue queries on the right
+ database.
+ """
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
@@ -1223,7 +1236,10 @@ class QueryTestCase(TestCase):
self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
def test_select_related(self):
- "Database assignment is retained if an object is retrieved with select_related()"
+ """
+ Database assignment is retained if an object is retrieved with
+ select_related().
+ """
# Create a book and author on the other database
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Book.objects.using("other").create(
@@ -1465,7 +1481,10 @@ class RouterTestCase(TestCase):
published=datetime.date(2009, 5, 4),
)
# Set a foreign key set with an object from a different database
- msg = "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the object first."
+ msg = (
+ "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the "
+ "object first."
+ )
with self.assertRaisesMessage(ValueError, msg):
marty.edited.set([dive])
@@ -1508,7 +1527,8 @@ class RouterTestCase(TestCase):
# Set a foreign key set with an object from a different database
marty.edited.set([pro, dive], bulk=False)
- # Assignment implies a save, so database assignments of original objects have changed...
+ # Assignment implies a save, so database assignments of original
+ # objects have changed...
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "default")
@@ -1524,7 +1544,8 @@ class RouterTestCase(TestCase):
# Add to a foreign key set with an object from a different database
marty.edited.add(dive, bulk=False)
- # Add implies a save, so database assignments of original objects have changed...
+ # Add implies a save, so database assignments of original objects have
+ # changed...
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "default")
@@ -1813,7 +1834,10 @@ class RouterTestCase(TestCase):
self.assertEqual(marty.book_set.db_manager("default").all().db, "default")
def test_foreign_key_managers(self):
- "FK reverse relations are represented by managers, and can be controlled like managers"
+ """
+ FK reverse relations are represented by managers, and can be controlled
+ like managers.
+ """
marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
Book.objects.using("other").create(
pk=1,
@@ -1826,7 +1850,10 @@ class RouterTestCase(TestCase):
self.assertEqual(marty.edited.db_manager("default").all().db, "default")
def test_generic_key_managers(self):
- "Generic key relations are represented by managers, and can be controlled like managers"
+ """
+ Generic key relations are represented by managers, and can be
+ controlled like managers.
+ """
pro = Book.objects.using("other").create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
diff --git a/tests/null_queries/tests.py b/tests/null_queries/tests.py
index f0aad73057..4c5c3bbe5c 100644
--- a/tests/null_queries/tests.py
+++ b/tests/null_queries/tests.py
@@ -33,7 +33,10 @@ class NullQueriesTests(TestCase):
)
# Valid query, but fails because foo isn't a keyword
- msg = "Cannot resolve keyword 'foo' into field. Choices are: choice, id, poll, poll_id"
+ msg = (
+ "Cannot resolve keyword 'foo' into field. Choices are: choice, id, poll, "
+ "poll_id"
+ )
with self.assertRaisesMessage(FieldError, msg):
Choice.objects.filter(foo__exact=None)
diff --git a/tests/one_to_one/tests.py b/tests/one_to_one/tests.py
index 885e753567..40dcd45a77 100644
--- a/tests/one_to_one/tests.py
+++ b/tests/one_to_one/tests.py
@@ -158,7 +158,10 @@ class OneToOneTests(TestCase):
place = Place(name="User", address="London")
with self.assertRaises(Restaurant.DoesNotExist):
place.restaurant
- msg = "save() prohibited to prevent data loss due to unsaved related object 'place'."
+ msg = (
+ "save() prohibited to prevent data loss due to unsaved related object "
+ "'place'."
+ )
with self.assertRaisesMessage(ValueError, msg):
Restaurant.objects.create(
place=place, serves_hot_dogs=True, serves_pizza=False
@@ -445,7 +448,10 @@ class OneToOneTests(TestCase):
p.undergroundbar = b
# However saving the object is not allowed.
- msg = "save() prohibited to prevent data loss due to unsaved related object 'place'."
+ msg = (
+ "save() prohibited to prevent data loss due to unsaved related object "
+ "'place'."
+ )
with self.assertNumQueries(0):
with self.assertRaisesMessage(ValueError, msg):
b.save()
diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py
index 79d60530fa..8444bd3dd0 100644
--- a/tests/pagination/tests.py
+++ b/tests/pagination/tests.py
@@ -502,8 +502,9 @@ class ModelPaginationTests(TestCase):
paginator = Paginator(Article.objects.order_by("id"), 5)
p = paginator.page(1)
- # Make sure object_list queryset is not evaluated by an invalid __getitem__ call.
- # (this happens from the template engine when using eg: {% page_obj.has_previous %})
+ # object_list queryset is not evaluated by an invalid __getitem__ call.
+ # (this happens from the template engine when using e.g.:
+ # {% page_obj.has_previous %}).
self.assertIsNone(p.object_list._result_cache)
msg = "Page indices must be integers or slices, not str."
with self.assertRaisesMessage(TypeError, msg):
diff --git a/tests/postgres_tests/test_array.py b/tests/postgres_tests/test_array.py
index 512972b8e6..28d5924b9d 100644
--- a/tests/postgres_tests/test_array.py
+++ b/tests/postgres_tests/test_array.py
@@ -540,11 +540,17 @@ class TestQuerying(PostgreSQLTestCase):
)
def test_unsupported_lookup(self):
- msg = "Unsupported lookup '0_bar' for ArrayField or join on the field not permitted."
+ msg = (
+ "Unsupported lookup '0_bar' for ArrayField or join on the field not "
+ "permitted."
+ )
with self.assertRaisesMessage(FieldError, msg):
list(NullableIntegerArrayModel.objects.filter(field__0_bar=[2]))
- msg = "Unsupported lookup '0bar' for ArrayField or join on the field not permitted."
+ msg = (
+ "Unsupported lookup '0bar' for ArrayField or join on the field not "
+ "permitted."
+ )
with self.assertRaisesMessage(FieldError, msg):
list(NullableIntegerArrayModel.objects.filter(field__0bar=[2]))
@@ -881,7 +887,10 @@ class TestMigrations(TransactionTestCase):
class TestSerialization(PostgreSQLSimpleTestCase):
- test_data = '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, "model": "postgres_tests.integerarraymodel", "pk": null}]'
+ test_data = (
+ '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, '
+ '"model": "postgres_tests.integerarraymodel", "pk": null}]'
+ )
def test_dumping(self):
instance = IntegerArrayModel(field=[1, 2, None])
@@ -937,7 +946,8 @@ class TestValidation(PostgreSQLSimpleTestCase):
exception = cm.exception.error_list[0]
self.assertEqual(
exception.message,
- "Item 1 in the array did not validate: Ensure this value has at most 2 characters (it has 3).",
+ "Item 1 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 3).",
)
self.assertEqual(exception.code, "item_invalid")
self.assertEqual(
@@ -956,7 +966,8 @@ class TestValidation(PostgreSQLSimpleTestCase):
exception = cm.exception.error_list[0]
self.assertEqual(
exception.message,
- "Item 1 in the array did not validate: Ensure this value is greater than or equal to 1.",
+ "Item 1 in the array did not validate: Ensure this value is greater than "
+ "or equal to 1.",
)
self.assertEqual(exception.code, "item_invalid")
self.assertEqual(
@@ -997,7 +1008,8 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
first_error = errors[0]
self.assertEqual(
first_error.message,
- "Item 1 in the array did not validate: Ensure this value has at most 2 characters (it has 3).",
+ "Item 1 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 3).",
)
self.assertEqual(first_error.code, "item_invalid")
self.assertEqual(
@@ -1007,7 +1019,8 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
second_error = errors[1]
self.assertEqual(
second_error.message,
- "Item 3 in the array did not validate: Ensure this value has at most 2 characters (it has 4).",
+ "Item 3 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 4).",
)
self.assertEqual(second_error.code, "item_invalid")
self.assertEqual(
@@ -1169,7 +1182,10 @@ class TestSplitFormField(PostgreSQLSimpleTestCase):
)
def test_invalid_integer(self):
- msg = "Item 2 in the array did not validate: Ensure this value is less than or equal to 100."
+ msg = (
+ "Item 2 in the array did not validate: Ensure this value is less than or "
+ "equal to 100."
+ )
with self.assertRaisesMessage(exceptions.ValidationError, msg):
SplitArrayField(forms.IntegerField(max_value=100), size=2).clean([0, 101])
@@ -1200,8 +1216,10 @@ class TestSplitFormField(PostgreSQLSimpleTestCase):
self.assertEqual(
cm.exception.messages,
[
- "Item 1 in the array did not validate: Ensure this value has at most 2 characters (it has 3).",
- "Item 3 in the array did not validate: Ensure this value has at most 2 characters (it has 4).",
+ "Item 1 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 3).",
+ "Item 3 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 4).",
],
)
diff --git a/tests/postgres_tests/test_constraints.py b/tests/postgres_tests/test_constraints.py
index b1211d7673..1337c5730d 100644
--- a/tests/postgres_tests/test_constraints.py
+++ b/tests/postgres_tests/test_constraints.py
@@ -843,7 +843,8 @@ class ExclusionConstraintTests(PostgreSQLTestCase):
msg = "Covering exclusion constraints requires PostgreSQL 12+."
with connection.schema_editor() as editor:
with mock.patch(
- "django.db.backends.postgresql.features.DatabaseFeatures.supports_covering_gist_indexes",
+ "django.db.backends.postgresql.features.DatabaseFeatures."
+ "supports_covering_gist_indexes",
False,
):
with self.assertRaisesMessage(NotSupportedError, msg):
diff --git a/tests/postgres_tests/test_indexes.py b/tests/postgres_tests/test_indexes.py
index 5eb060e7f5..ab5cdfda32 100644
--- a/tests/postgres_tests/test_indexes.py
+++ b/tests/postgres_tests/test_indexes.py
@@ -519,7 +519,8 @@ class SchemaTests(PostgreSQLTestCase):
msg = "Covering GiST indexes requires PostgreSQL 12+."
with self.assertRaisesMessage(NotSupportedError, msg):
with mock.patch(
- "django.db.backends.postgresql.features.DatabaseFeatures.supports_covering_gist_indexes",
+ "django.db.backends.postgresql.features.DatabaseFeatures."
+ "supports_covering_gist_indexes",
False,
):
with connection.schema_editor() as editor:
diff --git a/tests/postgres_tests/test_introspection.py b/tests/postgres_tests/test_introspection.py
index 670be46536..3179b47cc9 100644
--- a/tests/postgres_tests/test_introspection.py
+++ b/tests/postgres_tests/test_introspection.py
@@ -23,10 +23,15 @@ class InspectDBTests(PostgreSQLTestCase):
self.assertFieldsInModel(
"postgres_tests_rangesmodel",
[
- "ints = django.contrib.postgres.fields.IntegerRangeField(blank=True, null=True)",
- "bigints = django.contrib.postgres.fields.BigIntegerRangeField(blank=True, null=True)",
- "decimals = django.contrib.postgres.fields.DecimalRangeField(blank=True, null=True)",
- "timestamps = django.contrib.postgres.fields.DateTimeRangeField(blank=True, null=True)",
- "dates = django.contrib.postgres.fields.DateRangeField(blank=True, null=True)",
+ "ints = django.contrib.postgres.fields.IntegerRangeField(blank=True, "
+ "null=True)",
+ "bigints = django.contrib.postgres.fields.BigIntegerRangeField("
+ "blank=True, null=True)",
+ "decimals = django.contrib.postgres.fields.DecimalRangeField("
+ "blank=True, null=True)",
+ "timestamps = django.contrib.postgres.fields.DateTimeRangeField("
+ "blank=True, null=True)",
+ "dates = django.contrib.postgres.fields.DateRangeField(blank=True, "
+ "null=True)",
],
)
diff --git a/tests/postgres_tests/test_ranges.py b/tests/postgres_tests/test_ranges.py
index d100d40713..d5ab0c5335 100644
--- a/tests/postgres_tests/test_ranges.py
+++ b/tests/postgres_tests/test_ranges.py
@@ -492,10 +492,12 @@ class TestSerialization(PostgreSQLSimpleTestCase):
test_data = (
'[{"fields": {"ints": "{\\"upper\\": \\"10\\", \\"lower\\": \\"0\\", '
'\\"bounds\\": \\"[)\\"}", "decimals": "{\\"empty\\": true}", '
- '"bigints": null, "timestamps": "{\\"upper\\": \\"2014-02-02T12:12:12+00:00\\", '
+ '"bigints": null, "timestamps": '
+ '"{\\"upper\\": \\"2014-02-02T12:12:12+00:00\\", '
'\\"lower\\": \\"2014-01-01T00:00:00+00:00\\", \\"bounds\\": \\"[)\\"}", '
'"timestamps_inner": null, '
- '"dates": "{\\"upper\\": \\"2014-02-02\\", \\"lower\\": \\"2014-01-01\\", \\"bounds\\": \\"[)\\"}", '
+ '"dates": "{\\"upper\\": \\"2014-02-02\\", \\"lower\\": \\"2014-01-01\\", '
+ '\\"bounds\\": \\"[)\\"}", '
'"dates_inner": null }, '
'"model": "postgres_tests.rangesmodel", "pk": null}]'
)
@@ -660,8 +662,10 @@ class TestFormField(PostgreSQLSimpleTestCase):
</th><td>
<input type="text" name="datetime_field_0" id="id_datetime_field_0">
<input type="text" name="datetime_field_1" id="id_datetime_field_1">
- <input type="hidden" name="initial-datetime_field_0" id="initial-id_datetime_field_0">
- <input type="hidden" name="initial-datetime_field_1" id="initial-id_datetime_field_1">
+ <input type="hidden" name="initial-datetime_field_0"
+ id="initial-id_datetime_field_0">
+ <input type="hidden" name="initial-datetime_field_1"
+ id="initial-id_datetime_field_1">
</td></tr>
""",
)
@@ -681,10 +685,10 @@ class TestFormField(PostgreSQLSimpleTestCase):
value="2010-01-01 11:13:00" id="id_datetime_field_0">
<input type="text" name="datetime_field_1"
value="2020-12-12 16:59:00" id="id_datetime_field_1">
- <input type="hidden" name="initial-datetime_field_0" value="2010-01-01 11:13:00"
- id="initial-id_datetime_field_0">
- <input type="hidden" name="initial-datetime_field_1" value="2020-12-12 16:59:00"
- id="initial-id_datetime_field_1"></td></tr>
+ <input type="hidden" name="initial-datetime_field_0"
+ value="2010-01-01 11:13:00" id="initial-id_datetime_field_0">
+ <input type="hidden" name="initial-datetime_field_1"
+ value="2020-12-12 16:59:00" id="initial-id_datetime_field_1"></td></tr>
""",
)
@@ -983,11 +987,13 @@ class TestWidget(PostgreSQLSimpleTestCase):
f = pg_forms.ranges.DateTimeRangeField()
self.assertHTMLEqual(
f.widget.render("datetimerange", ""),
- '<input type="text" name="datetimerange_0"><input type="text" name="datetimerange_1">',
+ '<input type="text" name="datetimerange_0">'
+ '<input type="text" name="datetimerange_1">',
)
self.assertHTMLEqual(
f.widget.render("datetimerange", None),
- '<input type="text" name="datetimerange_0"><input type="text" name="datetimerange_1">',
+ '<input type="text" name="datetimerange_0">'
+ '<input type="text" name="datetimerange_1">',
)
dt_range = DateTimeTZRange(
datetime.datetime(2006, 1, 10, 7, 30), datetime.datetime(2006, 2, 12, 9, 50)
diff --git a/tests/prefetch_related/test_uuid.py b/tests/prefetch_related/test_uuid.py
index 55332b7b5d..f22b2158a5 100644
--- a/tests/prefetch_related/test_uuid.py
+++ b/tests/prefetch_related/test_uuid.py
@@ -76,7 +76,8 @@ class UUIDPrefetchRelatedLookups(TestCase):
self.assertEqual("Racoon", spooky.fleas_hosted.all()[0].current_room.name)
def test_from_uuid_pk_lookup_integer_pk2_uuid_pk2(self):
- # From uuid-pk model, prefetch <integer-pk model>.<integer-pk model>.<uuid-pk model>.<uuid-pk model>:
+ # From uuid-pk model, prefetch
+ # <integer-pk model>.<integer-pk model>.<uuid-pk model>.<uuid-pk model>:
with self.assertNumQueries(5):
spooky = Pet.objects.prefetch_related("people__houses__rooms__fleas").get(
name="Spooky"
@@ -104,7 +105,8 @@ class UUIDPrefetchRelatedLookups(TestCase):
self.assertEqual(3, len(redwood.rooms.all()[0].fleas.all()))
def test_from_integer_pk_lookup_integer_pk_uuid_pk_uuid_pk(self):
- # From integer-pk model, prefetch <integer-pk model>.<uuid-pk model>.<uuid-pk model>:
+ # From integer-pk model, prefetch
+ # <integer-pk model>.<uuid-pk model>.<uuid-pk model>:
with self.assertNumQueries(4):
redwood = House.objects.prefetch_related("rooms__fleas__pets_visited").get(
name="Redwood"
diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py
index 14690ce0ec..06a9969a06 100644
--- a/tests/prefetch_related/tests.py
+++ b/tests/prefetch_related/tests.py
@@ -508,7 +508,8 @@ class CustomPrefetchTests(TestCase):
[["houses", "rooms"]],
)
- # Ambiguous: Lookup houses_lst doesn't yet exist when performing houses_lst__rooms.
+ # Ambiguous: Lookup houses_lst doesn't yet exist when performing
+ # houses_lst__rooms.
msg = (
"Cannot find 'houses_lst' on Person object, 'houses_lst__rooms' is "
"an invalid parameter to prefetch_related()"
@@ -1051,7 +1052,8 @@ class DefaultManagerTests(TestCase):
self.assertEqual(
depts,
"English department: Mr Cleese (BA, BSci, MA, PhD), Mr Idle (BA)\n"
- "Physics department: Mr Cleese (BA, BSci, MA, PhD), Mr Chapman (BSci)\n",
+ "Physics department: Mr Cleese (BA, BSci, MA, PhD), Mr Chapman "
+ "(BSci)\n",
)
diff --git a/tests/proxy_models/tests.py b/tests/proxy_models/tests.py
index f7c4a30496..f2f465678b 100644
--- a/tests/proxy_models/tests.py
+++ b/tests/proxy_models/tests.py
@@ -127,7 +127,10 @@ class ProxyModelTests(TestCase):
StatusPerson.objects.get(id__lt=max_id + 1)
def test_abstract_base_with_model_fields(self):
- msg = "Abstract base class containing model fields not permitted for proxy model 'NoAbstract'."
+ msg = (
+ "Abstract base class containing model fields not permitted for proxy model "
+ "'NoAbstract'."
+ )
with self.assertRaisesMessage(TypeError, msg):
class NoAbstract(Abstract):
@@ -135,7 +138,10 @@ class ProxyModelTests(TestCase):
proxy = True
def test_too_many_concrete_classes(self):
- msg = "Proxy model 'TooManyBases' has more than one non-abstract model base class."
+ msg = (
+ "Proxy model 'TooManyBases' has more than one non-abstract model base "
+ "class."
+ )
with self.assertRaisesMessage(TypeError, msg):
class TooManyBases(User, Person):
diff --git a/tests/queries/tests.py b/tests/queries/tests.py
index bbad3ed7e6..3210460819 100644
--- a/tests/queries/tests.py
+++ b/tests/queries/tests.py
@@ -906,7 +906,8 @@ class Queries1Tests(TestCase):
def test_ticket10205(self):
# When bailing out early because of an empty "__in" filter, we need
- # to set things up correctly internally so that subqueries can continue properly.
+ # to set things up correctly internally so that subqueries can continue
+ # properly.
self.assertEqual(Tag.objects.filter(name__in=()).update(name="foo"), 0)
def test_ticket10432(self):
@@ -1474,7 +1475,10 @@ class Queries4Tests(TestCase):
def test_ticket11811(self):
unsaved_category = NamedCategory(name="Other")
- msg = "Unsaved model instance <NamedCategory: Other> cannot be used in an ORM query."
+ msg = (
+ "Unsaved model instance <NamedCategory: Other> cannot be used in an ORM "
+ "query."
+ )
with self.assertRaisesMessage(ValueError, msg):
Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category)
@@ -2418,7 +2422,9 @@ class QuerySetBitwiseOperationTests(TestCase):
class CloneTests(TestCase):
def test_evaluated_queryset_as_argument(self):
- "#13227 -- If a queryset is already evaluated, it can still be used as a query arg"
+ """
+ If a queryset is already evaluated, it can still be used as a query arg.
+ """
n = Note(note="Test1", misc="misc")
n.save()
e = ExtraInfo(info="good", note=n)
@@ -4125,7 +4131,7 @@ class RelatedLookupTypeTests(TestCase):
def test_values_queryset_lookup(self):
"""
- #23396 - Ensure ValueQuerySets are not checked for compatibility with the lookup field
+ ValueQuerySets are not checked for compatibility with the lookup field.
"""
# Make sure the num and objecta field values match.
ob = ObjectB.objects.get(name="ob")
diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py
index 24c96b5954..ebbf31a8c8 100644
--- a/tests/raw_query/tests.py
+++ b/tests/raw_query/tests.py
@@ -35,7 +35,10 @@ class RawQueryTests(TestCase):
title="The awesome book",
author=cls.a1,
paperback=False,
- opening_line="It was a bright cold day in April and the clocks were striking thirteen.",
+ opening_line=(
+ "It was a bright cold day in April and the clocks were striking "
+ "thirteen."
+ ),
)
cls.b2 = Book.objects.create(
title="The horrible book",
@@ -193,7 +196,10 @@ class RawQueryTests(TestCase):
Test of raw query's optional ability to translate unexpected result
column names to specific model fields
"""
- query = "SELECT first_name AS first, last_name AS last, dob, id FROM raw_query_author"
+ query = (
+ "SELECT first_name AS first, last_name AS last, dob, id "
+ "FROM raw_query_author"
+ )
translations = {"first": "first_name", "last": "last_name"}
authors = Author.objects.all()
self.assertSuccessfulRawQuery(Author, query, authors, translations=translations)
@@ -358,7 +364,8 @@ class RawQueryTests(TestCase):
def test_subquery_in_raw_sql(self):
list(
Book.objects.raw(
- "SELECT id FROM (SELECT * FROM raw_query_book WHERE paperback IS NOT NULL) sq"
+ "SELECT id FROM "
+ "(SELECT * FROM raw_query_book WHERE paperback IS NOT NULL) sq"
)
)
diff --git a/tests/requests/test_data_upload_settings.py b/tests/requests/test_data_upload_settings.py
index 363e9a966f..0199296293 100644
--- a/tests/requests/test_data_upload_settings.py
+++ b/tests/requests/test_data_upload_settings.py
@@ -77,7 +77,8 @@ class DataUploadMaxMemorySizeMultipartPostTests(SimpleTestCase):
"\r\n".join(
[
"--boundary",
- 'Content-Disposition: form-data; name="file1"; filename="test.file"',
+ 'Content-Disposition: form-data; name="file1"; '
+ 'filename="test.file"',
"",
"value",
"--boundary--",
diff --git a/tests/requests/tests.py b/tests/requests/tests.py
index 13ea4670dd..ee37f9433b 100644
--- a/tests/requests/tests.py
+++ b/tests/requests/tests.py
@@ -421,7 +421,8 @@ class RequestsTests(SimpleTestCase):
def test_POST_multipart_with_content_length_zero(self):
"""
- Multipart POST requests with Content-Length >= 0 are valid and need to be handled.
+ Multipart POST requests with Content-Length >= 0 are valid and need to
+ be handled.
"""
# According to:
# https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13
@@ -591,7 +592,10 @@ class RequestsTests(SimpleTestCase):
"wsgi.input": FakePayload(),
}
)
- msg = "Invalid non-ASCII Content-Type in multipart: multipart/form-data; boundary = à"
+ msg = (
+ "Invalid non-ASCII Content-Type in multipart: multipart/form-data; "
+ "boundary = à"
+ )
with self.assertRaisesMessage(MultiPartParserError, msg):
request.POST
@@ -874,7 +878,10 @@ class HostValidationTests(SimpleTestCase):
@override_settings(ALLOWED_HOSTS=[])
def test_get_host_suggestion_of_allowed_host(self):
- """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS."""
+ """
+ get_host() makes helpful suggestions if a valid-looking host is not in
+ ALLOWED_HOSTS.
+ """
msg_invalid_host = "Invalid HTTP_HOST header: %r."
msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS."
msg_suggestion2 = (
diff --git a/tests/runtests.py b/tests/runtests.py
index 193314f474..5ae39adba3 100755
--- a/tests/runtests.py
+++ b/tests/runtests.py
@@ -608,8 +608,10 @@ if __name__ == "__main__":
parser.add_argument(
"--external-host",
default=socket.gethostname(),
- help="The external host that can be reached by the selenium hub instance when running Selenium "
- "tests via Selenium Hub.",
+ help=(
+ "The external host that can be reached by the selenium hub instance when "
+ "running Selenium tests via Selenium Hub."
+ ),
)
parser.add_argument(
"--debug-sql",
@@ -700,7 +702,8 @@ if __name__ == "__main__":
].count(True)
if enabled_module_options > 1:
print(
- "Aborting: --start-at, --start-after, and test labels are mutually exclusive."
+ "Aborting: --start-at, --start-after, and test labels are mutually "
+ "exclusive."
)
sys.exit(1)
for opt_name in ["start_at", "start_after"]:
diff --git a/tests/schema/tests.py b/tests/schema/tests.py
index 58dcdb3ab1..7e2080d2d9 100644
--- a/tests/schema/tests.py
+++ b/tests/schema/tests.py
@@ -1366,7 +1366,8 @@ class SchemaTests(TransactionTestCase):
Book._meta.get_field("author").column,
(Author._meta.db_table, Author._meta.pk.column),
)
- # The index on ForeignKey is replaced with a unique constraint for OneToOneField.
+ # The index on ForeignKey is replaced with a unique constraint for
+ # OneToOneField.
self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0})
def test_alter_field_fk_keeps_index(self):
@@ -1430,7 +1431,8 @@ class SchemaTests(TransactionTestCase):
BookWithO2O._meta.get_field("author").column,
(Author._meta.db_table, Author._meta.pk.column),
)
- # The unique constraint on OneToOneField is replaced with an index for ForeignKey.
+ # The unique constraint on OneToOneField is replaced with an index for
+ # ForeignKey.
self.assertEqual(counts, {"fks": expected_fks, "uniques": 0, "indexes": 1})
def test_alter_field_o2o_keeps_unique(self):
diff --git a/tests/select_for_update/tests.py b/tests/select_for_update/tests.py
index fae180a962..0a6f866380 100644
--- a/tests/select_for_update/tests.py
+++ b/tests/select_for_update/tests.py
@@ -513,7 +513,10 @@ class SelectForUpdateTests(TransactionTestCase):
@skipIfDBFeature("supports_select_for_update_with_limit")
def test_unsupported_select_for_update_with_limit(self):
- msg = "LIMIT/OFFSET is not supported with select_for_update on this database backend."
+ msg = (
+ "LIMIT/OFFSET is not supported with select_for_update on this database "
+ "backend."
+ )
with self.assertRaisesMessage(NotSupportedError, msg):
with transaction.atomic():
list(Person.objects.all().order_by("pk").select_for_update()[1:2])
diff --git a/tests/select_related/tests.py b/tests/select_related/tests.py
index 3ac36dc7e4..7d35edfcbd 100644
--- a/tests/select_related/tests.py
+++ b/tests/select_related/tests.py
@@ -41,16 +41,19 @@ class SelectRelatedTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.create_tree(
- "Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila melanogaster"
+ "Eukaryota Animalia Anthropoda Insecta Diptera Drosophilidae Drosophila "
+ "melanogaster"
)
cls.create_tree(
"Eukaryota Animalia Chordata Mammalia Primates Hominidae Homo sapiens"
)
cls.create_tree(
- "Eukaryota Plantae Magnoliophyta Magnoliopsida Fabales Fabaceae Pisum sativum"
+ "Eukaryota Plantae Magnoliophyta Magnoliopsida Fabales Fabaceae Pisum "
+ "sativum"
)
cls.create_tree(
- "Eukaryota Fungi Basidiomycota Homobasidiomycatae Agaricales Amanitacae Amanita muscaria"
+ "Eukaryota Fungi Basidiomycota Homobasidiomycatae Agaricales Amanitacae "
+ "Amanita muscaria"
)
def test_access_fks_without_select_related(self):
diff --git a/tests/serializers/test_xml.py b/tests/serializers/test_xml.py
index bfa91559ff..5d8b9c04cc 100644
--- a/tests/serializers/test_xml.py
+++ b/tests/serializers/test_xml.py
@@ -82,7 +82,10 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase):
This is the most straightforward way to prevent all entity definitions
and avoid both external entities and entity-expansion attacks.
"""
- xml = '<?xml version="1.0" standalone="no"?><!DOCTYPE example SYSTEM "http://example.com/example.dtd">'
+ xml = (
+ '<?xml version="1.0" standalone="no"?>'
+ '<!DOCTYPE example SYSTEM "http://example.com/example.dtd">'
+ )
with self.assertRaises(DTDForbidden):
next(serializers.deserialize("xml", xml))
@@ -107,4 +110,4 @@ class XmlSerializerTransactionTestCase(
</object>
<object pk="1" model="serializers.category">
<field type="CharField" name="name">Reference</field></object>
-</django-objects>"""
+</django-objects>""" # NOQA
diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py
index 057cce7cfd..32edb7bc3c 100644
--- a/tests/serializers/tests.py
+++ b/tests/serializers/tests.py
@@ -53,7 +53,10 @@ class SerializerRegistrationTests(SimpleTestCase):
self.assertIn("xml", public_formats)
def test_unregister(self):
- "Unregistering a serializer doesn't cause the registry to be repopulated. Refs #14823"
+ """
+ Unregistering a serializer doesn't cause the registry to be
+ repopulated.
+ """
serializers.unregister_serializer("xml")
serializers.register_serializer("json3", "django.core.serializers.json")
diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py
index b5338a2890..26daae2270 100644
--- a/tests/sessions_tests/tests.py
+++ b/tests/sessions_tests/tests.py
@@ -769,7 +769,8 @@ class SessionMiddlewareTests(TestCase):
# The cookie was deleted, not recreated.
# A deleted cookie header looks like:
- # Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
+ # "Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; "
+ # "Max-Age=0; Path=/"
self.assertEqual(
'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
"Max-Age=0; Path=/; SameSite={}".format(
diff --git a/tests/signals/tests.py b/tests/signals/tests.py
index 48cec70f5e..28995f078a 100644
--- a/tests/signals/tests.py
+++ b/tests/signals/tests.py
@@ -344,7 +344,10 @@ class LazyModelRefTests(BaseSignalSetup, SimpleTestCase):
self.received.append(kwargs)
def test_invalid_sender_model_name(self):
- msg = "Invalid model reference 'invalid'. String model references must be of the form 'app_label.ModelName'."
+ msg = (
+ "Invalid model reference 'invalid'. String model references must be of the "
+ "form 'app_label.ModelName'."
+ )
with self.assertRaisesMessage(ValueError, msg):
signals.post_init.connect(self.receiver, sender="invalid")
diff --git a/tests/sitemaps_tests/test_generic.py b/tests/sitemaps_tests/test_generic.py
index 8fd57b4acf..e2432a3d01 100644
--- a/tests/sitemaps_tests/test_generic.py
+++ b/tests/sitemaps_tests/test_generic.py
@@ -40,24 +40,25 @@ class GenericViewsSitemapTests(SitemapTestsBase):
for pk in TestModel.objects.values_list("id", flat=True):
expected += "<url><loc>%s/testmodel/%s/</loc></url>" % (self.base_url, pk)
expected_content = (
- """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-%s
-</urlset>
-"""
- % expected
- )
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "%s\n"
+ "</urlset>"
+ ) % expected
self.assertXMLEqual(response.content.decode(), expected_content)
def test_generic_sitemap_lastmod(self):
test_model = TestModel.objects.first()
TestModel.objects.update(lastmod=datetime(2013, 3, 13, 10, 0, 0))
response = self.client.get("/generic-lastmod/sitemap.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/testmodel/%s/</loc><lastmod>2013-03-13</lastmod></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/testmodel/%s/</loc><lastmod>2013-03-13</lastmod></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
test_model.pk,
)
diff --git a/tests/sitemaps_tests/test_http.py b/tests/sitemaps_tests/test_http.py
index ebe8928e06..12cb1bb207 100644
--- a/tests/sitemaps_tests/test_http.py
+++ b/tests/sitemaps_tests/test_http.py
@@ -82,11 +82,14 @@ class HTTPSitemapTests(SitemapTestsBase):
def test_simple_sitemap_section(self):
"A simple sitemap section can be rendered"
response = self.client.get("/simple/sitemap-simple.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
date.today(),
)
@@ -113,11 +116,14 @@ class HTTPSitemapTests(SitemapTestsBase):
def test_simple_sitemap(self):
"A simple sitemap can be rendered"
response = self.client.get("/simple/sitemap.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
date.today(),
)
@@ -233,13 +239,13 @@ class HTTPSitemapTests(SitemapTestsBase):
# doesn't raise an exception.
response = self.client.get("/simple/sitemap.xml")
expected_content = (
- """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>http://testserver/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-"""
- % date.today()
- )
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>http://testserver/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % date.today()
self.assertXMLEqual(response.content.decode(), expected_content)
@ignore_warnings(category=RemovedInDjango50Warning)
@@ -312,13 +318,15 @@ class HTTPSitemapTests(SitemapTestsBase):
"""
with self.assertNoLogs("django.template", "DEBUG"):
response = self.client.get("/simple/i18n.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>{0}/en/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url><url><loc>{0}/pt/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""".format(
- self.base_url, self.i18n_model.pk
- )
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>{0}/en/i18n/testmodel/{1}/</loc><changefreq>never</changefreq>"
+ "<priority>0.5</priority></url><url><loc>{0}/pt/i18n/testmodel/{1}/</loc>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ).format(self.base_url, self.i18n_model.pk)
self.assertXMLEqual(response.content.decode(), expected_content)
@override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese")))
@@ -340,11 +348,13 @@ class HTTPSitemapTests(SitemapTestsBase):
""".replace(
"\n", ""
)
- expected_content = f"""<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-{expected_urls}
-</urlset>
-"""
+ expected_content = (
+ f'<?xml version="1.0" encoding="UTF-8"?>\n'
+ f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ f"{expected_urls}\n"
+ f"</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
@override_settings(
@@ -368,11 +378,13 @@ class HTTPSitemapTests(SitemapTestsBase):
""".replace(
"\n", ""
)
- expected_content = f"""<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-{expected_urls}
-</urlset>
-"""
+ expected_content = (
+ f'<?xml version="1.0" encoding="UTF-8"?>\n'
+ f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ f"{expected_urls}\n"
+ f"</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
@override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese")))
@@ -396,17 +408,21 @@ class HTTPSitemapTests(SitemapTestsBase):
""".replace(
"\n", ""
)
- expected_content = f"""<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-{expected_urls}
-</urlset>
-"""
+ expected_content = (
+ f'<?xml version="1.0" encoding="UTF-8"?>\n'
+ f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ f"{expected_urls}\n"
+ f"</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
def test_sitemap_without_entries(self):
response = self.client.get("/sitemap-without-entries/sitemap.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-
-</urlset>"""
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n\n'
+ "</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
diff --git a/tests/sitemaps_tests/test_https.py b/tests/sitemaps_tests/test_https.py
index 7fc46e0d8e..6b12885a9a 100644
--- a/tests/sitemaps_tests/test_https.py
+++ b/tests/sitemaps_tests/test_https.py
@@ -25,11 +25,14 @@ class HTTPSSitemapTests(SitemapTestsBase):
def test_secure_sitemap_section(self):
"A secure sitemap section can be rendered"
response = self.client.get("/secure/sitemap-simple.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
date.today(),
)
@@ -55,11 +58,14 @@ class HTTPSDetectionSitemapTests(SitemapTestsBase):
def test_sitemap_section_with_https_request(self):
"A sitemap section requested in HTTPS is rendered with HTTPS links"
response = self.client.get("/simple/sitemap-simple.xml", **self.extra)
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url.replace("http://", "https://"),
date.today(),
)
diff --git a/tests/sitemaps_tests/test_utils.py b/tests/sitemaps_tests/test_utils.py
index ec94d7d5ea..8b03d53f7b 100644
--- a/tests/sitemaps_tests/test_utils.py
+++ b/tests/sitemaps_tests/test_utils.py
@@ -32,7 +32,10 @@ class PingGoogleTests(SitemapTestsBase):
@override_settings(ROOT_URLCONF="sitemaps_tests.urls.empty")
def test_get_sitemap_full_url_not_detected(self):
- msg = "You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected."
+ msg = (
+ "You didn't provide a sitemap_url, and the sitemap URL couldn't be "
+ "auto-detected."
+ )
with self.assertRaisesMessage(SitemapNotFound, msg):
_get_sitemap_full_url(None)
diff --git a/tests/staticfiles_tests/test_checks.py b/tests/staticfiles_tests/test_checks.py
index 5a4cbe7d0f..a8c6b78a96 100644
--- a/tests/staticfiles_tests/test_checks.py
+++ b/tests/staticfiles_tests/test_checks.py
@@ -16,7 +16,10 @@ class FindersCheckTests(CollectionTestCase):
def test_base_finder_check_not_implemented(self):
finder = BaseFinder()
- msg = "subclasses may provide a check() method to verify the finder is configured correctly."
+ msg = (
+ "subclasses may provide a check() method to verify the finder is "
+ "configured correctly."
+ )
with self.assertRaisesMessage(NotImplementedError, msg):
finder.check()
diff --git a/tests/staticfiles_tests/test_forms.py b/tests/staticfiles_tests/test_forms.py
index b0c5c19a0e..16ab904d17 100644
--- a/tests/staticfiles_tests/test_forms.py
+++ b/tests/staticfiles_tests/test_forms.py
@@ -29,10 +29,11 @@ class StaticFilesFormsMediaTestCase(SimpleTestCase):
)
self.assertEqual(
str(m),
- """<link href="https://example.com/assets/path/to/css1" type="text/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>
-<script src="https://example.com/assets/relative/path/to/js4"></script>""",
+ '<link href="https://example.com/assets/path/to/css1" type="text/css" '
+ 'media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>\n'
+ '<script src="https://example.com/assets/relative/path/to/js4"></script>',
)
diff --git a/tests/staticfiles_tests/test_management.py b/tests/staticfiles_tests/test_management.py
index afc8cc1637..09ce7c488c 100644
--- a/tests/staticfiles_tests/test_management.py
+++ b/tests/staticfiles_tests/test_management.py
@@ -142,7 +142,9 @@ class TestConfiguration(StaticFilesTestCase):
try:
storage.staticfiles_storage._wrapped = empty
with self.settings(
- STATICFILES_STORAGE="django.contrib.staticfiles.storage.StaticFilesStorage"
+ STATICFILES_STORAGE=(
+ "django.contrib.staticfiles.storage.StaticFilesStorage"
+ )
):
command = collectstatic.Command()
self.assertTrue(command.is_local_storage())
@@ -240,7 +242,9 @@ class TestCollectionVerbosity(CollectionTestCase):
self.assertIn(self.copying_msg, output)
@override_settings(
- STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
+ STATICFILES_STORAGE=(
+ "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
+ )
)
def test_verbosity_1_with_post_process(self):
stdout = StringIO()
@@ -248,7 +252,9 @@ class TestCollectionVerbosity(CollectionTestCase):
self.assertNotIn(self.post_process_msg, stdout.getvalue())
@override_settings(
- STATICFILES_STORAGE="django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
+ STATICFILES_STORAGE=(
+ "django.contrib.staticfiles.storage.ManifestStaticFilesStorage"
+ )
)
def test_verbosity_2_with_post_process(self):
stdout = StringIO()
diff --git a/tests/staticfiles_tests/test_storage.py b/tests/staticfiles_tests/test_storage.py
index e3685671dd..eba91a45a4 100644
--- a/tests/staticfiles_tests/test_storage.py
+++ b/tests/staticfiles_tests/test_storage.py
@@ -109,7 +109,8 @@ class TestHashedFiles:
b"fonts/font.b8d603e42714.svg#path/to/../../fonts/font.svg", content
)
self.assertIn(
- b"data:font/woff;charset=utf-8;base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA",
+ b"data:font/woff;charset=utf-8;"
+ b"base64,d09GRgABAAAAADJoAA0AAAAAR2QAAQAAAAAAAAAAAAA",
content,
)
self.assertIn(b"#default#VML", content)
diff --git a/tests/template_backends/test_django.py b/tests/template_backends/test_django.py
index abd4e3cdb5..40fe225ea0 100644
--- a/tests/template_backends/test_django.py
+++ b/tests/template_backends/test_django.py
@@ -69,8 +69,12 @@ class DjangoTemplatesTests(TemplateStringsTests):
"NAME": "django",
"OPTIONS": {
"libraries": {
- "alternate": "template_backends.apps.good.templatetags.good_tags",
- "override": "template_backends.apps.good.templatetags.good_tags",
+ "alternate": (
+ "template_backends.apps.good.templatetags.good_tags"
+ ),
+ "override": (
+ "template_backends.apps.good.templatetags.good_tags"
+ ),
},
},
}
diff --git a/tests/template_tests/filter_tests/test_addslashes.py b/tests/template_tests/filter_tests/test_addslashes.py
index 2626918f3d..fe42f529fd 100644
--- a/tests/template_tests/filter_tests/test_addslashes.py
+++ b/tests/template_tests/filter_tests/test_addslashes.py
@@ -8,7 +8,10 @@ from ..utils import setup
class AddslashesTests(SimpleTestCase):
@setup(
{
- "addslashes01": "{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}{% endautoescape %}"
+ "addslashes01": (
+ "{% autoescape off %}{{ a|addslashes }} {{ b|addslashes }}"
+ "{% endautoescape %}"
+ )
}
)
def test_addslashes01(self):
diff --git a/tests/template_tests/filter_tests/test_autoescape.py b/tests/template_tests/filter_tests/test_autoescape.py
index de58956f2c..c7cc9deb4a 100644
--- a/tests/template_tests/filter_tests/test_autoescape.py
+++ b/tests/template_tests/filter_tests/test_autoescape.py
@@ -17,7 +17,9 @@ class AutoescapeStringfilterTests(SimpleTestCase):
@setup(
{
- "autoescape-stringfilter02": "{% autoescape off %}{{ unsafe|capfirst }}{% endautoescape %}"
+ "autoescape-stringfilter02": (
+ "{% autoescape off %}{{ unsafe|capfirst }}{% endautoescape %}"
+ )
}
)
def test_autoescape_stringfilter02(self):
@@ -35,7 +37,9 @@ class AutoescapeStringfilterTests(SimpleTestCase):
@setup(
{
- "autoescape-stringfilter04": "{% autoescape off %}{{ safe|capfirst }}{% endautoescape %}"
+ "autoescape-stringfilter04": (
+ "{% autoescape off %}{{ safe|capfirst }}{% endautoescape %}"
+ )
}
)
def test_autoescape_stringfilter04(self):
diff --git a/tests/template_tests/filter_tests/test_capfirst.py b/tests/template_tests/filter_tests/test_capfirst.py
index 3c489e6a1f..f835691ff8 100644
--- a/tests/template_tests/filter_tests/test_capfirst.py
+++ b/tests/template_tests/filter_tests/test_capfirst.py
@@ -8,7 +8,10 @@ from ..utils import setup
class CapfirstTests(SimpleTestCase):
@setup(
{
- "capfirst01": "{% autoescape off %}{{ a|capfirst }} {{ b|capfirst }}{% endautoescape %}"
+ "capfirst01": (
+ "{% autoescape off %}{{ a|capfirst }} {{ b|capfirst }}"
+ "{% endautoescape %}"
+ )
}
)
def test_capfirst01(self):
diff --git a/tests/template_tests/filter_tests/test_center.py b/tests/template_tests/filter_tests/test_center.py
index 0a18294d88..3aafa9f9bb 100644
--- a/tests/template_tests/filter_tests/test_center.py
+++ b/tests/template_tests/filter_tests/test_center.py
@@ -8,7 +8,10 @@ from ..utils import setup
class CenterTests(SimpleTestCase):
@setup(
{
- "center01": '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.{% endautoescape %}'
+ "center01": (
+ '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.'
+ "{% endautoescape %}"
+ )
}
)
def test_center01(self):
diff --git a/tests/template_tests/filter_tests/test_chaining.py b/tests/template_tests/filter_tests/test_chaining.py
index 942707820f..9b07942101 100644
--- a/tests/template_tests/filter_tests/test_chaining.py
+++ b/tests/template_tests/filter_tests/test_chaining.py
@@ -18,7 +18,10 @@ class ChainingTests(SimpleTestCase):
@setup(
{
- "chaining02": '{% autoescape off %}{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}{% endautoescape %}'
+ "chaining02": (
+ '{% autoescape off %}{{ a|capfirst|center:"7" }}.'
+ '{{ b|capfirst|center:"7" }}{% endautoescape %}'
+ )
}
)
def test_chaining02(self):
@@ -37,7 +40,10 @@ class ChainingTests(SimpleTestCase):
@setup(
{
- "chaining04": '{% autoescape off %}{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}{% endautoescape %}'
+ "chaining04": (
+ '{% autoescape off %}{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}'
+ "{% endautoescape %}"
+ )
}
)
def test_chaining04(self):
@@ -68,7 +74,9 @@ class ChainingTests(SimpleTestCase):
@setup(
{
- "chaining08": '{% autoescape off %}{{ a|force_escape|cut:";" }}{% endautoescape %}'
+ "chaining08": (
+ '{% autoescape off %}{{ a|force_escape|cut:";" }}{% endautoescape %}'
+ )
}
)
def test_chaining08(self):
@@ -82,7 +90,9 @@ class ChainingTests(SimpleTestCase):
@setup(
{
- "chaining10": '{% autoescape off %}{{ a|cut:";"|force_escape }}{% endautoescape %}'
+ "chaining10": (
+ '{% autoescape off %}{{ a|cut:";"|force_escape }}{% endautoescape %}'
+ )
}
)
def test_chaining10(self):
@@ -108,7 +118,9 @@ class ChainingTests(SimpleTestCase):
@setup(
{
- "chaining14": "{% autoescape off %}{{ a|safe|force_escape }}{% endautoescape %}"
+ "chaining14": (
+ "{% autoescape off %}{{ a|safe|force_escape }}{% endautoescape %}"
+ )
}
)
def test_chaining14(self):
diff --git a/tests/template_tests/filter_tests/test_cut.py b/tests/template_tests/filter_tests/test_cut.py
index adf1468709..ea6129d84a 100644
--- a/tests/template_tests/filter_tests/test_cut.py
+++ b/tests/template_tests/filter_tests/test_cut.py
@@ -8,7 +8,9 @@ from ..utils import setup
class CutTests(SimpleTestCase):
@setup(
{
- "cut01": '{% autoescape off %}{{ a|cut:"x" }} {{ b|cut:"x" }}{% endautoescape %}'
+ "cut01": (
+ '{% autoescape off %}{{ a|cut:"x" }} {{ b|cut:"x" }}{% endautoescape %}'
+ )
}
)
def test_cut01(self):
@@ -26,7 +28,9 @@ class CutTests(SimpleTestCase):
@setup(
{
- "cut03": '{% autoescape off %}{{ a|cut:"&" }} {{ b|cut:"&" }}{% endautoescape %}'
+ "cut03": (
+ '{% autoescape off %}{{ a|cut:"&" }} {{ b|cut:"&" }}{% endautoescape %}'
+ )
}
)
def test_cut03(self):
@@ -46,7 +50,9 @@ class CutTests(SimpleTestCase):
# are auto-escaped.
@setup(
{
- "cut05": '{% autoescape off %}{{ a|cut:";" }} {{ b|cut:";" }}{% endautoescape %}'
+ "cut05": (
+ '{% autoescape off %}{{ a|cut:";" }} {{ b|cut:";" }}{% endautoescape %}'
+ )
}
)
def test_cut05(self):
diff --git a/tests/template_tests/filter_tests/test_default.py b/tests/template_tests/filter_tests/test_default.py
index 20621f610f..c55f5ad948 100644
--- a/tests/template_tests/filter_tests/test_default.py
+++ b/tests/template_tests/filter_tests/test_default.py
@@ -43,7 +43,9 @@ class DefaultIfNoneTests(SimpleTestCase):
@setup(
{
- "default_if_none02": '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'
+ "default_if_none02": (
+ '{% autoescape off %}{{ a|default:"x<" }}{% endautoescape %}'
+ )
}
)
def test_default_if_none02(self):
diff --git a/tests/template_tests/filter_tests/test_escape.py b/tests/template_tests/filter_tests/test_escape.py
index 16471ad53f..a8fe531645 100644
--- a/tests/template_tests/filter_tests/test_escape.py
+++ b/tests/template_tests/filter_tests/test_escape.py
@@ -21,7 +21,9 @@ class EscapeTests(SimpleTestCase):
@setup(
{
- "escape02": "{% autoescape off %}{{ a|escape }} {{ b|escape }}{% endautoescape %}"
+ "escape02": (
+ "{% autoescape off %}{{ a|escape }} {{ b|escape }}{% endautoescape %}"
+ )
}
)
def test_escape02(self):
diff --git a/tests/template_tests/filter_tests/test_first.py b/tests/template_tests/filter_tests/test_first.py
index 7a1849cd88..224dec7b0f 100644
--- a/tests/template_tests/filter_tests/test_first.py
+++ b/tests/template_tests/filter_tests/test_first.py
@@ -15,7 +15,9 @@ class FirstTests(SimpleTestCase):
@setup(
{
- "first02": "{% autoescape off %}{{ a|first }} {{ b|first }}{% endautoescape %}"
+ "first02": (
+ "{% autoescape off %}{{ a|first }} {{ b|first }}{% endautoescape %}"
+ )
}
)
def test_first02(self):
diff --git a/tests/template_tests/filter_tests/test_floatformat.py b/tests/template_tests/filter_tests/test_floatformat.py
index d7eb5f2076..8dc69b2437 100644
--- a/tests/template_tests/filter_tests/test_floatformat.py
+++ b/tests/template_tests/filter_tests/test_floatformat.py
@@ -11,7 +11,10 @@ from ..utils import setup
class FloatformatTests(SimpleTestCase):
@setup(
{
- "floatformat01": "{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}"
+ "floatformat01": (
+ "{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}"
+ "{% endautoescape %}"
+ )
}
)
def test_floatformat01(self):
diff --git a/tests/template_tests/filter_tests/test_force_escape.py b/tests/template_tests/filter_tests/test_force_escape.py
index 7a34caee2b..02a4063adc 100644
--- a/tests/template_tests/filter_tests/test_force_escape.py
+++ b/tests/template_tests/filter_tests/test_force_escape.py
@@ -13,7 +13,9 @@ class ForceEscapeTests(SimpleTestCase):
@setup(
{
- "force-escape01": "{% autoescape off %}{{ a|force_escape }}{% endautoescape %}"
+ "force-escape01": (
+ "{% autoescape off %}{{ a|force_escape }}{% endautoescape %}"
+ )
}
)
def test_force_escape01(self):
@@ -27,7 +29,10 @@ class ForceEscapeTests(SimpleTestCase):
@setup(
{
- "force-escape03": "{% autoescape off %}{{ a|force_escape|force_escape }}{% endautoescape %}"
+ "force-escape03": (
+ "{% autoescape off %}{{ a|force_escape|force_escape }}"
+ "{% endautoescape %}"
+ )
}
)
def test_force_escape03(self):
@@ -43,7 +48,9 @@ class ForceEscapeTests(SimpleTestCase):
# escape filter has no effect.
@setup(
{
- "force-escape05": "{% autoescape off %}{{ a|force_escape|escape }}{% endautoescape %}"
+ "force-escape05": (
+ "{% autoescape off %}{{ a|force_escape|escape }}{% endautoescape %}"
+ )
}
)
def test_force_escape05(self):
@@ -57,7 +64,9 @@ class ForceEscapeTests(SimpleTestCase):
@setup(
{
- "force-escape07": "{% autoescape off %}{{ a|escape|force_escape }}{% endautoescape %}"
+ "force-escape07": (
+ "{% autoescape off %}{{ a|escape|force_escape }}{% endautoescape %}"
+ )
}
)
def test_force_escape07(self):
diff --git a/tests/template_tests/filter_tests/test_json_script.py b/tests/template_tests/filter_tests/test_json_script.py
index 2457aefe49..909a4f886b 100644
--- a/tests/template_tests/filter_tests/test_json_script.py
+++ b/tests/template_tests/filter_tests/test_json_script.py
@@ -12,6 +12,7 @@ class JsonScriptTests(SimpleTestCase):
self.assertEqual(
output,
'<script id="test_id" type="application/json">'
- '{"a": "testing\\r\\njson \'string\\" \\u003Cb\\u003Eescaping\\u003C/b\\u003E"}'
+ '{"a": "testing\\r\\njson \'string\\" '
+ '\\u003Cb\\u003Eescaping\\u003C/b\\u003E"}'
"</script>",
)
diff --git a/tests/template_tests/filter_tests/test_length_is.py b/tests/template_tests/filter_tests/test_length_is.py
index 1cc760c8a2..cbda46e5b1 100644
--- a/tests/template_tests/filter_tests/test_length_is.py
+++ b/tests/template_tests/filter_tests/test_length_is.py
@@ -14,7 +14,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is02": '{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ "length_is02": (
+ '{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ )
}
)
def test_length_is02(self):
@@ -30,7 +32,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is04": '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ "length_is04": (
+ '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ )
}
)
def test_length_is04(self):
@@ -39,7 +43,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is05": '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ "length_is05": (
+ '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ )
}
)
def test_length_is05(self):
@@ -48,7 +54,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is06": "{% with var|length as my_length %}{{ my_length }}{% endwith %}"
+ "length_is06": (
+ "{% with var|length as my_length %}{{ my_length }}{% endwith %}"
+ )
}
)
def test_length_is06(self):
@@ -58,7 +66,9 @@ class LengthIsTests(SimpleTestCase):
# Boolean return value from length_is should not be coerced to a string
@setup(
{
- "length_is07": '{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}'
+ "length_is07": (
+ '{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}'
+ )
}
)
def test_length_is07(self):
@@ -67,7 +77,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is08": '{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}'
+ "length_is08": (
+ '{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}'
+ )
}
)
def test_length_is08(self):
diff --git a/tests/template_tests/filter_tests/test_linebreaks.py b/tests/template_tests/filter_tests/test_linebreaks.py
index ce0f082466..10c8a92d6a 100644
--- a/tests/template_tests/filter_tests/test_linebreaks.py
+++ b/tests/template_tests/filter_tests/test_linebreaks.py
@@ -21,7 +21,10 @@ class LinebreaksTests(SimpleTestCase):
@setup(
{
- "linebreaks02": "{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}"
+ "linebreaks02": (
+ "{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}"
+ "{% endautoescape %}"
+ )
}
)
def test_linebreaks02(self):
diff --git a/tests/template_tests/filter_tests/test_linebreaksbr.py b/tests/template_tests/filter_tests/test_linebreaksbr.py
index fa4cff209b..aa6505a47a 100644
--- a/tests/template_tests/filter_tests/test_linebreaksbr.py
+++ b/tests/template_tests/filter_tests/test_linebreaksbr.py
@@ -20,7 +20,10 @@ class LinebreaksbrTests(SimpleTestCase):
@setup(
{
- "linebreaksbr02": "{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}"
+ "linebreaksbr02": (
+ "{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}"
+ "{% endautoescape %}"
+ )
}
)
def test_linebreaksbr02(self):
diff --git a/tests/template_tests/filter_tests/test_linenumbers.py b/tests/template_tests/filter_tests/test_linenumbers.py
index 82fae4f889..8b1f8ef8af 100644
--- a/tests/template_tests/filter_tests/test_linenumbers.py
+++ b/tests/template_tests/filter_tests/test_linenumbers.py
@@ -23,7 +23,10 @@ class LinenumbersTests(SimpleTestCase):
@setup(
{
- "linenumbers02": "{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}"
+ "linenumbers02": (
+ "{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}"
+ "{% endautoescape %}"
+ )
}
)
def test_linenumbers02(self):
diff --git a/tests/template_tests/filter_tests/test_ljust.py b/tests/template_tests/filter_tests/test_ljust.py
index 9ea5b23862..f07a3c88f7 100644
--- a/tests/template_tests/filter_tests/test_ljust.py
+++ b/tests/template_tests/filter_tests/test_ljust.py
@@ -8,7 +8,10 @@ from ..utils import setup
class LjustTests(SimpleTestCase):
@setup(
{
- "ljust01": '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.{% endautoescape %}'
+ "ljust01": (
+ '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.'
+ "{% endautoescape %}"
+ )
}
)
def test_ljust01(self):
diff --git a/tests/template_tests/filter_tests/test_lower.py b/tests/template_tests/filter_tests/test_lower.py
index 29845663dd..ae30094d69 100644
--- a/tests/template_tests/filter_tests/test_lower.py
+++ b/tests/template_tests/filter_tests/test_lower.py
@@ -8,7 +8,9 @@ from ..utils import setup
class LowerTests(SimpleTestCase):
@setup(
{
- "lower01": "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}"
+ "lower01": (
+ "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}"
+ )
}
)
def test_lower01(self):
diff --git a/tests/template_tests/filter_tests/test_make_list.py b/tests/template_tests/filter_tests/test_make_list.py
index 34901d2ff2..ddf8dbc7e7 100644
--- a/tests/template_tests/filter_tests/test_make_list.py
+++ b/tests/template_tests/filter_tests/test_make_list.py
@@ -23,7 +23,10 @@ class MakeListTests(SimpleTestCase):
@setup(
{
- "make_list03": '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}'
+ "make_list03": (
+ '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}'
+ "{% endautoescape %}"
+ )
}
)
def test_make_list03(self):
diff --git a/tests/template_tests/filter_tests/test_phone2numeric.py b/tests/template_tests/filter_tests/test_phone2numeric.py
index 8165fba9da..ee3805b70d 100644
--- a/tests/template_tests/filter_tests/test_phone2numeric.py
+++ b/tests/template_tests/filter_tests/test_phone2numeric.py
@@ -16,7 +16,10 @@ class Phone2numericTests(SimpleTestCase):
@setup(
{
- "phone2numeric02": "{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}"
+ "phone2numeric02": (
+ "{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}"
+ "{% endautoescape %}"
+ )
}
)
def test_phone2numeric02(self):
diff --git a/tests/template_tests/filter_tests/test_random.py b/tests/template_tests/filter_tests/test_random.py
index a419128971..785f2d6a2f 100644
--- a/tests/template_tests/filter_tests/test_random.py
+++ b/tests/template_tests/filter_tests/test_random.py
@@ -14,7 +14,9 @@ class RandomTests(SimpleTestCase):
@setup(
{
- "random02": "{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}"
+ "random02": (
+ "{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}"
+ )
}
)
def test_random02(self):
diff --git a/tests/template_tests/filter_tests/test_rjust.py b/tests/template_tests/filter_tests/test_rjust.py
index b7dde7514a..2d12dfccf4 100644
--- a/tests/template_tests/filter_tests/test_rjust.py
+++ b/tests/template_tests/filter_tests/test_rjust.py
@@ -8,7 +8,10 @@ from ..utils import setup
class RjustTests(SimpleTestCase):
@setup(
{
- "rjust01": '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'
+ "rjust01": (
+ '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'
+ "{% endautoescape %}"
+ )
}
)
def test_rjust01(self):
diff --git a/tests/template_tests/filter_tests/test_safeseq.py b/tests/template_tests/filter_tests/test_safeseq.py
index 4a537551f9..e9b3feb0b3 100644
--- a/tests/template_tests/filter_tests/test_safeseq.py
+++ b/tests/template_tests/filter_tests/test_safeseq.py
@@ -11,7 +11,10 @@ class SafeseqTests(SimpleTestCase):
@setup(
{
- "safeseq02": '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}'
+ "safeseq02": (
+ '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}'
+ "{% endautoescape %}"
+ )
}
)
def test_safeseq02(self):
diff --git a/tests/template_tests/filter_tests/test_slice.py b/tests/template_tests/filter_tests/test_slice.py
index f1c91a5008..5a5dd6b155 100644
--- a/tests/template_tests/filter_tests/test_slice.py
+++ b/tests/template_tests/filter_tests/test_slice.py
@@ -15,7 +15,10 @@ class SliceTests(SimpleTestCase):
@setup(
{
- "slice02": '{% autoescape off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}{% endautoescape %}'
+ "slice02": (
+ '{% autoescape off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'
+ "{% endautoescape %}"
+ )
}
)
def test_slice02(self):
diff --git a/tests/template_tests/filter_tests/test_slugify.py b/tests/template_tests/filter_tests/test_slugify.py
index e0e8a52da9..7bb18c5c89 100644
--- a/tests/template_tests/filter_tests/test_slugify.py
+++ b/tests/template_tests/filter_tests/test_slugify.py
@@ -14,7 +14,9 @@ class SlugifyTests(SimpleTestCase):
@setup(
{
- "slugify01": "{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}"
+ "slugify01": (
+ "{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}"
+ )
}
)
def test_slugify01(self):
diff --git a/tests/template_tests/filter_tests/test_stringformat.py b/tests/template_tests/filter_tests/test_stringformat.py
index e8f06ac4a0..075906aecb 100644
--- a/tests/template_tests/filter_tests/test_stringformat.py
+++ b/tests/template_tests/filter_tests/test_stringformat.py
@@ -13,7 +13,10 @@ class StringformatTests(SimpleTestCase):
@setup(
{
- "stringformat01": '{% autoescape off %}.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.{% endautoescape %}'
+ "stringformat01": (
+ '{% autoescape off %}.{{ a|stringformat:"5s" }}. .'
+ '{{ b|stringformat:"5s" }}.{% endautoescape %}'
+ )
}
)
def test_stringformat01(self):
diff --git a/tests/template_tests/filter_tests/test_striptags.py b/tests/template_tests/filter_tests/test_striptags.py
index 7b142f5379..235a35b43e 100644
--- a/tests/template_tests/filter_tests/test_striptags.py
+++ b/tests/template_tests/filter_tests/test_striptags.py
@@ -20,7 +20,10 @@ class StriptagsTests(SimpleTestCase):
@setup(
{
- "striptags02": "{% autoescape off %}{{ a|striptags }} {{ b|striptags }}{% endautoescape %}"
+ "striptags02": (
+ "{% autoescape off %}{{ a|striptags }} {{ b|striptags }}"
+ "{% endautoescape %}"
+ )
}
)
def test_striptags02(self):
@@ -38,7 +41,8 @@ class FunctionTests(SimpleTestCase):
def test_strip(self):
self.assertEqual(
striptags(
- 'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags'
+ 'some <b>html</b> with <script>alert("You smell")</script> disallowed '
+ "<img /> tags"
),
'some html with alert("You smell") disallowed tags',
)
@@ -50,7 +54,8 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
striptags(
lazystr(
- 'some <b>html</b> with <script>alert("Hello")</script> disallowed <img /> tags'
+ 'some <b>html</b> with <script>alert("Hello")</script> disallowed '
+ "<img /> tags"
)
),
'some html with alert("Hello") disallowed tags',
diff --git a/tests/template_tests/filter_tests/test_truncatewords.py b/tests/template_tests/filter_tests/test_truncatewords.py
index b3457205ac..e737a1e3f9 100644
--- a/tests/template_tests/filter_tests/test_truncatewords.py
+++ b/tests/template_tests/filter_tests/test_truncatewords.py
@@ -8,7 +8,10 @@ from ..utils import setup
class TruncatewordsTests(SimpleTestCase):
@setup(
{
- "truncatewords01": '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}'
+ "truncatewords01": (
+ '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'
+ "{% endautoescape %}"
+ )
}
)
def test_truncatewords01(self):
diff --git a/tests/template_tests/filter_tests/test_unordered_list.py b/tests/template_tests/filter_tests/test_unordered_list.py
index 1f08ea790d..1748a0fb54 100644
--- a/tests/template_tests/filter_tests/test_unordered_list.py
+++ b/tests/template_tests/filter_tests/test_unordered_list.py
@@ -16,7 +16,9 @@ class UnorderedListTests(SimpleTestCase):
@setup(
{
- "unordered_list02": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ "unordered_list02": (
+ "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ )
}
)
def test_unordered_list02(self):
@@ -34,7 +36,9 @@ class UnorderedListTests(SimpleTestCase):
@setup(
{
- "unordered_list04": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ "unordered_list04": (
+ "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ )
}
)
def test_unordered_list04(self):
@@ -45,7 +49,9 @@ class UnorderedListTests(SimpleTestCase):
@setup(
{
- "unordered_list05": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ "unordered_list05": (
+ "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ )
}
)
def test_unordered_list05(self):
@@ -126,7 +132,8 @@ class FunctionTests(SimpleTestCase):
c = ULItem("<a>c</a>")
self.assertEqual(
unordered_list([a, b, c]),
- "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
+ "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t"
+ "<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
)
def item_generator():
@@ -134,7 +141,8 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
unordered_list(item_generator()),
- "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
+ "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t"
+ "<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
)
def test_nested_generators(self):
@@ -148,7 +156,8 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
unordered_list(item_generator()),
- "\t<li>A\n\t<ul>\n\t\t<li>B</li>\n\t\t<li>C</li>\n\t</ul>\n\t</li>\n\t<li>D</li>",
+ "\t<li>A\n\t<ul>\n\t\t<li>B</li>\n\t\t<li>C</li>\n\t</ul>\n\t</li>\n\t"
+ "<li>D</li>",
)
def test_ulitem_autoescape_off(self):
diff --git a/tests/template_tests/filter_tests/test_upper.py b/tests/template_tests/filter_tests/test_upper.py
index 01a2f306ae..90f14a794a 100644
--- a/tests/template_tests/filter_tests/test_upper.py
+++ b/tests/template_tests/filter_tests/test_upper.py
@@ -13,7 +13,9 @@ class UpperTests(SimpleTestCase):
@setup(
{
- "upper01": "{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}"
+ "upper01": (
+ "{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}"
+ )
}
)
def test_upper01(self):
diff --git a/tests/template_tests/filter_tests/test_urlize.py b/tests/template_tests/filter_tests/test_urlize.py
index 01e97b35fc..abc227ba6a 100644
--- a/tests/template_tests/filter_tests/test_urlize.py
+++ b/tests/template_tests/filter_tests/test_urlize.py
@@ -9,7 +9,9 @@ from ..utils import setup
class UrlizeTests(SimpleTestCase):
@setup(
{
- "urlize01": "{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}"
+ "urlize01": (
+ "{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}"
+ )
}
)
def test_urlize01(self):
@@ -22,8 +24,10 @@ class UrlizeTests(SimpleTestCase):
)
self.assertEqual(
output,
- '<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&y=</a> '
- '<a href="http://example.com?x=&amp;y=%3C2%3E" rel="nofollow">http://example.com?x=&amp;y=&lt;2&gt;</a>',
+ '<a href="http://example.com/?x=&amp;y=" rel="nofollow">'
+ "http://example.com/?x=&y=</a> "
+ '<a href="http://example.com?x=&amp;y=%3C2%3E" rel="nofollow">'
+ "http://example.com?x=&amp;y=&lt;2&gt;</a>",
)
@setup({"urlize02": "{{ a|urlize }} {{ b|urlize }}"})
@@ -37,8 +41,10 @@ class UrlizeTests(SimpleTestCase):
)
self.assertEqual(
output,
- '<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&amp;y=</a> '
- '<a href="http://example.com?x=&amp;y=" rel="nofollow">http://example.com?x=&amp;y=</a>',
+ '<a href="http://example.com/?x=&amp;y=" rel="nofollow">'
+ "http://example.com/?x=&amp;y=</a> "
+ '<a href="http://example.com?x=&amp;y=" rel="nofollow">'
+ "http://example.com?x=&amp;y=</a>",
)
@setup({"urlize03": "{% autoescape off %}{{ a|urlize }}{% endautoescape %}"})
@@ -95,7 +101,8 @@ class UrlizeTests(SimpleTestCase):
)
self.assertEqual(
output,
- '<a href="http://example.com/?x=&amp;y=%3C2%3E" rel="nofollow">http://example.com/?x=&amp;y=&lt;2&gt;</a>',
+ '<a href="http://example.com/?x=&amp;y=%3C2%3E" rel="nofollow">'
+ "http://example.com/?x=&amp;y=&lt;2&gt;</a>",
)
@@ -127,11 +134,13 @@ class FunctionTests(SimpleTestCase):
# part of URLs.
self.assertEqual(
urlize('www.server.com"abc'),
- '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&quot;abc',
+ '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&quot;'
+ "abc",
)
self.assertEqual(
urlize("www.server.com'abc"),
- '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&#x27;abc',
+ '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&#x27;'
+ "abc",
)
self.assertEqual(
urlize("www.server.com<abc"),
@@ -164,8 +173,9 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B"),
- '<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" rel="nofollow">'
- "http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B</a>",
+ '<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" '
+ 'rel="nofollow">http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B'
+ "</a>",
)
def test_urlencoded(self):
@@ -193,13 +203,13 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("https://en.wikipedia.org/wiki/Django_(web_framework)"),
- '<a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
- "https://en.wikipedia.org/wiki/Django_(web_framework)</a>",
+ '<a href="https://en.wikipedia.org/wiki/Django_(web_framework)" '
+ 'rel="nofollow">https://en.wikipedia.org/wiki/Django_(web_framework)</a>',
)
self.assertEqual(
urlize("(see https://en.wikipedia.org/wiki/Django_(web_framework))"),
- '(see <a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
- "https://en.wikipedia.org/wiki/Django_(web_framework)</a>)",
+ '(see <a href="https://en.wikipedia.org/wiki/Django_(web_framework)" '
+ 'rel="nofollow">https://en.wikipedia.org/wiki/Django_(web_framework)</a>)',
)
def test_nofollow(self):
@@ -269,25 +279,30 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("(Go to http://www.example.com/foo.)"),
- '(Go to <a href="http://www.example.com/foo" rel="nofollow">http://www.example.com/foo</a>.)',
+ '(Go to <a href="http://www.example.com/foo" rel="nofollow">'
+ "http://www.example.com/foo</a>.)",
)
def test_trailing_multiple_punctuation(self):
self.assertEqual(
urlize("A test http://testing.com/example.."),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>..',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>..",
)
self.assertEqual(
urlize("A test http://testing.com/example!!"),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>!!",
)
self.assertEqual(
urlize("A test http://testing.com/example!!!"),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!!',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>!!!",
)
self.assertEqual(
urlize('A test http://testing.com/example.,:;)"!'),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>.,:;)&quot;!',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>.,:;)&quot;!",
)
def test_brackets(self):
@@ -300,7 +315,8 @@ class FunctionTests(SimpleTestCase):
)
self.assertEqual(
urlize("see test[at[example.com"),
- 'see <a href="http://test[at[example.com" rel="nofollow">test[at[example.com</a>',
+ 'see <a href="http://test[at[example.com" rel="nofollow">'
+ "test[at[example.com</a>",
)
self.assertEqual(
urlize("[http://168.192.0.1](http://168.192.0.1)"),
@@ -321,21 +337,22 @@ class FunctionTests(SimpleTestCase):
start_in, end_in = wrapping_in
self.assertEqual(
urlize(start_in + "https://www.example.org/" + end_in),
- start_out
- + '<a href="https://www.example.org/" rel="nofollow">https://www.example.org/</a>'
- + end_out,
+ f'{start_out}<a href="https://www.example.org/" rel="nofollow">'
+ f"https://www.example.org/</a>{end_out}",
)
def test_ipv4(self):
self.assertEqual(
urlize("http://192.168.0.15/api/9"),
- '<a href="http://192.168.0.15/api/9" rel="nofollow">http://192.168.0.15/api/9</a>',
+ '<a href="http://192.168.0.15/api/9" rel="nofollow">'
+ "http://192.168.0.15/api/9</a>",
)
def test_ipv6(self):
self.assertEqual(
urlize("http://[2001:db8:cafe::2]/api/9"),
- '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">http://[2001:db8:cafe::2]/api/9</a>',
+ '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">'
+ "http://[2001:db8:cafe::2]/api/9</a>",
)
def test_quotation_marks(self):
@@ -375,7 +392,8 @@ class FunctionTests(SimpleTestCase):
urlize(
'Email us at "hi@example.com", or phone us at +xx.yy', autoescape=False
),
- 'Email us at "<a href="mailto:hi@example.com">hi@example.com</a>", or phone us at +xx.yy',
+ 'Email us at "<a href="mailto:hi@example.com">hi@example.com</a>", or '
+ "phone us at +xx.yy",
)
def test_exclamation_marks(self):
@@ -385,19 +403,23 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("Go to djangoproject.com! and enjoy."),
- 'Go to <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>! and enjoy.',
+ 'Go to <a href="http://djangoproject.com" rel="nofollow">djangoproject.com'
+ "</a>! and enjoy.",
)
self.assertEqual(
urlize("Search for google.com/?q=! and see."),
- 'Search for <a href="http://google.com/?q=" rel="nofollow">google.com/?q=</a>! and see.',
+ 'Search for <a href="http://google.com/?q=" rel="nofollow">google.com/?q='
+ "</a>! and see.",
)
self.assertEqual(
urlize("Search for google.com/?q=dj!`? and see."),
- 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a> and see.',
+ 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">'
+ "google.com/?q=dj!`?</a> and see.",
)
self.assertEqual(
urlize("Search for google.com/?q=dj!`?! and see."),
- 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a>! and see.',
+ 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">'
+ "google.com/?q=dj!`?</a>! and see.",
)
def test_non_string_input(self):
@@ -406,13 +428,15 @@ class FunctionTests(SimpleTestCase):
def test_autoescape(self):
self.assertEqual(
urlize('foo<a href=" google.com ">bar</a>buz'),
- 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com</a> &quot;&gt;bar&lt;/a&gt;buz',
+ 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com'
+ "</a> &quot;&gt;bar&lt;/a&gt;buz",
)
def test_autoescape_off(self):
self.assertEqual(
urlize('foo<a href=" google.com ">bar</a>buz', autoescape=False),
- 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz',
+ 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">'
+ "bar</a>buz",
)
def test_lazystring(self):
diff --git a/tests/template_tests/filter_tests/test_urlizetrunc.py b/tests/template_tests/filter_tests/test_urlizetrunc.py
index 69e4ec4741..752ee3571e 100644
--- a/tests/template_tests/filter_tests/test_urlizetrunc.py
+++ b/tests/template_tests/filter_tests/test_urlizetrunc.py
@@ -8,7 +8,10 @@ from ..utils import setup
class UrlizetruncTests(SimpleTestCase):
@setup(
{
- "urlizetrunc01": '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% endautoescape %}'
+ "urlizetrunc01": (
+ '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'
+ "{% endautoescape %}"
+ )
}
)
def test_urlizetrunc01(self):
@@ -21,8 +24,10 @@ class UrlizetruncTests(SimpleTestCase):
)
self.assertEqual(
output,
- '"Unsafe" <a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> '
- '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>',
+ '"Unsafe" '
+ '<a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> '
+ "&quot;Safe&quot; "
+ '<a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>',
)
@setup({"urlizetrunc02": '{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'})
@@ -36,8 +41,10 @@ class UrlizetruncTests(SimpleTestCase):
)
self.assertEqual(
output,
- '&quot;Unsafe&quot; <a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> '
- '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>',
+ '&quot;Unsafe&quot; <a href="http://example.com/x=&amp;y=" rel="nofollow">'
+ "http://…</a> "
+ '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">'
+ "http://…</a>",
)
@@ -72,11 +79,12 @@ class FunctionTests(SimpleTestCase):
def test_query_string(self):
self.assertEqual(
urlizetrunc(
- "http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=",
+ "http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search"
+ "&meta=",
20,
),
- '<a href="http://www.google.co.uk/search?hl=en&amp;q=some+long+url&amp;btnG=Search&amp;'
- 'meta=" rel="nofollow">http://www.google.c…</a>',
+ '<a href="http://www.google.co.uk/search?hl=en&amp;q=some+long+url&amp;'
+ 'btnG=Search&amp;meta=" rel="nofollow">http://www.google.c…</a>',
)
def test_non_string_input(self):
@@ -85,11 +93,13 @@ class FunctionTests(SimpleTestCase):
def test_autoescape(self):
self.assertEqual(
urlizetrunc('foo<a href=" google.com ">bar</a>buz', 10),
- 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com</a> &quot;&gt;bar&lt;/a&gt;buz',
+ 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com'
+ "</a> &quot;&gt;bar&lt;/a&gt;buz",
)
def test_autoescape_off(self):
self.assertEqual(
urlizetrunc('foo<a href=" google.com ">bar</a>buz', 9, autoescape=False),
- 'foo<a href=" <a href="http://google.com" rel="nofollow">google.c…</a> ">bar</a>buz',
+ 'foo<a href=" <a href="http://google.com" rel="nofollow">google.c…</a> ">'
+ "bar</a>buz",
)
diff --git a/tests/template_tests/filter_tests/test_wordcount.py b/tests/template_tests/filter_tests/test_wordcount.py
index d15447086f..d3a1eb05f1 100644
--- a/tests/template_tests/filter_tests/test_wordcount.py
+++ b/tests/template_tests/filter_tests/test_wordcount.py
@@ -8,7 +8,10 @@ from ..utils import setup
class WordcountTests(SimpleTestCase):
@setup(
{
- "wordcount01": "{% autoescape off %}{{ a|wordcount }} {{ b|wordcount }}{% endautoescape %}"
+ "wordcount01": (
+ "{% autoescape off %}{{ a|wordcount }} {{ b|wordcount }}"
+ "{% endautoescape %}"
+ )
}
)
def test_wordcount01(self):
diff --git a/tests/template_tests/filter_tests/test_wordwrap.py b/tests/template_tests/filter_tests/test_wordwrap.py
index fb2bce5a90..88fbd274da 100644
--- a/tests/template_tests/filter_tests/test_wordwrap.py
+++ b/tests/template_tests/filter_tests/test_wordwrap.py
@@ -9,7 +9,10 @@ from ..utils import setup
class WordwrapTests(SimpleTestCase):
@setup(
{
- "wordwrap01": '{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}{% endautoescape %}'
+ "wordwrap01": (
+ '{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}'
+ "{% endautoescape %}"
+ )
}
)
def test_wordwrap01(self):
@@ -30,28 +33,34 @@ class FunctionTests(SimpleTestCase):
def test_wrap(self):
self.assertEqual(
wordwrap(
- "this is a long paragraph of text that really needs to be wrapped I'm afraid",
+ "this is a long paragraph of text that really needs to be wrapped I'm "
+ "afraid",
14,
),
- "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid",
+ "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\n"
+ "I'm afraid",
)
def test_indent(self):
self.assertEqual(
wordwrap(
- "this is a short paragraph of text.\n But this line should be indented",
+ "this is a short paragraph of text.\n But this line should be "
+ "indented",
14,
),
- "this is a\nshort\nparagraph of\ntext.\n But this\nline should be\nindented",
+ "this is a\nshort\nparagraph of\ntext.\n But this\nline should be\n"
+ "indented",
)
def test_indent2(self):
self.assertEqual(
wordwrap(
- "this is a short paragraph of text.\n But this line should be indented",
+ "this is a short paragraph of text.\n But this line should be "
+ "indented",
15,
),
- "this is a short\nparagraph of\ntext.\n But this line\nshould be\nindented",
+ "this is a short\nparagraph of\ntext.\n But this line\nshould be\n"
+ "indented",
)
def test_non_string_input(self):
@@ -61,9 +70,11 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
wordwrap(
lazystr(
- "this is a long paragraph of text that really needs to be wrapped I'm afraid"
+ "this is a long paragraph of text that really needs to be wrapped "
+ "I'm afraid"
),
14,
),
- "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid",
+ "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\n"
+ "I'm afraid",
)
diff --git a/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py b/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
index 8ad004a899..4a162362c6 100644
--- a/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
+++ b/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
@@ -52,7 +52,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n03": "{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}"
+ "i18n03": (
+ "{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}"
+ )
}
)
def test_i18n03(self):
@@ -62,7 +64,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n04": "{% load i18n %}{% blocktranslate with berta=anton|lower %}{{ berta }}{% endblocktranslate %}"
+ "i18n04": (
+ "{% load i18n %}{% blocktranslate with berta=anton|lower %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n04(self):
@@ -72,8 +77,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "legacyi18n04": "{% load i18n %}"
- "{% blocktranslate with anton|lower as berta %}{{ berta }}{% endblocktranslate %}"
+ "legacyi18n04": (
+ "{% load i18n %}"
+ "{% blocktranslate with anton|lower as berta %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_legacyi18n04(self):
@@ -83,7 +91,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n05": "{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx{% endblocktranslate %}"
+ "i18n05": (
+ "{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n05(self):
@@ -141,8 +152,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n17": "{% load i18n %}"
- "{% blocktranslate with berta=anton|escape %}{{ berta }}{% endblocktranslate %}"
+ "i18n17": (
+ "{% load i18n %}"
+ "{% blocktranslate with berta=anton|escape %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n17(self):
@@ -155,8 +169,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n18": "{% load i18n %}"
- "{% blocktranslate with berta=anton|force_escape %}{{ berta }}{% endblocktranslate %}"
+ "i18n18": (
+ "{% load i18n %}"
+ "{% blocktranslate with berta=anton|force_escape %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n18(self):
@@ -165,7 +182,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n19": "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ "i18n19": (
+ "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ )
}
)
def test_i18n19(self):
@@ -174,7 +193,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n21": "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ "i18n21": (
+ "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ )
}
)
def test_i18n21(self):
@@ -183,8 +204,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "legacyi18n17": "{% load i18n %}"
- "{% blocktranslate with anton|escape as berta %}{{ berta }}{% endblocktranslate %}"
+ "legacyi18n17": (
+ "{% load i18n %}"
+ "{% blocktranslate with anton|escape as berta %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_legacyi18n17(self):
@@ -220,9 +244,12 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "legacyi18n26": "{% load i18n %}"
- "{% blocktranslate with myextra_field as extra_field count number as counter %}"
- "singular {{ extra_field }}{% plural %}plural{% endblocktranslate %}"
+ "legacyi18n26": (
+ "{% load i18n %}"
+ "{% blocktranslate with myextra_field as extra_field "
+ "count number as counter %}singular {{ extra_field }}{% plural %}plural"
+ "{% endblocktranslate %}"
+ )
}
)
def test_legacyi18n26(self):
@@ -262,8 +289,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n28": "{% load i18n %}"
- "{% blocktranslate with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktranslate %}"
+ "i18n28": (
+ "{% load i18n %}"
+ "{% blocktranslate with a=anton b=berta %}{{ a }} + {{ b }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n28(self):
@@ -288,7 +318,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
# this should work as if blocktranslate was not there (#19915)
@setup(
{
- "i18n34": "{% load i18n %}{% blocktranslate %}{{ missing }}{% endblocktranslate %}"
+ "i18n34": (
+ "{% load i18n %}{% blocktranslate %}{{ missing }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n34(self):
@@ -300,7 +333,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n34_2": "{% load i18n %}{% blocktranslate with a='α' %}{{ missing }}{% endblocktranslate %}"
+ "i18n34_2": (
+ "{% load i18n %}{% blocktranslate with a='α' %}{{ missing }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n34_2(self):
@@ -312,7 +348,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n34_3": "{% load i18n %}{% blocktranslate with a=anton %}{{ missing }}{% endblocktranslate %}"
+ "i18n34_3": (
+ "{% load i18n %}{% blocktranslate with a=anton %}{{ missing }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n34_3(self):
@@ -337,9 +376,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
# blocktranslate tag with asvar
@setup(
{
- "i18n39": "{% load i18n %}"
- "{% blocktranslate asvar page_not_found %}Page not found{% endblocktranslate %}"
- ">{{ page_not_found }}<"
+ "i18n39": (
+ "{% load i18n %}"
+ "{% blocktranslate asvar page_not_found %}Page not found"
+ "{% endblocktranslate %}>{{ page_not_found }}<"
+ )
}
)
def test_i18n39(self):
@@ -377,7 +418,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "template": "{% load i18n %}{% blocktranslate asvar %}Yes{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate asvar %}Yes{% endblocktranslate %}"
+ )
}
)
def test_blocktrans_syntax_error_missing_assignment(self, tag_name):
@@ -394,7 +437,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "template": "{% load i18n %}{% blocktranslate %}{% block b %} {% endblock %}{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate %}{% block b %} {% endblock %}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_with_block(self, tag_name):
@@ -414,15 +460,19 @@ class I18nBlockTransTagTests(SimpleTestCase):
}
)
def test_with_for(self, tag_name):
- msg = "'{}' doesn't allow other block tags (seen 'for b in [1, 2, 3]') inside it".format(
- tag_name
+ msg = (
+ f"'{tag_name}' doesn't allow other block tags (seen 'for b in [1, 2, 3]') "
+ f"inside it"
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
@setup(
{
- "template": "{% load i18n %}{% blocktranslate with foo=bar with %}{{ foo }}{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate with foo=bar with %}{{ foo }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_variable_twice(self):
@@ -443,7 +493,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "template": "{% load i18n %}{% blocktranslate count a %}{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate count a %}{% endblocktranslate %}"
+ )
}
)
def test_count(self, tag_name):
@@ -509,12 +561,14 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
# Existing context... using a literal
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "month name" %}May{% endblocktranslate %}'
+ "{% load i18n %}"
+ '{% blocktranslate context "month name" %}May{% endblocktranslate %}'
)
rendered = t.render(Context())
self.assertEqual(rendered, "Mai")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "verb" %}May{% endblocktranslate %}'
+ "{% load i18n %}"
+ '{% blocktranslate context "verb" %}May{% endblocktranslate %}'
)
rendered = t.render(Context())
self.assertEqual(rendered, "Kann")
@@ -535,51 +589,65 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
# Using a filter
t = self.get_template(
- "{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}"
+ "{% load i18n %}"
+ "{% blocktranslate context message_context|lower %}May"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"message_context": "MONTH NAME"}))
self.assertEqual(rendered, "Mai")
t = self.get_template(
- "{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}"
+ "{% load i18n %}"
+ "{% blocktranslate context message_context|lower %}May"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"message_context": "VERB"}))
self.assertEqual(rendered, "Kann")
# Using 'count'
t = self.get_template(
- '{% load i18n %}{% blocktranslate count number=1 context "super search" %}'
- "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate count number=1 context "super search" %}{{ number }}'
+ " super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "1 Super-Ergebnis")
t = self.get_template(
- '{% load i18n %}{% blocktranslate count number=2 context "super search" %}{{ number }}'
- " super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate count number=2 context "super search" %}{{ number }}'
+ " super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "2 Super-Ergebnisse")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "other super search" count number=1 %}'
- "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate context "other super search" count number=1 %}'
+ "{{ number }} super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "1 anderen Super-Ergebnis")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "other super search" count number=2 %}'
- "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate context "other super search" count number=2 %}'
+ "{{ number }} super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "2 andere Super-Ergebnisse")
# Using 'with'
t = self.get_template(
- '{% load i18n %}{% blocktranslate with num_comments=5 context "comment count" %}'
+ "{% load i18n %}"
+ '{% blocktranslate with num_comments=5 context "comment count" %}'
"There are {{ num_comments }} comments{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Es gibt 5 Kommentare")
t = self.get_template(
- '{% load i18n %}{% blocktranslate with num_comments=5 context "other comment count" %}'
+ "{% load i18n %}"
+ '{% blocktranslate with num_comments=5 context "other comment count" %}'
"There are {{ num_comments }} comments{% endblocktranslate %}"
)
rendered = t.render(Context())
@@ -593,14 +661,19 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
rendered = t.render(Context())
self.assertEqual(rendered, "There are 5 comments")
t = self.get_template(
- '{% load i18n %}{% blocktranslate with num_comments=5 context "comment count" trimmed %}\n\n'
- "There are \t\n \t {{ num_comments }} comments\n\n{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate with num_comments=5 context "comment count" trimmed '
+ "%}\n\n"
+ "There are \t\n \t {{ num_comments }} comments\n\n"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Es gibt 5 Kommentare")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "other super search" count number=2 trimmed %}\n'
- "{{ number }} super \n result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate context "other super search" count number=2 trimmed '
+ "%}\n{{ number }} super \n result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "2 andere Super-Ergebnisse")
@@ -609,7 +682,8 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
msg = "Unknown argument for 'blocktranslate' tag: %r."
with self.assertRaisesMessage(TemplateSyntaxError, msg % 'month="May"'):
self.get_template(
- '{% load i18n %}{% blocktranslate context with month="May" %}{{ month }}{% endblocktranslate %}'
+ '{% load i18n %}{% blocktranslate context with month="May" %}'
+ "{{ month }}{% endblocktranslate %}"
)
msg = (
'"context" in %r tag expected exactly one argument.' % "blocktranslate"
@@ -633,7 +707,8 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
"""
with translation.override("fr"):
t = Template(
- "{% load i18n %}{% blocktranslate %}My name is {{ person }}.{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}My name is {{ person }}."
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"person": "James"}))
self.assertEqual(rendered, "My name is James.")
@@ -647,7 +722,8 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
"""
with translation.override("fr"):
t = Template(
- "{% load i18n %}{% blocktranslate %}My other name is {{ person }}.{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}My other name is {{ person }}."
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"person": "James"}))
self.assertEqual(rendered, "My other name is James.")
@@ -728,7 +804,8 @@ class MiscTests(SimpleTestCase):
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_percent_in_translatable_block(self):
t_sing = self.get_template(
- "{% load i18n %}{% blocktranslate %}The result was {{ percent }}%{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}The result was {{ percent }}%"
+ "{% endblocktranslate %}"
)
t_plur = self.get_template(
"{% load i18n %}{% blocktranslate count num as number %}"
@@ -755,7 +832,8 @@ class MiscTests(SimpleTestCase):
or plural.
"""
t_sing = self.get_template(
- "{% load i18n %}{% blocktranslate %}There are %(num_comments)s comments{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}There are %(num_comments)s comments"
+ "{% endblocktranslate %}"
)
t_plur = self.get_template(
"{% load i18n %}{% blocktranslate count num as number %}"
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py b/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
index dce5a4de66..ce2e60c0d9 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
@@ -20,6 +20,9 @@ class GetAvailableLanguagesTagTests(SimpleTestCase):
@setup({"syntax_i18n": "{% load i18n %}{% get_available_languages a langs %}"})
def test_no_as_var(self):
- msg = "'get_available_languages' requires 'as variable' (got ['get_available_languages', 'a', 'langs'])"
+ msg = (
+ "'get_available_languages' requires 'as variable' (got "
+ "['get_available_languages', 'a', 'langs'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("syntax_i18n")
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_current_language.py b/tests/template_tests/syntax_tests/i18n/test_get_current_language.py
index 8ed7f742c2..7de1b53bd9 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_current_language.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_current_language.py
@@ -9,6 +9,9 @@ class I18nGetCurrentLanguageTagTests(SimpleTestCase):
@setup({"template": "{% load i18n %} {% get_current_language %}"})
def test_no_as_var(self):
- msg = "'get_current_language' requires 'as variable' (got ['get_current_language'])"
+ msg = (
+ "'get_current_language' requires 'as variable' (got "
+ "['get_current_language'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py b/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
index 3f307471ae..9b57047209 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
@@ -9,6 +9,9 @@ class I18nGetCurrentLanguageBidiTagTests(SimpleTestCase):
@setup({"template": "{% load i18n %} {% get_current_language_bidi %}"})
def test_no_as_var(self):
- msg = "'get_current_language_bidi' requires 'as variable' (got ['get_current_language_bidi'])"
+ msg = (
+ "'get_current_language_bidi' requires 'as variable' (got "
+ "['get_current_language_bidi'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py b/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
index 93038daa2f..962c888782 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
@@ -65,6 +65,9 @@ class GetLanguageInfoListTests(SimpleTestCase):
@setup({"i18n_syntax": "{% load i18n %} {% get_language_info_list error %}"})
def test_no_for_as(self):
- msg = "'get_language_info_list' requires 'for sequence as variable' (got ['error'])"
+ msg = (
+ "'get_language_info_list' requires 'for sequence as variable' (got "
+ "['error'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("i18n_syntax")
diff --git a/tests/template_tests/syntax_tests/i18n/test_translate.py b/tests/template_tests/syntax_tests/i18n/test_translate.py
index 932b47a373..d8a224df9d 100644
--- a/tests/template_tests/syntax_tests/i18n/test_translate.py
+++ b/tests/template_tests/syntax_tests/i18n/test_translate.py
@@ -84,7 +84,9 @@ class I18nTransTagTests(SimpleTestCase):
@setup(
{
- "i18n23": '{% load i18n %}{% translate "Page not found"|capfirst|slice:"6:" %}'
+ "i18n23": (
+ '{% load i18n %}{% translate "Page not found"|capfirst|slice:"6:" %}'
+ )
}
)
def test_i18n23(self):
@@ -110,7 +112,10 @@ class I18nTransTagTests(SimpleTestCase):
# trans tag with as var
@setup(
{
- "i18n35": '{% load i18n %}{% translate "Page not found" as page_not_found %}{{ page_not_found }}'
+ "i18n35": (
+ '{% load i18n %}{% translate "Page not found" as page_not_found %}'
+ "{{ page_not_found }}"
+ )
}
)
def test_i18n35(self):
@@ -120,8 +125,10 @@ class I18nTransTagTests(SimpleTestCase):
@setup(
{
- "i18n36": "{% load i18n %}"
- '{% translate "Page not found" noop as page_not_found %}{{ page_not_found }}'
+ "i18n36": (
+ '{% load i18n %}{% translate "Page not found" noop as page_not_found %}'
+ "{{ page_not_found }}"
+ )
}
)
def test_i18n36(self):
@@ -157,16 +164,18 @@ class I18nTransTagTests(SimpleTestCase):
@setup({"template": '{% load i18n %}{% translate "Yes" context as var %}'})
def test_syntax_error_context_as(self, tag_name):
- msg = "Invalid argument 'as' provided to the '{}' tag for the context option".format(
- tag_name
+ msg = (
+ f"Invalid argument 'as' provided to the '{tag_name}' tag for the context "
+ f"option"
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
@setup({"template": '{% load i18n %}{% translate "Yes" context noop %}'})
def test_syntax_error_context_noop(self, tag_name):
- msg = "Invalid argument 'noop' provided to the '{}' tag for the context option".format(
- tag_name
+ msg = (
+ f"Invalid argument 'noop' provided to the '{tag_name}' tag for the context "
+ f"option"
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
@@ -240,12 +249,14 @@ class TranslationTransTagTests(SimpleTestCase):
# Using 'as'
t = self.get_template(
- '{% load i18n %}{% translate "May" context "month name" as var %}Value: {{ var }}'
+ '{% load i18n %}{% translate "May" context "month name" as var %}'
+ "Value: {{ var }}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Value: Mai")
t = self.get_template(
- '{% load i18n %}{% translate "May" as var context "verb" %}Value: {{ var }}'
+ '{% load i18n %}{% translate "May" as var context "verb" %}Value: '
+ "{{ var }}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Value: Kann")
diff --git a/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py b/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
index dfb035999c..ac6a22ed46 100644
--- a/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
+++ b/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
@@ -90,7 +90,10 @@ class I18nStringLiteralTests(SimpleTestCase):
@setup(
{
- "i18n14": '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}'
+ "i18n14": (
+ '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} '
+ "{% cycle c %}"
+ )
}
)
def test_i18n14(self):
diff --git a/tests/template_tests/syntax_tests/test_autoescape.py b/tests/template_tests/syntax_tests/test_autoescape.py
index d3c5cb02da..a45b850fcf 100644
--- a/tests/template_tests/syntax_tests/test_autoescape.py
+++ b/tests/template_tests/syntax_tests/test_autoescape.py
@@ -28,7 +28,10 @@ class AutoescapeTagTests(SimpleTestCase):
# Autoescape disabling and enabling nest in a predictable way.
@setup(
{
- "autoescape-tag04": "{% autoescape off %}{{ first }} {% autoescape on %}{{ first }}{% endautoescape %}{% endautoescape %}"
+ "autoescape-tag04": (
+ "{% autoescape off %}{{ first }} {% autoescape on %}{{ first }}"
+ "{% endautoescape %}{% endautoescape %}"
+ )
}
)
def test_autoescape_tag04(self):
@@ -60,7 +63,10 @@ class AutoescapeTagTests(SimpleTestCase):
@setup(
{
- "autoescape-tag08": r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}'
+ "autoescape-tag08": (
+ r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}'
+ r"{% endautoescape %}"
+ )
}
)
def test_autoescape_tag08(self):
@@ -86,7 +92,9 @@ class AutoescapeTagTests(SimpleTestCase):
@setup(
{
- "autoescape-filtertag01": "{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}"
+ "autoescape-filtertag01": (
+ "{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}"
+ )
}
)
def test_autoescape_filtertag01(self):
@@ -143,7 +151,9 @@ class AutoescapeTagTests(SimpleTestCase):
@setup(
{
- "autoescape-incorrect-arg": "{% autoescape true %}{{ var.key }}{% endautoescape %}"
+ "autoescape-incorrect-arg": (
+ "{% autoescape true %}{{ var.key }}{% endautoescape %}"
+ )
}
)
def test_invalid_arg(self):
diff --git a/tests/template_tests/syntax_tests/test_cache.py b/tests/template_tests/syntax_tests/test_cache.py
index a722420637..9dcf9a6b5a 100644
--- a/tests/template_tests/syntax_tests/test_cache.py
+++ b/tests/template_tests/syntax_tests/test_cache.py
@@ -105,7 +105,10 @@ class CacheTagTests(SimpleTestCase):
@setup(
{
- "cache17": "{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}"
+ "cache17": (
+ "{% load cache %}{% cache 10 long_cache_key poem %}Some Content"
+ "{% endcache %}"
+ )
}
)
def test_cache17(self):
@@ -119,8 +122,8 @@ class CacheTagTests(SimpleTestCase):
"Oh freddled gruntbuggly/Thy micturations are to me/"
"As plurdled gabbleblotchits/On a lurgid bee/"
"That mordiously hath bitled out/Its earted jurtles/"
- "Into a rancid festering/Or else I shall rend thee in the gobberwarts"
- "with my blurglecruncheon/See if I don't."
+ "Into a rancid festering/Or else I shall rend thee in the "
+ "gobberwarts with my blurglecruncheon/See if I don't."
),
},
)
@@ -128,7 +131,10 @@ class CacheTagTests(SimpleTestCase):
@setup(
{
- "cache18": '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}'
+ "cache18": (
+ '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18'
+ "{% endcache %}"
+ )
}
)
def test_cache18(self):
@@ -141,7 +147,9 @@ class CacheTagTests(SimpleTestCase):
@setup(
{
"first": "{% load cache %}{% cache None fragment19 %}content{% endcache %}",
- "second": "{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}",
+ "second": (
+ "{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}"
+ ),
}
)
def test_none_timeout(self):
diff --git a/tests/template_tests/syntax_tests/test_cycle.py b/tests/template_tests/syntax_tests/test_cycle.py
index d4233fac3e..cff0363e38 100644
--- a/tests/template_tests/syntax_tests/test_cycle.py
+++ b/tests/template_tests/syntax_tests/test_cycle.py
@@ -35,7 +35,10 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle12": "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}"
+ "cycle12": (
+ "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}"
+ "{% cycle abc %}"
+ )
}
)
def test_cycle12(self):
@@ -106,7 +109,10 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle22": "{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}"
+ "cycle22": (
+ "{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}"
+ "{% endfor %}"
+ )
}
)
def test_cycle22(self):
@@ -125,8 +131,11 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle24": "{% for x in values %}"
- "{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}",
+ "cycle24": (
+ "{% for x in values %}"
+ "{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}"
+ "{% endfor %}"
+ ),
"included-cycle": "{{ abc }}",
}
)
@@ -146,7 +155,10 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle27": "{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}"
+ "cycle27": (
+ "{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}"
+ "{% endautoescape %}"
+ )
}
)
def test_cycle27(self):
diff --git a/tests/template_tests/syntax_tests/test_exceptions.py b/tests/template_tests/syntax_tests/test_exceptions.py
index 7000b45afd..b6d86ac42b 100644
--- a/tests/template_tests/syntax_tests/test_exceptions.py
+++ b/tests/template_tests/syntax_tests/test_exceptions.py
@@ -42,13 +42,17 @@ class ExceptionsTests(SimpleTestCase):
@setup(
{
- "exception04": "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}"
+ "exception04": (
+ "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678"
+ "{% endblock %}"
+ )
},
inheritance_templates,
)
def test_exception04(self):
"""
- Raise exception for custom tags used in child with {% load %} tag in parent, not in child
+ Raise exception for custom tags used in child with {% load %} tag in
+ parent, not in child
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template("exception04")
diff --git a/tests/template_tests/syntax_tests/test_extends.py b/tests/template_tests/syntax_tests/test_extends.py
index ce073fb909..9f5dae0db4 100644
--- a/tests/template_tests/syntax_tests/test_extends.py
+++ b/tests/template_tests/syntax_tests/test_extends.py
@@ -6,7 +6,9 @@ from django.test import SimpleTestCase
from ..utils import setup
inheritance_templates = {
- "inheritance01": "1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}",
+ "inheritance01": (
+ "1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}"
+ ),
"inheritance02": "{% extends 'inheritance01' %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
"inheritance03": "{% extends 'inheritance02' %}",
@@ -22,7 +24,9 @@ inheritance_templates = {
"inheritance12": "{% extends 'inheritance07' %}{% block first %}2{% endblock %}",
"inheritance13": "{% extends 'inheritance02' %}"
"{% block first %}a{% endblock %}{% block second %}b{% endblock %}",
- "inheritance14": "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}",
+ "inheritance14": (
+ "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}"
+ ),
"inheritance15": "{% extends 'inheritance01' %}"
"{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}",
"inheritance16": "{% extends 'inheritance15' %}{% block inner %}out{% endblock %}",
@@ -30,10 +34,18 @@ inheritance_templates = {
"inheritance18": "{% load testtags %}{% echo this that theother %}5678",
"inheritance19": "{% extends 'inheritance01' %}"
"{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}",
- "inheritance20": "{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}",
- "inheritance21": "{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}",
- "inheritance22": "{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}",
- "inheritance23": "{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}",
+ "inheritance20": (
+ "{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}"
+ ),
+ "inheritance21": (
+ "{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}"
+ ),
+ "inheritance22": (
+ "{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}"
+ ),
+ "inheritance23": (
+ "{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}"
+ ),
"inheritance24": "{% extends context_template %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
"inheritance25": "{% extends context_template.1 %}"
@@ -45,19 +57,32 @@ inheritance_templates = {
"inheritance30": "1{% if optional %}{% block opt %}2{% endblock %}{% endif %}3",
"inheritance31": "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}",
"inheritance32": "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}",
- "inheritance33": "1{% if optional == 1 %}{% block opt %}2{% endblock %}{% endif %}3",
+ "inheritance33": (
+ "1{% if optional == 1 %}{% block opt %}2{% endblock %}{% endif %}3"
+ ),
"inheritance34": "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}",
"inheritance35": "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}",
- "inheritance36": "{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_",
+ "inheritance36": (
+ "{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_"
+ ),
"inheritance37": "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}",
"inheritance38": "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}",
- "inheritance39": "{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}",
- "inheritance40": "{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}",
- "inheritance41": "{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}",
+ "inheritance39": (
+ "{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}"
+ ),
+ "inheritance40": (
+ "{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}"
+ ),
+ "inheritance41": (
+ "{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}"
+ ),
"inheritance42": "{% extends 'inheritance02'|cut:' ' %}",
"inheritance_empty": "{% extends %}",
"extends_duplicate": "{% extends 'base.html' %}{% extends 'base.html' %}",
- "duplicate_block": "{% extends 'base.html' %}{% block content %}2{% endblock %}{% block content %}4{% endblock %}",
+ "duplicate_block": (
+ "{% extends 'base.html' %}{% block content %}2{% endblock %}{% block content %}"
+ "4{% endblock %}"
+ ),
}
diff --git a/tests/template_tests/syntax_tests/test_for.py b/tests/template_tests/syntax_tests/test_for.py
index ad1d158f9b..a47a99ac65 100644
--- a/tests/template_tests/syntax_tests/test_for.py
+++ b/tests/template_tests/syntax_tests/test_for.py
@@ -34,7 +34,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-vars03": "{% for val in values %}{{ forloop.revcounter }}{% endfor %}"
+ "for-tag-vars03": (
+ "{% for val in values %}{{ forloop.revcounter }}{% endfor %}"
+ )
}
)
def test_for_tag_vars03(self):
@@ -43,7 +45,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-vars04": "{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}"
+ "for-tag-vars04": (
+ "{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}"
+ )
}
)
def test_for_tag_vars04(self):
@@ -72,7 +76,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack01": "{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack01": (
+ "{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack01(self):
@@ -83,7 +89,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack03": "{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack03": (
+ "{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack03(self):
@@ -94,7 +102,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack04": "{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack04": (
+ "{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack04(self):
@@ -105,7 +115,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack05": "{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack05": (
+ "{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack05(self):
@@ -116,7 +128,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack06": "{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack06": (
+ "{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack06(self):
@@ -128,7 +142,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack07": "{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack07": (
+ "{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack07(self):
@@ -140,7 +156,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack08": "{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack08": (
+ "{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack08(self):
@@ -170,7 +188,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack09": "{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}"
+ "for-tag-unpack09": (
+ "{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack09(self):
@@ -184,7 +204,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack13": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ "for-tag-unpack13": (
+ "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack13(self):
@@ -198,7 +220,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-empty01": "{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}"
+ "for-tag-empty01": (
+ "{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}"
+ )
}
)
def test_for_tag_empty01(self):
@@ -207,7 +231,10 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-empty02": "{% for val in values %}{{ val }}{% empty %}values array empty{% endfor %}"
+ "for-tag-empty02": (
+ "{% for val in values %}{{ val }}{% empty %}values array empty"
+ "{% endfor %}"
+ )
}
)
def test_for_tag_empty02(self):
@@ -226,7 +253,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-filter-ws": "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}"
+ "for-tag-filter-ws": (
+ "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}"
+ )
}
)
def test_for_tag_filter_ws(self):
@@ -257,7 +286,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack11": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ "for-tag-unpack11": (
+ "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack11(self):
@@ -271,7 +302,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack12": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ "for-tag-unpack12": (
+ "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack12(self):
diff --git a/tests/template_tests/syntax_tests/test_if.py b/tests/template_tests/syntax_tests/test_if.py
index fda44b0672..36077f0687 100644
--- a/tests/template_tests/syntax_tests/test_if.py
+++ b/tests/template_tests/syntax_tests/test_if.py
@@ -53,7 +53,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag10": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag10": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag10(self):
@@ -62,7 +65,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag11": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag11": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag11(self):
@@ -71,7 +77,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag12": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag12": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag12(self):
@@ -80,7 +89,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag13": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag13": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag13(self):
@@ -588,7 +600,9 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "else-if-tag-error01": "{% if foo is bar %} yes {% else if foo is not bar %} no {% endif %}"
+ "else-if-tag-error01": (
+ "{% if foo is bar %} yes {% else if foo is not bar %} no {% endif %}"
+ )
}
)
def test_else_if_tag_error01(self):
@@ -598,7 +612,9 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag-shortcircuit01": "{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}"
+ "if-tag-shortcircuit01": (
+ "{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}"
+ )
}
)
def test_if_tag_shortcircuit01(self):
@@ -610,7 +626,9 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag-shortcircuit02": "{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}"
+ "if-tag-shortcircuit02": (
+ "{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}"
+ )
}
)
def test_if_tag_shortcircuit02(self):
diff --git a/tests/template_tests/syntax_tests/test_if_changed.py b/tests/template_tests/syntax_tests/test_if_changed.py
index 3835e52d78..fb0a693460 100644
--- a/tests/template_tests/syntax_tests/test_if_changed.py
+++ b/tests/template_tests/syntax_tests/test_if_changed.py
@@ -9,7 +9,9 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged01": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ "ifchanged01": (
+ "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ )
}
)
def test_ifchanged01(self):
@@ -18,7 +20,9 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged02": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ "ifchanged02": (
+ "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ )
}
)
def test_ifchanged02(self):
@@ -27,7 +31,9 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged03": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ "ifchanged03": (
+ "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ )
}
)
def test_ifchanged03(self):
@@ -108,8 +114,10 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param01": "{% for n in num %}{% ifchanged n %}..{% endifchanged %}"
- "{{ n }}{% endfor %}"
+ "ifchanged-param01": (
+ "{% for n in num %}{% ifchanged n %}..{% endifchanged %}"
+ "{{ n }}{% endfor %}"
+ )
}
)
def test_ifchanged_param01(self):
@@ -121,8 +129,11 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param02": "{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}"
- "{{ x }}{% endfor %}{% endfor %}"
+ "ifchanged-param02": (
+ "{% for n in num %}{% for x in numx %}"
+ "{% ifchanged n %}..{% endifchanged %}{{ x }}"
+ "{% endfor %}{% endfor %}"
+ )
}
)
def test_ifchanged_param02(self):
@@ -149,9 +160,11 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param04": "{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}"
- "{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}"
- "{% endfor %}{% endfor %}"
+ "ifchanged-param04": (
+ "{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}"
+ "{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}"
+ "{% endfor %}{% endfor %}"
+ )
}
)
def test_ifchanged_param04(self):
@@ -167,9 +180,11 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param05": "{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}"
- "{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}"
- "{% endfor %}{% endfor %}"
+ "ifchanged-param05": (
+ "{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}"
+ "{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}"
+ "{% endfor %}{% endfor %}"
+ )
}
)
def test_ifchanged_param05(self):
@@ -275,7 +290,8 @@ class IfChangedTests(SimpleTestCase):
yield 1
yield 2
# Simulate that another thread is now rendering.
- # When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below.
+ # When the IfChangeNode stores state at 'self' it stays at '3' and
+ # skip the last yielded value below.
iter2 = iter([1, 2, 3])
output2 = template.render(
Context({"foo": range(3), "get_value": lambda: next(iter2)})
@@ -319,7 +335,9 @@ class IfChangedTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- "template": '{% for x in vars %}{% include "include" %}{% endfor %}',
+ "template": (
+ '{% for x in vars %}{% include "include" %}{% endfor %}'
+ ),
"include": "{% ifchanged %}{{ x }}{% endifchanged %}",
},
),
@@ -335,7 +353,10 @@ class IfChangedTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- "template": '{% for x in vars %}{% include "include" %}{% include "include" %}{% endfor %}',
+ "template": (
+ '{% for x in vars %}{% include "include" %}'
+ '{% include "include" %}{% endfor %}'
+ ),
"include": "{% ifchanged %}{{ x }}{% endifchanged %}",
},
),
diff --git a/tests/template_tests/syntax_tests/test_include.py b/tests/template_tests/syntax_tests/test_include.py
index add2ca139f..3ee99b3798 100644
--- a/tests/template_tests/syntax_tests/test_include.py
+++ b/tests/template_tests/syntax_tests/test_include.py
@@ -73,9 +73,12 @@ class IncludeTagTests(SimpleTestCase):
@setup(
{
- "include09": "{{ first }}--"
- '{% include "basic-syntax03" with first=second|lower|upper second=first|upper %}'
- "--{{ second }}"
+ "include09": (
+ "{{ first }}--"
+ '{% include "basic-syntax03" with '
+ "first=second|lower|upper second=first|upper %}"
+ "--{{ second }}"
+ )
},
basic_templates,
)
@@ -117,7 +120,9 @@ class IncludeTagTests(SimpleTestCase):
@setup(
{
- "include13": '{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}'
+ "include13": (
+ '{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}'
+ )
},
basic_templates,
)
@@ -350,7 +355,9 @@ class IncludeTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- "template": '{% for x in vars %}{% include "include" %}{% endfor %}',
+ "template": (
+ '{% for x in vars %}{% include "include" %}{% endfor %}'
+ ),
"include": '{% include "next" %}',
"next": "{% load custom %}{% counter %}",
},
diff --git a/tests/template_tests/syntax_tests/test_invalid_string.py b/tests/template_tests/syntax_tests/test_invalid_string.py
index e65ac938ec..d8601febf1 100644
--- a/tests/template_tests/syntax_tests/test_invalid_string.py
+++ b/tests/template_tests/syntax_tests/test_invalid_string.py
@@ -55,7 +55,9 @@ class InvalidStringTests(SimpleTestCase):
@setup(
{
- "invalidstr07": "{% load i18n %}{% blocktranslate %}{{ var }}{% endblocktranslate %}"
+ "invalidstr07": (
+ "{% load i18n %}{% blocktranslate %}{{ var }}{% endblocktranslate %}"
+ )
}
)
def test_invalidstr07(self):
diff --git a/tests/template_tests/syntax_tests/test_load.py b/tests/template_tests/syntax_tests/test_load.py
index ae5f1d4b48..a13871b247 100644
--- a/tests/template_tests/syntax_tests/test_load.py
+++ b/tests/template_tests/syntax_tests/test_load.py
@@ -12,7 +12,9 @@ class LoadTagTests(SimpleTestCase):
@setup(
{
- "load01": '{% load testtags subpackage.echo %}{% echo test %} {% echo2 "test" %}'
+ "load01": (
+ '{% load testtags subpackage.echo %}{% echo test %} {% echo2 "test" %}'
+ )
}
)
def test_load01(self):
@@ -64,24 +66,36 @@ class LoadTagTests(SimpleTestCase):
@setup({"load08": "{% load echo other_echo bad_tag from %}"})
def test_load08(self):
- msg = "'echo' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'echo' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load08")
@setup({"load09": "{% load from testtags %}"})
def test_load09(self):
- msg = "'from' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'from' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load09")
@setup({"load10": "{% load echo from bad_library %}"})
def test_load10(self):
- msg = "'bad_library' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'bad_library' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load10")
@setup({"load12": "{% load subpackage.missing %}"})
def test_load12(self):
- msg = "'subpackage.missing' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'subpackage.missing' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load12")
diff --git a/tests/template_tests/syntax_tests/test_named_endblock.py b/tests/template_tests/syntax_tests/test_named_endblock.py
index 2230edf52b..7469a28778 100644
--- a/tests/template_tests/syntax_tests/test_named_endblock.py
+++ b/tests/template_tests/syntax_tests/test_named_endblock.py
@@ -48,7 +48,9 @@ class NamedEndblockTests(SimpleTestCase):
@setup(
{
- "namedendblocks05": "1{% block first %}_{% block second %}2{% endblock first %}"
+ "namedendblocks05": (
+ "1{% block first %}_{% block second %}2{% endblock first %}"
+ )
}
)
def test_namedendblocks05(self):
diff --git a/tests/template_tests/syntax_tests/test_resetcycle.py b/tests/template_tests/syntax_tests/test_resetcycle.py
index 6d7365a6ec..fb67b3368e 100644
--- a/tests/template_tests/syntax_tests/test_resetcycle.py
+++ b/tests/template_tests/syntax_tests/test_resetcycle.py
@@ -33,7 +33,9 @@ class ResetCycleTagTests(SimpleTestCase):
@setup(
{
- "resetcycle05": "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}"
+ "resetcycle05": (
+ "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}"
+ )
}
)
def test_resetcycle05(self):
diff --git a/tests/template_tests/syntax_tests/test_spaceless.py b/tests/template_tests/syntax_tests/test_spaceless.py
index 8bb20dba6c..e86c60f06b 100644
--- a/tests/template_tests/syntax_tests/test_spaceless.py
+++ b/tests/template_tests/syntax_tests/test_spaceless.py
@@ -6,7 +6,9 @@ from ..utils import setup
class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless01": "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}"
+ "spaceless01": (
+ "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}"
+ )
}
)
def test_spaceless01(self):
@@ -15,7 +17,9 @@ class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless02": "{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}"
+ "spaceless02": (
+ "{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}"
+ )
}
)
def test_spaceless02(self):
@@ -29,7 +33,9 @@ class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless04": "{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}"
+ "spaceless04": (
+ "{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}"
+ )
}
)
def test_spaceless04(self):
@@ -49,7 +55,9 @@ class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless06": "{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}"
+ "spaceless06": (
+ "{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}"
+ )
}
)
def test_spaceless06(self):
diff --git a/tests/template_tests/syntax_tests/test_static.py b/tests/template_tests/syntax_tests/test_static.py
index cd63350cb5..63265f57f3 100644
--- a/tests/template_tests/syntax_tests/test_static.py
+++ b/tests/template_tests/syntax_tests/test_static.py
@@ -44,7 +44,10 @@ class StaticTagTests(SimpleTestCase):
@setup(
{
- "t": "{% load static %}{% get_media_prefix ad media_prefix %}{{ media_prefix }}"
+ "t": (
+ "{% load static %}{% get_media_prefix ad media_prefix %}"
+ "{{ media_prefix }}"
+ )
}
)
def test_static_prefixtag_without_as(self):
@@ -66,7 +69,9 @@ class StaticTagTests(SimpleTestCase):
@setup(
{
- "static-statictag03": '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'
+ "static-statictag03": (
+ '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'
+ )
}
)
def test_static_statictag03(self):
@@ -84,7 +89,9 @@ class StaticTagTests(SimpleTestCase):
@setup(
{
- "static-statictag05": '{% load static %}{% static "special?chars&quoted.html" %}'
+ "static-statictag05": (
+ '{% load static %}{% static "special?chars&quoted.html" %}'
+ )
}
)
def test_static_quotes_urls(self):
diff --git a/tests/template_tests/syntax_tests/test_verbatim.py b/tests/template_tests/syntax_tests/test_verbatim.py
index afb08e013a..16e0239177 100644
--- a/tests/template_tests/syntax_tests/test_verbatim.py
+++ b/tests/template_tests/syntax_tests/test_verbatim.py
@@ -24,7 +24,9 @@ class VerbatimTagTests(SimpleTestCase):
@setup(
{
- "verbatim-tag04": "{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}"
+ "verbatim-tag04": (
+ "{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}"
+ )
}
)
def test_verbatim_tag04(self):
@@ -33,7 +35,9 @@ class VerbatimTagTests(SimpleTestCase):
@setup(
{
- "verbatim-tag05": "{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}"
+ "verbatim-tag05": (
+ "{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}"
+ )
}
)
def test_verbatim_tag05(self):
diff --git a/tests/template_tests/templatetags/inclusion.py b/tests/template_tests/templatetags/inclusion.py
index f9e457bbc1..c4455e4fa4 100644
--- a/tests/template_tests/templatetags/inclusion.py
+++ b/tests/template_tests/templatetags/inclusion.py
@@ -75,7 +75,9 @@ inclusion_explicit_no_context_from_template.anything = (
def inclusion_no_params_with_context(context):
"""Expected inclusion_no_params_with_context __doc__"""
return {
- "result": "inclusion_no_params_with_context - Expected result (context value: %s)"
+ "result": (
+ "inclusion_no_params_with_context - Expected result (context value: %s)"
+ )
% context["value"]
}
@@ -90,9 +92,10 @@ def inclusion_no_params_with_context_from_template(context):
"""Expected inclusion_no_params_with_context_from_template __doc__"""
return {
"result": (
- "inclusion_no_params_with_context_from_template - Expected result (context value: %s)"
- % context["value"]
+ "inclusion_no_params_with_context_from_template - Expected result (context "
+ "value: %s)"
)
+ % context["value"]
}
@@ -105,7 +108,9 @@ inclusion_no_params_with_context_from_template.anything = (
def inclusion_params_and_context(context, arg):
"""Expected inclusion_params_and_context __doc__"""
return {
- "result": "inclusion_params_and_context - Expected result (context value: %s): %s"
+ "result": (
+ "inclusion_params_and_context - Expected result (context value: %s): %s"
+ )
% (context["value"], arg)
}
diff --git a/tests/template_tests/test_custom.py b/tests/template_tests/test_custom.py
index acfb6890a5..1697d16ef5 100644
--- a/tests/template_tests/test_custom.py
+++ b/tests/template_tests/test_custom.py
@@ -111,8 +111,11 @@ class SimpleTagTests(TagTestCase):
"simple_only_unlimited_args - Expected result: 37, 42, 56, 89",
),
(
- '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}',
- "simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4",
+ "{% load custom %}"
+ '{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" '
+ "four=1|add:3 %}",
+ "simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / "
+ "eggs=scrambled, four=4",
),
]
@@ -141,7 +144,8 @@ class SimpleTagTests(TagTestCase):
"{% load custom %}{% simple_one_default 37 42 56 %}",
),
(
- "'simple_keyword_only_param' did not receive value(s) for the argument(s): 'kwarg'",
+ "'simple_keyword_only_param' did not receive value(s) for the "
+ "argument(s): 'kwarg'",
"{% load custom %}{% simple_keyword_only_param %}",
),
(
@@ -156,12 +160,18 @@ class SimpleTagTests(TagTestCase):
"kwarg=37 %}",
),
(
- "'simple_unlimited_args_kwargs' received some positional argument(s) after some keyword argument(s)",
- '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}',
+ "'simple_unlimited_args_kwargs' received some positional argument(s) "
+ "after some keyword argument(s)",
+ "{% load custom %}"
+ "{% simple_unlimited_args_kwargs 37 40|add:2 "
+ 'eggs="scrambled" 56 four=1|add:3 %}',
),
(
- "'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
- '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}',
+ "'simple_unlimited_args_kwargs' received multiple values for keyword "
+ "argument 'eggs'",
+ "{% load custom %}"
+ "{% simple_unlimited_args_kwargs 37 "
+ 'eggs="scrambled" eggs="scrambled" %}',
),
]
@@ -252,11 +262,13 @@ class InclusionTagTests(TagTestCase):
),
(
"{% load inclusion %}{% inclusion_no_params_with_context %}",
- "inclusion_no_params_with_context - Expected result (context value: 42)\n",
+ "inclusion_no_params_with_context - Expected result (context value: "
+ "42)\n",
),
(
"{% load inclusion %}{% inclusion_params_and_context 37 %}",
- "inclusion_params_and_context - Expected result (context value: 42): 37\n",
+ "inclusion_params_and_context - Expected result (context value: 42): "
+ "37\n",
),
(
"{% load inclusion %}{% inclusion_two_params 37 42 %}",
@@ -299,8 +311,11 @@ class InclusionTagTests(TagTestCase):
"inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n",
),
(
- '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}',
- "inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n",
+ "{% load inclusion %}"
+ '{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" '
+ "four=1|add:3 %}",
+ "inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / "
+ "eggs=scrambled, four=4\n",
),
]
@@ -312,7 +327,8 @@ class InclusionTagTests(TagTestCase):
errors = [
(
"'inclusion_one_default' received unexpected keyword argument 'three'",
- '{% load inclusion %}{% inclusion_one_default 99 two="hello" three="foo" %}',
+ "{% load inclusion %}"
+ '{% inclusion_one_default 99 two="hello" three="foo" %}',
),
(
"'inclusion_two_params' received too many positional arguments",
@@ -323,7 +339,8 @@ class InclusionTagTests(TagTestCase):
"{% load inclusion %}{% inclusion_one_default 37 42 56 %}",
),
(
- "'inclusion_one_default' did not receive value(s) for the argument(s): 'one'",
+ "'inclusion_one_default' did not receive value(s) for the argument(s): "
+ "'one'",
"{% load inclusion %}{% inclusion_one_default %}",
),
(
@@ -333,17 +350,23 @@ class InclusionTagTests(TagTestCase):
"kwarg=37 kwarg=42 %}",
),
(
- "'inclusion_unlimited_args' did not receive value(s) for the argument(s): 'one'",
+ "'inclusion_unlimited_args' did not receive value(s) for the "
+ "argument(s): 'one'",
"{% load inclusion %}{% inclusion_unlimited_args %}",
),
(
- "'inclusion_unlimited_args_kwargs' received some positional argument(s) "
- "after some keyword argument(s)",
- '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="boiled" 56 four=1|add:3 %}',
+ "'inclusion_unlimited_args_kwargs' received some positional "
+ "argument(s) after some keyword argument(s)",
+ "{% load inclusion %}"
+ "{% inclusion_unlimited_args_kwargs 37 40|add:2 "
+ 'eggs="boiled" 56 four=1|add:3 %}',
),
(
- "'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
- '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}',
+ "'inclusion_unlimited_args_kwargs' received multiple values for "
+ "keyword argument 'eggs'",
+ "{% load inclusion %}"
+ "{% inclusion_unlimited_args_kwargs 37 "
+ 'eggs="scrambled" eggs="scrambled" %}',
),
]
@@ -385,16 +408,21 @@ class InclusionTagTests(TagTestCase):
"inclusion_one_param_from_template - Expected result: 37\n",
),
(
- "{% load inclusion %}{% inclusion_explicit_no_context_from_template 37 %}",
+ "{% load inclusion %}"
+ "{% inclusion_explicit_no_context_from_template 37 %}",
"inclusion_explicit_no_context_from_template - Expected result: 37\n",
),
(
- "{% load inclusion %}{% inclusion_no_params_with_context_from_template %}",
- "inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n",
+ "{% load inclusion %}"
+ "{% inclusion_no_params_with_context_from_template %}",
+ "inclusion_no_params_with_context_from_template - Expected result "
+ "(context value: 42)\n",
),
(
- "{% load inclusion %}{% inclusion_params_and_context_from_template 37 %}",
- "inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n",
+ "{% load inclusion %}"
+ "{% inclusion_params_and_context_from_template 37 %}",
+ "inclusion_params_and_context_from_template - Expected result (context "
+ "value: 42): 37\n",
),
(
"{% load inclusion %}{% inclusion_two_params_from_template 37 42 %}",
@@ -413,16 +441,20 @@ class InclusionTagTests(TagTestCase):
"inclusion_unlimited_args_from_template - Expected result: 37, hi\n",
),
(
- "{% load inclusion %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}",
- "inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n",
+ "{% load inclusion %}"
+ "{% inclusion_unlimited_args_from_template 37 42 56 89 %}",
+ "inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, "
+ "89\n",
),
(
"{% load inclusion %}{% inclusion_only_unlimited_args_from_template %}",
"inclusion_only_unlimited_args_from_template - Expected result: \n",
),
(
- "{% load inclusion %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}",
- "inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n",
+ "{% load inclusion %}"
+ "{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}",
+ "inclusion_only_unlimited_args_from_template - Expected result: 37, "
+ "42, 56, 89\n",
),
]
diff --git a/tests/template_tests/test_extends.py b/tests/template_tests/test_extends.py
index bce5162d83..ce1838654b 100644
--- a/tests/template_tests/test_extends.py
+++ b/tests/template_tests/test_extends.py
@@ -45,13 +45,16 @@ class ExtendsBehaviorTests(SimpleTestCase):
"django.template.loaders.locmem.Loader",
{
"one.html": (
- '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}'
+ '{% extends "one.html" %}{% block content %}'
+ "{{ block.super }} locmem-one{% endblock %}"
),
"two.html": (
- '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}'
+ '{% extends "two.html" %}{% block content %}'
+ "{{ block.super }} locmem-two{% endblock %}"
),
"three.html": (
- '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}'
+ '{% extends "three.html" %}{% block content %}'
+ "{{ block.super }} locmem-three{% endblock %}"
),
},
),
@@ -126,7 +129,10 @@ class ExtendsBehaviorTests(SimpleTestCase):
[
"django.template.loaders.locmem.Loader",
{
- "base.html": '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}',
+ "base.html": (
+ '{% extends "base.html" %}{% block content %}'
+ "{{ block.super }} loader1{% endblock %}"
+ ),
},
],
[
@@ -151,14 +157,23 @@ class ExtendsBehaviorTests(SimpleTestCase):
[
"django.template.loaders.locmem.Loader",
{
- "base.html": "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}",
- "included.html": "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}",
+ "base.html": (
+ "{% extends 'base.html' %}{% block base %}{{ block.super }}"
+ "2{% endblock %}"
+ ),
+ "included.html": (
+ "{% extends 'included.html' %}{% block included %}"
+ "{{ block.super }}B{% endblock %}"
+ ),
},
],
[
"django.template.loaders.locmem.Loader",
{
- "base.html": "{% block base %}1{% endblock %}{% include 'included.html' %}",
+ "base.html": (
+ "{% block base %}1{% endblock %}"
+ "{% include 'included.html' %}"
+ ),
"included.html": "{% block included %}A{% endblock %}",
},
],
diff --git a/tests/template_tests/test_parser.py b/tests/template_tests/test_parser.py
index ee9b9b1b12..e40a5611e2 100644
--- a/tests/template_tests/test_parser.py
+++ b/tests/template_tests/test_parser.py
@@ -1,5 +1,6 @@
"""
-Testing some internals of the template processing. These are *not* examples to be copied in user code.
+Testing some internals of the template processing.
+These are *not* examples to be copied in user code.
"""
from django.template import Library, TemplateSyntaxError
from django.template.base import (
diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py
index b1415e2557..d30352ef18 100644
--- a/tests/test_client/tests.py
+++ b/tests/test_client/tests.py
@@ -229,7 +229,8 @@ class ClientTest(TestCase):
def test_raw_post(self):
"POST raw data (with a content type) to a view"
test_doc = """<?xml version="1.0" encoding="utf-8"?>
- <library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>
+ <library><book><title>Blink</title><author>Malcolm Gladwell</author></book>
+ </library>
"""
response = self.client.post(
"/raw_post_view/", test_doc, content_type="text/xml"
@@ -578,7 +579,10 @@ class ClientTest(TestCase):
self.assertEqual(response.context["user"].username, "testclient")
def test_view_with_login_and_custom_redirect(self):
- "Request a page that is protected with @login_required(redirect_field_name='redirect_to')"
+ """
+ Request a page that is protected with
+ @login_required(redirect_field_name='redirect_to')
+ """
# Get the page without logging in. Should result in 302.
response = self.client.get("/login_protected_view_custom_redirect/")
@@ -775,7 +779,10 @@ class ClientTest(TestCase):
# TODO: Log in with right permissions and request the page again
def test_view_with_permissions_exception(self):
- "Request a page that is protected with @permission_required but raises an exception"
+ """
+ Request a page that is protected with @permission_required but raises
+ an exception.
+ """
# Get the page without logging in. Should result in 403.
response = self.client.get("/permission_protected_view_exception/")
diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py
index a87c1bdd71..123208a35f 100644
--- a/tests/test_client_regress/tests.py
+++ b/tests/test_client_regress/tests.py
@@ -326,7 +326,8 @@ class AssertRedirectsTests(SimpleTestCase):
self.assertRedirects(response, "/get_view/")
except AssertionError as e:
self.assertIn(
- "Response didn't redirect as expected: Response code was 301 (expected 302)",
+ "Response didn't redirect as expected: Response code was 301 "
+ "(expected 302)",
str(e),
)
@@ -334,12 +335,16 @@ class AssertRedirectsTests(SimpleTestCase):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
- "abc: Response didn't redirect as expected: Response code was 301 (expected 302)",
+ "abc: Response didn't redirect as expected: Response code was 301 "
+ "(expected 302)",
str(e),
)
def test_lost_query(self):
- "An assertion is raised if the redirect location doesn't preserve GET parameters"
+ """
+ An assertion is raised if the redirect location doesn't preserve GET
+ parameters.
+ """
response = self.client.get("/redirect_view/", {"var": "value"})
try:
self.assertRedirects(response, "/get_view/")
@@ -353,7 +358,8 @@ class AssertRedirectsTests(SimpleTestCase):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
- "abc: Response redirected to '/get_view/?var=value', expected '/get_view/'",
+ "abc: Response redirected to '/get_view/?var=value', expected "
+ "'/get_view/'",
str(e),
)
@@ -365,12 +371,16 @@ class AssertRedirectsTests(SimpleTestCase):
self.assertRedirects(response, "/some_view/")
except AssertionError as e:
self.assertIn(
- "Response didn't redirect as expected: Response code was 301 (expected 302)",
+ "Response didn't redirect as expected: Response code was 301 "
+ "(expected 302)",
str(e),
)
def test_target_page(self):
- "An assertion is raised if the response redirect target cannot be retrieved as expected"
+ """
+ An assertion is raised if the response redirect target cannot be
+ retrieved as expected.
+ """
response = self.client.get("/double_redirect_view/")
try:
# The redirect target responds with a 301 code, not 200
@@ -509,14 +519,18 @@ class AssertRedirectsTests(SimpleTestCase):
)
def test_redirect_chain_on_non_redirect_page(self):
- "An assertion is raised if the original page couldn't be retrieved as expected"
+ """
+ An assertion is raised if the original page couldn't be retrieved as
+ expected.
+ """
# This page will redirect with code 301, not 302
response = self.client.get("/get_view/", follow=True)
try:
self.assertRedirects(response, "/get_view/")
except AssertionError as e:
self.assertIn(
- "Response didn't redirect as expected: Response code was 200 (expected 302)",
+ "Response didn't redirect as expected: Response code was 200 "
+ "(expected 302)",
str(e),
)
@@ -524,7 +538,8 @@ class AssertRedirectsTests(SimpleTestCase):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
- "abc: Response didn't redirect as expected: Response code was 200 (expected 302)",
+ "abc: Response didn't redirect as expected: Response code was 200 "
+ "(expected 302)",
str(e),
)
@@ -536,7 +551,8 @@ class AssertRedirectsTests(SimpleTestCase):
self.assertRedirects(response, "/get_view/")
except AssertionError as e:
self.assertIn(
- "Response didn't redirect as expected: Response code was 200 (expected 302)",
+ "Response didn't redirect as expected: Response code was 200 "
+ "(expected 302)",
str(e),
)
@@ -544,12 +560,16 @@ class AssertRedirectsTests(SimpleTestCase):
self.assertRedirects(response, "/get_view/", msg_prefix="abc")
except AssertionError as e:
self.assertIn(
- "abc: Response didn't redirect as expected: Response code was 200 (expected 302)",
+ "abc: Response didn't redirect as expected: Response code was 200 "
+ "(expected 302)",
str(e),
)
def test_redirect_scheme(self):
- "An assertion is raised if the response doesn't have the scheme specified in expected_url"
+ """
+ An assertion is raised if the response doesn't have the scheme
+ specified in expected_url.
+ """
# For all possible True/False combinations of follow and secure
for follow, secure in itertools.product([True, False], repeat=2):
@@ -651,7 +671,8 @@ class AssertFormErrorTests(SimpleTestCase):
)
except AssertionError as e:
self.assertIn(
- "abc: The form 'form' in context 0 does not contain the field 'some_field'",
+ "abc: The form 'form' in context 0 does not contain the field "
+ "'some_field'",
str(e),
)
@@ -824,7 +845,8 @@ class AssertFormsetErrorTests(SimpleTestCase):
for prefix, kwargs in self.msg_prefixes:
msg = (
prefix
- + "The formset 'my_formset', form 0 in context 0 does not contain the field 'Some_field'"
+ + "The formset 'my_formset', form 0 in context 0 does not contain the "
+ "field 'Some_field'"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertFormsetError(
@@ -841,7 +863,8 @@ class AssertFormsetErrorTests(SimpleTestCase):
for prefix, kwargs in self.msg_prefixes:
msg = (
prefix
- + "The field 'value' on formset 'my_formset', form 1 in context 0 contains no errors"
+ + "The field 'value' on formset 'my_formset', form 1 in context 0 "
+ "contains no errors"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertFormsetError(
@@ -880,11 +903,15 @@ class AssertFormsetErrorTests(SimpleTestCase):
)
def test_no_nonfield_error(self):
- "An assertion is raised if the formsets non-field errors doesn't contain any errors."
+ """
+ An assertion is raised if the formsets non-field errors doesn't contain
+ any errors.
+ """
for prefix, kwargs in self.msg_prefixes:
msg = (
prefix
- + "The formset 'my_formset', form 1 in context 0 does not contain any non-field errors."
+ + "The formset 'my_formset', form 1 in context 0 does not contain any "
+ "non-field errors."
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertFormsetError(
@@ -897,7 +924,10 @@ class AssertFormsetErrorTests(SimpleTestCase):
)
def test_unknown_nonfield_error(self):
- "An assertion is raised if the formsets non-field errors doesn't contain the provided error."
+ """
+ An assertion is raised if the formsets non-field errors doesn't contain
+ the provided error.
+ """
for prefix, kwargs in self.msg_prefixes:
msg = prefix + (
"The formset 'my_formset', form 0 in context 0 does not "
@@ -915,7 +945,10 @@ class AssertFormsetErrorTests(SimpleTestCase):
)
def test_nonfield_error(self):
- "No assertion is raised if the formsets non-field errors contains the provided error."
+ """
+ No assertion is raised if the formsets non-field errors contains the
+ provided error.
+ """
for prefix, kwargs in self.msg_prefixes:
self.assertFormsetError(
self.response_form_errors,
@@ -927,11 +960,15 @@ class AssertFormsetErrorTests(SimpleTestCase):
)
def test_no_nonform_error(self):
- "An assertion is raised if the formsets non-form errors doesn't contain any errors."
+ """
+ An assertion is raised if the formsets non-form errors doesn't contain
+ any errors.
+ """
for prefix, kwargs in self.msg_prefixes:
msg = (
prefix
- + "The formset 'my_formset' in context 0 does not contain any non-form errors."
+ + "The formset 'my_formset' in context 0 does not contain any non-form "
+ "errors."
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertFormsetError(
@@ -944,7 +981,10 @@ class AssertFormsetErrorTests(SimpleTestCase):
)
def test_unknown_nonform_error(self):
- "An assertion is raised if the formsets non-form errors doesn't contain the provided error."
+ """
+ An assertion is raised if the formsets non-form errors doesn't contain
+ the provided error.
+ """
for prefix, kwargs in self.msg_prefixes:
msg = prefix + (
"The formset 'my_formset' in context 0 does not contain the "
@@ -962,7 +1002,10 @@ class AssertFormsetErrorTests(SimpleTestCase):
)
def test_nonform_error(self):
- "No assertion is raised if the formsets non-form errors contains the provided error."
+ """
+ No assertion is raised if the formsets non-form errors contains the
+ provided error.
+ """
msg = "Forms in a set must have distinct email addresses."
for prefix, kwargs in self.msg_prefixes:
self.assertFormsetError(
@@ -1463,7 +1506,8 @@ class QueryStringTests(SimpleTestCase):
response = method("/request_data/?foo=whiz")
self.assertEqual(response.context["get-foo"], "whiz")
- # Data provided in the URL to a GET-like request is overridden by actual form data
+ # Data provided in the URL to a GET-like request is overridden by
+ # actual form data.
response = method("/request_data/?foo=whiz", data={"foo": "bang"})
self.assertEqual(response.context["get-foo"], "bang")
@@ -1546,7 +1590,8 @@ class UploadedFileEncodingTest(SimpleTestCase):
)
self.assertEqual(b"--TEST_BOUNDARY", encoded_file[0])
self.assertEqual(
- b'Content-Disposition: form-data; name="TEST_KEY"; filename="test_name.bin"',
+ b'Content-Disposition: form-data; name="TEST_KEY"; '
+ b'filename="test_name.bin"',
encoded_file[1],
)
self.assertEqual(b"TEST_FILE_CONTENT", encoded_file[-1])
diff --git a/tests/test_client_regress/views.py b/tests/test_client_regress/views.py
index 27294ec741..91b8bdfefc 100644
--- a/tests/test_client_regress/views.py
+++ b/tests/test_client_regress/views.py
@@ -107,7 +107,8 @@ def return_unicode(request):
def return_undecodable_binary(request):
return HttpResponse(
- b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e ReportLab Generated PDF document http://www.reportlab.com"
+ b"%PDF-1.4\r\n%\x93\x8c\x8b\x9e ReportLab Generated PDF document "
+ b"http://www.reportlab.com"
)
diff --git a/tests/test_runner/test_discover_runner.py b/tests/test_runner/test_discover_runner.py
index f7ba567e2d..10962cb114 100644
--- a/tests/test_runner/test_discover_runner.py
+++ b/tests/test_runner/test_discover_runner.py
@@ -500,7 +500,8 @@ class DiscoverRunnerTests(SimpleTestCase):
[test.id() for test in suite],
[
"unittest.loader._FailedTest.doesnotexist",
- "unittest.loader._FailedTest.test_runner_apps.tagged.tests_syntax_error",
+ "unittest.loader._FailedTest.test_runner_apps.tagged."
+ "tests_syntax_error",
],
)
@@ -563,7 +564,8 @@ class DiscoverRunnerTests(SimpleTestCase):
with captured_stdout() as stdout, captured_stderr() as stderr:
suite = runner.build_suite(
[
- "test_runner_apps.buffer.tests_buffer.WriteToStdoutStderrTestCase.test_pass",
+ "test_runner_apps.buffer.tests_buffer.WriteToStdoutStderrTestCase."
+ "test_pass",
]
)
runner.run_suite(suite)
@@ -575,7 +577,8 @@ class DiscoverRunnerTests(SimpleTestCase):
with captured_stdout() as stdout, captured_stderr() as stderr:
suite = runner.build_suite(
[
- "test_runner_apps.buffer.tests_buffer.WriteToStdoutStderrTestCase.test_fail",
+ "test_runner_apps.buffer.tests_buffer.WriteToStdoutStderrTestCase."
+ "test_fail",
]
)
runner.run_suite(suite)
diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py
index 15a14e89b3..b21c83585b 100644
--- a/tests/test_utils/tests.py
+++ b/tests/test_utils/tests.py
@@ -791,7 +791,7 @@ class HTMLEqualTests(SimpleTestCase):
<tr><th><label for="id_last_name">Last name:</label></th>
<td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th>
-<td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""",
+<td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""", # NOQA
"""
<tr><th>
<label for="id_first_name">First name:</label></th><td>
@@ -1711,8 +1711,8 @@ class DatabaseAliasTests(SimpleTestCase):
def test_no_close_match(self):
self.__class__.databases = {"void"}
message = (
- "test_utils.tests.DatabaseAliasTests.databases refers to 'void' which is not defined "
- "in settings.DATABASES."
+ "test_utils.tests.DatabaseAliasTests.databases refers to 'void' which is "
+ "not defined in settings.DATABASES."
)
with self.assertRaisesMessage(ImproperlyConfigured, message):
self._validate_databases()
@@ -1720,8 +1720,8 @@ class DatabaseAliasTests(SimpleTestCase):
def test_close_match(self):
self.__class__.databases = {"defualt"}
message = (
- "test_utils.tests.DatabaseAliasTests.databases refers to 'defualt' which is not defined "
- "in settings.DATABASES. Did you mean 'default'?"
+ "test_utils.tests.DatabaseAliasTests.databases refers to 'defualt' which "
+ "is not defined in settings.DATABASES. Did you mean 'default'?"
)
with self.assertRaisesMessage(ImproperlyConfigured, message):
self._validate_databases()
diff --git a/tests/timezones/tests.py b/tests/timezones/tests.py
index fd5ddd7edc..4ebd704f23 100644
--- a/tests/timezones/tests.py
+++ b/tests/timezones/tests.py
@@ -727,7 +727,8 @@ class ForcedTimeZoneDatabaseTests(TransactionTestCase):
raise SkipTest("Database has feature(s) supports_timezones")
if not connection.features.test_db_allows_multiple_connections:
raise SkipTest(
- "Database doesn't support feature(s): test_db_allows_multiple_connections"
+ "Database doesn't support feature(s): "
+ "test_db_allows_multiple_connections"
)
super().setUpClass()
@@ -979,7 +980,8 @@ class TemplateTests(SimpleTestCase):
}
templates = {
"notag": Template(
- "{% load tz %}{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}"
+ "{% load tz %}"
+ "{{ dt }}|{{ dt|localtime }}|{{ dt|utc }}|{{ dt|timezone:ICT }}"
),
"noarg": Template(
"{% load tz %}{% localtime %}{{ dt }}|{{ dt|localtime }}|"
@@ -1130,7 +1132,8 @@ class TemplateTests(SimpleTestCase):
)
self.assertEqual(
tpl.render(ctx),
- "2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|2011-09-01T13:20:30+03:00",
+ "2011-09-01T13:20:30+03:00|2011-09-01T17:20:30+07:00|"
+ "2011-09-01T13:20:30+03:00",
)
def test_timezone_templatetag_with_iana(self):
@@ -1217,7 +1220,10 @@ class TemplateTests(SimpleTestCase):
self.assertEqual(tpl.render(Context()), "Europe/Paris")
def test_get_current_timezone_templatetag_invalid_argument(self):
- msg = "'get_current_timezone' requires 'as variable' (got ['get_current_timezone'])"
+ msg = (
+ "'get_current_timezone' requires 'as variable' (got "
+ "['get_current_timezone'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template("{% load tz %}{% get_current_timezone %}").render()
diff --git a/tests/transactions/tests.py b/tests/transactions/tests.py
index af586bbbad..f68b464422 100644
--- a/tests/transactions/tests.py
+++ b/tests/transactions/tests.py
@@ -454,7 +454,8 @@ class AtomicMiscTests(TransactionTestCase):
# Swallow the intentional error raised.
with self.assertRaisesMessage(Exception, "Oops"):
- # Wrap in `mark_for_rollback_on_error` to check if the transaction is marked broken.
+ # Wrap in `mark_for_rollback_on_error` to check if the
+ # transaction is marked broken.
with transaction.mark_for_rollback_on_error():
# Ensure that we are still in a good state.
@@ -462,7 +463,7 @@ class AtomicMiscTests(TransactionTestCase):
raise Exception("Oops")
- # Ensure that `mark_for_rollback_on_error` marked the transaction as broken …
+ # mark_for_rollback_on_error marked the transaction as broken …
self.assertTrue(transaction.get_rollback())
# … and further queries fail.
@@ -470,7 +471,8 @@ class AtomicMiscTests(TransactionTestCase):
with self.assertRaisesMessage(transaction.TransactionManagementError, msg):
Reporter.objects.create()
- # Transaction errors are reset at the end of an transaction, so this should just work.
+ # Transaction errors are reset at the end of an transaction, so this
+ # should just work.
Reporter.objects.create()
def test_mark_for_rollback_on_error_in_autocommit(self):
@@ -479,7 +481,8 @@ class AtomicMiscTests(TransactionTestCase):
# Swallow the intentional error raised.
with self.assertRaisesMessage(Exception, "Oops"):
- # Wrap in `mark_for_rollback_on_error` to check if the transaction is marked broken.
+ # Wrap in `mark_for_rollback_on_error` to check if the transaction
+ # is marked broken.
with transaction.mark_for_rollback_on_error():
# Ensure that we are still in a good state.
diff --git a/tests/unmanaged_models/tests.py b/tests/unmanaged_models/tests.py
index 79bd1aad06..dc75bdc993 100644
--- a/tests/unmanaged_models/tests.py
+++ b/tests/unmanaged_models/tests.py
@@ -52,7 +52,8 @@ class ManyToManyUnmanagedTests(TestCase):
def test_many_to_many_between_unmanaged_and_managed(self):
"""
- An intermediary table between a managed and an unmanaged model should be created.
+ An intermediary table between a managed and an unmanaged model should
+ be created.
"""
table = Managed1._meta.get_field("mm").m2m_db_table()
tables = connection.introspection.table_names()
diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py
index e293f3c505..59c22dd589 100644
--- a/tests/urlpatterns_reverse/tests.py
+++ b/tests/urlpatterns_reverse/tests.py
@@ -37,7 +37,8 @@ from .utils import URLObject
from .views import empty_view
resolve_test_data = (
- # These entries are in the format: (path, url_name, app_name, namespace, view_name, func, args, kwargs)
+ # These entries are in the format:
+ # (path, url_name, app_name, namespace, view_name, func, args, kwargs)
# Simple case
(
"/normal/42/37/",
@@ -505,12 +506,18 @@ class URLPatternReverse(SimpleTestCase):
reverse("places")
def test_illegal_args_message(self):
- msg = "Reverse for 'places' with arguments '(1, 2)' not found. 1 pattern(s) tried:"
+ msg = (
+ "Reverse for 'places' with arguments '(1, 2)' not found. 1 pattern(s) "
+ "tried:"
+ )
with self.assertRaisesMessage(NoReverseMatch, msg):
reverse("places", args=(1, 2))
def test_illegal_kwargs_message(self):
- msg = "Reverse for 'places' with keyword arguments '{'arg1': 2}' not found. 1 pattern(s) tried:"
+ msg = (
+ "Reverse for 'places' with keyword arguments '{'arg1': 2}' not found. 1 "
+ "pattern(s) tried:"
+ )
with self.assertRaisesMessage(NoReverseMatch, msg):
reverse("places", kwargs={"arg1": 2})
@@ -709,7 +716,10 @@ class ReverseLazySettingsTest(AdminScriptTestCase):
super().setUp()
self.write_settings(
"settings.py",
- extra="from django.urls import reverse_lazy\nLOGIN_URL = reverse_lazy('login')",
+ extra=(
+ "from django.urls import reverse_lazy\n"
+ "LOGIN_URL = reverse_lazy('login')"
+ ),
)
def test_lazy_in_settings(self):
@@ -1673,7 +1683,10 @@ class IncludeTests(SimpleTestCase):
include((self.url_patterns, "app_name", "namespace"))
def test_include_3_tuple_namespace(self):
- msg = "Cannot override the namespace for a dynamic module that provides a namespace."
+ msg = (
+ "Cannot override the namespace for a dynamic module that provides a "
+ "namespace."
+ )
with self.assertRaisesMessage(ImproperlyConfigured, msg):
include((self.url_patterns, "app_name", "namespace"), "namespace")
diff --git a/tests/user_commands/tests.py b/tests/user_commands/tests.py
index 1e7716a3bf..99166cb29d 100644
--- a/tests/user_commands/tests.py
+++ b/tests/user_commands/tests.py
@@ -151,7 +151,7 @@ class CommandTests(SimpleTestCase):
"Dave, my mind is going. I can feel it. I can feel it.\n", out.getvalue()
)
- def test_calling_a_command_with_no_app_labels_and_parameters_should_raise_a_command_error(
+ def test_calling_a_command_with_no_app_labels_and_parameters_raise_command_error(
self,
):
with self.assertRaises(CommandError):
diff --git a/tests/utils_tests/test_autoreload.py b/tests/utils_tests/test_autoreload.py
index c50d141cf3..6fe7ae64fa 100644
--- a/tests/utils_tests/test_autoreload.py
+++ b/tests/utils_tests/test_autoreload.py
@@ -558,11 +558,12 @@ class ReloaderTests(SimpleTestCase):
def ensure_file(self, path):
path.parent.mkdir(exist_ok=True, parents=True)
path.touch()
- # On Linux and Windows updating the mtime of a file using touch() will set a timestamp
- # value that is in the past, as the time value for the last kernel tick is used rather
- # than getting the correct absolute time.
- # To make testing simpler set the mtime to be the observed time when this function is
- # called.
+ # On Linux and Windows updating the mtime of a file using touch() will
+ # set a timestamp value that is in the past, as the time value for the
+ # last kernel tick is used rather than getting the correct absolute
+ # time.
+ # To make testing simpler set the mtime to be the observed time when
+ # this function is called.
self.set_mtime(path, time.time())
return path.absolute()
diff --git a/tests/utils_tests/test_html.py b/tests/utils_tests/test_html.py
index f761ba84f2..81e2e8944b 100644
--- a/tests/utils_tests/test_html.py
+++ b/tests/utils_tests/test_html.py
@@ -183,24 +183,28 @@ class TestUtilsHtml(SimpleTestCase):
(
(
"&<>",
- '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>',
+ '<script id="test_id" type="application/json">'
+ '"\\u0026\\u003C\\u003E"</script>',
)
),
# "<", ">" and "&" are quoted inside JSON objects
(
{"a": "<script>test&ing</script>"},
'<script id="test_id" type="application/json">'
- '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>',
+ '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}'
+ "</script>",
),
# Lazy strings are quoted
(
lazystr("&<>"),
- '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>',
+ '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"'
+ "</script>",
),
(
{"a": lazystr("<script>test&ing</script>")},
'<script id="test_id" type="application/json">'
- '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>',
+ '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}'
+ "</script>",
),
)
for arg, expected in tests:
@@ -222,11 +226,14 @@ class TestUtilsHtml(SimpleTestCase):
("http://example.com/?x=<>\"'", "http://example.com/?x=%3C%3E%22%27"),
(
"http://example.com/?q=http://example.com/?x=1%26q=django",
- "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango",
+ "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D"
+ "django",
),
(
- "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango",
- "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3Ddjango",
+ "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D"
+ "django",
+ "http://example.com/?q=http%3A%2F%2Fexample.com%2F%3Fx%3D1%26q%3D"
+ "django",
),
("http://.www.f oo.bar/", "http://.www.f%20oo.bar/"),
)
@@ -291,11 +298,13 @@ class TestUtilsHtml(SimpleTestCase):
tests = (
(
"Search for google.com/?q=! and see.",
- 'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and see.',
+ 'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and '
+ "see.",
),
(
"Search for google.com/?q=1&lt! and see.",
- 'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1&lt</a>! and see.',
+ 'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1&lt'
+ "</a>! and see.",
),
(
lazystr("Search for google.com/?q=!"),
diff --git a/tests/utils_tests/test_jslex.py b/tests/utils_tests/test_jslex.py
index 0963dd0f16..ee13eb4d64 100644
--- a/tests/utils_tests/test_jslex.py
+++ b/tests/utils_tests/test_jslex.py
@@ -72,7 +72,7 @@ class JsTokensTest(SimpleTestCase):
(r"a=/\//,1", ["id a", "punct =", r"regex /\//", "punct ,", "dnum 1"]),
# next two are from https://www-archive.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions # NOQA
(
- """for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);}""",
+ 'for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);}',
[
"keyword for",
"punct (",
@@ -104,7 +104,7 @@ class JsTokensTest(SimpleTestCase):
],
),
(
- """for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);}""",
+ 'for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);}',
[
"keyword for",
"punct (",
@@ -240,7 +240,8 @@ class JsTokensTest(SimpleTestCase):
],
),
(
- r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """,
+ r' this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\")'
+ r'.replace(/"/g, "\\\"") + "\")"; ',
[
"keyword this",
"punct .",
diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py
index 131d893a44..9ccae595f4 100644
--- a/tests/utils_tests/test_lazyobject.py
+++ b/tests/utils_tests/test_lazyobject.py
@@ -126,7 +126,8 @@ class LazyObjectTestCase(TestCase):
for needle, haystack in test_data:
self.assertIn(needle, self.lazy_wrap(haystack))
- # __contains__ doesn't work when the haystack is a string and the needle a LazyObject
+ # __contains__ doesn't work when the haystack is a string and the
+ # needle a LazyObject.
for needle_haystack in test_data[1:]:
self.assertIn(self.lazy_wrap(needle), haystack)
self.assertIn(self.lazy_wrap(needle), self.lazy_wrap(haystack))
diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py
index 4aceeaf21e..34b027c28a 100644
--- a/tests/utils_tests/test_text.py
+++ b/tests/utils_tests/test_text.py
@@ -122,10 +122,12 @@ class TestUtilsText(SimpleTestCase):
def test_truncate_html_words(self):
truncator = text.Truncator(
- '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>'
+ '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>'
+ "</strong></p>"
)
self.assertEqual(
- '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>',
+ '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>'
+ "</strong></p>",
truncator.words(10, html=True),
)
self.assertEqual(
@@ -143,7 +145,8 @@ class TestUtilsText(SimpleTestCase):
# Test with new line inside tag
truncator = text.Truncator(
- '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over the lazy dog.</p>'
+ '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over '
+ "the lazy dog.</p>"
)
self.assertEqual(
'<p>The quick <a href="xyz.html"\n id="mylink">brown…</a></p>',
diff --git a/tests/validation/test_error_messages.py b/tests/validation/test_error_messages.py
index 470c055eef..ffc660aad6 100644
--- a/tests/validation/test_error_messages.py
+++ b/tests/validation/test_error_messages.py
@@ -52,28 +52,32 @@ class ValidationMessagesTest(TestCase):
f,
"fõo",
[
- "“fõo” value has an invalid date format. It must be in YYYY-MM-DD format."
+ "“fõo” value has an invalid date format. It must be in YYYY-MM-DD "
+ "format."
],
)
self._test_validation_messages(
f,
"aaaa-10-10",
[
- "“aaaa-10-10” value has an invalid date format. It must be in YYYY-MM-DD format."
+ "“aaaa-10-10” value has an invalid date format. It must be in "
+ "YYYY-MM-DD format."
],
)
self._test_validation_messages(
f,
"2011-13-10",
[
- "“2011-13-10” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ "“2011-13-10” value has the correct format (YYYY-MM-DD) but it is an "
+ "invalid date."
],
)
self._test_validation_messages(
f,
"2011-10-32",
[
- "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an "
+ "invalid date."
],
)
@@ -84,7 +88,8 @@ class ValidationMessagesTest(TestCase):
f,
"fõo",
[
- "“fõo” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
+ "“fõo” value has an invalid format. It must be in "
+ "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
],
)
# Correct format but invalid date
@@ -92,7 +97,8 @@ class ValidationMessagesTest(TestCase):
f,
"2011-10-32",
[
- "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an "
+ "invalid date."
],
)
# Correct format but invalid date/time
@@ -100,8 +106,8 @@ class ValidationMessagesTest(TestCase):
f,
"2011-10-32 10:10",
[
- "“2011-10-32 10:10” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
- "but it is an invalid date/time."
+ "“2011-10-32 10:10” value has the correct format "
+ "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time."
],
)
@@ -112,7 +118,8 @@ class ValidationMessagesTest(TestCase):
f,
"fõo",
[
- "“fõo” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."
+ "“fõo” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] "
+ "format."
],
)
# Correct format but invalid time
@@ -120,6 +127,7 @@ class ValidationMessagesTest(TestCase):
f,
"25:50",
[
- "“25:50” value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an invalid time."
+ "“25:50” value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is "
+ "an invalid time."
],
)
diff --git a/tests/view_tests/tests/test_csrf.py b/tests/view_tests/tests/test_csrf.py
index c0f812431d..2f4542c143 100644
--- a/tests/view_tests/tests/test_csrf.py
+++ b/tests/view_tests/tests/test_csrf.py
@@ -96,7 +96,9 @@ class CsrfViewTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- CSRF_FAILURE_TEMPLATE_NAME: "Test template for CSRF failure"
+ CSRF_FAILURE_TEMPLATE_NAME: (
+ "Test template for CSRF failure"
+ )
},
),
],
diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py
index 6b2e8b86fe..94c78ff322 100644
--- a/tests/view_tests/tests/test_debug.py
+++ b/tests/view_tests/tests/test_debug.py
@@ -127,7 +127,10 @@ class DebugViewTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- "403.html": "This is a test template for a 403 error ({{ exception }}).",
+ "403.html": (
+ "This is a test template for a 403 error "
+ "({{ exception }})."
+ ),
},
),
],
@@ -225,13 +228,15 @@ class DebugViewTests(SimpleTestCase):
def test_non_l10ned_numeric_ids(self):
"""
- Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized.
+ Numeric IDs and fancy traceback context blocks line numbers shouldn't
+ be localized.
"""
with self.settings(DEBUG=True):
with self.assertLogs("django.request", "ERROR"):
response = self.client.get("/raises500/")
# We look for a HTML fragment of the form
- # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
+ # '<div class="context" id="c38123208">',
+ # not '<div class="context" id="c38,123,208"'.
self.assertContains(response, '<div class="context" id="', status_code=500)
match = re.search(
b'<div class="context" id="(?P<id>[^"]+)">', response.content
@@ -240,8 +245,8 @@ class DebugViewTests(SimpleTestCase):
id_repr = match["id"]
self.assertFalse(
re.search(b"[^c0-9]", id_repr),
- "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)."
- % id_repr.decode(),
+ "Numeric IDs in debug response HTML page shouldn't be localized "
+ "(value: %s)." % id_repr.decode(),
)
def test_template_exceptions(self):
@@ -736,7 +741,8 @@ class ExceptionReporterTests(SimpleTestCase):
html,
)
self.assertIn(
- '"generated", line 2, in funcName\n &lt;source code not available&gt;',
+ '"generated", line 2, in funcName\n'
+ " &lt;source code not available&gt;",
html,
)
text = reporter.get_traceback_text()
@@ -848,7 +854,8 @@ class ExceptionReporterTests(SimpleTestCase):
exc_type, exc_value, tb = sys.exc_info()
html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html()
self.assertIn(
- '<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre></td>',
+ '<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre>'
+ "</td>",
html,
)
diff --git a/tests/view_tests/tests/test_defaults.py b/tests/view_tests/tests/test_defaults.py
index 0c4fc7c7da..f99066e5bb 100644
--- a/tests/view_tests/tests/test_defaults.py
+++ b/tests/view_tests/tests/test_defaults.py
@@ -111,8 +111,11 @@ class DefaultsTests(TestCase):
(
"django.template.loaders.locmem.Loader",
{
- "404.html": "This is a test template for a 404 error "
- "(path: {{ request_path }}, exception: {{ exception }}).",
+ "404.html": (
+ "This is a test template for a 404 error "
+ "(path: {{ request_path }}, "
+ "exception: {{ exception }})."
+ ),
"500.html": "This is a test template for a 500 error.",
},
),
diff --git a/tests/view_tests/tests/test_i18n.py b/tests/view_tests/tests/test_i18n.py
index 0b6250dd1c..793cb29c05 100644
--- a/tests/view_tests/tests/test_i18n.py
+++ b/tests/view_tests/tests/test_i18n.py
@@ -517,7 +517,8 @@ class I18nSeleniumTests(SeleniumTestCase):
elem = self.selenium.find_element_by_id("formats")
self.assertEqual(
elem.text,
- "DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; FIRST_DAY_OF_WEEK is a number;",
+ "DATE_INPUT_FORMATS is an object; DECIMAL_SEPARATOR is a string; "
+ "FIRST_DAY_OF_WEEK is a number;",
)
@modify_settings(INSTALLED_APPS={"append": ["view_tests.app1", "view_tests.app2"]})
diff --git a/tests/view_tests/views.py b/tests/view_tests/views.py
index 378864dcaf..f613b81f0b 100644
--- a/tests/view_tests/views.py
+++ b/tests/view_tests/views.py
@@ -129,9 +129,9 @@ def non_sensitive_view(request):
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
- sauce = "".join(
+ sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
- ) # NOQA
+ )
try:
raise Exception
except Exception:
@@ -147,9 +147,9 @@ def sensitive_view(request):
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
- sauce = "".join(
+ sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
- ) # NOQA
+ )
try:
raise Exception
except Exception:
@@ -165,9 +165,9 @@ def paranoid_view(request):
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
- sauce = "".join(
+ sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
- ) # NOQA
+ )
try:
raise Exception
except Exception:
@@ -239,9 +239,9 @@ def custom_exception_reporter_filter_view(request):
# so that the tests don't return false positives when the function's source
# is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
- sauce = "".join(
+ sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
- ) # NOQA
+ )
request.exception_reporter_filter = UnsafeExceptionReporterFilter()
try:
raise Exception
@@ -279,9 +279,9 @@ class Klass:
# so that the tests don't return false positives when the function's
# source is displayed in the exception report.
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
- sauce = "".join(
+ sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
- ) # NOQA
+ )
try:
raise Exception
except Exception:
@@ -298,9 +298,9 @@ def sensitive_method_view(request):
@sensitive_post_parameters("bacon-key", "sausage-key")
def multivalue_dict_key_error(request):
cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"]) # NOQA
- sauce = "".join(
+ sauce = "".join( # NOQA
["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]
- ) # NOQA
+ )
try:
request.POST["bar"]
except Exception:
diff --git a/tests/wsgi/tests.py b/tests/wsgi/tests.py
index db46070182..b1b5a7d00e 100644
--- a/tests/wsgi/tests.py
+++ b/tests/wsgi/tests.py
@@ -44,8 +44,10 @@ class WSGITest(SimpleTestCase):
self.assertIn(
bytes(response),
[
- b"Content-Length: 12\r\nContent-Type: text/html; charset=utf-8\r\n\r\nHello World!",
- b"Content-Type: text/html; charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!",
+ b"Content-Length: 12\r\nContent-Type: text/html; "
+ b"charset=utf-8\r\n\r\nHello World!",
+ b"Content-Type: text/html; "
+ b"charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!",
],
)