From 7119f40c9881666b6f9b5cf7df09ee1d21cc8344 Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Fri, 4 Feb 2022 08:08:27 +0100 Subject: [PATCH] Refs #33476 -- Refactored code to strictly match 88 characters line length. --- django/apps/registry.py | 6 +- django/conf/global_settings.py | 7 +- django/contrib/admin/checks.py | 45 +- django/contrib/admin/models.py | 3 +- django/contrib/admin/options.py | 21 +- django/contrib/admin/templatetags/log.py | 2 +- django/contrib/auth/__init__.py | 6 +- django/contrib/auth/checks.py | 13 +- .../management/commands/changepassword.py | 5 +- .../contrib/auth/migrations/0001_initial.py | 22 +- .../0004_alter_user_username_opts.py | 5 +- ...007_alter_validators_add_error_messages.py | 5 +- .../0008_alter_user_username_max_length.py | 5 +- django/contrib/auth/mixins.py | 11 +- django/contrib/auth/models.py | 3 +- django/contrib/auth/password_validation.py | 11 +- django/contrib/contenttypes/admin.py | 7 +- django/contrib/contenttypes/models.py | 5 +- django/contrib/flatpages/forms.py | 3 +- .../flatpages/migrations/0001_initial.py | 9 +- .../gis/db/backends/base/operations.py | 6 +- .../gis/db/backends/oracle/features.py | 3 +- .../gis/db/backends/oracle/operations.py | 8 +- .../contrib/gis/db/backends/oracle/schema.py | 5 +- .../contrib/gis/db/backends/postgis/const.py | 4 +- .../gis/db/backends/postgis/introspection.py | 4 +- .../gis/db/backends/postgis/operations.py | 6 +- django/contrib/gis/db/models/functions.py | 6 +- django/contrib/gis/db/models/lookups.py | 6 +- django/contrib/gis/gdal/geometries.py | 2 +- django/contrib/gis/gdal/layer.py | 8 +- django/contrib/gis/gdal/srs.py | 3 +- django/contrib/gis/geos/polygon.py | 6 +- .../gis/management/commands/ogrinspect.py | 4 +- django/contrib/gis/serializers/geojson.py | 6 +- django/contrib/gis/sitemaps/kml.py | 3 +- django/contrib/gis/utils/layermapping.py | 6 +- django/contrib/gis/utils/ogrinspect.py | 4 +- .../contrib/humanize/templatetags/humanize.py | 3 +- django/contrib/postgres/constraints.py | 5 +- django/contrib/postgres/fields/ranges.py | 3 +- django/contrib/postgres/operations.py | 5 +- django/contrib/postgres/validators.py | 12 +- .../redirects/migrations/0001_initial.py | 8 +- django/contrib/redirects/models.py | 3 +- django/contrib/sitemaps/__init__.py | 3 +- django/contrib/sitemaps/views.py | 5 +- django/contrib/sites/managers.py | 3 +- .../management/commands/collectstatic.py | 8 +- django/core/cache/backends/memcached.py | 3 +- django/core/checks/security/csrf.py | 4 +- django/core/files/locks.py | 2 +- django/core/files/storage.py | 3 +- django/core/files/uploadhandler.py | 5 +- django/core/handlers/base.py | 3 +- django/core/management/base.py | 10 +- .../management/commands/compilemessages.py | 4 +- .../management/commands/createcachetable.py | 5 +- django/core/management/commands/dbshell.py | 5 +- .../core/management/commands/diffsettings.py | 4 +- django/core/management/commands/dumpdata.py | 12 +- django/core/management/commands/flush.py | 3 +- django/core/management/commands/inspectdb.py | 23 +- django/core/management/commands/loaddata.py | 13 +- .../core/management/commands/makemessages.py | 21 +- .../management/commands/makemigrations.py | 3 +- django/core/management/commands/migrate.py | 17 +- .../core/management/commands/sendtestemail.py | 5 +- django/core/management/commands/shell.py | 15 +- .../management/commands/showmigrations.py | 6 +- django/core/management/commands/sqlflush.py | 5 +- django/core/management/commands/sqlmigrate.py | 13 +- .../management/commands/sqlsequencereset.py | 5 +- .../management/commands/squashmigrations.py | 29 +- django/core/management/commands/test.py | 5 +- django/core/validators.py | 28 +- django/db/backends/base/base.py | 9 +- django/db/backends/base/introspection.py | 9 +- django/db/backends/base/operations.py | 21 +- django/db/backends/base/schema.py | 26 +- django/db/backends/mysql/base.py | 6 +- django/db/backends/mysql/features.py | 36 +- django/db/backends/mysql/introspection.py | 3 +- django/db/backends/mysql/operations.py | 11 +- django/db/backends/mysql/validation.py | 3 +- django/db/backends/oracle/base.py | 27 +- django/db/backends/oracle/creation.py | 16 +- django/db/backends/oracle/features.py | 15 +- django/db/backends/oracle/introspection.py | 27 +- django/db/backends/oracle/operations.py | 12 +- django/db/backends/oracle/schema.py | 6 +- django/db/backends/postgresql/features.py | 3 +- .../db/backends/postgresql/introspection.py | 45 +- django/db/backends/postgresql/operations.py | 15 +- django/db/backends/postgresql/schema.py | 6 +- django/db/backends/sqlite3/_functions.py | 10 +- django/db/backends/sqlite3/features.py | 30 +- django/db/backends/sqlite3/introspection.py | 9 +- django/db/backends/sqlite3/operations.py | 7 +- django/db/backends/sqlite3/schema.py | 9 +- django/db/migrations/autodetector.py | 18 +- django/db/migrations/executor.py | 4 +- django/db/migrations/migration.py | 9 +- django/db/migrations/state.py | 14 +- django/db/models/base.py | 11 +- django/db/models/fields/__init__.py | 3 +- django/db/models/fields/files.py | 3 +- django/db/models/fields/related.py | 42 +- .../db/models/fields/related_descriptors.py | 17 +- django/db/models/fields/related_lookups.py | 5 +- django/db/models/fields/reverse_related.py | 6 +- django/db/models/functions/comparison.py | 3 +- django/db/models/indexes.py | 3 +- django/db/models/manager.py | 3 +- django/db/models/options.py | 4 +- django/db/models/query.py | 3 +- django/db/models/sql/compiler.py | 31 +- django/db/models/sql/datastructures.py | 3 +- django/db/models/sql/query.py | 3 +- django/forms/models.py | 13 +- django/http/multipartparser.py | 13 +- django/http/request.py | 11 +- django/template/defaulttags.py | 20 +- django/template/loader_tags.py | 3 +- django/templatetags/i18n.py | 13 +- django/templatetags/static.py | 3 +- django/templatetags/tz.py | 3 +- django/test/testcases.py | 51 +- django/test/utils.py | 5 +- django/urls/resolvers.py | 6 +- django/utils/asyncio.py | 5 +- django/utils/dateformat.py | 5 +- django/utils/deconstruct.py | 4 +- django/utils/feedgenerator.py | 5 +- django/utils/formats.py | 3 +- django/utils/translation/trans_real.py | 11 +- django/views/csrf.py | 2 +- django/views/defaults.py | 3 +- django/views/i18n.py | 2 +- docs/_ext/djangodocs.py | 3 +- docs/conf.py | 2 +- tests/admin_changelist/tests.py | 3 +- tests/admin_checks/tests.py | 11 +- tests/admin_docs/test_views.py | 20 +- tests/admin_filters/tests.py | 5 +- tests/admin_inlines/tests.py | 84 +- tests/admin_registration/tests.py | 5 +- tests/admin_scripts/tests.py | 467 +++++++-- tests/admin_utils/tests.py | 3 +- tests/admin_views/test_actions.py | 9 +- tests/admin_views/tests.py | 214 ++-- tests/admin_widgets/tests.py | 47 +- tests/aggregation/tests.py | 26 +- tests/aggregation_regress/tests.py | 43 +- tests/annotations/tests.py | 10 +- tests/app_loading/tests.py | 20 +- tests/apps/tests.py | 5 +- tests/auth_tests/test_checks.py | 10 +- tests/auth_tests/test_forms.py | 49 +- tests/auth_tests/test_hashers.py | 3 +- tests/auth_tests/test_management.py | 26 +- tests/auth_tests/test_views.py | 5 +- tests/auth_tests/urls.py | 4 +- tests/backends/mysql/tests.py | 3 +- tests/backends/oracle/tests.py | 6 +- tests/backends/test_utils.py | 5 +- tests/backends/tests.py | 12 +- tests/basic/tests.py | 5 +- tests/cache/tests.py | 15 +- .../test_model_field_deprecation.py | 5 +- tests/check_framework/test_security.py | 4 +- tests/check_framework/test_translation.py | 5 +- tests/check_framework/test_urls.py | 18 +- tests/contenttypes_tests/test_checks.py | 7 +- tests/csrf_tests/tests.py | 8 +- tests/csrf_tests/views.py | 4 +- tests/custom_lookups/tests.py | 27 +- .../datetime/test_extract_trunc.py | 5 +- tests/db_functions/text/test_sha224.py | 4 +- tests/db_functions/text/test_sha256.py | 4 +- tests/db_functions/text/test_sha384.py | 18 +- tests/delete/tests.py | 8 +- tests/delete_regress/tests.py | 4 +- tests/expressions/tests.py | 10 +- tests/expressions_window/tests.py | 3 +- tests/extra_regress/tests.py | 3 +- tests/file_storage/tests.py | 5 +- tests/file_uploads/tests.py | 23 +- tests/files/tests.py | 3 +- tests/filtered_relation/tests.py | 4 +- tests/fixtures/tests.py | 564 +++++++---- tests/fixtures_regress/tests.py | 39 +- tests/flatpages_tests/test_csrf.py | 10 +- tests/flatpages_tests/test_forms.py | 8 +- tests/flatpages_tests/test_middleware.py | 10 +- tests/flatpages_tests/test_templatetags.py | 18 +- tests/flatpages_tests/test_views.py | 10 +- tests/foreign_object/test_forms.py | 3 +- tests/foreign_object/tests.py | 16 +- .../field_tests/test_booleanfield.py | 3 +- .../field_tests/test_decimalfield.py | 3 +- .../field_tests/test_emailfield.py | 3 +- .../field_tests/test_floatfield.py | 6 +- .../field_tests/test_multivaluefield.py | 9 +- .../field_tests/test_nullbooleanfield.py | 9 +- tests/forms_tests/models.py | 7 +- tests/forms_tests/tests/test_forms.py | 919 +++++++++++------- tests/forms_tests/tests/test_formsets.py | 72 +- tests/forms_tests/tests/test_i18n.py | 37 +- tests/forms_tests/tests/test_input_formats.py | 50 +- tests/forms_tests/tests/test_media.py | 192 ++-- tests/forms_tests/tests/test_utils.py | 6 +- tests/forms_tests/tests/tests.py | 234 +++-- .../widget_tests/test_checkboxinput.py | 3 +- .../test_checkboxselectmultiple.py | 100 +- .../widget_tests/test_clearablefileinput.py | 14 +- .../widget_tests/test_datetimeinput.py | 5 +- .../widget_tests/test_multiplehiddeninput.py | 23 +- .../widget_tests/test_multiwidget.py | 6 +- .../widget_tests/test_numberinput.py | 3 +- .../widget_tests/test_radioselect.py | 91 +- tests/forms_tests/widget_tests/test_select.py | 12 +- .../widget_tests/test_selectdatewidget.py | 3 +- .../forms_tests/widget_tests/test_textarea.py | 6 +- .../widget_tests/test_textinput.py | 13 +- tests/generic_inline_admin/tests.py | 38 +- tests/generic_relations/test_forms.py | 123 ++- tests/generic_relations/tests.py | 8 +- tests/generic_views/test_dates.py | 15 +- tests/get_object_or_404/tests.py | 15 +- tests/get_or_create/tests.py | 5 +- tests/gis_tests/distapp/tests.py | 45 +- tests/gis_tests/gdal_tests/test_ds.py | 7 +- tests/gis_tests/gdal_tests/test_geom.py | 3 +- tests/gis_tests/gdal_tests/test_raster.py | 15 +- tests/gis_tests/gdal_tests/test_srs.py | 30 +- tests/gis_tests/geoadmin_deprecated/tests.py | 14 +- tests/gis_tests/geoapp/test_functions.py | 24 +- tests/gis_tests/geoapp/tests.py | 10 +- tests/gis_tests/geogapp/tests.py | 5 +- tests/gis_tests/geos_tests/test_geos.py | 6 +- tests/gis_tests/inspectapp/tests.py | 6 +- tests/gis_tests/layermap/models.py | 3 +- tests/gis_tests/layermap/tests.py | 5 +- tests/gis_tests/relatedapp/tests.py | 18 +- tests/gis_tests/test_geoforms.py | 3 +- tests/gis_tests/test_spatialrefsys.py | 14 +- tests/handlers/tests.py | 12 +- tests/httpwrappers/tests.py | 10 +- tests/humanize_tests/tests.py | 3 +- tests/i18n/patterns/tests.py | 20 +- tests/i18n/test_extraction.py | 17 +- tests/i18n/test_percents.py | 31 +- tests/i18n/tests.py | 54 +- tests/indexes/tests.py | 3 +- tests/inline_formsets/tests.py | 5 +- tests/inspectdb/tests.py | 21 +- .../test_deprecated_fields.py | 6 +- tests/invalid_models_tests/test_models.py | 9 +- .../test_ordinary_fields.py | 3 +- .../test_relative_fields.py | 74 +- tests/logging_tests/tests.py | 6 +- tests/lookup/tests.py | 11 +- tests/m2m_regress/tests.py | 9 +- tests/m2m_through_regress/tests.py | 36 +- tests/mail/tests.py | 23 +- tests/managers_regress/tests.py | 3 +- tests/many_to_many/tests.py | 5 +- tests/many_to_one/tests.py | 17 +- tests/messages_tests/test_api.py | 5 +- tests/messages_tests/test_cookie.py | 3 +- tests/middleware/tests.py | 10 +- tests/middleware_exceptions/tests.py | 3 +- tests/migrations/test_autodetector.py | 13 +- tests/migrations/test_commands.py | 53 +- tests/migrations/test_graph.py | 27 +- tests/migrations/test_loader.py | 10 +- tests/migrations/test_operations.py | 47 +- tests/migrations/test_optimizer.py | 6 +- tests/migrations/test_state.py | 28 +- tests/migrations/test_writer.py | 6 +- tests/model_fields/test_durationfield.py | 5 +- tests/model_fields/test_foreignkey.py | 8 +- tests/model_forms/test_modelchoicefield.py | 27 +- tests/model_forms/tests.py | 384 +++++--- tests/model_formsets/tests.py | 284 ++++-- tests/model_formsets_regress/tests.py | 10 +- tests/model_regress/tests.py | 2 +- tests/modeladmin/test_checks.py | 19 +- tests/multiple_database/tests.py | 53 +- tests/null_queries/tests.py | 5 +- tests/one_to_one/tests.py | 10 +- tests/pagination/tests.py | 5 +- tests/postgres_tests/test_array.py | 38 +- tests/postgres_tests/test_constraints.py | 3 +- tests/postgres_tests/test_indexes.py | 6 +- tests/postgres_tests/test_introspection.py | 15 +- tests/postgres_tests/test_ranges.py | 27 +- tests/prefetch_related/test_uuid.py | 6 +- tests/prefetch_related/tests.py | 6 +- tests/proxy_models/tests.py | 10 +- tests/queries/tests.py | 14 +- tests/raw_query/tests.py | 13 +- tests/requests/test_data_upload_settings.py | 3 +- tests/requests/tests.py | 13 +- tests/runtests.py | 9 +- tests/schema/tests.py | 6 +- tests/select_for_update/tests.py | 5 +- tests/select_related/tests.py | 9 +- tests/serializers/test_xml.py | 7 +- tests/serializers/tests.py | 5 +- tests/sessions_tests/tests.py | 3 +- tests/signals/tests.py | 5 +- tests/sitemaps_tests/test_generic.py | 25 +- tests/sitemaps_tests/test_http.py | 136 ++- tests/sitemaps_tests/test_https.py | 26 +- tests/sitemaps_tests/test_utils.py | 5 +- tests/staticfiles_tests/test_checks.py | 5 +- tests/staticfiles_tests/test_management.py | 12 +- tests/staticfiles_tests/test_storage.py | 3 +- tests/template_backends/test_django.py | 8 +- .../filter_tests/test_addslashes.py | 5 +- .../filter_tests/test_autoescape.py | 8 +- .../filter_tests/test_capfirst.py | 5 +- .../filter_tests/test_center.py | 5 +- .../filter_tests/test_chaining.py | 22 +- tests/template_tests/filter_tests/test_cut.py | 12 +- .../filter_tests/test_default.py | 4 +- .../filter_tests/test_escape.py | 4 +- .../template_tests/filter_tests/test_first.py | 4 +- .../filter_tests/test_floatformat.py | 5 +- .../filter_tests/test_force_escape.py | 17 +- .../filter_tests/test_json_script.py | 3 +- .../filter_tests/test_length_is.py | 24 +- .../filter_tests/test_linebreaks.py | 5 +- .../filter_tests/test_linebreaksbr.py | 5 +- .../filter_tests/test_linenumbers.py | 5 +- .../template_tests/filter_tests/test_ljust.py | 5 +- .../template_tests/filter_tests/test_lower.py | 4 +- .../filter_tests/test_make_list.py | 5 +- .../filter_tests/test_phone2numeric.py | 5 +- .../filter_tests/test_random.py | 4 +- .../template_tests/filter_tests/test_rjust.py | 5 +- .../filter_tests/test_safeseq.py | 5 +- .../template_tests/filter_tests/test_slice.py | 5 +- .../filter_tests/test_slugify.py | 4 +- .../filter_tests/test_stringformat.py | 5 +- .../filter_tests/test_striptags.py | 11 +- .../filter_tests/test_truncatewords.py | 5 +- .../filter_tests/test_unordered_list.py | 21 +- .../template_tests/filter_tests/test_upper.py | 4 +- .../filter_tests/test_urlize.py | 88 +- .../filter_tests/test_urlizetrunc.py | 30 +- .../filter_tests/test_wordcount.py | 5 +- .../filter_tests/test_wordwrap.py | 29 +- .../syntax_tests/i18n/test_blocktranslate.py | 184 +++- .../i18n/test_get_available_languages.py | 5 +- .../i18n/test_get_current_language.py | 5 +- .../i18n/test_get_current_language_bidi.py | 5 +- .../i18n/test_get_language_info_list.py | 5 +- .../syntax_tests/i18n/test_translate.py | 31 +- .../i18n/test_underscore_syntax.py | 5 +- .../syntax_tests/test_autoescape.py | 18 +- .../template_tests/syntax_tests/test_cache.py | 18 +- .../template_tests/syntax_tests/test_cycle.py | 22 +- .../syntax_tests/test_exceptions.py | 8 +- .../syntax_tests/test_extends.py | 49 +- tests/template_tests/syntax_tests/test_for.py | 65 +- tests/template_tests/syntax_tests/test_if.py | 32 +- .../syntax_tests/test_if_changed.py | 53 +- .../syntax_tests/test_include.py | 17 +- .../syntax_tests/test_invalid_string.py | 4 +- .../template_tests/syntax_tests/test_load.py | 24 +- .../syntax_tests/test_named_endblock.py | 4 +- .../syntax_tests/test_resetcycle.py | 4 +- .../syntax_tests/test_spaceless.py | 16 +- .../syntax_tests/test_static.py | 13 +- .../syntax_tests/test_verbatim.py | 8 +- .../template_tests/templatetags/inclusion.py | 13 +- tests/template_tests/test_custom.py | 88 +- tests/template_tests/test_extends.py | 29 +- tests/template_tests/test_parser.py | 3 +- tests/test_client/tests.py | 13 +- tests/test_client_regress/tests.py | 92 +- tests/test_client_regress/views.py | 3 +- tests/test_runner/test_discover_runner.py | 9 +- tests/test_utils/tests.py | 10 +- tests/timezones/tests.py | 14 +- tests/transactions/tests.py | 11 +- tests/unmanaged_models/tests.py | 3 +- tests/urlpatterns_reverse/tests.py | 23 +- tests/user_commands/tests.py | 2 +- tests/utils_tests/test_autoreload.py | 11 +- tests/utils_tests/test_html.py | 27 +- tests/utils_tests/test_jslex.py | 7 +- tests/utils_tests/test_lazyobject.py | 3 +- tests/utils_tests/test_text.py | 9 +- tests/validation/test_error_messages.py | 28 +- tests/view_tests/tests/test_csrf.py | 4 +- tests/view_tests/tests/test_debug.py | 21 +- tests/view_tests/tests/test_defaults.py | 7 +- tests/view_tests/tests/test_i18n.py | 3 +- tests/view_tests/views.py | 24 +- tests/wsgi/tests.py | 6 +- 404 files changed, 5944 insertions(+), 2842 deletions(-) diff --git a/django/apps/registry.py b/django/apps/registry.py index 06d5bca060..c5ba3a307d 100644 --- a/django/apps/registry.py +++ b/django/apps/registry.py @@ -224,9 +224,9 @@ class Apps: and model.__module__ == app_models[model_name].__module__ ): warnings.warn( - "Model '%s.%s' was already registered. " - "Reloading models is not advised as it can lead to inconsistencies, " - "most notably with related models." % (app_label, model_name), + "Model '%s.%s' was already registered. Reloading models is not " + "advised as it can lead to inconsistencies, most notably with " + "related models." % (app_label, model_name), RuntimeWarning, stacklevel=2, ) diff --git a/django/conf/global_settings.py b/django/conf/global_settings.py index 2a5f95d6fb..40b34bb71c 100644 --- a/django/conf/global_settings.py +++ b/django/conf/global_settings.py @@ -21,8 +21,8 @@ DEBUG = False # on a live site. DEBUG_PROPAGATE_EXCEPTIONS = False -# People who get code error notifications. -# In the format [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')] +# People who get code error notifications. In the format +# [('Full Name', 'email@example.com'), ('Full Name', 'anotheremail@example.com')] ADMINS = [] # List of IP addresses, as strings, that: @@ -319,7 +319,8 @@ DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000 FILE_UPLOAD_TEMP_DIR = None # The numeric mode to set newly-uploaded files to. The value should be a mode -# you'd pass directly to os.chmod; see https://docs.python.org/library/os.html#files-and-directories. +# you'd pass directly to os.chmod; see +# https://docs.python.org/library/os.html#files-and-directories. FILE_UPLOAD_PERMISSIONS = 0o644 # The numeric mode to assign to newly-created directories, when uploading files. diff --git a/django/contrib/admin/checks.py b/django/contrib/admin/checks.py index 7449503f5c..10d33b06f8 100644 --- a/django/contrib/admin/checks.py +++ b/django/contrib/admin/checks.py @@ -447,9 +447,9 @@ class BaseModelAdminChecks: ): return [ checks.Error( - "The value of '%s' cannot include the ManyToManyField '%s', " - "because that field manually specifies a relationship model." - % (label, field_name), + "The value of '%s' cannot include the ManyToManyField " + "'%s', because that field manually specifies a " + "relationship model." % (label, field_name), obj=obj.__class__, id="admin.E013", ) @@ -568,8 +568,8 @@ class BaseModelAdminChecks: return [ checks.Error( "The value of '%s' refers to '%s', which is not an " - "instance of ForeignKey, and does not have a 'choices' definition." - % (label, field_name), + "instance of ForeignKey, and does not have a 'choices' " + "definition." % (label, field_name), obj=obj.__class__, id="admin.E023", ) @@ -585,8 +585,8 @@ class BaseModelAdminChecks: if val not in (HORIZONTAL, VERTICAL): return [ checks.Error( - "The value of '%s' must be either admin.HORIZONTAL or admin.VERTICAL." - % label, + "The value of '%s' must be either admin.HORIZONTAL or " + "admin.VERTICAL." % label, obj=obj.__class__, id="admin.E024", ) @@ -598,7 +598,8 @@ class BaseModelAdminChecks: if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): return [ checks.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=obj.__class__, id="admin.E025", ) @@ -643,9 +644,9 @@ class BaseModelAdminChecks: ): return [ checks.Error( - "The value of '%s' refers to '%s', which must not be a DateTimeField, " - "a ForeignKey, a OneToOneField, or a ManyToManyField." - % (label, field_name), + "The value of '%s' refers to '%s', which must not be a " + "DateTimeField, a ForeignKey, a OneToOneField, or a " + "ManyToManyField." % (label, field_name), obj=obj.__class__, id="admin.E028", ) @@ -955,8 +956,8 @@ class ModelAdminChecks(BaseModelAdminChecks): if field_name not in obj.list_display: return [ checks.Error( - "The value of '%s' refers to '%s', which is not defined in 'list_display'." - % (label, field_name), + "The value of '%s' refers to '%s', which is not defined in " + "'list_display'." % (label, field_name), obj=obj.__class__, id="admin.E111", ) @@ -1027,8 +1028,8 @@ class ModelAdminChecks(BaseModelAdminChecks): except (NotRelationField, FieldDoesNotExist): return [ checks.Error( - "The value of '%s' refers to '%s', which does not refer to a Field." - % (label, field), + "The value of '%s' refers to '%s', which does not refer to a " + "Field." % (label, field), obj=obj.__class__, id="admin.E116", ) @@ -1107,8 +1108,8 @@ class ModelAdminChecks(BaseModelAdminChecks): elif obj.list_display_links and field_name in obj.list_display_links: return [ checks.Error( - "The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." - % field_name, + "The value of '%s' cannot be in both 'list_editable' and " + "'list_display_links'." % field_name, obj=obj.__class__, id="admin.E123", ) @@ -1122,9 +1123,9 @@ class ModelAdminChecks(BaseModelAdminChecks): ): return [ checks.Error( - "The value of '%s' refers to the first field in 'list_display' ('%s'), " - "which cannot be used unless 'list_display_links' is set." - % (label, obj.list_display[0]), + "The value of '%s' refers to the first field in 'list_display' " + "('%s'), which cannot be used unless 'list_display_links' is " + "set." % (label, obj.list_display[0]), obj=obj.__class__, id="admin.E124", ) @@ -1132,8 +1133,8 @@ class ModelAdminChecks(BaseModelAdminChecks): elif not field.editable: return [ checks.Error( - "The value of '%s' refers to '%s', which is not editable through the admin." - % (label, field_name), + "The value of '%s' refers to '%s', which is not editable " + "through the admin." % (label, field_name), obj=obj.__class__, id="admin.E125", ) diff --git a/django/contrib/admin/models.py b/django/contrib/admin/models.py index 917fc77dba..7ff04102a7 100644 --- a/django/contrib/admin/models.py +++ b/django/contrib/admin/models.py @@ -64,7 +64,8 @@ class LogEntry(models.Model): null=True, ) object_id = models.TextField(_("object id"), blank=True, null=True) - # Translators: 'repr' means representation (https://docs.python.org/library/functions.html#repr) + # Translators: 'repr' means representation + # (https://docs.python.org/library/functions.html#repr) object_repr = models.CharField(_("object repr"), max_length=200) action_flag = models.PositiveSmallIntegerField( _("action flag"), choices=ACTION_FLAG_CHOICES diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index f051c79ac9..b1aa610d43 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -1276,7 +1276,9 @@ class ModelAdmin(BaseModelAdmin): "has_add_permission": self.has_add_permission(request), "has_change_permission": self.has_change_permission(request, obj), "has_delete_permission": self.has_delete_permission(request, obj), - "has_editable_inline_admin_formsets": has_editable_inline_admin_formsets, + "has_editable_inline_admin_formsets": ( + has_editable_inline_admin_formsets + ), "has_file_field": context["adminform"].form.is_multipart() or any( admin_formset.formset.is_multipart() @@ -1383,7 +1385,8 @@ class ModelAdmin(BaseModelAdmin): elif "_addanother" in request.POST: msg = format_html( _( - "The {name} “{obj}” was added successfully. You may add another {name} below." + "The {name} “{obj}” was added successfully. You may add another " + "{name} below." ), **msg_dict, ) @@ -1444,7 +1447,8 @@ class ModelAdmin(BaseModelAdmin): if "_continue" in request.POST: msg = format_html( _( - "The {name} “{obj}” was changed successfully. You may edit it again below." + "The {name} “{obj}” was changed successfully. You may edit it " + "again below." ), **msg_dict, ) @@ -1458,7 +1462,8 @@ class ModelAdmin(BaseModelAdmin): elif "_saveasnew" in request.POST: msg = format_html( _( - "The {name} “{obj}” was added successfully. You may edit it again below." + "The {name} “{obj}” was added successfully. You may edit it again " + "below." ), **msg_dict, ) @@ -1476,7 +1481,8 @@ class ModelAdmin(BaseModelAdmin): elif "_addanother" in request.POST: msg = format_html( _( - "The {name} “{obj}” was changed successfully. You may add another {name} below." + "The {name} “{obj}” was changed successfully. You may add another " + "{name} below." ), **msg_dict, ) @@ -2389,8 +2395,9 @@ class InlineModelAdmin(BaseModelAdmin): objs = [] for p in collector.protected: objs.append( - # Translators: Model verbose name and instance representation, - # suitable to be an item in a list. + # Translators: Model verbose name and instance + # representation, suitable to be an item in a + # list. _("%(class_name)s %(instance)s") % {"class_name": p._meta.verbose_name, "instance": p} ) diff --git a/django/contrib/admin/templatetags/log.py b/django/contrib/admin/templatetags/log.py index 04a375013d..098aa640d5 100644 --- a/django/contrib/admin/templatetags/log.py +++ b/django/contrib/admin/templatetags/log.py @@ -32,7 +32,7 @@ def get_admin_log(parser, token): Usage:: - {% get_admin_log [limit] as [varname] for_user [context_var_containing_user_obj] %} + {% get_admin_log [limit] as [varname] for_user [context_var_with_user_obj] %} Examples:: diff --git a/django/contrib/auth/__init__.py b/django/contrib/auth/__init__.py index 00a2940344..155330c596 100644 --- a/django/contrib/auth/__init__.py +++ b/django/contrib/auth/__init__.py @@ -70,12 +70,14 @@ def authenticate(request=None, **credentials): try: backend_signature.bind(request, **credentials) except TypeError: - # This backend doesn't accept these credentials as arguments. Try the next one. + # This backend doesn't accept these credentials as arguments. Try + # the next one. continue try: user = backend.authenticate(request, **credentials) except PermissionDenied: - # This backend says to stop in our tracks - this user should not be allowed in at all. + # This backend says to stop in our tracks - this user should not be + # allowed in at all. break if user is None: continue diff --git a/django/contrib/auth/checks.py b/django/contrib/auth/checks.py index e1505d63fd..ee8082524d 100644 --- a/django/contrib/auth/checks.py +++ b/django/contrib/auth/checks.py @@ -61,8 +61,8 @@ def check_user_model(app_configs=None, **kwargs): ]: errors.append( checks.Error( - "'%s.%s' must be unique because it is named as the 'USERNAME_FIELD'." - % (cls._meta.object_name, cls.USERNAME_FIELD), + "'%s.%s' must be unique because it is named as the " + "'USERNAME_FIELD'." % (cls._meta.object_name, cls.USERNAME_FIELD), obj=cls, id="auth.E003", ) @@ -72,7 +72,10 @@ def check_user_model(app_configs=None, **kwargs): checks.Warning( "'%s.%s' is named as the 'USERNAME_FIELD', but it is not unique." % (cls._meta.object_name, cls.USERNAME_FIELD), - 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=cls, id="auth.W004", ) @@ -197,8 +200,8 @@ def check_models_permissions(app_configs=None, **kwargs): if codename in builtin_permissions: errors.append( checks.Error( - "The permission codenamed '%s' clashes with a builtin permission " - "for model '%s'." % (codename, opts.label), + "The permission codenamed '%s' clashes with a builtin " + "permission for model '%s'." % (codename, opts.label), obj=model, id="auth.E005", ) diff --git a/django/contrib/auth/management/commands/changepassword.py b/django/contrib/auth/management/commands/changepassword.py index dfe6cbe5f5..669d8cf5d0 100644 --- a/django/contrib/auth/management/commands/changepassword.py +++ b/django/contrib/auth/management/commands/changepassword.py @@ -24,7 +24,10 @@ class Command(BaseCommand): parser.add_argument( "username", nargs="?", - help="Username to change password for; by default, it's the current username.", + help=( + "Username to change password for; by default, it's the current " + "username." + ), ) parser.add_argument( "--database", diff --git a/django/contrib/auth/migrations/0001_initial.py b/django/contrib/auth/migrations/0001_initial.py index 87652308c1..3d1635f461 100644 --- a/django/contrib/auth/migrations/0001_initial.py +++ b/django/contrib/auth/migrations/0001_initial.py @@ -102,14 +102,20 @@ class Migration(migrations.Migration): "is_superuser", models.BooleanField( default=False, - help_text="Designates that this user has all permissions without explicitly assigning them.", + help_text=( + "Designates that this user has all permissions without " + "explicitly assigning them." + ), verbose_name="superuser status", ), ), ( "username", models.CharField( - help_text="Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.", + help_text=( + "Required. 30 characters or fewer. Letters, digits and " + "@/./+/-/_ only." + ), unique=True, max_length=30, verbose_name="username", @@ -138,7 +144,9 @@ class Migration(migrations.Migration): "is_staff", models.BooleanField( default=False, - help_text="Designates whether the user can log into this admin site.", + help_text=( + "Designates whether the user can log into this admin site." + ), verbose_name="staff status", ), ), @@ -148,8 +156,8 @@ class Migration(migrations.Migration): default=True, verbose_name="active", help_text=( - "Designates whether this user should be treated as active. Unselect this instead of deleting " - "accounts." + "Designates whether this user should be treated as active. " + "Unselect this instead of deleting accounts." ), ), ), @@ -168,8 +176,8 @@ class Migration(migrations.Migration): related_name="user_set", related_query_name="user", help_text=( - "The groups this user belongs to. A user will get all permissions granted to each of their " - "groups." + "The groups this user belongs to. A user will get all " + "permissions granted to each of their groups." ), ), ), diff --git a/django/contrib/auth/migrations/0004_alter_user_username_opts.py b/django/contrib/auth/migrations/0004_alter_user_username_opts.py index 380737478d..6930e9bccb 100644 --- a/django/contrib/auth/migrations/0004_alter_user_username_opts.py +++ b/django/contrib/auth/migrations/0004_alter_user_username_opts.py @@ -17,7 +17,10 @@ class Migration(migrations.Migration): error_messages={"unique": "A user with that username already exists."}, max_length=30, validators=[validators.UnicodeUsernameValidator()], - help_text="Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.", + help_text=( + "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ " + "only." + ), unique=True, verbose_name="username", ), diff --git a/django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py b/django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py index e0c835115e..3c94141e61 100644 --- a/django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py +++ b/django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py @@ -14,7 +14,10 @@ class Migration(migrations.Migration): name="username", field=models.CharField( error_messages={"unique": "A user with that username already exists."}, - help_text="Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.", + help_text=( + "Required. 30 characters or fewer. Letters, digits and @/./+/-/_ " + "only." + ), max_length=30, unique=True, validators=[validators.UnicodeUsernameValidator()], diff --git a/django/contrib/auth/migrations/0008_alter_user_username_max_length.py b/django/contrib/auth/migrations/0008_alter_user_username_max_length.py index 4208dbcc7a..bfb844bb2a 100644 --- a/django/contrib/auth/migrations/0008_alter_user_username_max_length.py +++ b/django/contrib/auth/migrations/0008_alter_user_username_max_length.py @@ -14,7 +14,10 @@ class Migration(migrations.Migration): name="username", field=models.CharField( error_messages={"unique": "A user with that username already exists."}, - help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.", + help_text=( + "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ " + "only." + ), max_length=150, unique=True, validators=[validators.UnicodeUsernameValidator()], diff --git a/django/contrib/auth/mixins.py b/django/contrib/auth/mixins.py index 09fd087f56..0e46000d97 100644 --- a/django/contrib/auth/mixins.py +++ b/django/contrib/auth/mixins.py @@ -25,8 +25,9 @@ class AccessMixin: login_url = self.login_url or settings.LOGIN_URL if not login_url: raise ImproperlyConfigured( - "{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override " - "{0}.get_login_url().".format(self.__class__.__name__) + f"{self.__class__.__name__} is missing the login_url attribute. Define " + f"{self.__class__.__name__}.login_url, settings.LOGIN_URL, or override " + f"{self.__class__.__name__}.get_login_url()." ) return str(login_url) @@ -84,8 +85,10 @@ class PermissionRequiredMixin(AccessMixin): """ if self.permission_required is None: raise ImproperlyConfigured( - "{0} is missing the permission_required attribute. Define {0}.permission_required, or override " - "{0}.get_permission_required().".format(self.__class__.__name__) + f"{self.__class__.__name__} is missing the " + f"permission_required attribute. Define " + f"{self.__class__.__name__}.permission_required, or override " + f"{self.__class__.__name__}.get_permission_required()." ) if isinstance(self.permission_required, str): perms = (self.permission_required,) diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py index 5dd9c03a76..85330e2c0e 100644 --- a/django/contrib/auth/models.py +++ b/django/contrib/auth/models.py @@ -435,7 +435,8 @@ class AnonymousUser: def __int__(self): raise TypeError( - "Cannot cast AnonymousUser to int. Are you trying to use it in place of User?" + "Cannot cast AnonymousUser to int. Are you trying to use it in place of " + "User?" ) def save(self): diff --git a/django/contrib/auth/password_validation.py b/django/contrib/auth/password_validation.py index 6af742eb6a..3f8f888ddc 100644 --- a/django/contrib/auth/password_validation.py +++ b/django/contrib/auth/password_validation.py @@ -28,7 +28,10 @@ def get_password_validators(validator_config): try: klass = import_string(validator["NAME"]) except ImportError: - msg = "The module in NAME could not be imported: %s. Check your AUTH_PASSWORD_VALIDATORS setting." + msg = ( + "The module in NAME could not be imported: %s. Check your " + "AUTH_PASSWORD_VALIDATORS setting." + ) raise ImproperlyConfigured(msg % validator["NAME"]) validators.append(klass(**validator.get("OPTIONS", {}))) @@ -105,8 +108,10 @@ class MinimumLengthValidator: if len(password) < self.min_length: raise ValidationError( ngettext( - "This password is too short. It must contain at least %(min_length)d character.", - "This password is too short. It must contain at least %(min_length)d characters.", + "This password is too short. It must contain at least " + "%(min_length)d character.", + "This password is too short. It must contain at least " + "%(min_length)d characters.", self.min_length, ), code="password_too_short", diff --git a/django/contrib/contenttypes/admin.py b/django/contrib/contenttypes/admin.py index 6f442549f1..617d6d2e81 100644 --- a/django/contrib/contenttypes/admin.py +++ b/django/contrib/contenttypes/admin.py @@ -19,8 +19,8 @@ class GenericInlineModelAdminChecks(InlineModelAdminChecks): return [] def _check_relation(self, obj, parent_model): - # There's no FK, but we do need to confirm that the ct_field and ct_fk_field are valid, - # and that they are part of a GenericForeignKey. + # There's no FK, but we do need to confirm that the ct_field and + # ct_fk_field are valid, and that they are part of a GenericForeignKey. gfks = [ f @@ -75,7 +75,8 @@ class GenericInlineModelAdminChecks(InlineModelAdminChecks): return [ checks.Error( - "'%s' has no GenericForeignKey using content type field '%s' and object ID field '%s'." + "'%s' has no GenericForeignKey using content type field '%s' and " + "object ID field '%s'." % ( obj.model._meta.label, obj.ct_field, diff --git a/django/contrib/contenttypes/models.py b/django/contrib/contenttypes/models.py index e4734cc893..ef4f30556f 100644 --- a/django/contrib/contenttypes/models.py +++ b/django/contrib/contenttypes/models.py @@ -120,8 +120,9 @@ class ContentTypeManager(models.Manager): def _add_to_cache(self, using, ct): """Insert a ContentType into the cache.""" - # Note it's possible for ContentType objects to be stale; model_class() will return None. - # Hence, there is no reliance on model._meta.app_label here, just using the model fields instead. + # Note it's possible for ContentType objects to be stale; model_class() + # will return None. Hence, there is no reliance on + # model._meta.app_label here, just using the model fields instead. key = (ct.app_label, ct.model) self._cache.setdefault(using, {})[key] = ct self._cache.setdefault(using, {})[ct.id] = ct diff --git a/django/contrib/flatpages/forms.py b/django/contrib/flatpages/forms.py index 18fdfa658b..a6619c51e7 100644 --- a/django/contrib/flatpages/forms.py +++ b/django/contrib/flatpages/forms.py @@ -12,7 +12,8 @@ class FlatpageForm(forms.ModelForm): max_length=100, regex=r"^[-\w/\.~]+$", help_text=_( - "Example: “/about/contact/”. Make sure to have leading and trailing slashes." + "Example: “/about/contact/”. Make sure to have leading and trailing " + "slashes." ), error_messages={ "invalid": _( diff --git a/django/contrib/flatpages/migrations/0001_initial.py b/django/contrib/flatpages/migrations/0001_initial.py index 6faa610181..631ebbcb1e 100644 --- a/django/contrib/flatpages/migrations/0001_initial.py +++ b/django/contrib/flatpages/migrations/0001_initial.py @@ -34,8 +34,8 @@ class Migration(migrations.Migration): "template_name", models.CharField( help_text=( - "Example: “flatpages/contact_page.html”. If this isn’t provided, the system will use " - "“flatpages/default.html”." + "Example: “flatpages/contact_page.html”. If this isn’t " + "provided, the system will use “flatpages/default.html”." ), max_length=70, verbose_name="template name", @@ -46,7 +46,10 @@ class Migration(migrations.Migration): "registration_required", models.BooleanField( default=False, - help_text="If this is checked, only logged-in users will be able to view the page.", + help_text=( + "If this is checked, only logged-in users will be able to " + "view the page." + ), verbose_name="registration required", ), ), diff --git a/django/contrib/gis/db/backends/base/operations.py b/django/contrib/gis/db/backends/base/operations.py index 5e56b82a78..e7bffb11b4 100644 --- a/django/contrib/gis/db/backends/base/operations.py +++ b/django/contrib/gis/db/backends/base/operations.py @@ -158,12 +158,14 @@ class BaseSpatialOperations: # Routines for getting the OGC-compliant models. def geometry_columns(self): raise NotImplementedError( - "Subclasses of BaseSpatialOperations must provide a geometry_columns() method." + "Subclasses of BaseSpatialOperations must provide a geometry_columns() " + "method." ) def spatial_ref_sys(self): raise NotImplementedError( - "subclasses of BaseSpatialOperations must a provide spatial_ref_sys() method" + "subclasses of BaseSpatialOperations must a provide spatial_ref_sys() " + "method" ) distance_expr_for_lookup = staticmethod(Distance) diff --git a/django/contrib/gis/db/backends/oracle/features.py b/django/contrib/gis/db/backends/oracle/features.py index ee4b296c07..f346d93573 100644 --- a/django/contrib/gis/db/backends/oracle/features.py +++ b/django/contrib/gis/db/backends/oracle/features.py @@ -20,7 +20,8 @@ class DatabaseFeatures(BaseSpatialFeatures, OracleDatabaseFeatures): skips.update( { "Oracle doesn't support spatial operators in constraints.": { - "gis_tests.gis_migrations.test_operations.OperationTests.test_add_check_constraint", + "gis_tests.gis_migrations.test_operations.OperationTests." + "test_add_check_constraint", }, } ) diff --git a/django/contrib/gis/db/backends/oracle/operations.py b/django/contrib/gis/db/backends/oracle/operations.py index 45010ef517..ba7e3ca4d8 100644 --- a/django/contrib/gis/db/backends/oracle/operations.py +++ b/django/contrib/gis/db/backends/oracle/operations.py @@ -40,7 +40,10 @@ class SDORelate(SpatialOperator): sql_template = "SDO_RELATE(%(lhs)s, %(rhs)s, 'mask=%(mask)s') = 'TRUE'" def check_relate_argument(self, arg): - masks = "TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|CONTAINS|COVERS|ANYINTERACT|ON" + masks = ( + "TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|" + "CONTAINS|COVERS|ANYINTERACT|ON" + ) mask_regex = re.compile(r"^(%s)(\+(%s))*$" % (masks, masks), re.I) if not isinstance(arg, str) or not mask_regex.match(arg): raise ValueError('Invalid SDO_RELATE mask: "%s"' % arg) @@ -105,7 +108,8 @@ class OracleOperations(BaseSpatialOperations, DatabaseOperations): "exact": SDOOperator(func="SDO_EQUAL"), "overlaps": SDOOperator(func="SDO_OVERLAPS"), "same_as": SDOOperator(func="SDO_EQUAL"), - "relate": SDORelate(), # Oracle uses a different syntax, e.g., 'mask=inside+touch' + # Oracle uses a different syntax, e.g., 'mask=inside+touch' + "relate": SDORelate(), "touches": SDOOperator(func="SDO_TOUCH"), "within": SDOOperator(func="SDO_INSIDE"), "dwithin": SDODWithin(), diff --git a/django/contrib/gis/db/backends/oracle/schema.py b/django/contrib/gis/db/backends/oracle/schema.py index edc692ffc7..c9192d03fa 100644 --- a/django/contrib/gis/db/backends/oracle/schema.py +++ b/django/contrib/gis/db/backends/oracle/schema.py @@ -16,7 +16,10 @@ class OracleGISSchemaEditor(DatabaseSchemaEditor): ), %(srid)s )""" - sql_add_spatial_index = "CREATE INDEX %(index)s ON %(table)s(%(column)s) INDEXTYPE IS MDSYS.SPATIAL_INDEX" + sql_add_spatial_index = ( + "CREATE INDEX %(index)s ON %(table)s(%(column)s) " + "INDEXTYPE IS MDSYS.SPATIAL_INDEX" + ) sql_drop_spatial_index = "DROP INDEX %(index)s" sql_clear_geometry_table_metadata = ( "DELETE FROM USER_SDO_GEOM_METADATA WHERE TABLE_NAME = %(table)s" diff --git a/django/contrib/gis/db/backends/postgis/const.py b/django/contrib/gis/db/backends/postgis/const.py index d2ad51799f..2f4393d25e 100644 --- a/django/contrib/gis/db/backends/postgis/const.py +++ b/django/contrib/gis/db/backends/postgis/const.py @@ -56,7 +56,7 @@ STRUCT_SIZE = { # whether the band data is stored as part of the datum or is to be found on the # server's filesystem. There are currently 11 supported pixel value types, so 4 # bits are enough to account for all. Reserve the upper 4 bits for generic -# flags. -# See https://trac.osgeo.org/postgis/wiki/WKTRaster/RFC/RFC1_V0SerialFormat#Pixeltypeandstorageflag +# flags. See +# https://trac.osgeo.org/postgis/wiki/WKTRaster/RFC/RFC1_V0SerialFormat#Pixeltypeandstorageflag BANDTYPE_PIXTYPE_MASK = 0x0F BANDTYPE_FLAG_HASNODATA = 1 << 6 diff --git a/django/contrib/gis/db/backends/postgis/introspection.py b/django/contrib/gis/db/backends/postgis/introspection.py index b12b7b912f..766c0fa583 100644 --- a/django/contrib/gis/db/backends/postgis/introspection.py +++ b/django/contrib/gis/db/backends/postgis/introspection.py @@ -22,7 +22,9 @@ class PostGISIntrospection(DatabaseIntrospection): # dictionary isn't updated until introspection is performed here. with self.connection.cursor() as cursor: cursor.execute( - "SELECT oid, typname FROM pg_type WHERE typname IN ('geometry', 'geography')" + "SELECT oid, typname " + "FROM pg_type " + "WHERE typname IN ('geometry', 'geography')" ) self.postgis_oid_lookup = dict(cursor.fetchall()) self.data_types_reverse.update( diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py index b11b2efcf3..36bec4ba5d 100644 --- a/django/contrib/gis/db/backends/postgis/operations.py +++ b/django/contrib/gis/db/backends/postgis/operations.py @@ -56,7 +56,8 @@ class PostGISOperator(SpatialOperator): if lookup.band_lhs is not None and lhs_is_raster: if not self.func: raise ValueError( - "Band indices are not allowed for this operator, it works on bbox only." + "Band indices are not allowed for this operator, it works on bbox " + "only." ) template_params["lhs"] = "%s, %s" % ( template_params["lhs"], @@ -66,7 +67,8 @@ class PostGISOperator(SpatialOperator): if lookup.band_rhs is not None and rhs_is_raster: if not self.func: raise ValueError( - "Band indices are not allowed for this operator, it works on bbox only." + "Band indices are not allowed for this operator, it works on bbox " + "only." ) template_params["rhs"] = "%s, %s" % ( template_params["rhs"], diff --git a/django/contrib/gis/db/models/functions.py b/django/contrib/gis/db/models/functions.py index c7b071c7c9..5f6c7b5cfd 100644 --- a/django/contrib/gis/db/models/functions.py +++ b/django/contrib/gis/db/models/functions.py @@ -317,9 +317,11 @@ class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFunc): ) if not geography and self.geo_field.geodetic(connection): - # Geometry fields with geodetic (lon/lat) coordinates need special distance functions + # Geometry fields with geodetic (lon/lat) coordinates need special + # distance functions. if self.spheroid: - # DistanceSpheroid is more accurate and resource intensive than DistanceSphere + # DistanceSpheroid is more accurate and resource intensive than + # DistanceSphere. function = connection.ops.spatial_function_name("DistanceSpheroid") # Replace boolean param by the real spheroid of the base field clone.source_expressions.append( diff --git a/django/contrib/gis/db/models/lookups.py b/django/contrib/gis/db/models/lookups.py index 9c06922508..07762d0a13 100644 --- a/django/contrib/gis/db/models/lookups.py +++ b/django/contrib/gis/db/models/lookups.py @@ -202,7 +202,8 @@ class BBContainsLookup(GISLookup): @BaseSpatialField.register_lookup class BBOverlapsLookup(GISLookup): """ - The 'bboverlaps' operator returns true if A's bounding box overlaps B's bounding box. + The 'bboverlaps' operator returns true if A's bounding box overlaps B's + bounding box. """ lookup_name = "bboverlaps" @@ -307,7 +308,8 @@ class DistanceLookupBase(GISLookup): ) elif len(self.rhs_params) == 3 and self.rhs_params[2] != "spheroid": raise ValueError( - "For 4-element tuples the last argument must be the 'spheroid' directive." + "For 4-element tuples the last argument must be the 'spheroid' " + "directive." ) # Check if the second parameter is a band index. diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py index dbb391f75f..f74dc688b3 100644 --- a/django/contrib/gis/gdal/geometries.py +++ b/django/contrib/gis/gdal/geometries.py @@ -28,7 +28,7 @@ >>> print(mpnt.proj) +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs >>> print(mpnt) - MULTIPOINT (-89.999930378602485 29.999797886557641,-89.999930378602485 29.999797886557641) + MULTIPOINT (-89.99993037860248 29.99979788655764,-89.99993037860248 29.99979788655764) The OGRGeomType class is to make it easy to specify an OGR geometry type: >>> from django.contrib.gis.gdal import OGRGeomType diff --git a/django/contrib/gis/gdal/layer.py b/django/contrib/gis/gdal/layer.py index e8f97b7552..1afa0469f6 100644 --- a/django/contrib/gis/gdal/layer.py +++ b/django/contrib/gis/gdal/layer.py @@ -19,7 +19,10 @@ from django.utils.encoding import force_bytes, force_str # # The OGR_L_* routines are relevant here. class Layer(GDALBase): - "A class that wraps an OGR Layer, needs to be instantiated from a DataSource object." + """ + A class that wraps an OGR Layer, needs to be instantiated from a DataSource + object. + """ def __init__(self, layer_ptr, ds): """ @@ -192,7 +195,8 @@ class Layer(GDALBase): capi.set_spatial_filter(self.ptr, None) else: raise TypeError( - "Spatial filter must be either an OGRGeometry instance, a 4-tuple, or None." + "Spatial filter must be either an OGRGeometry instance, a 4-tuple, or " + "None." ) spatial_filter = property(_get_spatial_filter, _set_spatial_filter) diff --git a/django/contrib/gis/gdal/srs.py b/django/contrib/gis/gdal/srs.py index 41477d55db..2e335fe5d5 100644 --- a/django/contrib/gis/gdal/srs.py +++ b/django/contrib/gis/gdal/srs.py @@ -131,7 +131,8 @@ class SpatialReference(GDALBase): 4326 >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt 0 - >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbole. + >>> # For the units authority, have to use the pipe symbole. + >>> print(srs['UNIT|AUTHORITY']) EPSG >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units 9122 diff --git a/django/contrib/gis/geos/polygon.py b/django/contrib/gis/geos/polygon.py index 452e72fcb6..e384614b0b 100644 --- a/django/contrib/gis/geos/polygon.py +++ b/django/contrib/gis/geos/polygon.py @@ -32,7 +32,8 @@ class Polygon(GEOSGeometry): ext_ring, *init_holes = args n_holes = len(init_holes) - # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility] + # If initialized as Polygon(shell, (LinearRing, LinearRing)) + # [for backward-compatibility] if n_holes == 1 and isinstance(init_holes[0], (tuple, list)): if not init_holes[0]: init_holes = () @@ -101,7 +102,8 @@ class Polygon(GEOSGeometry): self, param, msg=( - "Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings" + "Parameter must be a sequence of LinearRings or objects that can " + "initialize to LinearRings" ), ): "Try to construct a ring from the given parameter." diff --git a/django/contrib/gis/management/commands/ogrinspect.py b/django/contrib/gis/management/commands/ogrinspect.py index 133cec3e60..2d2bd63176 100644 --- a/django/contrib/gis/management/commands/ogrinspect.py +++ b/django/contrib/gis/management/commands/ogrinspect.py @@ -34,8 +34,8 @@ class ListOptionAction(argparse.Action): class Command(BaseCommand): help = ( - "Inspects the given OGR-compatible data source (e.g., a shapefile) and outputs\n" - "a GeoDjango model with the given model name. For example:\n" + "Inspects the given OGR-compatible data source (e.g., a shapefile) and " + "outputs\na GeoDjango model with the given model name. For example:\n" " ./manage.py ogrinspect zipcode.shp Zipcode" ) diff --git a/django/contrib/gis/serializers/geojson.py b/django/contrib/gis/serializers/geojson.py index f90d3544e7..865e90caec 100644 --- a/django/contrib/gis/serializers/geojson.py +++ b/django/contrib/gis/serializers/geojson.py @@ -25,7 +25,8 @@ class Serializer(JSONSerializer): self._init_options() self._cts = {} # cache of CoordTransform's self.stream.write( - '{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:%d"}},' + '{"type": "FeatureCollection", ' + '"crs": {"type": "name", "properties": {"name": "EPSG:%d"}},' ' "features": [' % self.srid ) @@ -53,7 +54,8 @@ class Serializer(JSONSerializer): data["properties"]["pk"] = obj._meta.pk.value_to_string(obj) if self._geometry: if self._geometry.srid != self.srid: - # If needed, transform the geometry in the srid of the global geojson srid + # If needed, transform the geometry in the srid of the global + # geojson srid. if self._geometry.srid not in self._cts: srs = SpatialReference(self.srid) self._cts[self._geometry.srid] = CoordTransform( diff --git a/django/contrib/gis/sitemaps/kml.py b/django/contrib/gis/sitemaps/kml.py index 5ec089d6f5..a84b5aef6d 100644 --- a/django/contrib/gis/sitemaps/kml.py +++ b/django/contrib/gis/sitemaps/kml.py @@ -42,7 +42,8 @@ class KMLSitemap(Sitemap): elif isinstance(source, (list, tuple)): if len(source) != 3: raise ValueError( - "Must specify a 3-tuple of (app_label, module_name, field_name)." + "Must specify a 3-tuple of (app_label, module_name, " + "field_name)." ) kml_sources.append(source) else: diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index bad4c05fb8..2dcf839603 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -233,7 +233,8 @@ class LayerMapping: if isinstance(model_field, GeometryField): if self.geom_field: raise LayerMapError( - "LayerMapping does not support more than one GeometryField per model." + "LayerMapping does not support more than one GeometryField per " + "model." ) # Getting the coordinate dimension of the geometry field. @@ -695,7 +696,8 @@ class LayerMapping: # Incremental saving is requested at the given interval (step) if default_range: raise LayerMapError( - "The `step` keyword may not be used in conjunction with the `fid_range` keyword." + "The `step` keyword may not be used in conjunction with the " + "`fid_range` keyword." ) beg, num_feat, num_saved = (0, 0, 0) indices = range(step, nfeat, step) diff --git a/django/contrib/gis/utils/ogrinspect.py b/django/contrib/gis/utils/ogrinspect.py index c50b39ad14..40ca0cb461 100644 --- a/django/contrib/gis/utils/ogrinspect.py +++ b/django/contrib/gis/utils/ogrinspect.py @@ -209,7 +209,9 @@ def _ogrinspect( # may also be mapped to `DecimalField` if specified in the # `decimal` keyword. if field_name.lower() in decimal_fields: - yield " %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)" % ( + yield ( + " %s = models.DecimalField(max_digits=%d, decimal_places=%d%s)" + ) % ( mfield, width, precision, diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py index bdceec344d..07bb70b186 100644 --- a/django/contrib/humanize/templatetags/humanize.py +++ b/django/contrib/humanize/templatetags/humanize.py @@ -256,7 +256,8 @@ class NaturalTimeFormatter: ), } future_substrings = { - # Translators: 'naturaltime-future' strings will be included in '%(delta)s from now' + # Translators: 'naturaltime-future' strings will be included in + # '%(delta)s from now'. "year": npgettext_lazy( "naturaltime-future", "%(num)d year", "%(num)d years", "num" ), diff --git a/django/contrib/postgres/constraints.py b/django/contrib/postgres/constraints.py index c0bc0c444f..07dbc8cda1 100644 --- a/django/contrib/postgres/constraints.py +++ b/django/contrib/postgres/constraints.py @@ -18,7 +18,10 @@ class ExclusionConstraintExpression(IndexExpression): class ExclusionConstraint(BaseConstraint): - template = "CONSTRAINT %(name)s EXCLUDE USING %(index_type)s (%(expressions)s)%(include)s%(where)s%(deferrable)s" + template = ( + "CONSTRAINT %(name)s EXCLUDE USING %(index_type)s " + "(%(expressions)s)%(include)s%(where)s%(deferrable)s" + ) def __init__( self, diff --git a/django/contrib/postgres/fields/ranges.py b/django/contrib/postgres/fields/ranges.py index 58ffacbbe5..f0a2a58936 100644 --- a/django/contrib/postgres/fields/ranges.py +++ b/django/contrib/postgres/fields/ranges.py @@ -54,7 +54,8 @@ class RangeField(models.Field): raise TypeError( f"Cannot use 'default_bounds' with {self.__class__.__name__}." ) - # Initializing base_field here ensures that its model matches the model for self. + # Initializing base_field here ensures that its model matches the model + # for self. if hasattr(self, "base_field"): self.base_field = self.base_field() super().__init__(*args, **kwargs) diff --git a/django/contrib/postgres/operations.py b/django/contrib/postgres/operations.py index 374f5ee1ec..b2d6d9f95a 100644 --- a/django/contrib/postgres/operations.py +++ b/django/contrib/postgres/operations.py @@ -185,9 +185,8 @@ class CollationOperation(Operation): ) def create_collation(self, schema_editor): - if ( - self.deterministic is False - and not schema_editor.connection.features.supports_non_deterministic_collations + if self.deterministic is False and not ( + schema_editor.connection.features.supports_non_deterministic_collations ): raise NotSupportedError( "Non-deterministic collations require PostgreSQL 12+." diff --git a/django/contrib/postgres/validators.py b/django/contrib/postgres/validators.py index df2bd88eb9..47bb7bc7b6 100644 --- a/django/contrib/postgres/validators.py +++ b/django/contrib/postgres/validators.py @@ -12,16 +12,20 @@ from django.utils.translation import ngettext_lazy class ArrayMaxLengthValidator(MaxLengthValidator): message = ngettext_lazy( - "List contains %(show_value)d item, it should contain no more than %(limit_value)d.", - "List contains %(show_value)d items, it should contain no more than %(limit_value)d.", + "List contains %(show_value)d item, it should contain no more than " + "%(limit_value)d.", + "List contains %(show_value)d items, it should contain no more than " + "%(limit_value)d.", "limit_value", ) class ArrayMinLengthValidator(MinLengthValidator): message = ngettext_lazy( - "List contains %(show_value)d item, it should contain no fewer than %(limit_value)d.", - "List contains %(show_value)d items, it should contain no fewer than %(limit_value)d.", + "List contains %(show_value)d item, it should contain no fewer than " + "%(limit_value)d.", + "List contains %(show_value)d items, it should contain no fewer than " + "%(limit_value)d.", "limit_value", ) diff --git a/django/contrib/redirects/migrations/0001_initial.py b/django/contrib/redirects/migrations/0001_initial.py index 79dd21f15d..3b3b87962a 100644 --- a/django/contrib/redirects/migrations/0001_initial.py +++ b/django/contrib/redirects/migrations/0001_initial.py @@ -32,7 +32,8 @@ class Migration(migrations.Migration): "old_path", models.CharField( help_text=( - "This should be an absolute path, excluding the domain name. Example: “/events/search/”." + "This should be an absolute path, excluding the domain " + "name. Example: “/events/search/”." ), max_length=200, verbose_name="redirect from", @@ -42,7 +43,10 @@ class Migration(migrations.Migration): ( "new_path", models.CharField( - help_text="This can be either an absolute path (as above) or a full URL starting with “http://”.", + help_text=( + "This can be either an absolute path (as above) or a full " + "URL starting with “http://”." + ), max_length=200, verbose_name="redirect to", blank=True, diff --git a/django/contrib/redirects/models.py b/django/contrib/redirects/models.py index 0375e65c67..1552414977 100644 --- a/django/contrib/redirects/models.py +++ b/django/contrib/redirects/models.py @@ -10,7 +10,8 @@ class Redirect(models.Model): max_length=200, db_index=True, help_text=_( - "This should be an absolute path, excluding the domain name. Example: “/events/search/”." + "This should be an absolute path, excluding the domain name. Example: " + "“/events/search/”." ), ) new_path = models.CharField( diff --git a/django/contrib/sitemaps/__init__.py b/django/contrib/sitemaps/__init__.py index 05249b218b..27756d9d96 100644 --- a/django/contrib/sitemaps/__init__.py +++ b/django/contrib/sitemaps/__init__.py @@ -48,7 +48,8 @@ def _get_sitemap_full_url(sitemap_url, sitemap_uses_https=True): if sitemap_url is None: raise SitemapNotFound( - "You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected." + "You didn't provide a sitemap_url, and the sitemap URL couldn't be " + "auto-detected." ) Site = django_apps.get_model("sites.Site") diff --git a/django/contrib/sitemaps/views.py b/django/contrib/sitemaps/views.py index f5c0935a96..41c115de49 100644 --- a/django/contrib/sitemaps/views.py +++ b/django/contrib/sitemaps/views.py @@ -20,7 +20,10 @@ class SitemapIndexItem: # RemovedInDjango50Warning def __str__(self): - msg = "Calling `__str__` on SitemapIndexItem is deprecated, use the `location` attribute instead." + msg = ( + "Calling `__str__` on SitemapIndexItem is deprecated, use the `location` " + "attribute instead." + ) warnings.warn(msg, RemovedInDjango50Warning, stacklevel=2) return self.location diff --git a/django/contrib/sites/managers.py b/django/contrib/sites/managers.py index 15682d7e38..ec28826560 100644 --- a/django/contrib/sites/managers.py +++ b/django/contrib/sites/managers.py @@ -35,7 +35,8 @@ class CurrentSiteManager(models.Manager): if not field.many_to_many and not isinstance(field, (models.ForeignKey)): return [ checks.Error( - "CurrentSiteManager cannot use '%s.%s' as it is not a foreign key or a many-to-many field." + "CurrentSiteManager cannot use '%s.%s' as it is not a foreign key " + "or a many-to-many field." % (self.model._meta.object_name, field_name), obj=self, id="sites.E002", diff --git a/django/contrib/staticfiles/management/commands/collectstatic.py b/django/contrib/staticfiles/management/commands/collectstatic.py index c6d561bc81..c346038df8 100644 --- a/django/contrib/staticfiles/management/commands/collectstatic.py +++ b/django/contrib/staticfiles/management/commands/collectstatic.py @@ -83,7 +83,10 @@ class Command(BaseCommand): "--no-default-ignore", action="store_false", dest="use_default_ignore_patterns", - help="Don't ignore the common private glob-style patterns (defaults to 'CVS', '.*' and '*~').", + help=( + "Don't ignore the common private glob-style patterns (defaults to " + "'CVS', '.*' and '*~')." + ), ) def set_options(self, **options): @@ -169,7 +172,8 @@ class Command(BaseCommand): message = ["\n"] if self.dry_run: message.append( - "You have activated the --dry-run option so no files will be modified.\n\n" + "You have activated the --dry-run option so no files will be " + "modified.\n\n" ) message.append( diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py index 2416168634..c970505b48 100644 --- a/django/core/cache/backends/memcached.py +++ b/django/core/cache/backends/memcached.py @@ -77,7 +77,8 @@ class BaseMemcachedCache(BaseCache): def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) if not self._cache.set(key, value, self.get_backend_timeout(timeout)): - # make sure the key doesn't keep its old value in case of failure to set (memcached's 1MB limit) + # Make sure the key doesn't keep its old value in case of failure + # to set (memcached's 1MB limit). self._cache.delete(key) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): diff --git a/django/core/checks/security/csrf.py b/django/core/checks/security/csrf.py index ea65e48c94..af59589ae5 100644 --- a/django/core/checks/security/csrf.py +++ b/django/core/checks/security/csrf.py @@ -60,8 +60,8 @@ def check_csrf_failure_view(app_configs, **kwargs): inspect.signature(view).bind(None, reason=None) except TypeError: msg = ( - "The CSRF failure view '%s' does not take the correct number of arguments." - % settings.CSRF_FAILURE_VIEW + "The CSRF failure view '%s' does not take the correct number of " + "arguments." % settings.CSRF_FAILURE_VIEW ) errors.append(Error(msg, id="security.E101")) return errors diff --git a/django/core/files/locks.py b/django/core/files/locks.py index da1a25fcf0..5752b08a69 100644 --- a/django/core/files/locks.py +++ b/django/core/files/locks.py @@ -6,7 +6,7 @@ Cookbook [1] (licensed under the Python Software License) and a ctypes port by Anatoly Techtonik for Roundup [2] (license [3]). [1] https://code.activestate.com/recipes/65203/ -[2] https://sourceforge.net/p/roundup/code/ci/default/tree/roundup/backends/portalocker.py +[2] https://sourceforge.net/p/roundup/code/ci/default/tree/roundup/backends/portalocker.py # NOQA [3] https://sourceforge.net/p/roundup/code/ci/default/tree/COPYING.txt Example Usage:: diff --git a/django/core/files/storage.py b/django/core/files/storage.py index 690456aa71..714f9c1255 100644 --- a/django/core/files/storage.py +++ b/django/core/files/storage.py @@ -104,7 +104,8 @@ class Storage: truncation = len(name) - max_length if truncation > 0: file_root = file_root[:-truncation] - # Entire file_root was truncated in attempt to find an available filename. + # Entire file_root was truncated in attempt to find an + # available filename. if not file_root: raise SuspiciousFileOperation( 'Storage can not find an available filename for "%s". ' diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py index 64781f811b..b6c185e8fc 100644 --- a/django/core/files/uploadhandler.py +++ b/django/core/files/uploadhandler.py @@ -242,7 +242,10 @@ def load_handler(path, *args, **kwargs): E.g.:: >>> from django.http import HttpRequest >>> request = HttpRequest() - >>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request) + >>> load_handler( + ... 'django.core.files.uploadhandler.TemporaryFileUploadHandler', + ... request, + ... ) """ return import_string(path)(*args, **kwargs) diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py index 7c863bb5c1..0f341a5328 100644 --- a/django/core/handlers/base.py +++ b/django/core/handlers/base.py @@ -208,7 +208,8 @@ class BaseHandler: if hasattr(response, "render") and callable(response.render): for middleware_method in self._template_response_middleware: response = middleware_method(request, response) - # Complain if the template response middleware returned None (a common error). + # Complain if the template response middleware returned None + # (a common error). self.check_response( response, middleware_method, diff --git a/django/core/management/base.py b/django/core/management/base.py index ab1f7e9f70..f0e711ac76 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -308,7 +308,10 @@ class BaseCommand: default=1, type=int, choices=[0, 1, 2, 3], - help="Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output", + help=( + "Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, " + "3=very verbose output" + ), ) self.add_base_argument( parser, @@ -322,7 +325,10 @@ class BaseCommand: self.add_base_argument( parser, "--pythonpath", - help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".', + help=( + "A directory to add to the Python path, e.g. " + '"/home/djangoprojects/myproject".' + ), ) self.add_base_argument( parser, diff --git a/django/core/management/commands/compilemessages.py b/django/core/management/commands/compilemessages.py index bd055d087f..9ed3ef7c31 100644 --- a/django/core/management/commands/compilemessages.py +++ b/django/core/management/commands/compilemessages.py @@ -173,8 +173,8 @@ class Command(BaseCommand): # Check writability on first location if i == 0 and not is_writable(mo_path): self.stderr.write( - "The po files under %s are in a seemingly not writable location. " - "mo files will not be updated/created." % dirpath + "The po files under %s are in a seemingly not writable " + "location. mo files will not be updated/created." % dirpath ) self.has_errors = True return diff --git a/django/core/management/commands/createcachetable.py b/django/core/management/commands/createcachetable.py index 99dc3da040..65ed1686d2 100644 --- a/django/core/management/commands/createcachetable.py +++ b/django/core/management/commands/createcachetable.py @@ -22,7 +22,10 @@ class Command(BaseCommand): "args", metavar="table_name", nargs="*", - help="Optional table names. Otherwise, settings.CACHES is used to find cache tables.", + help=( + "Optional table names. Otherwise, settings.CACHES is used to find " + "cache tables." + ), ) parser.add_argument( "--database", diff --git a/django/core/management/commands/dbshell.py b/django/core/management/commands/dbshell.py index 9cdd64f190..30d2765afb 100644 --- a/django/core/management/commands/dbshell.py +++ b/django/core/management/commands/dbshell.py @@ -16,7 +16,10 @@ class Command(BaseCommand): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, - help='Nominates a database onto which to open a shell. Defaults to the "default" database.', + help=( + "Nominates a database onto which to open a shell. Defaults to the " + '"default" database.' + ), ) parameters = parser.add_argument_group("parameters", prefix_chars="--") parameters.add_argument("parameters", nargs="*") diff --git a/django/core/management/commands/diffsettings.py b/django/core/management/commands/diffsettings.py index 27cd575294..047e4764a8 100644 --- a/django/core/management/commands/diffsettings.py +++ b/django/core/management/commands/diffsettings.py @@ -25,8 +25,8 @@ class Command(BaseCommand): "--default", metavar="MODULE", help=( - "The settings module to compare the current settings against. Leave empty to " - "compare against Django's default settings." + "The settings module to compare the current settings against. Leave " + "empty to compare against Django's default settings." ), ) parser.add_argument( diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py index 74a5b2d22a..038b82698d 100644 --- a/django/core/management/commands/dumpdata.py +++ b/django/core/management/commands/dumpdata.py @@ -38,7 +38,10 @@ class Command(BaseCommand): "args", metavar="app_label[.ModelName]", nargs="*", - help="Restricts dumped data to the specified app_label or app_label.ModelName.", + help=( + "Restricts dumped data to the specified app_label or " + "app_label.ModelName." + ), ) parser.add_argument( "--format", @@ -81,8 +84,11 @@ class Command(BaseCommand): "--all", action="store_true", dest="use_base_manager", - help="Use Django's base manager to dump all models stored in the database, " - "including those that would otherwise be filtered or modified by a custom manager.", + help=( + "Use Django's base manager to dump all models stored in the database, " + "including those that would otherwise be filtered or modified by a " + "custom manager." + ), ) parser.add_argument( "--pks", diff --git a/django/core/management/commands/flush.py b/django/core/management/commands/flush.py index 8bad63d41d..e9d440dd86 100644 --- a/django/core/management/commands/flush.py +++ b/django/core/management/commands/flush.py @@ -82,7 +82,8 @@ Are you sure you want to do this? % (connection.settings_dict["NAME"],) ) from exc - # Empty sql_list may signify an empty database and post_migrate would then crash + # Empty sql_list may signify an empty database and post_migrate + # would then crash. if sql_list and not inhibit_post_migrate: # Emit the post migrate signal. This allows individual applications to # respond as if the database had been migrated from scratch. diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py index 753290d574..b48f6fcdd9 100644 --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -7,7 +7,10 @@ from django.db.models.constants import LOOKUP_SEP class Command(BaseCommand): - help = "Introspects the database tables in the given database and outputs a Django model module." + help = ( + "Introspects the database tables in the given database and outputs a Django " + "model module." + ) requires_system_checks = [] stealth_options = ("table_name_filter",) db_module = "django.db" @@ -22,7 +25,10 @@ class Command(BaseCommand): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, - help='Nominates a database to introspect. Defaults to using the "default" database.', + help=( + 'Nominates a database to introspect. Defaults to using the "default" ' + "database." + ), ) parser.add_argument( "--include-partitions", @@ -41,7 +47,8 @@ class Command(BaseCommand): self.stdout.write(line) except NotImplementedError: raise CommandError( - "Database inspection isn't supported for the currently selected database backend." + "Database inspection isn't supported for the currently selected " + "database backend." ) def handle_inspection(self, options): @@ -57,12 +64,18 @@ class Command(BaseCommand): yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" - yield "# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior" + yield ( + "# * Make sure each ForeignKey and OneToOneField has `on_delete` set " + "to the desired behavior" + ) yield ( "# * Remove `managed = False` lines if you wish to allow " "Django to create, modify, and delete the table" ) - yield "# Feel free to rename the models, but don't rename db_table values or field names." + yield ( + "# Feel free to rename the models, but don't rename db_table values or " + "field names." + ) yield "from %s import models" % self.db_module known_models = [] table_info = connection.introspection.get_table_list(cursor) diff --git a/django/core/management/commands/loaddata.py b/django/core/management/commands/loaddata.py index 38a2818d5c..ac97f13161 100644 --- a/django/core/management/commands/loaddata.py +++ b/django/core/management/commands/loaddata.py @@ -55,7 +55,10 @@ class Command(BaseCommand): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, - help='Nominates a specific database to load fixtures into. Defaults to the "default" database.', + help=( + "Nominates a specific database to load fixtures into. Defaults to the " + '"default" database.' + ), ) parser.add_argument( "--app", @@ -75,7 +78,10 @@ class Command(BaseCommand): "--exclude", action="append", default=[], - help="An app_label or app_label.ModelName to exclude. Can be used multiple times.", + help=( + "An app_label or app_label.ModelName to exclude. Can be used multiple " + "times." + ), ) parser.add_argument( "--format", @@ -105,7 +111,8 @@ class Command(BaseCommand): @cached_property def compression_formats(self): """A dict mapping format names to (open function, mode arg) tuples.""" - # Forcing binary mode may be revisited after dropping Python 2 support (see #22399) + # Forcing binary mode may be revisited after dropping Python 2 support + # (see #22399). compression_formats = { None: (open, "rb"), "gz": (gzip.GzipFile, "rb"), diff --git a/django/core/management/commands/makemessages.py b/django/core/management/commands/makemessages.py index af1b43b7c7..1c68fb453e 100644 --- a/django/core/management/commands/makemessages.py +++ b/django/core/management/commands/makemessages.py @@ -203,11 +203,11 @@ def write_pot_file(potfile, msgs): class Command(BaseCommand): help = ( - "Runs over the entire source tree of the current directory and " - "pulls out all strings marked for translation. It creates (or updates) a message " - "file in the conf/locale (in the django tree) or locale (for projects and " - "applications) directory.\n\nYou must run this command with one of either the " - "--locale, --exclude, or --all options." + "Runs over the entire source tree of the current directory and pulls out all " + "strings marked for translation. It creates (or updates) a message file in the " + "conf/locale (in the django tree) or locale (for projects and applications) " + "directory.\n\nYou must run this command with one of either the --locale, " + "--exclude, or --all options." ) translatable_file_class = TranslatableFile @@ -226,8 +226,10 @@ class Command(BaseCommand): "-l", default=[], action="append", - help="Creates or updates the message files for the given locale(s) (e.g. pt_BR). " - "Can be used multiple times.", + help=( + "Creates or updates the message files for the given locale(s) (e.g. " + "pt_BR). Can be used multiple times." + ), ) parser.add_argument( "--exclude", @@ -278,7 +280,10 @@ class Command(BaseCommand): "--no-default-ignore", action="store_false", dest="use_default_ignore_patterns", - help="Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and '*.pyc'.", + help=( + "Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and " + "'*.pyc'." + ), ) parser.add_argument( "--no-wrap", diff --git a/django/core/management/commands/makemigrations.py b/django/core/management/commands/makemigrations.py index 325848d8b2..5afa209136 100644 --- a/django/core/management/commands/makemigrations.py +++ b/django/core/management/commands/makemigrations.py @@ -147,7 +147,8 @@ class Command(BaseCommand): # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() - # If app_labels is specified, filter out conflicting migrations for unspecified apps + # If app_labels is specified, filter out conflicting migrations for + # unspecified apps. if app_labels: conflicts = { app_label: conflict diff --git a/django/core/management/commands/migrate.py b/django/core/management/commands/migrate.py index 59fd1f0d55..d98072c66e 100644 --- a/django/core/management/commands/migrate.py +++ b/django/core/management/commands/migrate.py @@ -47,7 +47,10 @@ class Command(BaseCommand): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, - help='Nominates a database to synchronize. Defaults to the "default" database.', + help=( + 'Nominates a database to synchronize. Defaults to the "default" ' + "database." + ), ) parser.add_argument( "--fake", @@ -57,9 +60,12 @@ class Command(BaseCommand): parser.add_argument( "--fake-initial", action="store_true", - help="Detect if tables already exist and fake-apply initial migrations if so. Make sure " - "that the current database schema matches your initial migration before using this " - "flag. Django will only check for an existing table name.", + help=( + "Detect if tables already exist and fake-apply initial migrations if " + "so. Make sure that the current database schema matches your initial " + "migration before using this flag. Django will only check for an " + "existing table name." + ), ) parser.add_argument( "--plan", @@ -313,7 +319,8 @@ class Command(BaseCommand): if not plan: if self.verbosity >= 1: self.stdout.write(" No migrations to apply.") - # If there's changes that aren't in migrations yet, tell them how to fix it. + # If there's changes that aren't in migrations yet, tell them + # how to fix it. autodetector = MigrationAutodetector( executor.loader.project_state(), ProjectState.from_apps(apps), diff --git a/django/core/management/commands/sendtestemail.py b/django/core/management/commands/sendtestemail.py index 6a69849300..fbb2a7856e 100644 --- a/django/core/management/commands/sendtestemail.py +++ b/django/core/management/commands/sendtestemail.py @@ -7,7 +7,10 @@ from django.utils import timezone class Command(BaseCommand): help = "Sends a test email to the email addresses specified as arguments." - missing_args_message = "You must specify some email recipients, or pass the --managers or --admin options." + missing_args_message = ( + "You must specify some email recipients, or pass the --managers or --admin " + "options." + ) def add_arguments(self, parser): parser.add_argument( diff --git a/django/core/management/commands/shell.py b/django/core/management/commands/shell.py index 52ab27cb21..f55b346406 100644 --- a/django/core/management/commands/shell.py +++ b/django/core/management/commands/shell.py @@ -21,18 +21,27 @@ class Command(BaseCommand): parser.add_argument( "--no-startup", action="store_true", - help="When using plain Python, ignore the PYTHONSTARTUP environment variable and ~/.pythonrc.py script.", + help=( + "When using plain Python, ignore the PYTHONSTARTUP environment " + "variable and ~/.pythonrc.py script." + ), ) parser.add_argument( "-i", "--interface", choices=self.shells, - help='Specify an interactive interpreter interface. Available options: "ipython", "bpython", and "python"', + help=( + "Specify an interactive interpreter interface. Available options: " + '"ipython", "bpython", and "python"' + ), ) parser.add_argument( "-c", "--command", - help="Instead of opening an interactive shell, run a command as Django and exit.", + help=( + "Instead of opening an interactive shell, run a command as Django and " + "exit." + ), ) def ipython(self, options): diff --git a/django/core/management/commands/showmigrations.py b/django/core/management/commands/showmigrations.py index 1f3a64f9b1..203f92151d 100644 --- a/django/core/management/commands/showmigrations.py +++ b/django/core/management/commands/showmigrations.py @@ -45,9 +45,9 @@ class Command(BaseCommand): dest="format", const="plan", help=( - "Shows all migrations in the order they will be applied. " - "With a verbosity level of 2 or above all direct migration dependencies " - "and reverse dependencies (run_before) will be included." + "Shows all migrations in the order they will be applied. With a " + "verbosity level of 2 or above all direct migration dependencies and " + "reverse dependencies (run_before) will be included." ), ) diff --git a/django/core/management/commands/sqlflush.py b/django/core/management/commands/sqlflush.py index e6701349d6..bc82e1f05f 100644 --- a/django/core/management/commands/sqlflush.py +++ b/django/core/management/commands/sqlflush.py @@ -16,7 +16,10 @@ class Command(BaseCommand): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, - help='Nominates a database to print the SQL for. Defaults to the "default" database.', + help=( + 'Nominates a database to print the SQL for. Defaults to the "default" ' + "database." + ), ) def handle(self, **options): diff --git a/django/core/management/commands/sqlmigrate.py b/django/core/management/commands/sqlmigrate.py index 880eb11d9b..2f6993682f 100644 --- a/django/core/management/commands/sqlmigrate.py +++ b/django/core/management/commands/sqlmigrate.py @@ -19,7 +19,10 @@ class Command(BaseCommand): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, - help='Nominates a database to create SQL for. Defaults to the "default" database.', + help=( + 'Nominates a database to create SQL for. Defaults to the "default" ' + "database." + ), ) parser.add_argument( "--backwards", @@ -55,13 +58,13 @@ class Command(BaseCommand): migration = loader.get_migration_by_prefix(app_label, migration_name) except AmbiguityError: raise CommandError( - "More than one migration matches '%s' in app '%s'. Please be more specific." - % (migration_name, app_label) + "More than one migration matches '%s' in app '%s'. Please be more " + "specific." % (migration_name, app_label) ) except KeyError: raise CommandError( - "Cannot find a migration matching '%s' from app '%s'. Is it in INSTALLED_APPS?" - % (migration_name, app_label) + "Cannot find a migration matching '%s' from app '%s'. Is it in " + "INSTALLED_APPS?" % (migration_name, app_label) ) target = (app_label, migration.name) diff --git a/django/core/management/commands/sqlsequencereset.py b/django/core/management/commands/sqlsequencereset.py index 454a2ab10c..9653fa59d0 100644 --- a/django/core/management/commands/sqlsequencereset.py +++ b/django/core/management/commands/sqlsequencereset.py @@ -14,7 +14,10 @@ class Command(AppCommand): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, - help='Nominates a database to print the SQL for. Defaults to the "default" database.', + help=( + 'Nominates a database to print the SQL for. Defaults to the "default" ' + "database." + ), ) def handle_app_config(self, app_config, **options): diff --git a/django/core/management/commands/squashmigrations.py b/django/core/management/commands/squashmigrations.py index 1592e792f8..aafa5e7bcc 100644 --- a/django/core/management/commands/squashmigrations.py +++ b/django/core/management/commands/squashmigrations.py @@ -12,7 +12,10 @@ from django.utils.version import get_docs_version class Command(BaseCommand): - help = "Squashes an existing set of migrations (from first until specified) into a single new one." + help = ( + "Squashes an existing set of migrations (from first until specified) into a " + "single new one." + ) def add_arguments(self, parser): parser.add_argument( @@ -22,7 +25,10 @@ class Command(BaseCommand): parser.add_argument( "start_migration_name", nargs="?", - help="Migrations will be squashed starting from and including this migration.", + help=( + "Migrations will be squashed starting from and including this " + "migration." + ), ) parser.add_argument( "migration_name", @@ -66,7 +72,8 @@ class Command(BaseCommand): apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) - # Load the current graph state, check the app and migration they asked for exists + # Load the current graph state, check the app and migration they asked + # for exists. loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) if app_label not in loader.migrated_apps: raise CommandError( @@ -135,10 +142,9 @@ class Command(BaseCommand): for smigration in migrations_to_squash: if smigration.replaces: raise CommandError( - "You cannot squash squashed migrations! Please transition " - "it to a normal migration first: " - "https://docs.djangoproject.com/en/%s/topics/migrations/#squashing-migrations" - % get_docs_version() + "You cannot squash squashed migrations! Please transition it to a " + "normal migration first: https://docs.djangoproject.com/en/%s/" + "topics/migrations/#squashing-migrations" % get_docs_version() ) operations.extend(smigration.operations) for dependency in smigration.dependencies: @@ -223,15 +229,18 @@ class Command(BaseCommand): + "\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." ) if writer.needs_manual_porting: self.stdout.write( self.style.MIGRATE_HEADING("Manual porting required") + "\n" - " Your migrations contained functions that must be manually copied over,\n" + " Your migrations contained functions that must be manually " + "copied over,\n" " as we could not safely copy their implementation.\n" - " See the comment at the top of the squashed migration for details." + " See the comment at the top of the squashed migration for " + "details." ) def find_migration(self, loader, app_label, name): diff --git a/django/core/management/commands/test.py b/django/core/management/commands/test.py index e5660955cd..2df6dbbecf 100644 --- a/django/core/management/commands/test.py +++ b/django/core/management/commands/test.py @@ -28,7 +28,10 @@ class Command(BaseCommand): "args", metavar="test_label", nargs="*", - help="Module paths to test; can be modulename, modulename.TestCase or modulename.TestCase.test_method", + help=( + "Module paths to test; can be modulename, modulename.TestCase or " + "modulename.TestCase.test_method" + ), ) parser.add_argument( "--noinput", diff --git a/django/core/validators.py b/django/core/validators.py index 5272258a77..605b491ba7 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -174,8 +174,11 @@ class EmailValidator: message = _("Enter a valid email address.") code = "invalid" user_regex = _lazy_re_compile( - r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom - r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string + # dot-atom + r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" + # quoted-string + r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])' + r'*"\Z)', re.IGNORECASE, ) domain_regex = _lazy_re_compile( @@ -257,7 +260,8 @@ slug_unicode_re = _lazy_re_compile(r"^[-\w]+\Z") validate_unicode_slug = RegexValidator( slug_unicode_re, _( - "Enter a valid “slug” consisting of Unicode letters, numbers, underscores, or hyphens." + "Enter a valid “slug” consisting of Unicode letters, numbers, underscores, or " + "hyphens." ), "invalid", ) @@ -400,8 +404,10 @@ class MinValueValidator(BaseValidator): @deconstructible class MinLengthValidator(BaseValidator): message = ngettext_lazy( - "Ensure this value has at least %(limit_value)d character (it has %(show_value)d).", - "Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).", + "Ensure this value has at least %(limit_value)d character (it has " + "%(show_value)d).", + "Ensure this value has at least %(limit_value)d characters (it has " + "%(show_value)d).", "limit_value", ) code = "min_length" @@ -416,8 +422,10 @@ class MinLengthValidator(BaseValidator): @deconstructible class MaxLengthValidator(BaseValidator): message = ngettext_lazy( - "Ensure this value has at most %(limit_value)d character (it has %(show_value)d).", - "Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).", + "Ensure this value has at most %(limit_value)d character (it has " + "%(show_value)d).", + "Ensure this value has at most %(limit_value)d characters (it has " + "%(show_value)d).", "limit_value", ) code = "max_length" @@ -449,8 +457,10 @@ class DecimalValidator: "max", ), "max_whole_digits": ngettext_lazy( - "Ensure that there are no more than %(max)s digit before the decimal point.", - "Ensure that there are no more than %(max)s digits before the decimal point.", + "Ensure that there are no more than %(max)s digit before the decimal " + "point.", + "Ensure that there are no more than %(max)s digits before the decimal " + "point.", "max", ), } diff --git a/django/db/backends/base/base.py b/django/db/backends/base/base.py index 1aee03848b..d2e79c1dd4 100644 --- a/django/db/backends/base/base.py +++ b/django/db/backends/base/base.py @@ -190,19 +190,22 @@ class BaseDatabaseWrapper: def get_connection_params(self): """Return a dict of parameters suitable for get_new_connection.""" raise NotImplementedError( - "subclasses of BaseDatabaseWrapper may require a get_connection_params() method" + "subclasses of BaseDatabaseWrapper may require a get_connection_params() " + "method" ) def get_new_connection(self, conn_params): """Open a connection to the database.""" raise NotImplementedError( - "subclasses of BaseDatabaseWrapper may require a get_new_connection() method" + "subclasses of BaseDatabaseWrapper may require a get_new_connection() " + "method" ) def init_connection_state(self): """Initialize the database connection settings.""" raise NotImplementedError( - "subclasses of BaseDatabaseWrapper may require an init_connection_state() method" + "subclasses of BaseDatabaseWrapper may require an init_connection_state() " + "method" ) def create_cursor(self, name=None): diff --git a/django/db/backends/base/introspection.py b/django/db/backends/base/introspection.py index c8036ef1e9..8bf456225e 100644 --- a/django/db/backends/base/introspection.py +++ b/django/db/backends/base/introspection.py @@ -63,7 +63,8 @@ class BaseDatabaseIntrospection: views that exist in the database. """ raise NotImplementedError( - "subclasses of BaseDatabaseIntrospection may require a get_table_list() method" + "subclasses of BaseDatabaseIntrospection may require a get_table_list() " + "method" ) def get_table_description(self, cursor, table_name): @@ -158,7 +159,8 @@ class BaseDatabaseIntrospection: 'name' key can be added if the backend supports named sequences. """ raise NotImplementedError( - "subclasses of BaseDatabaseIntrospection may require a get_sequences() method" + "subclasses of BaseDatabaseIntrospection may require a get_sequences() " + "method" ) def get_relations(self, cursor, table_name): @@ -200,5 +202,6 @@ class BaseDatabaseIntrospection: if they don't name constraints of a certain type (e.g. SQLite) """ raise NotImplementedError( - "subclasses of BaseDatabaseIntrospection may require a get_constraints() method" + "subclasses of BaseDatabaseIntrospection may require a get_constraints() " + "method" ) diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py index 5201e53af6..4e6a67685f 100644 --- a/django/db/backends/base/operations.py +++ b/django/db/backends/base/operations.py @@ -106,7 +106,8 @@ class BaseDatabaseOperations: extracts a value from the given date field field_name. """ raise NotImplementedError( - "subclasses of BaseDatabaseOperations may require a date_extract_sql() method" + "subclasses of BaseDatabaseOperations may require a date_extract_sql() " + "method" ) def date_trunc_sql(self, lookup_type, field_name, tzname=None): @@ -119,7 +120,8 @@ class BaseDatabaseOperations: timezone. """ raise NotImplementedError( - "subclasses of BaseDatabaseOperations may require a date_trunc_sql() method." + "subclasses of BaseDatabaseOperations may require a date_trunc_sql() " + "method." ) def datetime_cast_date_sql(self, field_name, tzname): @@ -136,7 +138,8 @@ class BaseDatabaseOperations: Return the SQL to cast a datetime value to time value. """ raise NotImplementedError( - "subclasses of BaseDatabaseOperations may require a datetime_cast_time_sql() method" + "subclasses of BaseDatabaseOperations may require a " + "datetime_cast_time_sql() method" ) def datetime_extract_sql(self, lookup_type, field_name, tzname): @@ -146,7 +149,8 @@ class BaseDatabaseOperations: datetime field field_name. """ raise NotImplementedError( - "subclasses of BaseDatabaseOperations may require a datetime_extract_sql() method" + "subclasses of BaseDatabaseOperations may require a datetime_extract_sql() " + "method" ) def datetime_trunc_sql(self, lookup_type, field_name, tzname): @@ -156,7 +160,8 @@ class BaseDatabaseOperations: field_name to a datetime object with only the given specificity. """ raise NotImplementedError( - "subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method" + "subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() " + "method" ) def time_trunc_sql(self, lookup_type, field_name, tzname=None): @@ -727,9 +732,9 @@ class BaseDatabaseOperations: def window_frame_range_start_end(self, start=None, end=None): start_, end_ = self.window_frame_rows_start_end(start, end) - if ( - self.connection.features.only_supports_unbounded_with_preceding_and_following - and ((start and start < 0) or (end and end > 0)) + features = self.connection.features + if features.only_supports_unbounded_with_preceding_and_following and ( + (start and start < 0) or (end and end > 0) ): raise NotSupportedError( "%s only supports UNBOUNDED together with PRECEDING and " diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py index ea98e86b77..9d6952df21 100644 --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -104,7 +104,10 @@ class BaseDatabaseSchemaEditor: sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)" sql_delete_check = sql_delete_constraint - sql_create_unique = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s UNIQUE (%(columns)s)%(deferrable)s" + sql_create_unique = ( + "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s " + "UNIQUE (%(columns)s)%(deferrable)s" + ) sql_delete_unique = sql_delete_constraint sql_create_fk = ( @@ -115,8 +118,14 @@ class BaseDatabaseSchemaEditor: sql_create_column_inline_fk = None sql_delete_fk = sql_delete_constraint - sql_create_index = "CREATE INDEX %(name)s ON %(table)s (%(columns)s)%(include)s%(extra)s%(condition)s" - sql_create_unique_index = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)%(include)s%(condition)s" + sql_create_index = ( + "CREATE INDEX %(name)s ON %(table)s " + "(%(columns)s)%(include)s%(extra)s%(condition)s" + ) + sql_create_unique_index = ( + "CREATE UNIQUE INDEX %(name)s ON %(table)s " + "(%(columns)s)%(include)s%(condition)s" + ) sql_delete_index = "DROP INDEX %(name)s" sql_create_pk = ( @@ -418,10 +427,12 @@ class BaseDatabaseSchemaEditor: the given `model`. """ sql, params = self.table_sql(model) - # Prevent using [] as params, in the case a literal '%' is used in the definition + # Prevent using [] as params, in the case a literal '%' is used in the + # definition. self.execute(sql, params or None) - # Add any field index and index_together's (deferred as SQLite _remake_table needs it) + # Add any field index and index_together's (deferred as SQLite + # _remake_table needs it). self.deferred_sql.extend(self._model_indexes_sql(model)) # Make M2M tables @@ -1190,8 +1201,9 @@ class BaseDatabaseSchemaEditor: # Repoint the FK to the other side self.alter_field( new_field.remote_field.through, - # We need the field that points to the target model, so we can tell alter_field to change it - - # this is m2m_reverse_field_name() (as opposed to m2m_field_name, which points to our model) + # The field that points to the target model is needed, so we can + # tell alter_field to change it - this is m2m_reverse_field_name() + # (as opposed to m2m_field_name(), which points to our model). old_field.remote_field.through._meta.get_field( old_field.m2m_reverse_field_name() ), diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py index b689040f7f..1c20554b4d 100644 --- a/django/db/backends/mysql/base.py +++ b/django/db/backends/mysql/base.py @@ -349,9 +349,9 @@ class DatabaseWrapper(BaseDatabaseWrapper): ) for bad_row in cursor.fetchall(): raise IntegrityError( - "The row in table '%s' with primary key '%s' has an invalid " - "foreign key: %s.%s contains a value '%s' that does not " - "have a corresponding value in %s.%s." + "The row in table '%s' with primary key '%s' has an " + "invalid foreign key: %s.%s contains a value '%s' that " + "does not have a corresponding value in %s.%s." % ( table_name, bad_row[0], diff --git a/django/db/backends/mysql/features.py b/django/db/backends/mysql/features.py index d485d40d60..e27e766e48 100644 --- a/django/db/backends/mysql/features.py +++ b/django/db/backends/mysql/features.py @@ -69,8 +69,10 @@ class DatabaseFeatures(BaseDatabaseFeatures): def django_test_skips(self): skips = { "This doesn't work on MySQL.": { - "db_functions.comparison.test_greatest.GreatestTests.test_coalesce_workaround", - "db_functions.comparison.test_least.LeastTests.test_coalesce_workaround", + "db_functions.comparison.test_greatest.GreatestTests." + "test_coalesce_workaround", + "db_functions.comparison.test_least.LeastTests." + "test_coalesce_workaround", }, "Running on MySQL requires utf8mb4 encoding (#18392).": { "model_fields.test_textfield.TextFieldTests.test_emoji", @@ -90,8 +92,10 @@ class DatabaseFeatures(BaseDatabaseFeatures): { "GROUP BY optimization does not work properly when " "ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #31331.": { - "aggregation.tests.AggregateTestCase.test_aggregation_subquery_annotation_multivalued", - "annotations.tests.NonAggregateAnnotationTestCase.test_annotation_aggregate_with_m2o", + "aggregation.tests.AggregateTestCase." + "test_aggregation_subquery_annotation_multivalued", + "annotations.tests.NonAggregateAnnotationTestCase." + "test_annotation_aggregate_with_m2o", }, } ) @@ -100,13 +104,19 @@ class DatabaseFeatures(BaseDatabaseFeatures): ): skips.update( { - "Casting to datetime/time is not supported by MySQL < 8.0. (#30224)": { - "aggregation.tests.AggregateTestCase.test_aggregation_default_using_time_from_python", - "aggregation.tests.AggregateTestCase.test_aggregation_default_using_datetime_from_python", + "Casting to datetime/time is not supported by MySQL < 8.0. " + "(#30224)": { + "aggregation.tests.AggregateTestCase." + "test_aggregation_default_using_time_from_python", + "aggregation.tests.AggregateTestCase." + "test_aggregation_default_using_datetime_from_python", }, - "MySQL < 8.0 returns string type instead of datetime/time. (#30224)": { - "aggregation.tests.AggregateTestCase.test_aggregation_default_using_time_from_database", - "aggregation.tests.AggregateTestCase.test_aggregation_default_using_datetime_from_database", + "MySQL < 8.0 returns string type instead of datetime/time. " + "(#30224)": { + "aggregation.tests.AggregateTestCase." + "test_aggregation_default_using_time_from_database", + "aggregation.tests.AggregateTestCase." + "test_aggregation_default_using_datetime_from_database", }, } ) @@ -118,7 +128,8 @@ class DatabaseFeatures(BaseDatabaseFeatures): skips.update( { "https://jira.mariadb.org/browse/MDEV-19598": { - "schema.tests.SchemaTests.test_alter_not_unique_field_to_primary_key", + "schema.tests.SchemaTests." + "test_alter_not_unique_field_to_primary_key", }, } ) @@ -130,7 +141,8 @@ class DatabaseFeatures(BaseDatabaseFeatures): skips.update( { "https://jira.mariadb.org/browse/MDEV-22775": { - "schema.tests.SchemaTests.test_alter_pk_with_self_referential_field", + "schema.tests.SchemaTests." + "test_alter_pk_with_self_referential_field", }, } ) diff --git a/django/db/backends/mysql/introspection.py b/django/db/backends/mysql/introspection.py index 3cf56dffce..9f57cd599a 100644 --- a/django/db/backends/mysql/introspection.py +++ b/django/db/backends/mysql/introspection.py @@ -92,7 +92,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): FROM information_schema.check_constraints AS c WHERE c.table_name = %s AND - LOWER(c.check_clause) = 'json_valid(`' + LOWER(c.constraint_name) + '`)' AND + LOWER(c.check_clause) = + 'json_valid(`' + LOWER(c.constraint_name) + '`)' AND c.constraint_schema = DATABASE() """, [table_name], diff --git a/django/db/backends/mysql/operations.py b/django/db/backends/mysql/operations.py index 5bcc03a67b..823090b9d1 100644 --- a/django/db/backends/mysql/operations.py +++ b/django/db/backends/mysql/operations.py @@ -69,7 +69,8 @@ class DatabaseOperations(BaseDatabaseOperations): return "CAST(DATE_FORMAT(%s, '%s') AS DATE)" % (field_name, format_str) elif lookup_type == "quarter": return ( - "MAKEDATE(YEAR(%s), 1) + INTERVAL QUARTER(%s) QUARTER - INTERVAL 1 QUARTER" + "MAKEDATE(YEAR(%s), 1) + " + "INTERVAL QUARTER(%s) QUARTER - INTERVAL 1 QUARTER" % (field_name, field_name) ) elif lookup_type == "week": @@ -266,7 +267,8 @@ class DatabaseOperations(BaseDatabaseOperations): value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( - "MySQL backend does not support timezone-aware datetimes when USE_TZ is False." + "MySQL backend does not support timezone-aware datetimes when " + "USE_TZ is False." ) return str(value) @@ -347,7 +349,10 @@ class DatabaseOperations(BaseDatabaseOperations): if self.connection.mysql_is_mariadb: # MariaDB includes the microsecond component in TIME_TO_SEC as # a decimal. MySQL returns an integer without microseconds. - return "CAST((TIME_TO_SEC(%(lhs)s) - TIME_TO_SEC(%(rhs)s)) * 1000000 AS SIGNED)" % { + return ( + "CAST((TIME_TO_SEC(%(lhs)s) - TIME_TO_SEC(%(rhs)s)) " + "* 1000000 AS SIGNED)" + ) % { "lhs": lhs_sql, "rhs": rhs_sql, }, ( diff --git a/django/db/backends/mysql/validation.py b/django/db/backends/mysql/validation.py index 5d61b4865a..fdc3809c12 100644 --- a/django/db/backends/mysql/validation.py +++ b/django/db/backends/mysql/validation.py @@ -22,7 +22,8 @@ class DatabaseValidation(BaseDatabaseValidation): "%s, such as data truncation upon insertion, by " "escalating warnings into errors. It is strongly " "recommended you activate it. See: " - "https://docs.djangoproject.com/en/%s/ref/databases/#mysql-sql-mode" + "https://docs.djangoproject.com/en/%s/ref/databases/" + "#mysql-sql-mode" % ( self.connection.display_name, self.connection.display_name, diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index b13c5f8bb2..7cbee768ea 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -158,16 +158,31 @@ class DatabaseWrapper(BaseDatabaseWrapper): _standard_operators = { "exact": "= %s", "iexact": "= UPPER(%s)", - "contains": "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", - "icontains": "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", + "contains": ( + "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)" + ), + "icontains": ( + "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) " + "ESCAPE TRANSLATE('\\' USING NCHAR_CS)" + ), "gt": "> %s", "gte": ">= %s", "lt": "< %s", "lte": "<= %s", - "startswith": "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", - "endswith": "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", - "istartswith": "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", - "iendswith": "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) ESCAPE TRANSLATE('\\' USING NCHAR_CS)", + "startswith": ( + "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)" + ), + "endswith": ( + "LIKE TRANSLATE(%s USING NCHAR_CS) ESCAPE TRANSLATE('\\' USING NCHAR_CS)" + ), + "istartswith": ( + "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) " + "ESCAPE TRANSLATE('\\' USING NCHAR_CS)" + ), + "iendswith": ( + "LIKE UPPER(TRANSLATE(%s USING NCHAR_CS)) " + "ESCAPE TRANSLATE('\\' USING NCHAR_CS)" + ), } _likec_operators = { diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py index bdde162aa8..df773bff8c 100644 --- a/django/db/backends/oracle/creation.py +++ b/django/db/backends/oracle/creation.py @@ -61,7 +61,8 @@ class DatabaseCreation(BaseDatabaseCreation): cursor, parameters, verbosity, autoclobber ) else: - # Ran into a database error that isn't about leftover objects in the tablespace + # Ran into a database error that isn't about + # leftover objects in the tablespace. self.log( "Got an error destroying the old test database: %s" % e @@ -117,7 +118,8 @@ class DatabaseCreation(BaseDatabaseCreation): else: self.log("Tests cancelled.") sys.exit(1) - self._maindb_connection.close() # done with main user -- test user and tablespaces created + # Done with main user -- test user and tablespaces created. + self._maindb_connection.close() self._switch_to_test_user(parameters) return self.connection.settings_dict["NAME"] @@ -160,8 +162,8 @@ class DatabaseCreation(BaseDatabaseCreation): # There are objects in the test tablespace which prevent dropping it # The easy fix is to drop the test user -- but are we allowed to do so? self.log( - "There are objects in the old test database which prevent its destruction.\n" - "If they belong to the test user, deleting the user will allow the test " + "There are objects in the old test database which prevent its destruction." + "\nIf they belong to the test user, deleting the user will allow the test " "database to be recreated.\n" "Otherwise, you will need to find and remove each of these objects, " "or use a different tablespace.\n" @@ -301,8 +303,10 @@ class DatabaseCreation(BaseDatabaseCreation): if verbosity >= 2: self.log("_execute_test_db_destruction(): dbname=%s" % parameters["user"]) statements = [ - "DROP TABLESPACE %(tblspace)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS", - "DROP TABLESPACE %(tblspace_temp)s INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS", + "DROP TABLESPACE %(tblspace)s " + "INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS", + "DROP TABLESPACE %(tblspace_temp)s " + "INCLUDING CONTENTS AND DATAFILES CASCADE CONSTRAINTS", ] self._execute_statements(cursor, statements, parameters, verbosity) diff --git a/django/db/backends/oracle/features.py b/django/db/backends/oracle/features.py index 6a3c9dab79..257c3e1b87 100644 --- a/django/db/backends/oracle/features.py +++ b/django/db/backends/oracle/features.py @@ -31,7 +31,8 @@ class DatabaseFeatures(BaseDatabaseFeatures): requires_literal_defaults = True closed_cursor_error_class = InterfaceError bare_select_suffix = " FROM DUAL" - # select for update with limit can be achieved on Oracle, but not with the current backend. + # Select for update with limit can be achieved on Oracle, but not with the + # current backend. supports_select_for_update_with_limit = False supports_temporal_subtraction = True # Oracle doesn't ignore quoted identifiers case but the current backend @@ -79,13 +80,16 @@ class DatabaseFeatures(BaseDatabaseFeatures): }, "Oracle doesn't correctly calculate ISO 8601 week numbering before " "1583 (the Gregorian calendar was introduced in 1582).": { - "db_functions.datetime.test_extract_trunc.DateFunctionTests.test_trunc_week_before_1000", - "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests.test_trunc_week_before_1000", + "db_functions.datetime.test_extract_trunc.DateFunctionTests." + "test_trunc_week_before_1000", + "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests." + "test_trunc_week_before_1000", }, "Oracle doesn't support bitwise XOR.": { "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor", "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor_null", - "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor_right_null", + "expressions.tests.ExpressionOperatorTests." + "test_lefthand_bitwise_xor_right_null", }, "Oracle requires ORDER BY in row_number, ANSI:SQL doesn't.": { "expressions_window.tests.WindowFunctionTests.test_row_number_no_ordering", @@ -97,7 +101,8 @@ class DatabaseFeatures(BaseDatabaseFeatures): django_test_expected_failures = { # A bug in Django/cx_Oracle with respect to string handling (#23843). "annotations.tests.NonAggregateAnnotationTestCase.test_custom_functions", - "annotations.tests.NonAggregateAnnotationTestCase.test_custom_functions_can_ref_other_functions", + "annotations.tests.NonAggregateAnnotationTestCase." + "test_custom_functions_can_ref_other_functions", } @cached_property diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py index 17ffd3a99d..0fba9a21ed 100644 --- a/django/db/backends/oracle/introspection.py +++ b/django/db/backends/oracle/introspection.py @@ -147,7 +147,14 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): is_autofield, is_json, ) - for column, default, collation, internal_size, is_autofield, is_json in cursor.fetchall() + for ( + column, + default, + collation, + internal_size, + is_autofield, + is_json, + ) in cursor.fetchall() } self.cache_bust_counter += 1 cursor.execute( @@ -271,7 +278,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): """ SELECT user_constraints.constraint_name, - LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), + LISTAGG(LOWER(cols.column_name), ',') + WITHIN GROUP (ORDER BY cols.position), CASE user_constraints.constraint_type WHEN 'P' THEN 1 ELSE 0 @@ -287,7 +295,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): FROM user_constraints LEFT OUTER JOIN - user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name + user_cons_columns cols + ON user_constraints.constraint_name = cols.constraint_name WHERE user_constraints.constraint_type = ANY('P', 'U', 'C') AND user_constraints.table_name = UPPER(%s) @@ -310,15 +319,18 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): """ SELECT cons.constraint_name, - LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), + LISTAGG(LOWER(cols.column_name), ',') + WITHIN GROUP (ORDER BY cols.position), LOWER(rcols.table_name), LOWER(rcols.column_name) FROM user_constraints cons INNER JOIN - user_cons_columns rcols ON rcols.constraint_name = cons.r_constraint_name AND rcols.position = 1 + user_cons_columns rcols + ON rcols.constraint_name = cons.r_constraint_name AND rcols.position = 1 LEFT OUTER JOIN - user_cons_columns cols ON cons.constraint_name = cols.constraint_name + user_cons_columns cols + ON cons.constraint_name = cols.constraint_name WHERE cons.constraint_type = 'R' AND cons.table_name = UPPER(%s) @@ -343,7 +355,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): ind.index_name, LOWER(ind.index_type), LOWER(ind.uniqueness), - LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.column_position), + LISTAGG(LOWER(cols.column_name), ',') + WITHIN GROUP (ORDER BY cols.column_position), LISTAGG(cols.descend, ',') WITHIN GROUP (ORDER BY cols.column_position) FROM user_ind_columns cols, user_indexes ind diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py index 63f9714333..ddad567a24 100644 --- a/django/db/backends/oracle/operations.py +++ b/django/db/backends/oracle/operations.py @@ -399,12 +399,15 @@ END; user_tables JOIN user_constraints cons - ON (user_tables.table_name = cons.table_name AND cons.constraint_type = ANY('P', 'U')) + ON (user_tables.table_name = cons.table_name + AND cons.constraint_type = ANY('P', 'U')) LEFT JOIN user_constraints rcons - ON (user_tables.table_name = rcons.table_name AND rcons.constraint_type = 'R') + ON (user_tables.table_name = rcons.table_name + AND rcons.constraint_type = 'R') START WITH user_tables.table_name = UPPER(%s) - CONNECT BY NOCYCLE PRIOR cons.constraint_name = rcons.r_constraint_name + CONNECT BY + NOCYCLE PRIOR cons.constraint_name = rcons.r_constraint_name GROUP BY user_tables.table_name, rcons.constraint_name HAVING user_tables.table_name != UPPER(%s) @@ -583,7 +586,8 @@ END; value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( - "Oracle backend does not support timezone-aware datetimes when USE_TZ is False." + "Oracle backend does not support timezone-aware datetimes when " + "USE_TZ is False." ) return Oracle_datetime.from_datetime(value) diff --git a/django/db/backends/oracle/schema.py b/django/db/backends/oracle/schema.py index 2b1027d6b5..7d4edcbd32 100644 --- a/django/db/backends/oracle/schema.py +++ b/django/db/backends/oracle/schema.py @@ -132,10 +132,8 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): new_value = "TO_TIMESTAMP(%s, 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value elif new_internal_type == "TimeField": # TimeField are stored as TIMESTAMP with a 1900-01-01 date part. - new_value = ( - "TO_TIMESTAMP(CONCAT('1900-01-01 ', %s), 'YYYY-MM-DD HH24:MI:SS.FF')" - % new_value - ) + new_value = "CONCAT('1900-01-01 ', %s)" % new_value + new_value = "TO_TIMESTAMP(%s, 'YYYY-MM-DD HH24:MI:SS.FF')" % new_value # Transfer values across self.execute( "UPDATE %s set %s=%s" diff --git a/django/db/backends/postgresql/features.py b/django/db/backends/postgresql/features.py index 182c230c75..7c5d09d193 100644 --- a/django/db/backends/postgresql/features.py +++ b/django/db/backends/postgresql/features.py @@ -67,7 +67,8 @@ class DatabaseFeatures(BaseDatabaseFeatures): django_test_skips = { "opclasses are PostgreSQL only.": { - "indexes.tests.SchemaIndexesNotPostgreSQLTests.test_create_index_ignores_opclasses", + "indexes.tests.SchemaIndexesNotPostgreSQLTests." + "test_create_index_ignores_opclasses", }, } diff --git a/django/db/backends/postgresql/introspection.py b/django/db/backends/postgresql/introspection.py index a7e9a13d61..16d80663aa 100644 --- a/django/db/backends/postgresql/introspection.py +++ b/django/db/backends/postgresql/introspection.py @@ -50,8 +50,13 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): """Return a list of table and view names in the current database.""" cursor.execute( """ - SELECT c.relname, - CASE WHEN c.relispartition THEN 'p' WHEN c.relkind IN ('m', 'v') THEN 'v' ELSE 't' END + SELECT + c.relname, + CASE + WHEN c.relispartition THEN 'p' + WHEN c.relkind IN ('m', 'v') THEN 'v' + ELSE 't' + END FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind IN ('f', 'm', 'p', 'r', 'v') @@ -116,9 +121,15 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): SELECT s.relname as sequence_name, col.attname FROM pg_class s JOIN pg_namespace sn ON sn.oid = s.relnamespace - JOIN pg_depend d ON d.refobjid = s.oid AND d.refclassid = 'pg_class'::regclass - JOIN pg_attrdef ad ON ad.oid = d.objid AND d.classid = 'pg_attrdef'::regclass - JOIN pg_attribute col ON col.attrelid = ad.adrelid AND col.attnum = ad.adnum + JOIN + pg_depend d ON d.refobjid = s.oid + AND d.refclassid = 'pg_class'::regclass + JOIN + pg_attrdef ad ON ad.oid = d.objid + AND d.classid = 'pg_attrdef'::regclass + JOIN + pg_attribute col ON col.attrelid = ad.adrelid + AND col.attnum = ad.adnum JOIN pg_class tbl ON tbl.oid = ad.adrelid WHERE s.relkind = 'S' AND d.deptype in ('a', 'n') @@ -143,8 +154,10 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): FROM pg_constraint con LEFT JOIN pg_class c1 ON con.conrelid = c1.oid LEFT JOIN pg_class c2 ON con.confrelid = c2.oid - LEFT JOIN pg_attribute a1 ON c1.oid = a1.attrelid AND a1.attnum = con.conkey[1] - LEFT JOIN pg_attribute a2 ON c2.oid = a2.attrelid AND a2.attnum = con.confkey[1] + LEFT JOIN + pg_attribute a1 ON c1.oid = a1.attrelid AND a1.attnum = con.conkey[1] + LEFT JOIN + pg_attribute a2 ON c2.oid = a2.attrelid AND a2.attnum = con.confkey[1] WHERE c1.relname = %s AND con.contype = 'f' AND @@ -203,8 +216,14 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): cursor.execute( """ SELECT - indexname, array_agg(attname ORDER BY arridx), indisunique, indisprimary, - array_agg(ordering ORDER BY arridx), amname, exprdef, s2.attoptions + indexname, + array_agg(attname ORDER BY arridx), + indisunique, + indisprimary, + array_agg(ordering ORDER BY arridx), + amname, + exprdef, + s2.attoptions FROM ( SELECT c2.relname as indexname, idx.*, attr.attname, am.amname, @@ -221,12 +240,16 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): c2.reloptions as attoptions FROM ( SELECT * - FROM pg_index i, unnest(i.indkey, i.indoption) WITH ORDINALITY koi(key, option, arridx) + FROM + pg_index i, + unnest(i.indkey, i.indoption) + WITH ORDINALITY koi(key, option, arridx) ) idx LEFT JOIN pg_class c ON idx.indrelid = c.oid LEFT JOIN pg_class c2 ON idx.indexrelid = c2.oid LEFT JOIN pg_am am ON c2.relam = am.oid - LEFT JOIN pg_attribute attr ON attr.attrelid = c.oid AND attr.attnum = idx.key + LEFT JOIN + pg_attribute attr ON attr.attrelid = c.oid AND attr.attnum = idx.key WHERE c.relname = %s AND pg_catalog.pg_table_is_visible(c.oid) ) s2 GROUP BY indexname, indisunique, indisprimary, amname, exprdef, attoptions; diff --git a/django/db/backends/postgresql/operations.py b/django/db/backends/postgresql/operations.py index 68448157ec..49a61d148a 100644 --- a/django/db/backends/postgresql/operations.py +++ b/django/db/backends/postgresql/operations.py @@ -187,11 +187,12 @@ class DatabaseOperations(BaseDatabaseOperations): output = [] qn = self.quote_name for model in model_list: - # Use `coalesce` to set the sequence for each model to the max pk value if there are records, - # or 1 if there are none. Set the `is_called` property (the third argument to `setval`) to true - # if there are records (as the max pk value is already in use), otherwise set it to false. - # Use pg_get_serial_sequence to get the underlying sequence name from the table name - # and column name (available since PostgreSQL 8) + # Use `coalesce` to set the sequence for each model to the max pk + # value if there are records, or 1 if there are none. Set the + # `is_called` property (the third argument to `setval`) to true if + # there are records (as the max pk value is already in use), + # otherwise set it to false. Use pg_get_serial_sequence to get the + # underlying sequence name from the table name and column name. for f in model._meta.local_fields: if isinstance(f, models.AutoField): @@ -209,7 +210,9 @@ class DatabaseOperations(BaseDatabaseOperations): style.SQL_TABLE(qn(model._meta.db_table)), ) ) - break # Only one AutoField is allowed per model, so don't bother continuing. + # Only one AutoField is allowed per model, so don't bother + # continuing. + break return output def prep_for_iexact_query(self, x): diff --git a/django/db/backends/postgresql/schema.py b/django/db/backends/postgresql/schema.py index 47e9a6a8f3..73e2749020 100644 --- a/django/db/backends/postgresql/schema.py +++ b/django/db/backends/postgresql/schema.py @@ -33,8 +33,10 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): ) # Setting the constraint to IMMEDIATE runs any deferred checks to allow # dropping it in the same transaction. - sql_delete_fk = "SET CONSTRAINTS %(name)s IMMEDIATE; ALTER TABLE %(table)s DROP CONSTRAINT %(name)s" - + sql_delete_fk = ( + "SET CONSTRAINTS %(name)s IMMEDIATE; " + "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s" + ) sql_delete_procedure = "DROP FUNCTION %(procedure)s(%(param_types)s)" def quote_value(self, value): diff --git a/django/db/backends/sqlite3/_functions.py b/django/db/backends/sqlite3/_functions.py index 86684c1907..f16d926100 100644 --- a/django/db/backends/sqlite3/_functions.py +++ b/django/db/backends/sqlite3/_functions.py @@ -209,9 +209,15 @@ def _sqlite_datetime_trunc(lookup_type, dt, tzname, conn_tzname): elif lookup_type == "hour": return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} {dt.hour:02d}:00:00" elif lookup_type == "minute": - return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} {dt.hour:02d}:{dt.minute:02d}:00" + return ( + f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} " + f"{dt.hour:02d}:{dt.minute:02d}:00" + ) elif lookup_type == "second": - return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} {dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}" + return ( + f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} " + f"{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}" + ) raise ValueError(f"Unsupported lookup type: {lookup_type!r}") diff --git a/django/db/backends/sqlite3/features.py b/django/db/backends/sqlite3/features.py index c076f0121e..d0c9dc5391 100644 --- a/django/db/backends/sqlite3/features.py +++ b/django/db/backends/sqlite3/features.py @@ -57,26 +57,34 @@ class DatabaseFeatures(BaseDatabaseFeatures): def django_test_skips(self): skips = { "SQLite stores values rounded to 15 significant digits.": { - "model_fields.test_decimalfield.DecimalFieldTests.test_fetch_from_db_without_float_rounding", + "model_fields.test_decimalfield.DecimalFieldTests." + "test_fetch_from_db_without_float_rounding", }, "SQLite naively remakes the table on field alteration.": { "schema.tests.SchemaTests.test_unique_no_unnecessary_fk_drops", "schema.tests.SchemaTests.test_unique_and_reverse_m2m", - "schema.tests.SchemaTests.test_alter_field_default_doesnt_perform_queries", - "schema.tests.SchemaTests.test_rename_column_renames_deferred_sql_references", + "schema.tests.SchemaTests." + "test_alter_field_default_doesnt_perform_queries", + "schema.tests.SchemaTests." + "test_rename_column_renames_deferred_sql_references", }, "SQLite doesn't support negative precision for ROUND().": { - "db_functions.math.test_round.RoundTests.test_null_with_negative_precision", - "db_functions.math.test_round.RoundTests.test_decimal_with_negative_precision", - "db_functions.math.test_round.RoundTests.test_float_with_negative_precision", - "db_functions.math.test_round.RoundTests.test_integer_with_negative_precision", + "db_functions.math.test_round.RoundTests." + "test_null_with_negative_precision", + "db_functions.math.test_round.RoundTests." + "test_decimal_with_negative_precision", + "db_functions.math.test_round.RoundTests." + "test_float_with_negative_precision", + "db_functions.math.test_round.RoundTests." + "test_integer_with_negative_precision", }, } if Database.sqlite_version_info < (3, 27): skips.update( { "Nondeterministic failure on SQLite < 3.27.": { - "expressions_window.tests.WindowFunctionTests.test_subquery_row_range_rank", + "expressions_window.tests.WindowFunctionTests." + "test_subquery_row_range_rank", }, } ) @@ -85,8 +93,10 @@ class DatabaseFeatures(BaseDatabaseFeatures): { "the sqlite backend's close() method is a no-op when using an " "in-memory database": { - "servers.test_liveserverthread.LiveServerThreadTest.test_closes_connections", - "servers.tests.LiveServerTestCloseConnectionTest.test_closes_connections", + "servers.test_liveserverthread.LiveServerThreadTest." + "test_closes_connections", + "servers.tests.LiveServerTestCloseConnectionTest." + "test_closes_connections", }, } ) diff --git a/django/db/backends/sqlite3/introspection.py b/django/db/backends/sqlite3/introspection.py index f5a5e81e9d..a74153757b 100644 --- a/django/db/backends/sqlite3/introspection.py +++ b/django/db/backends/sqlite3/introspection.py @@ -146,7 +146,14 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): ) return { column_name: (ref_column_name, ref_table_name) - for _, _, ref_table_name, column_name, ref_column_name, *_ in cursor.fetchall() + for ( + _, + _, + ref_table_name, + column_name, + ref_column_name, + *_, + ) in cursor.fetchall() } def get_primary_key_column(self, cursor, table_name): diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py index ef8b91c0f0..7c7cfce1ba 100644 --- a/django/db/backends/sqlite3/operations.py +++ b/django/db/backends/sqlite3/operations.py @@ -168,7 +168,9 @@ class DatabaseOperations(BaseDatabaseOperations): def last_executed_query(self, cursor, sql, params): # Python substitutes parameters in Modules/_sqlite/cursor.c with: - # pysqlite_statement_bind_parameters(self->statement, parameters, allow_8bit_chars); + # pysqlite_statement_bind_parameters( + # self->statement, parameters, allow_8bit_chars + # ); # Unfortunately there is no way to reach self->statement from Python, # so we quote and substitute parameters manually. if params: @@ -271,7 +273,8 @@ class DatabaseOperations(BaseDatabaseOperations): value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( - "SQLite backend does not support timezone-aware datetimes when USE_TZ is False." + "SQLite backend does not support timezone-aware datetimes when " + "USE_TZ is False." ) return str(value) diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py index c9af8088e5..18449026bd 100644 --- a/django/db/backends/sqlite3/schema.py +++ b/django/db/backends/sqlite3/schema.py @@ -468,12 +468,15 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): old_field.remote_field.through._meta.db_table == new_field.remote_field.through._meta.db_table ): - # The field name didn't change, but some options did; we have to propagate this altering. + # The field name didn't change, but some options did, so we have to + # propagate this altering. self._remake_table( old_field.remote_field.through, alter_field=( - # We need the field that points to the target model, so we can tell alter_field to change it - - # this is m2m_reverse_field_name() (as opposed to m2m_field_name, which points to our model) + # The field that points to the target model is needed, so + # we can tell alter_field to change it - this is + # m2m_reverse_field_name() (as opposed to m2m_field_name(), + # which points to our model). old_field.remote_field.through._meta.get_field( old_field.m2m_reverse_field_name() ), diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py index f8140f1845..04e651ec4a 100644 --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -310,12 +310,17 @@ class MigrationAutodetector: (dep[0], self.migrations[dep[0]][-1].name) ) else: - # If we can't find the other app, we add a first/last dependency, - # but only if we've already been through once and checked everything + # If we can't find the other app, we add a + # first/last dependency, but only if we've + # already been through once and checked + # everything. if chop_mode: - # If the app already exists, we add a dependency on the last migration, - # as we don't know which migration contains the target field. - # If it's not yet migrated or has no migrations, we use __first__ + # If the app already exists, we add a + # dependency on the last migration, as + # we don't know which migration + # contains the target field. If it's + # not yet migrated or has no + # migrations, we use __first__. if graph and graph.leaf_nodes(dep[0]): operation_dependencies.add( graph.leaf_nodes(dep[0])[0] @@ -469,7 +474,8 @@ class MigrationAutodetector: raise ValueError("Can't handle dependency %r" % (dependency,)) def add_operation(self, app_label, operation, dependencies=None, beginning=False): - # Dependencies are (app_label, model_name, field_name, create/delete as True/False) + # Dependencies are + # (app_label, model_name, field_name, create/delete as True/False) operation._auto_deps = dependencies or [] if beginning: self.generated_operations.setdefault(app_label, []).insert(0, operation) diff --git a/django/db/migrations/executor.py b/django/db/migrations/executor.py index ef7f9060f1..eb738cf457 100644 --- a/django/db/migrations/executor.py +++ b/django/db/migrations/executor.py @@ -405,6 +405,6 @@ class MigrationExecutor: break else: return False, project_state - # If we get this far and we found at least one CreateModel or AddField migration, - # the migration is considered implicitly applied. + # If we get this far and we found at least one CreateModel or AddField + # migration, the migration is considered implicitly applied. return (found_create_model_migration or found_add_field_migration), after_state diff --git a/django/db/migrations/migration.py b/django/db/migrations/migration.py index 39278d4cc7..ccbd2f72e4 100644 --- a/django/db/migrations/migration.py +++ b/django/db/migrations/migration.py @@ -12,7 +12,8 @@ class Migration: and subclass it as a class called Migration. It will have one or more of the following attributes: - - operations: A list of Operation instances, probably from django.db.migrations.operations + - operations: A list of Operation instances, probably from + django.db.migrations.operations - dependencies: A list of tuples of (app_path, migration_name) - run_before: A list of tuples of (app_path, migration_name) - replaces: A list of migration_names @@ -104,7 +105,8 @@ class Migration: schema_editor.collected_sql.append("--") if not operation.reduces_to_sql: schema_editor.collected_sql.append( - "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:" + "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS " + "SQL:" ) schema_editor.collected_sql.append("-- %s" % operation.describe()) schema_editor.collected_sql.append("--") @@ -167,7 +169,8 @@ class Migration: schema_editor.collected_sql.append("--") if not operation.reduces_to_sql: schema_editor.collected_sql.append( - "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS SQL:" + "-- MIGRATION NOW PERFORMS OPERATION THAT CANNOT BE WRITTEN AS " + "SQL:" ) schema_editor.collected_sql.append("-- %s" % operation.describe()) schema_editor.collected_sql.append("--") diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index 0c9416ae45..7d7a9174f0 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -645,10 +645,12 @@ class StateApps(Apps): new_unrendered_models.append(model) if len(new_unrendered_models) == len(unrendered_models): raise InvalidBasesError( - "Cannot resolve bases for %r\nThis can happen if you are inheriting models from an " - "app with migrations (e.g. contrib.auth)\n in an app with no migrations; see " - "https://docs.djangoproject.com/en/%s/topics/migrations/#dependencies " - "for more" % (new_unrendered_models, get_docs_version()) + "Cannot resolve bases for %r\nThis can happen if you are " + "inheriting models from an app with migrations (e.g. " + "contrib.auth)\n in an app with no migrations; see " + "https://docs.djangoproject.com/en/%s/topics/migrations/" + "#dependencies for more" + % (new_unrendered_models, get_docs_version()) ) unrendered_models = new_unrendered_models @@ -717,8 +719,8 @@ class ModelState: ) if field.many_to_many and hasattr(field.remote_field.through, "_meta"): raise ValueError( - 'ModelState.fields cannot refer to a model class - "%s.through" does. ' - "Use a string reference instead." % name + 'ModelState.fields cannot refer to a model class - "%s.through" ' + "does. Use a string reference instead." % name ) # Sanity-check that indexes have their name set. for index in self.options["indexes"]: diff --git a/django/db/models/base.py b/django/db/models/base.py index 8127a9895a..cf3f25319d 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -215,8 +215,8 @@ class ModelBase(type): base = parent elif parent._meta.concrete_model is not base._meta.concrete_model: raise TypeError( - "Proxy model '%s' has more than one non-abstract model base class." - % name + "Proxy model '%s' has more than one non-abstract model base " + "class." % name ) if base is None: raise TypeError( @@ -1973,8 +1973,8 @@ class Model(metaclass=ModelBase): elif field not in cls._meta.local_fields: errors.append( checks.Error( - "'%s' refers to field '%s' which is not local to model '%s'." - % (option, field_name, cls._meta.object_name), + "'%s' refers to field '%s' which is not local to model " + "'%s'." % (option, field_name, cls._meta.object_name), hint="This issue may be caused by multi-table inheritance.", obj=cls, id="models.E016", @@ -2003,7 +2003,8 @@ class Model(metaclass=ModelBase): if not isinstance(cls._meta.ordering, (list, tuple)): return [ checks.Error( - "'ordering' must be a tuple or list (even if you want to order by only one field).", + "'ordering' must be a tuple or list (even if you want to order by " + "only one field).", obj=cls, id="models.E014", ) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 313e31b5f5..0afc2a0c92 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -1834,7 +1834,8 @@ class FilePathField(Field): if not self.allow_files and not self.allow_folders: return [ checks.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=self, id="fields.E140", ) diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py index 33a1176ed6..1a3a0ce5fc 100644 --- a/django/db/models/fields/files.py +++ b/django/db/models/fields/files.py @@ -303,7 +303,8 @@ class FileField(Field): def get_prep_value(self, value): value = super().get_prep_value(value) - # Need to convert File objects provided via a form to string for database insertion + # Need to convert File objects provided via a form to string for + # database insertion. if value is None: return None return str(value) diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index 1cf447c6d4..18c6c4e607 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -141,7 +141,10 @@ class RelatedField(FieldCacheMixin, Field): self.model._meta.object_name, self.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=self, id="fields.E306", ) @@ -227,8 +230,8 @@ class RelatedField(FieldCacheMixin, Field): errors = [] opts = self.model._meta - # `f.remote_field.model` may be a string instead of a model. Skip if model name is - # not resolved. + # f.remote_field.model may be a string instead of a model. Skip if + # model name is not resolved. if not isinstance(self.remote_field.model, ModelBase): return [] @@ -321,8 +324,8 @@ class RelatedField(FieldCacheMixin, Field): if clash_field.get_accessor_name() == rel_query_name: errors.append( checks.Error( - "Reverse query name for '%s' clashes with reverse query name for '%s'." - % (field_name, clash_name), + "Reverse query name for '%s' clashes with reverse query name " + "for '%s'." % (field_name, clash_name), hint=( "Add or change a related_name argument " "to the definition for '%s' or '%s'." @@ -498,7 +501,8 @@ class RelatedField(FieldCacheMixin, Field): target_fields = self.path_infos[-1].target_fields if len(target_fields) > 1: raise exceptions.FieldError( - "The relation has multiple target fields, but only single target field was asked for" + "The relation has multiple target fields, but only single target field " + "was asked for" ) return target_fields[0] @@ -987,7 +991,10 @@ class ForeignKey(ForeignObject): return [ checks.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=self, id="fields.E320", ) @@ -1008,8 +1015,12 @@ class ForeignKey(ForeignObject): return ( [ 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=self, id="fields.W342", ) @@ -1482,7 +1493,10 @@ class ManyToManyField(RelatedField): "which two foreign keys Django should use via the " "through_fields keyword argument." % (self, from_model_name), - 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=self.remote_field.through, id="fields.E333", ) @@ -1569,7 +1583,10 @@ class ManyToManyField(RelatedField): "Field specifies 'through_fields' but does not provide " "the names of the two link fields that should be used " "for the relation through model '%s'." % qualified_model_name, - 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=self, id="fields.E337", ) @@ -1608,7 +1625,8 @@ class ManyToManyField(RelatedField): possible_field_names.append(f.name) if possible_field_names: hint = ( - "Did you mean one of the following foreign keys to '%s': %s?" + "Did you mean one of the following foreign keys to '%s': " + "%s?" % ( related_model._meta.object_name, ", ".join(possible_field_names), diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py index 3f67ed8166..7e782630f0 100644 --- a/django/db/models/fields/related_descriptors.py +++ b/django/db/models/fields/related_descriptors.py @@ -252,8 +252,8 @@ class ForwardManyToOneDescriptor: ) if not router.allow_relation(value, instance): raise ValueError( - 'Cannot assign "%r": the current database router prevents this relation.' - % value + 'Cannot assign "%r": the current database router prevents this ' + "relation." % value ) remote_field = self.field.remote_field @@ -515,15 +515,16 @@ class ReverseOneToOneDescriptor: ) if not router.allow_relation(value, instance): raise ValueError( - 'Cannot assign "%r": the current database router prevents this relation.' - % value + 'Cannot assign "%r": the current database router prevents this ' + "relation." % value ) related_pk = tuple( getattr(instance, field.attname) for field in self.related.field.foreign_related_fields ) - # Set the value of the related field to the value of the related object's related field + # Set the value of the related field to the value of the related + # object's related field. for index, field in enumerate(self.related.field.local_related_fields): setattr(value, field.attname, related_pk[index]) @@ -771,7 +772,8 @@ def create_reverse_many_to_one_manager(superclass, rel): update_or_create.alters_data = True - # remove() and clear() are only provided if the ForeignKey can have a value of null. + # remove() and clear() are only provided if the ForeignKey can have a + # value of null. if rel.field.null: def remove(self, *objs, bulk=True): @@ -1273,7 +1275,8 @@ def create_forward_many_to_many_manager(superclass, rel, reverse): ): # source_field_name: the PK fieldname in join table for the source object # target_field_name: the PK fieldname in join table for the target object - # *objs - objects to add. Either object instances, or primary keys of object instances. + # *objs - objects to add. Either object instances, or primary keys + # of object instances. if not objs: return diff --git a/django/db/models/fields/related_lookups.py b/django/db/models/fields/related_lookups.py index 1bad1cf416..99eadc5da7 100644 --- a/django/db/models/fields/related_lookups.py +++ b/django/db/models/fields/related_lookups.py @@ -98,8 +98,9 @@ class RelatedIn(In): def as_sql(self, compiler, connection): if isinstance(self.lhs, MultiColSource): # For multicolumn lookups we need to build a multicolumn where clause. - # This clause is either a SubqueryConstraint (for values that need to be compiled to - # SQL) or an OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses. + # This clause is either a SubqueryConstraint (for values that need + # to be compiled to SQL) or an OR-combined list of + # (col1 = val1 AND col2 = val2 AND ...) clauses. from django.db.models.sql.where import ( AND, OR, diff --git a/django/db/models/fields/reverse_related.py b/django/db/models/fields/reverse_related.py index 2ff66f34d0..eb2d4714bb 100644 --- a/django/db/models/fields/reverse_related.py +++ b/django/db/models/fields/reverse_related.py @@ -90,7 +90,8 @@ class ForeignObjectRel(FieldCacheMixin): def related_model(self): if not self.field.model: raise AttributeError( - "This property can't be accessed before self.field.contribute_to_class has been called." + "This property can't be accessed before self.field.contribute_to_class " + "has been called." ) return self.field.model @@ -211,7 +212,8 @@ class ForeignObjectRel(FieldCacheMixin): opts = model._meta if model else self.related_model._meta model = model or self.related_model if self.multiple: - # If this is a symmetrical m2m relation on self, there is no reverse accessor. + # If this is a symmetrical m2m relation on self, there is no + # reverse accessor. if self.symmetrical and model == self.model: return None if self.related_name: diff --git a/django/db/models/functions/comparison.py b/django/db/models/functions/comparison.py index cc78834f20..eb1f20a77c 100644 --- a/django/db/models/functions/comparison.py +++ b/django/db/models/functions/comparison.py @@ -104,7 +104,8 @@ class Coalesce(Func): class Collate(Func): function = "COLLATE" template = "%(expressions)s %(function)s %(collation)s" - # Inspired from https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS + # Inspired from + # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS collation_re = _lazy_re_compile(r"^[\w\-]+$") def __init__(self, expression, collation): diff --git a/django/db/models/indexes.py b/django/db/models/indexes.py index 95b71ae5bf..3c2b699ccc 100644 --- a/django/db/models/indexes.py +++ b/django/db/models/indexes.py @@ -51,7 +51,8 @@ class Index: ) if opclasses and len(fields) != len(opclasses): raise ValueError( - "Index.fields and Index.opclasses must have the same number of elements." + "Index.fields and Index.opclasses must have the same number of " + "elements." ) if fields and not all(isinstance(field, str) for field in fields): raise ValueError("Index.fields must contain only strings with field names.") diff --git a/django/db/models/manager.py b/django/db/models/manager.py index 0c0688828e..e37e56cd17 100644 --- a/django/db/models/manager.py +++ b/django/db/models/manager.py @@ -95,7 +95,8 @@ class BaseManager: # Only copy missing methods. if hasattr(cls, name): continue - # Only copy public methods or methods with the attribute `queryset_only=False`. + # Only copy public methods or methods with the attribute + # queryset_only=False. queryset_only = getattr(method, "queryset_only", None) if queryset_only or (queryset_only is None and name.startswith("_")): continue diff --git a/django/db/models/options.py b/django/db/models/options.py index b95f9871b1..3caad38072 100644 --- a/django/db/models/options.py +++ b/django/db/models/options.py @@ -20,8 +20,8 @@ PROXY_PARENTS = object() EMPTY_RELATION_TREE = () IMMUTABLE_WARNING = ( - "The return type of '%s' should never be mutated. If you want to manipulate this list " - "for your own use, make a copy first." + "The return type of '%s' should never be mutated. If you want to manipulate this " + "list for your own use, make a copy first." ) DEFAULT_NAMES = ( diff --git a/django/db/models/query.py b/django/db/models/query.py index 687fd8b4cd..aa10176dc0 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1063,7 +1063,8 @@ class QuerySet: raise TypeError("'flat' and 'named' can't be used together.") if flat and len(fields) > 1: raise TypeError( - "'flat' is not valid when values_list is called with more than one field." + "'flat' is not valid when values_list is called with more than one " + "field." ) field_names = {f for f in fields if not hasattr(f, "resolve_expression")} diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 13a7ec7263..28d412e11a 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -94,7 +94,8 @@ class SQLCompiler: # SomeModel.objects.annotate(Count('somecol')).values('name') # GROUP BY: all cols of the model # - # SomeModel.objects.values('name', 'pk').annotate(Count('somecol')).values('pk') + # SomeModel.objects.values('name', 'pk') + # .annotate(Count('somecol')).values('pk') # GROUP BY: name, pk # # SomeModel.objects.values('name').annotate(Count('somecol')).values('pk') @@ -647,10 +648,7 @@ class SQLCompiler: result += [", ".join(out_cols), "FROM", *from_] params.extend(f_params) - if ( - self.query.select_for_update - and self.connection.features.has_select_for_update - ): + if self.query.select_for_update and features.has_select_for_update: if self.connection.get_autocommit(): raise TransactionManagementError( "select_for_update cannot be used outside of a transaction." @@ -658,7 +656,7 @@ class SQLCompiler: if ( with_limit_offset - and not self.connection.features.supports_select_for_update_with_limit + and not features.supports_select_for_update_with_limit ): raise NotSupportedError( "LIMIT/OFFSET is not supported with " @@ -671,28 +669,19 @@ class SQLCompiler: # If it's a NOWAIT/SKIP LOCKED/OF/NO KEY query but the # backend doesn't support it, raise NotSupportedError to # prevent a possible deadlock. - if ( - nowait - and not self.connection.features.has_select_for_update_nowait - ): + if nowait and not features.has_select_for_update_nowait: raise NotSupportedError( "NOWAIT is not supported on this database backend." ) - elif ( - skip_locked - and not self.connection.features.has_select_for_update_skip_locked - ): + elif skip_locked and not features.has_select_for_update_skip_locked: raise NotSupportedError( "SKIP LOCKED is not supported on this database backend." ) - elif of and not self.connection.features.has_select_for_update_of: + elif of and not features.has_select_for_update_of: raise NotSupportedError( "FOR UPDATE OF is not supported on this database backend." ) - elif ( - no_key - and not self.connection.features.has_select_for_no_key_update - ): + elif no_key and not features.has_select_for_no_key_update: raise NotSupportedError( "FOR NO KEY UPDATE is not supported on this " "database backend." @@ -704,7 +693,7 @@ class SQLCompiler: no_key=no_key, ) - if for_update_part and self.connection.features.for_update_after_from: + if for_update_part and features.for_update_after_from: result.append(for_update_part) if where: @@ -751,7 +740,7 @@ class SQLCompiler: ) ) - if for_update_part and not self.connection.features.for_update_after_from: + if for_update_part and not features.for_update_after_from: result.append(for_update_part) if self.query.subquery and extra_select: diff --git a/django/db/models/sql/datastructures.py b/django/db/models/sql/datastructures.py index f398074bf7..1edf040e82 100644 --- a/django/db/models/sql/datastructures.py +++ b/django/db/models/sql/datastructures.py @@ -26,7 +26,8 @@ class Join: """ Used by sql.Query and sql.SQLCompiler to generate JOIN clauses into the FROM entry. For example, the SQL generated could be - LEFT OUTER JOIN "sometable" T1 ON ("othertable"."sometable_id" = "sometable"."id") + LEFT OUTER JOIN "sometable" T1 + ON ("othertable"."sometable_id" = "sometable"."id") This class is primarily used in Query.alias_map. All entries in alias_map must be Join compatible by providing the following attributes and methods: diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 242b2a1f3f..2b1f6757ba 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -682,7 +682,8 @@ class Query(BaseExpression): # the extra complexity when you can write a real query instead. if self.extra and rhs.extra: raise ValueError( - "When merging querysets using 'or', you cannot have extra(select=...) on both sides." + "When merging querysets using 'or', you cannot have " + "extra(select=...) on both sides." ) self.extra.update(rhs.extra) extra_select_mask = set() diff --git a/django/forms/models.py b/django/forms/models.py index a55af8eeb6..b6ce73cc5e 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -195,8 +195,8 @@ def fields_for_model( and (exclude is None or f.name not in exclude) ): raise FieldError( - "'%s' cannot be specified for %s model form as it is a non-editable field" - % (f.name, model.__name__) + "'%s' cannot be specified for %s model form as it is a " + "non-editable field" % (f.name, model.__name__) ) continue if fields is not None and f.name not in fields: @@ -816,7 +816,8 @@ class BaseModelFormSet(BaseFormSet): for uclass, unique_check in all_unique_checks: seen_data = set() for form in valid_forms: - # Get the data for the set of fields that must be unique among the forms. + # Get the data for the set of fields that must be unique among + # the forms. row_data = ( field if field in self.unique_fields else form.cleaned_data[field] for field in unique_check @@ -839,7 +840,8 @@ class BaseModelFormSet(BaseFormSet): [self.get_form_error()], renderer=self.renderer, ) - # remove the data from the cleaned_data dict since it was invalid + # Remove the data from the cleaned_data dict since it + # was invalid. for field in unique_check: if field in form.cleaned_data: del form.cleaned_data[field] @@ -874,7 +876,8 @@ class BaseModelFormSet(BaseFormSet): [self.get_form_error()], renderer=self.renderer, ) - # remove the data from the cleaned_data dict since it was invalid + # Remove the data from the cleaned_data dict since it + # was invalid. del form.cleaned_data[field] # mark the data as seen seen_data.add(data) diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 13ed2fa4cd..f52ff7619e 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -218,7 +218,8 @@ class MultiPartParser: and num_bytes_read > settings.DATA_UPLOAD_MAX_MEMORY_SIZE ): raise RequestDataTooBig( - "Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE." + "Request body exceeded " + "settings.DATA_UPLOAD_MAX_MEMORY_SIZE." ) self._post.appendlist( @@ -263,8 +264,8 @@ class MultiPartParser: for chunk in field_stream: if transfer_encoding == "base64": # We only special-case base64 transfer encoding - # We should always decode base64 chunks by multiple of 4, - # ignoring whitespace. + # We should always decode base64 chunks by + # multiple of 4, ignoring whitespace. stripped_chunk = b"".join(chunk.split()) @@ -279,7 +280,8 @@ class MultiPartParser: try: chunk = base64.b64decode(stripped_chunk) except Exception as exc: - # Since this is only a chunk, any error is an unfixable error. + # Since this is only a chunk, any error is + # an unfixable error. raise MultiPartParserError( "Could not decode base64 data." ) from exc @@ -362,7 +364,8 @@ class MultiPartParser: def _close_files(self): # Free up all file handles. # FIXME: this currently assumes that upload handlers store the file as 'file' - # We should document that... (Maybe add handler.free_file to complement new_file) + # We should document that... + # (Maybe add handler.free_file to complement new_file) for handler in self._upload_handlers: if hasattr(handler, "file"): handler.file.close() diff --git a/django/http/request.py b/django/http/request.py index d975aadf25..0b64b1b2b9 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -256,7 +256,8 @@ class HttpRequest: header, secure_value = settings.SECURE_PROXY_SSL_HEADER except ValueError: raise ImproperlyConfigured( - "The SECURE_PROXY_SSL_HEADER setting must be a tuple containing two values." + "The SECURE_PROXY_SSL_HEADER setting must be a tuple containing " + "two values." ) header_value = self.META.get(header) if header_value is not None: @@ -300,7 +301,8 @@ class HttpRequest: def upload_handlers(self, upload_handlers): if hasattr(self, "_files"): raise AttributeError( - "You cannot set the upload handlers after the upload has been processed." + "You cannot set the upload handlers after the upload has been " + "processed." ) self._upload_handlers = upload_handlers @@ -308,7 +310,10 @@ class HttpRequest: """Return a tuple of (POST QueryDict, FILES MultiValueDict).""" self.upload_handlers = ImmutableList( self.upload_handlers, - warning="You cannot alter upload handlers after the upload has been processed.", + warning=( + "You cannot alter upload handlers after the upload has been " + "processed." + ), ) parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding) return parser.parse() diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index 7762b94723..59049069de 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -278,15 +278,17 @@ class IfChangedNode(Node): return "" def _get_context_stack_frame(self, context): - # The Context object behaves like a stack where each template tag can create a new scope. - # Find the place where to store the state to detect changes. + # The Context object behaves like a stack where each template tag can + # create a new scope. Find the place where to store the state to detect + # changes. if "forloop" in context: # Ifchanged is bound to the local for loop. # When there is a loop-in-loop, the state is bound to the inner loop, # so it resets when the outer loop continues. return context["forloop"] else: - # Using ifchanged outside loops. Effectively this is a no-op because the state is associated with 'self'. + # Using ifchanged outside loops. Effectively this is a no-op + # because the state is associated with 'self'. return context.render_context @@ -545,7 +547,8 @@ def autoescape(parser, token): """ Force autoescape behavior for this block. """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. args = token.contents.split() if len(args) != 2: raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.") @@ -697,7 +700,8 @@ def do_filter(parser, token): Instead, use the ``autoescape`` tag to manage autoescaping for blocks of template code. """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. _, rest = token.contents.split(None, 1) filter_expr = parser.compile_filter("var|%s" % (rest)) for func, unused in filter_expr.filters: @@ -1070,7 +1074,8 @@ def load(parser, token): {% load byline from news %} """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. bits = token.contents.split() if len(bits) >= 4 and bits[-2] == "from": # from syntax is used; load individual tags from the library @@ -1304,7 +1309,8 @@ def templatetag(parser, token): ``closecomment`` ``#}`` ================== ======= """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'templatetag' statement takes one argument") diff --git a/django/template/loader_tags.py b/django/template/loader_tags.py index bf4d4f0d74..c92b37bb97 100644 --- a/django/template/loader_tags.py +++ b/django/template/loader_tags.py @@ -213,7 +213,8 @@ def do_block(parser, token): """ Define a block that can be overridden by child templates. """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0]) diff --git a/django/templatetags/i18n.py b/django/templatetags/i18n.py index 9724efbd91..3582df1829 100644 --- a/django/templatetags/i18n.py +++ b/django/templatetags/i18n.py @@ -229,7 +229,8 @@ def do_get_available_languages(parser, token): This puts settings.LANGUAGES into the named variable. """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. args = token.contents.split() if len(args) != 3 or args[1] != "as": raise TemplateSyntaxError( @@ -321,7 +322,8 @@ def do_get_current_language(parser, token): This fetches the currently active language and puts its value into the ``language`` context variable. """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. args = token.contents.split() if len(args) != 3 or args[1] != "as": raise TemplateSyntaxError( @@ -343,7 +345,8 @@ def do_get_current_language_bidi(parser, token): the ``bidi`` context variable. True indicates right-to-left layout, otherwise left-to-right. """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. args = token.contents.split() if len(args) != 3 or args[1] != "as": raise TemplateSyntaxError( @@ -424,8 +427,8 @@ def do_translate(parser, token): ) if value in invalid_context: raise TemplateSyntaxError( - "Invalid argument '%s' provided to the '%s' tag for the context option" - % (value, bits[0]), + "Invalid argument '%s' provided to the '%s' tag for the context " + "option" % (value, bits[0]), ) message_context = parser.compile_filter(value) elif option == "as": diff --git a/django/templatetags/static.py b/django/templatetags/static.py index 7a5147a0dd..a68e44add2 100644 --- a/django/templatetags/static.py +++ b/django/templatetags/static.py @@ -25,7 +25,8 @@ class PrefixNode(template.Node): """ Class method to parse prefix node and return a Node. """ - # token.split_contents() isn't useful here because tags using this method don't accept variable as arguments + # token.split_contents() isn't useful here because tags using this + # method don't accept variable as arguments. tokens = token.contents.split() if len(tokens) > 1 and tokens[1] != "as": raise template.TemplateSyntaxError( diff --git a/django/templatetags/tz.py b/django/templatetags/tz.py index 50810cece6..de0432cd4d 100644 --- a/django/templatetags/tz.py +++ b/django/templatetags/tz.py @@ -217,7 +217,8 @@ def get_current_timezone_tag(parser, token): This will fetch the currently active time zone and put its name into the ``TIME_ZONE`` context variable. """ - # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments + # token.split_contents() isn't useful here because this tag doesn't accept + # variable as arguments. args = token.contents.split() if len(args) != 3 or args[1] != "as": raise TemplateSyntaxError( diff --git a/django/test/testcases.py b/django/test/testcases.py index d514d06c7a..14416807be 100644 --- a/django/test/testcases.py +++ b/django/test/testcases.py @@ -209,7 +209,8 @@ class SimpleTestCase(unittest.TestCase): for alias in cls.databases: if alias not in connections: message = ( - "%s.%s.databases refers to %r which is not defined in settings.DATABASES." + "%s.%s.databases refers to %r which is not defined in " + "settings.DATABASES." % ( cls.__module__, cls.__qualname__, @@ -352,7 +353,10 @@ class SimpleTestCase(unittest.TestCase): self.assertTrue( response.redirect_chain, msg_prefix - + "Response didn't redirect as expected: Response code was %d (expected %d)" + + ( + "Response didn't redirect as expected: Response code was %d " + "(expected %d)" + ) % (response.status_code, status_code), ) @@ -360,7 +364,10 @@ class SimpleTestCase(unittest.TestCase): response.redirect_chain[0][1], status_code, msg_prefix - + "Initial response didn't redirect as expected: Response code was %d (expected %d)" + + ( + "Initial response didn't redirect as expected: Response code was " + "%d (expected %d)" + ) % (response.redirect_chain[0][1], status_code), ) @@ -370,7 +377,10 @@ class SimpleTestCase(unittest.TestCase): response.status_code, target_status_code, msg_prefix - + "Response didn't redirect as expected: Final Response code was %d (expected %d)" + + ( + "Response didn't redirect as expected: Final Response code was %d " + "(expected %d)" + ) % (response.status_code, target_status_code), ) @@ -380,7 +390,10 @@ class SimpleTestCase(unittest.TestCase): response.status_code, status_code, msg_prefix - + "Response didn't redirect as expected: Response code was %d (expected %d)" + + ( + "Response didn't redirect as expected: Response code was %d " + "(expected %d)" + ) % (response.status_code, status_code), ) @@ -401,7 +414,8 @@ class SimpleTestCase(unittest.TestCase): raise ValueError( "The test client is unable to fetch remote URLs (got %s). " "If the host is served by Django, add '%s' to ALLOWED_HOSTS. " - "Otherwise, use assertRedirects(..., fetch_redirect_response=False)." + "Otherwise, use " + "assertRedirects(..., fetch_redirect_response=False)." % (url, domain) ) # Get the redirection page, using the same client that was used @@ -417,7 +431,10 @@ class SimpleTestCase(unittest.TestCase): redirect_response.status_code, target_status_code, msg_prefix - + "Couldn't retrieve redirection page '%s': response code was %d (expected %d)" + + ( + "Couldn't retrieve redirection page '%s': response code was %d " + "(expected %d)" + ) % (path, redirect_response.status_code, target_status_code), ) @@ -593,13 +610,19 @@ class SimpleTestCase(unittest.TestCase): elif field in context[form].fields: self.fail( msg_prefix - + "The field '%s' on form '%s' in context %d contains no errors" + + ( + "The field '%s' on form '%s' in context %d contains no " + "errors" + ) % (field, form, i) ) else: self.fail( msg_prefix - + "The form '%s' in context %d does not contain the field '%s'" + + ( + "The form '%s' in context %d does not contain the " + "field '%s'" + ) % (form, i, field) ) else: @@ -672,13 +695,19 @@ class SimpleTestCase(unittest.TestCase): elif field in context[formset].forms[form_index].fields: self.fail( msg_prefix - + "The field '%s' on formset '%s', form %d in context %d contains no errors" + + ( + "The field '%s' on formset '%s', form %d in context " + "%d contains no errors" + ) % (field, formset, form_index, i) ) else: self.fail( msg_prefix - + "The formset '%s', form %d in context %d does not contain the field '%s'" + + ( + "The formset '%s', form %d in context %d does not " + "contain the field '%s'" + ) % (formset, form_index, i, field) ) elif form_index is not None: diff --git a/django/test/utils.py b/django/test/utils.py index ac0fc34b08..270e34b69d 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -199,7 +199,10 @@ def setup_databases( with time_keeper.timed(" Creating '%s'" % alias): # RemovedInDjango50Warning: when the deprecation ends, # replace with: - # serialize_alias = serialized_aliases is None or alias in serialized_aliases + # serialize_alias = ( + # serialized_aliases is None + # or alias in serialized_aliases + # ) try: serialize_alias = connection.settings_dict["TEST"]["SERIALIZE"] except KeyError: diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py index fee8ae9750..26c9884e18 100644 --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -492,7 +492,8 @@ class URLResolver: except (ImportError, ViewDoesNotExist) as e: path = getattr(self.urlconf_module, "handler%s" % status_code) msg = ( - "The custom handler{status_code} view '{path}' could not be imported." + "The custom handler{status_code} view '{path}' could not be " + "imported." ).format(status_code=status_code, path=path) messages.append(Error(msg, hint=str(e), id="urls.E008")) continue @@ -657,7 +658,8 @@ class URLResolver: # Update the sub_match_dict with the kwargs from the sub_match. sub_match_dict.update(sub_match.kwargs) # If there are *any* named groups, ignore all non-named groups. - # Otherwise, pass all non-named arguments as positional arguments. + # Otherwise, pass all non-named arguments as positional + # arguments. sub_match_args = sub_match.args if not sub_match_dict: sub_match_args = args + sub_match.args diff --git a/django/utils/asyncio.py b/django/utils/asyncio.py index 7e0b439db2..1e79f90c2c 100644 --- a/django/utils/asyncio.py +++ b/django/utils/asyncio.py @@ -30,7 +30,10 @@ def async_unsafe(message): # If the message is actually a function, then be a no-arguments decorator. if callable(message): func = message - message = "You cannot call this from an async context - use a thread or sync_to_async." + message = ( + "You cannot call this from an async context - use a thread or " + "sync_to_async." + ) return decorator(func) else: return decorator diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py index 541b8f8688..f96f9176a9 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -276,7 +276,10 @@ class DateFormat(TimeFormat): return format_datetime_rfc5322(dt) def S(self): - "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'" + """ + English ordinal suffix for the day of the month, 2 characters; i.e. + 'st', 'nd', 'rd' or 'th'. + """ if self.data.day in (11, 12, 13): # Special case return "th" last = self.data.day % 10 diff --git a/django/utils/deconstruct.py b/django/utils/deconstruct.py index ca87f7ecc9..f8754c1974 100644 --- a/django/utils/deconstruct.py +++ b/django/utils/deconstruct.py @@ -38,8 +38,8 @@ def deconstructible(*args, path=None): "classes. Please move the object into the main module " "body to use migrations.\n" "For more information, see " - "https://docs.djangoproject.com/en/%s/topics/migrations/#serializing-values" - % (name, module_name, get_docs_version()) + "https://docs.djangoproject.com/en/%s/topics/migrations/" + "#serializing-values" % (name, module_name, get_docs_version()) ) return ( path diff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py index a8f6bc5c06..5a57db19ec 100644 --- a/django/utils/feedgenerator.py +++ b/django/utils/feedgenerator.py @@ -7,7 +7,7 @@ Sample usage: >>> feed = feedgenerator.Rss201rev2Feed( ... title="Poynter E-Media Tidbits", ... link="http://www.poynter.org/column.asp?id=31", -... description="A group blog by the sharpest minds in online media/journalism/publishing.", +... description="A group blog by the sharpest minds in online journalism.", ... language="en", ... ) >>> feed.add_item( @@ -47,7 +47,8 @@ def get_tag_uri(url, date): """ Create a TagURI. - See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id + See + https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse(url) d = "" diff --git a/django/utils/formats.py b/django/utils/formats.py index 50b58445e4..ba569974ed 100644 --- a/django/utils/formats.py +++ b/django/utils/formats.py @@ -302,7 +302,8 @@ def sanitize_separators(value): and value.count(".") == 1 and len(value.split(".")[-1]) != 3 ): - # Special case where we suspect a dot meant decimal separator (see #22171) + # Special case where we suspect a dot meant decimal separator + # (see #22171). pass else: for replacement in { diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index 52110af83a..7c81e8bee2 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -34,10 +34,13 @@ CONTEXT_SEPARATOR = "\x04" # and RFC 3066, section 2.1 accept_language_re = _lazy_re_compile( r""" - ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # "en", "en-au", "x-y-z", "es-419", "*" - (?:\s*;\s*q=(0(?:\.[0-9]{,3})?|1(?:\.0{,3})?))? # Optional "q=1.00", "q=0.8" - (?:\s*,\s*|$) # Multiple accepts per header. - """, + # "en", "en-au", "x-y-z", "es-419", "*" + ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) + # Optional "q=1.00", "q=0.8" + (?:\s*;\s*q=(0(?:\.[0-9]{,3})?|1(?:\.0{,3})?))? + # Multiple accepts per header. + (?:\s*,\s*|$) + """, re.VERBOSE, ) diff --git a/django/views/csrf.py b/django/views/csrf.py index ec3c6d5d91..2d9616784d 100644 --- a/django/views/csrf.py +++ b/django/views/csrf.py @@ -97,7 +97,7 @@ CSRF_FAILURE_TEMPLATE = """ {% endif %} -""" +""" # NOQA CSRF_FAILURE_TEMPLATE_NAME = "403_csrf.html" diff --git a/django/views/defaults.py b/django/views/defaults.py index 273d5fa7d5..d5f6708788 100644 --- a/django/views/defaults.py +++ b/django/views/defaults.py @@ -120,7 +120,8 @@ def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME): ERROR_PAGE_TEMPLATE % {"title": "Bad Request (400)", "details": ""}, content_type="text/html", ) - # No exception content is passed to the template, to not disclose any sensitive information. + # No exception content is passed to the template, to not disclose any + # sensitive information. return HttpResponseBadRequest(template.render()) diff --git a/django/views/i18n.py b/django/views/i18n.py index b7eca510aa..2cf24d3540 100644 --- a/django/views/i18n.py +++ b/django/views/i18n.py @@ -188,7 +188,7 @@ js_catalog_template = r""" } }; {% endautoescape %} -""" +""" # NOQA class JavaScriptCatalog(View): diff --git a/docs/_ext/djangodocs.py b/docs/_ext/djangodocs.py index f3c4321499..5e99f9f5e0 100644 --- a/docs/_ext/djangodocs.py +++ b/docs/_ext/djangodocs.py @@ -250,7 +250,8 @@ def visit_console_html(self, node): self.body.append( """\
- + diff --git a/docs/conf.py b/docs/conf.py index 41301337ee..2711eb9c89 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -269,7 +269,7 @@ rst_epilog = """ .. |django-developers| replace:: :ref:`django-developers ` .. |django-announce| replace:: :ref:`django-announce ` .. |django-updates| replace:: :ref:`django-updates ` -""" +""" # NOQA # -- Options for LaTeX output -------------------------------------------------- diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py index 7d6deced7e..6ffcdc6497 100644 --- a/tests/admin_changelist/tests.py +++ b/tests/admin_changelist/tests.py @@ -1243,7 +1243,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 c11b8f71c2..d85f401855 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, - '

/admindocs/

', + '

/admindocs/

', 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, - '

/admin/

', + "

" + '' + "/admin/

", html=True, ) @@ -118,7 +121,8 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): response = self.client.get(reverse("django-admindocs-models-index")) self.assertContains( response, - '

Authentication and Authorization (django.contrib.auth)

', + '

Authentication and Authorization (django.contrib.auth)' + "

", html=True, ) @@ -380,11 +384,15 @@ class TestModelDetailView(TestDataMixin, AdminDocsTestCase): def test_model_docstring_renders_correctly(self): summary = ( - '

Stores information about a person, related to myapp.Company.

' + '

Stores information about a person, related to ' + '' + "myapp.Company.

" ) subheading = "

Notes

" - body = '

Use save_changes() when saving this object.

' + body = ( + '

Use save_changes() when saving this ' + "object.

" + ) model_body = ( '
company
Field storing
" % (story2.id, story1.id), html=True, ) self.assertContains(response, '%d' % story1.id, 1) @@ -4257,8 +4298,8 @@ class AdminViewListEditable(TestCase): response, '
\n' '' - '\n
' - % (story2.id, story1.id), + '\n' + "" % (story2.id, story1.id), html=True, ) self.assertContains( @@ -5069,7 +5110,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( @@ -5512,7 +5555,8 @@ class SeleniumTests(AdminSeleniumTestCase): 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" @@ -5643,7 +5687,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", @@ -6203,17 +6250,20 @@ class ReadonlyTest(AdminFieldExtractionMixin, TestCase): self.assertContains(response, '
', 3) self.assertContains( response, - '
Some help text for the title (with Unicode ŠĐĆŽćžšđ)
', + '
Some help text for the title (with Unicode ŠĐĆŽćžšđ)' + "
", html=True, ) self.assertContains( response, - '
Some help text for the content (with Unicode ŠĐĆŽćžšđ)
', + '
Some help text for the content (with Unicode ŠĐĆŽćžšđ)' + "
", html=True, ) self.assertContains( response, - '
Some help text for the date (with Unicode ŠĐĆŽćžšđ)
', + '
Some help text for the date (with Unicode ŠĐĆŽćžšđ)' + "
", html=True, ) @@ -6648,7 +6698,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( @@ -6673,7 +6726,10 @@ class UserAdminTest(TestCase): self.assertContains(response, ""obj": "newuser"") 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__",)) @@ -6705,7 +6761,10 @@ class UserAdminTest(TestCase): self.assertContains(response, ""action": "change"") 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__",)) @@ -6915,8 +6974,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")) @@ -7409,33 +7468,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. @@ -7450,12 +7503,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): @@ -7765,7 +7816,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( @@ -7774,10 +7828,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"] @@ -7819,7 +7877,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" ], ) @@ -7838,7 +7897,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", ), @@ -8175,7 +8235,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") @@ -8184,7 +8244,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") @@ -8198,14 +8258,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 35563653b0..e291801cae 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -314,7 +314,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): @@ -363,13 +364,15 @@ class AdminDateWidgetTest(SimpleTestCase): w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), - '', + '', ) # pass attrs to widget w = widgets.AdminDateWidget(attrs={"size": 20, "class": "myDateField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), - '', + '', ) @@ -378,13 +381,15 @@ class AdminTimeWidgetTest(SimpleTestCase): w = widgets.AdminTimeWidget() self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), - '', + '', ) # pass attrs to widget w = widgets.AdminTimeWidget(attrs={"size": 20, "class": "myTimeField"}) self.assertHTMLEqual( w.render("test", datetime(2007, 12, 1, 9, 30)), - '', + '', ) @@ -486,7 +491,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], @@ -495,7 +501,8 @@ class AdminURLWidgetTest(SimpleTestCase): ) self.assertEqual( VALUE_RE.search(output)[1], - "http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"", + "http://www.example.com/%C3%A4"><script>" + "alert("XSS!")</script>"", ) @@ -504,12 +511,14 @@ class AdminUUIDWidgetTests(SimpleTestCase): w = widgets.AdminUUIDInputWidget() self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), - '', + '', ) w = widgets.AdminUUIDInputWidget(attrs={"class": "myUUIDInput"}) self.assertHTMLEqual( w.render("test", "550e8400-e29b-41d4-a716-446655440000"), - '', + '', ) @@ -685,7 +694,8 @@ class ForeignKeyRawIdWidgetTest(TestCase): ) self.assertHTMLEqual( w.render("test", child_of_hidden.parent_id, attrs={}), - '' + '' '' ' ' @@ -698,8 +708,9 @@ class ForeignKeyRawIdWidgetTest(TestCase): self.assertHTMLEqual( w.render("test", None), '\n' - '', + '', ) def test_render_fk_as_pk_model(self): @@ -727,8 +738,10 @@ class ManyToManyRawIdWidgetTest(TestCase): self.assertHTMLEqual( w.render("test", [m1.pk, m2.pk], attrs={}), ( - '' - '' + '' + '' ) % {"m1pk": m1.pk, "m2pk": m2.pk}, ) @@ -736,8 +749,10 @@ class ManyToManyRawIdWidgetTest(TestCase): self.assertHTMLEqual( w.render("test", [m1.pk]), ( - '' - '' + '' + '' ) % {"m1pk": m1.pk}, ) diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index de63b375d4..c71fedec1b 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 b4954684aa..b3b0e5d703 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"), @@ -1121,7 +1124,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 efb60d187e..278caa3584 100644 --- a/tests/apps/tests.py +++ b/tests/apps/tests.py @@ -78,7 +78,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, - "
  • Your password can’t be too similar to your other personal information.
", + "
  • " + "Your password can’t be too similar to your other personal information." + "
", ) @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 7650548d2b..b767c2823d 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$390000$seasalt2$geC/uZ92nRXDSjSxeoiBqYyRcrLzMm8xK3ro1QS1uo8=", + "pbkdf2_sha256$390000$seasalt2$geC/uZ92nRXDSjSxeoiBqYyRcrLzMm8xK3r" + "o1QS1uo8=", ) self.assertTrue(hasher.verify("lètmein", encoded)) diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index 41596a2210..071ea85a65 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") @@ -785,7 +787,10 @@ class CreatesuperuserManagementCommandTestCase(TestCase): @override_settings( AUTH_PASSWORD_VALIDATORS=[ { - "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator" + "NAME": ( + "django.contrib.auth.password_validation." + "UserAttributeSimilarityValidator" + ) }, ] ) @@ -830,7 +835,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" + ) }, ], ) @@ -877,7 +885,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" + ) }, ], ) @@ -1094,7 +1105,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("", 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///", 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 a518db2c64..3f51d57de8 100644 --- a/tests/backends/oracle/tests.py +++ b/tests/backends/oracle/tests.py @@ -80,9 +80,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 4ff91388e6..403a761492 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -809,7 +809,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 d010bc0708..40ba275eb7 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -1680,9 +1680,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) @@ -2079,7 +2079,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. @@ -2460,9 +2461,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 413e2da1fa..d025c4d92c 100644 --- a/tests/check_framework/test_security.py +++ b/tests/check_framework/test_security.py @@ -597,7 +597,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/\$', 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/\$', 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/\$', 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/\$', 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 6c8f5e1f04..834a92eecf 100644 --- a/tests/csrf_tests/tests.py +++ b/tests/csrf_tests/tests.py @@ -712,14 +712,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=""" -

\u00a1Unicode!
+ +

\u00a1Unicode!
+ """ ) 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 5a92993912..67a4b81766 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 597589b836..977294427c 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 d800462129..c7488d7e25 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", @@ -1059,9 +1062,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 251fa7b1e5..15f8a4d6b2 100644 --- a/tests/expressions_window/tests.py +++ b/tests/expressions_window/tests.py @@ -1310,7 +1310,8 @@ class NonQueryWindowTests(SimpleTestCase): ) self.assertEqual( repr(Window(expression=Avg("salary"), order_by=F("department").asc())), - "", + "", ) 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 37f9559eef..c96f36e2a1 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", @@ -349,7 +349,8 @@ class FileUploadTests(TestCase): "\r\n".join( [ "--" + client.BOUNDARY, - f'Content-Disposition: form-data; name="file"; filename="{file_name}"', + f'Content-Disposition: form-data; name="file"; ' + f'filename="{file_name}"', "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", @@ -706,7 +707,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 @@ -723,7 +725,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", @@ -907,7 +910,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***", ), ( @@ -930,7 +934,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(), [ - "", + "", "", "", ], @@ -288,7 +317,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): self.assertQuerysetEqual( Visa.objects.all(), [ - "", + "", "", '', ], @@ -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"], - 'News StoriesLatest news storiesPoker on TV is great!2006-06-16T11:00:00Copyright is fine the way it ' - 'is2006-06-16T14:00:00Django conquers world!' - '2006-06-16T15:00:00XML identified as leading ' - 'cause of cancer2006-06-16T16:00:00' - 'copyright' - 'fixtures' - 'article3' - 'legal' - '' - 'fixturesarticle3djangofixturesarticle4' - 'world dominationfixturesarticle' - '4Django Reinhardt' - 'Stephane Grappelli' - '' - 'Artist formerly known as "Prince"Django Reinhardt' - 'add_user' - "authuserchange_user" - "authuserdelete_user" - 'authuserStephane' - ' Grappelli' - "add_userauthuser" - "delete_userauthuser" - 'Artist formerly known as "Prince"change_user' - 'authuserMusic for all agesArtist formerly known as ' - '"Prince"Django Reinhardt' - "", + '' + '' + 'News Stories' + 'Latest news stories' + "" + '' + 'Poker on TV is great!' + '2006-06-16T11:00:00' + "" + '' + 'Copyright is fine the way it is' + "" + '2006-06-16T14:00:00' + "" + '' + 'Django conquers world!' + '2006-06-16T15:00:00' + "" + '' + '' + "XML identified as leading cause of cancer" + '2006-06-16T16:00:00' + "" + '' + 'copyright' + 'fixturesarticle' + "" + '3' + "" + '' + 'legal' + 'fixturesarticle' + "" + '3' + '' + 'django' + 'fixturesarticle' + "" + '4' + "" + '' + 'world domination' + 'fixturesarticle' + "" + '4' + "" + '' + 'Django Reinhardt' + "" + '' + 'Stephane Grappelli' + "" + '' + 'Artist formerly known as "Prince"' + "" + "" + '' + '' + "Django Reinhardt" + '' + "add_userauth" + "userchange_user" + "authuser" + "delete_userauth" + "user" + "" + '' + '' + "Stephane Grappelli" + '' + "add_userauth" + "user" + "delete_userauth" + "user" + "" + '' + '' + 'Artist formerly known as "Prince"' + '' + "change_userauth" + "user" + "" + '' + 'Music for all ages' + '' + 'Artist formerly known as "Prince"' + "Django Reinhardt" + "", 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"], - 'News StoriesLatest news storiesPoker has no place on ESPN' - '2006-06-16T12:00:00Time to reform copyright' - '2006-06-16T13:00:00copyrightfixtures' - 'article3' - 'lawfixtures' - 'article3' - 'Django Reinhardt' - 'Stephane ' - 'Grappelli' - "Prince", + '' + '' + 'News Stories' + 'Latest news stories' + "" + '' + 'Poker has no place on ESPN' + '2006-06-16T12:00:00' + "" + '' + 'Time to reform copyright' + '2006-06-16T13:00:00' + "" + '' + 'copyright' + 'fixtures' + "article" + '3' + "" + '' + 'law' + 'fixtures' + "article" + '3' + "" + '' + 'Django Reinhardt' + "" + '' + 'Stephane Grappelli' + "" + '' + 'Prince' + "", 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, [ - "", - "", - "", + "", + "", + "", ], 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, "

Isn't it sekrit!

") 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 9022fbf9c5..f63abf82bd 100644 --- a/tests/foreign_object/tests.py +++ b/tests/foreign_object/tests.py @@ -79,7 +79,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, @@ -289,7 +290,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") @@ -315,7 +316,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 ) @@ -327,7 +329,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 ) @@ -352,8 +355,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, - '', + '", ) 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, - '', + '", ) 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 365684c2db..f6022807be 100644 --- a/tests/forms_tests/field_tests/test_floatfield.py +++ b/tests/forms_tests/field_tests/test_floatfield.py @@ -54,7 +54,8 @@ class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase): f = FloatField(max_value=1.5, min_value=0.5) self.assertWidgetRendersTo( f, - '', + '", ) with self.assertRaisesMessage( ValidationError, "'Ensure this value is less than or equal to 1.5.'" @@ -73,7 +74,8 @@ class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase): f = FloatField(widget=NumberInput(attrs={"step": 0.01, "max": 1.0, "min": 0.0})) self.assertWidgetRendersTo( f, - '', + '", ) 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 88f7490013..4c7664b81e 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(), """ - + - - + + """, ) 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( - '' - '', str(f), + '' + '', ) 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/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 5467cee9ad..c5376b115f 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -101,18 +101,24 @@ class FormsTestCase(SimpleTestCase): self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertHTMLEqual( str(p["first_name"]), - '', + '", ) self.assertHTMLEqual( str(p["last_name"]), - '', + '", ) self.assertHTMLEqual( str(p["birthday"]), - '', + '", ) - 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"] @@ -143,12 +149,17 @@ class FormsTestCase(SimpleTestCase): ) self.assertHTMLEqual( str(p), - """ - - - - -""", + """ + + + + + + + """, ) def test_empty_dict(self): @@ -276,33 +287,41 @@ class FormsTestCase(SimpleTestCase): self.assertHTMLEqual( p.as_table(), '' - '\n' + '\n" '' '\n' '' - '', + '", ) self.assertHTMLEqual( p.as_ul(), '
  • ' - '
  • \n' + '\n" '
  • ' '
  • \n' + 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' + 'id="id_last_name" required>\n' '
  • ' - '
  • ', + '", ) self.assertHTMLEqual( p.as_p(), '

    ' - '

    \n' + '

    \n" '

    ' '

    \n' + 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' + 'id="id_last_name" required>

    \n' '

    ' - '

    ', + '

    ", ) p = Person({"last_name": "Lennon"}) @@ -357,11 +376,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() @@ -388,10 +407,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

    """, ) - # Regarding auto_id and ) self.assertHTMLEqual( "\n".join("
    %s
    " % bf for bf in f["name"]), - """
    -
    -
    -
    """, + """ +
    +
    +
    +
    + """, ) def test_form_with_iterable_boundfield_id(self): @@ -858,7 +901,7 @@ Java 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(), '') self.assertHTMLEqual(str(fields[0]), '') @@ -1093,7 +1136,8 @@ Java self.assertTrue(f.is_valid()) self.assertHTMLEqual( str(f["when"]), - '' + '" '', ) self.assertHTMLEqual( @@ -1107,26 +1151,38 @@ Java f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), - """
    -
    -
    -
    """, + """ +
    +
    +
    +
    + """, ) f = SongForm({"composers": ["J"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), - """
    -
    -
    -
    """, + """ +
    +
    +
    +
    + """, ) f = SongForm({"composers": ["J", "P"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), - """
    -
    -
    -
    """, + """ +
    +
    +
    +
    + """, ) def test_checkbox_auto_id(self): @@ -1143,12 +1199,16 @@ Java f = SongForm(auto_id="%s_id") self.assertHTMLEqual( str(f["composers"]), - """
    -
    -
    -
    """, + """ +
    +
    +
    +
    + """, ) def test_multiple_choice_list_data(self): @@ -1253,12 +1313,18 @@ Java ) self.assertHTMLEqual( f.as_table(), - """<em>Special</em> Field: -
    • Something's wrong with 'Nothing to escape'
    - -Special Field: -
    • 'Nothing to escape' is a safe string
    -""", + """ + <em>Special</em> Field: +
      +
    • Something's wrong with 'Nothing to escape'
    + + + Special Field: +
      +
    • 'Nothing to escape' is a safe string
    + + """, ) f = EscapingForm( { @@ -1269,24 +1335,29 @@ Java ) self.assertHTMLEqual( f.as_table(), - """<em>Special</em> Field: -
    • Something's wrong with 'Should escape < & > and -<script>alert('xss')</script>'
    - -Special Field: -
    • 'Do not escape' is a safe string
    -""", + "<em>Special</em> Field:" + '
    • ' + "Something's wrong with 'Should escape < & > and " + "<script>alert('xss')</script>'
    " + '' + "" + "Special Field:" + '
      ' + "
    • 'Do not escape' is a safe string
    " + '', ) def test_validating_multiple_fields(self): - # There are a couple of ways to do multiple-field validation. If you want the - # 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) @@ -1396,19 +1467,30 @@ value="Should escape < & > and <script>alert('xss')< ) self.assertHTMLEqual( f.as_table(), - """ -
    • Please make sure your passwords match.
    -Username: -Password1: -Password2:""", + """ + +
      +
    • Please make sure your passwords match.
    + Username: + + + Password1: + + Password2: + + """, ) self.assertHTMLEqual( f.as_ul(), - """
    • -
    • Please make sure your passwords match.
  • -
  • Username:
  • -
  • Password1:
  • -
  • Password2:
  • """, + """ +
    • +
    • Please make sure your passwords match.
  • +
  • Username: + +
  • +
  • Password1:
  • +
  • Password2:
  • + """, ) f = UserRegistration( @@ -1583,9 +1665,14 @@ value="Should escape < & > and <script>alert('xss')< p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), - """First name: -Last name: -Birthday:""", + """ + First name: + + Last name: + + Birthday: + + """, ) # Instances of a dynamic Form do not persist fields from one Form instance to @@ -1601,15 +1688,19 @@ value="Should escape < & > and <script>alert('xss')< my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), - """Field1: -Field2:""", + """ + Field1: + Field2: + """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), - """Field3: -Field4:""", + """ + Field3: + Field4: + """, ) class MyForm(Form): @@ -1626,19 +1717,27 @@ value="Should escape < & > and <script>alert('xss')< my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), - """Default field 1: -Default field 2: -Field1: -Field2:""", + """ + Default field 1: + + Default field 2: + + Field1: + Field2: + """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), - """Default field 1: -Default field 2: -Field3: -Field4:""", + """ + Default field 1: + + Default field 2: + + Field3: + Field4: + """, ) # Similarly, changes to field attributes do not persist from one Form instance @@ -1766,22 +1865,33 @@ value="Should escape < & > and <script>alert('xss')< p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), - """First name: -Last name: -Birthday: -""", + """ + First name: + + Last name: + + Birthday: + + + """, ) self.assertHTMLEqual( p.as_ul(), - """
  • First name:
  • -
  • Last name:
  • -
  • Birthday:
  • """, + """ +
  • First name:
  • +
  • Last name:
  • +
  • Birthday: +
  • + """, ) self.assertHTMLEqual( p.as_p(), - """

    First name:

    -

    Last name:

    -

    Birthday:

    """, + """ +

    First name:

    +

    Last name:

    +

    Birthday: +

    + """, ) # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. @@ -1827,28 +1937,44 @@ value="Should escape < & > and <script>alert('xss')< ) self.assertHTMLEqual( p.as_table(), - """ -
    • (Hidden field hidden_text) This field is required.
    -First name: -Last name: -Birthday: -""", + """ + +
    • + (Hidden field hidden_text) This field is required.
    + First name: + + Last name: + + Birthday: + + + """, ) self.assertHTMLEqual( p.as_ul(), - """
    • (Hidden field hidden_text) This field is required.
  • -
  • First name:
  • -
  • Last name:
  • -
  • Birthday: -
  • """, + """ +
    • + (Hidden field hidden_text) This field is required.
  • +
  • First name: +
  • +
  • Last name: +
  • +
  • Birthday: +
  • + """, ) self.assertHTMLEqual( p.as_p(), - """
    • (Hidden field hidden_text) This field is required.
    -

    First name:

    -

    Last name:

    -

    Birthday: -

    """, + """ +
    • + (Hidden field hidden_text) This field is required.
    +

    First name: +

    +

    Last name: +

    +

    Birthday: +

    + """, ) # A corner case: It's possible for a form to have only HiddenInputs. @@ -1890,20 +2016,11 @@ value="Should escape < & > and <script>alert('xss')< p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), - """Field1: -Field2: -Field3: -Field4: -Field5: -Field6: -Field7: -Field8: -Field9: -Field10: -Field11: -Field12: -Field13: -Field14:""", + "".join( + f"Field{i}:" + f'' + for i in range(1, 15) + ), ) def test_explicit_field_order(self): @@ -1967,15 +2084,20 @@ value="Should escape < & > and <script>alert('xss')< p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • -
  • Realname:
  • -
  • Address:
  • """, + """ +
  • Username: +
  • +
  • Password:
  • +
  • Realname: +
  • +
  • Address:
  • + """, ) - # 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}) @@ -2001,9 +2123,13 @@ value="Should escape < & > and <script>alert('xss')< p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Your username:
  • -
  • Password1:
  • -
  • Contraseña (de nuevo):
  • """, + """ +
  • Your username: +
  • +
  • Password1:
  • +
  • Contraseña (de nuevo): +
  • + """, ) # Labels for as_* methods will only end in a colon if they don't end in other @@ -2025,14 +2151,22 @@ value="Should escape < & > and <script>alert('xss')< ) self.assertHTMLEqual( Questions().as_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) @@ -2046,9 +2180,13 @@ value="Should escape < & > and <script>alert('xss')< p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), - """
  • -
  • -
  • """, + """ +
  • + +
  • +
  • +
  • + """, ) # If label is None, Django will auto-create the label from the field name. This @@ -2073,11 +2211,12 @@ value="Should escape < & > and <script>alert('xss')< ) 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") @@ -2111,7 +2250,8 @@ value="Should escape < & > and <script>alert('xss')< self.assertHTMLEqual( f.as_ul(), '
  • Favorite color?
  • \n' - '
  • Favorite animal\u2192
  • \n' + "
  • Favorite animal\u2192 " + '
  • \n' '
  • Secret answer =
  • ', ) @@ -2129,8 +2269,11 @@ value="Should escape < & > and <script>alert('xss')< p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • """, + """ +
  • Username:
  • +
  • Password:
  • + """, ) # Here, we're submitting data, so the initial value will *not* be displayed. @@ -2153,14 +2296,18 @@ Password: """, p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
    • This field is required.
    -Password:
  • """, + """ +
  • Username:
  • +
    • This field is required.
    + Password:
  • + """, ) - # 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()) @@ -2179,14 +2326,20 @@ Password: """, p = UserRegistration(initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • """, + """ +
  • Username:
  • +
  • Password:
  • + """, ) p = UserRegistration(initial={"username": "stephane"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • """, + """ +
  • Username:
  • +
  • Password:
  • + """, ) # The 'initial' parameter is meaningless if you pass data. @@ -2213,20 +2366,24 @@ Password: """, ) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
    • This field is required.
    -Password:
  • """, + """ +
  • Username:
  • +
    • This field is required.
    + Password:
  • + """, ) # 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) @@ -2234,8 +2391,11 @@ Password: """, p = UserRegistration(initial={"username": "babik"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • """, + """ +
  • Username:
  • +
  • Password:
  • + """, ) def test_callable_initial_data(self): @@ -2268,13 +2428,16 @@ Password: """, ) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • -
  • Options:
  • """, + """ +
  • Username:
  • +
  • Password:
  • +
  • Options:
  • + """, ) # The 'initial' parameter is meaningless if you pass data. @@ -2319,19 +2482,23 @@ Options: -
    • This field is required.
    -Password:
  • -
  • Options:
  • """, + """ +
  • Username:
  • +
    • This field is required.
    + Password:
  • +
  • Options:
  • + """, ) - # 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}, @@ -2339,8 +2506,8 @@ Password: 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) @@ -2352,13 +2519,16 @@ Password: p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • -
  • Options:
  • """, + """ +
  • Username:
  • +
  • Password:
  • +
  • Options:
  • + """, ) p = UserRegistration( initial={"username": initial_stephane, "options": initial_options}, @@ -2366,13 +2536,16 @@ Password: ) self.assertHTMLEqual( p.as_ul(), - """
  • Username:
  • -
  • Password:
  • -
  • Options:
  • """, + """ +
  • Username:
  • +
  • Password:
  • +
  • Options:
  • + """, ) def test_get_initial_for_field(self): @@ -2605,7 +2778,8 @@ Password: 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( @@ -2629,10 +2803,13 @@ Password: ) self.assertHTMLEqual( p.as_table(), - """Username:
    -e.g., user@example.com -Password:
    -Wählen Sie mit Bedacht.""", + """ + Username: +
    + e.g., user@example.com + Password: +
    + Wählen Sie mit Bedacht.""", ) # The help text is displayed whether or not data is provided for the form. @@ -2752,13 +2929,14 @@ Password: ) 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() @@ -2772,24 +2950,32 @@ Password: p = Person(data, prefix="person1") self.assertHTMLEqual( p.as_ul(), - """
  • -
  • -
  • -
  • -
  • -
  • """, + """ +
  • +
  • +
  • +
  • +
  • +
  • + """, ) self.assertHTMLEqual( str(p["first_name"]), - '', + '', ) self.assertHTMLEqual( str(p["last_name"]), - '', + '', ) self.assertHTMLEqual( str(p["birthday"]), - '', + '', ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) @@ -2861,12 +3047,17 @@ Password: p = Person(prefix="foo") self.assertHTMLEqual( p.as_ul(), - """
  • -
  • -
  • -
  • -
  • -
  • """, + """ +
  • +
  • +
  • +
  • +
  • +
  • + """, ) data = { "foo-prefix-first_name": "John", @@ -2981,15 +3172,16 @@ Password: ) 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(), - 'File1:', + "File1:" + '', ) f = FileForm(data={}, files={}, auto_id=False) @@ -3028,7 +3220,8 @@ Password: ) self.assertHTMLEqual( f.as_table(), - 'File1:', + "File1:" + '', ) self.assertTrue(f.is_valid()) @@ -3038,7 +3231,8 @@ Password: f = FileForm(data={}, files={"file1": file1}, auto_id=False) self.assertHTMLEqual( f.as_table(), - 'File1:', + "File1:" + '', ) # A required file field with initial data should not contain the @@ -3158,9 +3352,10 @@ Password: self.assertHTMLEqual( MyForm().as_table(), - '' - '' - '', + '' + '' + '' + "", ) def test_error_html_required_html_classes(self): @@ -3176,34 +3371,46 @@ Password: self.assertHTMLEqual( p.as_ul(), - """
    • This field is required.
    -
  • -
  • -
  • -
  • -
    • This field is required.
    -
  • """, + """ +
    • +
    • This field is required.
    + +
  • +
  • + +
  • +
  • +
  • +
    • +
    • This field is required.
    + +
  • """, ) self.assertHTMLEqual( p.as_p(), - """
    • This field is required.
    -

    -

    -

    -

    -

    -
    • This field is required.
    -

    -

    """, + """ +
    • This field is required.
    +

    + +

    +

    + +

    +

    +

    +
    • This field is required.
    +

    +

    + """, ) self.assertHTMLEqual( @@ -3481,10 +3688,14 @@ Password: self.assertHTMLEqual( form.as_p(), """ -

    Phone1:

    -

    Phone2:

    -

    Phone3:

    -

    Phone4:

    +

    Phone1: +

    +

    Phone2: +

    +

    Phone3: +

    +

    Phone4: +

    """, ) @@ -3694,7 +3905,8 @@ Password: control = [ '
  • foo
    • This field is required.
  • ', '
  • bar
    • This field is required.
  • ', - '
  • __all__
    • Non-field error.
  • ', + '
  • __all__
    • Non-field error.
    ' + "
  • ", ] for error in control: self.assertInHTML(error, errors) @@ -3798,10 +4010,14 @@ Password: ) self.assertHTMLEqual( p.as_p(), - """
    • (Hidden field last_name) This field is required.
    -

    - -

    """, + """ +
      +
    • (Hidden field last_name) This field is required.
    +

    + +

    + """, ) self.assertHTMLEqual( p.as_table(), @@ -3847,11 +4063,18 @@ Password: ) self.assertHTMLEqual( p.as_table(), - """
    • Generic validation error
    - - - -""", + """ +
      +
    • Generic validation error
    + + + + + + + """, ) def test_error_escaping(self): @@ -3868,7 +4091,8 @@ Password: form.is_valid() self.assertHTMLEqual( form.as_ul(), - '
    • (Hidden field hidden) Foo & "bar"!
  • ' + '
    • ' + "
    • (Hidden field hidden) Foo & "bar"!
  • " '
    • Foo & "bar"!
    ' ' ' '' @@ -3883,14 +4107,16 @@ Password: p = Person() self.assertEqual( repr(p), - "", + "", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertEqual( repr(p), - "", + "", ) p.is_valid() self.assertEqual( @@ -4003,9 +4229,12 @@ Password: form = MyForm() self.assertHTMLEqual( form.as_p(), - '

    ' - '

    ' - '

    " '

    form.as_ul(), '

  • ' '
  • ' - '
  • ' - '
  • " '
  • self.assertHTMLEqual( form.as_table(), '' - '' + '' + "" '' '' '' '" - '' '' '' "", @@ -4050,10 +4283,12 @@ Password: form = MyForm() self.assertHTMLEqual( form.as_p(), - '

    ' - '

    ' - '

    " + '

    ' + '

    ' + '

    ' + '

    ' + '

    ' + '

    ' '

    ) self.assertHTMLEqual( form.as_ul(), - '

  • ' - '
  • ' - '
  • " + '
  • ' + '
  • ' + '
  • ' + '
  • ' + '
  • ' + '
  • ' '
  • '' '' '' - '" - '' '' '' "", diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index 9846cb5874..87084102a5 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -657,7 +657,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 @@ -959,10 +960,13 @@ class FormsFormsetTestCase(SimpleTestCase): formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Fernet and Coke"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), - """ - - -""", + """ + + + + + """, ) def test_max_num_zero(self): @@ -988,10 +992,14 @@ class FormsFormsetTestCase(SimpleTestCase): formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), - """ - - -""", + """ + + + + + """, ) def test_more_initial_than_max_num(self): @@ -1010,12 +1018,20 @@ class FormsFormsetTestCase(SimpleTestCase): formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), - """ - - - - -""", + """ + + + + + + + + + + + """, ) def test_default_absolute_max(self): @@ -1093,10 +1109,13 @@ class FormsFormsetTestCase(SimpleTestCase): formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Gin Tonic"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), - """ - - -""", + """ + + + + + + """, ) def test_management_form_field_names(self): @@ -1539,7 +1558,8 @@ class FormsetAsTagTests(SimpleTestCase): self.formset.as_p(), self.management_form_html + ( - '

    Choice:

    ' + "

    Choice: " + '

    ' '

    Votes:

    ' ), ) @@ -1549,8 +1569,10 @@ class FormsetAsTagTests(SimpleTestCase): self.formset.as_ul(), self.management_form_html + ( - '
  • Choice:
  • ' - '
  • Votes:
  • ' + "
  • Choice: " + '
  • ' + "
  • Votes: " + '
  • ' ), ) @@ -1620,8 +1642,10 @@ class TestIsBoundBehavior(SimpleTestCase): "
  • (Hidden field TOTAL_FORMS) Enter a whole number.
  • " "
  • (Hidden field INITIAL_FORMS) Enter a whole number.
  • " "" - '' - '' + '' + '' '' '' "\n", diff --git a/tests/forms_tests/tests/test_i18n.py b/tests/forms_tests/tests/test_i18n.py index 777c84e4e4..2548ceb481 100644 --- a/tests/forms_tests/tests/test_i18n.py +++ b/tests/forms_tests/tests/test_i18n.py @@ -23,21 +23,25 @@ class FormsI18nTests(SimpleTestCase): self.assertHTMLEqual( f.as_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(), '

    ' - '

    ', + '

    ", ) with translation.override("pl"): self.assertHTMLEqual( f.as_p(), '

    ' - '

    ', + '

    ", ) def test_non_ascii_label(self): @@ -79,13 +83,13 @@ class FormsI18nTests(SimpleTestCase): "

    " '

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

    ", + ' Mies\n
    \n

    ", ) # Translated error messages @@ -98,13 +102,14 @@ class FormsI18nTests(SimpleTestCase): "\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.\n" "

    " '

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

    ", + ' Mies\n
    ' + '
    \n

    ', ) 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 59fd74f4c9..4338321af8 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), - """ - - - -""", + '\n' + '\n' + '\n' + '\n' + '', ) 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), - """ - - - -""", + '\n' + '\n' + '\n' + '\n' + '', ) # A widget can exist without a media definition @@ -78,18 +81,20 @@ class FormsMediaTestCase(SimpleTestCase): w1 = MyWidget1() self.assertEqual( str(w1.media), - """ - - - -""", + '\n' + '\n' + '\n' + '\n' + '', ) # Media objects can be interrogated by media type self.assertEqual( str(w1.media["css"]), - """ -""", + '\n' + '', ) self.assertEqual( @@ -126,23 +131,25 @@ class FormsMediaTestCase(SimpleTestCase): w3 = MyWidget3() self.assertEqual( str(w1.media + w2.media + w3.media), - """ - - - - - -""", + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '', ) # media addition hasn't affected the original objects self.assertEqual( str(w1.media), - """ - - - -""", + '\n' + '\n' + '\n' + '\n' + '', ) # 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), - """ - - - - - -""", + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '', ) 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), - """ - - - -""", + '\n' + '\n' + '\n' + '\n' + '', ) - # 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")} @@ -290,8 +301,8 @@ class FormsMediaTestCase(SimpleTestCase): ) 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")} @@ -338,7 +349,8 @@ class FormsMediaTestCase(SimpleTestCase): ) 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")} @@ -367,7 +379,8 @@ class FormsMediaTestCase(SimpleTestCase): ) def test_media_inheritance_single_type(self): - # A widget can enable inheritance of one media type by specifying extend as a tuple + # 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")} @@ -453,13 +466,14 @@ class FormsMediaTestCase(SimpleTestCase): mymulti = MyMultiWidget() self.assertEqual( str(mymulti.media), - """ - - - - - -""", + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '', ) def test_form_media(self): @@ -494,13 +508,14 @@ class FormsMediaTestCase(SimpleTestCase): f1 = MyForm() self.assertEqual( str(f1.media), - """ - - - - - -""", + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '', ) # Form media can be combined to produce a single media definition. @@ -510,13 +525,14 @@ class FormsMediaTestCase(SimpleTestCase): f2 = AnotherForm() self.assertEqual( str(f1.media + f2.media), - """ - - - - - -""", + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '', ) # Forms can also define media, following the same rules as widgets. @@ -531,15 +547,16 @@ class FormsMediaTestCase(SimpleTestCase): f3 = FormWithMedia() self.assertEqual( str(f3.media), - """ - - - - - - - -""", + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '\n' + '', ) # Media works in templates @@ -547,15 +564,16 @@ class FormsMediaTestCase(SimpleTestCase): Template("{{ form.media.js }}{{ form.media.css }}").render( Context({"form": f3}) ), - """ - - - -""" - """ - - -""", + '\n' + '\n' + '\n' + '\n' + '' + '\n' + '\n' + '\n' + '', ) 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])), '
    • Example of link: ' - "<a href="http://www.example.com/">example</a>
    ", + "<a href="http://www.example.com/">example</a>" + "", ) self.assertHTMLEqual( str(ErrorList([mark_safe(example)])), @@ -144,7 +145,8 @@ class FormsUtilsTestCase(SimpleTestCase): self.assertHTMLEqual( str(ErrorDict({"name": example})), '
    • nameExample of link: ' - "<a href="http://www.example.com/">example</a>
    ", + "<a href="http://www.example.com/">example</a>" + "", ) 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 5a860037e5..aba405db15 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(), - """

    -

    -

    -

    -

    -

    """, + """ +

    + + +

    +

    + + +

    +

    + + +

    +

    + + +

    + """, ) def test_initial_instance_value(self): @@ -136,30 +160,47 @@ class ModelFormCallableModelDefault(TestCase): ), } ).as_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(), - """

    -

    """, + """ +

    +

    +

    +

    + """, ) def test_empty_field_char_none(self): f = EmptyCharLabelNoneChoiceForm() self.assertHTMLEqual( f.as_p(), - """

    -

    -

    """, + """ +

    +

    +

    +

    + """, ) def test_save_empty_label_forms(self): @@ -367,13 +414,16 @@ class EmptyLabelTestCase(TestCase): f = EmptyIntegerLabelChoiceForm() self.assertHTMLEqual( f.as_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(), - """

    -

    -

    -

    """, + """ +

    + +

    +

    +

    + """, ) foo_model = ChoiceModel(name="foo-test", choice_integer=1) f = EmptyIntegerLabelChoiceForm(instance=foo_model) self.assertHTMLEqual( f.as_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=( - '' + '' ), ) diff --git a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py index 35db8192ef..89cd473638 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="""
    -
    -
    -
    -
    +
    +
    +
    +
    """, ) @@ -32,10 +36,14 @@ class CheckboxSelectMultipleTest(WidgetTest): ["J", "P"], html="""
    -
    -
    -
    -
    +
    +
    +
    +
    """, ) @@ -51,11 +59,16 @@ class CheckboxSelectMultipleTest(WidgetTest): None, html="""
    -
    -
    -
    -
    -
    +
    +
    +
    +
    +
    """, ) @@ -69,19 +82,24 @@ class CheckboxSelectMultipleTest(WidgetTest): html = """
    + Unknown +
    + + Vinyl
    + CD +
    + VHS +
    + DVD + """ @@ -101,15 +119,21 @@ class CheckboxSelectMultipleTest(WidgetTest): ) html = """
    -
    +
    -
    -
    +
    +
    -
    -
    +
    +
    """ @@ -128,11 +152,14 @@ class CheckboxSelectMultipleTest(WidgetTest): html = """
    - +
    -
    +
    - +
    """ @@ -154,11 +181,14 @@ class CheckboxSelectMultipleTest(WidgetTest): html = """
    - +
    -
    +
    - +
    """ @@ -174,8 +204,10 @@ class CheckboxSelectMultipleTest(WidgetTest): html = """
    -
    -
    +
    +
    """ self.check_html(self.widget(choices=choices), "numbers", None, html=html) @@ -186,8 +218,10 @@ class CheckboxSelectMultipleTest(WidgetTest): ] html = """
    -
    -
    +
    +
    """ 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: - something<div onclick="alert('oops')">.jpg - -
    - Change: - """ + Currently: + + something<div onclick="alert('oops')">.jpg + +
    + Change: + """ ), ) 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='', + html=( + '' + ), ) 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='', + html=( + '' + ), ) def test_render_attrs_multiple(self): @@ -41,7 +44,8 @@ class MultipleHiddenInputTest(WidgetTest): ["test@example.com", "foo@example.com"], attrs={"class": "fun"}, html=( - '\n' + '\n' '' ), ) @@ -53,15 +57,19 @@ class MultipleHiddenInputTest(WidgetTest): widget, "email", ["foo@example.com"], - html='', + html=( + '' + ), ) self.check_html( widget, "email", ["foo@example.com", "test@example.com"], html=( - '\n' - '' + '\n' + '' ), ) self.check_html( @@ -69,7 +77,10 @@ class MultipleHiddenInputTest(WidgetTest): "email", ["foo@example.com"], attrs={"class": "special"}, - html='', + html=( + '' + ), ) 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=( '' - '' + '' ), ) @@ -161,7 +162,8 @@ class MultiWidgetTest(WidgetTest): ["john", "lennon"], html=( '' - '' + '' ), ) 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", - '', + '', ) 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="""
    -
    +
    -
    +
    """, @@ -35,19 +37,28 @@ class RadioSelectTest(WidgetTest): html = """
    -
    +
    -
    -
    +
    +
    -
    +
    - -
    + """ @@ -68,11 +79,15 @@ class RadioSelectTest(WidgetTest): html = """
    - +
    -
    -
    -
    +
    +
    +
    """ self.check_html(widget, "beatle", "J", html=html) @@ -85,11 +100,15 @@ class RadioSelectTest(WidgetTest): html = """
    - +
    -
    -
    -
    +
    +
    +
    """ self.check_html( @@ -107,10 +126,15 @@ class RadioSelectTest(WidgetTest): """ html = """
    -
    -
    -
    -
    +
    +
    +
    +
    +
    """ self.check_html( @@ -131,8 +155,10 @@ class RadioSelectTest(WidgetTest): html = """
    -
    -
    +
    +
    """ self.check_html(self.widget(choices=choices), "number", None, html=html) @@ -143,8 +169,10 @@ class RadioSelectTest(WidgetTest): ] html = """
    -
    -
    +
    +
    """ self.check_html(self.widget(choices=choices), "time", None, html=html) @@ -158,11 +186,16 @@ class RadioSelectTest(WidgetTest): ["J"], html="""
    -
    -
    -
    -
    -
    +
    +
    +
    +
    +
    """, ) 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=( - """ + - - """ + + + """ ), ) 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=( - '' + '" ), ) @@ -57,6 +58,7 @@ class TextareaTest(WidgetTest): "msg", mark_safe("pre "quoted" value"), html=( - '' + '" ), ) 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='', + html=( + '' + ), ) def test_render_custom_attrs(self): @@ -57,7 +60,9 @@ class TextInputTest(WidgetTest): "email", "test@example.com", attrs={"class": "fun"}, - html='', + html=( + '' + ), ) def test_render_unicode(self): @@ -81,7 +86,9 @@ class TextInputTest(WidgetTest): widget, "email", "foo@example.com", - html='', + html=( + '' + ), ) 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), - """

    -

    - -

    """, + """ +

    +

    +

    + +

    + """, ) formset = GenericFormSet(instance=Animal()) self.assertHTMLEqual( "".join(form.as_p() for form in formset.forms), - """

    -

    -

    """, + """ +

    +

    +

    + +

    + """, ) platypus = Animal.objects.create( common_name="Platypus", @@ -63,32 +83,54 @@ id="id_generic_relations-taggeditem-content_type-object_id-0-id">

    """, tagged_item_id = TaggedItem.objects.get(tag="shiny", object_id=platypus.id).id self.assertHTMLEqual( "".join(form.as_p() for form in formset.forms), - """

    -

    -

    - -

    -

    -

    -

    - -

    """ + """ +

    +

    +

    + +

    +

    +

    +

    + +

    + """ % 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), - """

    -

    -

    -

    """, + """ +

    +

    +

    + +

    + """, ) def test_options(self): @@ -108,7 +150,9 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id">

    """ self.assertEqual(len(formset.forms), 5) self.assertHTMLEqual( formset.forms[0].as_p(), - '' % harmless.pk, ) @@ -166,7 +210,10 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id">

    """ 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 = " instance isn't saved. Use bulk=False or save the object first." + msg = ( + " 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 5fdceaa04a..a64900d097 100644 --- a/tests/get_object_or_404/tests.py +++ b/tests/get_object_or_404/tests.py @@ -88,19 +88,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('', 4326) 'SPHEROID["WGS 84",6378137,298.257223563, - # AUTHORITY["EPSG","7030"]]'); + # SELECT ST_length_spheroid( + # ST_GeomFromText('', 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 fae11cfea9..30c011f126 100644 --- a/tests/gis_tests/gdal_tests/test_ds.py +++ b/tests/gis_tests/gdal_tests/test_ds.py @@ -119,7 +119,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 @@ -194,8 +194,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( - '' + '' ' 0 0' "" ), 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 320d215482..8a2973cf00 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 = """Delete all Features""" - + delete_all_btn = ( + 'Delete all Features' + "" + ) 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'^' - r'-104.60925\d+,38.25500\d+ ' + r'^' + r'' + r"-104.60925\d+,38.25500\d+ " r"" ) 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 d37d826d39..4754f17c9b 100644 --- a/tests/gis_tests/geos_tests/test_geos.py +++ b/tests/gis_tests/geos_tests/test_geos.py @@ -807,7 +807,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) @@ -1496,7 +1497,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin): self.assertEqual( GEOSGeometry("POINT(0 0)"), GEOSGeometry.from_gml( - '' + '' ' 0 0' "" ), diff --git a/tests/gis_tests/inspectapp/tests.py b/tests/gis_tests/inspectapp/tests.py index 952124db8c..d9b3cf985f 100644 --- a/tests/gis_tests/inspectapp/tests.py +++ b/tests/gis_tests/inspectapp/tests.py @@ -132,7 +132,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" @@ -140,7 +141,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 = '' + expected = ( + '' + ) 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 = '' + expected = ( + '' + ) 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 5d46eeac52..c98bab382d 100644 --- a/tests/humanize_tests/tests.py +++ b/tests/humanize_tests/tests.py @@ -528,7 +528,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 c4aeef7339..c2ae10efd8 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 \n" + "License GPLv3+: GNU GPL version 3 or later " + "\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 aa77657471..45f0ea9a9b 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): '' '' '' - '' + '" '' '' - '' + '" "" '' + '' '
  • ' - '
  • ' + '' '
  • ' - '
  • ' + '" '
  • ' - '' + '' "
  • ", ) 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), - ';' - '', + ';' + '", ) self.assertHTMLEqual( template_as_text.render(context), - ';' - ' ', + ';' + '", ) self.assertHTMLEqual( template_as_hidden.render(context), - ';' - '', + ';' + '', ) def test_format_arbitrary_settings(self): @@ -1999,8 +2015,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 83dbfd406d..53c7ce9013 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( @@ -325,7 +331,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() @@ -390,7 +398,8 @@ class InspectDBTestCase(TestCase): """ out = StringIO() with mock.patch( - "django.db.connection.introspection.data_types_reverse.base_data_types_reverse", + "django.db.connection.introspection.data_types_reverse." + "base_data_types_reverse", { "text": "myfields.TextField", "bigint": "BigIntegerField", 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 1dc4e7e6be..5b4bb45ff8 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, ), @@ -1831,13 +1849,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", ), @@ -1870,14 +1894,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", ), @@ -1911,7 +1943,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", ), @@ -1985,7 +2020,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 e585e0e23a..aa12cdf8c7 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 acaf36d516..9f2e9d4b46 100644 --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -793,9 +793,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( [ @@ -976,7 +976,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 02d293f160..d5ad559e85 100644 --- a/tests/m2m_regress/tests.py +++ b/tests/m2m_regress/tests.py @@ -50,10 +50,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): """ - - %(p_pk)s - %(g_pk)s + + %(p_pk)s + %(g_pk)s 100 - + Bob - + Roll @@ -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 = "

    Firstname Sürname is a great guy.

    " 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 " + msg = ( + "'Publication' instance expected, got " + ) 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 = " instance isn't saved. Use bulk=False or save the object first." + msg = ( + " 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 e2e62378d3..c4b4d88844 100644 --- a/tests/messages_tests/test_cookie.py +++ b/tests/messages_tests/test_cookie.py @@ -92,7 +92,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 cadc8cef30..36c6ffb872 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, @@ -2361,7 +2362,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", ) ], @@ -2390,7 +2392,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", ) ], @@ -4058,7 +4061,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 099690aa30..b3d9972b0c 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -271,7 +271,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() @@ -488,7 +490,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) @@ -507,7 +510,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(), ) @@ -835,13 +839,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, @@ -851,12 +857,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"}) @@ -888,17 +896,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( @@ -1173,7 +1184,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() @@ -2203,7 +2217,8 @@ class MakeMigrationsTests(MigrationTestBase): " - add field rating to author\n" " - create model book\n" "\n" - "merging will only work if the operations printed above do not conflict\n" + "merging will only work if the operations printed above do not " + "conflict\n" "with each other (working on different fields or models)\n" "should these migration branches be merged? [y/n] ", ) @@ -2308,7 +2323,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") @@ -2512,7 +2530,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, ) @@ -2696,10 +2715,12 @@ class SquashMigrationsTests(MigrationTestBase): f"Created new squashed migration {squashed_migration_file}\n" f" You should commit this migration but leave the old ones in place;\n" f" the new migration will be used for new installs. Once you are sure\n" - f" all instances of the codebase have applied the migrations you squashed,\n" + f" all instances of the codebase have applied the migrations you " + f"squashed,\n" f" you can delete them.\n" f"Manual porting required\n" - f" Your migrations contained functions that must be manually copied over,\n" + f" Your migrations contained functions that must be manually copied " + f"over,\n" f" as we could not safely copy their implementation.\n" f" See the comment at the top of the squashed migration for details.\n", ) 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 52a798e22d..a84321ad3b 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 in CreateModel bases argument." + message = ( + "Found duplicate value 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 in CreateModel bases argument." + message = ( + "Found duplicate value 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: @@ -1772,7 +1783,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 @@ -2114,7 +2126,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" @@ -3278,7 +3290,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() @@ -3935,12 +3948,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%';" @@ -4182,7 +4200,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 0b45247bc5..56ad3a07cf 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", []), - """
    -
    -
    -
    -
    """ + """ +
    +
    +
    +
    + """ % (self.c1.pk, self.c2.pk, self.c3.pk), ) diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index dd397785a1..592bc693af 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"]), - '', + '", ) self.assertHTMLEqual( str(form["url"]), - '', + '", ) self.assertHTMLEqual( str(form["slug"]), @@ -1392,7 +1401,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." + ), } } @@ -1458,9 +1469,14 @@ class ModelFormBasicTests(TestCase): ) self.assertHTMLEqual( str(f.as_ul()), - """
  • -
  • -
  • """, + """ +
  • +
  • +
  • +
  • +
  • +
  • + """, ) self.assertHTMLEqual( str(f["name"]), @@ -1488,26 +1504,32 @@ class ModelFormBasicTests(TestCase): ) self.assertHTMLEqual( f.as_ul(), - """
  • Headline:
  • -
  • Slug:
  • -
  • Pub date:
  • -
  • Writer:
  • -
  • Article:
  • -
  • Categories:
  • -
  • Status:
  • """ + """ +
  • Headline: + +
  • +
  • Slug:
  • +
  • Pub date:
  • +
  • Writer:
  • +
  • Article: +
  • +
  • Categories:
  • +
  • Status:
  • + """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) @@ -1516,8 +1538,12 @@ class ModelFormBasicTests(TestCase): f = RoykoForm(auto_id=False, instance=self.w_royko) self.assertHTMLEqual( str(f), - """Name:
    - Use both first and last names.""", + """ + Name: + +
    + Use both first and last names. + """, ) art = Article.objects.create( @@ -1532,26 +1558,35 @@ class ModelFormBasicTests(TestCase): f = ArticleForm(auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), - """
  • Headline:
  • -
  • Slug:
  • -
  • Pub date:
  • -
  • Writer:
  • -
  • Article:
  • -
  • Categories:
  • -
  • Status:
  • """ + """ +
  • Headline: + +
  • +
  • Slug: + +
  • +
  • Pub date: +
  • +
  • Writer:
  • +
  • Article: +
  • +
  • Categories:
  • +
  • Status:
  • + """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) @@ -1574,7 +1609,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() @@ -1647,7 +1682,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"}) @@ -1666,26 +1702,32 @@ class ModelFormBasicTests(TestCase): f = ArticleForm(auto_id=False) self.assertHTMLEqual( str(f), - """Headline: -Slug: -Pub date: -Writer: -Article: -Categories: -Status:""" + """ + Headline: + + Slug: + + Pub date: + + Writer: + Article: + + Categories: + Status: + """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) @@ -1702,26 +1744,35 @@ class ModelFormBasicTests(TestCase): f = ArticleForm(auto_id=False, instance=new_art) self.assertHTMLEqual( f.as_ul(), - """
  • Headline:
  • -
  • Slug:
  • -
  • Pub date:
  • -
  • Writer:
  • -
  • Article:
  • -
  • Categories:
  • -
  • Status:
  • """ + """ +
  • Headline: + +
  • +
  • Slug: + +
  • +
  • Pub date: +
  • +
  • Writer:
  • +
  • Article: +
  • +
  • Categories:
  • +
  • Status:
  • + """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) @@ -1740,8 +1791,12 @@ class ModelFormBasicTests(TestCase): f = PartialArticleForm(auto_id=False) self.assertHTMLEqual( str(f), - """Headline: -Pub date:""", + """ + Headline: + + Pub date: + + """, ) class PartialArticleFormWithSlug(forms.ModelForm): @@ -1768,9 +1823,18 @@ class ModelFormBasicTests(TestCase): ) self.assertHTMLEqual( f.as_ul(), - """
  • Headline:
  • -
  • Slug:
  • -
  • Pub date:
  • """, + """ +
  • Headline: + +
  • +
  • Slug: + +
  • +
  • Pub date: +
  • + """, ) self.assertTrue(f.is_valid()) new_art = f.save() @@ -1797,7 +1861,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() @@ -1835,9 +1900,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) @@ -1961,7 +2026,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." ] }, ) @@ -2234,7 +2300,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__" @@ -2271,12 +2338,16 @@ class ModelOneToOneFieldTests(TestCase): form = WriterProfileForm() self.assertHTMLEqual( form.as_p(), - """

    -

    """ + """ +

    +

    +

    +

    + """ % ( self.w_woodward.pk, self.w_royko.pk, @@ -2294,13 +2365,16 @@ class ModelOneToOneFieldTests(TestCase): form = WriterProfileForm(instance=instance) self.assertHTMLEqual( form.as_p(), - """

    -

    -

    """ + """ +

    +

    +

    + +

    """ % ( self.w_woodward.pk, self.w_royko.pk, @@ -2508,7 +2582,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()) @@ -2615,8 +2690,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()) @@ -2712,7 +2788,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)}, @@ -2748,7 +2825,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." ] }, ) @@ -2797,7 +2875,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): @@ -2807,7 +2888,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): @@ -2948,11 +3029,15 @@ class OtherModelFormTests(TestCase): self.maxDiff = 1024 self.assertHTMLEqual( form.as_p(), - """

    -

    -

    """ + """ +

    + +

    +

    +

    + """ % {"blue_pk": colour.pk}, ) @@ -2969,19 +3054,27 @@ class OtherModelFormTests(TestCase): form.as_p(), """

    -

    + +

    - -

    + + +

    -

    -

    - + + + +

    +

    + + + """.format( today_str ), @@ -3025,7 +3118,8 @@ class ModelFormCustomErrorTests(SimpleTestCase): self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors["name1"]), - '

    • Model.clean() error messages (simpler syntax).
    ', + '
      ' + "
    • Model.clean() error messages (simpler syntax).
    ", ) data = {"name1": "GLOBAL_ERROR", "name2": "ABC"} form = CustomErrorMessageForm(data) @@ -3301,7 +3395,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 dbc06f3555..a456e1a65e 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(), '

    ' - ' ' + '' '

    ', ) @@ -229,14 +229,16 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '' + '' '

    ' % author2.id, ) self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' - '' + '' '

    ' % author1.id, ) @@ -313,8 +315,8 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[3].as_p(), '

    ' - '

    ' - '

    ' + '' + '

    ' '' '

    ', ) @@ -565,10 +567,11 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '

    ' - '

    ' + '' + '

    ' '' - '

    ', + '' + "

    ", ) data = { @@ -593,19 +596,22 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '

    ' + '

    ' '

    ' - '' - '

    ' - % hemingway_id, + '' + '

    ' % hemingway_id, ) self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' - '

    ' - '

    ' + '' + '

    ' '' - '

    ', + '' + "

    ", ) data = { @@ -637,24 +643,31 @@ class ModelFormsetTest(TestCase): self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), - '

    ' + '

    ' + '' + '' + '' "

    " % author.id, ) self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' - '' - '' + '' + '' '

    ' % author.id, ) self.assertHTMLEqual( formset.forms[2].as_p(), '

    ' - '' - '' + '' + '' '

    ' % author.id, ) @@ -693,8 +706,10 @@ class ModelFormsetTest(TestCase): '

    ' '' - '' - '

    ' + '' + '

    ' % ( author.id, book1.id, @@ -703,16 +718,20 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' - '' - '' + '' + '' '

    ' % author.id, ) self.assertHTMLEqual( formset.forms[2].as_p(), '

    ' - '' - '' + '' + '' '

    ' % author.id, ) @@ -782,7 +801,8 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '' + '' '' '

    ', ) @@ -790,7 +810,8 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[1].as_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): '

    ' '' - '' - '

    ', + '' + '' + "

    ", ) self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' '' - '' - '

    ', + '' + '' + "

    ", ) self.assertHTMLEqual( formset.forms[2].as_p(), '

    ' '' - '' - '

    ', + '' + '

    ', ) self.assertHTMLEqual( formset.forms[3].as_p(), '

    ' - '' - '' + '' + '' '

    ', ) self.assertHTMLEqual( formset.forms[4].as_p(), '

    ' - '' - '' + '' + '' '

    ', ) @@ -1022,21 +1062,27 @@ class ModelFormsetTest(TestCase): '

    ' '' - '' - '

    ', + '' + '

    ', ) self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' - '' - '' + '' + '' '

    ', ) self.assertHTMLEqual( formset.forms[2].as_p(), '

    ' - '' - '' + '' + '' '

    ', ) @@ -1103,10 +1149,12 @@ class ModelFormsetTest(TestCase): self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), - '

    ' + '

    ' + '

    ' '

    ' - '

    ', + '

    ', ) # Custom primary keys with ForeignKey, OneToOneField and AutoField ############ @@ -1121,16 +1169,22 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '' - '' - '

    ', + '' + '' + '

    ', ) self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' - '' - '' - '

    ', + '' + '' + '

    ', ) data = { @@ -1155,24 +1209,32 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '' - '' - '

    ' - % owner1.auto_id, + '' + '' + '

    ' % owner1.auto_id, ) self.assertHTMLEqual( formset.forms[1].as_p(), '

    ' - '' - '' - '

    ', + '' + '' + '

    ', ) self.assertHTMLEqual( formset.forms[2].as_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(), '

    ' - '' - '

    ' - % owner1.auto_id, + '' + '

    ' % owner1.auto_id, ) data = { @@ -1247,9 +1310,10 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '' - '

    ' - % owner1.auto_id, + '' + '

    ' % owner1.auto_id, ) data = { @@ -1282,11 +1346,15 @@ class ModelFormsetTest(TestCase): self.assertHTMLEqual( formset.forms[0].as_p(), '

    ' - '

    ' - '

    ' - '' - '' - '

    ', + '

    ' + '

    ' + '' + '' + '

    ', ) def test_foreign_keys_in_parents(self): @@ -1511,13 +1579,16 @@ class ModelFormsetTest(TestCase): '

    ' '' - '

    ' '

    ' - '' - '' - '

    ' - % person.id, + '' + '' + '

    ' % 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." ] } ], @@ -1996,7 +2074,8 @@ class TestModelFormsetOverridesTroughFormMeta(TestCase): form = PoetFormSet.form() self.assertHTMLEqual( str(form["name"]), - '', + '", ) def test_inlineformset_factory_widgets(self): @@ -2007,7 +2086,8 @@ class TestModelFormsetOverridesTroughFormMeta(TestCase): form = BookFormSet.form() self.assertHTMLEqual( str(form["title"]), - '', + '', ) 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 = " instance isn't saved. Use bulk=False or save the object first." + msg = ( + " 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 14b45f9b7f..377af41042 100644 --- a/tests/postgres_tests/test_constraints.py +++ b/tests/postgres_tests/test_constraints.py @@ -920,7 +920,8 @@ class ExclusionConstraintTests(PostgreSQLTestCase): ) 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 f57e7a7c80..100e570092 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 require 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: @@ -632,7 +633,8 @@ class SchemaTests(PostgreSQLTestCase): msg = "Covering SP-GiST indexes require PostgreSQL 14+." with self.assertRaisesMessage(NotSupportedError, msg): with mock.patch( - "django.db.backends.postgresql.features.DatabaseFeatures.supports_covering_spgist_indexes", + "django.db.backends.postgresql.features.DatabaseFeatures." + "supports_covering_spgist_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 7563b4ffff..aaef47d6be 100644 --- a/tests/postgres_tests/test_ranges.py +++ b/tests/postgres_tests/test_ranges.py @@ -550,13 +550,14 @@ 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, ' '"timestamps_closed_bounds": "{\\"upper\\": \\"2014-02-02T12:12:12+00:00\\", ' '\\"lower\\": \\"2014-01-01T00:00:00+00:00\\", \\"bounds\\": \\"()\\"}", ' - '"dates": "{\\"upper\\": \\"2014-02-02\\", \\"lower\\": \\"2014-01-01\\", \\"bounds\\": \\"[)\\"}", ' - '"dates_inner": null }, ' + '"dates": "{\\"upper\\": \\"2014-02-02\\", \\"lower\\": \\"2014-01-01\\", ' + '\\"bounds\\": \\"[)\\"}", "dates_inner": null }, ' '"model": "postgres_tests.rangesmodel", "pk": null}]' ) @@ -730,8 +731,10 @@ class TestFormField(PostgreSQLSimpleTestCase): - - + + """, ) @@ -751,10 +754,10 @@ class TestFormField(PostgreSQLSimpleTestCase): value="2010-01-01 11:13:00" id="id_datetime_field_0"> - - + + """, ) @@ -1074,11 +1077,13 @@ class TestWidget(PostgreSQLSimpleTestCase): f = pg_forms.ranges.DateTimeRangeField() self.assertHTMLEqual( f.widget.render("datetimerange", ""), - '', + '' + '', ) self.assertHTMLEqual( f.widget.render("datetimerange", None), - '', + '' + '', ) 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 ...: + # From uuid-pk model, prefetch + # ...: 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 ..: + # From integer-pk model, prefetch + # ..: 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 bc34bb870d..584e6d5475 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -541,7 +541,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()" @@ -1084,7 +1085,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 e1fd8b24b6..5fc3fe0096 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -907,7 +907,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): @@ -1475,7 +1476,10 @@ class Queries4Tests(TestCase): def test_ticket11811(self): unsaved_category = NamedCategory(name="Other") - msg = "Unsaved model instance cannot be used in an ORM query." + msg = ( + "Unsaved model instance cannot be used in an ORM " + "query." + ) with self.assertRaisesMessage(ValueError, msg): Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category) @@ -2441,7 +2445,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) @@ -4158,7 +4164,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 6be47efc8b..6d2d7d777a 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 4408dd92e5..330c8abd04 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -603,8 +603,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", @@ -695,7 +697,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 267a7c971b..208421eb64 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -1402,7 +1402,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): @@ -1466,7 +1467,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 9d73c59af9..58b4b04263 100644 --- a/tests/select_for_update/tests.py +++ b/tests/select_for_update/tests.py @@ -522,7 +522,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 = ( + '' + '' + ) with self.assertRaises(DTDForbidden): next(serializers.deserialize("xml", xml)) @@ -107,4 +110,4 @@ class XmlSerializerTransactionTestCase(
    Reference -""" +""" # NOQA diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py index 8778d6f7da..d995b36e04 100644 --- a/tests/serializers/tests.py +++ b/tests/serializers/tests.py @@ -54,7 +54,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 42e68df420..cac0e9bdc6 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -763,7 +763,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 57e9703546..4636e97330 100644 --- a/tests/signals/tests.py +++ b/tests/signals/tests.py @@ -422,7 +422,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 33a8ee5592..2865c77902 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 += "%s/testmodel/%s/" % (self.base_url, pk) expected_content = ( - """ - -%s - -""" - % expected - ) + '\n' + '\n' + "%s\n" + "" + ) % 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 = """ - -%s/testmodel/%s/2013-03-13 - -""" % ( + expected_content = ( + '\n' + '\n' + "%s/testmodel/%s/2013-03-13\n" + "" + ) % ( self.base_url, test_model.pk, ) diff --git a/tests/sitemaps_tests/test_http.py b/tests/sitemaps_tests/test_http.py index 76707e16e3..d1c345b53e 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 = """ - -%s/location/%snever0.5 - -""" % ( + expected_content = ( + '\n' + '\n' + "%s/location/%s" + "never0.5\n" + "" + ) % ( 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 = """ - -%s/location/%snever0.5 - -""" % ( + expected_content = ( + '\n' + '\n' + "%s/location/%s" + "never0.5\n" + "" + ) % ( self.base_url, date.today(), ) @@ -256,13 +262,13 @@ class HTTPSitemapTests(SitemapTestsBase): # doesn't raise an exception. response = self.client.get("/simple/sitemap.xml") expected_content = ( - """ - -http://testserver/location/%snever0.5 - -""" - % date.today() - ) + '\n' + '\n' + "http://testserver/location/%s" + "never0.5\n" + "" + ) % date.today() self.assertXMLEqual(response.content.decode(), expected_content) @ignore_warnings(category=RemovedInDjango50Warning) @@ -335,13 +341,15 @@ class HTTPSitemapTests(SitemapTestsBase): """ with self.assertNoLogs("django.template", "DEBUG"): response = self.client.get("/simple/i18n.xml") - expected_content = """ - -{0}/en/i18n/testmodel/{1}/never0.5{0}/pt/i18n/testmodel/{1}/never0.5 - -""".format( - self.base_url, self.i18n_model.pk - ) + expected_content = ( + '\n' + '\n' + "{0}/en/i18n/testmodel/{1}/never" + "0.5{0}/pt/i18n/testmodel/{1}/" + "never0.5\n" + "" + ).format(self.base_url, self.i18n_model.pk) self.assertXMLEqual(response.content.decode(), expected_content) @override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese"))) @@ -363,11 +371,13 @@ class HTTPSitemapTests(SitemapTestsBase): """.replace( "\n", "" ) - expected_content = f""" - -{expected_urls} - -""" + expected_content = ( + f'\n' + f'\n' + f"{expected_urls}\n" + f"" + ) self.assertXMLEqual(response.content.decode(), expected_content) @override_settings( @@ -391,11 +401,13 @@ class HTTPSitemapTests(SitemapTestsBase): """.replace( "\n", "" ) - expected_content = f""" - -{expected_urls} - -""" + expected_content = ( + f'\n' + f'\n' + f"{expected_urls}\n" + f"" + ) self.assertXMLEqual(response.content.decode(), expected_content) @override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese"))) @@ -419,19 +431,23 @@ class HTTPSitemapTests(SitemapTestsBase): """.replace( "\n", "" ) - expected_content = f""" - -{expected_urls} - -""" + expected_content = ( + f'\n' + f'\n' + f"{expected_urls}\n" + f"" + ) self.assertXMLEqual(response.content.decode(), expected_content) def test_sitemap_without_entries(self): response = self.client.get("/sitemap-without-entries/sitemap.xml") - expected_content = """ - - -""" + expected_content = ( + '\n' + '\n\n' + "" + ) self.assertXMLEqual(response.content.decode(), expected_content) def test_callable_sitemod_partial(self): @@ -448,11 +464,15 @@ class HTTPSitemapTests(SitemapTestsBase): http://example.com/simple/sitemap-callable-lastmod.xml """ - expected_content_sitemap = """ - - http://example.com/location/2013-03-13http://example.com/location/ - - """ + expected_content_sitemap = ( + '\n' + '\n' + "http://example.com/location/" + "2013-03-13" + "http://example.com/location/\n" + "" + ) self.assertXMLEqual(index_response.content.decode(), expected_content_index) self.assertXMLEqual(sitemap_response.content.decode(), expected_content_sitemap) @@ -474,11 +494,16 @@ class HTTPSitemapTests(SitemapTestsBase): http://example.com/simple/sitemap-callable-lastmod.xml2014-03-13T10:00:00 """ - expected_content_sitemap = """ - - http://example.com/location/2013-03-13http://example.com/location/2014-03-13 - - """ + expected_content_sitemap = ( + '\n' + '\n' + "http://example.com/location/" + "2013-03-13" + "http://example.com/location/" + "2014-03-13\n" + "" + ) self.assertXMLEqual(index_response.content.decode(), expected_content_index) self.assertXMLEqual(sitemap_response.content.decode(), expected_content_sitemap) @@ -494,7 +519,10 @@ class DeprecatedTests(SitemapTestsBase): ] ) def test_simple_sitemap_custom_index_warning(self): - msg = "Calling `__str__` on SitemapIndexItem is deprecated, use the `location` attribute instead." + msg = ( + "Calling `__str__` on SitemapIndexItem is deprecated, use the `location` " + "attribute instead." + ) with self.assertRaisesMessage(RemovedInDjango50Warning, msg): self.client.get("/simple/custom-index.xml") diff --git a/tests/sitemaps_tests/test_https.py b/tests/sitemaps_tests/test_https.py index e2923cf6f4..2eae71e4cc 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 = """ - -%s/location/%snever0.5 - -""" % ( + expected_content = ( + '\n' + '\n' + "%s/location/%s" + "never0.5\n" + "" + ) % ( self.base_url, date.today(), ) @@ -56,11 +59,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 = """ - -%s/location/%snever0.5 - -""" % ( + expected_content = ( + '\n' + '\n' + "%s/location/%s" + "never0.5\n" + "" + ) % ( 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 e83b50cd73..3aba9b5a1a 100644 --- a/tests/sitemaps_tests/test_utils.py +++ b/tests/sitemaps_tests/test_utils.py @@ -34,7 +34,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_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 513d0cf010..38c34c3f66 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 28a078effb..8b9d6556fe 100644 --- a/tests/template_tests/filter_tests/test_json_script.py +++ b/tests/template_tests/filter_tests/test_json_script.py @@ -12,7 +12,8 @@ class JsonScriptTests(SimpleTestCase): self.assertEqual( output, '", ) 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 html with disallowed tags' + 'some html with disallowed ' + " tags" ), 'some html with alert("You smell") disallowed tags', ) @@ -50,7 +54,8 @@ class FunctionTests(SimpleTestCase): self.assertEqual( striptags( lazystr( - 'some html with disallowed tags' + 'some html with disallowed ' + " 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("c") self.assertEqual( unordered_list([a, b, c]), - "\t
  • ulitem-a
  • \n\t
  • ulitem-b
  • \n\t
  • ulitem-<a>c</a>
  • ", + "\t
  • ulitem-a
  • \n\t
  • ulitem-b
  • \n\t" + "
  • ulitem-<a>c</a>
  • ", ) def item_generator(): @@ -134,7 +141,8 @@ class FunctionTests(SimpleTestCase): self.assertEqual( unordered_list(item_generator()), - "\t
  • ulitem-a
  • \n\t
  • ulitem-b
  • \n\t
  • ulitem-<a>c</a>
  • ", + "\t
  • ulitem-a
  • \n\t
  • ulitem-b
  • \n\t" + "
  • ulitem-<a>c</a>
  • ", ) def test_nested_generators(self): @@ -148,7 +156,8 @@ class FunctionTests(SimpleTestCase): self.assertEqual( unordered_list(item_generator()), - "\t
  • A\n\t
      \n\t\t
    • B
    • \n\t\t
    • C
    • \n\t
    \n\t
  • \n\t
  • D
  • ", + "\t
  • A\n\t
      \n\t\t
    • B
    • \n\t\t
    • C
    • \n\t
    \n\t
  • \n\t" + "
  • D
  • ", ) 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, - 'http://example.com/?x=&y= ' - 'http://example.com?x=&y=<2>', + '' + "http://example.com/?x=&y= " + '' + "http://example.com?x=&y=<2>", ) @setup({"urlize02": "{{ a|urlize }} {{ b|urlize }}"}) @@ -37,8 +41,10 @@ class UrlizeTests(SimpleTestCase): ) self.assertEqual( output, - 'http://example.com/?x=&y= ' - 'http://example.com?x=&y=', + '' + "http://example.com/?x=&y= " + '' + "http://example.com?x=&y=", ) @setup({"urlize03": "{% autoescape off %}{{ a|urlize }}{% endautoescape %}"}) @@ -95,7 +101,8 @@ class UrlizeTests(SimpleTestCase): ) self.assertEqual( output, - 'http://example.com/?x=&y=<2>', + '' + "http://example.com/?x=&y=<2>", ) @@ -127,11 +134,13 @@ class FunctionTests(SimpleTestCase): # part of URLs. self.assertEqual( urlize('www.server.com"abc'), - 'www.server.com"abc', + 'www.server.com"' + "abc", ) self.assertEqual( urlize("www.server.com'abc"), - 'www.server.com'abc', + 'www.server.com'' + "abc", ) self.assertEqual( urlize("www.server.com' - "http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B", + 'http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B' + "", ) def test_urlencoded(self): @@ -193,13 +203,13 @@ class FunctionTests(SimpleTestCase): """ self.assertEqual( urlize("https://en.wikipedia.org/wiki/Django_(web_framework)"), - '' - "https://en.wikipedia.org/wiki/Django_(web_framework)", + 'https://en.wikipedia.org/wiki/Django_(web_framework)', ) self.assertEqual( urlize("(see https://en.wikipedia.org/wiki/Django_(web_framework))"), - '(see ' - "https://en.wikipedia.org/wiki/Django_(web_framework))", + '(see https://en.wikipedia.org/wiki/Django_(web_framework))', ) def test_nofollow(self): @@ -269,25 +279,30 @@ class FunctionTests(SimpleTestCase): """ self.assertEqual( urlize("(Go to http://www.example.com/foo.)"), - '(Go to http://www.example.com/foo.)', + '(Go to ' + "http://www.example.com/foo.)", ) def test_trailing_multiple_punctuation(self): self.assertEqual( urlize("A test http://testing.com/example.."), - 'A test http://testing.com/example..', + 'A test ' + "http://testing.com/example..", ) self.assertEqual( urlize("A test http://testing.com/example!!"), - 'A test http://testing.com/example!!', + 'A test ' + "http://testing.com/example!!", ) self.assertEqual( urlize("A test http://testing.com/example!!!"), - 'A test http://testing.com/example!!!', + 'A test ' + "http://testing.com/example!!!", ) self.assertEqual( urlize('A test http://testing.com/example.,:;)"!'), - 'A test http://testing.com/example.,:;)"!', + 'A test ' + "http://testing.com/example.,:;)"!", ) def test_brackets(self): @@ -300,7 +315,8 @@ class FunctionTests(SimpleTestCase): ) self.assertEqual( urlize("see test[at[example.com"), - 'see test[at[example.com', + 'see ' + "test[at[example.com", ) 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 - + 'https://www.example.org/' - + end_out, + f'{start_out}' + f"https://www.example.org/{end_out}", ) def test_ipv4(self): self.assertEqual( urlize("http://192.168.0.15/api/9"), - 'http://192.168.0.15/api/9', + '' + "http://192.168.0.15/api/9", ) def test_ipv6(self): self.assertEqual( urlize("http://[2001:db8:cafe::2]/api/9"), - 'http://[2001:db8:cafe::2]/api/9', + '' + "http://[2001:db8:cafe::2]/api/9", ) 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 "hi@example.com", or phone us at +xx.yy', + 'Email us at "hi@example.com", 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 djangoproject.com! and enjoy.', + 'Go to djangoproject.com' + "! and enjoy.", ) self.assertEqual( urlize("Search for google.com/?q=! and see."), - 'Search for google.com/?q=! and see.', + 'Search for google.com/?q=' + "! and see.", ) self.assertEqual( urlize("Search for google.com/?q=dj!`? and see."), - 'Search for google.com/?q=dj!`? and see.', + 'Search for ' + "google.com/?q=dj!`? and see.", ) self.assertEqual( urlize("Search for google.com/?q=dj!`?! and see."), - 'Search for google.com/?q=dj!`?! and see.', + 'Search for ' + "google.com/?q=dj!`?! and see.", ) def test_non_string_input(self): @@ -406,13 +428,15 @@ class FunctionTests(SimpleTestCase): def test_autoescape(self): self.assertEqual( urlize('foobarbuz'), - 'foo<a href=" google.com ">bar</a>buz', + 'foo<a href=" google.com' + " ">bar</a>buz", ) def test_autoescape_off(self): self.assertEqual( urlize('foobarbuz', autoescape=False), - 'foogoogle.com ">barbuz', + 'foogoogle.com ">' + "barbuz", ) 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" http://… ' - '"Safe" http://…', + '"Unsafe" ' + 'http://… ' + ""Safe" " + 'http://…', ) @setup({"urlizetrunc02": '{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'}) @@ -36,8 +41,10 @@ class UrlizetruncTests(SimpleTestCase): ) self.assertEqual( output, - '"Unsafe" http://… ' - '"Safe" http://…', + '"Unsafe" ' + "http://… " + '"Safe" ' + "http://…", ) @@ -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, ), - 'http://www.google.c…', + 'http://www.google.c…', ) def test_non_string_input(self): @@ -85,11 +93,13 @@ class FunctionTests(SimpleTestCase): def test_autoescape(self): self.assertEqual( urlizetrunc('foobarbuz', 10), - 'foo<a href=" google.com ">bar</a>buz', + 'foo<a href=" google.com' + " ">bar</a>buz", ) def test_autoescape_off(self): self.assertEqual( urlizetrunc('foobarbuz', 9, autoescape=False), - 'foogoogle.c… ">barbuz', + 'foogoogle.c… ">' + "barbuz", ) 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 text {% endspaceless %}" + "spaceless01": ( + "{% spaceless %} text {% endspaceless %}" + ) } ) def test_spaceless01(self): @@ -15,7 +17,9 @@ class SpacelessTagTests(SimpleTestCase): @setup( { - "spaceless02": "{% spaceless %} \n text \n {% endspaceless %}" + "spaceless02": ( + "{% spaceless %} \n text \n {% endspaceless %}" + ) } ) def test_spaceless02(self): @@ -29,7 +33,9 @@ class SpacelessTagTests(SimpleTestCase): @setup( { - "spaceless04": "{% spaceless %} {{ text }} {% endspaceless %}" + "spaceless04": ( + "{% spaceless %} {{ text }} {% endspaceless %}" + ) } ) def test_spaceless04(self): @@ -49,7 +55,9 @@ class SpacelessTagTests(SimpleTestCase): @setup( { - "spaceless06": "{% spaceless %} {{ text|safe }} {% endspaceless %}" + "spaceless06": ( + "{% spaceless %} {{ text|safe }} {% 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"ed.html" %}' + "static-statictag05": ( + '{% load static %}{% static "special?chars"ed.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 ea096efda4..8fcf3e046d 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -238,7 +238,8 @@ class ClientTest(TestCase): def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """ - BlinkMalcolm Gladwell + BlinkMalcolm Gladwell + """ response = self.client.post( "/raw_post_view/", test_doc, content_type="text/xml" @@ -587,7 +588,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/") @@ -784,7 +788,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 7e8b3b43da..11f63f8731 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): @@ -782,7 +802,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( @@ -799,7 +820,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( @@ -838,11 +860,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( @@ -855,7 +881,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 " @@ -873,7 +902,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, @@ -885,11 +917,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( @@ -902,7 +938,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 " @@ -920,7 +959,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( @@ -1421,7 +1463,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") @@ -1504,7 +1547,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 f264ad52f8..fd36f0ab89 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 72183838b7..c755d356ee 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -804,7 +804,7 @@ class HTMLEqualTests(SimpleTestCase): -""", +""", # NOQA """ @@ -2023,8 +2023,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() @@ -2032,8 +2032,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 3215ecb175..342434666e 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 c128c52f69..222a1c5835 100644 --- a/tests/user_commands/tests.py +++ b/tests/user_commands/tests.py @@ -150,7 +150,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 c38a16de40..dc86925e8d 100644 --- a/tests/utils_tests/test_html.py +++ b/tests/utils_tests/test_html.py @@ -183,24 +183,28 @@ class TestUtilsHtml(SimpleTestCase): ( ( "&<>", - '', + '', ) ), # "<", ">" and "&" are quoted inside JSON objects ( {"a": ""}, '', + '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' + "", ), # Lazy strings are quoted ( lazystr("&<>"), - '', + '", ), ( {"a": lazystr("")}, '', + '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}' + "", ), ) for arg, expected in tests: @@ -228,11 +232,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/"), ) @@ -297,11 +304,13 @@ class TestUtilsHtml(SimpleTestCase): tests = ( ( "Search for google.com/?q=! and see.", - 'Search for google.com/?q=! and see.', + 'Search for google.com/?q=! and ' + "see.", ), ( "Search for google.com/?q=1<! and see.", - 'Search for google.com/?q=1<! and see.', + 'Search for google.com/?q=1<' + "! 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 && "" || mot ? z:/x:3;x<5;y" || mot ? z:/x:3;x<5;y" || mot ? z/x:3;x<5;y" || mot ? z/x:3;x<5;yThe quick brown fox jumped over the lazy dog.

    ' + '

    The quick brown fox jumped over the lazy dog.' + "

    " ) self.assertEqual( - '

    The quick brown fox jumped over the lazy dog.

    ', + '

    The quick brown fox jumped over the lazy dog.' + "

    ", truncator.words(10, html=True), ) self.assertEqual( @@ -143,7 +145,8 @@ class TestUtilsText(SimpleTestCase): # Test with new line inside tag truncator = text.Truncator( - '

    The quick brown fox jumped over the lazy dog.

    ' + '

    The quick brown fox jumped over ' + "the lazy dog.

    " ) self.assertEqual( '

    The quick brown…

    ', 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 1bf395ce37..5a07131349 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 }})." + ), }, ), ], @@ -259,13 +262,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 - # '
    ', not '
    ', + # not '
    ', response.content @@ -274,8 +279,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): @@ -791,7 +796,8 @@ class ExceptionReporterTests(SimpleTestCase): html, ) self.assertIn( - '"generated", line 2, in funcName\n <source code not available>', + '"generated", line 2, in funcName\n' + " <source code not available>", html, ) text = reporter.get_traceback_text() @@ -903,7 +909,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( - '
    '<p>Local variable</p>'
    ', + '
    '<p>Local variable</p>'
    ' + "", 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 6c8e0f8c91..3aacded7c6 100644 --- a/tests/view_tests/tests/test_i18n.py +++ b/tests/view_tests/tests/test_i18n.py @@ -518,7 +518,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 43057af3a1..a9eeee3cd2 100644 --- a/tests/view_tests/views.py +++ b/tests/view_tests/views.py @@ -149,9 +149,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: @@ -167,9 +167,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: @@ -185,9 +185,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: @@ -259,9 +259,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 @@ -299,9 +299,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: @@ -318,9 +318,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!", ], )