summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--django/apps/registry.py6
-rw-r--r--django/conf/global_settings.py7
-rw-r--r--django/contrib/admin/checks.py45
-rw-r--r--django/contrib/admin/models.py3
-rw-r--r--django/contrib/admin/options.py21
-rw-r--r--django/contrib/admin/templatetags/log.py2
-rw-r--r--django/contrib/auth/__init__.py6
-rw-r--r--django/contrib/auth/checks.py13
-rw-r--r--django/contrib/auth/management/commands/changepassword.py5
-rw-r--r--django/contrib/auth/migrations/0001_initial.py22
-rw-r--r--django/contrib/auth/migrations/0004_alter_user_username_opts.py5
-rw-r--r--django/contrib/auth/migrations/0007_alter_validators_add_error_messages.py5
-rw-r--r--django/contrib/auth/migrations/0008_alter_user_username_max_length.py5
-rw-r--r--django/contrib/auth/mixins.py11
-rw-r--r--django/contrib/auth/models.py3
-rw-r--r--django/contrib/auth/password_validation.py11
-rw-r--r--django/contrib/contenttypes/admin.py7
-rw-r--r--django/contrib/contenttypes/models.py5
-rw-r--r--django/contrib/flatpages/forms.py3
-rw-r--r--django/contrib/flatpages/migrations/0001_initial.py9
-rw-r--r--django/contrib/gis/db/backends/base/operations.py6
-rw-r--r--django/contrib/gis/db/backends/oracle/features.py3
-rw-r--r--django/contrib/gis/db/backends/oracle/operations.py8
-rw-r--r--django/contrib/gis/db/backends/oracle/schema.py5
-rw-r--r--django/contrib/gis/db/backends/postgis/const.py4
-rw-r--r--django/contrib/gis/db/backends/postgis/introspection.py4
-rw-r--r--django/contrib/gis/db/backends/postgis/operations.py6
-rw-r--r--django/contrib/gis/db/models/functions.py6
-rw-r--r--django/contrib/gis/db/models/lookups.py6
-rw-r--r--django/contrib/gis/gdal/geometries.py2
-rw-r--r--django/contrib/gis/gdal/layer.py8
-rw-r--r--django/contrib/gis/gdal/srs.py3
-rw-r--r--django/contrib/gis/geos/polygon.py6
-rw-r--r--django/contrib/gis/management/commands/ogrinspect.py4
-rw-r--r--django/contrib/gis/serializers/geojson.py6
-rw-r--r--django/contrib/gis/sitemaps/kml.py3
-rw-r--r--django/contrib/gis/utils/layermapping.py6
-rw-r--r--django/contrib/gis/utils/ogrinspect.py4
-rw-r--r--django/contrib/humanize/templatetags/humanize.py3
-rw-r--r--django/contrib/postgres/constraints.py5
-rw-r--r--django/contrib/postgres/fields/ranges.py3
-rw-r--r--django/contrib/postgres/operations.py5
-rw-r--r--django/contrib/postgres/validators.py12
-rw-r--r--django/contrib/redirects/migrations/0001_initial.py8
-rw-r--r--django/contrib/redirects/models.py3
-rw-r--r--django/contrib/sitemaps/__init__.py3
-rw-r--r--django/contrib/sitemaps/views.py5
-rw-r--r--django/contrib/sites/managers.py3
-rw-r--r--django/contrib/staticfiles/management/commands/collectstatic.py8
-rw-r--r--django/core/cache/backends/memcached.py3
-rw-r--r--django/core/checks/security/csrf.py4
-rw-r--r--django/core/files/locks.py2
-rw-r--r--django/core/files/storage.py3
-rw-r--r--django/core/files/uploadhandler.py5
-rw-r--r--django/core/handlers/base.py3
-rw-r--r--django/core/management/base.py10
-rw-r--r--django/core/management/commands/compilemessages.py4
-rw-r--r--django/core/management/commands/createcachetable.py5
-rw-r--r--django/core/management/commands/dbshell.py5
-rw-r--r--django/core/management/commands/diffsettings.py4
-rw-r--r--django/core/management/commands/dumpdata.py12
-rw-r--r--django/core/management/commands/flush.py3
-rw-r--r--django/core/management/commands/inspectdb.py23
-rw-r--r--django/core/management/commands/loaddata.py13
-rw-r--r--django/core/management/commands/makemessages.py21
-rw-r--r--django/core/management/commands/makemigrations.py3
-rw-r--r--django/core/management/commands/migrate.py17
-rw-r--r--django/core/management/commands/sendtestemail.py5
-rw-r--r--django/core/management/commands/shell.py15
-rw-r--r--django/core/management/commands/showmigrations.py6
-rw-r--r--django/core/management/commands/sqlflush.py5
-rw-r--r--django/core/management/commands/sqlmigrate.py13
-rw-r--r--django/core/management/commands/sqlsequencereset.py5
-rw-r--r--django/core/management/commands/squashmigrations.py29
-rw-r--r--django/core/management/commands/test.py5
-rw-r--r--django/core/validators.py28
-rw-r--r--django/db/backends/base/base.py9
-rw-r--r--django/db/backends/base/introspection.py9
-rw-r--r--django/db/backends/base/operations.py21
-rw-r--r--django/db/backends/base/schema.py26
-rw-r--r--django/db/backends/mysql/base.py6
-rw-r--r--django/db/backends/mysql/features.py36
-rw-r--r--django/db/backends/mysql/introspection.py3
-rw-r--r--django/db/backends/mysql/operations.py11
-rw-r--r--django/db/backends/mysql/validation.py3
-rw-r--r--django/db/backends/oracle/base.py27
-rw-r--r--django/db/backends/oracle/creation.py16
-rw-r--r--django/db/backends/oracle/features.py15
-rw-r--r--django/db/backends/oracle/introspection.py27
-rw-r--r--django/db/backends/oracle/operations.py12
-rw-r--r--django/db/backends/oracle/schema.py6
-rw-r--r--django/db/backends/postgresql/features.py3
-rw-r--r--django/db/backends/postgresql/introspection.py45
-rw-r--r--django/db/backends/postgresql/operations.py15
-rw-r--r--django/db/backends/postgresql/schema.py6
-rw-r--r--django/db/backends/sqlite3/_functions.py10
-rw-r--r--django/db/backends/sqlite3/features.py30
-rw-r--r--django/db/backends/sqlite3/introspection.py9
-rw-r--r--django/db/backends/sqlite3/operations.py7
-rw-r--r--django/db/backends/sqlite3/schema.py9
-rw-r--r--django/db/migrations/autodetector.py18
-rw-r--r--django/db/migrations/executor.py4
-rw-r--r--django/db/migrations/migration.py9
-rw-r--r--django/db/migrations/state.py14
-rw-r--r--django/db/models/base.py11
-rw-r--r--django/db/models/fields/__init__.py3
-rw-r--r--django/db/models/fields/files.py3
-rw-r--r--django/db/models/fields/related.py42
-rw-r--r--django/db/models/fields/related_descriptors.py17
-rw-r--r--django/db/models/fields/related_lookups.py5
-rw-r--r--django/db/models/fields/reverse_related.py6
-rw-r--r--django/db/models/functions/comparison.py3
-rw-r--r--django/db/models/indexes.py3
-rw-r--r--django/db/models/manager.py3
-rw-r--r--django/db/models/options.py4
-rw-r--r--django/db/models/query.py3
-rw-r--r--django/db/models/sql/compiler.py31
-rw-r--r--django/db/models/sql/datastructures.py3
-rw-r--r--django/db/models/sql/query.py3
-rw-r--r--django/forms/models.py13
-rw-r--r--django/http/multipartparser.py13
-rw-r--r--django/http/request.py11
-rw-r--r--django/template/defaulttags.py20
-rw-r--r--django/template/loader_tags.py3
-rw-r--r--django/templatetags/i18n.py13
-rw-r--r--django/templatetags/static.py3
-rw-r--r--django/templatetags/tz.py3
-rw-r--r--django/test/testcases.py51
-rw-r--r--django/test/utils.py5
-rw-r--r--django/urls/resolvers.py6
-rw-r--r--django/utils/asyncio.py5
-rw-r--r--django/utils/dateformat.py5
-rw-r--r--django/utils/deconstruct.py4
-rw-r--r--django/utils/feedgenerator.py5
-rw-r--r--django/utils/formats.py3
-rw-r--r--django/utils/translation/trans_real.py11
-rw-r--r--django/views/csrf.py2
-rw-r--r--django/views/defaults.py3
-rw-r--r--django/views/i18n.py2
-rw-r--r--docs/_ext/djangodocs.py3
-rw-r--r--docs/conf.py2
-rw-r--r--tests/admin_changelist/tests.py3
-rw-r--r--tests/admin_checks/tests.py11
-rw-r--r--tests/admin_docs/test_views.py20
-rw-r--r--tests/admin_filters/tests.py5
-rw-r--r--tests/admin_inlines/tests.py84
-rw-r--r--tests/admin_registration/tests.py5
-rw-r--r--tests/admin_scripts/tests.py467
-rw-r--r--tests/admin_utils/tests.py3
-rw-r--r--tests/admin_views/test_actions.py9
-rw-r--r--tests/admin_views/tests.py214
-rw-r--r--tests/admin_widgets/tests.py47
-rw-r--r--tests/aggregation/tests.py26
-rw-r--r--tests/aggregation_regress/tests.py43
-rw-r--r--tests/annotations/tests.py10
-rw-r--r--tests/app_loading/tests.py20
-rw-r--r--tests/apps/tests.py5
-rw-r--r--tests/auth_tests/test_checks.py10
-rw-r--r--tests/auth_tests/test_forms.py49
-rw-r--r--tests/auth_tests/test_hashers.py3
-rw-r--r--tests/auth_tests/test_management.py26
-rw-r--r--tests/auth_tests/test_views.py5
-rw-r--r--tests/auth_tests/urls.py4
-rw-r--r--tests/backends/mysql/tests.py3
-rw-r--r--tests/backends/oracle/tests.py6
-rw-r--r--tests/backends/test_utils.py5
-rw-r--r--tests/backends/tests.py12
-rw-r--r--tests/basic/tests.py5
-rw-r--r--tests/cache/tests.py15
-rw-r--r--tests/check_framework/test_model_field_deprecation.py5
-rw-r--r--tests/check_framework/test_security.py4
-rw-r--r--tests/check_framework/test_translation.py5
-rw-r--r--tests/check_framework/test_urls.py18
-rw-r--r--tests/contenttypes_tests/test_checks.py7
-rw-r--r--tests/csrf_tests/tests.py8
-rw-r--r--tests/csrf_tests/views.py4
-rw-r--r--tests/custom_lookups/tests.py27
-rw-r--r--tests/db_functions/datetime/test_extract_trunc.py5
-rw-r--r--tests/db_functions/text/test_sha224.py4
-rw-r--r--tests/db_functions/text/test_sha256.py4
-rw-r--r--tests/db_functions/text/test_sha384.py18
-rw-r--r--tests/delete/tests.py8
-rw-r--r--tests/delete_regress/tests.py4
-rw-r--r--tests/expressions/tests.py10
-rw-r--r--tests/expressions_window/tests.py3
-rw-r--r--tests/extra_regress/tests.py3
-rw-r--r--tests/file_storage/tests.py5
-rw-r--r--tests/file_uploads/tests.py23
-rw-r--r--tests/files/tests.py3
-rw-r--r--tests/filtered_relation/tests.py4
-rw-r--r--tests/fixtures/tests.py564
-rw-r--r--tests/fixtures_regress/tests.py39
-rw-r--r--tests/flatpages_tests/test_csrf.py10
-rw-r--r--tests/flatpages_tests/test_forms.py8
-rw-r--r--tests/flatpages_tests/test_middleware.py10
-rw-r--r--tests/flatpages_tests/test_templatetags.py18
-rw-r--r--tests/flatpages_tests/test_views.py10
-rw-r--r--tests/foreign_object/test_forms.py3
-rw-r--r--tests/foreign_object/tests.py16
-rw-r--r--tests/forms_tests/field_tests/test_booleanfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_decimalfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_emailfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_floatfield.py6
-rw-r--r--tests/forms_tests/field_tests/test_multivaluefield.py9
-rw-r--r--tests/forms_tests/field_tests/test_nullbooleanfield.py9
-rw-r--r--tests/forms_tests/models.py7
-rw-r--r--tests/forms_tests/tests/test_forms.py919
-rw-r--r--tests/forms_tests/tests/test_formsets.py72
-rw-r--r--tests/forms_tests/tests/test_i18n.py37
-rw-r--r--tests/forms_tests/tests/test_input_formats.py50
-rw-r--r--tests/forms_tests/tests/test_media.py192
-rw-r--r--tests/forms_tests/tests/test_utils.py6
-rw-r--r--tests/forms_tests/tests/tests.py234
-rw-r--r--tests/forms_tests/widget_tests/test_checkboxinput.py3
-rw-r--r--tests/forms_tests/widget_tests/test_checkboxselectmultiple.py100
-rw-r--r--tests/forms_tests/widget_tests/test_clearablefileinput.py14
-rw-r--r--tests/forms_tests/widget_tests/test_datetimeinput.py5
-rw-r--r--tests/forms_tests/widget_tests/test_multiplehiddeninput.py23
-rw-r--r--tests/forms_tests/widget_tests/test_multiwidget.py6
-rw-r--r--tests/forms_tests/widget_tests/test_numberinput.py3
-rw-r--r--tests/forms_tests/widget_tests/test_radioselect.py91
-rw-r--r--tests/forms_tests/widget_tests/test_select.py12
-rw-r--r--tests/forms_tests/widget_tests/test_selectdatewidget.py3
-rw-r--r--tests/forms_tests/widget_tests/test_textarea.py6
-rw-r--r--tests/forms_tests/widget_tests/test_textinput.py13
-rw-r--r--tests/generic_inline_admin/tests.py38
-rw-r--r--tests/generic_relations/test_forms.py123
-rw-r--r--tests/generic_relations/tests.py8
-rw-r--r--tests/generic_views/test_dates.py15
-rw-r--r--tests/get_object_or_404/tests.py15
-rw-r--r--tests/get_or_create/tests.py5
-rw-r--r--tests/gis_tests/distapp/tests.py45
-rw-r--r--tests/gis_tests/gdal_tests/test_ds.py7
-rw-r--r--tests/gis_tests/gdal_tests/test_geom.py3
-rw-r--r--tests/gis_tests/gdal_tests/test_raster.py15
-rw-r--r--tests/gis_tests/gdal_tests/test_srs.py30
-rw-r--r--tests/gis_tests/geoadmin_deprecated/tests.py14
-rw-r--r--tests/gis_tests/geoapp/test_functions.py24
-rw-r--r--tests/gis_tests/geoapp/tests.py10
-rw-r--r--tests/gis_tests/geogapp/tests.py5
-rw-r--r--tests/gis_tests/geos_tests/test_geos.py6
-rw-r--r--tests/gis_tests/inspectapp/tests.py6
-rw-r--r--tests/gis_tests/layermap/models.py3
-rw-r--r--tests/gis_tests/layermap/tests.py5
-rw-r--r--tests/gis_tests/relatedapp/tests.py18
-rw-r--r--tests/gis_tests/test_geoforms.py3
-rw-r--r--tests/gis_tests/test_spatialrefsys.py14
-rw-r--r--tests/handlers/tests.py12
-rw-r--r--tests/httpwrappers/tests.py10
-rw-r--r--tests/humanize_tests/tests.py3
-rw-r--r--tests/i18n/patterns/tests.py20
-rw-r--r--tests/i18n/test_extraction.py17
-rw-r--r--tests/i18n/test_percents.py31
-rw-r--r--tests/i18n/tests.py54
-rw-r--r--tests/indexes/tests.py3
-rw-r--r--tests/inline_formsets/tests.py5
-rw-r--r--tests/inspectdb/tests.py21
-rw-r--r--tests/invalid_models_tests/test_deprecated_fields.py6
-rw-r--r--tests/invalid_models_tests/test_models.py9
-rw-r--r--tests/invalid_models_tests/test_ordinary_fields.py3
-rw-r--r--tests/invalid_models_tests/test_relative_fields.py74
-rw-r--r--tests/logging_tests/tests.py6
-rw-r--r--tests/lookup/tests.py11
-rw-r--r--tests/m2m_regress/tests.py9
-rw-r--r--tests/m2m_through_regress/tests.py36
-rw-r--r--tests/mail/tests.py23
-rw-r--r--tests/managers_regress/tests.py3
-rw-r--r--tests/many_to_many/tests.py5
-rw-r--r--tests/many_to_one/tests.py17
-rw-r--r--tests/messages_tests/test_api.py5
-rw-r--r--tests/messages_tests/test_cookie.py3
-rw-r--r--tests/middleware/tests.py10
-rw-r--r--tests/middleware_exceptions/tests.py3
-rw-r--r--tests/migrations/test_autodetector.py13
-rw-r--r--tests/migrations/test_commands.py53
-rw-r--r--tests/migrations/test_graph.py27
-rw-r--r--tests/migrations/test_loader.py10
-rw-r--r--tests/migrations/test_operations.py47
-rw-r--r--tests/migrations/test_optimizer.py6
-rw-r--r--tests/migrations/test_state.py28
-rw-r--r--tests/migrations/test_writer.py6
-rw-r--r--tests/model_fields/test_durationfield.py5
-rw-r--r--tests/model_fields/test_foreignkey.py8
-rw-r--r--tests/model_forms/test_modelchoicefield.py27
-rw-r--r--tests/model_forms/tests.py384
-rw-r--r--tests/model_formsets/tests.py284
-rw-r--r--tests/model_formsets_regress/tests.py10
-rw-r--r--tests/model_regress/tests.py2
-rw-r--r--tests/modeladmin/test_checks.py19
-rw-r--r--tests/multiple_database/tests.py53
-rw-r--r--tests/null_queries/tests.py5
-rw-r--r--tests/one_to_one/tests.py10
-rw-r--r--tests/pagination/tests.py5
-rw-r--r--tests/postgres_tests/test_array.py38
-rw-r--r--tests/postgres_tests/test_constraints.py3
-rw-r--r--tests/postgres_tests/test_indexes.py6
-rw-r--r--tests/postgres_tests/test_introspection.py15
-rw-r--r--tests/postgres_tests/test_ranges.py27
-rw-r--r--tests/prefetch_related/test_uuid.py6
-rw-r--r--tests/prefetch_related/tests.py6
-rw-r--r--tests/proxy_models/tests.py10
-rw-r--r--tests/queries/tests.py14
-rw-r--r--tests/raw_query/tests.py13
-rw-r--r--tests/requests/test_data_upload_settings.py3
-rw-r--r--tests/requests/tests.py13
-rwxr-xr-xtests/runtests.py9
-rw-r--r--tests/schema/tests.py6
-rw-r--r--tests/select_for_update/tests.py5
-rw-r--r--tests/select_related/tests.py9
-rw-r--r--tests/serializers/test_xml.py7
-rw-r--r--tests/serializers/tests.py5
-rw-r--r--tests/sessions_tests/tests.py3
-rw-r--r--tests/signals/tests.py5
-rw-r--r--tests/sitemaps_tests/test_generic.py25
-rw-r--r--tests/sitemaps_tests/test_http.py136
-rw-r--r--tests/sitemaps_tests/test_https.py26
-rw-r--r--tests/sitemaps_tests/test_utils.py5
-rw-r--r--tests/staticfiles_tests/test_checks.py5
-rw-r--r--tests/staticfiles_tests/test_management.py12
-rw-r--r--tests/staticfiles_tests/test_storage.py3
-rw-r--r--tests/template_backends/test_django.py8
-rw-r--r--tests/template_tests/filter_tests/test_addslashes.py5
-rw-r--r--tests/template_tests/filter_tests/test_autoescape.py8
-rw-r--r--tests/template_tests/filter_tests/test_capfirst.py5
-rw-r--r--tests/template_tests/filter_tests/test_center.py5
-rw-r--r--tests/template_tests/filter_tests/test_chaining.py22
-rw-r--r--tests/template_tests/filter_tests/test_cut.py12
-rw-r--r--tests/template_tests/filter_tests/test_default.py4
-rw-r--r--tests/template_tests/filter_tests/test_escape.py4
-rw-r--r--tests/template_tests/filter_tests/test_first.py4
-rw-r--r--tests/template_tests/filter_tests/test_floatformat.py5
-rw-r--r--tests/template_tests/filter_tests/test_force_escape.py17
-rw-r--r--tests/template_tests/filter_tests/test_json_script.py3
-rw-r--r--tests/template_tests/filter_tests/test_length_is.py24
-rw-r--r--tests/template_tests/filter_tests/test_linebreaks.py5
-rw-r--r--tests/template_tests/filter_tests/test_linebreaksbr.py5
-rw-r--r--tests/template_tests/filter_tests/test_linenumbers.py5
-rw-r--r--tests/template_tests/filter_tests/test_ljust.py5
-rw-r--r--tests/template_tests/filter_tests/test_lower.py4
-rw-r--r--tests/template_tests/filter_tests/test_make_list.py5
-rw-r--r--tests/template_tests/filter_tests/test_phone2numeric.py5
-rw-r--r--tests/template_tests/filter_tests/test_random.py4
-rw-r--r--tests/template_tests/filter_tests/test_rjust.py5
-rw-r--r--tests/template_tests/filter_tests/test_safeseq.py5
-rw-r--r--tests/template_tests/filter_tests/test_slice.py5
-rw-r--r--tests/template_tests/filter_tests/test_slugify.py4
-rw-r--r--tests/template_tests/filter_tests/test_stringformat.py5
-rw-r--r--tests/template_tests/filter_tests/test_striptags.py11
-rw-r--r--tests/template_tests/filter_tests/test_truncatewords.py5
-rw-r--r--tests/template_tests/filter_tests/test_unordered_list.py21
-rw-r--r--tests/template_tests/filter_tests/test_upper.py4
-rw-r--r--tests/template_tests/filter_tests/test_urlize.py88
-rw-r--r--tests/template_tests/filter_tests/test_urlizetrunc.py30
-rw-r--r--tests/template_tests/filter_tests/test_wordcount.py5
-rw-r--r--tests/template_tests/filter_tests/test_wordwrap.py29
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_blocktranslate.py184
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_available_languages.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_current_language.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py5
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_translate.py31
-rw-r--r--tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py5
-rw-r--r--tests/template_tests/syntax_tests/test_autoescape.py18
-rw-r--r--tests/template_tests/syntax_tests/test_cache.py18
-rw-r--r--tests/template_tests/syntax_tests/test_cycle.py22
-rw-r--r--tests/template_tests/syntax_tests/test_exceptions.py8
-rw-r--r--tests/template_tests/syntax_tests/test_extends.py49
-rw-r--r--tests/template_tests/syntax_tests/test_for.py65
-rw-r--r--tests/template_tests/syntax_tests/test_if.py32
-rw-r--r--tests/template_tests/syntax_tests/test_if_changed.py53
-rw-r--r--tests/template_tests/syntax_tests/test_include.py17
-rw-r--r--tests/template_tests/syntax_tests/test_invalid_string.py4
-rw-r--r--tests/template_tests/syntax_tests/test_load.py24
-rw-r--r--tests/template_tests/syntax_tests/test_named_endblock.py4
-rw-r--r--tests/template_tests/syntax_tests/test_resetcycle.py4
-rw-r--r--tests/template_tests/syntax_tests/test_spaceless.py16
-rw-r--r--tests/template_tests/syntax_tests/test_static.py13
-rw-r--r--tests/template_tests/syntax_tests/test_verbatim.py8
-rw-r--r--tests/template_tests/templatetags/inclusion.py13
-rw-r--r--tests/template_tests/test_custom.py88
-rw-r--r--tests/template_tests/test_extends.py29
-rw-r--r--tests/template_tests/test_parser.py3
-rw-r--r--tests/test_client/tests.py13
-rw-r--r--tests/test_client_regress/tests.py92
-rw-r--r--tests/test_client_regress/views.py3
-rw-r--r--tests/test_runner/test_discover_runner.py9
-rw-r--r--tests/test_utils/tests.py10
-rw-r--r--tests/timezones/tests.py14
-rw-r--r--tests/transactions/tests.py11
-rw-r--r--tests/unmanaged_models/tests.py3
-rw-r--r--tests/urlpatterns_reverse/tests.py23
-rw-r--r--tests/user_commands/tests.py2
-rw-r--r--tests/utils_tests/test_autoreload.py11
-rw-r--r--tests/utils_tests/test_html.py27
-rw-r--r--tests/utils_tests/test_jslex.py7
-rw-r--r--tests/utils_tests/test_lazyobject.py3
-rw-r--r--tests/utils_tests/test_text.py9
-rw-r--r--tests/validation/test_error_messages.py28
-rw-r--r--tests/view_tests/tests/test_csrf.py4
-rw-r--r--tests/view_tests/tests/test_debug.py21
-rw-r--r--tests/view_tests/tests/test_defaults.py7
-rw-r--r--tests/view_tests/tests/test_i18n.py3
-rw-r--r--tests/view_tests/views.py24
-rw-r--r--tests/wsgi/tests.py6
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,
+ ... )
<TemporaryFileUploadHandler object at 0x...>
"""
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 %}
</body>
</html>
-"""
+""" # 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(
"""\
<div class="console-block" id="console-block-%(id)s">
-<input class="c-tab-unix" id="c-tab-%(id)s-unix" type="radio" name="console-%(id)s" checked>
+<input class="c-tab-unix" id="c-tab-%(id)s-unix" type="radio" name="console-%(id)s" \
+checked>
<label for="c-tab-%(id)s-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-%(id)s-win" type="radio" name="console-%(id)s">
<label for="c-tab-%(id)s-win" title="Windows">&#xf17a</label>
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-developers-mailing-list>`
.. |django-announce| replace:: :ref:`django-announce <django-announce-mailing-list>`
.. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>`
-"""
+""" # 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,
- '<h3><a href="/admindocs/views/django.contrib.admindocs.views.BaseAdminDocsView/">/admindocs/</a></h3>',
+ '<h3><a href="/admindocs/views/django.contrib.admindocs.views.'
+ 'BaseAdminDocsView/">/admindocs/</a></h3>',
html=True,
)
self.assertContains(response, "Views by namespace test")
@@ -73,7 +74,9 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
response = self.client.get(reverse("django-admindocs-views-index"))
self.assertContains(
response,
- '<h3><a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">/admin/</a></h3>',
+ "<h3>"
+ '<a href="/admindocs/views/django.contrib.admin.sites.AdminSite.index/">'
+ "/admin/</a></h3>",
html=True,
)
@@ -118,7 +121,8 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
response = self.client.get(reverse("django-admindocs-models-index"))
self.assertContains(
response,
- '<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)</h2>',
+ '<h2 id="app-auth">Authentication and Authorization (django.contrib.auth)'
+ "</h2>",
html=True,
)
@@ -380,11 +384,15 @@ class TestModelDetailView(TestDataMixin, AdminDocsTestCase):
def test_model_docstring_renders_correctly(self):
summary = (
- '<h2 class="subhead"><p>Stores information about a person, related to <a class="reference external" '
- 'href="/admindocs/models/myapp.company/">myapp.Company</a>.</p></h2>'
+ '<h2 class="subhead"><p>Stores information about a person, related to '
+ '<a class="reference external" href="/admindocs/models/myapp.company/">'
+ "myapp.Company</a>.</p></h2>"
)
subheading = "<p><strong>Notes</strong></p>"
- body = '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this object.</p>'
+ body = (
+ '<p>Use <tt class="docutils literal">save_changes()</tt> when saving this '
+ "object.</p>"
+ )
model_body = (
'<dl class="docutils"><dt><tt class="'
'docutils literal">company</tt></dt><dd>Field storing <a class="'
diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py
index 14cfb757b5..ffce914d23 100644
--- a/tests/admin_filters/tests.py
+++ b/tests/admin_filters/tests.py
@@ -1262,7 +1262,10 @@ class ListFiltersTests(TestCase):
modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site)
request = self.request_factory.get("/", {})
request.user = self.alfred
- msg = "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'."
+ msg = (
+ "The list filter 'DecadeListFilterWithoutParameter' does not specify a "
+ "'parameter_name'."
+ )
with self.assertRaisesMessage(ImproperlyConfigured, msg):
modeladmin.get_changelist_instance(request)
diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py
index 7db86f5663..91d69c8d17 100644
--- a/tests/admin_inlines/tests.py
+++ b/tests/admin_inlines/tests.py
@@ -206,10 +206,12 @@ class TestInline(TestDataMixin, TestCase):
response = self.client.post(
reverse("admin:admin_inlines_titlecollection_add"), data
)
- # Here colspan is "4": two fields (title1 and title2), one hidden field and the delete checkbox.
+ # Here colspan is "4": two fields (title1 and title2), one hidden field
+ # and the delete checkbox.
self.assertContains(
response,
- '<tr class="row-form-errors"><td colspan="4"><ul class="errorlist nonfield">'
+ '<tr class="row-form-errors"><td colspan="4">'
+ '<ul class="errorlist nonfield">'
"<li>The two titles must be the same</li></ul></td></tr>",
)
@@ -225,7 +227,10 @@ class TestInline(TestDataMixin, TestCase):
)
def test_callable_lookup(self):
- """Admin inline should invoke local callable when its name is listed in readonly_fields"""
+ """
+ Admin inline should invoke local callable when its name is listed in
+ readonly_fields.
+ """
response = self.client.get(reverse("admin:admin_inlines_poll_add"))
# Add parent object view should have the child inlines section
self.assertContains(
@@ -323,7 +328,8 @@ class TestInline(TestDataMixin, TestCase):
"""
self.client.force_login(self.view_only_user)
url = reverse(
- "stacked_inline_hidden_field_in_group_admin:admin_inlines_someparentmodel_change",
+ "stacked_inline_hidden_field_in_group_admin:"
+ "admin_inlines_someparentmodel_change",
args=(self.parent.pk,),
)
response = self.client.get(url)
@@ -354,7 +360,8 @@ class TestInline(TestDataMixin, TestCase):
"""
self.client.force_login(self.view_only_user)
url = reverse(
- "stacked_inline_hidden_field_on_single_line_admin:admin_inlines_someparentmodel_change",
+ "stacked_inline_hidden_field_on_single_line_admin:"
+ "admin_inlines_someparentmodel_change",
args=(self.parent.pk,),
)
response = self.client.get(url)
@@ -424,12 +431,14 @@ class TestInline(TestDataMixin, TestCase):
)
self.assertContains(
response,
- '<input type="hidden" name="-1-0-capo_famiglia" id="id_-1-0-capo_famiglia">',
+ '<input type="hidden" name="-1-0-capo_famiglia" '
+ 'id="id_-1-0-capo_famiglia">',
html=True,
)
self.assertContains(
response,
- '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" maxlength="100">',
+ '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" '
+ 'maxlength="100">',
html=True,
)
self.assertContains(
@@ -437,12 +446,14 @@ class TestInline(TestDataMixin, TestCase):
)
self.assertContains(
response,
- '<input type="hidden" name="-2-0-capo_famiglia" id="id_-2-0-capo_famiglia">',
+ '<input type="hidden" name="-2-0-capo_famiglia" '
+ 'id="id_-2-0-capo_famiglia">',
html=True,
)
self.assertContains(
response,
- '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" maxlength="100">',
+ '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" '
+ 'maxlength="100">',
html=True,
)
@@ -870,7 +881,8 @@ class TestInlinePermissions(TestCase):
cls.author_change_url = reverse(
"admin:admin_inlines_author_change", args=(author.id,)
)
- # Get the ID of the automatically created intermediate model for the Author-Book m2m
+ # Get the ID of the automatically created intermediate model for the
+ # Author-Book m2m.
author_book_auto_m2m_intermediate = Author.books.through.objects.get(
author=author, book=cls.book
)
@@ -1011,7 +1023,8 @@ class TestInlinePermissions(TestCase):
self.assertContains(response, "<p>%s</p>" % self.book)
self.assertNotContains(
response,
- '<input type="checkbox" name="Author_books-0-DELETE" id="id_Author_books-0-DELETE">',
+ '<input type="checkbox" name="Author_books-0-DELETE" '
+ 'id="id_Author_books-0-DELETE">',
html=True,
)
@@ -1066,8 +1079,8 @@ class TestInlinePermissions(TestCase):
)
self.assertNotContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
@@ -1082,19 +1095,21 @@ class TestInlinePermissions(TestCase):
# Just the one form for existing instances
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
# max-num 0 means we can't add new ones
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" name="inner2_set-MAX_NUM_FORMS">',
+ '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" '
+ 'name="inner2_set-MAX_NUM_FORMS">',
html=True,
)
# TabularInline
@@ -1123,13 +1138,14 @@ class TestInlinePermissions(TestCase):
# One form for existing instance and three extra for new
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
@@ -1148,13 +1164,14 @@ class TestInlinePermissions(TestCase):
# One form for existing instance only, no new
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
@@ -1178,13 +1195,14 @@ class TestInlinePermissions(TestCase):
# One form for existing instance only, three for new
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS">',
+ '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" '
+ 'name="inner2_set-TOTAL_FORMS">',
html=True,
)
self.assertContains(
response,
- '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">'
- % self.inner2.id,
+ '<input type="hidden" id="id_inner2_set-0-id" value="%i" '
+ 'name="inner2_set-0-id">' % self.inner2.id,
html=True,
)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
@@ -1247,7 +1265,10 @@ class TestReadOnlyChangeViewInlinePermissions(TestCase):
self.assertContains(
response, '<div class="readonly">%s</div>' % self.poll.name, html=True
)
- input = '<input type="text" name="name" value="%s" class="vTextField" maxlength="40" required id="id_name">'
+ input = (
+ '<input type="text" name="name" value="%s" class="vTextField" '
+ 'maxlength="40" required id="id_name">'
+ )
self.assertNotContains(response, input % self.poll.name, html=True)
def test_inlines_are_rendered_as_read_only(self):
@@ -1284,7 +1305,8 @@ class TestReadOnlyChangeViewInlinePermissions(TestCase):
response = self.client.get(self.change_url)
self.assertNotContains(
response,
- '<input type="checkbox" name="question_set-0-DELETE" id="id_question_set-0-DELETE">',
+ '<input type="checkbox" name="question_set-0-DELETE" '
+ 'id="id_question_set-0-DELETE">',
html=True,
)
@@ -1790,11 +1812,13 @@ class SeleniumTests(AdminSeleniumTestCase):
# Click on a few delete buttons
self.selenium.find_element(
By.CSS_SELECTOR,
- "form#profilecollection_form tr.dynamic-profile_set#profile_set-1 td.delete a",
+ "form#profilecollection_form tr.dynamic-profile_set#profile_set-1 "
+ "td.delete a",
).click()
self.selenium.find_element(
By.CSS_SELECTOR,
- "form#profilecollection_form tr.dynamic-profile_set#profile_set-2 td.delete a",
+ "form#profilecollection_form tr.dynamic-profile_set#profile_set-2 "
+ "td.delete a",
).click()
# The rows are gone and the IDs have been re-sequenced
self.assertCountSeleniumElements(
diff --git a/tests/admin_registration/tests.py b/tests/admin_registration/tests.py
index 12fc98b1cc..25f317d322 100644
--- a/tests/admin_registration/tests.py
+++ b/tests/admin_registration/tests.py
@@ -43,7 +43,10 @@ class TestRegistration(SimpleTestCase):
pass
self.site.register(Person, PersonAdmin)
- msg = "The model Person is already registered with 'admin_registration.PersonAdmin'."
+ msg = (
+ "The model Person is already registered with "
+ "'admin_registration.PersonAdmin'."
+ )
with self.assertRaisesMessage(admin.sites.AlreadyRegistered, msg):
self.site.register(Person, PersonAdmin)
diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py
index 55880802c2..3d5902f768 100644
--- a/tests/admin_scripts/tests.py
+++ b/tests/admin_scripts/tests.py
@@ -201,21 +201,30 @@ class DjangoAdminNoSettings(AdminScriptTestCase):
"A series of tests for django-admin when there is no settings.py file."
def test_builtin_command(self):
- "no settings: django-admin builtin commands fail with an error when no settings provided"
+ """
+ no settings: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_bad_settings(self):
- "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ no settings: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ no settings: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
@@ -243,42 +252,60 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase):
self.write_settings("settings.py")
def test_builtin_command(self):
- "default: django-admin builtin commands fail with an error when no settings provided"
+ """
+ default: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "default: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ default: django-admin builtin commands succeed if settings are provided
+ as argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "default: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ default: django-admin builtin commands succeed if settings are provided
+ in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "default: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ default: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "default: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ default: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "default: django-admin can't execute user commands if it isn't provided settings"
+ """
+ default: django-admin can't execute user commands if it isn't provided
+ settings.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -286,14 +313,20 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "default: django-admin can execute user commands if settings are provided as argument"
+ """
+ default: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "default: django-admin can execute user commands if settings are provided in environment"
+ """
+ default: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
@@ -319,42 +352,60 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "fulldefault: django-admin builtin commands fail with an error when no settings provided"
+ """
+ fulldefault: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "fulldefault: django-admin builtin commands succeed if a settings file is provided"
+ """
+ fulldefault: django-admin builtin commands succeed if a settings file
+ is provided.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "fulldefault: django-admin builtin commands succeed if the environment contains settings"
+ """
+ fulldefault: django-admin builtin commands succeed if the environment
+ contains settings.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ fulldefault: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ fulldefault: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "fulldefault: django-admin can't execute user commands unless settings are provided"
+ """
+ fulldefault: django-admin can't execute user commands unless settings
+ are provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -362,14 +413,20 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "fulldefault: django-admin can execute user commands if settings are provided as argument"
+ """
+ fulldefault: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "fulldefault: django-admin can execute user commands if settings are provided in environment"
+ """
+ fulldefault: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
@@ -389,35 +446,50 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "minimal: django-admin builtin commands fail with an error when no settings provided"
+ """
+ minimal: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "minimal: django-admin builtin commands fail if settings are provided as argument"
+ """
+ minimal: django-admin builtin commands fail if settings are provided as
+ argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_environment(self):
- "minimal: django-admin builtin commands fail if settings are provided in the environment"
+ """
+ minimal: django-admin builtin commands fail if settings are provided in
+ the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_bad_settings(self):
- "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ minimal: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ minimal: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
@@ -432,14 +504,20 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "minimal: django-admin can't execute user commands, even if settings are provided as argument"
+ """
+ minimal: django-admin can't execute user commands, even if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_environment(self):
- "minimal: django-admin can't execute user commands, even if settings are provided in environment"
+ """
+ minimal: django-admin can't execute user commands, even if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(out)
@@ -457,42 +535,60 @@ class DjangoAdminAlternateSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "alternate: django-admin builtin commands fail with an error when no settings provided"
+ """
+ alternate: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "alternate: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "alternate: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "alternate: django-admin can't execute user commands unless settings are provided"
+ """
+ alternate: django-admin can't execute user commands unless settings
+ are provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -500,14 +596,20 @@ class DjangoAdminAlternateSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "alternate: django-admin can execute user commands if settings are provided as argument"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.alternate_settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "alternate: django-admin can execute user commands if settings are provided in environment"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
@@ -530,41 +632,59 @@ class DjangoAdminMultipleSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "alternate: django-admin builtin commands fail with an error when no settings provided"
+ """
+ alternate: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_settings(self):
- "alternate: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "alternate: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ alternate: django-admin builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ alternate: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "alternate: django-admin can't execute user commands unless settings are provided"
+ """
+ alternate: django-admin can't execute user commands unless settings are
+ provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -572,14 +692,20 @@ class DjangoAdminMultipleSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "alternate: django-admin can execute user commands if settings are provided as argument"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.alternate_settings"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "alternate: django-admin can execute user commands if settings are provided in environment"
+ """
+ alternate: django-admin can execute user commands if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args, "test_project.alternate_settings")
self.assertNoOutput(err)
@@ -631,27 +757,39 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
self.assertIn("name = 'こんにちは'", content)
def test_builtin_command(self):
- "directory: django-admin builtin commands fail with an error when no settings provided"
+ """
+ directory: django-admin builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
self.assertOutput(err, "settings are not configured")
def test_builtin_with_bad_settings(self):
- "directory: django-admin builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ directory: django-admin builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "directory: django-admin builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ directory: django-admin builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "directory: django-admin can't execute user commands unless settings are provided"
+ """
+ directory: django-admin can't execute user commands unless settings are
+ provided.
+ """
args = ["noargs_command"]
out, err = self.run_django_admin(args)
self.assertNoOutput(out)
@@ -659,14 +797,20 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_builtin_with_settings(self):
- "directory: django-admin builtin commands succeed if settings are provided as argument"
+ """
+ directory: django-admin builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_django_admin(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "directory: django-admin builtin commands succeed if settings are provided in the environment"
+ """
+ directory: django-admin builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_django_admin(args, "test_project.settings")
self.assertNoOutput(err)
@@ -696,7 +840,10 @@ class ManageNoSettings(AdminScriptTestCase):
"A series of tests for manage.py when there is no settings.py file."
def test_builtin_command(self):
- "no settings: manage.py builtin commands fail with an error when no settings provided"
+ """
+ no settings: manage.py builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
@@ -705,14 +852,20 @@ class ManageNoSettings(AdminScriptTestCase):
)
def test_builtin_with_bad_settings(self):
- "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ no settings: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ no settings: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -729,56 +882,80 @@ class ManageDefaultSettings(AdminScriptTestCase):
self.write_settings("settings.py")
def test_builtin_command(self):
- "default: manage.py builtin commands succeed when default settings are appropriate"
+ """
+ default: manage.py builtin commands succeed when default settings are
+ appropriate.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_settings(self):
- "default: manage.py builtin commands succeed if settings are provided as argument"
+ """
+ default: manage.py builtin commands succeed if settings are provided as
+ argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "default: manage.py builtin commands succeed if settings are provided in the environment"
+ """
+ default: manage.py builtin commands succeed if settings are provided in
+ the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist"
+ """
+ default: manage.py builtin commands succeed if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "default: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ default: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "default: manage.py can execute user commands when default settings are appropriate"
+ """
+ default: manage.py can execute user commands when default settings are
+ appropriate.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
- "default: manage.py can execute user commands when settings are provided as argument"
+ """
+ default: manage.py can execute user commands when settings are provided
+ as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "default: manage.py can execute user commands when settings are provided in environment"
+ """
+ default: manage.py can execute user commands when settings are provided
+ in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
@@ -798,56 +975,80 @@ class ManageFullPathDefaultSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "fulldefault: manage.py builtin commands succeed when default settings are appropriate"
+ """
+ fulldefault: manage.py builtin commands succeed when default settings
+ are appropriate.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_settings(self):
- "fulldefault: manage.py builtin commands succeed if settings are provided as argument"
+ """
+ fulldefault: manage.py builtin commands succeed if settings are
+ provided as argument.
+ """
args = ["check", "--settings=test_project.settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "fulldefault: manage.py builtin commands succeed if settings are provided in the environment"
+ """
+ fulldefault: manage.py builtin commands succeed if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist"
+ """
+ fulldefault: manage.py builtin commands succeed if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ fulldefault: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_custom_command(self):
- "fulldefault: manage.py can execute user commands when default settings are appropriate"
+ """
+ fulldefault: manage.py can execute user commands when default settings
+ are appropriate.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_settings(self):
- "fulldefault: manage.py can execute user commands when settings are provided as argument"
+ """
+ fulldefault: manage.py can execute user commands when settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "fulldefault: manage.py can execute user commands when settings are provided in environment"
+ """
+ fulldefault: manage.py can execute user commands when settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(err)
@@ -866,7 +1067,10 @@ class ManageMinimalSettings(AdminScriptTestCase):
)
def test_builtin_command(self):
- "minimal: manage.py builtin commands fail with an error when no settings provided"
+ """
+ minimal: manage.py builtin commands fail with an error when no settings
+ provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
@@ -880,21 +1084,30 @@ class ManageMinimalSettings(AdminScriptTestCase):
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_environment(self):
- "minimal: manage.py builtin commands fail if settings are provided in the environment"
+ """
+ minimal: manage.py builtin commands fail if settings are provided in
+ the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_bad_settings(self):
- "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ minimal: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ minimal: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -908,14 +1121,20 @@ class ManageMinimalSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "minimal: manage.py can't execute user commands, even if settings are provided as argument"
+ """
+ minimal: manage.py can't execute user commands, even if settings are
+ provided as argument.
+ """
args = ["noargs_command", "--settings=test_project.settings"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_environment(self):
- "minimal: manage.py can't execute user commands, even if settings are provided in environment"
+ """
+ minimal: manage.py can't execute user commands, even if settings are
+ provided in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "test_project.settings")
self.assertNoOutput(out)
@@ -932,7 +1151,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "alternate: manage.py builtin commands fail with an error when no default settings provided"
+ """
+ alternate: manage.py builtin commands fail with an error when no
+ default settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
@@ -948,21 +1170,30 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.assertNoOutput(err)
def test_builtin_with_environment(self):
- "alternate: manage.py builtin commands work if settings are provided in the environment"
+ """
+ alternate: manage.py builtin commands work if settings are provided in
+ the environment
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "alternate_settings")
self.assertOutput(out, SYSTEM_CHECK_MSG)
self.assertNoOutput(err)
def test_builtin_with_bad_settings(self):
- "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ alternate: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ alternate: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -978,7 +1209,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
)
def test_custom_command_with_settings(self):
- "alternate: manage.py can execute user commands if settings are provided as argument"
+ """
+ alternate: manage.py can execute user commands if settings are provided
+ as argument
+ """
args = ["noargs_command", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertOutput(
@@ -990,7 +1224,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.assertNoOutput(err)
def test_custom_command_with_environment(self):
- "alternate: manage.py can execute user commands if settings are provided in environment"
+ """
+ alternate: manage.py can execute user commands if settings are provided
+ in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "alternate_settings")
self.assertOutput(
@@ -1002,7 +1239,10 @@ class ManageAlternateSettings(AdminScriptTestCase):
self.assertNoOutput(err)
def test_custom_command_output_color(self):
- "alternate: manage.py output syntax color can be deactivated with the `--no-color` option"
+ """
+ alternate: manage.py output syntax color can be deactivated with the
+ `--no-color` option.
+ """
args = ["noargs_command", "--no-color", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertOutput(
@@ -1029,35 +1269,50 @@ class ManageMultipleSettings(AdminScriptTestCase):
self.write_settings("alternate_settings.py")
def test_builtin_command(self):
- "multiple: manage.py builtin commands fail with an error when no settings provided"
+ """
+ multiple: manage.py builtin commands fail with an error when no
+ settings provided.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No installed app with label 'admin_scripts'.")
def test_builtin_with_settings(self):
- "multiple: manage.py builtin commands succeed if settings are provided as argument"
+ """
+ multiple: manage.py builtin commands succeed if settings are provided
+ as argument.
+ """
args = ["check", "--settings=alternate_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_environment(self):
- "multiple: manage.py can execute builtin commands if settings are provided in the environment"
+ """
+ multiple: manage.py can execute builtin commands if settings are
+ provided in the environment.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "alternate_settings")
self.assertNoOutput(err)
self.assertOutput(out, SYSTEM_CHECK_MSG)
def test_builtin_with_bad_settings(self):
- "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist"
+ """
+ multiple: manage.py builtin commands fail if settings file (from
+ argument) doesn't exist.
+ """
args = ["check", "--settings=bad_settings", "admin_scripts"]
out, err = self.run_manage(args)
self.assertNoOutput(out)
self.assertOutput(err, "No module named '?bad_settings'?", regex=True)
def test_builtin_with_bad_environment(self):
- "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist"
+ """
+ multiple: manage.py builtin commands fail if settings file (from
+ environment) doesn't exist.
+ """
args = ["check", "admin_scripts"]
out, err = self.run_manage(args, "bad_settings")
self.assertNoOutput(out)
@@ -1071,14 +1326,20 @@ class ManageMultipleSettings(AdminScriptTestCase):
self.assertOutput(err, "Unknown command: 'noargs_command'")
def test_custom_command_with_settings(self):
- "multiple: manage.py can execute user commands if settings are provided as argument"
+ """
+ multiple: manage.py can execute user commands if settings are provided
+ as argument.
+ """
args = ["noargs_command", "--settings=alternate_settings"]
out, err = self.run_manage(args)
self.assertNoOutput(err)
self.assertOutput(out, "EXECUTE: noargs_command")
def test_custom_command_with_environment(self):
- "multiple: manage.py can execute user commands if settings are provided in environment"
+ """
+ multiple: manage.py can execute user commands if settings are provided
+ in environment.
+ """
args = ["noargs_command"]
out, err = self.run_manage(args, "alternate_settings")
self.assertNoOutput(err)
@@ -2106,7 +2367,9 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
]
def test_wrong_args(self):
- "Make sure passing the wrong kinds of arguments outputs an error and prints usage"
+ """
+ Passing the wrong kinds of arguments outputs an error and prints usage.
+ """
out, err = self.run_django_admin(["startproject"])
self.assertNoOutput(out)
self.assertOutput(err, "usage:")
@@ -2165,7 +2428,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertFalse(os.path.exists(testproject_dir))
def test_simple_project_different_directory(self):
- "Make sure the startproject management command creates a project in a specific directory"
+ """
+ The startproject management command creates a project in a specific
+ directory.
+ """
args = ["startproject", "testproject", "othertestproject"]
testproject_dir = os.path.join(self.test_dir, "othertestproject")
os.mkdir(testproject_dir)
@@ -2184,7 +2450,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
)
def test_custom_project_template(self):
- "Make sure the startproject management command is able to use a different project template"
+ """
+ The startproject management command is able to use a different project
+ template.
+ """
template_path = os.path.join(custom_templates_dir, "project_template")
args = ["startproject", "--template", template_path, "customtestproject"]
testproject_dir = os.path.join(self.test_dir, "customtestproject")
@@ -2206,7 +2475,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir")))
def test_custom_project_template_from_tarball_by_path(self):
- "Make sure the startproject management command is able to use a different project template from a tarball"
+ """
+ The startproject management command is able to use a different project
+ template from a tarball.
+ """
template_path = os.path.join(custom_templates_dir, "project_template.tgz")
args = ["startproject", "--template", template_path, "tarballtestproject"]
testproject_dir = os.path.join(self.test_dir, "tarballtestproject")
@@ -2217,7 +2489,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py")))
def test_custom_project_template_from_tarball_to_alternative_location(self):
- "Startproject can use a project template from a tarball and create it in a specified location"
+ """
+ Startproject can use a project template from a tarball and create it in
+ a specified location.
+ """
template_path = os.path.join(custom_templates_dir, "project_template.tgz")
args = [
"startproject",
@@ -2279,7 +2554,10 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
urls.urlpatterns = old_urlpatterns
def test_project_template_tarball_url(self):
- "Startproject management command handles project template tar/zip balls from non-canonical urls"
+ """ "
+ Startproject management command handles project template tar/zip balls
+ from non-canonical urls.
+ """
template_url = (
"%s/custom_templates/project_template.tgz/" % self.live_server_url
)
@@ -2724,7 +3002,8 @@ class MainModule(AdminScriptTestCase):
out, err = self.run_test(["-m", "django", "help"])
self.assertOutput(
out,
- "Type 'python -m django help <subcommand>' for help on a specific subcommand.",
+ "Type 'python -m django help <subcommand>' for help on a specific "
+ "subcommand.",
)
diff --git a/tests/admin_utils/tests.py b/tests/admin_utils/tests.py
index 27fe049274..a2ef3b1942 100644
--- a/tests/admin_utils/tests.py
+++ b/tests/admin_utils/tests.py
@@ -379,7 +379,8 @@ class UtilsTests(SimpleTestCase):
)
self.assertHTMLEqual(
helpers.AdminField(form, "cb", is_first=False).label_tag(),
- '<label for="id_cb" class="vCheckboxLabel required inline"><i>cb</i></label>',
+ '<label for="id_cb" class="vCheckboxLabel required inline">'
+ "<i>cb</i></label>",
)
# normal strings needs to be escaped
diff --git a/tests/admin_views/test_actions.py b/tests/admin_views/test_actions.py
index 2bdcff44ae..ec690f5692 100644
--- a/tests/admin_views/test_actions.py
+++ b/tests/admin_views/test_actions.py
@@ -314,7 +314,9 @@ action)</option>
self.assertContains(
response,
"jquery.min.js",
- msg_prefix="jQuery missing from admin pages for model with no admin actions",
+ msg_prefix=(
+ "jQuery missing from admin pages for model with no admin actions"
+ ),
)
def test_action_column_class(self):
@@ -365,7 +367,10 @@ action)</option>
response = self.client.post(url, action_data)
self.assertRedirects(response, url, fetch_redirect_response=False)
response = self.client.get(response.url)
- msg = "Items must be selected in order to perform actions on them. No items have been changed."
+ msg = (
+ "Items must be selected in order to perform actions on them. No items have "
+ "been changed."
+ )
self.assertContains(response, msg)
self.assertEqual(Subscriber.objects.count(), 2)
diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index 4935b58823..7df96fa042 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -1072,34 +1072,38 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
)
self.assertEqual(response.status_code, 400)
- # #23839 - Primary key should always be allowed, even if the referenced model isn't registered.
+ # Primary key should always be allowed, even if the referenced model
+ # isn't registered.
response = self.client.get(
reverse("admin:admin_views_notreferenced_changelist"), {TO_FIELD_VAR: "id"}
)
self.assertEqual(response.status_code, 200)
- # #23915 - Specifying a field referenced by another model though a m2m should be allowed.
+ # Specifying a field referenced by another model though a m2m should be
+ # allowed.
response = self.client.get(
reverse("admin:admin_views_recipe_changelist"), {TO_FIELD_VAR: "rname"}
)
self.assertEqual(response.status_code, 200)
- # #23604, #23915 - Specifying a field referenced through a reverse m2m relationship should be allowed.
+ # Specifying a field referenced through a reverse m2m relationship
+ # should be allowed.
response = self.client.get(
reverse("admin:admin_views_ingredient_changelist"), {TO_FIELD_VAR: "iname"}
)
self.assertEqual(response.status_code, 200)
- # #23329 - Specifying a field that is not referred by any other model directly registered
- # to this admin site but registered through inheritance should be allowed.
+ # Specifying a field that is not referred by any other model directly
+ # registered to this admin site but registered through inheritance
+ # should be allowed.
response = self.client.get(
reverse("admin:admin_views_referencedbyparent_changelist"),
{TO_FIELD_VAR: "name"},
)
self.assertEqual(response.status_code, 200)
- # #23431 - Specifying a field that is only referred to by a inline of a registered
- # model should be allowed.
+ # Specifying a field that is only referred to by a inline of a
+ # registered model should be allowed.
response = self.client.get(
reverse("admin:admin_views_referencedbyinline_changelist"),
{TO_FIELD_VAR: "name"},
@@ -1138,7 +1142,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
ForeignKey 'limit_choices_to' should be allowed, otherwise raw_id_fields
can break.
"""
- # Filters should be allowed if they are defined on a ForeignKey pointing to this model
+ # Filters should be allowed if they are defined on a ForeignKey
+ # pointing to this model.
url = "%s?leader__name=Palin&leader__age=27" % reverse(
"admin:admin_views_inquisition_changelist"
)
@@ -1169,7 +1174,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
self.assertNotContains(
response,
reverse("admin:password_change"),
- msg_prefix='The "change password" link should not be displayed if a user does not have a usable password.',
+ msg_prefix=(
+ 'The "change password" link should not be displayed if a user does not '
+ "have a usable password."
+ ),
)
def test_change_view_with_show_delete_extra_context(self):
@@ -1427,8 +1435,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
TEMPLATES=[
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
- # Put this app's and the shared tests templates dirs in DIRS to take precedence
- # over the admin's templates dir.
+ # Put this app's and the shared tests templates dirs in DIRS to
+ # take precedence over the admin's templates dir.
"DIRS": [
os.path.join(os.path.dirname(__file__), "templates"),
os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates"),
@@ -2271,7 +2279,10 @@ class AdminViewPermissionsTest(TestCase):
self.assertNotContains(
addpage,
change_list_link,
- msg_prefix="User restricted to add permission is given link to change list view in breadcrumbs.",
+ msg_prefix=(
+ "User restricted to add permission is given link to change list view "
+ "in breadcrumbs."
+ ),
)
post = self.client.post(reverse("admin:admin_views_article_add"), add_dict)
self.assertRedirects(post, self.index_url)
@@ -2297,7 +2308,10 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(
addpage,
change_list_link,
- msg_prefix="Unrestricted user is not given link to change list view in breadcrumbs.",
+ msg_prefix=(
+ "Unrestricted user is not given link to change list view in "
+ "breadcrumbs."
+ ),
)
post = self.client.post(reverse("admin:admin_views_article_add"), add_dict)
self.assertRedirects(post, reverse("admin:admin_views_article_changelist"))
@@ -2374,7 +2388,8 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(response, "<label>Extra form field:</label>")
self.assertContains(
response,
- '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close</a>',
+ '<a href="/test_admin/admin/admin_views/article/" class="closelink">Close'
+ "</a>",
)
self.assertEqual(response.context["title"], "View article")
post = self.client.post(article_change_url, change_dict)
@@ -2406,13 +2421,16 @@ class AdminViewPermissionsTest(TestCase):
Article.objects.get(pk=self.a1.pk).content, "<p>edited article</p>"
)
- # one error in form should produce singular error message, multiple errors plural
+ # one error in form should produce singular error message, multiple
+ # errors plural.
change_dict["title"] = ""
post = self.client.post(article_change_url, change_dict)
self.assertContains(
post,
"Please correct the error below.",
- msg_prefix="Singular error message not found in response to post with one error",
+ msg_prefix=(
+ "Singular error message not found in response to post with one error"
+ ),
)
change_dict["content"] = ""
@@ -2420,7 +2438,10 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(
post,
"Please correct the errors below.",
- msg_prefix="Plural error message not found in response to post with multiple errors",
+ msg_prefix=(
+ "Plural error message not found in response to post with multiple "
+ "errors"
+ ),
)
self.client.get(reverse("admin:logout"))
@@ -2519,7 +2540,8 @@ class AdminViewPermissionsTest(TestCase):
self.assertContains(response, "<h1>View article</h1>")
self.assertContains(
response,
- '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close</a>',
+ '<a href="/test_admin/admin9/admin_views/article/" class="closelink">Close'
+ "</a>",
)
def test_change_view_save_as_new(self):
@@ -2870,13 +2892,15 @@ class AdminViewPermissionsTest(TestCase):
)
self.client.force_login(self.adduser)
- # The user can't change sections yet, so they shouldn't see the "change section" link.
+ # The user can't change sections yet, so they shouldn't see the
+ # "change section" link.
url = reverse("admin:admin_views_article_add")
change_link_text = "change_id_section"
response = self.client.get(url)
self.assertFalse(get_change_related(response))
self.assertNotContains(response, change_link_text)
- # Allow the user to change sections too. Now they can see the "change section" link.
+ # Allow the user to change sections too. Now they can see the
+ # "change section" link.
user = User.objects.get(username="adduser")
perm = get_perm(Section, get_permission_codename("change", Section._meta))
user.user_permissions.add(perm)
@@ -2898,13 +2922,15 @@ class AdminViewPermissionsTest(TestCase):
)
self.client.force_login(self.adduser)
- # The user can't delete sections yet, so they shouldn't see the "delete section" link.
+ # The user can't delete sections yet, so they shouldn't see the
+ # "delete section" link.
url = reverse("admin:admin_views_article_add")
delete_link_text = "delete_id_sub_section"
response = self.client.get(url)
self.assertFalse(get_delete_related(response))
self.assertNotContains(response, delete_link_text)
- # Allow the user to delete sections too. Now they can see the "delete section" link.
+ # Allow the user to delete sections too. Now they can see the
+ # "delete section" link.
user = User.objects.get(username="adduser")
perm = get_perm(Section, get_permission_codename("delete", Section._meta))
user.user_permissions.add(perm)
@@ -3076,7 +3102,8 @@ class AdminViewPermissionsTest(TestCase):
)
self.assertContains(
response,
- '<li class="success">The article “Fun &amp; games” was added successfully.</li>',
+ '<li class="success">The article “Fun &amp; games” was added successfully.'
+ "</li>",
html=True,
)
@@ -3313,7 +3340,8 @@ class AdminViewDeletedObjectsTest(TestCase):
)
self.assertContains(
response,
- "your account doesn't have permission to delete the following types of objects",
+ "your account doesn't have permission to delete the following types of "
+ "objects",
)
self.assertContains(response, "<li>plot details</li>")
@@ -3580,7 +3608,10 @@ class AdminViewStringPrimaryKeyTest(TestCase):
self.assertContains(response, escape(self.pk))
def test_changelist_to_changeform_link(self):
- "Link to the changeform of the object in changelist should use reverse() and be quoted -- #18072"
+ """
+ Link to the changeform of the object in changelist should use reverse()
+ and be quoted.
+ """
response = self.client.get(
reverse("admin:admin_views_modelwithstringprimarykey_changelist")
)
@@ -3596,7 +3627,10 @@ class AdminViewStringPrimaryKeyTest(TestCase):
self.assertContains(response, should_contain)
def test_recentactions_link(self):
- "The link from the recent actions list referring to the changeform of the object should be quoted"
+ """
+ The link from the recent actions list referring to the changeform of
+ the object should be quoted.
+ """
response = self.client.get(reverse("admin:index"))
link = reverse(
"admin:admin_views_modelwithstringprimarykey_change", args=(quote(self.pk),)
@@ -3605,7 +3639,10 @@ class AdminViewStringPrimaryKeyTest(TestCase):
self.assertContains(response, should_contain)
def test_deleteconfirmation_link(self):
- "The link from the delete confirmation page referring back to the changeform of the object should be quoted"
+ """ "
+ The link from the delete confirmation page referring back to the
+ changeform of the object should be quoted.
+ """
url = reverse(
"admin:admin_views_modelwithstringprimarykey_delete", args=(quote(self.pk),)
)
@@ -3800,10 +3837,14 @@ class AdminViewUnicodeTest(TestCase):
"chapter_set-MAX_NUM_FORMS": "0",
"chapter_set-0-id": self.chap1.pk,
"chapter_set-0-title": "Norske bostaver æøå skaper problemer",
- "chapter_set-0-content": "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;",
+ "chapter_set-0-content": (
+ "&lt;p&gt;Svært frustrerende med UnicodeDecodeError&lt;/p&gt;"
+ ),
"chapter_set-1-id": self.chap2.id,
"chapter_set-1-title": "Kjærlighet.",
- "chapter_set-1-content": "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;",
+ "chapter_set-1-content": (
+ "&lt;p&gt;La kjærligheten til de lidende seire.&lt;/p&gt;"
+ ),
"chapter_set-2-id": self.chap3.id,
"chapter_set-2-title": "Need a title.",
"chapter_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;",
@@ -4227,8 +4268,8 @@ class AdminViewListEditable(TestCase):
response,
'<div class="hiddenfields">\n'
'<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">'
- '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n</div>'
- % (story2.id, story1.id),
+ '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n'
+ "</div>" % (story2.id, story1.id),
html=True,
)
self.assertContains(response, '<td class="field-id">%d</td>' % story1.id, 1)
@@ -4257,8 +4298,8 @@ class AdminViewListEditable(TestCase):
response,
'<div class="hiddenfields">\n'
'<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id">'
- '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n</div>'
- % (story2.id, story1.id),
+ '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id">\n'
+ "</div>" % (story2.id, story1.id),
html=True,
)
self.assertContains(
@@ -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, '<div class="help">', 3)
self.assertContains(
response,
- '<div class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)</div>',
+ '<div class="help">Some help text for the title (with Unicode ŠĐĆŽćžšđ)'
+ "</div>",
html=True,
)
self.assertContains(
response,
- '<div class="help">Some help text for the content (with Unicode ŠĐĆŽćžšđ)</div>',
+ '<div class="help">Some help text for the content (with Unicode ŠĐĆŽćžšđ)'
+ "</div>",
html=True,
)
self.assertContains(
response,
- '<div class="help">Some help text for the date (with Unicode ŠĐĆŽćžšđ)</div>',
+ '<div class="help">Some help text for the date (with Unicode ŠĐĆŽćžšđ)'
+ "</div>",
html=True,
)
@@ -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, "&quot;obj&quot;: &quot;newuser&quot;")
def test_user_fk_change_popup(self):
- """User change through a FK popup should return the appropriate JavaScript response."""
+ """
+ User change through a FK popup should return the appropriate JavaScript
+ response.
+ """
response = self.client.get(reverse("admin:admin_views_album_add"))
self.assertContains(
response, reverse("admin:auth_user_change", args=("__fk__",))
@@ -6705,7 +6761,10 @@ class UserAdminTest(TestCase):
self.assertContains(response, "&quot;action&quot;: &quot;change&quot;")
def test_user_fk_delete_popup(self):
- """User deletion through a FK popup should return the appropriate JavaScript response."""
+ """
+ User deletion through a FK popup should return the appropriate
+ JavaScript response.
+ """
response = self.client.get(reverse("admin:admin_views_album_add"))
self.assertContains(
response, reverse("admin:auth_user_delete", args=("__fk__",))
@@ -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)),
- '<input value="2007-12-01" type="text" class="vDateField" name="test" size="10">',
+ '<input value="2007-12-01" type="text" class="vDateField" name="test" '
+ 'size="10">',
)
# pass attrs to widget
w = widgets.AdminDateWidget(attrs={"size": 20, "class": "myDateField"})
self.assertHTMLEqual(
w.render("test", datetime(2007, 12, 1, 9, 30)),
- '<input value="2007-12-01" type="text" class="myDateField" name="test" size="20">',
+ '<input value="2007-12-01" type="text" class="myDateField" name="test" '
+ 'size="20">',
)
@@ -378,13 +381,15 @@ class AdminTimeWidgetTest(SimpleTestCase):
w = widgets.AdminTimeWidget()
self.assertHTMLEqual(
w.render("test", datetime(2007, 12, 1, 9, 30)),
- '<input value="09:30:00" type="text" class="vTimeField" name="test" size="8">',
+ '<input value="09:30:00" type="text" class="vTimeField" name="test" '
+ 'size="8">',
)
# pass attrs to widget
w = widgets.AdminTimeWidget(attrs={"size": 20, "class": "myTimeField"})
self.assertHTMLEqual(
w.render("test", datetime(2007, 12, 1, 9, 30)),
- '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20">',
+ '<input value="09:30:00" type="text" class="myTimeField" name="test" '
+ 'size="20">',
)
@@ -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&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;",
+ "http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;"
+ "alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;",
)
@@ -504,12 +511,14 @@ class AdminUUIDWidgetTests(SimpleTestCase):
w = widgets.AdminUUIDInputWidget()
self.assertHTMLEqual(
w.render("test", "550e8400-e29b-41d4-a716-446655440000"),
- '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" class="vUUIDField" name="test">',
+ '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" '
+ 'class="vUUIDField" name="test">',
)
w = widgets.AdminUUIDInputWidget(attrs={"class": "myUUIDInput"})
self.assertHTMLEqual(
w.render("test", "550e8400-e29b-41d4-a716-446655440000"),
- '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" class="myUUIDInput" name="test">',
+ '<input value="550e8400-e29b-41d4-a716-446655440000" type="text" '
+ 'class="myUUIDInput" name="test">',
)
@@ -685,7 +694,8 @@ class ForeignKeyRawIdWidgetTest(TestCase):
)
self.assertHTMLEqual(
w.render("test", child_of_hidden.parent_id, attrs={}),
- '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField">'
+ '<input type="text" name="test" value="93" '
+ ' class="vForeignKeyRawIdAdminField">'
'<a href="/admin_widgets/inventory/?_to_field=barcode" '
'class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
'&nbsp;<strong><a href="/admin_widgets/inventory/%(pk)s/change/">'
@@ -698,8 +708,9 @@ class ForeignKeyRawIdWidgetTest(TestCase):
self.assertHTMLEqual(
w.render("test", None),
'<input type="text" name="test" class="vForeignKeyRawIdAdminField">\n'
- '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;_to_field=artist_ptr" '
- 'class="related-lookup" id="lookup_id_test" title="Lookup"></a>',
+ '<a href="/admin_widgets/band/?name=%22%26%3E%3Cescapeme&amp;'
+ '_to_field=artist_ptr" class="related-lookup" id="lookup_id_test" '
+ 'title="Lookup"></a>',
)
def test_render_fk_as_pk_model(self):
@@ -727,8 +738,10 @@ class ManyToManyRawIdWidgetTest(TestCase):
self.assertHTMLEqual(
w.render("test", [m1.pk, m2.pk], attrs={}),
(
- '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField">'
- '<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
+ '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" '
+ ' class="vManyToManyRawIdAdminField">'
+ '<a href="/admin_widgets/member/" class="related-lookup" '
+ ' id="lookup_id_test" title="Lookup"></a>'
)
% {"m1pk": m1.pk, "m2pk": m2.pk},
)
@@ -736,8 +749,10 @@ class ManyToManyRawIdWidgetTest(TestCase):
self.assertHTMLEqual(
w.render("test", [m1.pk]),
(
- '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
- '<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
+ '<input type="text" name="test" value="%(m1pk)s" '
+ ' class="vManyToManyRawIdAdminField">'
+ '<a href="/admin_widgets/member/" class="related-lookup" '
+ ' id="lookup_id_test" title="Lookup"></a>'
)
% {"m1pk": m1.pk},
)
diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
index 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,
- "<ul><li>Your password can’t be too similar to your other personal information.</li></ul>",
+ "<ul><li>"
+ "Your password can’t be too similar to your other personal information."
+ "</li></ul>",
)
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
]
)
@@ -610,10 +623,15 @@ class SetPasswordFormTest(TestDataMixin, TestCase):
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
{
- "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
+ "NAME": (
+ "django.contrib.auth.password_validation.MinimumLengthValidator"
+ ),
"OPTIONS": {
"min_length": 12,
},
@@ -651,10 +669,15 @@ class SetPasswordFormTest(TestDataMixin, TestCase):
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{
- "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
+ "NAME": (
+ "django.contrib.auth.password_validation."
+ "UserAttributeSimilarityValidator"
+ )
},
{
- "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
+ "NAME": (
+ "django.contrib.auth.password_validation.MinimumLengthValidator"
+ ),
"OPTIONS": {
"min_length": 12,
},
@@ -663,7 +686,8 @@ class SetPasswordFormTest(TestDataMixin, TestCase):
)
def test_help_text_translation(self):
french_help_texts = [
- "Votre mot de passe ne peut pas trop ressembler à vos autres informations personnelles.",
+ "Votre mot de passe ne peut pas trop ressembler à vos autres informations "
+ "personnelles.",
"Votre mot de passe doit contenir au minimum 12 caractères.",
]
form = SetPasswordForm(self.u1)
@@ -1129,7 +1153,10 @@ class ReadOnlyPasswordHashTest(SimpleTestCase):
)
def test_render(self):
widget = ReadOnlyPasswordHashWidget()
- value = "pbkdf2_sha256$100000$a6Pucb1qSFcD$WmCkn9Hqidj48NVe5x0FEM6A9YiOqQcl/83m2Z5udm0="
+ value = (
+ "pbkdf2_sha256$100000$a6Pucb1qSFcD$WmCkn9Hqidj48NVe5x0FEM6A9YiOqQcl/83m2Z5u"
+ "dm0="
+ )
self.assertHTMLEqual(
widget.render("name", value, {"id": "id_password"}),
"""
diff --git a/tests/auth_tests/test_hashers.py b/tests/auth_tests/test_hashers.py
index 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("<html>", message.get_payload(1).get_payload())
def test_email_found_custom_from(self):
- "Email is sent if a valid email address is provided for password reset when a custom from_email is provided."
+ """
+ Email is sent if a valid email address is provided for password reset
+ when a custom from_email is provided.
+ """
response = self.client.post(
"/password_reset_from_email/", {"email": "staffmember@example.com"}
)
diff --git a/tests/auth_tests/urls.py b/tests/auth_tests/urls.py
index 9f8cd14bdd..99fa22e4f4 100644
--- a/tests/auth_tests/urls.py
+++ b/tests/auth_tests/urls.py
@@ -148,7 +148,9 @@ urlpatterns = auth_urlpatterns + [
"reset/post_reset_login_custom_backend/<uidb64>/<token>/",
views.PasswordResetConfirmView.as_view(
post_reset_login=True,
- post_reset_login_backend="django.contrib.auth.backends.AllowAllUsersModelBackend",
+ post_reset_login_backend=(
+ "django.contrib.auth.backends.AllowAllUsersModelBackend"
+ ),
),
),
path("reset/missing_parameters/", views.PasswordResetConfirmView.as_view()),
diff --git a/tests/backends/mysql/tests.py b/tests/backends/mysql/tests.py
index 6ea289e151..139b363bf4 100644
--- a/tests/backends/mysql/tests.py
+++ b/tests/backends/mysql/tests.py
@@ -40,7 +40,8 @@ class IsolationLevelTests(TestCase):
def get_isolation_level(connection):
with connection.cursor() as cursor:
cursor.execute(
- "SHOW VARIABLES WHERE variable_name IN ('transaction_isolation', 'tx_isolation')"
+ "SHOW VARIABLES "
+ "WHERE variable_name IN ('transaction_isolation', 'tx_isolation')"
)
return cursor.fetchone()[1].replace("-", " ")
diff --git a/tests/backends/oracle/tests.py b/tests/backends/oracle/tests.py
index 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/\$', <function <lambda> at 0x(\w+)>\) is "
- r"invalid. Ensure that urlpatterns is a list of path\(\) and/or re_path\(\) "
- r"instances\.$"
+ r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) "
+ r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or "
+ r"re_path\(\) instances\.$"
),
)
@@ -66,9 +66,9 @@ class CheckUrlConfigTests(SimpleTestCase):
self.assertRegex(
warning.msg,
(
- r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) is "
- r"invalid. Ensure that urlpatterns is a list of path\(\) and/or re_path\(\) "
- r"instances\.$"
+ r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) "
+ r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or "
+ r"re_path\(\) instances\.$"
),
)
@@ -211,7 +211,8 @@ class CheckCustomErrorHandlersTests(SimpleTestCase):
Error(
"The custom handler{} view 'check_framework.urls."
"bad_function_based_error_handlers.bad_handler' "
- "does not take the correct number of arguments (request{}).".format(
+ "does not take the correct number of arguments "
+ "(request{}).".format(
code, ", exception" if num_params == 2 else ""
),
id="urls.E007",
@@ -254,7 +255,8 @@ class CheckCustomErrorHandlersTests(SimpleTestCase):
]
hints = [
"Could not import '{}'. View does not exist in module django.views.",
- "Could not import '{}'. Parent module django.invalid_module does not exist.",
+ "Could not import '{}'. Parent module django.invalid_module does not "
+ "exist.",
"No module named 'invalid_module'",
"Could not import '{}'. The path must be fully qualified.",
]
diff --git a/tests/contenttypes_tests/test_checks.py b/tests/contenttypes_tests/test_checks.py
index b3f4a0f4ba..bd36c569a1 100644
--- a/tests/contenttypes_tests/test_checks.py
+++ b/tests/contenttypes_tests/test_checks.py
@@ -60,7 +60,8 @@ class GenericForeignKeyTests(SimpleTestCase):
Model.content_object.check(),
[
checks.Error(
- "'Model.content_type' is not a ForeignKey to 'contenttypes.ContentType'.",
+ "'Model.content_type' is not a ForeignKey to "
+ "'contenttypes.ContentType'.",
hint=(
"GenericForeignKeys must use a ForeignKey to "
"'contenttypes.ContentType' as the 'content_type' field."
@@ -221,7 +222,9 @@ class GenericRelationTests(SimpleTestCase):
"Field defines a relation with the model "
"'contenttypes_tests.SwappedModel', "
"which has been swapped out.",
- hint="Update the relation to point at 'settings.TEST_SWAPPED_MODEL'.",
+ hint=(
+ "Update the relation to point at 'settings.TEST_SWAPPED_MODEL'."
+ ),
obj=Model.rel.field,
id="fields.E301",
)
diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py
index 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="""
-<html><body><h1>\u00a1Unicode!<form method="post"><input type="text"></form></body></html>
+<html>
+<body><h1>\u00a1Unicode!<form method="post"><input type="text"></form></body>
+</html>
"""
)
diff --git a/tests/custom_lookups/tests.py b/tests/custom_lookups/tests.py
index 2af145595e..1cf99b8300 100644
--- a/tests/custom_lookups/tests.py
+++ b/tests/custom_lookups/tests.py
@@ -512,8 +512,10 @@ class YearLteTests(TestCase):
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params + lhs_params + rhs_params
return (
- "%(lhs)s >= str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
- "AND %(lhs)s <= str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
+ "%(lhs)s >= "
+ "str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
+ "AND %(lhs)s <= "
+ "str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
@@ -525,12 +527,12 @@ class YearLteTests(TestCase):
finally:
delattr(YearExact, "as_" + connection.vendor)
try:
- # The other way is to subclass the original lookup and register the subclassed
- # lookup instead of the original.
+ # The other way is to subclass the original lookup and register the
+ # subclassed lookup instead of the original.
class CustomYearExact(YearExact):
- # This method should be named "as_mysql" for MySQL, "as_postgresql" for postgres
- # and so on, but as we don't know which DB we are running on, we need to use
- # setattr.
+ # This method should be named "as_mysql" for MySQL,
+ # "as_postgresql" for postgres and so on, but as we don't know
+ # which DB we are running on, we need to use setattr.
def as_custom_sql(self, compiler, connection):
lhs_sql, lhs_params = self.process_lhs(
compiler, connection, self.lhs.lhs
@@ -538,8 +540,10 @@ class YearLteTests(TestCase):
rhs_sql, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params + lhs_params + rhs_params
return (
- "%(lhs)s >= str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
- "AND %(lhs)s <= str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
+ "%(lhs)s >= "
+ "str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
+ "AND %(lhs)s <= "
+ "str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')"
% {"lhs": lhs_sql, "rhs": rhs_sql},
params,
)
@@ -584,7 +588,10 @@ class LookupTransformCallOrderTests(SimpleTestCase):
def test_call_order(self):
with register_lookup(models.DateField, TrackCallsYearTransform):
# junk lookup - tries lookup, then transform, then fails
- msg = "Unsupported lookup 'junk' for IntegerField or join on the field not permitted."
+ msg = (
+ "Unsupported lookup 'junk' for IntegerField or join on the field not "
+ "permitted."
+ )
with self.assertRaisesMessage(FieldError, msg):
Author.objects.filter(birthdate__testyear__junk=2012)
self.assertEqual(
diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py
index 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())),
- "<Window: Avg(F(salary)) OVER (OrderByList(OrderBy(F(department), descending=False)))>",
+ "<Window: Avg(F(salary)) OVER (OrderByList(OrderBy(F(department), "
+ "descending=False)))>",
)
def test_window_frame_repr(self):
diff --git a/tests/extra_regress/tests.py b/tests/extra_regress/tests.py
index 51ba601c1d..da403df98c 100644
--- a/tests/extra_regress/tests.py
+++ b/tests/extra_regress/tests.py
@@ -36,7 +36,8 @@ class ExtraRegressTests(TestCase):
# Queryset to match most recent revision:
qs = RevisionableModel.objects.extra(
where=[
- "%(table)s.id IN (SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)"
+ "%(table)s.id IN "
+ "(SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)"
% {
"table": RevisionableModel._meta.db_table,
}
diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py
index 6d6949ef01..f7bbb343d6 100644
--- a/tests/file_storage/tests.py
+++ b/tests/file_storage/tests.py
@@ -953,7 +953,10 @@ class FieldCallableFileStorageTests(SimpleTestCase):
class NotStorage:
pass
- msg = "FileField.storage must be a subclass/instance of django.core.files.storage.Storage"
+ msg = (
+ "FileField.storage must be a subclass/instance of "
+ "django.core.files.storage.Storage"
+ )
for invalid_type in (NotStorage, str, list, set, tuple):
with self.subTest(invalid_type=invalid_type):
with self.assertRaisesMessage(TypeError, msg):
diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py
index 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(),
[
- "<Visa: Django Reinhardt Can add user, Can change user, Can delete user>",
+ "<Visa: Django Reinhardt Can add user, Can change user, Can delete "
+ "user>",
"<Visa: Stephane Grappelli Can add user>",
"<Visa: Prince >",
],
@@ -288,7 +317,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
self.assertQuerysetEqual(
Visa.objects.all(),
[
- "<Visa: Django Reinhardt Can add user, Can change user, Can delete user>",
+ "<Visa: Django Reinhardt Can add user, Can change user, Can delete "
+ "user>",
"<Visa: Stephane Grappelli Can add user, Can delete user>",
'<Visa: Artist formerly known as "Prince" Can change user>',
],
@@ -310,102 +340,176 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# By default, you get raw keys on dumpdata
self._dumpdata_assert(
["fixtures.book"],
- '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]',
+ '[{"pk": 1, "model": "fixtures.book", "fields": '
+ '{"name": "Music for all ages", "authors": [3, 1]}}]',
)
# But you can get natural keys if you ask for them and they are available
self._dumpdata_assert(
["fixtures.book"],
- '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist '
- 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
+ '[{"pk": 1, "model": "fixtures.book", "fields": '
+ '{"name": "Music for all ages", "authors": '
+ '[["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
natural_foreign_keys=True,
)
- # You can also omit the primary keys for models that we can get later with natural keys.
+ # You can also omit the primary keys for models that we can get later
+ # with natural keys.
self._dumpdata_assert(
["fixtures.person"],
- '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, {"fields": {"name": "Stephane '
- 'Grappelli"}, "model": "fixtures.person"}, {"fields": {"name": "Artist formerly known as '
- '\\"Prince\\""}, "model": "fixtures.person"}]',
+ '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, '
+ '{"fields": {"name": "Stephane Grappelli"}, "model": "fixtures.person"}, '
+ '{"fields": {"name": "Artist formerly known as \\"Prince\\""}, '
+ '"model": "fixtures.person"}]',
natural_primary_keys=True,
)
# Dump the current contents of the database as a JSON fixture
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is '
- 'great!", "pub_date": "2006-06-16T11:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}, {"pk": 4, '
- '"model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": '
- '"2006-06-16T15:00:00"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML '
- 'identified as leading cause of cancer", "pub_date": "2006-06-16T16:00:00"}}, {"pk": 1, "model": '
- '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": '
- '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": '
- '"legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", '
- '"article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": '
- '{"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 1, '
- '"model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": '
- '"fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", '
- '"fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.visa", '
- '"fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], '
- '["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": '
- '"fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", '
- '"user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person":'
- ' ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, '
- '{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist '
- 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker on TV is great!", '
+ '"pub_date": "2006-06-16T11:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}, '
+ '{"pk": 4, "model": "fixtures.article", "fields": '
+ '{"headline": "Django conquers world!", '
+ '"pub_date": "2006-06-16T15:00:00"}}, '
+ '{"pk": 5, "model": "fixtures.article", "fields": '
+ '{"headline": "XML identified as leading cause of cancer", '
+ '"pub_date": "2006-06-16T16:00:00"}}, '
+ '{"pk": 1, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "copyright", '
+ '"tagged_id": 3}}, '
+ '{"pk": 2, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "legal", '
+ '"tagged_id": 3}}, '
+ '{"pk": 3, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "django", '
+ '"tagged_id": 4}}, '
+ '{"pk": 4, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "world domination", '
+ '"tagged_id": 4}}, '
+ '{"pk": 1, "model": "fixtures.person", '
+ '"fields": {"name": "Django Reinhardt"}}, '
+ '{"pk": 2, "model": "fixtures.person", '
+ '"fields": {"name": "Stephane Grappelli"}}, '
+ '{"pk": 3, "model": "fixtures.person", '
+ '"fields": {"name": "Artist formerly known as \\"Prince\\""}}, '
+ '{"pk": 1, "model": "fixtures.visa", '
+ '"fields": {"person": ["Django Reinhardt"], "permissions": '
+ '[["add_user", "auth", "user"], ["change_user", "auth", "user"], '
+ '["delete_user", "auth", "user"]]}}, '
+ '{"pk": 2, "model": "fixtures.visa", "fields": '
+ '{"person": ["Stephane Grappelli"], "permissions": '
+ '[["add_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, '
+ '{"pk": 3, "model": "fixtures.visa", "fields": '
+ '{"person": ["Artist formerly known as \\"Prince\\""], "permissions": '
+ '[["change_user", "auth", "user"]]}}, '
+ '{"pk": 1, "model": "fixtures.book", "fields": '
+ '{"name": "Music for all ages", "authors": '
+ '[["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
natural_foreign_keys=True,
)
# Dump the current contents of the database as an XML fixture
self._dumpdata_assert(
["fixtures"],
- '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" '
- 'model="fixtures.category"><field type="CharField" name="title">News Stories</field><field '
- 'type="TextField" name="description">Latest news stories</field></object><object pk="2" '
- 'model="fixtures.article"><field type="CharField" name="headline">Poker on TV is great!</field><field '
- 'type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field></object><object pk="3" '
- 'model="fixtures.article"><field type="CharField" name="headline">Copyright is fine the way it '
- 'is</field><field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field></object><object '
- 'pk="4" model="fixtures.article"><field type="CharField" name="headline">Django conquers world!'
- '</field><field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field></object><object '
- 'pk="5" model="fixtures.article"><field type="CharField" name="headline">XML identified as leading '
- 'cause of cancer</field><field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field>'
- '</object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field>'
- '<field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures'
- '</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3'
- '</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">legal'
- '</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>'
- 'fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" '
- 'name="tagged_id">3</field></object><object pk="3" model="fixtures.tag"><field type="CharField" '
- 'name="name">django</field><field to="contenttypes.contenttype" name="tagged_type" '
- 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field '
- 'type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="4" model="fixtures.tag">'
- '<field type="CharField" name="name">world domination</field><field to="contenttypes.contenttype" '
- 'name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field>'
- '<field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="1" '
- 'model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object>'
- '<object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli'
- '</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">'
- 'Artist formerly known as "Prince"</field></object><object pk="1" model="fixtures.visa"><field '
- 'to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Django Reinhardt</natural></field>'
- '<field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user'
- "</natural><natural>auth</natural><natural>user</natural></object><object><natural>change_user"
- "</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user"
- '</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="2" '
- 'model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Stephane'
- ' Grappelli</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel">'
- "<object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object>"
- "<natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field>"
- '</object><object pk="3" model="fixtures.visa"><field to="fixtures.person" name="person" '
- 'rel="ManyToOneRel"><natural>Artist formerly known as "Prince"</natural></field><field '
- 'to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>change_user</natural>'
- '<natural>auth</natural><natural>user</natural></object></field></object><object pk="1" '
- 'model="fixtures.book"><field type="CharField" name="name">Music for all ages</field><field '
- 'to="fixtures.person" name="authors" rel="ManyToManyRel"><object><natural>Artist formerly known as '
- '"Prince"</natural></object><object><natural>Django Reinhardt</natural></object></field></object>'
- "</django-objects>",
+ '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0">'
+ '<object pk="1" model="fixtures.category">'
+ '<field type="CharField" name="title">News Stories</field>'
+ '<field type="TextField" name="description">Latest news stories</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.article">'
+ '<field type="CharField" name="headline">Poker on TV is great!</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.article">'
+ '<field type="CharField" name="headline">Copyright is fine the way it is'
+ "</field>"
+ '<field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field>'
+ "</object>"
+ '<object pk="4" model="fixtures.article">'
+ '<field type="CharField" name="headline">Django conquers world!</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field>'
+ "</object>"
+ '<object pk="5" model="fixtures.article">'
+ '<field type="CharField" name="headline">'
+ "XML identified as leading cause of cancer</field>"
+ '<field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.tag">'
+ '<field type="CharField" name="name">copyright</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.tag">'
+ '<field type="CharField" name="name">legal</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field></object>'
+ '<object pk="3" model="fixtures.tag">'
+ '<field type="CharField" name="name">django</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">4</field>'
+ "</object>"
+ '<object pk="4" model="fixtures.tag">'
+ '<field type="CharField" name="name">world domination</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
+ "</field>"
+ '<field type="PositiveIntegerField" name="tagged_id">4</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.person">'
+ '<field type="CharField" name="name">Django Reinhardt</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.person">'
+ '<field type="CharField" name="name">Stephane Grappelli</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.person">'
+ '<field type="CharField" name="name">Artist formerly known as "Prince"'
+ "</field>"
+ "</object>"
+ '<object pk="1" model="fixtures.visa">'
+ '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
+ "<natural>Django Reinhardt</natural></field>"
+ '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
+ "<object><natural>add_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object><object><natural>change_user</natural>"
+ "<natural>auth</natural><natural>user</natural></object>"
+ "<object><natural>delete_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object></field>"
+ "</object>"
+ '<object pk="2" model="fixtures.visa">'
+ '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
+ "<natural>Stephane Grappelli</natural></field>"
+ '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
+ "<object><natural>add_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object>"
+ "<object><natural>delete_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object></field>"
+ "</object>"
+ '<object pk="3" model="fixtures.visa">'
+ '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
+ '<natural>Artist formerly known as "Prince"</natural></field>'
+ '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
+ "<object><natural>change_user</natural><natural>auth</natural>"
+ "<natural>user</natural></object></field>"
+ "</object>"
+ '<object pk="1" model="fixtures.book">'
+ '<field type="CharField" name="name">Music for all ages</field>'
+ '<field to="fixtures.person" name="authors" rel="ManyToManyRel">'
+ '<object><natural>Artist formerly known as "Prince"</natural></object>'
+ "<object><natural>Django Reinhardt</natural></object></field>"
+ "</object></django-objects>",
format="xml",
natural_foreign_keys=True,
)
@@ -418,33 +522,37 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# Excluding fixtures app should only leave sites
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]',
+ '[{"pk": 1, "model": "sites.site", "fields": '
+ '{"domain": "example.com", "name": "example.com"}}]',
exclude_list=["fixtures"],
)
# Excluding fixtures.Article/Book should leave fixtures.Category
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, '
- '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}]',
+ '[{"pk": 1, "model": "sites.site", '
+ '"fields": {"domain": "example.com", "name": "example.com"}}, '
+ '{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}]',
exclude_list=["fixtures.Article", "fixtures.Book"],
)
# Excluding fixtures and fixtures.Article/Book should be a no-op
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, '
- '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}]',
+ '[{"pk": 1, "model": "sites.site", '
+ '"fields": {"domain": "example.com", "name": "example.com"}}, '
+ '{"pk": 1, "model": "fixtures.category", '
+ '"fields": {"description": "Latest news stories", '
+ '"title": "News Stories"}}]',
exclude_list=["fixtures.Article", "fixtures.Book"],
)
# Excluding sites and fixtures.Article/Book should only leave fixtures.Category
self._dumpdata_assert(
["sites", "fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}]',
exclude_list=["fixtures.Article", "fixtures.Book", "sites"],
)
@@ -486,8 +594,9 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# even those normally filtered by the manager
self._dumpdata_assert(
["fixtures.Spy"],
- '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": '
- '"fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk),
+ '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, '
+ '{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]'
+ % (spy2.pk, spy1.pk),
use_base_manager=True,
)
@@ -496,15 +605,19 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture2.json", verbosity=0)
self._dumpdata_assert(
["fixtures.Article"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": '
- '"Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", '
+ '"fields": {"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
self._dumpdata_assert(
["fixtures.Article"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
+ '[{"pk": 2, "model": "fixtures.article", '
+ '"fields": {"headline": "Poker has no place on ESPN", '
'"pub_date": "2006-06-16T12:00:00"}}]',
primary_keys="2",
)
@@ -514,9 +627,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
):
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
@@ -525,9 +641,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
):
self._dumpdata_assert(
"",
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
@@ -536,9 +655,12 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
):
self._dumpdata_assert(
["fixtures.Article", "fixtures.category"],
- '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
- '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
+ '[{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Copyright is fine the way it is", '
+ '"pub_date": "2006-06-16T14:00:00"}}]',
primary_keys="2,3",
)
@@ -561,10 +683,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json",
)
@@ -572,10 +698,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.gz",
)
@@ -584,10 +714,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.bz2",
)
@@ -596,10 +730,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.lzma",
)
@@ -608,10 +746,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture1.json", verbosity=0)
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.xz",
)
@@ -621,10 +763,14 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
with self.assertWarnsMessage(RuntimeWarning, msg):
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
filename="dumpdata.json.zip",
)
@@ -679,8 +825,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
warnings.simplefilter("always")
self._dumpdata_assert(
["fixtures.ProxySpy", "fixtures.Spy"],
- '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]'
- % spy.pk,
+ '[{"pk": %d, "model": "fixtures.spy", '
+ '"fields": {"cover_blown": false}}]' % spy.pk,
)
self.assertEqual(len(warning_list), 0)
@@ -743,7 +889,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
management.call_command("loaddata", "fixture5", verbosity=0)
def test_db_loading(self):
- # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly
+ # Load db fixtures 1 and 2. These will load using the 'default'
+ # database identifier implicitly.
management.call_command("loaddata", "db_fixture_1", verbosity=0)
management.call_command("loaddata", "db_fixture_2", verbosity=0)
self.assertSequenceEqual(
@@ -809,7 +956,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
)
def test_loading_using(self):
- # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly
+ # Load fixtures 1 and 2. These will load using the 'default' database
+ # identifier explicitly.
management.call_command(
"loaddata", "db_fixture_1", verbosity=0, database="default"
)
@@ -825,7 +973,8 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
)
def test_unmatched_identifier_loading(self):
- # Try to load db fixture 3. This won't load because the database identifier doesn't match
+ # Db fixture 3 won't load because the database identifier doesn't
+ # match.
with self.assertRaisesMessage(
CommandError, "No fixture named 'db_fixture_3' found."
):
@@ -857,14 +1006,23 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# Dump the current contents of the database as a JSON fixture
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}, {"pk": 1, "model": '
- '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": '
- '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": '
- '"law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django '
- 'Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, '
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}, '
+ '{"pk": 1, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "copyright", '
+ '"tagged_id": 3}}, '
+ '{"pk": 2, "model": "fixtures.tag", "fields": '
+ '{"tagged_type": ["fixtures", "article"], "name": "law", "tagged_id": 3}}, '
+ '{"pk": 1, "model": "fixtures.person", "fields": '
+ '{"name": "Django Reinhardt"}}, '
+ '{"pk": 2, "model": "fixtures.person", "fields": '
+ '{"name": "Stephane Grappelli"}}, '
'{"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}]',
natural_foreign_keys=True,
)
@@ -872,23 +1030,42 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
# Dump the current contents of the database as an XML fixture
self._dumpdata_assert(
["fixtures"],
- '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" '
- 'model="fixtures.category"><field type="CharField" name="title">News Stories</field><field '
- 'type="TextField" name="description">Latest news stories</field></object><object pk="2" '
- 'model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field>'
- '<field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" '
- 'model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field>'
- '<field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" '
- 'model="fixtures.tag"><field type="CharField" name="name">copyright</field><field '
- 'to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural>'
- '<natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field>'
- '</object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field '
- 'to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural>'
- '<natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field>'
- '</object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt'
- '</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane '
- 'Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">'
- "Prince</field></object></django-objects>",
+ '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0">'
+ '<object pk="1" model="fixtures.category">'
+ '<field type="CharField" name="title">News Stories</field>'
+ '<field type="TextField" name="description">Latest news stories</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.article">'
+ '<field type="CharField" name="headline">Poker has no place on ESPN</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.article">'
+ '<field type="CharField" name="headline">Time to reform copyright</field>'
+ '<field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.tag">'
+ '<field type="CharField" name="name">copyright</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural>'
+ "<natural>article</natural></field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.tag">'
+ '<field type="CharField" name="name">law</field>'
+ '<field to="contenttypes.contenttype" name="tagged_type" '
+ 'rel="ManyToOneRel"><natural>fixtures</natural>'
+ "<natural>article</natural></field>"
+ '<field type="PositiveIntegerField" name="tagged_id">3</field>'
+ "</object>"
+ '<object pk="1" model="fixtures.person">'
+ '<field type="CharField" name="name">Django Reinhardt</field>'
+ "</object>"
+ '<object pk="2" model="fixtures.person">'
+ '<field type="CharField" name="name">Stephane Grappelli</field>'
+ "</object>"
+ '<object pk="3" model="fixtures.person">'
+ '<field type="CharField" name="name">Prince</field>'
+ "</object></django-objects>",
format="xml",
natural_foreign_keys=True,
)
@@ -1024,10 +1201,14 @@ class FixtureTransactionTests(DumpDataAssertMixin, TransactionTestCase):
# Dump the current contents of the database as a JSON fixture
self._dumpdata_assert(
["fixtures"],
- '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
- '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
- 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
- '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
+ '[{"pk": 1, "model": "fixtures.category", "fields": '
+ '{"description": "Latest news stories", "title": "News Stories"}}, '
+ '{"pk": 2, "model": "fixtures.article", "fields": '
+ '{"headline": "Poker has no place on ESPN", '
+ '"pub_date": "2006-06-16T12:00:00"}}, '
+ '{"pk": 3, "model": "fixtures.article", "fields": '
+ '{"headline": "Time to reform copyright", '
+ '"pub_date": "2006-06-16T13:00:00"}}]',
)
# Load fixture 4 (compressed), using format discovery
@@ -1108,7 +1289,8 @@ class ForwardReferenceTests(DumpDataAssertMixin, TestCase):
self._dumpdata_assert(
["fixtures"],
'[{"model": "fixtures.naturalkeything", '
- '"fields": {"key": "t1", "other_thing": null, "other_things": [["t2"], ["t3"]]}}, '
+ '"fields": {"key": "t1", "other_thing": null, '
+ '"other_things": [["t2"], ["t3"]]}}, '
'{"model": "fixtures.naturalkeything", '
'"fields": {"key": "t2", "other_thing": null, "other_things": []}}, '
'{"model": "fixtures.naturalkeything", '
diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py
index 318c9a3a14..61dd12754c 100644
--- a/tests/fixtures_regress/tests.py
+++ b/tests/fixtures_regress/tests.py
@@ -209,7 +209,10 @@ class TestFixtures(TestCase):
Test for ticket #4371 -- Loading data of an unknown format should fail
Validate that error conditions are caught correctly
"""
- msg = "Problem installing fixture 'bad_fix.ture1': unkn is not a known serialization format."
+ msg = (
+ "Problem installing fixture 'bad_fix.ture1': unkn is not a known "
+ "serialization format."
+ )
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
@@ -438,14 +441,14 @@ class TestFixtures(TestCase):
)
self.assertJSONEqual(
out.getvalue(),
- """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
- % widget.pk,
+ '[{"pk": %d, "model": "fixtures_regress.widget", '
+ '"fields": {"name": "grommet"}}]' % widget.pk,
)
@skipUnlessDBFeature("supports_forward_references")
def test_loaddata_works_when_fixture_has_forward_refs(self):
"""
- Regression for #3615 - Forward references cause fixtures not to load in MySQL (InnoDB)
+ Forward references cause fixtures not to load in MySQL (InnoDB).
"""
management.call_command(
"loaddata",
@@ -457,7 +460,7 @@ class TestFixtures(TestCase):
def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
"""
- Regression for #3615 - Ensure data with nonexistent child key references raises error
+ Data with nonexistent child key references raises error.
"""
with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"):
management.call_command(
@@ -489,9 +492,13 @@ class TestFixtures(TestCase):
def test_loaddata_no_fixture_specified(self):
"""
- Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line.
+ Error is quickly reported when no fixtures is provided in the command
+ line.
"""
- msg = "No database fixture specified. Please provide the path of at least one fixture in the command line."
+ msg = (
+ "No database fixture specified. Please provide the path of at least one "
+ "fixture in the command line."
+ )
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command(
"loaddata",
@@ -648,10 +655,13 @@ class NaturalKeyFixtureTests(TestCase):
self.assertJSONEqual(
out.getvalue(),
"""
- [{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"},
- {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"},
+ [{"fields": {"main": null, "name": "Amazon"},
+ "model": "fixtures_regress.store"},
+ {"fields": {"main": null, "name": "Borders"},
+ "model": "fixtures_regress.store"},
{"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"},
- {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]],
+ {"pk": 1, "model": "fixtures_regress.book",
+ "fields": {"stores": [["Amazon"], ["Borders"]],
"name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
""",
)
@@ -770,9 +780,12 @@ class NaturalKeyFixtureTests(TestCase):
self.assertQuerysetEqual(
books,
[
- "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>",
- "<Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>",
- "<Book: Permutation City by Greg Egan (available at Angus and Robertson)>",
+ "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, "
+ "Borders)>",
+ "<Book: Ender's Game by Orson Scott Card (available at Collins "
+ "Bookstore)>",
+ "<Book: Permutation City by Greg Egan (available at Angus and "
+ "Robertson)>",
],
transform=repr,
)
diff --git a/tests/flatpages_tests/test_csrf.py b/tests/flatpages_tests/test_csrf.py
index d26546876e..62ac5f9a14 100644
--- a/tests/flatpages_tests/test_csrf.py
+++ b/tests/flatpages_tests/test_csrf.py
@@ -105,12 +105,18 @@ class FlatpageCSRFTests(TestCase):
self.assertEqual(response.status_code, 404)
def test_post_view_flatpage(self):
- "POSTing to a flatpage served through a view will raise a CSRF error if no token is provided (Refs #14156)"
+ """
+ POSTing to a flatpage served through a view will raise a CSRF error if
+ no token is provided.
+ """
response = self.client.post("/flatpage_root/flatpage/")
self.assertEqual(response.status_code, 403)
def test_post_fallback_flatpage(self):
- "POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided (Refs #14156)"
+ """
+ POSTing to a flatpage served by the middleware will raise a CSRF error
+ if no token is provided.
+ """
response = self.client.post("/flatpage/")
self.assertEqual(response.status_code, 403)
diff --git a/tests/flatpages_tests/test_forms.py b/tests/flatpages_tests/test_forms.py
index 7f56549235..00caf01960 100644
--- a/tests/flatpages_tests/test_forms.py
+++ b/tests/flatpages_tests/test_forms.py
@@ -91,7 +91,10 @@ class FlatpageAdminFormTests(TestCase):
)
def test_flatpage_admin_form_url_uniqueness_validation(self):
- "The flatpage admin form correctly enforces url uniqueness among flatpages of the same site"
+ """
+ The flatpage admin form correctly enforces url uniqueness among
+ flatpages of the same site.
+ """
data = dict(url="/myflatpage1/", **self.form_data)
FlatpageForm(data=data).save()
@@ -105,7 +108,8 @@ class FlatpageAdminFormTests(TestCase):
f.errors,
{
"__all__": [
- "Flatpage with url /myflatpage1/ already exists for site example.com"
+ "Flatpage with url /myflatpage1/ already exists for site "
+ "example.com"
]
},
)
diff --git a/tests/flatpages_tests/test_middleware.py b/tests/flatpages_tests/test_middleware.py
index 193c8232bf..581947e9f6 100644
--- a/tests/flatpages_tests/test_middleware.py
+++ b/tests/flatpages_tests/test_middleware.py
@@ -113,7 +113,10 @@ class FlatpageMiddlewareTests(TestDataMixin, TestCase):
self.assertContains(response, "<p>Isn't it sekrit!</p>")
def test_fallback_flatpage_special_chars(self):
- "A flatpage with special chars in the URL can be served by the fallback middleware"
+ """
+ A flatpage with special chars in the URL can be served by the fallback
+ middleware.
+ """
fp = FlatPage.objects.create(
url="/some.very_special~chars-here/",
title="A very special page",
@@ -171,7 +174,10 @@ class FlatpageMiddlewareAppendSlashTests(TestDataMixin, TestCase):
self.assertEqual(response.status_code, 404)
def test_redirect_fallback_flatpage_special_chars(self):
- "A flatpage with special chars in the URL can be served by the fallback middleware and should add a slash"
+ """
+ A flatpage with special chars in the URL can be served by the fallback
+ middleware and should add a slash.
+ """
fp = FlatPage.objects.create(
url="/some.very_special~chars-here/",
title="A very special page",
diff --git a/tests/flatpages_tests/test_templatetags.py b/tests/flatpages_tests/test_templatetags.py
index 1c7bc4d38a..eb36ee375b 100644
--- a/tests/flatpages_tests/test_templatetags.py
+++ b/tests/flatpages_tests/test_templatetags.py
@@ -61,7 +61,10 @@ class FlatpageTemplateTagTests(TestCase):
self.assertEqual(out, "A Flatpage,A Nested Flatpage,")
def test_get_flatpages_tag_for_anon_user(self):
- "The flatpage template tag retrieves unregistered flatpages for an anonymous user"
+ """
+ The flatpage template tag retrieves unregistered flatpages for an
+ anonymous user.
+ """
out = Template(
"{% load flatpages %}"
"{% get_flatpages for anonuser as flatpages %}"
@@ -97,7 +100,10 @@ class FlatpageTemplateTagTests(TestCase):
self.assertEqual(out, "A Nested Flatpage,")
def test_get_flatpages_with_prefix_for_anon_user(self):
- "The flatpage template tag retrieves unregistered prefixed flatpages for an anonymous user"
+ """
+ The flatpage template tag retrieves unregistered prefixed flatpages for
+ an anonymous user.
+ """
out = Template(
"{% load flatpages %}"
"{% get_flatpages '/location/' for anonuser as location_flatpages %}"
@@ -108,7 +114,10 @@ class FlatpageTemplateTagTests(TestCase):
self.assertEqual(out, "A Nested Flatpage,")
def test_get_flatpages_with_prefix_for_user(self):
- "The flatpage template tag retrieve prefixed flatpages for an authenticated user"
+ """
+ The flatpage template tag retrieve prefixed flatpages for an
+ authenticated user.
+ """
me = User.objects.create_user("testuser", "test@example.com", "s3krit")
out = Template(
"{% load flatpages %}"
@@ -156,5 +165,6 @@ class FlatpageTemplateTagTests(TestCase):
render("{% load flatpages %}{% get_flatpages for user as flatpages asdf %}")
with self.assertRaisesMessage(TemplateSyntaxError, msg):
render(
- "{% load flatpages %}{% get_flatpages prefix for user as flatpages asdf %}"
+ "{% load flatpages %}"
+ "{% get_flatpages prefix for user as flatpages asdf %}"
)
diff --git a/tests/flatpages_tests/test_views.py b/tests/flatpages_tests/test_views.py
index 2a01587a7a..24ad07d35a 100644
--- a/tests/flatpages_tests/test_views.py
+++ b/tests/flatpages_tests/test_views.py
@@ -146,7 +146,10 @@ class FlatpageViewAppendSlashTests(TestDataMixin, TestCase):
self.assertEqual(response.status_code, 404)
def test_redirect_fallback_flatpage(self):
- "A fallback flatpage won't be served if the middleware is disabled and should not add a slash"
+ """
+ A fallback flatpage won't be served if the middleware is disabled and
+ should not add a slash.
+ """
response = self.client.get("/flatpage")
self.assertEqual(response.status_code, 404)
@@ -159,7 +162,10 @@ class FlatpageViewAppendSlashTests(TestDataMixin, TestCase):
self.assertEqual(response.status_code, 404)
def test_redirect_view_flatpage_special_chars(self):
- "A flatpage with special chars in the URL can be served through a view and should add a slash"
+ """
+ A flatpage with special chars in the URL can be served through a view
+ and should add a slash.
+ """
fp = FlatPage.objects.create(
url="/some.very_special~chars-here/",
title="A very special page",
diff --git a/tests/foreign_object/test_forms.py b/tests/foreign_object/test_forms.py
index 61f8f42295..a3ad74d28b 100644
--- a/tests/foreign_object/test_forms.py
+++ b/tests/foreign_object/test_forms.py
@@ -15,7 +15,8 @@ class FormsTests(TestCase):
fields = "__all__"
def test_foreign_object_form(self):
- # A very crude test checking that the non-concrete fields do not get form fields.
+ # A very crude test checking that the non-concrete fields do not get
+ # form fields.
form = FormsTests.ArticleForm()
self.assertIn("id_pub_date", form.as_table())
self.assertNotIn("active_translation", form.as_table())
diff --git a/tests/foreign_object/tests.py b/tests/foreign_object/tests.py
index 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,
- '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" required>',
+ '<input step="0.01" name="f" min="0.5" max="1.5" type="number" id="id_f" '
+ "required>",
)
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is less than or equal to 1.5.'"
diff --git a/tests/forms_tests/field_tests/test_emailfield.py b/tests/forms_tests/field_tests/test_emailfield.py
index d1d52dd608..869a1aacc5 100644
--- a/tests/forms_tests/field_tests/test_emailfield.py
+++ b/tests/forms_tests/field_tests/test_emailfield.py
@@ -49,7 +49,8 @@ class EmailFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
f = EmailField(min_length=10, max_length=15)
self.assertWidgetRendersTo(
f,
- '<input id="id_f" type="email" name="f" maxlength="15" minlength="10" required>',
+ '<input id="id_f" type="email" name="f" maxlength="15" minlength="10" '
+ "required>",
)
with self.assertRaisesMessage(
ValidationError,
diff --git a/tests/forms_tests/field_tests/test_floatfield.py b/tests/forms_tests/field_tests/test_floatfield.py
index 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,
- '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" required>',
+ '<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" '
+ "required>",
)
with self.assertRaisesMessage(
ValidationError, "'Ensure this value is less than or equal to 1.5.'"
@@ -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,
- '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" required>',
+ '<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" '
+ "required>",
)
def test_floatfield_localized(self):
diff --git a/tests/forms_tests/field_tests/test_multivaluefield.py b/tests/forms_tests/field_tests/test_multivaluefield.py
index 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(),
"""
<tr><th><label>Field1:</label></th>
- <td><input type="text" name="field1_0" value="some text" id="id_field1_0" required>
+ <td><input type="text" name="field1_0" value="some text" id="id_field1_0"
+ required>
<select multiple name="field1_1" id="id_field1_1" required>
<option value="J" selected>John</option>
<option value="P" selected>Paul</option>
<option value="G">George</option>
<option value="R">Ringo</option>
</select>
- <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0" required>
- <input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1" required></td></tr>
+ <input type="text" name="field1_2_0" value="2007-04-25" id="id_field1_2_0"
+ required>
+ <input type="text" name="field1_2_1" value="06:24:00" id="id_field1_2_1"
+ required></td></tr>
""",
)
diff --git a/tests/forms_tests/field_tests/test_nullbooleanfield.py b/tests/forms_tests/field_tests/test_nullbooleanfield.py
index 5b632c8de3..c1e120c0bb 100644
--- a/tests/forms_tests/field_tests/test_nullbooleanfield.py
+++ b/tests/forms_tests/field_tests/test_nullbooleanfield.py
@@ -27,9 +27,11 @@ class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
f = HiddenNullBooleanForm()
self.assertHTMLEqual(
- '<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1">'
- '<input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2">',
str(f),
+ '<input type="hidden" name="hidden_nullbool1" value="True" '
+ 'id="id_hidden_nullbool1">'
+ '<input type="hidden" name="hidden_nullbool2" value="False" '
+ 'id="id_hidden_nullbool2">',
)
def test_nullbooleanfield_3(self):
@@ -69,7 +71,8 @@ class NullBooleanFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
self.assertTrue(f.has_changed(True, False))
self.assertTrue(f.has_changed(True, None))
self.assertTrue(f.has_changed(True, False))
- # HiddenInput widget sends string values for boolean but doesn't clean them in value_from_datadict
+ # HiddenInput widget sends string values for boolean but doesn't clean
+ # them in value_from_datadict.
self.assertFalse(f.has_changed(False, "False"))
self.assertFalse(f.has_changed(True, "True"))
self.assertFalse(f.has_changed(None, ""))
diff --git a/tests/forms_tests/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"]),
- '<input type="text" name="first_name" value="John" id="id_first_name" required>',
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required>",
)
self.assertHTMLEqual(
str(p["last_name"]),
- '<input type="text" name="last_name" value="Lennon" id="id_last_name" required>',
+ '<input type="text" name="last_name" value="Lennon" id="id_last_name" '
+ "required>",
)
self.assertHTMLEqual(
str(p["birthday"]),
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required>",
)
- msg = "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, first_name, last_name."
+ msg = (
+ "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, "
+ "first_name, last_name."
+ )
with self.assertRaisesMessage(KeyError, msg):
p["nonexistentfield"]
@@ -143,12 +149,17 @@ class FormsTestCase(SimpleTestCase):
)
self.assertHTMLEqual(
str(p),
- """<tr><th><label for="id_first_name">First name:</label></th><td>
-<input type="text" name="first_name" value="John" id="id_first_name" required></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td>
-<input type="text" name="last_name" value="Lennon" id="id_last_name" required></td></tr>
-<tr><th><label for="id_birthday">Birthday:</label></th><td>
-<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></td></tr>""",
+ """
+ <tr><th><label for="id_first_name">First name:</label></th><td>
+ <input type="text" name="first_name" value="John" id="id_first_name"
+ required></td></tr>
+ <tr><th><label for="id_last_name">Last name:</label></th><td>
+ <input type="text" name="last_name" value="Lennon" id="id_last_name"
+ required></td></tr>
+ <tr><th><label for="id_birthday">Birthday:</label></th><td>
+ <input type="text" name="birthday" value="1940-10-9" id="id_birthday"
+ required></td></tr>
+ """,
)
def test_empty_dict(self):
@@ -276,33 +287,41 @@ class FormsTestCase(SimpleTestCase):
self.assertHTMLEqual(
p.as_table(),
'<tr><th><label for="id_first_name">First name:</label></th><td>'
- '<input type="text" name="first_name" value="John" id="id_first_name" required></td></tr>\n'
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required></td></tr>\n"
'<tr><th><label for="id_last_name">Last name:</label>'
'</th><td><input type="text" name="last_name" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"'
'id="id_last_name" required></td></tr>\n'
'<tr><th><label for="id_birthday">Birthday:</label></th><td>'
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></td></tr>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required></td></tr>",
)
self.assertHTMLEqual(
p.as_ul(),
'<li><label for="id_first_name">First name:</label> '
- '<input type="text" name="first_name" value="John" id="id_first_name" required></li>\n'
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required></li>\n"
'<li><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
- 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required></li>\n'
+ 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
+ 'id="id_last_name" required></li>\n'
'<li><label for="id_birthday">Birthday:</label> '
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></li>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required></li>",
)
self.assertHTMLEqual(
p.as_p(),
'<p><label for="id_first_name">First name:</label> '
- '<input type="text" name="first_name" value="John" id="id_first_name" required></p>\n'
+ '<input type="text" name="first_name" value="John" id="id_first_name" '
+ "required></p>\n"
'<p><label for="id_last_name">Last name:</label> '
'<input type="text" name="last_name" '
- 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" id="id_last_name" required></p>\n'
+ 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" '
+ 'id="id_last_name" required></p>\n'
'<p><label for="id_birthday">Birthday:</label> '
- '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" required></p>',
+ '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" '
+ "required></p>",
)
p = Person({"last_name": "Lennon"})
@@ -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 <label> around
- # the human-readable labels for a field.
+ # "auto_id" tells the Form to add an "id" attribute to each form
+ # element. If it's a string that contains '%s', Django will use that as
+ # a format string into which the field's name will be inserted. It will
+ # also put a <label> around the human-readable labels for a field.
p = Person(auto_id="%s_id")
self.assertHTMLEqual(
p.as_table(),
@@ -728,18 +747,21 @@ class FormsTestCase(SimpleTestCase):
</div></li>""",
)
- # Regarding auto_id and <label>, RadioSelect is a special case. Each radio button
- # gets a distinct ID, formed by appending an underscore plus the button's
- # zero-based index.
+ # Regarding auto_id and <label>, RadioSelect is a special case. Each
+ # radio button gets a distinct ID, formed by appending an underscore
+ # plus the button's zero-based index.
f = FrameworkForm(auto_id="id_%s")
self.assertHTMLEqual(
str(f["language"]),
- """<div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div>""",
+ """
+ <div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div>""",
)
# When RadioSelect is used with auto_id, and the whole form is printed
@@ -748,33 +770,47 @@ Java</label></div>
# accessibility for screen reader users.
self.assertHTMLEqual(
f.as_table(),
- """<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" id="id_name" required></td></tr>
-<tr><th><label>Language:</label></th><td><div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div></td></tr>""",
+ """
+ <tr><th><label for="id_name">Name:</label></th><td>
+ <input type="text" name="name" id="id_name" required></td></tr>
+ <tr><th><label>Language:</label></th><td><div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div></td></tr>""",
)
self.assertHTMLEqual(
f.as_ul(),
- """<li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li>
-<li><label>Language:</label> <div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div></li>""",
+ """
+ <li><label for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></li>
+ <li><label>Language:</label> <div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div></li>
+ """,
)
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p>
-<p><label>Language:</label> <div id="id_language">
-<div><label for="id_language_0"><input type="radio" id="id_language_0" value="P" name="language" required>
-Python</label></div>
-<div><label for="id_language_1"><input type="radio" id="id_language_1" value="J" name="language" required>
-Java</label></div>
-</div></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></p>
+ <p><label>Language:</label> <div id="id_language">
+ <div><label for="id_language_0">
+ <input type="radio" id="id_language_0" value="P" name="language" required>
+ Python</label></div>
+ <div><label for="id_language_1">
+ <input type="radio" id="id_language_1" value="J" name="language" required>
+ Java</label></div>
+ </div></p>
+ """,
)
def test_form_with_iterable_boundfield(self):
@@ -799,10 +835,17 @@ Java</label></div>
)
self.assertHTMLEqual(
"\n".join("<div>%s</div>" % bf for bf in f["name"]),
- """<div><label><input type="radio" name="name" value="john" required> John</label></div>
-<div><label><input type="radio" name="name" value="paul" required> Paul</label></div>
-<div><label><input type="radio" name="name" value="george" required> George</label></div>
-<div><label><input type="radio" name="name" value="ringo" required> Ringo</label></div>""",
+ """
+ <div><label>
+ <input type="radio" name="name" value="john" required> John</label></div>
+ <div><label>
+ <input type="radio" name="name" value="paul" required> Paul</label></div>
+ <div><label>
+ <input type="radio" name="name" value="george" required> George
+ </label></div>
+ <div><label>
+ <input type="radio" name="name" value="ringo" required> Ringo</label></div>
+ """,
)
def test_form_with_iterable_boundfield_id(self):
@@ -858,7 +901,7 @@ Java</label></div>
fields = list(BeatleForm(auto_id=False)["name"])
self.assertEqual(len(fields), 4)
- self.assertEqual(fields[0].id_for_label, None)
+ self.assertIsNone(fields[0].id_for_label)
self.assertEqual(fields[0].choice_label, "John")
self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>')
self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>')
@@ -1093,7 +1136,8 @@ Java</label></div>
self.assertTrue(f.is_valid())
self.assertHTMLEqual(
str(f["when"]),
- '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" required>'
+ '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" '
+ "required>"
'<input type="text" name="when_1" value="01:01" id="id_when_1" required>',
)
self.assertHTMLEqual(
@@ -1107,26 +1151,38 @@ Java</label></div>
f = SongForm(auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
- """<div>
-<div><label><input type="checkbox" name="composers" value="J"> John Lennon</label></div>
-<div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div>
+ <div><label><input type="checkbox" name="composers" value="J">
+ John Lennon</label></div>
+ <div><label><input type="checkbox" name="composers" value="P">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
f = SongForm({"composers": ["J"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
- """<div>
-<div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div>
-<div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div>
+ <div><label><input checked type="checkbox" name="composers" value="J">
+ John Lennon</label></div>
+ <div><label><input type="checkbox" name="composers" value="P">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
f = SongForm({"composers": ["J", "P"]}, auto_id=False)
self.assertHTMLEqual(
str(f["composers"]),
- """<div>
-<div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div>
-<div><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div>
+ <div><label><input checked type="checkbox" name="composers" value="J">
+ John Lennon</label></div>
+ <div><label><input checked type="checkbox" name="composers" value="P">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
def test_checkbox_auto_id(self):
@@ -1143,12 +1199,16 @@ Java</label></div>
f = SongForm(auto_id="%s_id")
self.assertHTMLEqual(
str(f["composers"]),
- """<div id="composers_id">
-<div><label for="composers_id_0">
-<input type="checkbox" name="composers" value="J" id="composers_id_0"> John Lennon</label></div>
-<div><label for="composers_id_1">
-<input type="checkbox" name="composers" value="P" id="composers_id_1"> Paul McCartney</label></div>
-</div>""",
+ """
+ <div id="composers_id">
+ <div><label for="composers_id_0">
+ <input type="checkbox" name="composers" value="J" id="composers_id_0">
+ John Lennon</label></div>
+ <div><label for="composers_id_1">
+ <input type="checkbox" name="composers" value="P" id="composers_id_1">
+ Paul McCartney</label></div>
+ </div>
+ """,
)
def test_multiple_choice_list_data(self):
@@ -1253,12 +1313,18 @@ Java</label></div>
)
self.assertHTMLEqual(
f.as_table(),
- """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
-<ul class="errorlist"><li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul>
-<input type="text" name="special_name" value="Nothing to escape" required></td></tr>
-<tr><th><em>Special</em> Field:</th><td>
-<ul class="errorlist"><li>'<b>Nothing to escape</b>' is a safe string</li></ul>
-<input type="text" name="special_safe_name" value="Nothing to escape" required></td></tr>""",
+ """
+ <tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
+ <ul class="errorlist">
+ <li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul>
+ <input type="text" name="special_name" value="Nothing to escape" required>
+ </td></tr>
+ <tr><th><em>Special</em> Field:</th><td>
+ <ul class="errorlist">
+ <li>'<b>Nothing to escape</b>' is a safe string</li></ul>
+ <input type="text" name="special_safe_name" value="Nothing to escape"
+ required></td></tr>
+ """,
)
f = EscapingForm(
{
@@ -1269,24 +1335,29 @@ Java</label></div>
)
self.assertHTMLEqual(
f.as_table(),
- """<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>
-<ul class="errorlist"><li>Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and
-&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>
-<input type="text" name="special_name"
-value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required></td></tr>
-<tr><th><em>Special</em> Field:</th><td>
-<ul class="errorlist"><li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>
-<input type="text" name="special_safe_name" value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>""",
+ "<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>"
+ '<ul class="errorlist"><li>'
+ "Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and "
+ "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>"
+ '<input type="text" name="special_name" value="Should escape &lt; &amp; '
+ '&gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required>'
+ "</td></tr>"
+ "<tr><th><em>Special</em> Field:</th><td>"
+ '<ul class="errorlist">'
+ "<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>"
+ '<input type="text" name="special_safe_name" '
+ 'value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>',
)
def test_validating_multiple_fields(self):
- # There are a couple of ways to do multiple-field validation. If you want the
- # validation message to be associated with a particular field, implement the
- # clean_XXX() method on the Form, where XXX is the field name. As in
- # Field.clean(), the clean_XXX() method should return the cleaned value. In the
- # clean_XXX() method, you have access to self.cleaned_data, which is a dictionary
- # of all the data that has been cleaned *so far*, in order by the fields,
- # including the current field (e.g., the field XXX if you're in clean_XXX()).
+ # There are a couple of ways to do multiple-field validation. If you
+ # want the validation message to be associated with a particular field,
+ # implement the clean_XXX() method on the Form, where XXX is the field
+ # name. As in Field.clean(), the clean_XXX() method should return the
+ # cleaned value. In the clean_XXX() method, you have access to
+ # self.cleaned_data, which is a dictionary of all the data that has
+ # been cleaned *so far*, in order by the fields, including the current
+ # field (e.g., the field XXX if you're in clean_XXX()).
class UserRegistration(Form):
username = CharField(max_length=10)
password1 = CharField(widget=PasswordInput)
@@ -1396,19 +1467,30 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
self.assertHTMLEqual(
f.as_table(),
- """<tr><td colspan="2">
-<ul class="errorlist nonfield"><li>Please make sure your passwords match.</li></ul></td></tr>
-<tr><th>Username:</th><td><input type="text" name="username" value="adrian" maxlength="10" required></td></tr>
-<tr><th>Password1:</th><td><input type="password" name="password1" required></td></tr>
-<tr><th>Password2:</th><td><input type="password" name="password2" required></td></tr>""",
+ """
+ <tr><td colspan="2">
+ <ul class="errorlist nonfield">
+ <li>Please make sure your passwords match.</li></ul></td></tr>
+ <tr><th>Username:</th><td>
+ <input type="text" name="username" value="adrian" maxlength="10" required>
+ </td></tr>
+ <tr><th>Password1:</th><td>
+ <input type="password" name="password1" required></td></tr>
+ <tr><th>Password2:</th><td>
+ <input type="password" name="password2" required></td></tr>
+ """,
)
self.assertHTMLEqual(
f.as_ul(),
- """<li><ul class="errorlist nonfield">
-<li>Please make sure your passwords match.</li></ul></li>
-<li>Username: <input type="text" name="username" value="adrian" maxlength="10" required></li>
-<li>Password1: <input type="password" name="password1" required></li>
-<li>Password2: <input type="password" name="password2" required></li>""",
+ """
+ <li><ul class="errorlist nonfield">
+ <li>Please make sure your passwords match.</li></ul></li>
+ <li>Username:
+ <input type="text" name="username" value="adrian" maxlength="10" required>
+ </li>
+ <li>Password1: <input type="password" name="password1" required></li>
+ <li>Password2: <input type="password" name="password2" required></li>
+ """,
)
f = UserRegistration(
@@ -1583,9 +1665,14 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" required></td></tr>""",
+ """
+ <tr><th>First name:</th><td>
+ <input type="text" name="first_name" required></td></tr>
+ <tr><th>Last name:</th><td>
+ <input type="text" name="last_name" required></td></tr>
+ <tr><th>Birthday:</th><td>
+ <input type="text" name="birthday" required></td></tr>
+ """,
)
# Instances of a dynamic Form do not persist fields from one Form instance to
@@ -1601,15 +1688,19 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""",
+ """
+ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
+ <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
+ """,
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>""",
+ """
+ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
+ <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
+ """,
)
class MyForm(Form):
@@ -1626,19 +1717,27 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr>
-<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr>
-<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>""",
+ """
+ <tr><th>Default field 1:</th><td>
+ <input type="text" name="default_field_1" required></td></tr>
+ <tr><th>Default field 2:</th><td>
+ <input type="text" name="default_field_2" required></td></tr>
+ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
+ <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
+ """,
)
field_list = [("field3", CharField()), ("field4", CharField())]
my_form = MyForm(field_list=field_list)
self.assertHTMLEqual(
my_form.as_table(),
- """<tr><th>Default field 1:</th><td><input type="text" name="default_field_1" required></td></tr>
-<tr><th>Default field 2:</th><td><input type="text" name="default_field_2" required></td></tr>
-<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>""",
+ """
+ <tr><th>Default field 1:</th><td>
+ <input type="text" name="default_field_1" required></td></tr>
+ <tr><th>Default field 2:</th><td>
+ <input type="text" name="default_field_2" required></td></tr>
+ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
+ <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
+ """,
)
# Similarly, changes to field attributes do not persist from one Form instance
@@ -1766,22 +1865,33 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = Person(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>First name:</th><td><input type="text" name="first_name" required></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" required></td></tr>
-<tr><th>Birthday:</th>
-<td><input type="text" name="birthday" required><input type="hidden" name="hidden_text"></td></tr>""",
+ """
+ <tr><th>First name:</th><td><input type="text" name="first_name" required>
+ </td></tr>
+ <tr><th>Last name:</th><td><input type="text" name="last_name" required>
+ </td></tr>
+ <tr><th>Birthday:</th>
+ <td><input type="text" name="birthday" required>
+ <input type="hidden" name="hidden_text"></td></tr>
+ """,
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>First name: <input type="text" name="first_name" required></li>
-<li>Last name: <input type="text" name="last_name" required></li>
-<li>Birthday: <input type="text" name="birthday" required><input type="hidden" name="hidden_text"></li>""",
+ """
+ <li>First name: <input type="text" name="first_name" required></li>
+ <li>Last name: <input type="text" name="last_name" required></li>
+ <li>Birthday: <input type="text" name="birthday" required>
+ <input type="hidden" name="hidden_text"></li>
+ """,
)
self.assertHTMLEqual(
p.as_p(),
- """<p>First name: <input type="text" name="first_name" required></p>
-<p>Last name: <input type="text" name="last_name" required></p>
-<p>Birthday: <input type="text" name="birthday" required><input type="hidden" name="hidden_text"></p>""",
+ """
+ <p>First name: <input type="text" name="first_name" required></p>
+ <p>Last name: <input type="text" name="last_name" required></p>
+ <p>Birthday: <input type="text" name="birthday" required>
+ <input type="hidden" name="hidden_text"></p>
+ """,
)
# With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label.
@@ -1827,28 +1937,44 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
self.assertHTMLEqual(
p.as_table(),
- """<tr><td colspan="2">
-<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></td></tr>
-<tr><th>First name:</th><td><input type="text" name="first_name" value="John" required></td></tr>
-<tr><th>Last name:</th><td><input type="text" name="last_name" value="Lennon" required></td></tr>
-<tr><th>Birthday:</th><td><input type="text" name="birthday" value="1940-10-9" required>
-<input type="hidden" name="hidden_text"></td></tr>""",
+ """
+ <tr><td colspan="2">
+ <ul class="errorlist nonfield"><li>
+ (Hidden field hidden_text) This field is required.</li></ul></td></tr>
+ <tr><th>First name:</th><td>
+ <input type="text" name="first_name" value="John" required></td></tr>
+ <tr><th>Last name:</th><td>
+ <input type="text" name="last_name" value="Lennon" required></td></tr>
+ <tr><th>Birthday:</th><td>
+ <input type="text" name="birthday" value="1940-10-9" required>
+ <input type="hidden" name="hidden_text"></td></tr>
+ """,
)
self.assertHTMLEqual(
p.as_ul(),
- """<li><ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul></li>
-<li>First name: <input type="text" name="first_name" value="John" required></li>
-<li>Last name: <input type="text" name="last_name" value="Lennon" required></li>
-<li>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
-<input type="hidden" name="hidden_text"></li>""",
+ """
+ <li><ul class="errorlist nonfield"><li>
+ (Hidden field hidden_text) This field is required.</li></ul></li>
+ <li>First name: <input type="text" name="first_name" value="John" required>
+ </li>
+ <li>Last name: <input type="text" name="last_name" value="Lennon" required>
+ </li>
+ <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
+ <input type="hidden" name="hidden_text"></li>
+ """,
)
self.assertHTMLEqual(
p.as_p(),
- """<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field is required.</li></ul>
-<p>First name: <input type="text" name="first_name" value="John" required></p>
-<p>Last name: <input type="text" name="last_name" value="Lennon" required></p>
-<p>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
-<input type="hidden" name="hidden_text"></p>""",
+ """
+ <ul class="errorlist nonfield"><li>
+ (Hidden field hidden_text) This field is required.</li></ul>
+ <p>First name: <input type="text" name="first_name" value="John" required>
+ </p>
+ <p>Last name: <input type="text" name="last_name" value="Lennon" required>
+ </p>
+ <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required>
+ <input type="hidden" name="hidden_text"></p>
+ """,
)
# A corner case: It's possible for a form to have only HiddenInputs.
@@ -1890,20 +2016,11 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = TestForm(auto_id=False)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr>
-<tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr>
-<tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr>
-<tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr>
-<tr><th>Field5:</th><td><input type="text" name="field5" required></td></tr>
-<tr><th>Field6:</th><td><input type="text" name="field6" required></td></tr>
-<tr><th>Field7:</th><td><input type="text" name="field7" required></td></tr>
-<tr><th>Field8:</th><td><input type="text" name="field8" required></td></tr>
-<tr><th>Field9:</th><td><input type="text" name="field9" required></td></tr>
-<tr><th>Field10:</th><td><input type="text" name="field10" required></td></tr>
-<tr><th>Field11:</th><td><input type="text" name="field11" required></td></tr>
-<tr><th>Field12:</th><td><input type="text" name="field12" required></td></tr>
-<tr><th>Field13:</th><td><input type="text" name="field13" required></td></tr>
-<tr><th>Field14:</th><td><input type="text" name="field14" required></td></tr>""",
+ "".join(
+ f"<tr><th>Field{i}:</th><td>"
+ f'<input type="text" name="field{i}" required></td></tr>'
+ for i in range(1, 15)
+ ),
)
def test_explicit_field_order(self):
@@ -1967,15 +2084,20 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" maxlength="10" required></li>
-<li>Realname: <input type="text" name="realname" maxlength="10" required></li>
-<li>Address: <input type="text" name="address" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" maxlength="10" required>
+ </li>
+ <li>Password: <input type="password" name="password" maxlength="10"
+ required></li>
+ <li>Realname: <input type="text" name="realname" maxlength="10" required>
+ </li>
+ <li>Address: <input type="text" name="address" required></li>
+ """,
)
- # If you specify a custom "attrs" that includes the "maxlength" attribute,
- # the Field's max_length attribute will override whatever "maxlength" you specify
- # in "attrs".
+ # If you specify a custom "attrs" that includes the "maxlength"
+ # attribute, the Field's max_length attribute will override whatever
+ # "maxlength" you specify in "attrs".
class UserRegistration(Form):
username = CharField(
max_length=10, widget=TextInput(attrs={"maxlength": 20})
@@ -2001,9 +2123,13 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Your username: <input type="text" name="username" maxlength="10" required></li>
-<li>Password1: <input type="password" name="password1" required></li>
-<li>Contraseña (de nuevo): <input type="password" name="password2" required></li>""",
+ """
+ <li>Your username:
+ <input type="text" name="username" maxlength="10" required></li>
+ <li>Password1: <input type="password" name="password1" required></li>
+ <li>Contraseña (de nuevo):
+ <input type="password" name="password2" required></li>
+ """,
)
# Labels for as_* methods will only end in a colon if they don't end in other
@@ -2025,14 +2151,22 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
self.assertHTMLEqual(
Questions().as_p(),
- """<p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p>
-<p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p>
-<p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p>
-<p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p>
-<p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p>""",
+ """
+ <p><label for="id_q1">The first question:</label>
+ <input type="text" name="q1" id="id_q1" required></p>
+ <p><label for="id_q2">What is your name?</label>
+ <input type="text" name="q2" id="id_q2" required></p>
+ <p><label for="id_q3">The answer to life is:</label>
+ <input type="text" name="q3" id="id_q3" required></p>
+ <p><label for="id_q4">Answer this question!</label>
+ <input type="text" name="q4" id="id_q4" required></p>
+ <p><label for="id_q5">The last question. Period.</label>
+ <input type="text" name="q5" id="id_q5" required></p>
+ """,
)
- # If a label is set to the empty string for a field, that field won't get a label.
+ # If a label is set to the empty string for a field, that field won't
+ # get a label.
class UserRegistration(Form):
username = CharField(max_length=10, label="")
password = CharField(widget=PasswordInput)
@@ -2046,9 +2180,13 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id="id_%s")
self.assertHTMLEqual(
p.as_ul(),
- """<li> <input id="id_username" type="text" name="username" maxlength="10" required></li>
-<li><label for="id_password">Password:</label>
-<input type="password" name="password" id="id_password" required></li>""",
+ """
+ <li>
+ <input id="id_username" type="text" name="username" maxlength="10" required>
+ </li>
+ <li><label for="id_password">Password:</label>
+ <input type="password" name="password" id="id_password" required></li>
+ """,
)
# If label is None, Django will auto-create the label from the field name. This
@@ -2073,11 +2211,12 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
)
def test_label_suffix(self):
- # You can specify the 'label_suffix' argument to a Form class to modify the
- # punctuation symbol used at the end of a label. By default, the colon (:) is
- # used, and is only appended to the label if the label doesn't already end with a
- # punctuation symbol: ., !, ? or :. If you specify a different suffix, it will
- # be appended regardless of the last character of the label.
+ # You can specify the 'label_suffix' argument to a Form class to modify
+ # the punctuation symbol used at the end of a label. By default, the
+ # colon (:) is used, and is only appended to the label if the label
+ # doesn't already end with a punctuation symbol: ., !, ? or :. If you
+ # specify a different suffix, it will be appended regardless of the
+ # last character of the label.
class FavoriteForm(Form):
color = CharField(label="Favorite color?")
animal = CharField(label="Favorite animal")
@@ -2111,7 +2250,8 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
self.assertHTMLEqual(
f.as_ul(),
'<li>Favorite color? <input type="text" name="color" required></li>\n'
- '<li>Favorite animal\u2192 <input type="text" name="animal" required></li>\n'
+ "<li>Favorite animal\u2192 "
+ '<input type="text" name="animal" required></li>\n'
'<li>Secret answer = <input type="text" name="answer" required></li>',
)
@@ -2129,8 +2269,11 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
# Here, we're submitting data, so the initial value will *not* be displayed.
@@ -2153,14 +2296,18 @@ Password: <input type="password" name="password" required></li>""",
p = UserRegistration({"username": "foo"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>
-Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="foo" maxlength="10"
+ required></li>
+ <li><ul class="errorlist"><li>This field is required.</li></ul>
+ Password: <input type="password" name="password" required></li>
+ """,
)
- # An 'initial' value is *not* used as a fallback if data is not provided. In this
- # example, we don't provide a value for 'username', and the form raises a
- # validation error rather than using the initial value for 'username'.
+ # An 'initial' value is *not* used as a fallback if data is not
+ # provided. In this example, we don't provide a value for 'username',
+ # and the form raises a validation error rather than using the initial
+ # value for 'username'.
p = UserRegistration({"password": "secret"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
@@ -2179,14 +2326,20 @@ Password: <input type="password" name="password" required></li>""",
p = UserRegistration(initial={"username": "django"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
p = UserRegistration(initial={"username": "stephane"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="stephane"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
# The 'initial' parameter is meaningless if you pass data.
@@ -2213,20 +2366,24 @@ Password: <input type="password" name="password" required></li>""",
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>
-Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="foo" maxlength="10"
+ required></li>
+ <li><ul class="errorlist"><li>This field is required.</li></ul>
+ Password: <input type="password" name="password" required></li>
+ """,
)
# A dynamic 'initial' value is *not* used as a fallback if data is not provided.
- # In this example, we don't provide a value for 'username', and the form raises a
- # validation error rather than using the initial value for 'username'.
+ # In this example, we don't provide a value for 'username', and the
+ # form raises a validation error rather than using the initial value
+ # for 'username'.
p = UserRegistration({"password": "secret"}, initial={"username": "django"})
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
- # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
- # then the latter will get precedence.
+ # If a Form defines 'initial' *and* 'initial' is passed as a parameter
+ # to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial="django")
password = CharField(widget=PasswordInput)
@@ -2234,8 +2391,11 @@ Password: <input type="password" name="password" required></li>""",
p = UserRegistration(initial={"username": "babik"}, auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="babik"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ """,
)
def test_callable_initial_data(self):
@@ -2268,13 +2428,16 @@ Password: <input type="password" name="password" required></li>""",
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f" selected>foo</option>
-<option value="b" selected>bar</option>
-<option value="w">whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f" selected>foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w">whiz</option>
+ </select></li>
+ """,
)
# The 'initial' parameter is meaningless if you pass data.
@@ -2319,19 +2482,23 @@ Options: <select multiple name="options" required>
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li>
-<li><ul class="errorlist"><li>This field is required.</li></ul>
-Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f" selected>foo</option>
-<option value="b" selected>bar</option>
-<option value="w">whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="foo" maxlength="10"
+ required></li>
+ <li><ul class="errorlist"><li>This field is required.</li></ul>
+ Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f" selected>foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w">whiz</option>
+ </select></li>
+ """,
)
- # A callable 'initial' value is *not* used as a fallback if data is not provided.
- # In this example, we don't provide a value for 'username', and the form raises a
- # validation error rather than using the initial value for 'username'.
+ # A callable 'initial' value is *not* used as a fallback if data is not
+ # provided. In this example, we don't provide a value for 'username',
+ # and the form raises a validation error rather than using the initial
+ # value for 'username'.
p = UserRegistration(
{"password": "secret"},
initial={"username": initial_django, "options": initial_options},
@@ -2339,8 +2506,8 @@ Password: <input type="password" name="password" required></li>
self.assertEqual(p.errors["username"], ["This field is required."])
self.assertFalse(p.is_valid())
- # If a Form defines 'initial' *and* 'initial' is passed as a parameter to Form(),
- # then the latter will get precedence.
+ # If a Form defines 'initial' *and* 'initial' is passed as a parameter
+ # to Form(), then the latter will get precedence.
class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput)
@@ -2352,13 +2519,16 @@ Password: <input type="password" name="password" required></li>
p = UserRegistration(auto_id=False)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="django" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f">foo</option>
-<option value="b" selected>bar</option>
-<option value="w" selected>whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="django"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f">foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w" selected>whiz</option>
+ </select></li>
+ """,
)
p = UserRegistration(
initial={"username": initial_stephane, "options": initial_options},
@@ -2366,13 +2536,16 @@ Password: <input type="password" name="password" required></li>
)
self.assertHTMLEqual(
p.as_ul(),
- """<li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li>
-<li>Password: <input type="password" name="password" required></li>
-<li>Options: <select multiple name="options" required>
-<option value="f" selected>foo</option>
-<option value="b" selected>bar</option>
-<option value="w">whiz</option>
-</select></li>""",
+ """
+ <li>Username: <input type="text" name="username" value="stephane"
+ maxlength="10" required></li>
+ <li>Password: <input type="password" name="password" required></li>
+ <li>Options: <select multiple name="options" required>
+ <option value="f" selected>foo</option>
+ <option value="b" selected>bar</option>
+ <option value="w">whiz</option>
+ </select></li>
+ """,
)
def test_get_initial_for_field(self):
@@ -2605,7 +2778,8 @@ Password: <input type="password" name="password" required></li>
self.assertEqual(form.changed_data, [])
def test_help_text(self):
- # You can specify descriptive text for a field by using the 'help_text' argument)
+ # You can specify descriptive text for a field by using the 'help_text'
+ # argument.
class UserRegistration(Form):
username = CharField(max_length=10, help_text="e.g., user@example.com")
password = CharField(
@@ -2629,10 +2803,13 @@ Password: <input type="password" name="password" required></li>
)
self.assertHTMLEqual(
p.as_table(),
- """<tr><th>Username:</th><td><input type="text" name="username" maxlength="10" required><br>
-<span class="helptext">e.g., user@example.com</span></td></tr>
-<tr><th>Password:</th><td><input type="password" name="password" required><br>
-<span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""",
+ """
+ <tr><th>Username:</th><td>
+ <input type="text" name="username" maxlength="10" required><br>
+ <span class="helptext">e.g., user@example.com</span></td></tr>
+ <tr><th>Password:</th><td><input type="password" name="password" required>
+ <br>
+ <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""",
)
# The help text is displayed whether or not data is provided for the form.
@@ -2752,13 +2929,14 @@ Password: <input type="password" name="password" required>
)
def test_forms_with_prefixes(self):
- # Sometimes it's necessary to have multiple forms display on the same HTML page,
- # or multiple copies of the same form. We can accomplish this with form prefixes.
- # Pass the keyword argument 'prefix' to the Form constructor to use this feature.
- # This value will be prepended to each HTML form field name. One way to think
- # about this is "namespaces for HTML forms". Notice that in the data argument,
- # each field's key has the prefix, in this case 'person1', prepended to the
- # actual field name.
+ # Sometimes it's necessary to have multiple forms display on the same
+ # HTML page, or multiple copies of the same form. We can accomplish
+ # this with form prefixes. Pass the keyword argument 'prefix' to the
+ # Form constructor to use this feature. This value will be prepended to
+ # each HTML form field name. One way to think about this is "namespaces
+ # for HTML forms". Notice that in the data argument, each field's key
+ # has the prefix, in this case 'person1', prepended to the actual field
+ # name.
class Person(Form):
first_name = CharField()
last_name = CharField()
@@ -2772,24 +2950,32 @@ Password: <input type="password" name="password" required>
p = Person(data, prefix="person1")
self.assertHTMLEqual(
p.as_ul(),
- """<li><label for="id_person1-first_name">First name:</label>
-<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required></li>
-<li><label for="id_person1-last_name">Last name:</label>
-<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required></li>
-<li><label for="id_person1-birthday">Birthday:</label>
-<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li>""",
+ """
+ <li><label for="id_person1-first_name">First name:</label>
+ <input type="text" name="person1-first_name" value="John"
+ id="id_person1-first_name" required></li>
+ <li><label for="id_person1-last_name">Last name:</label>
+ <input type="text" name="person1-last_name" value="Lennon"
+ id="id_person1-last_name" required></li>
+ <li><label for="id_person1-birthday">Birthday:</label>
+ <input type="text" name="person1-birthday" value="1940-10-9"
+ id="id_person1-birthday" required></li>
+ """,
)
self.assertHTMLEqual(
str(p["first_name"]),
- '<input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required>',
+ '<input type="text" name="person1-first_name" value="John" '
+ 'id="id_person1-first_name" required>',
)
self.assertHTMLEqual(
str(p["last_name"]),
- '<input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required>',
+ '<input type="text" name="person1-last_name" value="Lennon" '
+ 'id="id_person1-last_name" required>',
)
self.assertHTMLEqual(
str(p["birthday"]),
- '<input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required>',
+ '<input type="text" name="person1-birthday" value="1940-10-9" '
+ 'id="id_person1-birthday" required>',
)
self.assertEqual(p.errors, {})
self.assertTrue(p.is_valid())
@@ -2861,12 +3047,17 @@ Password: <input type="password" name="password" required>
p = Person(prefix="foo")
self.assertHTMLEqual(
p.as_ul(),
- """<li><label for="id_foo-prefix-first_name">First name:</label>
-<input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required></li>
-<li><label for="id_foo-prefix-last_name">Last name:</label>
-<input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required></li>
-<li><label for="id_foo-prefix-birthday">Birthday:</label>
-<input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li>""",
+ """
+ <li><label for="id_foo-prefix-first_name">First name:</label>
+ <input type="text" name="foo-prefix-first_name"
+ id="id_foo-prefix-first_name" required></li>
+ <li><label for="id_foo-prefix-last_name">Last name:</label>
+ <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name"
+ required></li>
+ <li><label for="id_foo-prefix-birthday">Birthday:</label>
+ <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday"
+ required></li>
+ """,
)
data = {
"foo-prefix-first_name": "John",
@@ -2981,15 +3172,16 @@ Password: <input type="password" name="password" required>
)
def test_forms_with_file_fields(self):
- # FileFields are a special case because they take their data from the request.FILES,
- # not request.POST.
+ # FileFields are a special case because they take their data from the
+ # request.FILES, not request.POST.
class FileForm(Form):
file1 = FileField()
f = FileForm(auto_id=False)
self.assertHTMLEqual(
f.as_table(),
- '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>',
+ "<tr><th>File1:</th><td>"
+ '<input type="file" name="file1" required></td></tr>',
)
f = FileForm(data={}, files={}, auto_id=False)
@@ -3028,7 +3220,8 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
f.as_table(),
- '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>',
+ "<tr><th>File1:</th><td>"
+ '<input type="file" name="file1" required></td></tr>',
)
self.assertTrue(f.is_valid())
@@ -3038,7 +3231,8 @@ Password: <input type="password" name="password" required>
f = FileForm(data={}, files={"file1": file1}, auto_id=False)
self.assertHTMLEqual(
f.as_table(),
- '<tr><th>File1:</th><td><input type="file" name="file1" required></td></tr>',
+ "<tr><th>File1:</th><td>"
+ '<input type="file" name="file1" required></td></tr>',
)
# A required file field with initial data should not contain the
@@ -3158,9 +3352,10 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
MyForm().as_table(),
- '<tr><th><label for="id_field1">Field1:</label></th>'
- '<td><input id="id_field1" type="text" name="field1" maxlength="50" required>'
- '<input type="hidden" name="initial-field1" id="initial-id_field1"></td></tr>',
+ '<tr><th><label for="id_field1">Field1:</label></th><td>'
+ '<input id="id_field1" type="text" name="field1" maxlength="50" required>'
+ '<input type="hidden" name="initial-field1" id="initial-id_field1">'
+ "</td></tr>",
)
def test_error_html_required_html_classes(self):
@@ -3176,34 +3371,46 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
p.as_ul(),
- """<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
-<label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li>
-<li class="required"><label class="required" for="id_is_cool">Is cool:</label>
-<select name="is_cool" id="id_is_cool">
-<option value="unknown" selected>Unknown</option>
-<option value="true">Yes</option>
-<option value="false">No</option>
-</select></li>
-<li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li>
-<li class="required error"><ul class="errorlist"><li>This field is required.</li></ul>
-<label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""",
+ """
+ <li class="required error"><ul class="errorlist">
+ <li>This field is required.</li></ul>
+ <label class="required" for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></li>
+ <li class="required">
+ <label class="required" for="id_is_cool">Is cool:</label>
+ <select name="is_cool" id="id_is_cool">
+ <option value="unknown" selected>Unknown</option>
+ <option value="true">Yes</option>
+ <option value="false">No</option>
+ </select></li>
+ <li><label for="id_email">Email:</label>
+ <input type="email" name="email" id="id_email"></li>
+ <li class="required error"><ul class="errorlist">
+ <li>This field is required.</li></ul>
+ <label class="required" for="id_age">Age:</label>
+ <input type="number" name="age" id="id_age" required></li>""",
)
self.assertHTMLEqual(
p.as_p(),
- """<ul class="errorlist"><li>This field is required.</li></ul>
-<p class="required error"><label class="required" for="id_name">Name:</label>
-<input type="text" name="name" id="id_name" required></p>
-<p class="required"><label class="required" for="id_is_cool">Is cool:</label>
-<select name="is_cool" id="id_is_cool">
-<option value="unknown" selected>Unknown</option>
-<option value="true">Yes</option>
-<option value="false">No</option>
-</select></p>
-<p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p>
-<ul class="errorlist"><li>This field is required.</li></ul>
-<p class="required error"><label class="required" for="id_age">Age:</label>
-<input type="number" name="age" id="id_age" required></p>""",
+ """
+ <ul class="errorlist"><li>This field is required.</li></ul>
+ <p class="required error">
+ <label class="required" for="id_name">Name:</label>
+ <input type="text" name="name" id="id_name" required></p>
+ <p class="required">
+ <label class="required" for="id_is_cool">Is cool:</label>
+ <select name="is_cool" id="id_is_cool">
+ <option value="unknown" selected>Unknown</option>
+ <option value="true">Yes</option>
+ <option value="false">No</option>
+ </select></p>
+ <p><label for="id_email">Email:</label>
+ <input type="email" name="email" id="id_email"></p>
+ <ul class="errorlist"><li>This field is required.</li></ul>
+ <p class="required error"><label class="required" for="id_age">Age:</label>
+ <input type="number" name="age" id="id_age" required></p>
+ """,
)
self.assertHTMLEqual(
@@ -3481,10 +3688,14 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
form.as_p(),
"""
- <p>Phone1:<input type="text" name="phone1_0" required><input type="text" name="phone1_1" required></p>
- <p>Phone2:<input type="text" name="phone2_0"><input type="text" name="phone2_1"></p>
- <p>Phone3:<input type="text" name="phone3_0" required><input type="text" name="phone3_1"></p>
- <p>Phone4:<input type="text" name="phone4_0"><input type="text" name="phone4_1"></p>
+ <p>Phone1:<input type="text" name="phone1_0" required>
+ <input type="text" name="phone1_1" required></p>
+ <p>Phone2:<input type="text" name="phone2_0">
+ <input type="text" name="phone2_1"></p>
+ <p>Phone3:<input type="text" name="phone3_0" required>
+ <input type="text" name="phone3_1"></p>
+ <p>Phone4:<input type="text" name="phone4_0">
+ <input type="text" name="phone4_1"></p>
""",
)
@@ -3694,7 +3905,8 @@ Password: <input type="password" name="password" required>
control = [
'<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>',
'<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>',
- '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul></li>',
+ '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>'
+ "</li>",
]
for error in control:
self.assertInHTML(error, errors)
@@ -3798,10 +4010,14 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
p.as_p(),
- """<ul class="errorlist nonfield"><li>(Hidden field last_name) This field is required.</li></ul>
-<p><label for="id_first_name">First name:</label>
-<input id="id_first_name" name="first_name" type="text" value="John" required>
-<input id="id_last_name" name="last_name" type="hidden"></p>""",
+ """
+ <ul class="errorlist nonfield">
+ <li>(Hidden field last_name) This field is required.</li></ul>
+ <p><label for="id_first_name">First name:</label>
+ <input id="id_first_name" name="first_name" type="text" value="John"
+ required>
+ <input id="id_last_name" name="last_name" type="hidden"></p>
+ """,
)
self.assertHTMLEqual(
p.as_table(),
@@ -3847,11 +4063,18 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
p.as_table(),
- """<tr><td colspan="2"><ul class="errorlist nonfield"><li>Generic validation error</li></ul></td></tr>
-<tr><th><label for="id_first_name">First name:</label></th><td>
-<input id="id_first_name" name="first_name" type="text" value="John" required></td></tr>
-<tr><th><label for="id_last_name">Last name:</label></th><td>
-<input id="id_last_name" name="last_name" type="text" value="Lennon" required></td></tr>""",
+ """
+ <tr><td colspan="2"><ul class="errorlist nonfield">
+ <li>Generic validation error</li></ul></td></tr>
+ <tr><th><label for="id_first_name">First name:</label></th><td>
+ <input id="id_first_name" name="first_name" type="text" value="John"
+ required>
+ </td></tr>
+ <tr><th><label for="id_last_name">Last name:</label></th><td>
+ <input id="id_last_name" name="last_name" type="text" value="Lennon"
+ required>
+ </td></tr>
+ """,
)
def test_error_escaping(self):
@@ -3868,7 +4091,8 @@ Password: <input type="password" name="password" required>
form.is_valid()
self.assertHTMLEqual(
form.as_ul(),
- '<li><ul class="errorlist nonfield"><li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>'
+ '<li><ul class="errorlist nonfield">'
+ "<li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>"
'<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>'
'<label for="id_visible">Visible:</label> '
'<input type="text" name="visible" value="b" id="id_visible" required>'
@@ -3883,14 +4107,16 @@ Password: <input type="password" name="password" required>
p = Person()
self.assertEqual(
repr(p),
- "<Person bound=False, valid=Unknown, fields=(first_name;last_name;birthday)>",
+ "<Person bound=False, valid=Unknown, "
+ "fields=(first_name;last_name;birthday)>",
)
p = Person(
{"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}
)
self.assertEqual(
repr(p),
- "<Person bound=True, valid=Unknown, fields=(first_name;last_name;birthday)>",
+ "<Person bound=True, valid=Unknown, "
+ "fields=(first_name;last_name;birthday)>",
)
p.is_valid()
self.assertEqual(
@@ -4003,9 +4229,12 @@ Password: <input type="password" name="password" required>
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
- '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text" required></p>'
- '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>'
- '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
+ '<p><label for="id_f1">F1:</label>'
+ '<input id="id_f1" maxlength="30" name="f1" type="text" required></p>'
+ '<p><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
+ '<p><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></p>"
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
@@ -4016,8 +4245,10 @@ Password: <input type="password" name="password" required>
form.as_ul(),
'<li><label for="id_f1">F1:</label> '
'<input id="id_f1" maxlength="30" name="f1" type="text" required></li>'
- '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>'
- '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10" required>'
+ '<li><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
+ '<li><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></li>"
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
@@ -4027,13 +4258,15 @@ Password: <input type="password" name="password" required>
self.assertHTMLEqual(
form.as_table(),
'<tr><th><label for="id_f1">F1:</label></th>'
- '<td><input id="id_f1" maxlength="30" name="f1" type="text" required></td></tr>'
+ '<td><input id="id_f1" maxlength="30" name="f1" type="text" required>'
+ "</td></tr>"
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
'<tr><th><label for="id_f3">F3:</label></th>'
'<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>'
"</textarea></td></tr>"
- '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">'
+ '<tr><th><label for="id_f4">F4:</label></th><td>'
+ '<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
@@ -4050,10 +4283,12 @@ Password: <input type="password" name="password" required>
form = MyForm()
self.assertHTMLEqual(
form.as_p(),
- '<p><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></p>'
- '<p><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></p>'
- '<p><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
- "</textarea></p>"
+ '<p><label for="id_f1">F1:</label>'
+ '<input id="id_f1" maxlength="30" name="f1" type="text"></p>'
+ '<p><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></p>'
+ '<p><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>'
'<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
@@ -4061,10 +4296,12 @@ Password: <input type="password" name="password" required>
)
self.assertHTMLEqual(
form.as_ul(),
- '<li><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" name="f1" type="text"></li>'
- '<li><label for="id_f2">F2:</label> <input id="id_f2" maxlength="30" name="f2" type="text"></li>'
- '<li><label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" rows="10">'
- "</textarea></li>"
+ '<li><label for="id_f1">F1:</label>'
+ '<input id="id_f1" maxlength="30" name="f1" type="text"></li>'
+ '<li><label for="id_f2">F2:</label>'
+ '<input id="id_f2" maxlength="30" name="f2" type="text"></li>'
+ '<li><label for="id_f3">F3:</label>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>'
'<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
@@ -4076,9 +4313,11 @@ Password: <input type="password" name="password" required>
'<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>'
'<tr><th><label for="id_f2">F2:</label></th>'
'<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>'
- '<tr><th><label for="id_f3">F3:</label></th><td><textarea cols="40" id="id_f3" name="f3" rows="10">'
+ '<tr><th><label for="id_f3">F3:</label></th><td>'
+ '<textarea cols="40" id="id_f3" name="f3" rows="10">'
"</textarea></td></tr>"
- '<tr><th><label for="id_f4">F4:</label></th><td><select id="id_f4" name="f4">'
+ '<tr><th><label for="id_f4">F4:</label></th><td>'
+ '<select id="id_f4" name="f4">'
'<option value="P">Python</option>'
'<option value="J">Java</option>'
"</select></td></tr>",
diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py
index 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),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td><input type="text" name="form-0-name" value="Fernet and Coke"
+ id="id_form-0-name"></td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>
+ """,
)
def test_max_num_zero(self):
@@ -988,10 +992,14 @@ class FormsFormsetTestCase(SimpleTestCase):
formset = LimitedFavoriteDrinkFormSet(initial=initial)
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td><input id="id_form-0-name" name="form-0-name" type="text"
+ value="Fernet and Coke"></td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td><input id="id_form-1-name" name="form-1-name" type="text"
+ value="Bloody Mary"></td></tr>
+ """,
)
def test_more_initial_than_max_num(self):
@@ -1010,12 +1018,20 @@ class FormsFormsetTestCase(SimpleTestCase):
formset = LimitedFavoriteDrinkFormSet(initial=initial)
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></td></tr>
-<tr><th><label for="id_form-2-name">Name:</label></th>
-<td><input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td>
+ <input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic">
+ </td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td>
+ <input id="id_form-1-name" name="form-1-name" type="text"
+ value="Bloody Mary"></td></tr>
+ <tr><th><label for="id_form-2-name">Name:</label></th>
+ <td>
+ <input id="id_form-2-name" name="form-2-name" type="text"
+ value="Jack and Coke"></td></tr>
+ """,
)
def test_default_absolute_max(self):
@@ -1093,10 +1109,13 @@ class FormsFormsetTestCase(SimpleTestCase):
formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Gin Tonic"}])
self.assertHTMLEqual(
"\n".join(str(form) for form in formset.forms),
- """<tr><th><label for="id_form-0-name">Name:</label></th>
-<td><input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name"></td></tr>
-<tr><th><label for="id_form-1-name">Name:</label></th>
-<td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>""",
+ """
+ <tr><th><label for="id_form-0-name">Name:</label></th>
+ <td>
+ <input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name">
+ </td></tr>
+ <tr><th><label for="id_form-1-name">Name:</label></th>
+ <td><input type="text" name="form-1-name" id="id_form-1-name"></td></tr>""",
)
def test_management_form_field_names(self):
@@ -1539,7 +1558,8 @@ class FormsetAsTagTests(SimpleTestCase):
self.formset.as_p(),
self.management_form_html
+ (
- '<p>Choice: <input type="text" name="choices-0-choice" value="Calexico"></p>'
+ "<p>Choice: "
+ '<input type="text" name="choices-0-choice" value="Calexico"></p>'
'<p>Votes: <input type="number" name="choices-0-votes" value="100"></p>'
),
)
@@ -1549,8 +1569,10 @@ class FormsetAsTagTests(SimpleTestCase):
self.formset.as_ul(),
self.management_form_html
+ (
- '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li>'
- '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>'
+ "<li>Choice: "
+ '<input type="text" name="choices-0-choice" value="Calexico"></li>'
+ "<li>Votes: "
+ '<input type="number" name="choices-0-votes" value="100"></li>'
),
)
@@ -1620,8 +1642,10 @@ class TestIsBoundBehavior(SimpleTestCase):
"<li>(Hidden field TOTAL_FORMS) Enter a whole number.</li>"
"<li>(Hidden field INITIAL_FORMS) Enter a whole number.</li>"
"</ul>"
- '<input type="hidden" name="form-TOTAL_FORMS" value="two" id="id_form-TOTAL_FORMS">'
- '<input type="hidden" name="form-INITIAL_FORMS" value="one" id="id_form-INITIAL_FORMS">'
+ '<input type="hidden" name="form-TOTAL_FORMS" value="two" '
+ 'id="id_form-TOTAL_FORMS">'
+ '<input type="hidden" name="form-INITIAL_FORMS" value="one" '
+ 'id="id_form-INITIAL_FORMS">'
'<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">'
'<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">'
"</td></tr>\n",
diff --git a/tests/forms_tests/tests/test_i18n.py b/tests/forms_tests/tests/test_i18n.py
index 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(),
'<p><label for="id_username">username:</label>'
- '<input id="id_username" type="text" name="username" maxlength="10" required></p>',
+ '<input id="id_username" type="text" name="username" maxlength="10" '
+ "required></p>",
)
- # Translations are done at rendering time, so multi-lingual apps can define forms)
+ # Translations are done at rendering time, so multi-lingual apps can
+ # define forms.
with translation.override("de"):
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_username">Benutzername:</label>'
- '<input id="id_username" type="text" name="username" maxlength="10" required></p>',
+ '<input id="id_username" type="text" name="username" maxlength="10" '
+ "required></p>",
)
with translation.override("pl"):
self.assertHTMLEqual(
f.as_p(),
'<p><label for="id_username">nazwa u\u017cytkownika:</label>'
- '<input id="id_username" type="text" name="username" maxlength="10" required></p>',
+ '<input id="id_username" type="text" name="username" maxlength="10" '
+ "required></p>",
)
def test_non_ascii_label(self):
@@ -79,13 +83,13 @@ class FormsI18nTests(SimpleTestCase):
"<p><label>\xc5\xf8\xdf:</label>"
'<div id="id_somechoice">\n'
'<div><label for="id_somechoice_0">'
- '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required> '
- "En tied\xe4</label></div>\n"
+ '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" '
+ "required> En tied\xe4</label></div>\n"
'<div><label for="id_somechoice_1">'
- '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required> '
- 'Mies</label></div>\n<div><label for="id_somechoice_2">'
- '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required> '
- "Nainen</label></div>\n</div></p>",
+ '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" '
+ 'required> Mies</label></div>\n<div><label for="id_somechoice_2">'
+ '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" '
+ "required> Nainen</label></div>\n</div></p>",
)
# Translated error messages
@@ -98,13 +102,14 @@ class FormsI18nTests(SimpleTestCase):
"\u043d\u043e\u0435 \u043f\u043e\u043b\u0435.</li></ul>\n"
"<p><label>\xc5\xf8\xdf:</label>"
' <div id="id_somechoice">\n<div><label for="id_somechoice_0">'
- '<input type="radio" id="id_somechoice_0" value="\xc5" name="somechoice" required> '
- "En tied\xe4</label></div>\n"
+ '<input type="radio" id="id_somechoice_0" value="\xc5" '
+ 'name="somechoice" required> En tied\xe4</label></div>\n'
'<div><label for="id_somechoice_1">'
- '<input type="radio" id="id_somechoice_1" value="\xf8" name="somechoice" required> '
- 'Mies</label></div>\n<div><label for="id_somechoice_2">'
- '<input type="radio" id="id_somechoice_2" value="\xdf" name="somechoice" required> '
- "Nainen</label></div>\n</div></p>",
+ '<input type="radio" id="id_somechoice_1" value="\xf8" '
+ 'name="somechoice" required> Mies</label></div>\n<div>'
+ '<label for="id_somechoice_2">'
+ '<input type="radio" id="id_somechoice_2" value="\xdf" '
+ 'name="somechoice" required> Nainen</label></div>\n</div></p>',
)
def test_select_translated_text(self):
diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py
index 3ac28b1b30..cd3817d421 100644
--- a/tests/forms_tests/tests/test_input_formats.py
+++ b/tests/forms_tests/tests/test_input_formats.py
@@ -92,7 +92,10 @@ class LocalizedTimeTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
def test_localized_timeField_with_inputformat(self):
- "Localized TimeFields with manually specified input formats can accept those formats"
+ """
+ Localized TimeFields with manually specified input formats can accept
+ those formats.
+ """
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -192,7 +195,10 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:00 PM")
def test_localized_timeField_with_inputformat(self):
- "Localized TimeFields with manually specified input formats can accept those formats"
+ """
+ Localized TimeFields with manually specified input formats can accept
+ those formats.
+ """
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -288,7 +294,10 @@ class SimpleTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "13:30:00")
def test_localized_timeField_with_inputformat(self):
- "Localized TimeFields with manually specified input formats can accept those formats"
+ """
+ Localized TimeFields with manually specified input formats can accept
+ those formats.
+ """
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True)
# Parse a time in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -395,7 +404,10 @@ class LocalizedDateTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
def test_localized_dateField_with_inputformat(self):
- "Localized DateFields with manually specified input formats can accept those formats"
+ """
+ Localized DateFields with manually specified input formats can accept
+ those formats.
+ """
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -497,7 +509,10 @@ class CustomDateInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010")
def test_localized_dateField_with_inputformat(self):
- "Localized DateFields with manually specified input formats can accept those formats"
+ """
+ Localized DateFields with manually specified input formats can accept
+ those formats.
+ """
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -593,7 +608,10 @@ class SimpleDateFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21")
def test_localized_dateField_with_inputformat(self):
- "Localized DateFields with manually specified input formats can accept those formats"
+ """
+ Localized DateFields with manually specified input formats can accept
+ those formats.
+ """
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -702,7 +720,10 @@ class LocalizedDateTimeTests(SimpleTestCase):
self.assertEqual(text, "21.12.2010 13:30:00")
def test_localized_dateTimeField_with_inputformat(self):
- "Localized DateTimeFields with manually specified input formats can accept those formats"
+ """
+ Localized DateTimeFields with manually specified input formats can
+ accept those formats.
+ """
f = forms.DateTimeField(
input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True
)
@@ -810,7 +831,10 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
self.assertEqual(text, "01:30:00 PM 21/12/2010")
def test_localized_dateTimeField_with_inputformat(self):
- "Localized DateTimeFields with manually specified input formats can accept those formats"
+ """
+ Localized DateTimeFields with manually specified input formats can
+ accept those formats.
+ """
f = forms.DateTimeField(
input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True
)
@@ -862,7 +886,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:05")
def test_localized_dateTimeField(self):
- "Localized DateTimeFields in a non-localized environment act as unlocalized widgets"
+ """
+ Localized DateTimeFields in a non-localized environment act as
+ unlocalized widgets.
+ """
f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error
with self.assertRaises(ValidationError):
@@ -910,7 +937,10 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
self.assertEqual(text, "2010-12-21 13:30:00")
def test_localized_dateTimeField_with_inputformat(self):
- "Localized DateTimeFields with manually specified input formats can accept those formats"
+ """
+ Localized DateTimeFields with manually specified input formats can
+ accept those formats.
+ """
f = forms.DateTimeField(
input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True
)
diff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py
index 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),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
self.assertEqual(
repr(m),
"Media(css={'all': ['path/to/css1', '/path/to/css2']}, "
- "js=['/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'])",
+ "js=['/path/to/js1', 'http://media.other.com/path/to/js2', "
+ "'https://secure.other.com/path/to/js3'])",
)
class Foo:
@@ -44,11 +46,12 @@ class FormsMediaTestCase(SimpleTestCase):
m3 = Media(Foo)
self.assertEqual(
str(m3),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# A widget can exist without a media definition
@@ -78,18 +81,20 @@ class FormsMediaTestCase(SimpleTestCase):
w1 = MyWidget1()
self.assertEqual(
str(w1.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Media objects can be interrogated by media type
self.assertEqual(
str(w1.media["css"]),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">',
)
self.assertEqual(
@@ -126,23 +131,25 @@ class FormsMediaTestCase(SimpleTestCase):
w3 = MyWidget3()
self.assertEqual(
str(w1.media + w2.media + w3.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<link href="/path/to/css3" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# media addition hasn't affected the original objects
self.assertEqual(
str(w1.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Regression check for #12879: specifying the same CSS or JS file
@@ -234,13 +241,14 @@ class FormsMediaTestCase(SimpleTestCase):
w6 = MyWidget6()
self.assertEqual(
str(w6.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/other/path" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="/other/js"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/other/path" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/other/js"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
def test_media_inheritance(self):
@@ -248,7 +256,8 @@ class FormsMediaTestCase(SimpleTestCase):
# Inheritance of media
###############################################################
- # If a widget extends another but provides no media definition, it inherits the parent widget's media
+ # If a widget extends another but provides no media definition, it
+ # inherits the parent widget's media.
class MyWidget1(TextInput):
class Media:
css = {"all": ("path/to/css1", "/path/to/css2")}
@@ -264,14 +273,16 @@ class FormsMediaTestCase(SimpleTestCase):
w7 = MyWidget7()
self.assertEqual(
str(w7.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
- # If a widget extends another but defines media, it extends the parent widget's media by default
+ # If a widget extends another but defines media, it extends the parent
+ # widget's media by default.
class MyWidget8(MyWidget1):
class Media:
css = {"all": ("/path/to/css3", "path/to/css1")}
@@ -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),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<link href="/path/to/css3" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
def test_form_media(self):
@@ -494,13 +508,14 @@ class FormsMediaTestCase(SimpleTestCase):
f1 = MyForm()
self.assertEqual(
str(f1.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<link href="/path/to/css3" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Form media can be combined to produce a single media definition.
@@ -510,13 +525,14 @@ class FormsMediaTestCase(SimpleTestCase):
f2 = AnotherForm()
self.assertEqual(
str(f1.media + f2.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<link href="/path/to/css3" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Forms can also define media, following the same rules as widgets.
@@ -531,15 +547,16 @@ class FormsMediaTestCase(SimpleTestCase):
f3 = FormWithMedia()
self.assertEqual(
str(f3.media),
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/some/form/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<link href="/path/to/css3" media="all" rel="stylesheet">
-<script src="/path/to/js1"></script>
-<script src="/some/form/javascript"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>""",
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/some/form/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" media="all" rel="stylesheet">\n'
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/some/form/javascript"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>',
)
# Media works in templates
@@ -547,15 +564,16 @@ class FormsMediaTestCase(SimpleTestCase):
Template("{{ form.media.js }}{{ form.media.css }}").render(
Context({"form": f3})
),
- """<script src="/path/to/js1"></script>
-<script src="/some/form/javascript"></script>
-<script src="http://media.other.com/path/to/js2"></script>
-<script src="/path/to/js4"></script>
-<script src="https://secure.other.com/path/to/js3"></script>"""
- """<link href="http://media.example.com/static/path/to/css1" media="all" rel="stylesheet">
-<link href="/some/form/css" media="all" rel="stylesheet">
-<link href="/path/to/css2" media="all" rel="stylesheet">
-<link href="/path/to/css3" media="all" rel="stylesheet">""",
+ '<script src="/path/to/js1"></script>\n'
+ '<script src="/some/form/javascript"></script>\n'
+ '<script src="http://media.other.com/path/to/js2"></script>\n'
+ '<script src="/path/to/js4"></script>\n'
+ '<script src="https://secure.other.com/path/to/js3"></script>'
+ '<link href="http://media.example.com/static/path/to/css1" media="all" '
+ 'rel="stylesheet">\n'
+ '<link href="/some/form/css" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css2" media="all" rel="stylesheet">\n'
+ '<link href="/path/to/css3" media="all" rel="stylesheet">',
)
def test_html_safe(self):
diff --git a/tests/forms_tests/tests/test_utils.py b/tests/forms_tests/tests/test_utils.py
index c4a2e5c651..a921a924b6 100644
--- a/tests/forms_tests/tests/test_utils.py
+++ b/tests/forms_tests/tests/test_utils.py
@@ -134,7 +134,8 @@ class FormsUtilsTestCase(SimpleTestCase):
self.assertHTMLEqual(
str(ErrorList([example])),
'<ul class="errorlist"><li>Example of link: '
- "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>",
+ "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;"
+ "</li></ul>",
)
self.assertHTMLEqual(
str(ErrorList([mark_safe(example)])),
@@ -144,7 +145,8 @@ class FormsUtilsTestCase(SimpleTestCase):
self.assertHTMLEqual(
str(ErrorDict({"name": example})),
'<ul class="errorlist"><li>nameExample of link: '
- "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;</li></ul>",
+ "&lt;a href=&quot;http://www.example.com/&quot;&gt;example&lt;/a&gt;"
+ "</li></ul>",
)
self.assertHTMLEqual(
str(ErrorDict({"name": mark_safe(example)})),
diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py
index 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(),
- """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice" value="1" id="initial-id_choice"></p>
-<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int">
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int"></p>
-<p><label for="id_multi_choice">Multi choice:</label>
-<select multiple name="multi_choice" id="id_multi_choice" required>
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0"></p>
-<p><label for="id_multi_choice_int">Multi choice int:</label>
-<select multiple name="multi_choice_int" id="id_multi_choice_int" required>
-<option value="1" selected>ChoiceOption 1</option>
-<option value="2">ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0"></p>""",
+ """
+ <p><label for="id_choice">Choice:</label>
+ <select name="choice" id="id_choice">
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice" value="1" id="initial-id_choice">
+ </p>
+ <p><label for="id_choice_int">Choice int:</label>
+ <select name="choice_int" id="id_choice_int">
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice_int" value="1"
+ id="initial-id_choice_int">
+ </p>
+ <p><label for="id_multi_choice">Multi choice:</label>
+ <select multiple name="multi_choice" id="id_multi_choice" required>
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice" value="1"
+ id="initial-id_multi_choice_0">
+ </p>
+ <p><label for="id_multi_choice_int">Multi choice int:</label>
+ <select multiple name="multi_choice_int" id="id_multi_choice_int" required>
+ <option value="1" selected>ChoiceOption 1</option>
+ <option value="2">ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice_int" value="1"
+ id="initial-id_multi_choice_int_0">
+ </p>
+ """,
)
def test_initial_instance_value(self):
@@ -136,30 +160,47 @@ class ModelFormCallableModelDefault(TestCase):
),
}
).as_p(),
- """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice" value="2" id="initial-id_choice"></p>
-<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int">
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3">ChoiceOption 3</option>
-</select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int"></p>
-<p><label for="id_multi_choice">Multi choice:</label>
-<select multiple name="multi_choice" id="id_multi_choice" required>
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3" selected>ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0">
-<input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1"></p>
-<p><label for="id_multi_choice_int">Multi choice int:</label>
-<select multiple name="multi_choice_int" id="id_multi_choice_int" required>
-<option value="1">ChoiceOption 1</option>
-<option value="2" selected>ChoiceOption 2</option>
-<option value="3" selected>ChoiceOption 3</option>
-</select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0">
-<input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1"></p>""",
+ """
+ <p><label for="id_choice">Choice:</label>
+ <select name="choice" id="id_choice">
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice" value="2" id="initial-id_choice">
+ </p>
+ <p><label for="id_choice_int">Choice int:</label>
+ <select name="choice_int" id="id_choice_int">
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3">ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-choice_int" value="2"
+ id="initial-id_choice_int">
+ </p>
+ <p><label for="id_multi_choice">Multi choice:</label>
+ <select multiple name="multi_choice" id="id_multi_choice" required>
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3" selected>ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice" value="2"
+ id="initial-id_multi_choice_0">
+ <input type="hidden" name="initial-multi_choice" value="3"
+ id="initial-id_multi_choice_1">
+ </p>
+ <p><label for="id_multi_choice_int">Multi choice int:</label>
+ <select multiple name="multi_choice_int" id="id_multi_choice_int" required>
+ <option value="1">ChoiceOption 1</option>
+ <option value="2" selected>ChoiceOption 2</option>
+ <option value="3" selected>ChoiceOption 3</option>
+ </select>
+ <input type="hidden" name="initial-multi_choice_int" value="2"
+ id="initial-id_multi_choice_int_0">
+ <input type="hidden" name="initial-multi_choice_int" value="3"
+ id="initial-id_multi_choice_int_1">
+ </p>
+ """,
)
@@ -194,9 +235,8 @@ class FormsModelTestCase(TestCase):
self.assertFalse(f.is_valid())
def test_formfield_initial(self):
- # Formfield initial values ########
- # If the model has default values for some fields, they are used as the formfield
- # initial values.
+ # If the model has default values for some fields, they are used as the
+ # formfield initial values.
class DefaultsForm(ModelForm):
class Meta:
model = Defaults
@@ -323,25 +363,32 @@ class EmptyLabelTestCase(TestCase):
f = EmptyCharLabelChoiceForm()
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required></p>
-<p><label for="id_choice">Choice:</label> <select id="id_choice" name="choice">
-<option value="" selected>No Preference</option>
-<option value="f">Foo</option>
-<option value="b">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text" required></p>
+ <p><label for="id_choice">Choice:</label>
+ <select id="id_choice" name="choice">
+ <option value="" selected>No Preference</option>
+ <option value="f">Foo</option>
+ <option value="b">Bar</option>
+ </select></p>
+ """,
)
def test_empty_field_char_none(self):
f = EmptyCharLabelNoneChoiceForm()
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required></p>
-<p><label for="id_choice_string_w_none">Choice string w none:</label>
-<select id="id_choice_string_w_none" name="choice_string_w_none">
-<option value="" selected>No Preference</option>
-<option value="f">Foo</option>
-<option value="b">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text" required></p>
+ <p><label for="id_choice_string_w_none">Choice string w none:</label>
+ <select id="id_choice_string_w_none" name="choice_string_w_none">
+ <option value="" selected>No Preference</option>
+ <option value="f">Foo</option>
+ <option value="b">Bar</option>
+ </select></p>
+ """,
)
def test_save_empty_label_forms(self):
@@ -367,13 +414,16 @@ class EmptyLabelTestCase(TestCase):
f = EmptyIntegerLabelChoiceForm()
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label> <input id="id_name" maxlength="10" name="name" type="text" required></p>
-<p><label for="id_choice_integer">Choice integer:</label>
-<select id="id_choice_integer" name="choice_integer">
-<option value="" selected>No Preference</option>
-<option value="1">Foo</option>
-<option value="2">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text" required></p>
+ <p><label for="id_choice_integer">Choice integer:</label>
+ <select id="id_choice_integer" name="choice_integer">
+ <option value="" selected>No Preference</option>
+ <option value="1">Foo</option>
+ <option value="2">Bar</option>
+ </select></p>
+ """,
)
def test_get_display_value_on_none(self):
@@ -386,28 +436,36 @@ class EmptyLabelTestCase(TestCase):
f = EmptyIntegerLabelChoiceForm(instance=none_model)
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label>
-<input id="id_name" maxlength="10" name="name" type="text" value="none-test" required></p>
-<p><label for="id_choice_integer">Choice integer:</label>
-<select id="id_choice_integer" name="choice_integer">
-<option value="" selected>No Preference</option>
-<option value="1">Foo</option>
-<option value="2">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text"
+ value="none-test" required>
+ </p>
+ <p><label for="id_choice_integer">Choice integer:</label>
+ <select id="id_choice_integer" name="choice_integer">
+ <option value="" selected>No Preference</option>
+ <option value="1">Foo</option>
+ <option value="2">Bar</option>
+ </select></p>
+ """,
)
foo_model = ChoiceModel(name="foo-test", choice_integer=1)
f = EmptyIntegerLabelChoiceForm(instance=foo_model)
self.assertHTMLEqual(
f.as_p(),
- """<p><label for="id_name">Name:</label>
-<input id="id_name" maxlength="10" name="name" type="text" value="foo-test" required></p>
-<p><label for="id_choice_integer">Choice integer:</label>
-<select id="id_choice_integer" name="choice_integer">
-<option value="">No Preference</option>
-<option value="1" selected>Foo</option>
-<option value="2">Bar</option>
-</select></p>""",
+ """
+ <p><label for="id_name">Name:</label>
+ <input id="id_name" maxlength="10" name="name" type="text"
+ value="foo-test" required>
+ </p>
+ <p><label for="id_choice_integer">Choice integer:</label>
+ <select id="id_choice_integer" name="choice_integer">
+ <option value="">No Preference</option>
+ <option value="1" selected>Foo</option>
+ <option value="2">Bar</option>
+ </select></p>
+ """,
)
diff --git a/tests/forms_tests/widget_tests/test_checkboxinput.py b/tests/forms_tests/widget_tests/test_checkboxinput.py
index 0f65e876df..c30aadbbb1 100644
--- a/tests/forms_tests/widget_tests/test_checkboxinput.py
+++ b/tests/forms_tests/widget_tests/test_checkboxinput.py
@@ -86,7 +86,8 @@ class CheckboxInputTest(WidgetTest):
"greeting",
"hello & goodbye",
html=(
- '<input checked type="checkbox" name="greeting" value="hello &amp; goodbye">'
+ '<input checked type="checkbox" name="greeting" '
+ 'value="hello &amp; goodbye">'
),
)
diff --git a/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py b/tests/forms_tests/widget_tests/test_checkboxselectmultiple.py
index 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="""
<div>
- <div><label><input checked type="checkbox" name="beatles" value="J"> John</label></div>
- <div><label><input type="checkbox" name="beatles" value="P"> Paul</label></div>
- <div><label><input type="checkbox" name="beatles" value="G"> George</label></div>
- <div><label><input type="checkbox" name="beatles" value="R"> Ringo</label></div>
+ <div><label><input checked type="checkbox" name="beatles" value="J"> John
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="P"> Paul
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="G"> George
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="R"> Ringo
+ </label></div>
</div>
""",
)
@@ -32,10 +36,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
["J", "P"],
html="""
<div>
- <div><label><input checked type="checkbox" name="beatles" value="J"> John</label></div>
- <div><label><input checked type="checkbox" name="beatles" value="P"> Paul</label></div>
- <div><label><input type="checkbox" name="beatles" value="G"> George</label></div>
- <div><label><input type="checkbox" name="beatles" value="R"> Ringo</label></div>
+ <div><label><input checked type="checkbox" name="beatles" value="J"> John
+ </label></div>
+ <div><label><input checked type="checkbox" name="beatles" value="P"> Paul
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="G"> George
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="R"> Ringo
+ </label></div>
</div>
""",
)
@@ -51,11 +59,16 @@ class CheckboxSelectMultipleTest(WidgetTest):
None,
html="""
<div>
- <div><label><input type="checkbox" name="beatles" value=""> Unknown</label></div>
- <div><label><input type="checkbox" name="beatles" value="J"> John</label></div>
- <div><label><input type="checkbox" name="beatles" value="P"> Paul</label></div>
- <div><label><input type="checkbox" name="beatles" value="G"> George</label></div>
- <div><label><input type="checkbox" name="beatles" value="R"> Ringo</label></div>
+ <div><label><input type="checkbox" name="beatles" value=""> Unknown
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="J"> John
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="P"> Paul
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="G"> George
+ </label></div>
+ <div><label><input type="checkbox" name="beatles" value="R"> Ringo
+ </label></div>
</div>
""",
)
@@ -69,19 +82,24 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div id="media">
<div> <label for="media_0">
- <input type="checkbox" name="nestchoice" value="unknown" id="media_0"> Unknown</label></div>
+ <input type="checkbox" name="nestchoice" value="unknown" id="media_0"> Unknown
+ </label></div>
<div>
<label>Audio</label>
<div> <label for="media_1_0">
- <input checked type="checkbox" name="nestchoice" value="vinyl" id="media_1_0"> Vinyl</label></div>
+ <input checked type="checkbox" name="nestchoice" value="vinyl" id="media_1_0">
+ Vinyl</label></div>
<div> <label for="media_1_1">
- <input type="checkbox" name="nestchoice" value="cd" id="media_1_1"> CD</label></div>
+ <input type="checkbox" name="nestchoice" value="cd" id="media_1_1"> CD
+ </label></div>
</div><div>
<label>Video</label>
<div> <label for="media_2_0">
- <input type="checkbox" name="nestchoice" value="vhs" id="media_2_0"> VHS</label></div>
+ <input type="checkbox" name="nestchoice" value="vhs" id="media_2_0"> VHS
+ </label></div>
<div> <label for="media_2_1">
- <input type="checkbox" name="nestchoice" value="dvd" id="media_2_1" checked> DVD</label></div>
+ <input type="checkbox" name="nestchoice" value="dvd" id="media_2_1" checked> DVD
+ </label></div>
</div>
</div>
"""
@@ -101,15 +119,21 @@ class CheckboxSelectMultipleTest(WidgetTest):
)
html = """
<div>
- <div> <label><input type="checkbox" name="nestchoice" value="unknown"> Unknown</label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="unknown"> Unknown</label></div>
<div>
<label>Audio</label>
- <div> <label><input checked type="checkbox" name="nestchoice" value="vinyl"> Vinyl</label></div>
- <div> <label><input type="checkbox" name="nestchoice" value="cd"> CD</label></div>
+ <div> <label>
+ <input checked type="checkbox" name="nestchoice" value="vinyl"> Vinyl
+ </label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="cd"> CD</label></div>
</div><div>
<label>Video</label>
- <div> <label><input type="checkbox" name="nestchoice" value="vhs"> VHS</label></div>
- <div> <label><input type="checkbox" name="nestchoice" value="dvd"checked> DVD</label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="vhs"> VHS</label></div>
+ <div> <label>
+ <input type="checkbox" name="nestchoice" value="dvd"checked> DVD</label></div>
</div>
</div>
"""
@@ -128,11 +152,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div id="abc">
<div>
- <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
+ <label for="abc_0">
+ <input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
</div>
- <div><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
+ <div><label for="abc_1">
+ <input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
<div>
- <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
+ <label for="abc_2">
+ <input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
</div>
</div>
"""
@@ -154,11 +181,14 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div id="abc">
<div>
- <label for="abc_0"><input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
+ <label for="abc_0">
+ <input checked type="checkbox" name="letters" value="a" id="abc_0"> A</label>
</div>
- <div><label for="abc_1"><input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
+ <div><label for="abc_1">
+ <input type="checkbox" name="letters" value="b" id="abc_1"> B</label></div>
<div>
- <label for="abc_2"><input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
+ <label for="abc_2">
+ <input checked type="checkbox" name="letters" value="c" id="abc_2"> C</label>
</div>
</div>
"""
@@ -174,8 +204,10 @@ class CheckboxSelectMultipleTest(WidgetTest):
html = """
<div>
<div><label><input type="checkbox" name="numbers" value="1"> One</label></div>
- <div><label><input type="checkbox" name="numbers" value="1000"> One thousand</label></div>
- <div><label><input type="checkbox" name="numbers" value="1000000"> One million</label></div>
+ <div><label>
+ <input type="checkbox" name="numbers" value="1000"> One thousand</label></div>
+ <div><label>
+ <input type="checkbox" name="numbers" value="1000000"> One million</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "numbers", None, html=html)
@@ -186,8 +218,10 @@ class CheckboxSelectMultipleTest(WidgetTest):
]
html = """
<div>
- <div><label><input type="checkbox" name="times" value="00:00:00"> midnight</label></div>
- <div><label><input type="checkbox" name="times" value="12:00:00"> noon</label></div>
+ <div><label>
+ <input type="checkbox" name="times" value="00:00:00"> midnight</label></div>
+ <div><label>
+ <input type="checkbox" name="times" value="12:00:00"> noon</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "times", None, html=html)
diff --git a/tests/forms_tests/widget_tests/test_clearablefileinput.py b/tests/forms_tests/widget_tests/test_clearablefileinput.py
index 03fe34306b..630ff79486 100644
--- a/tests/forms_tests/widget_tests/test_clearablefileinput.py
+++ b/tests/forms_tests/widget_tests/test_clearablefileinput.py
@@ -56,12 +56,14 @@ class ClearableFileInputTest(WidgetTest):
StrangeFieldFile(),
html=(
"""
- Currently: <a href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en">
- something&lt;div onclick=&quot;alert(&#x27;oops&#x27;)&quot;&gt;.jpg</a>
- <input type="checkbox" name="my&lt;div&gt;file-clear" id="my&lt;div&gt;file-clear_id">
- <label for="my&lt;div&gt;file-clear_id">Clear</label><br>
- Change: <input type="file" name="my&lt;div&gt;file">
- """
+ Currently:
+ <a href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en">
+ something&lt;div onclick=&quot;alert(&#x27;oops&#x27;)&quot;&gt;.jpg</a>
+ <input type="checkbox" name="my&lt;div&gt;file-clear"
+ id="my&lt;div&gt;file-clear_id">
+ <label for="my&lt;div&gt;file-clear_id">Clear</label><br>
+ Change: <input type="file" name="my&lt;div&gt;file">
+ """
),
)
diff --git a/tests/forms_tests/widget_tests/test_datetimeinput.py b/tests/forms_tests/widget_tests/test_datetimeinput.py
index 5795660f30..e9bb77eb69 100644
--- a/tests/forms_tests/widget_tests/test_datetimeinput.py
+++ b/tests/forms_tests/widget_tests/test_datetimeinput.py
@@ -85,7 +85,10 @@ class DateTimeInputTest(WidgetTest):
self.widget,
"date",
d,
- html='<input type="text" name="date" value="2007-09-17 12:51:34">',
+ html=(
+ '<input type="text" name="date" '
+ 'value="2007-09-17 12:51:34">'
+ ),
)
with translation.override("es"):
self.check_html(
diff --git a/tests/forms_tests/widget_tests/test_multiplehiddeninput.py b/tests/forms_tests/widget_tests/test_multiplehiddeninput.py
index d0ad188929..9498b756e9 100644
--- a/tests/forms_tests/widget_tests/test_multiplehiddeninput.py
+++ b/tests/forms_tests/widget_tests/test_multiplehiddeninput.py
@@ -31,7 +31,10 @@ class MultipleHiddenInputTest(WidgetTest):
"email",
["test@example.com"],
attrs={"class": "fun"},
- html='<input type="hidden" name="email" value="test@example.com" class="fun">',
+ html=(
+ '<input type="hidden" name="email" value="test@example.com" '
+ 'class="fun">'
+ ),
)
def test_render_attrs_multiple(self):
@@ -41,7 +44,8 @@ class MultipleHiddenInputTest(WidgetTest):
["test@example.com", "foo@example.com"],
attrs={"class": "fun"},
html=(
- '<input type="hidden" name="email" value="test@example.com" class="fun">\n'
+ '<input type="hidden" name="email" value="test@example.com" '
+ 'class="fun">\n'
'<input type="hidden" name="email" value="foo@example.com" class="fun">'
),
)
@@ -53,15 +57,19 @@ class MultipleHiddenInputTest(WidgetTest):
widget,
"email",
["foo@example.com"],
- html='<input type="hidden" class="fun" value="foo@example.com" name="email">',
+ html=(
+ '<input type="hidden" class="fun" value="foo@example.com" name="email">'
+ ),
)
self.check_html(
widget,
"email",
["foo@example.com", "test@example.com"],
html=(
- '<input type="hidden" class="fun" value="foo@example.com" name="email">\n'
- '<input type="hidden" class="fun" value="test@example.com" name="email">'
+ '<input type="hidden" class="fun" value="foo@example.com" '
+ 'name="email">\n'
+ '<input type="hidden" class="fun" value="test@example.com" '
+ 'name="email">'
),
)
self.check_html(
@@ -69,7 +77,10 @@ class MultipleHiddenInputTest(WidgetTest):
"email",
["foo@example.com"],
attrs={"class": "special"},
- html='<input type="hidden" class="special" value="foo@example.com" name="email">',
+ html=(
+ '<input type="hidden" class="special" value="foo@example.com" '
+ 'name="email">'
+ ),
)
def test_render_empty(self):
diff --git a/tests/forms_tests/widget_tests/test_multiwidget.py b/tests/forms_tests/widget_tests/test_multiwidget.py
index c3f676e3f7..a89082c4a6 100644
--- a/tests/forms_tests/widget_tests/test_multiwidget.py
+++ b/tests/forms_tests/widget_tests/test_multiwidget.py
@@ -143,7 +143,8 @@ class MultiWidgetTest(WidgetTest):
attrs={"id": "foo"},
html=(
'<input id="foo_0" type="text" class="big" value="john" name="name_0">'
- '<input id="foo_1" type="text" class="small" value="lennon" name="name_1">'
+ '<input id="foo_1" type="text" class="small" value="lennon" '
+ 'name="name_1">'
),
)
@@ -161,7 +162,8 @@ class MultiWidgetTest(WidgetTest):
["john", "lennon"],
html=(
'<input id="bar_0" type="text" class="big" value="john" name="name_0">'
- '<input id="bar_1" type="text" class="small" value="lennon" name="name_1">'
+ '<input id="bar_1" type="text" class="small" value="lennon" '
+ 'name="name_1">'
),
)
diff --git a/tests/forms_tests/widget_tests/test_numberinput.py b/tests/forms_tests/widget_tests/test_numberinput.py
index a6427e6e37..15df02db4f 100644
--- a/tests/forms_tests/widget_tests/test_numberinput.py
+++ b/tests/forms_tests/widget_tests/test_numberinput.py
@@ -12,5 +12,6 @@ class NumberInputTests(WidgetTest):
widget,
"name",
"value",
- '<input type="number" name="name" value="value" max="12345" min="1234" step="9999">',
+ '<input type="number" name="name" value="value" max="12345" min="1234" '
+ 'step="9999">',
)
diff --git a/tests/forms_tests/widget_tests/test_radioselect.py b/tests/forms_tests/widget_tests/test_radioselect.py
index 89e4022f1c..5aa4c194de 100644
--- a/tests/forms_tests/widget_tests/test_radioselect.py
+++ b/tests/forms_tests/widget_tests/test_radioselect.py
@@ -18,9 +18,11 @@ class RadioSelectTest(WidgetTest):
html="""
<div>
<div><label><input type="radio" name="beatle" value=""> ------</label></div>
- <div><label><input checked type="radio" name="beatle" value="J"> John</label></div>
+ <div><label>
+ <input checked type="radio" name="beatle" value="J"> John</label></div>
<div><label><input type="radio" name="beatle" value="P"> Paul</label></div>
- <div><label><input type="radio" name="beatle" value="G"> George</label></div>
+ <div><label>
+ <input type="radio" name="beatle" value="G"> George</label></div>
<div><label><input type="radio" name="beatle" value="R"> Ringo</label></div>
</div>
""",
@@ -35,19 +37,28 @@ class RadioSelectTest(WidgetTest):
html = """
<div id="media">
<div>
- <label for="media_0"><input type="radio" name="nestchoice" value="unknown" id="media_0"> Unknown</label></div>
+ <label for="media_0">
+ <input type="radio" name="nestchoice" value="unknown" id="media_0"> Unknown
+ </label></div>
<div>
<label>Audio</label>
<div>
- <label for="media_1_0"><input type="radio" name="nestchoice" value="vinyl" id="media_1_0"> Vinyl</label></div>
- <div> <label for="media_1_1"><input type="radio" name="nestchoice" value="cd" id="media_1_1"> CD</label></div>
+ <label for="media_1_0">
+ <input type="radio" name="nestchoice" value="vinyl" id="media_1_0"> Vinyl
+ </label></div>
+ <div> <label for="media_1_1">
+ <input type="radio" name="nestchoice" value="cd" id="media_1_1"> CD
+ </label></div>
</div><div>
<label>Video</label>
<div>
- <label for="media_2_0"><input type="radio" name="nestchoice" value="vhs" id="media_2_0"> VHS</label></div>
+ <label for="media_2_0">
+ <input type="radio" name="nestchoice" value="vhs" id="media_2_0"> VHS
+ </label></div>
<div>
- <label for="media_2_1"><input type="radio" name="nestchoice" value="dvd" id="media_2_1" checked> DVD</label>
- </div>
+ <label for="media_2_1">
+ <input type="radio" name="nestchoice" value="dvd" id="media_2_1" checked> DVD
+ </label></div>
</div>
</div>
"""
@@ -68,11 +79,15 @@ class RadioSelectTest(WidgetTest):
html = """
<div id="foo">
<div>
- <label for="foo_0"><input checked type="radio" id="foo_0" value="J" name="beatle"> John</label>
+ <label for="foo_0">
+ <input checked type="radio" id="foo_0" value="J" name="beatle"> John</label>
</div>
- <div><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle"> Paul</label></div>
- <div><label for="foo_2"><input type="radio" id="foo_2" value="G" name="beatle"> George</label></div>
- <div><label for="foo_3"><input type="radio" id="foo_3" value="R" name="beatle"> Ringo</label></div>
+ <div><label for="foo_1">
+ <input type="radio" id="foo_1" value="P" name="beatle"> Paul</label></div>
+ <div><label for="foo_2">
+ <input type="radio" id="foo_2" value="G" name="beatle"> George</label></div>
+ <div><label for="foo_3">
+ <input type="radio" id="foo_3" value="R" name="beatle"> Ringo</label></div>
</div>
"""
self.check_html(widget, "beatle", "J", html=html)
@@ -85,11 +100,15 @@ class RadioSelectTest(WidgetTest):
html = """
<div id="bar">
<div>
- <label for="bar_0"><input checked type="radio" id="bar_0" value="J" name="beatle"> John</label>
+ <label for="bar_0">
+ <input checked type="radio" id="bar_0" value="J" name="beatle"> John</label>
</div>
- <div><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle"> Paul</label></div>
- <div><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle"> George</label></div>
- <div><label for="bar_3"><input type="radio" id="bar_3" value="R" name="beatle"> Ringo</label></div>
+ <div><label for="bar_1">
+ <input type="radio" id="bar_1" value="P" name="beatle"> Paul</label></div>
+ <div><label for="bar_2">
+ <input type="radio" id="bar_2" value="G" name="beatle"> George</label></div>
+ <div><label for="bar_3">
+ <input type="radio" id="bar_3" value="R" name="beatle"> Ringo</label></div>
</div>
"""
self.check_html(
@@ -107,10 +126,15 @@ class RadioSelectTest(WidgetTest):
"""
html = """
<div class="bar">
- <div><label><input checked type="radio" class="bar" value="J" name="beatle"> John</label></div>
- <div><label><input type="radio" class="bar" value="P" name="beatle"> Paul</label></div>
- <div><label><input type="radio" class="bar" value="G" name="beatle"> George</label></div>
- <div><label><input type="radio" class="bar" value="R" name="beatle"> Ringo</label></div>
+ <div><label>
+ <input checked type="radio" class="bar" value="J" name="beatle"> John</label>
+ </div>
+ <div><label>
+ <input type="radio" class="bar" value="P" name="beatle"> Paul</label></div>
+ <div><label>
+ <input type="radio" class="bar" value="G" name="beatle"> George</label></div>
+ <div><label>
+ <input type="radio" class="bar" value="R" name="beatle"> Ringo</label></div>
</div>
"""
self.check_html(
@@ -131,8 +155,10 @@ class RadioSelectTest(WidgetTest):
html = """
<div>
<div><label><input type="radio" name="number" value="1"> One</label></div>
- <div><label><input type="radio" name="number" value="1000"> One thousand</label></div>
- <div><label><input type="radio" name="number" value="1000000"> One million</label></div>
+ <div><label>
+ <input type="radio" name="number" value="1000"> One thousand</label></div>
+ <div><label>
+ <input type="radio" name="number" value="1000000"> One million</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "number", None, html=html)
@@ -143,8 +169,10 @@ class RadioSelectTest(WidgetTest):
]
html = """
<div>
- <div><label><input type="radio" name="time" value="00:00:00"> midnight</label></div>
- <div><label><input type="radio" name="time" value="12:00:00"> noon</label></div>
+ <div><label>
+ <input type="radio" name="time" value="00:00:00"> midnight</label></div>
+ <div><label>
+ <input type="radio" name="time" value="12:00:00"> noon</label></div>
</div>
"""
self.check_html(self.widget(choices=choices), "time", None, html=html)
@@ -158,11 +186,16 @@ class RadioSelectTest(WidgetTest):
["J"],
html="""
<div>
- <div><label><input type="radio" name="beatle_0" value=""> ------</label></div>
- <div><label><input checked type="radio" name="beatle_0" value="J"> John</label></div>
- <div><label><input type="radio" name="beatle_0" value="P"> Paul</label></div>
- <div><label><input type="radio" name="beatle_0" value="G"> George</label></div>
- <div><label><input type="radio" name="beatle_0" value="R"> Ringo</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value=""> ------</label></div>
+ <div><label>
+ <input checked type="radio" name="beatle_0" value="J"> John</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value="P"> Paul</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value="G"> George</label></div>
+ <div><label>
+ <input type="radio" name="beatle_0" value="R"> Ringo</label></div>
</div>
""",
)
diff --git a/tests/forms_tests/widget_tests/test_select.py b/tests/forms_tests/widget_tests/test_select.py
index e78feeb110..8a40bd8b6a 100644
--- a/tests/forms_tests/widget_tests/test_select.py
+++ b/tests/forms_tests/widget_tests/test_select.py
@@ -227,12 +227,16 @@ class SelectTest(WidgetTest):
"email",
"ŠĐĆŽćžšđ",
html=(
- """<select name="email">
- <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" selected>
+ """
+ <select name="email">
+ <option value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"
+ selected>
\u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111
</option>
- <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111</option>
- </select>"""
+ <option value="\u0107\u017e\u0161\u0111">abc\u0107\u017e\u0161\u0111
+ </option>
+ </select>
+ """
),
)
diff --git a/tests/forms_tests/widget_tests/test_selectdatewidget.py b/tests/forms_tests/widget_tests/test_selectdatewidget.py
index de0c35cd5b..9192e4c1f1 100644
--- a/tests/forms_tests/widget_tests/test_selectdatewidget.py
+++ b/tests/forms_tests/widget_tests/test_selectdatewidget.py
@@ -520,7 +520,8 @@ class SelectDateWidgetTest(WidgetTest):
""",
)
- # Even with an invalid date, the widget should reflect the entered value (#17401).
+ # Even with an invalid date, the widget should reflect the entered
+ # value.
self.assertEqual(w.render("mydate", "2010-02-30").count("selected"), 3)
# Years before 1900 should work.
diff --git a/tests/forms_tests/widget_tests/test_textarea.py b/tests/forms_tests/widget_tests/test_textarea.py
index e92dfc51f4..e7695ab018 100644
--- a/tests/forms_tests/widget_tests/test_textarea.py
+++ b/tests/forms_tests/widget_tests/test_textarea.py
@@ -47,7 +47,8 @@ class TextareaTest(WidgetTest):
"msg",
'some "quoted" & ampersanded value',
html=(
- '<textarea rows="10" cols="40" name="msg">some &quot;quoted&quot; &amp; ampersanded value</textarea>'
+ '<textarea rows="10" cols="40" name="msg">'
+ "some &quot;quoted&quot; &amp; ampersanded value</textarea>"
),
)
@@ -57,6 +58,7 @@ class TextareaTest(WidgetTest):
"msg",
mark_safe("pre &quot;quoted&quot; value"),
html=(
- '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value</textarea>'
+ '<textarea rows="10" cols="40" name="msg">pre &quot;quoted&quot; value'
+ "</textarea>"
),
)
diff --git a/tests/forms_tests/widget_tests/test_textinput.py b/tests/forms_tests/widget_tests/test_textinput.py
index 52ffabec65..efd0cfed4b 100644
--- a/tests/forms_tests/widget_tests/test_textinput.py
+++ b/tests/forms_tests/widget_tests/test_textinput.py
@@ -48,7 +48,10 @@ class TextInputTest(WidgetTest):
self.widget,
"email",
'some "quoted" & ampersanded value',
- html='<input type="text" name="email" value="some &quot;quoted&quot; &amp; ampersanded value">',
+ html=(
+ '<input type="text" name="email" '
+ 'value="some &quot;quoted&quot; &amp; ampersanded value">'
+ ),
)
def test_render_custom_attrs(self):
@@ -57,7 +60,9 @@ class TextInputTest(WidgetTest):
"email",
"test@example.com",
attrs={"class": "fun"},
- html='<input type="text" name="email" value="test@example.com" class="fun">',
+ html=(
+ '<input type="text" name="email" value="test@example.com" class="fun">'
+ ),
)
def test_render_unicode(self):
@@ -81,7 +86,9 @@ class TextInputTest(WidgetTest):
widget,
"email",
"foo@example.com",
- html='<input type="email" class="fun" value="foo@example.com" name="email">',
+ html=(
+ '<input type="email" class="fun" value="foo@example.com" name="email">'
+ ),
)
def test_attrs_precedence(self):
diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py
index 7bb9686b6b..c90cf41224 100644
--- a/tests/generic_inline_admin/tests.py
+++ b/tests/generic_inline_admin/tests.py
@@ -74,22 +74,19 @@ class GenericAdminViewTest(TestDataMixin, TestCase):
"""
A smoke test to ensure POST on edit_view works.
"""
+ prefix = "generic_inline_admin-media-content_type-object_id"
post_data = {
"name": "This Week in Django",
# inline data
- "generic_inline_admin-media-content_type-object_id-TOTAL_FORMS": "3",
- "generic_inline_admin-media-content_type-object_id-INITIAL_FORMS": "2",
- "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": "0",
- "generic_inline_admin-media-content_type-object_id-0-id": str(
- self.mp3_media_pk
- ),
- "generic_inline_admin-media-content_type-object_id-0-url": "http://example.com/podcast.mp3",
- "generic_inline_admin-media-content_type-object_id-1-id": str(
- self.png_media_pk
- ),
- "generic_inline_admin-media-content_type-object_id-1-url": "http://example.com/logo.png",
- "generic_inline_admin-media-content_type-object_id-2-id": "",
- "generic_inline_admin-media-content_type-object_id-2-url": "",
+ f"{prefix}-TOTAL_FORMS": "3",
+ f"{prefix}-INITIAL_FORMS": "2",
+ f"{prefix}-MAX_NUM_FORMS": "0",
+ f"{prefix}-0-id": str(self.mp3_media_pk),
+ f"{prefix}-0-url": "http://example.com/podcast.mp3",
+ f"{prefix}-1-id": str(self.png_media_pk),
+ f"{prefix}-1-url": "http://example.com/logo.png",
+ f"{prefix}-2-id": "",
+ f"{prefix}-2-url": "",
}
url = reverse(
"admin:generic_inline_admin_episode_change", args=(self.episode_pk,)
@@ -264,17 +261,16 @@ class GenericInlineAdminWithUniqueTogetherTest(TestDataMixin, TestCase):
def test_add(self):
category_id = Category.objects.create(name="male").pk
+ prefix = "generic_inline_admin-phonenumber-content_type-object_id"
post_data = {
"name": "John Doe",
# inline data
- "generic_inline_admin-phonenumber-content_type-object_id-TOTAL_FORMS": "1",
- "generic_inline_admin-phonenumber-content_type-object_id-INITIAL_FORMS": "0",
- "generic_inline_admin-phonenumber-content_type-object_id-MAX_NUM_FORMS": "0",
- "generic_inline_admin-phonenumber-content_type-object_id-0-id": "",
- "generic_inline_admin-phonenumber-content_type-object_id-0-phone_number": "555-555-5555",
- "generic_inline_admin-phonenumber-content_type-object_id-0-category": str(
- category_id
- ),
+ f"{prefix}-TOTAL_FORMS": "1",
+ f"{prefix}-INITIAL_FORMS": "0",
+ f"{prefix}-MAX_NUM_FORMS": "0",
+ f"{prefix}-0-id": "",
+ f"{prefix}-0-phone_number": "555-555-5555",
+ f"{prefix}-0-category": str(category_id),
}
response = self.client.get(reverse("admin:generic_inline_admin_contact_add"))
self.assertEqual(response.status_code, 200)
diff --git a/tests/generic_relations/test_forms.py b/tests/generic_relations/test_forms.py
index 78c146e22a..00df254745 100644
--- a/tests/generic_relations/test_forms.py
+++ b/tests/generic_relations/test_forms.py
@@ -32,26 +32,46 @@ class GenericInlineFormsetTests(TestCase):
formset = GenericFormSet()
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
-Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text"
-name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
-<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id"
-id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>""",
+ """
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-0-tag"
+ maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-0-id"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
+ """,
)
formset = GenericFormSet(instance=Animal())
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
-Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
-type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE"><input type="hidden"
-name="generic_relations-taggeditem-content_type-object_id-0-id"
-id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>""",
+ """
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-0-tag"
+ maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-0-id"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
+ """,
)
platypus = Animal.objects.create(
common_name="Platypus",
@@ -63,32 +83,54 @@ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>""",
tagged_item_id = TaggedItem.objects.get(tag="shiny", object_id=platypus.id).id
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label>
-<input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text"
-name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
-<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id"
-value="%s" id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-1-tag">Tag:</label>
-<input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text"
-name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50"></p>
-<p><label for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">Delete:</label>
-<input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE"
-id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">
-<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id"
-id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>"""
+ """
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-0-tag"
+ value="shiny" maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-0-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-0-id"
+ value="%s"
+ id="id_generic_relations-taggeditem-content_type-object_id-0-id"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-1-tag">
+ Tag:</label>
+ <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag"
+ type="text"
+ name="generic_relations-taggeditem-content_type-object_id-1-tag"
+ maxlength="50"></p>
+ <p><label
+ for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">
+ Delete:</label>
+ <input type="checkbox"
+ name="generic_relations-taggeditem-content_type-object_id-1-DELETE"
+ id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">
+ <input type="hidden"
+ name="generic_relations-taggeditem-content_type-object_id-1-id"
+ id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>
+ """
% tagged_item_id,
)
lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo")
formset = GenericFormSet(instance=lion, prefix="x")
self.assertHTMLEqual(
"".join(form.as_p() for form in formset.forms),
- """<p><label for="id_x-0-tag">Tag:</label>
-<input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50"></p>
-<p><label for="id_x-0-DELETE">Delete:</label> <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE">
-<input type="hidden" name="x-0-id" id="id_x-0-id"></p>""",
+ """
+ <p><label for="id_x-0-tag">Tag:</label>
+ <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50"></p>
+ <p><label for="id_x-0-DELETE">Delete:</label>
+ <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE">
+ <input type="hidden" name="x-0-id" id="id_x-0-id"></p>
+ """,
)
def test_options(self):
@@ -108,7 +150,9 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>"""
self.assertEqual(len(formset.forms), 5)
self.assertHTMLEqual(
formset.forms[0].as_p(),
- '<input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="%s" '
+ '<input type="hidden" '
+ 'name="generic_relations-taggeditem-content_type-object_id-0-id" '
+ 'value="%s" '
'id="id_generic_relations-taggeditem-content_type-object_id-0-id">'
% harmless.pk,
)
@@ -166,7 +210,10 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id"></p>"""
class BadModel(models.Model):
content_type = models.PositiveIntegerField()
- msg = "fk_name 'generic_relations.BadModel.content_type' is not a ForeignKey to ContentType"
+ msg = (
+ "fk_name 'generic_relations.BadModel.content_type' is not a ForeignKey to "
+ "ContentType"
+ )
with self.assertRaisesMessage(Exception, msg):
generic_inlineformset_factory(BadModel, TaggedItemForm)
diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py
index 6c6b0d1611..7c49e218dd 100644
--- a/tests/generic_relations/tests.py
+++ b/tests/generic_relations/tests.py
@@ -285,7 +285,10 @@ class GenericRelationsTests(TestCase):
def test_add_rejects_unsaved_objects(self):
t1 = TaggedItem(content_object=self.quartz, tag="shiny")
- msg = "<TaggedItem: shiny> instance isn't saved. Use bulk=False or save the object first."
+ msg = (
+ "<TaggedItem: shiny> instance isn't saved. Use bulk=False or save the "
+ "object first."
+ )
with self.assertRaisesMessage(ValueError, msg):
self.bacon.tags.add(t1)
@@ -443,7 +446,8 @@ class GenericRelationsTests(TestCase):
self.assertEqual(ValuableTaggedItem.objects.count(), 0)
def test_gfk_manager(self):
- # GenericForeignKey should not use the default manager (which may filter objects) #16048
+ # GenericForeignKey should not use the default manager (which may
+ # filter objects).
tailless = Gecko.objects.create(has_tail=False)
tag = TaggedItem.objects.create(content_object=tailless, tag="lizard")
self.assertEqual(tag.content_object, tailless)
diff --git a/tests/generic_views/test_dates.py b/tests/generic_views/test_dates.py
index a826d5498d..9edcf8f688 100644
--- a/tests/generic_views/test_dates.py
+++ b/tests/generic_views/test_dates.py
@@ -278,7 +278,8 @@ class YearArchiveViewTests(TestDataMixin, TestCase):
self.assertTemplateUsed(res, "generic_views/book_archive_year.html")
def test_year_view_custom_sort_order(self):
- # Zebras comes after Dreaming by name, but before on '-pubdate' which is the default sorting
+ # Zebras comes after Dreaming by name, but before on '-pubdate' which
+ # is the default sorting.
Book.objects.create(
name="Zebras for Dummies", pages=600, pubdate=datetime.date(2006, 9, 1)
)
@@ -797,12 +798,14 @@ class DayArchiveViewTests(TestDataMixin, TestCase):
)
res = self.client.get("/dates/booksignings/2008/apr/2/")
self.assertEqual(res.status_code, 200)
- # 2008-04-02T00:00:00+03:00 (beginning of day) > 2008-04-01T22:00:00+00:00 (book signing event date)
+ # 2008-04-02T00:00:00+03:00 (beginning of day) >
+ # 2008-04-01T22:00:00+00:00 (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/")
self.assertEqual(res.status_code, 200)
- # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 (book signing event date)
+ # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00
+ # (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/")
@@ -898,12 +901,14 @@ class DateDetailViewTests(TestDataMixin, TestCase):
)
res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk)
self.assertEqual(res.status_code, 200)
- # 2008-04-02T00:00:00+03:00 (beginning of day) > 2008-04-01T22:00:00+00:00 (book signing event date)
+ # 2008-04-02T00:00:00+03:00 (beginning of day) >
+ # 2008-04-01T22:00:00+00:00 (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 1, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk)
self.assertEqual(res.status_code, 200)
- # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00 (book signing event date)
+ # 2008-04-03T00:00:00+03:00 (end of day) > 2008-04-02T22:00:00+00:00
+ # (book signing event date).
bs.event_date = datetime.datetime(2008, 4, 2, 22, 0, tzinfo=timezone.utc)
bs.save()
res = self.client.get("/dates/booksignings/2008/apr/2/%d/" % bs.pk)
diff --git a/tests/get_object_or_404/tests.py b/tests/get_object_or_404/tests.py
index 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('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
- # AUTHORITY["EPSG","7030"]]');
+ # SELECT ST_length_spheroid(
+ # ST_GeomFromText('<wkt>', 4326)
+ # 'SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]]'
+ # );
len_m1 = 473504.769553813
len_m2 = 4617.668
@@ -723,7 +741,8 @@ class DistanceFunctionsTests(FuncTestMixin, TestCase):
Test the `Perimeter` function.
"""
# Reference query:
- # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
+ # SELECT ST_Perimeter(distapp_southtexaszipcode.poly)
+ # FROM distapp_southtexaszipcode;
perim_m = [
18404.3550889361,
15627.2108551001,
diff --git a/tests/gis_tests/gdal_tests/test_ds.py b/tests/gis_tests/gdal_tests/test_ds.py
index 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(
- '<gml:Point gml:id="p21" srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
+ '<gml:Point gml:id="p21" '
+ 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
' <gml:pos srsDimension="2">0 0</gml:pos>'
"</gml:Point>"
),
diff --git a/tests/gis_tests/gdal_tests/test_raster.py b/tests/gis_tests/gdal_tests/test_raster.py
index 795fdd079f..fd59b57313 100644
--- a/tests/gis_tests/gdal_tests/test_raster.py
+++ b/tests/gis_tests/gdal_tests/test_raster.py
@@ -384,11 +384,16 @@ class GDALRasterTests(SimpleTestCase):
]:
self.assertIn(line, info_lines)
for line in [
- r'Upper Left \( 511700.468, 435103.377\) \( 82d51\'46.1\d"W, 27d55\' 1.5\d"N\)',
- r'Lower Left \( 511700.468, 417703.377\) \( 82d51\'52.0\d"W, 27d45\'37.5\d"N\)',
- r'Upper Right \( 528000.468, 435103.377\) \( 82d41\'48.8\d"W, 27d54\'56.3\d"N\)',
- r'Lower Right \( 528000.468, 417703.377\) \( 82d41\'55.5\d"W, 27d45\'32.2\d"N\)',
- r'Center \( 519850.468, 426403.377\) \( 82d46\'50.6\d"W, 27d50\'16.9\d"N\)',
+ r"Upper Left \( 511700.468, 435103.377\) "
+ r'\( 82d51\'46.1\d"W, 27d55\' 1.5\d"N\)',
+ r"Lower Left \( 511700.468, 417703.377\) "
+ r'\( 82d51\'52.0\d"W, 27d45\'37.5\d"N\)',
+ r"Upper Right \( 528000.468, 435103.377\) "
+ r'\( 82d41\'48.8\d"W, 27d54\'56.3\d"N\)',
+ r"Lower Right \( 528000.468, 417703.377\) "
+ r'\( 82d41\'55.5\d"W, 27d45\'32.2\d"N\)',
+ r"Center \( 519850.468, 426403.377\) "
+ r'\( 82d46\'50.6\d"W, 27d50\'16.9\d"N\)',
]:
self.assertRegex(infos, line)
# CRS (skip the name because string depends on the GDAL/Proj versions).
diff --git a/tests/gis_tests/gdal_tests/test_srs.py b/tests/gis_tests/gdal_tests/test_srs.py
index 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 = """<a href="javascript:geodjango_point.clearFeatures()">Delete all Features</a>"""
-
+ delete_all_btn = (
+ '<a href="javascript:geodjango_point.clearFeatures()">Delete all Features'
+ "</a>"
+ )
original_geoadmin = site._registry[City]
params = original_geoadmin.get_map_widget(City._meta.get_field("point")).params
result = original_geoadmin.get_map_widget(
City._meta.get_field("point")
)().render("point", Point(-79.460734, 40.18476), params)
self.assertIn(
- """geodjango_point.layers.base = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");""",
+ "geodjango_point.layers.base = "
+ 'new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");',
result,
)
@@ -50,8 +53,9 @@ class GeoAdminTest(SimpleTestCase):
"point", Point(-79.460734, 40.18476)
)
self.assertIn(
- """geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", """
- """"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic', format: 'image/jpeg'});""",
+ 'geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", '
+ '"http://vmap0.tiles.osgeo.org/wms/vmap0", '
+ "{layers: 'basic', format: 'image/jpeg'});",
result,
)
diff --git a/tests/gis_tests/geoapp/test_functions.py b/tests/gis_tests/geoapp/test_functions.py
index 076e51b7a2..b632d2cf61 100644
--- a/tests/gis_tests/geoapp/test_functions.py
+++ b/tests/gis_tests/geoapp/test_functions.py
@@ -36,12 +36,14 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
'{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}'
)
victoria_json = json.loads(
- '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
+ '{"type":"Point",'
+ '"bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
'"coordinates":[-123.305196,48.462611]}'
)
chicago_json = json.loads(
'{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},'
- '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}'
+ '"bbox":[-87.65018,41.85039,-87.65018,41.85039],'
+ '"coordinates":[-87.65018,41.85039]}'
)
if "crs" in connection.features.unsupported_geojson_options:
del houston_json["crs"]
@@ -131,8 +133,10 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
if connection.ops.oracle:
# No precision parameter for Oracle :-/
gml_regex = re.compile(
- r'^<gml:Point srsName="EPSG:4326" xmlns:gml="http://www.opengis.net/gml">'
- r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ '
+ r'^<gml:Point srsName="EPSG:4326" '
+ r'xmlns:gml="http://www.opengis.net/gml">'
+ r'<gml:coordinates decimal="\." cs="," ts=" ">'
+ r"-104.60925\d+,38.25500\d+ "
r"</gml:coordinates></gml:Point>"
)
else:
@@ -588,7 +592,8 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
# to pass into GEOS `equals_exact`.
tol = 0.000000001
- # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country"
+ # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1))
+ # FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr("MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))")
self.assertTrue(
@@ -600,7 +605,8 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
)
)
- # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country"
+ # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23))
+ # FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr(
"MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))"
@@ -614,10 +620,12 @@ class GISFunctionsTests(FuncTestMixin, TestCase):
)
)
- # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country"
+ # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23))
+ # FROM "geoapp_country"
# WHERE "geoapp_country"."name" = 'San Marino';
ref = fromstr(
- "MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))"
+ "MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,"
+ "12.45 43.87,12.4 43.87)))"
)
self.assertTrue(
ref.equals_exact(
diff --git a/tests/gis_tests/geoapp/tests.py b/tests/gis_tests/geoapp/tests.py
index 33d209bcdb..6acf6e150b 100644
--- a/tests/gis_tests/geoapp/tests.py
+++ b/tests/gis_tests/geoapp/tests.py
@@ -301,8 +301,8 @@ class GeoLookupTest(TestCase):
ks = State.objects.get(poly__contains=lawrence.point)
self.assertEqual("Kansas", ks.name)
- # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas)
- # are not contained in Texas or New Zealand.
+ # Pueblo and Oklahoma City (even though OK City is within the bounding
+ # box of Texas) are not contained in Texas or New Zealand.
self.assertEqual(
len(Country.objects.filter(mpoly__contains=pueblo.point)), 0
) # Query w/GEOSGeometry object
@@ -597,8 +597,10 @@ class GeoQuerySetTest(TestCase):
Testing the `Extent` aggregate.
"""
# Reference query:
- # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');`
- # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
+ # SELECT ST_extent(point)
+ # FROM geoapp_city
+ # WHERE (name='Houston' or name='Dallas');`
+ # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
expected = (
-96.8016128540039,
29.7633724212646,
diff --git a/tests/gis_tests/geogapp/tests.py b/tests/gis_tests/geogapp/tests.py
index 819b86545f..ae12d26706 100644
--- a/tests/gis_tests/geogapp/tests.py
+++ b/tests/gis_tests/geogapp/tests.py
@@ -39,7 +39,10 @@ class GeographyTest(TestCase):
self.assertEqual(["Dallas", "Houston", "Oklahoma City"], cities)
def test04_invalid_operators_functions(self):
- "Ensuring exceptions are raised for operators & functions invalid on geography fields."
+ """
+ Exceptions are raised for operators & functions invalid on geography
+ fields.
+ """
if not connection.ops.postgis:
self.skipTest("This is a PostGIS-specific test.")
# Only a subset of the geometry functions & operator are available
diff --git a/tests/gis_tests/geos_tests/test_geos.py b/tests/gis_tests/geos_tests/test_geos.py
index 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(
- '<gml:Point gml:id="p21" srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
+ '<gml:Point gml:id="p21" '
+ 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">'
' <gml:pos srsDimension="2">0 0</gml:pos>'
"</gml:Point>"
),
diff --git a/tests/gis_tests/inspectapp/tests.py b/tests/gis_tests/inspectapp/tests.py
index 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 = '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/redirected/">'
+ expected = (
+ '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", '
+ 'url="/redirected/">'
+ )
self.assertEqual(repr(response), expected)
def test_invalid_redirect_repr(self):
@@ -545,7 +548,10 @@ class HttpResponseSubclassesTests(SimpleTestCase):
DisallowedRedirect, "Unsafe redirect to URL with protocol 'ssh'"
):
HttpResponseRedirect.__init__(response, "ssh://foo")
- expected = '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="ssh://foo">'
+ expected = (
+ '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", '
+ 'url="ssh://foo">'
+ )
self.assertEqual(repr(response), expected)
def test_not_modified(self):
diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py
index 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 <http://gnu.org/licenses/gpl.html>\n"
+ "License GPLv3+: GNU GPL version 3 or later "
+ "<http://gnu.org/licenses/gpl.html>\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n"
"Written by Ulrich Drepper.\n",
@@ -773,7 +777,10 @@ class LocationCommentsTests(ExtractorTests):
CommandError is raised when using makemessages --add-location with
gettext < 0.19.
"""
- msg = "The --add-location option requires gettext 0.19 or later. You have 0.18.99."
+ msg = (
+ "The --add-location option requires gettext 0.19 or later. You have "
+ "0.18.99."
+ )
with self.assertRaisesMessage(CommandError, msg):
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, add_location="full"
diff --git a/tests/i18n/test_percents.py b/tests/i18n/test_percents.py
index f1dce0c7c6..412b013001 100644
--- a/tests/i18n/test_percents.py
+++ b/tests/i18n/test_percents.py
@@ -87,7 +87,8 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
expected = "Littérale avec un symbole de pour cent à la fin %"
trans_tpl = Template(
- '{% load i18n %}{% translate "Literal with a percent symbol at the end %" %}'
+ "{% load i18n %}"
+ '{% translate "Literal with a percent symbol at the end %" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
@@ -101,7 +102,8 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
expected = "Pour cent littérale % avec un symbole au milieu"
trans_tpl = Template(
- '{% load i18n %}{% translate "Literal with a percent % symbol in the middle" %}'
+ "{% load i18n %}"
+ '{% translate "Literal with a percent % symbol in the middle" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
@@ -124,13 +126,17 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
)
self.assertEqual(block_tpl.render(Context({})), "Il est de 100%")
block_tpl = Template(
- '{% load i18n %}{% blocktranslate context "female" %}It is 100%{% endblocktranslate %}'
+ "{% load i18n %}"
+ '{% blocktranslate context "female" %}It is 100%{% endblocktranslate %}'
)
self.assertEqual(block_tpl.render(Context({})), "Elle est de 100%")
def test_translates_with_string_that_look_like_fmt_spec_with_trans(self):
# tests "%s"
- expected = "On dirait un spec str fmt %s mais ne devrait pas être interprété comme plus disponible"
+ expected = (
+ "On dirait un spec str fmt %s mais ne devrait pas être interprété comme "
+ "plus disponible"
+ )
trans_tpl = Template(
'{% load i18n %}{% translate "Looks like a str fmt spec %s but '
'should not be interpreted as such" %}'
@@ -143,21 +149,28 @@ class RenderingTemplatesWithPercentSigns(FrenchTestCase):
self.assertEqual(block_tpl.render(Context({})), expected)
# tests "% o"
- expected = "On dirait un spec str fmt % o mais ne devrait pas être interprété comme plus disponible"
+ expected = (
+ "On dirait un spec str fmt % o mais ne devrait pas être interprété comme "
+ "plus disponible"
+ )
trans_tpl = Template(
- '{% load i18n %}{% translate "Looks like a str fmt spec % o but should not be '
+ "{% load i18n %}"
+ '{% translate "Looks like a str fmt spec % o but should not be '
'interpreted as such" %}'
)
self.assertEqual(trans_tpl.render(Context({})), expected)
block_tpl = Template(
- "{% load i18n %}{% blocktranslate %}Looks like a str fmt spec % o but should not be "
+ "{% load i18n %}"
+ "{% blocktranslate %}Looks like a str fmt spec % o but should not be "
"interpreted as such{% endblocktranslate %}"
)
self.assertEqual(block_tpl.render(Context({})), expected)
def test_translates_multiple_percent_signs(self):
- expected = "1 % signe pour cent, signes %% 2 pour cent, trois signes de pourcentage %%%"
-
+ expected = (
+ "1 % signe pour cent, signes %% 2 pour cent, trois signes de pourcentage "
+ "%%%"
+ )
trans_tpl = Template(
'{% load i18n %}{% translate "1 percent sign %, 2 percent signs %%, '
'3 percent signs %%%" %}'
diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index 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):
'<option value="6">\u0418\u044e\u043d\u044c</option>'
'<option value="7">\u0418\u044e\u043b\u044c</option>'
'<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>'
- '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c</option>'
+ '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c'
+ "</option>"
'<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>'
'<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>'
- '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c</option>'
+ '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c'
+ "</option>"
"</select>"
'<select name="mydate_year" id="id_mydate_year">'
'<option value="">---</option>'
@@ -1333,13 +1336,17 @@ class FormattingTests(SimpleTestCase):
self.assertHTMLEqual(
form6.as_ul(),
'<li><label for="id_name">Name:</label>'
- '<input id="id_name" type="text" name="name" value="acme" maxlength="50" required></li>'
+ '<input id="id_name" type="text" name="name" value="acme" '
+ ' maxlength="50" required></li>'
'<li><label for="id_date_added">Date added:</label>'
- '<input type="text" name="date_added" value="31.12.2009 06:00:00" id="id_date_added" required></li>'
+ '<input type="text" name="date_added" value="31.12.2009 06:00:00" '
+ ' id="id_date_added" required></li>'
'<li><label for="id_cents_paid">Cents paid:</label>'
- '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" required></li>'
+ '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" '
+ " required></li>"
'<li><label for="id_products_delivered">Products delivered:</label>'
- '<input type="text" name="products_delivered" value="12000" id="id_products_delivered" required>'
+ '<input type="text" name="products_delivered" value="12000" '
+ ' id="id_products_delivered" required>'
"</li>",
)
self.assertEqual(
@@ -1516,7 +1523,8 @@ class FormattingTests(SimpleTestCase):
{"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)}
)
template1 = Template(
- "{% load l10n %}{% localize %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; "
+ "{% load l10n %}{% localize %}"
+ "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; "
"{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}"
)
template2 = Template(
@@ -1589,7 +1597,7 @@ class FormattingTests(SimpleTestCase):
def test_localized_as_text_as_hidden_input(self):
"""
- Tests if form input with 'as_hidden' or 'as_text' is correctly localized. Ticket #18777
+ Form input with 'as_hidden' or 'as_text' is correctly localized.
"""
self.maxDiff = 1200
@@ -1598,10 +1606,12 @@ class FormattingTests(SimpleTestCase):
"{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}"
)
template_as_text = Template(
- "{% load l10n %}{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}"
+ "{% load l10n %}"
+ "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}"
)
template_as_hidden = Template(
- "{% load l10n %}{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}"
+ "{% load l10n %}"
+ "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}"
)
form = CompanyForm(
{
@@ -1616,18 +1626,24 @@ class FormattingTests(SimpleTestCase):
self.assertHTMLEqual(
template.render(context),
- '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required>;'
- '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required>',
+ '<input id="id_date_added" name="date_added" type="text" '
+ 'value="31.12.2009 06:00:00" required>;'
+ '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
+ "required>",
)
self.assertHTMLEqual(
template_as_text.render(context),
- '<input id="id_date_added" name="date_added" type="text" value="31.12.2009 06:00:00" required>;'
- ' <input id="id_cents_paid" name="cents_paid" type="text" value="59,47" required>',
+ '<input id="id_date_added" name="date_added" type="text" '
+ 'value="31.12.2009 06:00:00" required>;'
+ '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" '
+ "required>",
)
self.assertHTMLEqual(
template_as_hidden.render(context),
- '<input id="id_date_added" name="date_added" type="hidden" value="31.12.2009 06:00:00">;'
- '<input id="id_cents_paid" name="cents_paid" type="hidden" value="59,47">',
+ '<input id="id_date_added" name="date_added" type="hidden" '
+ 'value="31.12.2009 06:00:00">;'
+ '<input id="id_cents_paid" name="cents_paid" type="hidden" '
+ 'value="59,47">',
)
def test_format_arbitrary_settings(self):
@@ -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):
"""
<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
- <object pk="%(m_pk)s" model="m2m_through_regress.membership">
- <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field>
- <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field>
+ <object pk="%(m_pk)s" model="%(app_label)s.membership">
+ <field to="%(app_label)s.person" name="person" rel="ManyToOneRel">%(p_pk)s</field>
+ <field to="%(app_label)s.group" name="group" rel="ManyToOneRel">%(g_pk)s</field>
<field type="IntegerField" name="price">100</field>
</object>
- <object pk="%(p_pk)s" model="m2m_through_regress.person">
+ <object pk="%(p_pk)s" model="%(app_label)s.person">
<field type="CharField" name="name">Bob</field>
</object>
- <object pk="%(g_pk)s" model="m2m_through_regress.group">
+ <object pk="%(g_pk)s" model="%(app_label)s.group">
<field type="CharField" name="name">Roll</field>
</object>
</django-objects>
@@ -223,7 +230,10 @@ class ThroughLoadDataTestCase(TestCase):
)
self.assertJSONEqual(
out.getvalue().strip(),
- '[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user"'
- ': 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, '
- '"model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]',
+ '[{"pk": 1, "model": "m2m_through_regress.usermembership", '
+ '"fields": {"price": 100, "group": 1, "user": 1}}, '
+ '{"pk": 1, "model": "m2m_through_regress.person", '
+ '"fields": {"name": "Guido"}}, '
+ '{"pk": 1, "model": "m2m_through_regress.group", '
+ '"fields": {"name": "Python Core Group"}}]',
)
diff --git a/tests/mail/tests.py b/tests/mail/tests.py
index 309be47059..51e26cc6be 100644
--- a/tests/mail/tests.py
+++ b/tests/mail/tests.py
@@ -295,8 +295,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
Test for space continuation character in long (ASCII) subject headers (#7747)
"""
email = EmailMessage(
- "Long subject lines that get wrapped should contain a space "
- "continuation character to get expected behavior in Outlook and Thunderbird",
+ "Long subject lines that get wrapped should contain a space continuation "
+ "character to get expected behavior in Outlook and Thunderbird",
"Content",
"from@example.com",
["to@example.com"],
@@ -367,7 +367,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
email.to, ["list-subscriber@example.com", "list-subscriber2@example.com"]
)
- # If we don't set the To header manually, it should default to the `to` argument to the constructor
+ # If we don't set the To header manually, it should default to the `to`
+ # argument to the constructor.
email = EmailMessage(
"Subject",
"Content",
@@ -558,7 +559,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
)
self.assertEqual(message.get_payload(), "Firstname S=FCrname is a great guy.")
- # Make sure MIME attachments also works correctly with other encodings than utf-8
+ # MIME attachments works correctly with other encodings than utf-8.
text_content = "Firstname Sürname is a great guy."
html_content = "<p>Firstname Sürname is a <strong>great</strong> guy.</p>"
msg = EmailMultiAlternatives(
@@ -790,7 +791,10 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
)
if sys.platform == "win32":
- msg = "_getfullpathname: path should be string, bytes or os.PathLike, not object"
+ msg = (
+ "_getfullpathname: path should be string, bytes or os.PathLike, not "
+ "object"
+ )
else:
msg = "expected str, bytes or os.PathLike object, not object"
with self.assertRaisesMessage(TypeError, msg):
@@ -871,7 +875,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
self.assertIn(b"Content-Transfer-Encoding: 7bit", msg.message().as_bytes())
# Ticket #11212
- # Shouldn't use quoted printable, should detect it can represent content with 7 bit data
+ # Shouldn't use quoted printable, should detect it can represent
+ # content with 7 bit data.
msg = EmailMessage(
"Subject",
"Body with only ASCII characters.",
@@ -882,7 +887,8 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
s = msg.message().as_bytes()
self.assertIn(b"Content-Transfer-Encoding: 7bit", s)
- # Shouldn't use quoted printable, should detect it can represent content with 8 bit data
+ # Shouldn't use quoted printable, should detect it can represent
+ # content with 8 bit data.
msg = EmailMessage(
"Subject",
"Body with latin characters: àáä.",
@@ -1182,7 +1188,8 @@ class BaseEmailBackendTests(HeadersCheckMixin):
def get_mailbox_content(self):
raise NotImplementedError(
- "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() method"
+ "subclasses of BaseEmailBackendTests must provide a get_mailbox_content() "
+ "method"
)
def flush_mailbox(self):
diff --git a/tests/managers_regress/tests.py b/tests/managers_regress/tests.py
index 8a67b9f685..33192a1699 100644
--- a/tests/managers_regress/tests.py
+++ b/tests/managers_regress/tests.py
@@ -152,7 +152,8 @@ class ManagersRegressionTests(TestCase):
relation.m2m.add(related)
t = Template(
- "{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}{{ related.test_m2m.all.0 }}"
+ "{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}"
+ "{{ related.test_m2m.all.0 }}"
)
self.assertEqual(
diff --git a/tests/many_to_many/tests.py b/tests/many_to_many/tests.py
index 3d393b5711..53e870ddad 100644
--- a/tests/many_to_many/tests.py
+++ b/tests/many_to_many/tests.py
@@ -57,7 +57,10 @@ class ManyToManyTests(TestCase):
)
# Adding an object of the wrong type raises TypeError
- msg = "'Publication' instance expected, got <Article: Django lets you create web apps easily>"
+ msg = (
+ "'Publication' instance expected, got <Article: Django lets you create web "
+ "apps easily>"
+ )
with self.assertRaisesMessage(TypeError, msg):
with transaction.atomic():
a6.publications.add(a5)
diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py
index 8fca4d691f..b8b040eff6 100644
--- a/tests/many_to_one/tests.py
+++ b/tests/many_to_one/tests.py
@@ -84,7 +84,10 @@ class ManyToOneTests(TestCase):
new_article2 = Article(
headline="Paul's story", pub_date=datetime.date(2006, 1, 17)
)
- msg = "<Article: Paul's story> instance isn't saved. Use bulk=False or save the object first."
+ msg = (
+ "<Article: Paul's story> instance isn't saved. Use bulk=False or save the "
+ "object first."
+ )
with self.assertRaisesMessage(ValueError, msg):
self.r.article_set.add(new_article2)
@@ -268,7 +271,8 @@ class ManyToOneTests(TestCase):
),
[new_article1, self.a],
)
- # The underlying query only makes one join when a related table is referenced twice.
+ # The underlying query only makes one join when a related table is
+ # referenced twice.
queryset = Article.objects.filter(
reporter__first_name__exact="John", reporter__last_name__exact="Smith"
)
@@ -284,7 +288,8 @@ class ManyToOneTests(TestCase):
),
[new_article1, self.a],
)
- # ... and should work fine with the string that comes out of forms.Form.cleaned_data
+ # ... and should work fine with the string that comes out of
+ # forms.Form.cleaned_data.
self.assertQuerysetEqual(
(
Article.objects.filter(reporter__first_name__exact="John").extra(
@@ -632,11 +637,13 @@ class ManyToOneTests(TestCase):
# Creation using keyword argument and unsaved related instance (#8070).
p = Parent()
- msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'."
+ msg = (
+ "save() prohibited to prevent data loss due to unsaved related object "
+ "'parent'."
+ )
with self.assertRaisesMessage(ValueError, msg):
Child.objects.create(parent=p)
- msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'."
with self.assertRaisesMessage(ValueError, msg):
ToFieldChild.objects.create(parent=p)
diff --git a/tests/messages_tests/test_api.py b/tests/messages_tests/test_api.py
index dcd98f085c..40283d4153 100644
--- a/tests/messages_tests/test_api.py
+++ b/tests/messages_tests/test_api.py
@@ -35,7 +35,10 @@ class ApiTests(SimpleTestCase):
self.assertEqual(self.storage.store, [])
def test_middleware_missing(self):
- msg = "You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware"
+ msg = (
+ "You cannot add messages without installing "
+ "django.contrib.messages.middleware.MessageMiddleware"
+ )
with self.assertRaisesMessage(messages.MessageFailure, msg):
messages.add_message(self.request, messages.DEBUG, "some message")
self.assertEqual(self.storage.store, [])
diff --git a/tests/messages_tests/test_cookie.py b/tests/messages_tests/test_cookie.py
index 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 <class 'django.db.models.base.Model'> in CreateModel bases argument."
+ message = (
+ "Found duplicate value <class 'django.db.models.base.Model'> in "
+ "CreateModel bases argument."
+ )
with self.assertRaisesMessage(ValueError, message):
migrations.CreateModel(
"Pony",
@@ -135,7 +142,10 @@ class OperationTests(OperationTestBase):
models.Model,
),
)
- message = "Found duplicate value <class 'migrations.test_operations.Mixin'> in CreateModel bases argument."
+ message = (
+ "Found duplicate value <class 'migrations.test_operations.Mixin'> in "
+ "CreateModel bases argument."
+ )
with self.assertRaisesMessage(ValueError, message):
migrations.CreateModel(
"Pony",
@@ -838,7 +848,8 @@ class OperationTests(OperationTestBase):
.remote_field.model,
new_state.models["test_rmwsc", "rider"].fields["pony"].remote_field.model,
)
- # Before running the migration we have a table for Shetland Pony, not Little Horse
+ # Before running the migration we have a table for Shetland Pony, not
+ # Little Horse.
self.assertTableExists("test_rmwsc_shetlandpony")
self.assertTableNotExists("test_rmwsc_littlehorse")
if connection.features.supports_foreign_keys:
@@ -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", []),
- """<div>
-<div><label><input type="checkbox" name="name" value="%d" data-slug="entertainment">Entertainment</label></div>
-<div><label><input type="checkbox" name="name" value="%d" data-slug="test">A test</label></div>
-<div><label><input type="checkbox" name="name" value="%d" data-slug="third-test">Third</label></div>
-</div>"""
+ """
+ <div><div>
+ <label><input type="checkbox" name="name" value="%d"
+ data-slug="entertainment">Entertainment
+ </label></div>
+ <div><label>
+ <input type="checkbox" name="name" value="%d" data-slug="test">A test
+ </label></div>
+ <div><label>
+ <input type="checkbox" name="name" value="%d" data-slug="third-test">Third
+ </label></div></div>
+ """
% (self.c1.pk, self.c2.pk, self.c3.pk),
)
diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
index 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"]),
- '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" required></textarea>',
+ '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" '
+ "required></textarea>",
)
self.assertHTMLEqual(
str(form["url"]),
- '<input id="id_url" type="text" class="url" name="url" maxlength="40" required>',
+ '<input id="id_url" type="text" class="url" name="url" maxlength="40" '
+ "required>",
)
self.assertHTMLEqual(
str(form["slug"]),
@@ -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()),
- """<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" required></li>
-<li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" required></li>
-<li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" required></li>""",
+ """
+ <li><label for="id_name">Name:</label>
+ <input id="id_name" type="text" name="name" maxlength="20" required></li>
+ <li><label for="id_slug">Slug:</label>
+ <input id="id_slug" type="text" name="slug" maxlength="20" required></li>
+ <li><label for="id_url">The URL:</label>
+ <input id="id_url" type="text" name="url" maxlength="40" required></li>
+ """,
)
self.assertHTMLEqual(
str(f["name"]),
@@ -1488,26 +1504,32 @@ class ModelFormBasicTests(TestCase):
)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" required></li>
-<li>Writer: <select name="writer" required>
-<option value="" selected>---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></li>
-<li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li>
-<li>Categories: <select multiple name="categories">
-<option value="%s" selected>Entertainment</option>
-<option value="%s" selected>It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></li>
-<li>Status: <select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></li>"""
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="Your headline here" maxlength="50"
+ required>
+ </li>
+ <li>Slug: <input type="text" name="slug" maxlength="50" required></li>
+ <li>Pub date: <input type="text" name="pub_date" required></li>
+ <li>Writer: <select name="writer" required>
+ <option value="" selected>---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></li>
+ <li>Article:
+ <textarea rows="10" cols="40" name="article" required></textarea></li>
+ <li>Categories: <select multiple name="categories">
+ <option value="%s" selected>Entertainment</option>
+ <option value="%s" selected>It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></li>
+ <li>Status: <select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></li>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -1516,8 +1538,12 @@ class ModelFormBasicTests(TestCase):
f = RoykoForm(auto_id=False, instance=self.w_royko)
self.assertHTMLEqual(
str(f),
- """<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" required><br>
- <span class="helptext">Use both first and last names.</span></td></tr>""",
+ """
+ <tr><th>Name:</th><td>
+ <input type="text" name="name" value="Mike Royko" maxlength="50" required>
+ <br>
+ <span class="helptext">Use both first and last names.</span></td></tr>
+ """,
)
art = Article.objects.create(
@@ -1532,26 +1558,35 @@ class ModelFormBasicTests(TestCase):
f = ArticleForm(auto_id=False, instance=art)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>
-<li>Writer: <select name="writer" required>
-<option value="">---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s" selected>Mike Royko</option>
-</select></li>
-<li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
-<li>Categories: <select multiple name="categories">
-<option value="%s">Entertainment</option>
-<option value="%s">It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></li>
-<li>Status: <select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></li>"""
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="Test article" maxlength="50"
+ required>
+ </li>
+ <li>Slug:
+ <input type="text" name="slug" value="test-article" maxlength="50" required>
+ </li>
+ <li>Pub date:
+ <input type="text" name="pub_date" value="1988-01-04" required></li>
+ <li>Writer: <select name="writer" required>
+ <option value="">---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s" selected>Mike Royko</option>
+ </select></li>
+ <li>Article:
+ <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
+ <li>Categories: <select multiple name="categories">
+ <option value="%s">Entertainment</option>
+ <option value="%s">It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></li>
+ <li>Status: <select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></li>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -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),
- """<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr>
-<tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" required></td></tr>
-<tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr>
-<tr><th>Writer:</th><td><select name="writer" required>
-<option value="" selected>---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></td></tr>
-<tr><th>Article:</th><td><textarea rows="10" cols="40" name="article" required></textarea></td></tr>
-<tr><th>Categories:</th><td><select multiple name="categories">
-<option value="%s">Entertainment</option>
-<option value="%s">It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></td></tr>
-<tr><th>Status:</th><td><select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></td></tr>"""
+ """
+ <tr><th>Headline:</th><td>
+ <input type="text" name="headline" maxlength="50" required></td></tr>
+ <tr><th>Slug:</th><td>
+ <input type="text" name="slug" maxlength="50" required></td></tr>
+ <tr><th>Pub date:</th><td>
+ <input type="text" name="pub_date" required></td></tr>
+ <tr><th>Writer:</th><td><select name="writer" required>
+ <option value="" selected>---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></td></tr>
+ <tr><th>Article:</th><td>
+ <textarea rows="10" cols="40" name="article" required></textarea></td></tr>
+ <tr><th>Categories:</th><td><select multiple name="categories">
+ <option value="%s">Entertainment</option>
+ <option value="%s">It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></td></tr>
+ <tr><th>Status:</th><td><select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></td></tr>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -1702,26 +1744,35 @@ class ModelFormBasicTests(TestCase):
f = ArticleForm(auto_id=False, instance=new_art)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>
-<li>Writer: <select name="writer" required>
-<option value="">---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s" selected>Mike Royko</option>
-</select></li>
-<li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
-<li>Categories: <select multiple name="categories">
-<option value="%s" selected>Entertainment</option>
-<option value="%s">It&#x27;s a test</option>
-<option value="%s">Third test</option>
-</select></li>
-<li>Status: <select name="status">
-<option value="" selected>---------</option>
-<option value="1">Draft</option>
-<option value="2">Pending</option>
-<option value="3">Live</option>
-</select></li>"""
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="New headline" maxlength="50"
+ required>
+ </li>
+ <li>Slug:
+ <input type="text" name="slug" value="new-headline" maxlength="50" required>
+ </li>
+ <li>Pub date:
+ <input type="text" name="pub_date" value="1988-01-04" required></li>
+ <li>Writer: <select name="writer" required>
+ <option value="">---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s" selected>Mike Royko</option>
+ </select></li>
+ <li>Article:
+ <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li>
+ <li>Categories: <select multiple name="categories">
+ <option value="%s" selected>Entertainment</option>
+ <option value="%s">It&#x27;s a test</option>
+ <option value="%s">Third test</option>
+ </select></li>
+ <li>Status: <select name="status">
+ <option value="" selected>---------</option>
+ <option value="1">Draft</option>
+ <option value="2">Pending</option>
+ <option value="3">Live</option>
+ </select></li>
+ """
% (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk),
)
@@ -1740,8 +1791,12 @@ class ModelFormBasicTests(TestCase):
f = PartialArticleForm(auto_id=False)
self.assertHTMLEqual(
str(f),
- """<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr>
-<tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr>""",
+ """
+ <tr><th>Headline:</th><td>
+ <input type="text" name="headline" maxlength="50" required></td></tr>
+ <tr><th>Pub date:</th><td>
+ <input type="text" name="pub_date" required></td></tr>
+ """,
)
class PartialArticleFormWithSlug(forms.ModelForm):
@@ -1768,9 +1823,18 @@ class ModelFormBasicTests(TestCase):
)
self.assertHTMLEqual(
f.as_ul(),
- """<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li>
-<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li>
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>""",
+ """
+ <li>Headline:
+ <input type="text" name="headline" value="New headline" maxlength="50"
+ required>
+ </li>
+ <li>Slug:
+ <input type="text" name="slug" value="new-headline" maxlength="50"
+ required>
+ </li>
+ <li>Pub date:
+ <input type="text" name="pub_date" value="1988-01-04" required></li>
+ """,
)
self.assertTrue(f.is_valid())
new_art = f.save()
@@ -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(),
- """<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required>
-<option value="" selected>---------</option>
-<option value="%s">Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></p>
-<p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" required></p>"""
+ """
+ <p><label for="id_writer">Writer:</label>
+ <select name="writer" id="id_writer" required>
+ <option value="" selected>---------</option>
+ <option value="%s">Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></p>
+ <p><label for="id_age">Age:</label>
+ <input type="number" name="age" id="id_age" min="0" required></p>
+ """
% (
self.w_woodward.pk,
self.w_royko.pk,
@@ -2294,13 +2365,16 @@ class ModelOneToOneFieldTests(TestCase):
form = WriterProfileForm(instance=instance)
self.assertHTMLEqual(
form.as_p(),
- """<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required>
-<option value="">---------</option>
-<option value="%s" selected>Bob Woodward</option>
-<option value="%s">Mike Royko</option>
-</select></p>
-<p><label for="id_age">Age:</label>
-<input type="number" name="age" value="65" id="id_age" min="0" required></p>"""
+ """
+ <p><label for="id_writer">Writer:</label>
+ <select name="writer" id="id_writer" required>
+ <option value="">---------</option>
+ <option value="%s" selected>Bob Woodward</option>
+ <option value="%s">Mike Royko</option>
+ </select></p>
+ <p><label for="id_age">Age:</label>
+ <input type="number" name="age" value="65" id="id_age" min="0" required>
+ </p>"""
% (
self.w_woodward.pk,
self.w_royko.pk,
@@ -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(),
- """<p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" required></p>
- <p><label for="id_colours">Colours:</label>
- <select multiple name="colours" id="id_colours" required>
- <option value="%(blue_pk)s">Blue</option>
- </select></p>"""
+ """
+ <p>
+ <label for="id_name">Name:</label>
+ <input id="id_name" type="text" name="name" maxlength="50" required></p>
+ <p><label for="id_colours">Colours:</label>
+ <select multiple name="colours" id="id_colours" required>
+ <option value="%(blue_pk)s">Blue</option>
+ </select></p>
+ """
% {"blue_pk": colour.pk},
)
@@ -2969,19 +3054,27 @@ class OtherModelFormTests(TestCase):
form.as_p(),
"""
<p><label for="id_title">Title:</label>
- <input id="id_title" maxlength="30" name="title" type="text" required></p>
+ <input id="id_title" maxlength="30" name="title" type="text" required>
+ </p>
<p><label for="id_date_published">Date published:</label>
- <input id="id_date_published" name="date_published" type="text" value="{0}" required>
- <input id="initial-id_date_published" name="initial-date_published" type="hidden" value="{0}"></p>
+ <input id="id_date_published" name="date_published" type="text" value="{0}"
+ required>
+ <input id="initial-id_date_published" name="initial-date_published"
+ type="hidden" value="{0}">
+ </p>
<p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode">
- <option value="di" selected>direct</option>
- <option value="de">delayed</option></select>
- <input id="initial-id_mode" name="initial-mode" type="hidden" value="di"></p>
- <p><label for="id_category">Category:</label> <select id="id_category" name="category">
- <option value="1">Games</option>
- <option value="2">Comics</option>
- <option value="3" selected>Novel</option></select>
- <input id="initial-id_category" name="initial-category" type="hidden" value="3">
+ <option value="di" selected>direct</option>
+ <option value="de">delayed</option></select>
+ <input id="initial-id_mode" name="initial-mode" type="hidden" value="di">
+ </p>
+ <p>
+ <label for="id_category">Category:</label>
+ <select id="id_category" name="category">
+ <option value="1">Games</option>
+ <option value="2">Comics</option>
+ <option value="3" selected>Novel</option></select>
+ <input id="initial-id_category" name="initial-category" type="hidden"
+ value="3">
""".format(
today_str
),
@@ -3025,7 +3118,8 @@ class ModelFormCustomErrorTests(SimpleTestCase):
self.assertFalse(form.is_valid())
self.assertHTMLEqual(
str(form.errors["name1"]),
- '<ul class="errorlist"><li>Model.clean() error messages (simpler syntax).</li></ul>',
+ '<ul class="errorlist">'
+ "<li>Model.clean() error messages (simpler syntax).</li></ul>",
)
data = {"name1": "GLOBAL_ERROR", "name2": "ABC"}
form = CustomErrorMessageForm(data)
@@ -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(),
'<p><label for="id_form-2-name">Name:</label>'
- ' <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">'
+ '<input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">'
'<input type="hidden" name="form-2-id" id="id_form-2-id"></p>',
)
@@ -229,14 +229,16 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_form-0-name">Name:</label>'
- '<input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100">'
+ '<input id="id_form-0-name" type="text" name="form-0-name" '
+ 'value="Arthur Rimbaud" maxlength="100">'
'<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id"></p>'
% author2.id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_form-1-name">Name:</label>'
- '<input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100">'
+ '<input id="id_form-1-name" type="text" name="form-1-name" '
+ 'value="Charles Baudelaire" maxlength="100">'
'<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id"></p>'
% author1.id,
)
@@ -313,8 +315,8 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[3].as_p(),
'<p><label for="id_form-3-name">Name:</label>'
- '<input id="id_form-3-name" type="text" name="form-3-name" maxlength="100"></p>'
- '<p><label for="id_form-3-DELETE">Delete:</label>'
+ '<input id="id_form-3-name" type="text" name="form-3-name" maxlength="100">'
+ '</p><p><label for="id_form-3-DELETE">Delete:</label>'
'<input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE">'
'<input type="hidden" name="form-3-id" id="id_form-3-id"></p>',
)
@@ -565,10 +567,11 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_form-0-name">Name:</label>'
- '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100"></p>'
- '<p><label for="id_form-0-write_speed">Write speed:</label>'
+ '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100">'
+ '</p><p><label for="id_form-0-write_speed">Write speed:</label>'
'<input type="number" name="form-0-write_speed" id="id_form-0-write_speed">'
- '<input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr"></p>',
+ '<input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr">'
+ "</p>",
)
data = {
@@ -593,19 +596,22 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_form-0-name">Name:</label>'
- '<input id="id_form-0-name" type="text" name="form-0-name" value="Ernest Hemingway" maxlength="100"></p>'
+ '<input id="id_form-0-name" type="text" name="form-0-name" '
+ 'value="Ernest Hemingway" maxlength="100"></p>'
'<p><label for="id_form-0-write_speed">Write speed:</label>'
- '<input type="number" name="form-0-write_speed" value="10" id="id_form-0-write_speed">'
- '<input type="hidden" name="form-0-author_ptr" value="%d" id="id_form-0-author_ptr"></p>'
- % hemingway_id,
+ '<input type="number" name="form-0-write_speed" value="10" '
+ 'id="id_form-0-write_speed">'
+ '<input type="hidden" name="form-0-author_ptr" value="%d" '
+ 'id="id_form-0-author_ptr"></p>' % hemingway_id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_form-1-name">Name:</label>'
- '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100"></p>'
- '<p><label for="id_form-1-write_speed">Write speed:</label>'
+ '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100">'
+ '</p><p><label for="id_form-1-write_speed">Write speed:</label>'
'<input type="number" name="form-1-write_speed" id="id_form-1-write_speed">'
- '<input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr"></p>',
+ '<input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr">'
+ "</p>",
)
data = {
@@ -637,24 +643,31 @@ class ModelFormsetTest(TestCase):
self.assertEqual(len(formset.forms), 3)
self.assertHTMLEqual(
formset.forms[0].as_p(),
- '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" '
- 'name="book_set-0-title" maxlength="100"><input type="hidden" name="book_set-0-author" value="%d" '
- 'id="id_book_set-0-author"><input type="hidden" name="book_set-0-id" id="id_book_set-0-id">'
+ '<p><label for="id_book_set-0-title">Title:</label>'
+ '<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-0-author" value="%d" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" id="id_book_set-0-id">'
"</p>" % author.id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
- '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">'
+ '<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-1-author" value="%d" '
+ 'id="id_book_set-1-author">'
'<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>'
% author.id,
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
- '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">'
+ '<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-2-author" value="%d" '
+ 'id="id_book_set-2-author">'
'<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>'
% author.id,
)
@@ -693,8 +706,10 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_book_set-0-title">Title:</label>'
'<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
'value="Les Fleurs du Mal" maxlength="100">'
- '<input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author">'
- '<input type="hidden" name="book_set-0-id" value="%d" id="id_book_set-0-id"></p>'
+ '<input type="hidden" name="book_set-0-author" value="%d" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" value="%d" '
+ 'id="id_book_set-0-id"></p>'
% (
author.id,
book1.id,
@@ -703,16 +718,20 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
- '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">'
+ '<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-1-author" value="%d" '
+ 'id="id_book_set-1-author">'
'<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>'
% author.id,
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
- '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">'
+ '<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-2-author" value="%d" '
+ 'id="id_book_set-2-author">'
'<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>'
% author.id,
)
@@ -782,7 +801,8 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_test-0-title">Title:</label>'
- '<input id="id_test-0-title" type="text" name="test-0-title" maxlength="100">'
+ '<input id="id_test-0-title" type="text" name="test-0-title" '
+ 'maxlength="100">'
'<input type="hidden" name="test-0-author" id="id_test-0-author">'
'<input type="hidden" name="test-0-id" id="id_test-0-id"></p>',
)
@@ -790,7 +810,8 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_test-1-title">Title:</label>'
- '<input id="id_test-1-title" type="text" name="test-1-title" maxlength="100">'
+ '<input id="id_test-1-title" type="text" name="test-1-title" '
+ 'maxlength="100">'
'<input type="hidden" name="test-1-author" id="id_test-1-author">'
'<input type="hidden" name="test-1-id" id="id_test-1-id"></p>',
)
@@ -820,9 +841,12 @@ class ModelFormsetTest(TestCase):
)
data = {
- "bookwithcustompk_set-TOTAL_FORMS": "1", # the number of forms rendered
- "bookwithcustompk_set-INITIAL_FORMS": "0", # the number of forms with initial data
- "bookwithcustompk_set-MAX_NUM_FORMS": "", # the max number of forms
+ # The number of forms rendered.
+ "bookwithcustompk_set-TOTAL_FORMS": "1",
+ # The number of forms with initial data.
+ "bookwithcustompk_set-INITIAL_FORMS": "0",
+ # The max number of forms.
+ "bookwithcustompk_set-MAX_NUM_FORMS": "",
"bookwithcustompk_set-0-my_pk": "77777",
"bookwithcustompk_set-0-title": "Les Fleurs du Mal",
}
@@ -864,9 +888,12 @@ class ModelFormsetTest(TestCase):
)
data = {
- "alternatebook_set-TOTAL_FORMS": "1", # the number of forms rendered
- "alternatebook_set-INITIAL_FORMS": "0", # the number of forms with initial data
- "alternatebook_set-MAX_NUM_FORMS": "", # the max number of forms
+ # The number of forms rendered.
+ "alternatebook_set-TOTAL_FORMS": "1",
+ # The number of forms with initial data.
+ "alternatebook_set-INITIAL_FORMS": "0",
+ # The max number of forms.
+ "alternatebook_set-MAX_NUM_FORMS": "",
"alternatebook_set-0-title": "Flowers of Evil",
"alternatebook_set-0-notes": "English translation of Les Fleurs du Mal",
}
@@ -895,9 +922,12 @@ class ModelFormsetTest(TestCase):
author = Author.objects.create(pk=1, name="Charles Baudelaire")
data = {
- "bookwithoptionalalteditor_set-TOTAL_FORMS": "2", # the number of forms rendered
- "bookwithoptionalalteditor_set-INITIAL_FORMS": "0", # the number of forms with initial data
- "bookwithoptionalalteditor_set-MAX_NUM_FORMS": "", # the max number of forms
+ # The number of forms rendered.
+ "bookwithoptionalalteditor_set-TOTAL_FORMS": "2",
+ # The number of forms with initial data.
+ "bookwithoptionalalteditor_set-INITIAL_FORMS": "0",
+ # The max number of forms.
+ "bookwithoptionalalteditor_set-MAX_NUM_FORMS": "",
"bookwithoptionalalteditor_set-0-author": "1",
"bookwithoptionalalteditor_set-0-title": "Les Fleurs du Mal",
"bookwithoptionalalteditor_set-1-author": "1",
@@ -965,37 +995,47 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_book_set-0-title">Title:</label>'
'<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
'value="Les Paradis Artificiels" maxlength="100">'
- '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">'
- '<input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id"></p>',
+ '<input type="hidden" name="book_set-0-author" value="1" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id">'
+ "</p>",
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
'<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
'value="Les Fleurs du Mal" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">'
- '<input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id"></p>',
+ '<input type="hidden" name="book_set-1-author" value="1" '
+ 'id="id_book_set-1-author">'
+ '<input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id">'
+ "</p>",
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
'<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
'value="Flowers of Evil" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">'
- '<input type="hidden" name="book_set-2-id" value="3" id="id_book_set-2-id"></p>',
+ '<input type="hidden" name="book_set-2-author" value="1" '
+ 'id="id_book_set-2-author">'
+ '<input type="hidden" name="book_set-2-id" value="3" '
+ 'id="id_book_set-2-id"></p>',
)
self.assertHTMLEqual(
formset.forms[3].as_p(),
'<p><label for="id_book_set-3-title">Title:</label>'
- '<input id="id_book_set-3-title" type="text" name="book_set-3-title" maxlength="100">'
- '<input type="hidden" name="book_set-3-author" value="1" id="id_book_set-3-author">'
+ '<input id="id_book_set-3-title" type="text" name="book_set-3-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-3-author" value="1" '
+ 'id="id_book_set-3-author">'
'<input type="hidden" name="book_set-3-id" id="id_book_set-3-id"></p>',
)
self.assertHTMLEqual(
formset.forms[4].as_p(),
'<p><label for="id_book_set-4-title">Title:</label>'
- '<input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100">'
- '<input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author">'
+ '<input id="id_book_set-4-title" type="text" name="book_set-4-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-4-author" value="1" '
+ 'id="id_book_set-4-author">'
'<input type="hidden" name="book_set-4-id" id="id_book_set-4-id"></p>',
)
@@ -1022,21 +1062,27 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_book_set-0-title">Title:</label>'
'<input id="id_book_set-0-title" type="text" name="book_set-0-title" '
'value="Flowers of Evil" maxlength="100">'
- '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">'
- '<input type="hidden" name="book_set-0-id" value="3" id="id_book_set-0-id"></p>',
+ '<input type="hidden" name="book_set-0-author" value="1" '
+ 'id="id_book_set-0-author">'
+ '<input type="hidden" name="book_set-0-id" value="3" '
+ 'id="id_book_set-0-id"></p>',
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_book_set-1-title">Title:</label>'
- '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">'
- '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">'
+ '<input id="id_book_set-1-title" type="text" name="book_set-1-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-1-author" value="1" '
+ 'id="id_book_set-1-author">'
'<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>',
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_book_set-2-title">Title:</label>'
- '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">'
- '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">'
+ '<input id="id_book_set-2-title" type="text" name="book_set-2-title" '
+ 'maxlength="100">'
+ '<input type="hidden" name="book_set-2-author" value="1" '
+ 'id="id_book_set-2-author">'
'<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>',
)
@@ -1103,10 +1149,12 @@ class ModelFormsetTest(TestCase):
self.assertEqual(len(formset.forms), 1)
self.assertHTMLEqual(
formset.forms[0].as_p(),
- '<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" '
- 'name="form-0-my_pk" maxlength="10"></p>'
+ '<p><label for="id_form-0-my_pk">My pk:</label>'
+ '<input id="id_form-0-my_pk" type="text" name="form-0-my_pk" '
+ 'maxlength="10"></p>'
'<p><label for="id_form-0-some_field">Some field:</label>'
- '<input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100"></p>',
+ '<input id="id_form-0-some_field" type="text" name="form-0-some_field" '
+ 'maxlength="100"></p>',
)
# Custom primary keys with ForeignKey, OneToOneField and AutoField ############
@@ -1121,16 +1169,22 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_owner_set-0-name">Name:</label>'
- '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" maxlength="100">'
- '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">'
- '<input type="hidden" name="owner_set-0-auto_id" id="id_owner_set-0-auto_id"></p>',
+ '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-0-place" value="1" '
+ 'id="id_owner_set-0-place">'
+ '<input type="hidden" name="owner_set-0-auto_id" '
+ 'id="id_owner_set-0-auto_id"></p>',
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_owner_set-1-name">Name:</label>'
- '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">'
- '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">'
- '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>',
+ '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-1-place" value="1" '
+ 'id="id_owner_set-1-place">'
+ '<input type="hidden" name="owner_set-1-auto_id" '
+ 'id="id_owner_set-1-auto_id"></p>',
)
data = {
@@ -1155,24 +1209,32 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_owner_set-0-name">Name:</label>'
- '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" value="Joe Perry" maxlength="100">'
- '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">'
- '<input type="hidden" name="owner_set-0-auto_id" value="%d" id="id_owner_set-0-auto_id"></p>'
- % owner1.auto_id,
+ '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" '
+ 'value="Joe Perry" maxlength="100">'
+ '<input type="hidden" name="owner_set-0-place" value="1" '
+ 'id="id_owner_set-0-place">'
+ '<input type="hidden" name="owner_set-0-auto_id" value="%d" '
+ 'id="id_owner_set-0-auto_id"></p>' % owner1.auto_id,
)
self.assertHTMLEqual(
formset.forms[1].as_p(),
'<p><label for="id_owner_set-1-name">Name:</label>'
- '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">'
- '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">'
- '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>',
+ '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-1-place" value="1" '
+ 'id="id_owner_set-1-place">'
+ '<input type="hidden" name="owner_set-1-auto_id" '
+ 'id="id_owner_set-1-auto_id"></p>',
)
self.assertHTMLEqual(
formset.forms[2].as_p(),
'<p><label for="id_owner_set-2-name">Name:</label>'
- '<input id="id_owner_set-2-name" type="text" name="owner_set-2-name" maxlength="100">'
- '<input type="hidden" name="owner_set-2-place" value="1" id="id_owner_set-2-place">'
- '<input type="hidden" name="owner_set-2-auto_id" id="id_owner_set-2-auto_id"></p>',
+ '<input id="id_owner_set-2-name" type="text" name="owner_set-2-name" '
+ 'maxlength="100">'
+ '<input type="hidden" name="owner_set-2-place" value="1" '
+ 'id="id_owner_set-2-place">'
+ '<input type="hidden" name="owner_set-2-auto_id" '
+ 'id="id_owner_set-2-auto_id"></p>',
)
data = {
@@ -1194,8 +1256,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(owner2.name, "Jack Berry")
self.assertEqual(owner2.place.name, "Giordanos")
- # Ensure a custom primary key that is a ForeignKey or OneToOneField get rendered for the user to choose.
-
+ # A custom primary key that is a ForeignKey or OneToOneField get
+ # rendered for the user to choose.
FormSet = modelformset_factory(OwnerProfile, fields="__all__")
formset = FormSet()
self.assertHTMLEqual(
@@ -1222,9 +1284,10 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_ownerprofile-0-age">Age:</label>'
- '<input type="number" name="ownerprofile-0-age" id="id_ownerprofile-0-age" min="0">'
- '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>'
- % owner1.auto_id,
+ '<input type="number" name="ownerprofile-0-age" '
+ 'id="id_ownerprofile-0-age" min="0">'
+ '<input type="hidden" name="ownerprofile-0-owner" value="%d" '
+ 'id="id_ownerprofile-0-owner"></p>' % owner1.auto_id,
)
data = {
@@ -1247,9 +1310,10 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_ownerprofile-0-age">Age:</label>'
- '<input type="number" name="ownerprofile-0-age" value="54" id="id_ownerprofile-0-age" min="0">'
- '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>'
- % owner1.auto_id,
+ '<input type="number" name="ownerprofile-0-age" value="54" '
+ 'id="id_ownerprofile-0-age" min="0">'
+ '<input type="hidden" name="ownerprofile-0-owner" value="%d" '
+ 'id="id_ownerprofile-0-owner"></p>' % owner1.auto_id,
)
data = {
@@ -1282,11 +1346,15 @@ class ModelFormsetTest(TestCase):
self.assertHTMLEqual(
formset.forms[0].as_p(),
'<p><label for="id_location_set-0-lat">Lat:</label>'
- '<input id="id_location_set-0-lat" type="text" name="location_set-0-lat" maxlength="100"></p>'
- '<p><label for="id_location_set-0-lon">Lon:</label> '
- '<input id="id_location_set-0-lon" type="text" name="location_set-0-lon" maxlength="100">'
- '<input type="hidden" name="location_set-0-place" value="1" id="id_location_set-0-place">'
- '<input type="hidden" name="location_set-0-id" id="id_location_set-0-id"></p>',
+ '<input id="id_location_set-0-lat" type="text" name="location_set-0-lat" '
+ 'maxlength="100"></p>'
+ '<p><label for="id_location_set-0-lon">Lon:</label>'
+ '<input id="id_location_set-0-lon" type="text" name="location_set-0-lon" '
+ 'maxlength="100">'
+ '<input type="hidden" name="location_set-0-place" value="1" '
+ 'id="id_location_set-0-place">'
+ '<input type="hidden" name="location_set-0-id" '
+ 'id="id_location_set-0-id"></p>',
)
def test_foreign_keys_in_parents(self):
@@ -1511,13 +1579,16 @@ class ModelFormsetTest(TestCase):
'<p><label for="id_membership_set-0-date_joined">Date joined:</label>'
'<input type="text" name="membership_set-0-date_joined" '
'value="__DATETIME__" id="id_membership_set-0-date_joined">'
- '<input type="hidden" name="initial-membership_set-0-date_joined" value="__DATETIME__" '
+ '<input type="hidden" name="initial-membership_set-0-date_joined" '
+ 'value="__DATETIME__" '
'id="initial-membership_set-0-id_membership_set-0-date_joined"></p>'
'<p><label for="id_membership_set-0-karma">Karma:</label>'
- '<input type="number" name="membership_set-0-karma" id="id_membership_set-0-karma">'
- '<input type="hidden" name="membership_set-0-person" value="%d" id="id_membership_set-0-person">'
- '<input type="hidden" name="membership_set-0-id" id="id_membership_set-0-id"></p>'
- % person.id,
+ '<input type="number" name="membership_set-0-karma" '
+ 'id="id_membership_set-0-karma">'
+ '<input type="hidden" name="membership_set-0-person" value="%d" '
+ 'id="id_membership_set-0-person">'
+ '<input type="hidden" name="membership_set-0-id" '
+ 'id="id_membership_set-0-id"></p>' % person.id,
)
# test for validation with callable defaults. Validations rely on hidden fields
@@ -1701,12 +1772,14 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for price and quantity, which must be unique."
+ "Please correct the duplicate data for price and quantity, which must "
+ "be unique."
],
)
- # Only the price field is specified, this should skip any unique checks since
- # the unique_together is not fulfilled. This will fail with a KeyError if broken.
+ # Only the price field is specified, this should skip any unique
+ # checks since the unique_together is not fulfilled. This will fail
+ # with a KeyError if broken.
FormSet = modelformset_factory(Price, fields=("price",), extra=2)
data = {
"form-TOTAL_FORMS": "2",
@@ -1765,7 +1838,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for title which must be unique for the date in posted."
+ "Please correct the duplicate data for title which must be unique for "
+ "the date in posted."
],
)
self.assertEqual(
@@ -1791,7 +1865,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for slug which must be unique for the year in posted."
+ "Please correct the duplicate data for slug which must be unique for "
+ "the year in posted."
],
)
@@ -1813,7 +1888,8 @@ class ModelFormsetTest(TestCase):
self.assertEqual(
formset._non_form_errors,
[
- "Please correct the duplicate data for subtitle which must be unique for the month in posted."
+ "Please correct the duplicate data for subtitle which must be unique "
+ "for the month in posted."
],
)
@@ -1885,7 +1961,8 @@ class ModelFormsetTest(TestCase):
[
{
"id": [
- "Select a valid choice. That choice is not one of the available choices."
+ "Select a valid choice. That choice is not one of the "
+ "available choices."
]
}
],
@@ -1906,7 +1983,8 @@ class ModelFormsetTest(TestCase):
[
{
"id": [
- "Select a valid choice. That choice is not one of the available choices."
+ "Select a valid choice. That choice is not one of the "
+ "available choices."
]
}
],
@@ -1996,7 +2074,8 @@ class TestModelFormsetOverridesTroughFormMeta(TestCase):
form = PoetFormSet.form()
self.assertHTMLEqual(
str(form["name"]),
- '<input id="id_name" maxlength="100" type="text" class="poet" name="name" required>',
+ '<input id="id_name" maxlength="100" type="text" class="poet" name="name" '
+ "required>",
)
def test_inlineformset_factory_widgets(self):
@@ -2007,7 +2086,8 @@ class TestModelFormsetOverridesTroughFormMeta(TestCase):
form = BookFormSet.form()
self.assertHTMLEqual(
str(form["title"]),
- '<input class="book" id="id_title" maxlength="100" name="title" type="text" required>',
+ '<input class="book" id="id_title" maxlength="100" name="title" '
+ 'type="text" required>',
)
def test_modelformset_factory_labels_overrides(self):
diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py
index 696235a948..7767ec48a2 100644
--- a/tests/model_formsets_regress/tests.py
+++ b/tests/model_formsets_regress/tests.py
@@ -24,7 +24,9 @@ from .models import (
class InlineFormsetTests(TestCase):
def test_formset_over_to_field(self):
- "A formset over a ForeignKey with a to_field can be saved. Regression for #10243"
+ """
+ A formset over a ForeignKey with a to_field can be saved.
+ """
Form = modelform_factory(User, fields="__all__")
FormSet = inlineformset_factory(User, UserSite, fields="__all__")
@@ -100,7 +102,9 @@ class InlineFormsetTests(TestCase):
self.fail("Errors found on formset:%s" % form_set.errors)
def test_formset_over_inherited_model(self):
- "A formset over a ForeignKey with a to_field can be saved. Regression for #11120"
+ """
+ A formset over a ForeignKey with a to_field can be saved.
+ """
Form = modelform_factory(Restaurant, fields="__all__")
FormSet = inlineformset_factory(Restaurant, Manager, fields="__all__")
@@ -418,7 +422,7 @@ class BaseCustomDeleteFormSet(BaseFormSet):
class FormfieldShouldDeleteFormTests(TestCase):
"""
- Regression for #14099: BaseModelFormSet should use ModelFormSet method _should_delete_form
+ BaseModelFormSet should use ModelFormSet method _should_delete_form.
"""
class BaseCustomDeleteModelFormSet(BaseModelFormSet, BaseCustomDeleteFormSet):
diff --git a/tests/model_regress/tests.py b/tests/model_regress/tests.py
index eec8fa36eb..10dfbabcd9 100644
--- a/tests/model_regress/tests.py
+++ b/tests/model_regress/tests.py
@@ -217,7 +217,7 @@ class ModelTests(TestCase):
def test_chained_fks(self):
"""
- Regression for #18432: Chained foreign keys with to_field produce incorrect query
+ Chained foreign keys with to_field produce incorrect query.
"""
m1 = Model1.objects.create(pkey=1000)
diff --git a/tests/modeladmin/test_checks.py b/tests/modeladmin/test_checks.py
index c74c35f76f..e4ad0636a6 100644
--- a/tests/modeladmin/test_checks.py
+++ b/tests/modeladmin/test_checks.py
@@ -413,7 +413,8 @@ class RadioFieldsCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or admin.VERTICAL.",
+ "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or "
+ "admin.VERTICAL.",
"admin.E024",
)
@@ -466,8 +467,9 @@ class PrepopulatedFieldsCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'prepopulated_fields[\"slug\"][0]' refers to 'non_existent_field', "
- "which is not a field of 'modeladmin.ValidationTestModel'.",
+ "The value of 'prepopulated_fields[\"slug\"][0]' refers to "
+ "'non_existent_field', which is not a field of "
+ "'modeladmin.ValidationTestModel'.",
"admin.E030",
)
@@ -496,8 +498,9 @@ class PrepopulatedFieldsCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'prepopulated_fields' refers to 'best_friend', which must not be "
- "a DateTimeField, a ForeignKey, a OneToOneField, or a ManyToManyField.",
+ "The value of 'prepopulated_fields' refers to 'best_friend', which must "
+ "not be a DateTimeField, a ForeignKey, a OneToOneField, or a "
+ "ManyToManyField.",
"admin.E028",
)
@@ -606,7 +609,8 @@ class ListDisplayLinksCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "The value of 'list_display_links[0]' refers to 'name', which is not defined in 'list_display'.",
+ "The value of 'list_display_links[0]' refers to 'name', which is not "
+ "defined in 'list_display'.",
"admin.E111",
)
@@ -1170,7 +1174,8 @@ class FkNameCheckTests(CheckTestCase):
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
- "'modeladmin.ValidationTestInlineModel' has no field named 'non_existent_field'.",
+ "'modeladmin.ValidationTestInlineModel' has no field named "
+ "'non_existent_field'.",
"admin.E202",
invalid_obj=ValidationTestInline,
)
diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py
index 3f5548d761..2dc894b858 100644
--- a/tests/multiple_database/tests.py
+++ b/tests/multiple_database/tests.py
@@ -216,7 +216,8 @@ class QueryTestCase(TestCase):
dive = Book.objects.using("other").get(title="Dive into Python")
mark = Person.objects.using("other").get(name="Mark Pilgrim")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(
list(dive.authors.all().values_list("name", flat=True)), ["Mark Pilgrim"]
)
@@ -597,7 +598,8 @@ class QueryTestCase(TestCase):
chris = Person.objects.using("other").get(name="Chris Mills")
dive = Book.objects.using("other").get(title="Dive into Python")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(
list(chris.edited.values_list("title", flat=True)), ["Dive into Python"]
)
@@ -743,7 +745,10 @@ class QueryTestCase(TestCase):
marty.edited.add(dive)
def test_foreign_key_deletion(self):
- "Cascaded deletions of Foreign Key relations issue queries on the right database"
+ """
+ Cascaded deletions of Foreign Key relations issue queries on the right
+ database.
+ """
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Pet.objects.using("other").create(name="Fido", owner=mark)
@@ -843,7 +848,8 @@ class QueryTestCase(TestCase):
alice_profile = UserProfile.objects.using("default").get(flavor="chocolate")
bob_profile = UserProfile.objects.using("other").get(flavor="crunchy frog")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(alice_profile.user.username, "alice")
self.assertEqual(bob_profile.user.username, "bob")
@@ -976,7 +982,8 @@ class QueryTestCase(TestCase):
# Reget the objects to clear caches
dive = Book.objects.using("other").get(title="Dive into Python")
- # Retrieve related object by descriptor. Related objects should be database-bound
+ # Retrieve related object by descriptor. Related objects should be
+ # database-bound.
self.assertEqual(
list(dive.reviews.all().values_list("source", flat=True)), ["Python Weekly"]
)
@@ -1090,7 +1097,10 @@ class QueryTestCase(TestCase):
)
def test_generic_key_cross_database_protection(self):
- "Operations that involve sharing generic key objects across databases raise an error"
+ """
+ Operations that involve sharing generic key objects across databases
+ raise an error.
+ """
# Create a book and author on the default database
pro = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
@@ -1171,7 +1181,10 @@ class QueryTestCase(TestCase):
)
def test_generic_key_deletion(self):
- "Cascaded deletions of Generic Key relations issue queries on the right database"
+ """
+ Cascaded deletions of Generic Key relations issue queries on the right
+ database.
+ """
dive = Book.objects.using("other").create(
title="Dive into Python", published=datetime.date(2009, 5, 4)
)
@@ -1223,7 +1236,10 @@ class QueryTestCase(TestCase):
self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
def test_select_related(self):
- "Database assignment is retained if an object is retrieved with select_related()"
+ """
+ Database assignment is retained if an object is retrieved with
+ select_related().
+ """
# Create a book and author on the other database
mark = Person.objects.using("other").create(name="Mark Pilgrim")
Book.objects.using("other").create(
@@ -1465,7 +1481,10 @@ class RouterTestCase(TestCase):
published=datetime.date(2009, 5, 4),
)
# Set a foreign key set with an object from a different database
- msg = "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the object first."
+ msg = (
+ "<Book: Dive into Python> instance isn't saved. Use bulk=False or save the "
+ "object first."
+ )
with self.assertRaisesMessage(ValueError, msg):
marty.edited.set([dive])
@@ -1508,7 +1527,8 @@ class RouterTestCase(TestCase):
# Set a foreign key set with an object from a different database
marty.edited.set([pro, dive], bulk=False)
- # Assignment implies a save, so database assignments of original objects have changed...
+ # Assignment implies a save, so database assignments of original
+ # objects have changed...
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "default")
@@ -1524,7 +1544,8 @@ class RouterTestCase(TestCase):
# Add to a foreign key set with an object from a different database
marty.edited.add(dive, bulk=False)
- # Add implies a save, so database assignments of original objects have changed...
+ # Add implies a save, so database assignments of original objects have
+ # changed...
self.assertEqual(marty._state.db, "default")
self.assertEqual(pro._state.db, "default")
self.assertEqual(dive._state.db, "default")
@@ -1813,7 +1834,10 @@ class RouterTestCase(TestCase):
self.assertEqual(marty.book_set.db_manager("default").all().db, "default")
def test_foreign_key_managers(self):
- "FK reverse relations are represented by managers, and can be controlled like managers"
+ """
+ FK reverse relations are represented by managers, and can be controlled
+ like managers.
+ """
marty = Person.objects.using("other").create(pk=1, name="Marty Alchin")
Book.objects.using("other").create(
pk=1,
@@ -1826,7 +1850,10 @@ class RouterTestCase(TestCase):
self.assertEqual(marty.edited.db_manager("default").all().db, "default")
def test_generic_key_managers(self):
- "Generic key relations are represented by managers, and can be controlled like managers"
+ """
+ Generic key relations are represented by managers, and can be
+ controlled like managers.
+ """
pro = Book.objects.using("other").create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
diff --git a/tests/null_queries/tests.py b/tests/null_queries/tests.py
index f0aad73057..4c5c3bbe5c 100644
--- a/tests/null_queries/tests.py
+++ b/tests/null_queries/tests.py
@@ -33,7 +33,10 @@ class NullQueriesTests(TestCase):
)
# Valid query, but fails because foo isn't a keyword
- msg = "Cannot resolve keyword 'foo' into field. Choices are: choice, id, poll, poll_id"
+ msg = (
+ "Cannot resolve keyword 'foo' into field. Choices are: choice, id, poll, "
+ "poll_id"
+ )
with self.assertRaisesMessage(FieldError, msg):
Choice.objects.filter(foo__exact=None)
diff --git a/tests/one_to_one/tests.py b/tests/one_to_one/tests.py
index 885e753567..40dcd45a77 100644
--- a/tests/one_to_one/tests.py
+++ b/tests/one_to_one/tests.py
@@ -158,7 +158,10 @@ class OneToOneTests(TestCase):
place = Place(name="User", address="London")
with self.assertRaises(Restaurant.DoesNotExist):
place.restaurant
- msg = "save() prohibited to prevent data loss due to unsaved related object 'place'."
+ msg = (
+ "save() prohibited to prevent data loss due to unsaved related object "
+ "'place'."
+ )
with self.assertRaisesMessage(ValueError, msg):
Restaurant.objects.create(
place=place, serves_hot_dogs=True, serves_pizza=False
@@ -445,7 +448,10 @@ class OneToOneTests(TestCase):
p.undergroundbar = b
# However saving the object is not allowed.
- msg = "save() prohibited to prevent data loss due to unsaved related object 'place'."
+ msg = (
+ "save() prohibited to prevent data loss due to unsaved related object "
+ "'place'."
+ )
with self.assertNumQueries(0):
with self.assertRaisesMessage(ValueError, msg):
b.save()
diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py
index 79d60530fa..8444bd3dd0 100644
--- a/tests/pagination/tests.py
+++ b/tests/pagination/tests.py
@@ -502,8 +502,9 @@ class ModelPaginationTests(TestCase):
paginator = Paginator(Article.objects.order_by("id"), 5)
p = paginator.page(1)
- # Make sure object_list queryset is not evaluated by an invalid __getitem__ call.
- # (this happens from the template engine when using eg: {% page_obj.has_previous %})
+ # object_list queryset is not evaluated by an invalid __getitem__ call.
+ # (this happens from the template engine when using e.g.:
+ # {% page_obj.has_previous %}).
self.assertIsNone(p.object_list._result_cache)
msg = "Page indices must be integers or slices, not str."
with self.assertRaisesMessage(TypeError, msg):
diff --git a/tests/postgres_tests/test_array.py b/tests/postgres_tests/test_array.py
index 512972b8e6..28d5924b9d 100644
--- a/tests/postgres_tests/test_array.py
+++ b/tests/postgres_tests/test_array.py
@@ -540,11 +540,17 @@ class TestQuerying(PostgreSQLTestCase):
)
def test_unsupported_lookup(self):
- msg = "Unsupported lookup '0_bar' for ArrayField or join on the field not permitted."
+ msg = (
+ "Unsupported lookup '0_bar' for ArrayField or join on the field not "
+ "permitted."
+ )
with self.assertRaisesMessage(FieldError, msg):
list(NullableIntegerArrayModel.objects.filter(field__0_bar=[2]))
- msg = "Unsupported lookup '0bar' for ArrayField or join on the field not permitted."
+ msg = (
+ "Unsupported lookup '0bar' for ArrayField or join on the field not "
+ "permitted."
+ )
with self.assertRaisesMessage(FieldError, msg):
list(NullableIntegerArrayModel.objects.filter(field__0bar=[2]))
@@ -881,7 +887,10 @@ class TestMigrations(TransactionTestCase):
class TestSerialization(PostgreSQLSimpleTestCase):
- test_data = '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, "model": "postgres_tests.integerarraymodel", "pk": null}]'
+ test_data = (
+ '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, '
+ '"model": "postgres_tests.integerarraymodel", "pk": null}]'
+ )
def test_dumping(self):
instance = IntegerArrayModel(field=[1, 2, None])
@@ -937,7 +946,8 @@ class TestValidation(PostgreSQLSimpleTestCase):
exception = cm.exception.error_list[0]
self.assertEqual(
exception.message,
- "Item 1 in the array did not validate: Ensure this value has at most 2 characters (it has 3).",
+ "Item 1 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 3).",
)
self.assertEqual(exception.code, "item_invalid")
self.assertEqual(
@@ -956,7 +966,8 @@ class TestValidation(PostgreSQLSimpleTestCase):
exception = cm.exception.error_list[0]
self.assertEqual(
exception.message,
- "Item 1 in the array did not validate: Ensure this value is greater than or equal to 1.",
+ "Item 1 in the array did not validate: Ensure this value is greater than "
+ "or equal to 1.",
)
self.assertEqual(exception.code, "item_invalid")
self.assertEqual(
@@ -997,7 +1008,8 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
first_error = errors[0]
self.assertEqual(
first_error.message,
- "Item 1 in the array did not validate: Ensure this value has at most 2 characters (it has 3).",
+ "Item 1 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 3).",
)
self.assertEqual(first_error.code, "item_invalid")
self.assertEqual(
@@ -1007,7 +1019,8 @@ class TestSimpleFormField(PostgreSQLSimpleTestCase):
second_error = errors[1]
self.assertEqual(
second_error.message,
- "Item 3 in the array did not validate: Ensure this value has at most 2 characters (it has 4).",
+ "Item 3 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 4).",
)
self.assertEqual(second_error.code, "item_invalid")
self.assertEqual(
@@ -1169,7 +1182,10 @@ class TestSplitFormField(PostgreSQLSimpleTestCase):
)
def test_invalid_integer(self):
- msg = "Item 2 in the array did not validate: Ensure this value is less than or equal to 100."
+ msg = (
+ "Item 2 in the array did not validate: Ensure this value is less than or "
+ "equal to 100."
+ )
with self.assertRaisesMessage(exceptions.ValidationError, msg):
SplitArrayField(forms.IntegerField(max_value=100), size=2).clean([0, 101])
@@ -1200,8 +1216,10 @@ class TestSplitFormField(PostgreSQLSimpleTestCase):
self.assertEqual(
cm.exception.messages,
[
- "Item 1 in the array did not validate: Ensure this value has at most 2 characters (it has 3).",
- "Item 3 in the array did not validate: Ensure this value has at most 2 characters (it has 4).",
+ "Item 1 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 3).",
+ "Item 3 in the array did not validate: Ensure this value has at most 2 "
+ "characters (it has 4).",
],
)
diff --git a/tests/postgres_tests/test_constraints.py b/tests/postgres_tests/test_constraints.py
index 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):
</th><td>
<input type="text" name="datetime_field_0" id="id_datetime_field_0">
<input type="text" name="datetime_field_1" id="id_datetime_field_1">
- <input type="hidden" name="initial-datetime_field_0" id="initial-id_datetime_field_0">
- <input type="hidden" name="initial-datetime_field_1" id="initial-id_datetime_field_1">
+ <input type="hidden" name="initial-datetime_field_0"
+ id="initial-id_datetime_field_0">
+ <input type="hidden" name="initial-datetime_field_1"
+ id="initial-id_datetime_field_1">
</td></tr>
""",
)
@@ -751,10 +754,10 @@ class TestFormField(PostgreSQLSimpleTestCase):
value="2010-01-01 11:13:00" id="id_datetime_field_0">
<input type="text" name="datetime_field_1"
value="2020-12-12 16:59:00" id="id_datetime_field_1">
- <input type="hidden" name="initial-datetime_field_0" value="2010-01-01 11:13:00"
- id="initial-id_datetime_field_0">
- <input type="hidden" name="initial-datetime_field_1" value="2020-12-12 16:59:00"
- id="initial-id_datetime_field_1"></td></tr>
+ <input type="hidden" name="initial-datetime_field_0"
+ value="2010-01-01 11:13:00" id="initial-id_datetime_field_0">
+ <input type="hidden" name="initial-datetime_field_1"
+ value="2020-12-12 16:59:00" id="initial-id_datetime_field_1"></td></tr>
""",
)
@@ -1074,11 +1077,13 @@ class TestWidget(PostgreSQLSimpleTestCase):
f = pg_forms.ranges.DateTimeRangeField()
self.assertHTMLEqual(
f.widget.render("datetimerange", ""),
- '<input type="text" name="datetimerange_0"><input type="text" name="datetimerange_1">',
+ '<input type="text" name="datetimerange_0">'
+ '<input type="text" name="datetimerange_1">',
)
self.assertHTMLEqual(
f.widget.render("datetimerange", None),
- '<input type="text" name="datetimerange_0"><input type="text" name="datetimerange_1">',
+ '<input type="text" name="datetimerange_0">'
+ '<input type="text" name="datetimerange_1">',
)
dt_range = DateTimeTZRange(
datetime.datetime(2006, 1, 10, 7, 30), datetime.datetime(2006, 2, 12, 9, 50)
diff --git a/tests/prefetch_related/test_uuid.py b/tests/prefetch_related/test_uuid.py
index 55332b7b5d..f22b2158a5 100644
--- a/tests/prefetch_related/test_uuid.py
+++ b/tests/prefetch_related/test_uuid.py
@@ -76,7 +76,8 @@ class UUIDPrefetchRelatedLookups(TestCase):
self.assertEqual("Racoon", spooky.fleas_hosted.all()[0].current_room.name)
def test_from_uuid_pk_lookup_integer_pk2_uuid_pk2(self):
- # From uuid-pk model, prefetch <integer-pk model>.<integer-pk model>.<uuid-pk model>.<uuid-pk model>:
+ # From uuid-pk model, prefetch
+ # <integer-pk model>.<integer-pk model>.<uuid-pk model>.<uuid-pk model>:
with self.assertNumQueries(5):
spooky = Pet.objects.prefetch_related("people__houses__rooms__fleas").get(
name="Spooky"
@@ -104,7 +105,8 @@ class UUIDPrefetchRelatedLookups(TestCase):
self.assertEqual(3, len(redwood.rooms.all()[0].fleas.all()))
def test_from_integer_pk_lookup_integer_pk_uuid_pk_uuid_pk(self):
- # From integer-pk model, prefetch <integer-pk model>.<uuid-pk model>.<uuid-pk model>:
+ # From integer-pk model, prefetch
+ # <integer-pk model>.<uuid-pk model>.<uuid-pk model>:
with self.assertNumQueries(4):
redwood = House.objects.prefetch_related("rooms__fleas__pets_visited").get(
name="Redwood"
diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py
index 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 <NamedCategory: Other> cannot be used in an ORM query."
+ msg = (
+ "Unsaved model instance <NamedCategory: Other> cannot be used in an ORM "
+ "query."
+ )
with self.assertRaisesMessage(ValueError, msg):
Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category)
@@ -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 version="1.0" standalone="no"?><!DOCTYPE example SYSTEM "http://example.com/example.dtd">'
+ xml = (
+ '<?xml version="1.0" standalone="no"?>'
+ '<!DOCTYPE example SYSTEM "http://example.com/example.dtd">'
+ )
with self.assertRaises(DTDForbidden):
next(serializers.deserialize("xml", xml))
@@ -107,4 +110,4 @@ class XmlSerializerTransactionTestCase(
</object>
<object pk="1" model="serializers.category">
<field type="CharField" name="name">Reference</field></object>
-</django-objects>"""
+</django-objects>""" # NOQA
diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py
index 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 += "<url><loc>%s/testmodel/%s/</loc></url>" % (self.base_url, pk)
expected_content = (
- """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-%s
-</urlset>
-"""
- % expected
- )
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "%s\n"
+ "</urlset>"
+ ) % expected
self.assertXMLEqual(response.content.decode(), expected_content)
def test_generic_sitemap_lastmod(self):
test_model = TestModel.objects.first()
TestModel.objects.update(lastmod=datetime(2013, 3, 13, 10, 0, 0))
response = self.client.get("/generic-lastmod/sitemap.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/testmodel/%s/</loc><lastmod>2013-03-13</lastmod></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/testmodel/%s/</loc><lastmod>2013-03-13</lastmod></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
test_model.pk,
)
diff --git a/tests/sitemaps_tests/test_http.py b/tests/sitemaps_tests/test_http.py
index 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 = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
date.today(),
)
@@ -113,11 +116,14 @@ class HTTPSitemapTests(SitemapTestsBase):
def test_simple_sitemap(self):
"A simple sitemap can be rendered"
response = self.client.get("/simple/sitemap.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
date.today(),
)
@@ -256,13 +262,13 @@ class HTTPSitemapTests(SitemapTestsBase):
# doesn't raise an exception.
response = self.client.get("/simple/sitemap.xml")
expected_content = (
- """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>http://testserver/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-"""
- % date.today()
- )
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>http://testserver/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % date.today()
self.assertXMLEqual(response.content.decode(), expected_content)
@ignore_warnings(category=RemovedInDjango50Warning)
@@ -335,13 +341,15 @@ class HTTPSitemapTests(SitemapTestsBase):
"""
with self.assertNoLogs("django.template", "DEBUG"):
response = self.client.get("/simple/i18n.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>{0}/en/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url><url><loc>{0}/pt/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""".format(
- self.base_url, self.i18n_model.pk
- )
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>{0}/en/i18n/testmodel/{1}/</loc><changefreq>never</changefreq>"
+ "<priority>0.5</priority></url><url><loc>{0}/pt/i18n/testmodel/{1}/</loc>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ).format(self.base_url, self.i18n_model.pk)
self.assertXMLEqual(response.content.decode(), expected_content)
@override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese")))
@@ -363,11 +371,13 @@ class HTTPSitemapTests(SitemapTestsBase):
""".replace(
"\n", ""
)
- expected_content = f"""<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-{expected_urls}
-</urlset>
-"""
+ expected_content = (
+ f'<?xml version="1.0" encoding="UTF-8"?>\n'
+ f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ f"{expected_urls}\n"
+ f"</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
@override_settings(
@@ -391,11 +401,13 @@ class HTTPSitemapTests(SitemapTestsBase):
""".replace(
"\n", ""
)
- expected_content = f"""<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-{expected_urls}
-</urlset>
-"""
+ expected_content = (
+ f'<?xml version="1.0" encoding="UTF-8"?>\n'
+ f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ f"{expected_urls}\n"
+ f"</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
@override_settings(LANGUAGES=(("en", "English"), ("pt", "Portuguese")))
@@ -419,19 +431,23 @@ class HTTPSitemapTests(SitemapTestsBase):
""".replace(
"\n", ""
)
- expected_content = f"""<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-{expected_urls}
-</urlset>
-"""
+ expected_content = (
+ f'<?xml version="1.0" encoding="UTF-8"?>\n'
+ f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ f'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ f"{expected_urls}\n"
+ f"</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
def test_sitemap_without_entries(self):
response = self.client.get("/sitemap-without-entries/sitemap.xml")
- expected_content = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-
-</urlset>"""
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n\n'
+ "</urlset>"
+ )
self.assertXMLEqual(response.content.decode(), expected_content)
def test_callable_sitemod_partial(self):
@@ -448,11 +464,15 @@ class HTTPSitemapTests(SitemapTestsBase):
<sitemap><loc>http://example.com/simple/sitemap-callable-lastmod.xml</loc></sitemap>
</sitemapindex>
"""
- expected_content_sitemap = """<?xml version="1.0" encoding="UTF-8"?>
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
- <url><loc>http://example.com/location/</loc><lastmod>2013-03-13</lastmod></url><url><loc>http://example.com/location/</loc></url>
- </urlset>
- """
+ expected_content_sitemap = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>http://example.com/location/</loc>"
+ "<lastmod>2013-03-13</lastmod></url><url>"
+ "<loc>http://example.com/location/</loc></url>\n"
+ "</urlset>"
+ )
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):
<sitemap><loc>http://example.com/simple/sitemap-callable-lastmod.xml</loc><lastmod>2014-03-13T10:00:00</lastmod></sitemap>
</sitemapindex>
"""
- expected_content_sitemap = """<?xml version="1.0" encoding="UTF-8"?>
- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
- <url><loc>http://example.com/location/</loc><lastmod>2013-03-13</lastmod></url><url><loc>http://example.com/location/</loc><lastmod>2014-03-13</lastmod></url>
- </urlset>
- """
+ expected_content_sitemap = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>http://example.com/location/</loc>"
+ "<lastmod>2013-03-13</lastmod></url>"
+ "<url><loc>http://example.com/location/</loc>"
+ "<lastmod>2014-03-13</lastmod></url>\n"
+ "</urlset>"
+ )
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 = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url,
date.today(),
)
@@ -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 = """<?xml version="1.0" encoding="UTF-8"?>
-<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">
-<url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url>
-</urlset>
-""" % (
+ expected_content = (
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
+ '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" '
+ 'xmlns:xhtml="http://www.w3.org/1999/xhtml">\n'
+ "<url><loc>%s/location/</loc><lastmod>%s</lastmod>"
+ "<changefreq>never</changefreq><priority>0.5</priority></url>\n"
+ "</urlset>"
+ ) % (
self.base_url.replace("http://", "https://"),
date.today(),
)
diff --git a/tests/sitemaps_tests/test_utils.py b/tests/sitemaps_tests/test_utils.py
index 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,
'<script id="test_id" type="application/json">'
- '{"a": "testing\\r\\njson \'string\\" \\u003Cb\\u003Eescaping\\u003C/b\\u003E"}'
+ '{"a": "testing\\r\\njson \'string\\" '
+ '\\u003Cb\\u003Eescaping\\u003C/b\\u003E"}'
"</script>",
)
diff --git a/tests/template_tests/filter_tests/test_length_is.py b/tests/template_tests/filter_tests/test_length_is.py
index 1cc760c8a2..cbda46e5b1 100644
--- a/tests/template_tests/filter_tests/test_length_is.py
+++ b/tests/template_tests/filter_tests/test_length_is.py
@@ -14,7 +14,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is02": '{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ "length_is02": (
+ '{% if some_list|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ )
}
)
def test_length_is02(self):
@@ -30,7 +32,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is04": '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ "length_is04": (
+ '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ )
}
)
def test_length_is04(self):
@@ -39,7 +43,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is05": '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ "length_is05": (
+ '{% if mystring|length_is:"4" %}Four{% else %}Not Four{% endif %}'
+ )
}
)
def test_length_is05(self):
@@ -48,7 +54,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is06": "{% with var|length as my_length %}{{ my_length }}{% endwith %}"
+ "length_is06": (
+ "{% with var|length as my_length %}{{ my_length }}{% endwith %}"
+ )
}
)
def test_length_is06(self):
@@ -58,7 +66,9 @@ class LengthIsTests(SimpleTestCase):
# Boolean return value from length_is should not be coerced to a string
@setup(
{
- "length_is07": '{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}'
+ "length_is07": (
+ '{% if "X"|length_is:0 %}Length is 0{% else %}Length not 0{% endif %}'
+ )
}
)
def test_length_is07(self):
@@ -67,7 +77,9 @@ class LengthIsTests(SimpleTestCase):
@setup(
{
- "length_is08": '{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}'
+ "length_is08": (
+ '{% if "X"|length_is:1 %}Length is 1{% else %}Length not 1{% endif %}'
+ )
}
)
def test_length_is08(self):
diff --git a/tests/template_tests/filter_tests/test_linebreaks.py b/tests/template_tests/filter_tests/test_linebreaks.py
index ce0f082466..10c8a92d6a 100644
--- a/tests/template_tests/filter_tests/test_linebreaks.py
+++ b/tests/template_tests/filter_tests/test_linebreaks.py
@@ -21,7 +21,10 @@ class LinebreaksTests(SimpleTestCase):
@setup(
{
- "linebreaks02": "{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}"
+ "linebreaks02": (
+ "{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}"
+ "{% endautoescape %}"
+ )
}
)
def test_linebreaks02(self):
diff --git a/tests/template_tests/filter_tests/test_linebreaksbr.py b/tests/template_tests/filter_tests/test_linebreaksbr.py
index fa4cff209b..aa6505a47a 100644
--- a/tests/template_tests/filter_tests/test_linebreaksbr.py
+++ b/tests/template_tests/filter_tests/test_linebreaksbr.py
@@ -20,7 +20,10 @@ class LinebreaksbrTests(SimpleTestCase):
@setup(
{
- "linebreaksbr02": "{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}"
+ "linebreaksbr02": (
+ "{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}"
+ "{% endautoescape %}"
+ )
}
)
def test_linebreaksbr02(self):
diff --git a/tests/template_tests/filter_tests/test_linenumbers.py b/tests/template_tests/filter_tests/test_linenumbers.py
index 82fae4f889..8b1f8ef8af 100644
--- a/tests/template_tests/filter_tests/test_linenumbers.py
+++ b/tests/template_tests/filter_tests/test_linenumbers.py
@@ -23,7 +23,10 @@ class LinenumbersTests(SimpleTestCase):
@setup(
{
- "linenumbers02": "{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}"
+ "linenumbers02": (
+ "{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}"
+ "{% endautoescape %}"
+ )
}
)
def test_linenumbers02(self):
diff --git a/tests/template_tests/filter_tests/test_ljust.py b/tests/template_tests/filter_tests/test_ljust.py
index 9ea5b23862..f07a3c88f7 100644
--- a/tests/template_tests/filter_tests/test_ljust.py
+++ b/tests/template_tests/filter_tests/test_ljust.py
@@ -8,7 +8,10 @@ from ..utils import setup
class LjustTests(SimpleTestCase):
@setup(
{
- "ljust01": '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.{% endautoescape %}'
+ "ljust01": (
+ '{% autoescape off %}.{{ a|ljust:"5" }}. .{{ b|ljust:"5" }}.'
+ "{% endautoescape %}"
+ )
}
)
def test_ljust01(self):
diff --git a/tests/template_tests/filter_tests/test_lower.py b/tests/template_tests/filter_tests/test_lower.py
index 29845663dd..ae30094d69 100644
--- a/tests/template_tests/filter_tests/test_lower.py
+++ b/tests/template_tests/filter_tests/test_lower.py
@@ -8,7 +8,9 @@ from ..utils import setup
class LowerTests(SimpleTestCase):
@setup(
{
- "lower01": "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}"
+ "lower01": (
+ "{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}"
+ )
}
)
def test_lower01(self):
diff --git a/tests/template_tests/filter_tests/test_make_list.py b/tests/template_tests/filter_tests/test_make_list.py
index 34901d2ff2..ddf8dbc7e7 100644
--- a/tests/template_tests/filter_tests/test_make_list.py
+++ b/tests/template_tests/filter_tests/test_make_list.py
@@ -23,7 +23,10 @@ class MakeListTests(SimpleTestCase):
@setup(
{
- "make_list03": '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}'
+ "make_list03": (
+ '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}'
+ "{% endautoescape %}"
+ )
}
)
def test_make_list03(self):
diff --git a/tests/template_tests/filter_tests/test_phone2numeric.py b/tests/template_tests/filter_tests/test_phone2numeric.py
index 8165fba9da..ee3805b70d 100644
--- a/tests/template_tests/filter_tests/test_phone2numeric.py
+++ b/tests/template_tests/filter_tests/test_phone2numeric.py
@@ -16,7 +16,10 @@ class Phone2numericTests(SimpleTestCase):
@setup(
{
- "phone2numeric02": "{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}"
+ "phone2numeric02": (
+ "{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}"
+ "{% endautoescape %}"
+ )
}
)
def test_phone2numeric02(self):
diff --git a/tests/template_tests/filter_tests/test_random.py b/tests/template_tests/filter_tests/test_random.py
index a419128971..785f2d6a2f 100644
--- a/tests/template_tests/filter_tests/test_random.py
+++ b/tests/template_tests/filter_tests/test_random.py
@@ -14,7 +14,9 @@ class RandomTests(SimpleTestCase):
@setup(
{
- "random02": "{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}"
+ "random02": (
+ "{% autoescape off %}{{ a|random }} {{ b|random }}{% endautoescape %}"
+ )
}
)
def test_random02(self):
diff --git a/tests/template_tests/filter_tests/test_rjust.py b/tests/template_tests/filter_tests/test_rjust.py
index b7dde7514a..2d12dfccf4 100644
--- a/tests/template_tests/filter_tests/test_rjust.py
+++ b/tests/template_tests/filter_tests/test_rjust.py
@@ -8,7 +8,10 @@ from ..utils import setup
class RjustTests(SimpleTestCase):
@setup(
{
- "rjust01": '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'
+ "rjust01": (
+ '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'
+ "{% endautoescape %}"
+ )
}
)
def test_rjust01(self):
diff --git a/tests/template_tests/filter_tests/test_safeseq.py b/tests/template_tests/filter_tests/test_safeseq.py
index 4a537551f9..e9b3feb0b3 100644
--- a/tests/template_tests/filter_tests/test_safeseq.py
+++ b/tests/template_tests/filter_tests/test_safeseq.py
@@ -11,7 +11,10 @@ class SafeseqTests(SimpleTestCase):
@setup(
{
- "safeseq02": '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}'
+ "safeseq02": (
+ '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}'
+ "{% endautoescape %}"
+ )
}
)
def test_safeseq02(self):
diff --git a/tests/template_tests/filter_tests/test_slice.py b/tests/template_tests/filter_tests/test_slice.py
index f1c91a5008..5a5dd6b155 100644
--- a/tests/template_tests/filter_tests/test_slice.py
+++ b/tests/template_tests/filter_tests/test_slice.py
@@ -15,7 +15,10 @@ class SliceTests(SimpleTestCase):
@setup(
{
- "slice02": '{% autoescape off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}{% endautoescape %}'
+ "slice02": (
+ '{% autoescape off %}{{ a|slice:"1:3" }} {{ b|slice:"1:3" }}'
+ "{% endautoescape %}"
+ )
}
)
def test_slice02(self):
diff --git a/tests/template_tests/filter_tests/test_slugify.py b/tests/template_tests/filter_tests/test_slugify.py
index e0e8a52da9..7bb18c5c89 100644
--- a/tests/template_tests/filter_tests/test_slugify.py
+++ b/tests/template_tests/filter_tests/test_slugify.py
@@ -14,7 +14,9 @@ class SlugifyTests(SimpleTestCase):
@setup(
{
- "slugify01": "{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}"
+ "slugify01": (
+ "{% autoescape off %}{{ a|slugify }} {{ b|slugify }}{% endautoescape %}"
+ )
}
)
def test_slugify01(self):
diff --git a/tests/template_tests/filter_tests/test_stringformat.py b/tests/template_tests/filter_tests/test_stringformat.py
index e8f06ac4a0..075906aecb 100644
--- a/tests/template_tests/filter_tests/test_stringformat.py
+++ b/tests/template_tests/filter_tests/test_stringformat.py
@@ -13,7 +13,10 @@ class StringformatTests(SimpleTestCase):
@setup(
{
- "stringformat01": '{% autoescape off %}.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.{% endautoescape %}'
+ "stringformat01": (
+ '{% autoescape off %}.{{ a|stringformat:"5s" }}. .'
+ '{{ b|stringformat:"5s" }}.{% endautoescape %}'
+ )
}
)
def test_stringformat01(self):
diff --git a/tests/template_tests/filter_tests/test_striptags.py b/tests/template_tests/filter_tests/test_striptags.py
index 7b142f5379..235a35b43e 100644
--- a/tests/template_tests/filter_tests/test_striptags.py
+++ b/tests/template_tests/filter_tests/test_striptags.py
@@ -20,7 +20,10 @@ class StriptagsTests(SimpleTestCase):
@setup(
{
- "striptags02": "{% autoescape off %}{{ a|striptags }} {{ b|striptags }}{% endautoescape %}"
+ "striptags02": (
+ "{% autoescape off %}{{ a|striptags }} {{ b|striptags }}"
+ "{% endautoescape %}"
+ )
}
)
def test_striptags02(self):
@@ -38,7 +41,8 @@ class FunctionTests(SimpleTestCase):
def test_strip(self):
self.assertEqual(
striptags(
- 'some <b>html</b> with <script>alert("You smell")</script> disallowed <img /> tags'
+ 'some <b>html</b> with <script>alert("You smell")</script> disallowed '
+ "<img /> tags"
),
'some html with alert("You smell") disallowed tags',
)
@@ -50,7 +54,8 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
striptags(
lazystr(
- 'some <b>html</b> with <script>alert("Hello")</script> disallowed <img /> tags'
+ 'some <b>html</b> with <script>alert("Hello")</script> disallowed '
+ "<img /> tags"
)
),
'some html with alert("Hello") disallowed tags',
diff --git a/tests/template_tests/filter_tests/test_truncatewords.py b/tests/template_tests/filter_tests/test_truncatewords.py
index b3457205ac..e737a1e3f9 100644
--- a/tests/template_tests/filter_tests/test_truncatewords.py
+++ b/tests/template_tests/filter_tests/test_truncatewords.py
@@ -8,7 +8,10 @@ from ..utils import setup
class TruncatewordsTests(SimpleTestCase):
@setup(
{
- "truncatewords01": '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}{% endautoescape %}'
+ "truncatewords01": (
+ '{% autoescape off %}{{ a|truncatewords:"2" }} {{ b|truncatewords:"2"}}'
+ "{% endautoescape %}"
+ )
}
)
def test_truncatewords01(self):
diff --git a/tests/template_tests/filter_tests/test_unordered_list.py b/tests/template_tests/filter_tests/test_unordered_list.py
index 1f08ea790d..1748a0fb54 100644
--- a/tests/template_tests/filter_tests/test_unordered_list.py
+++ b/tests/template_tests/filter_tests/test_unordered_list.py
@@ -16,7 +16,9 @@ class UnorderedListTests(SimpleTestCase):
@setup(
{
- "unordered_list02": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ "unordered_list02": (
+ "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ )
}
)
def test_unordered_list02(self):
@@ -34,7 +36,9 @@ class UnorderedListTests(SimpleTestCase):
@setup(
{
- "unordered_list04": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ "unordered_list04": (
+ "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ )
}
)
def test_unordered_list04(self):
@@ -45,7 +49,9 @@ class UnorderedListTests(SimpleTestCase):
@setup(
{
- "unordered_list05": "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ "unordered_list05": (
+ "{% autoescape off %}{{ a|unordered_list }}{% endautoescape %}"
+ )
}
)
def test_unordered_list05(self):
@@ -126,7 +132,8 @@ class FunctionTests(SimpleTestCase):
c = ULItem("<a>c</a>")
self.assertEqual(
unordered_list([a, b, c]),
- "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
+ "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t"
+ "<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
)
def item_generator():
@@ -134,7 +141,8 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
unordered_list(item_generator()),
- "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
+ "\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>\n\t"
+ "<li>ulitem-&lt;a&gt;c&lt;/a&gt;</li>",
)
def test_nested_generators(self):
@@ -148,7 +156,8 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
unordered_list(item_generator()),
- "\t<li>A\n\t<ul>\n\t\t<li>B</li>\n\t\t<li>C</li>\n\t</ul>\n\t</li>\n\t<li>D</li>",
+ "\t<li>A\n\t<ul>\n\t\t<li>B</li>\n\t\t<li>C</li>\n\t</ul>\n\t</li>\n\t"
+ "<li>D</li>",
)
def test_ulitem_autoescape_off(self):
diff --git a/tests/template_tests/filter_tests/test_upper.py b/tests/template_tests/filter_tests/test_upper.py
index 01a2f306ae..90f14a794a 100644
--- a/tests/template_tests/filter_tests/test_upper.py
+++ b/tests/template_tests/filter_tests/test_upper.py
@@ -13,7 +13,9 @@ class UpperTests(SimpleTestCase):
@setup(
{
- "upper01": "{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}"
+ "upper01": (
+ "{% autoescape off %}{{ a|upper }} {{ b|upper }}{% endautoescape %}"
+ )
}
)
def test_upper01(self):
diff --git a/tests/template_tests/filter_tests/test_urlize.py b/tests/template_tests/filter_tests/test_urlize.py
index 01e97b35fc..abc227ba6a 100644
--- a/tests/template_tests/filter_tests/test_urlize.py
+++ b/tests/template_tests/filter_tests/test_urlize.py
@@ -9,7 +9,9 @@ from ..utils import setup
class UrlizeTests(SimpleTestCase):
@setup(
{
- "urlize01": "{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}"
+ "urlize01": (
+ "{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}"
+ )
}
)
def test_urlize01(self):
@@ -22,8 +24,10 @@ class UrlizeTests(SimpleTestCase):
)
self.assertEqual(
output,
- '<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&y=</a> '
- '<a href="http://example.com?x=&amp;y=%3C2%3E" rel="nofollow">http://example.com?x=&amp;y=&lt;2&gt;</a>',
+ '<a href="http://example.com/?x=&amp;y=" rel="nofollow">'
+ "http://example.com/?x=&y=</a> "
+ '<a href="http://example.com?x=&amp;y=%3C2%3E" rel="nofollow">'
+ "http://example.com?x=&amp;y=&lt;2&gt;</a>",
)
@setup({"urlize02": "{{ a|urlize }} {{ b|urlize }}"})
@@ -37,8 +41,10 @@ class UrlizeTests(SimpleTestCase):
)
self.assertEqual(
output,
- '<a href="http://example.com/?x=&amp;y=" rel="nofollow">http://example.com/?x=&amp;y=</a> '
- '<a href="http://example.com?x=&amp;y=" rel="nofollow">http://example.com?x=&amp;y=</a>',
+ '<a href="http://example.com/?x=&amp;y=" rel="nofollow">'
+ "http://example.com/?x=&amp;y=</a> "
+ '<a href="http://example.com?x=&amp;y=" rel="nofollow">'
+ "http://example.com?x=&amp;y=</a>",
)
@setup({"urlize03": "{% autoescape off %}{{ a|urlize }}{% endautoescape %}"})
@@ -95,7 +101,8 @@ class UrlizeTests(SimpleTestCase):
)
self.assertEqual(
output,
- '<a href="http://example.com/?x=&amp;y=%3C2%3E" rel="nofollow">http://example.com/?x=&amp;y=&lt;2&gt;</a>',
+ '<a href="http://example.com/?x=&amp;y=%3C2%3E" rel="nofollow">'
+ "http://example.com/?x=&amp;y=&lt;2&gt;</a>",
)
@@ -127,11 +134,13 @@ class FunctionTests(SimpleTestCase):
# part of URLs.
self.assertEqual(
urlize('www.server.com"abc'),
- '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&quot;abc',
+ '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&quot;'
+ "abc",
)
self.assertEqual(
urlize("www.server.com'abc"),
- '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&#x27;abc',
+ '<a href="http://www.server.com" rel="nofollow">www.server.com</a>&#x27;'
+ "abc",
)
self.assertEqual(
urlize("www.server.com<abc"),
@@ -164,8 +173,9 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B"),
- '<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" rel="nofollow">'
- "http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B</a>",
+ '<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" '
+ 'rel="nofollow">http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B'
+ "</a>",
)
def test_urlencoded(self):
@@ -193,13 +203,13 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("https://en.wikipedia.org/wiki/Django_(web_framework)"),
- '<a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
- "https://en.wikipedia.org/wiki/Django_(web_framework)</a>",
+ '<a href="https://en.wikipedia.org/wiki/Django_(web_framework)" '
+ 'rel="nofollow">https://en.wikipedia.org/wiki/Django_(web_framework)</a>',
)
self.assertEqual(
urlize("(see https://en.wikipedia.org/wiki/Django_(web_framework))"),
- '(see <a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
- "https://en.wikipedia.org/wiki/Django_(web_framework)</a>)",
+ '(see <a href="https://en.wikipedia.org/wiki/Django_(web_framework)" '
+ 'rel="nofollow">https://en.wikipedia.org/wiki/Django_(web_framework)</a>)',
)
def test_nofollow(self):
@@ -269,25 +279,30 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("(Go to http://www.example.com/foo.)"),
- '(Go to <a href="http://www.example.com/foo" rel="nofollow">http://www.example.com/foo</a>.)',
+ '(Go to <a href="http://www.example.com/foo" rel="nofollow">'
+ "http://www.example.com/foo</a>.)",
)
def test_trailing_multiple_punctuation(self):
self.assertEqual(
urlize("A test http://testing.com/example.."),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>..',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>..",
)
self.assertEqual(
urlize("A test http://testing.com/example!!"),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>!!",
)
self.assertEqual(
urlize("A test http://testing.com/example!!!"),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>!!!',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>!!!",
)
self.assertEqual(
urlize('A test http://testing.com/example.,:;)"!'),
- 'A test <a href="http://testing.com/example" rel="nofollow">http://testing.com/example</a>.,:;)&quot;!',
+ 'A test <a href="http://testing.com/example" rel="nofollow">'
+ "http://testing.com/example</a>.,:;)&quot;!",
)
def test_brackets(self):
@@ -300,7 +315,8 @@ class FunctionTests(SimpleTestCase):
)
self.assertEqual(
urlize("see test[at[example.com"),
- 'see <a href="http://test[at[example.com" rel="nofollow">test[at[example.com</a>',
+ 'see <a href="http://test[at[example.com" rel="nofollow">'
+ "test[at[example.com</a>",
)
self.assertEqual(
urlize("[http://168.192.0.1](http://168.192.0.1)"),
@@ -321,21 +337,22 @@ class FunctionTests(SimpleTestCase):
start_in, end_in = wrapping_in
self.assertEqual(
urlize(start_in + "https://www.example.org/" + end_in),
- start_out
- + '<a href="https://www.example.org/" rel="nofollow">https://www.example.org/</a>'
- + end_out,
+ f'{start_out}<a href="https://www.example.org/" rel="nofollow">'
+ f"https://www.example.org/</a>{end_out}",
)
def test_ipv4(self):
self.assertEqual(
urlize("http://192.168.0.15/api/9"),
- '<a href="http://192.168.0.15/api/9" rel="nofollow">http://192.168.0.15/api/9</a>',
+ '<a href="http://192.168.0.15/api/9" rel="nofollow">'
+ "http://192.168.0.15/api/9</a>",
)
def test_ipv6(self):
self.assertEqual(
urlize("http://[2001:db8:cafe::2]/api/9"),
- '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">http://[2001:db8:cafe::2]/api/9</a>',
+ '<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">'
+ "http://[2001:db8:cafe::2]/api/9</a>",
)
def test_quotation_marks(self):
@@ -375,7 +392,8 @@ class FunctionTests(SimpleTestCase):
urlize(
'Email us at "hi@example.com", or phone us at +xx.yy', autoescape=False
),
- 'Email us at "<a href="mailto:hi@example.com">hi@example.com</a>", or phone us at +xx.yy',
+ 'Email us at "<a href="mailto:hi@example.com">hi@example.com</a>", or '
+ "phone us at +xx.yy",
)
def test_exclamation_marks(self):
@@ -385,19 +403,23 @@ class FunctionTests(SimpleTestCase):
"""
self.assertEqual(
urlize("Go to djangoproject.com! and enjoy."),
- 'Go to <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>! and enjoy.',
+ 'Go to <a href="http://djangoproject.com" rel="nofollow">djangoproject.com'
+ "</a>! and enjoy.",
)
self.assertEqual(
urlize("Search for google.com/?q=! and see."),
- 'Search for <a href="http://google.com/?q=" rel="nofollow">google.com/?q=</a>! and see.',
+ 'Search for <a href="http://google.com/?q=" rel="nofollow">google.com/?q='
+ "</a>! and see.",
)
self.assertEqual(
urlize("Search for google.com/?q=dj!`? and see."),
- 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a> and see.',
+ 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">'
+ "google.com/?q=dj!`?</a> and see.",
)
self.assertEqual(
urlize("Search for google.com/?q=dj!`?! and see."),
- 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a>! and see.',
+ 'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">'
+ "google.com/?q=dj!`?</a>! and see.",
)
def test_non_string_input(self):
@@ -406,13 +428,15 @@ class FunctionTests(SimpleTestCase):
def test_autoescape(self):
self.assertEqual(
urlize('foo<a href=" google.com ">bar</a>buz'),
- 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com</a> &quot;&gt;bar&lt;/a&gt;buz',
+ 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com'
+ "</a> &quot;&gt;bar&lt;/a&gt;buz",
)
def test_autoescape_off(self):
self.assertEqual(
urlize('foo<a href=" google.com ">bar</a>buz', autoescape=False),
- 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz',
+ 'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">'
+ "bar</a>buz",
)
def test_lazystring(self):
diff --git a/tests/template_tests/filter_tests/test_urlizetrunc.py b/tests/template_tests/filter_tests/test_urlizetrunc.py
index 69e4ec4741..752ee3571e 100644
--- a/tests/template_tests/filter_tests/test_urlizetrunc.py
+++ b/tests/template_tests/filter_tests/test_urlizetrunc.py
@@ -8,7 +8,10 @@ from ..utils import setup
class UrlizetruncTests(SimpleTestCase):
@setup(
{
- "urlizetrunc01": '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% endautoescape %}'
+ "urlizetrunc01": (
+ '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'
+ "{% endautoescape %}"
+ )
}
)
def test_urlizetrunc01(self):
@@ -21,8 +24,10 @@ class UrlizetruncTests(SimpleTestCase):
)
self.assertEqual(
output,
- '"Unsafe" <a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> '
- '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>',
+ '"Unsafe" '
+ '<a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> '
+ "&quot;Safe&quot; "
+ '<a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>',
)
@setup({"urlizetrunc02": '{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}'})
@@ -36,8 +41,10 @@ class UrlizetruncTests(SimpleTestCase):
)
self.assertEqual(
output,
- '&quot;Unsafe&quot; <a href="http://example.com/x=&amp;y=" rel="nofollow">http://…</a> '
- '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">http://…</a>',
+ '&quot;Unsafe&quot; <a href="http://example.com/x=&amp;y=" rel="nofollow">'
+ "http://…</a> "
+ '&quot;Safe&quot; <a href="http://example.com?x=&amp;y=" rel="nofollow">'
+ "http://…</a>",
)
@@ -72,11 +79,12 @@ class FunctionTests(SimpleTestCase):
def test_query_string(self):
self.assertEqual(
urlizetrunc(
- "http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search&meta=",
+ "http://www.google.co.uk/search?hl=en&q=some+long+url&btnG=Search"
+ "&meta=",
20,
),
- '<a href="http://www.google.co.uk/search?hl=en&amp;q=some+long+url&amp;btnG=Search&amp;'
- 'meta=" rel="nofollow">http://www.google.c…</a>',
+ '<a href="http://www.google.co.uk/search?hl=en&amp;q=some+long+url&amp;'
+ 'btnG=Search&amp;meta=" rel="nofollow">http://www.google.c…</a>',
)
def test_non_string_input(self):
@@ -85,11 +93,13 @@ class FunctionTests(SimpleTestCase):
def test_autoescape(self):
self.assertEqual(
urlizetrunc('foo<a href=" google.com ">bar</a>buz', 10),
- 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com</a> &quot;&gt;bar&lt;/a&gt;buz',
+ 'foo&lt;a href=&quot; <a href="http://google.com" rel="nofollow">google.com'
+ "</a> &quot;&gt;bar&lt;/a&gt;buz",
)
def test_autoescape_off(self):
self.assertEqual(
urlizetrunc('foo<a href=" google.com ">bar</a>buz', 9, autoescape=False),
- 'foo<a href=" <a href="http://google.com" rel="nofollow">google.c…</a> ">bar</a>buz',
+ 'foo<a href=" <a href="http://google.com" rel="nofollow">google.c…</a> ">'
+ "bar</a>buz",
)
diff --git a/tests/template_tests/filter_tests/test_wordcount.py b/tests/template_tests/filter_tests/test_wordcount.py
index d15447086f..d3a1eb05f1 100644
--- a/tests/template_tests/filter_tests/test_wordcount.py
+++ b/tests/template_tests/filter_tests/test_wordcount.py
@@ -8,7 +8,10 @@ from ..utils import setup
class WordcountTests(SimpleTestCase):
@setup(
{
- "wordcount01": "{% autoescape off %}{{ a|wordcount }} {{ b|wordcount }}{% endautoescape %}"
+ "wordcount01": (
+ "{% autoescape off %}{{ a|wordcount }} {{ b|wordcount }}"
+ "{% endautoescape %}"
+ )
}
)
def test_wordcount01(self):
diff --git a/tests/template_tests/filter_tests/test_wordwrap.py b/tests/template_tests/filter_tests/test_wordwrap.py
index fb2bce5a90..88fbd274da 100644
--- a/tests/template_tests/filter_tests/test_wordwrap.py
+++ b/tests/template_tests/filter_tests/test_wordwrap.py
@@ -9,7 +9,10 @@ from ..utils import setup
class WordwrapTests(SimpleTestCase):
@setup(
{
- "wordwrap01": '{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}{% endautoescape %}'
+ "wordwrap01": (
+ '{% autoescape off %}{{ a|wordwrap:"3" }} {{ b|wordwrap:"3" }}'
+ "{% endautoescape %}"
+ )
}
)
def test_wordwrap01(self):
@@ -30,28 +33,34 @@ class FunctionTests(SimpleTestCase):
def test_wrap(self):
self.assertEqual(
wordwrap(
- "this is a long paragraph of text that really needs to be wrapped I'm afraid",
+ "this is a long paragraph of text that really needs to be wrapped I'm "
+ "afraid",
14,
),
- "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid",
+ "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\n"
+ "I'm afraid",
)
def test_indent(self):
self.assertEqual(
wordwrap(
- "this is a short paragraph of text.\n But this line should be indented",
+ "this is a short paragraph of text.\n But this line should be "
+ "indented",
14,
),
- "this is a\nshort\nparagraph of\ntext.\n But this\nline should be\nindented",
+ "this is a\nshort\nparagraph of\ntext.\n But this\nline should be\n"
+ "indented",
)
def test_indent2(self):
self.assertEqual(
wordwrap(
- "this is a short paragraph of text.\n But this line should be indented",
+ "this is a short paragraph of text.\n But this line should be "
+ "indented",
15,
),
- "this is a short\nparagraph of\ntext.\n But this line\nshould be\nindented",
+ "this is a short\nparagraph of\ntext.\n But this line\nshould be\n"
+ "indented",
)
def test_non_string_input(self):
@@ -61,9 +70,11 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(
wordwrap(
lazystr(
- "this is a long paragraph of text that really needs to be wrapped I'm afraid"
+ "this is a long paragraph of text that really needs to be wrapped "
+ "I'm afraid"
),
14,
),
- "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\nI'm afraid",
+ "this is a long\nparagraph of\ntext that\nreally needs\nto be wrapped\n"
+ "I'm afraid",
)
diff --git a/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py b/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
index 8ad004a899..4a162362c6 100644
--- a/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
+++ b/tests/template_tests/syntax_tests/i18n/test_blocktranslate.py
@@ -52,7 +52,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n03": "{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}"
+ "i18n03": (
+ "{% load i18n %}{% blocktranslate %}{{ anton }}{% endblocktranslate %}"
+ )
}
)
def test_i18n03(self):
@@ -62,7 +64,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n04": "{% load i18n %}{% blocktranslate with berta=anton|lower %}{{ berta }}{% endblocktranslate %}"
+ "i18n04": (
+ "{% load i18n %}{% blocktranslate with berta=anton|lower %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n04(self):
@@ -72,8 +77,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "legacyi18n04": "{% load i18n %}"
- "{% blocktranslate with anton|lower as berta %}{{ berta }}{% endblocktranslate %}"
+ "legacyi18n04": (
+ "{% load i18n %}"
+ "{% blocktranslate with anton|lower as berta %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_legacyi18n04(self):
@@ -83,7 +91,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n05": "{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx{% endblocktranslate %}"
+ "i18n05": (
+ "{% load i18n %}{% blocktranslate %}xxx{{ anton }}xxx"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n05(self):
@@ -141,8 +152,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n17": "{% load i18n %}"
- "{% blocktranslate with berta=anton|escape %}{{ berta }}{% endblocktranslate %}"
+ "i18n17": (
+ "{% load i18n %}"
+ "{% blocktranslate with berta=anton|escape %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n17(self):
@@ -155,8 +169,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n18": "{% load i18n %}"
- "{% blocktranslate with berta=anton|force_escape %}{{ berta }}{% endblocktranslate %}"
+ "i18n18": (
+ "{% load i18n %}"
+ "{% blocktranslate with berta=anton|force_escape %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n18(self):
@@ -165,7 +182,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n19": "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ "i18n19": (
+ "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ )
}
)
def test_i18n19(self):
@@ -174,7 +193,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n21": "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ "i18n21": (
+ "{% load i18n %}{% blocktranslate %}{{ andrew }}{% endblocktranslate %}"
+ )
}
)
def test_i18n21(self):
@@ -183,8 +204,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "legacyi18n17": "{% load i18n %}"
- "{% blocktranslate with anton|escape as berta %}{{ berta }}{% endblocktranslate %}"
+ "legacyi18n17": (
+ "{% load i18n %}"
+ "{% blocktranslate with anton|escape as berta %}{{ berta }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_legacyi18n17(self):
@@ -220,9 +244,12 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "legacyi18n26": "{% load i18n %}"
- "{% blocktranslate with myextra_field as extra_field count number as counter %}"
- "singular {{ extra_field }}{% plural %}plural{% endblocktranslate %}"
+ "legacyi18n26": (
+ "{% load i18n %}"
+ "{% blocktranslate with myextra_field as extra_field "
+ "count number as counter %}singular {{ extra_field }}{% plural %}plural"
+ "{% endblocktranslate %}"
+ )
}
)
def test_legacyi18n26(self):
@@ -262,8 +289,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n28": "{% load i18n %}"
- "{% blocktranslate with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktranslate %}"
+ "i18n28": (
+ "{% load i18n %}"
+ "{% blocktranslate with a=anton b=berta %}{{ a }} + {{ b }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n28(self):
@@ -288,7 +318,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
# this should work as if blocktranslate was not there (#19915)
@setup(
{
- "i18n34": "{% load i18n %}{% blocktranslate %}{{ missing }}{% endblocktranslate %}"
+ "i18n34": (
+ "{% load i18n %}{% blocktranslate %}{{ missing }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n34(self):
@@ -300,7 +333,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n34_2": "{% load i18n %}{% blocktranslate with a='α' %}{{ missing }}{% endblocktranslate %}"
+ "i18n34_2": (
+ "{% load i18n %}{% blocktranslate with a='α' %}{{ missing }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n34_2(self):
@@ -312,7 +348,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "i18n34_3": "{% load i18n %}{% blocktranslate with a=anton %}{{ missing }}{% endblocktranslate %}"
+ "i18n34_3": (
+ "{% load i18n %}{% blocktranslate with a=anton %}{{ missing }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_i18n34_3(self):
@@ -337,9 +376,11 @@ class I18nBlockTransTagTests(SimpleTestCase):
# blocktranslate tag with asvar
@setup(
{
- "i18n39": "{% load i18n %}"
- "{% blocktranslate asvar page_not_found %}Page not found{% endblocktranslate %}"
- ">{{ page_not_found }}<"
+ "i18n39": (
+ "{% load i18n %}"
+ "{% blocktranslate asvar page_not_found %}Page not found"
+ "{% endblocktranslate %}>{{ page_not_found }}<"
+ )
}
)
def test_i18n39(self):
@@ -377,7 +418,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "template": "{% load i18n %}{% blocktranslate asvar %}Yes{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate asvar %}Yes{% endblocktranslate %}"
+ )
}
)
def test_blocktrans_syntax_error_missing_assignment(self, tag_name):
@@ -394,7 +437,10 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "template": "{% load i18n %}{% blocktranslate %}{% block b %} {% endblock %}{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate %}{% block b %} {% endblock %}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_with_block(self, tag_name):
@@ -414,15 +460,19 @@ class I18nBlockTransTagTests(SimpleTestCase):
}
)
def test_with_for(self, tag_name):
- msg = "'{}' doesn't allow other block tags (seen 'for b in [1, 2, 3]') inside it".format(
- tag_name
+ msg = (
+ f"'{tag_name}' doesn't allow other block tags (seen 'for b in [1, 2, 3]') "
+ f"inside it"
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
@setup(
{
- "template": "{% load i18n %}{% blocktranslate with foo=bar with %}{{ foo }}{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate with foo=bar with %}{{ foo }}"
+ "{% endblocktranslate %}"
+ )
}
)
def test_variable_twice(self):
@@ -443,7 +493,9 @@ class I18nBlockTransTagTests(SimpleTestCase):
@setup(
{
- "template": "{% load i18n %}{% blocktranslate count a %}{% endblocktranslate %}"
+ "template": (
+ "{% load i18n %}{% blocktranslate count a %}{% endblocktranslate %}"
+ )
}
)
def test_count(self, tag_name):
@@ -509,12 +561,14 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
# Existing context... using a literal
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "month name" %}May{% endblocktranslate %}'
+ "{% load i18n %}"
+ '{% blocktranslate context "month name" %}May{% endblocktranslate %}'
)
rendered = t.render(Context())
self.assertEqual(rendered, "Mai")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "verb" %}May{% endblocktranslate %}'
+ "{% load i18n %}"
+ '{% blocktranslate context "verb" %}May{% endblocktranslate %}'
)
rendered = t.render(Context())
self.assertEqual(rendered, "Kann")
@@ -535,51 +589,65 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
# Using a filter
t = self.get_template(
- "{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}"
+ "{% load i18n %}"
+ "{% blocktranslate context message_context|lower %}May"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"message_context": "MONTH NAME"}))
self.assertEqual(rendered, "Mai")
t = self.get_template(
- "{% load i18n %}{% blocktranslate context message_context|lower %}May{% endblocktranslate %}"
+ "{% load i18n %}"
+ "{% blocktranslate context message_context|lower %}May"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"message_context": "VERB"}))
self.assertEqual(rendered, "Kann")
# Using 'count'
t = self.get_template(
- '{% load i18n %}{% blocktranslate count number=1 context "super search" %}'
- "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate count number=1 context "super search" %}{{ number }}'
+ " super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "1 Super-Ergebnis")
t = self.get_template(
- '{% load i18n %}{% blocktranslate count number=2 context "super search" %}{{ number }}'
- " super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate count number=2 context "super search" %}{{ number }}'
+ " super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "2 Super-Ergebnisse")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "other super search" count number=1 %}'
- "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate context "other super search" count number=1 %}'
+ "{{ number }} super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "1 anderen Super-Ergebnis")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "other super search" count number=2 %}'
- "{{ number }} super result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate context "other super search" count number=2 %}'
+ "{{ number }} super result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "2 andere Super-Ergebnisse")
# Using 'with'
t = self.get_template(
- '{% load i18n %}{% blocktranslate with num_comments=5 context "comment count" %}'
+ "{% load i18n %}"
+ '{% blocktranslate with num_comments=5 context "comment count" %}'
"There are {{ num_comments }} comments{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Es gibt 5 Kommentare")
t = self.get_template(
- '{% load i18n %}{% blocktranslate with num_comments=5 context "other comment count" %}'
+ "{% load i18n %}"
+ '{% blocktranslate with num_comments=5 context "other comment count" %}'
"There are {{ num_comments }} comments{% endblocktranslate %}"
)
rendered = t.render(Context())
@@ -593,14 +661,19 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
rendered = t.render(Context())
self.assertEqual(rendered, "There are 5 comments")
t = self.get_template(
- '{% load i18n %}{% blocktranslate with num_comments=5 context "comment count" trimmed %}\n\n'
- "There are \t\n \t {{ num_comments }} comments\n\n{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate with num_comments=5 context "comment count" trimmed '
+ "%}\n\n"
+ "There are \t\n \t {{ num_comments }} comments\n\n"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Es gibt 5 Kommentare")
t = self.get_template(
- '{% load i18n %}{% blocktranslate context "other super search" count number=2 trimmed %}\n'
- "{{ number }} super \n result{% plural %}{{ number }} super results{% endblocktranslate %}"
+ "{% load i18n %}"
+ '{% blocktranslate context "other super search" count number=2 trimmed '
+ "%}\n{{ number }} super \n result{% plural %}{{ number }} super results"
+ "{% endblocktranslate %}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "2 andere Super-Ergebnisse")
@@ -609,7 +682,8 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
msg = "Unknown argument for 'blocktranslate' tag: %r."
with self.assertRaisesMessage(TemplateSyntaxError, msg % 'month="May"'):
self.get_template(
- '{% load i18n %}{% blocktranslate context with month="May" %}{{ month }}{% endblocktranslate %}'
+ '{% load i18n %}{% blocktranslate context with month="May" %}'
+ "{{ month }}{% endblocktranslate %}"
)
msg = (
'"context" in %r tag expected exactly one argument.' % "blocktranslate"
@@ -633,7 +707,8 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
"""
with translation.override("fr"):
t = Template(
- "{% load i18n %}{% blocktranslate %}My name is {{ person }}.{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}My name is {{ person }}."
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"person": "James"}))
self.assertEqual(rendered, "My name is James.")
@@ -647,7 +722,8 @@ class TranslationBlockTranslateTagTests(SimpleTestCase):
"""
with translation.override("fr"):
t = Template(
- "{% load i18n %}{% blocktranslate %}My other name is {{ person }}.{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}My other name is {{ person }}."
+ "{% endblocktranslate %}"
)
rendered = t.render(Context({"person": "James"}))
self.assertEqual(rendered, "My other name is James.")
@@ -728,7 +804,8 @@ class MiscTests(SimpleTestCase):
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_percent_in_translatable_block(self):
t_sing = self.get_template(
- "{% load i18n %}{% blocktranslate %}The result was {{ percent }}%{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}The result was {{ percent }}%"
+ "{% endblocktranslate %}"
)
t_plur = self.get_template(
"{% load i18n %}{% blocktranslate count num as number %}"
@@ -755,7 +832,8 @@ class MiscTests(SimpleTestCase):
or plural.
"""
t_sing = self.get_template(
- "{% load i18n %}{% blocktranslate %}There are %(num_comments)s comments{% endblocktranslate %}"
+ "{% load i18n %}{% blocktranslate %}There are %(num_comments)s comments"
+ "{% endblocktranslate %}"
)
t_plur = self.get_template(
"{% load i18n %}{% blocktranslate count num as number %}"
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py b/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
index dce5a4de66..ce2e60c0d9 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_available_languages.py
@@ -20,6 +20,9 @@ class GetAvailableLanguagesTagTests(SimpleTestCase):
@setup({"syntax_i18n": "{% load i18n %}{% get_available_languages a langs %}"})
def test_no_as_var(self):
- msg = "'get_available_languages' requires 'as variable' (got ['get_available_languages', 'a', 'langs'])"
+ msg = (
+ "'get_available_languages' requires 'as variable' (got "
+ "['get_available_languages', 'a', 'langs'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("syntax_i18n")
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_current_language.py b/tests/template_tests/syntax_tests/i18n/test_get_current_language.py
index 8ed7f742c2..7de1b53bd9 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_current_language.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_current_language.py
@@ -9,6 +9,9 @@ class I18nGetCurrentLanguageTagTests(SimpleTestCase):
@setup({"template": "{% load i18n %} {% get_current_language %}"})
def test_no_as_var(self):
- msg = "'get_current_language' requires 'as variable' (got ['get_current_language'])"
+ msg = (
+ "'get_current_language' requires 'as variable' (got "
+ "['get_current_language'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py b/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
index 3f307471ae..9b57047209 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_current_language_bidi.py
@@ -9,6 +9,9 @@ class I18nGetCurrentLanguageBidiTagTests(SimpleTestCase):
@setup({"template": "{% load i18n %} {% get_current_language_bidi %}"})
def test_no_as_var(self):
- msg = "'get_current_language_bidi' requires 'as variable' (got ['get_current_language_bidi'])"
+ msg = (
+ "'get_current_language_bidi' requires 'as variable' (got "
+ "['get_current_language_bidi'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
diff --git a/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py b/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
index 93038daa2f..962c888782 100644
--- a/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
+++ b/tests/template_tests/syntax_tests/i18n/test_get_language_info_list.py
@@ -65,6 +65,9 @@ class GetLanguageInfoListTests(SimpleTestCase):
@setup({"i18n_syntax": "{% load i18n %} {% get_language_info_list error %}"})
def test_no_for_as(self):
- msg = "'get_language_info_list' requires 'for sequence as variable' (got ['error'])"
+ msg = (
+ "'get_language_info_list' requires 'for sequence as variable' (got "
+ "['error'])"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("i18n_syntax")
diff --git a/tests/template_tests/syntax_tests/i18n/test_translate.py b/tests/template_tests/syntax_tests/i18n/test_translate.py
index 932b47a373..d8a224df9d 100644
--- a/tests/template_tests/syntax_tests/i18n/test_translate.py
+++ b/tests/template_tests/syntax_tests/i18n/test_translate.py
@@ -84,7 +84,9 @@ class I18nTransTagTests(SimpleTestCase):
@setup(
{
- "i18n23": '{% load i18n %}{% translate "Page not found"|capfirst|slice:"6:" %}'
+ "i18n23": (
+ '{% load i18n %}{% translate "Page not found"|capfirst|slice:"6:" %}'
+ )
}
)
def test_i18n23(self):
@@ -110,7 +112,10 @@ class I18nTransTagTests(SimpleTestCase):
# trans tag with as var
@setup(
{
- "i18n35": '{% load i18n %}{% translate "Page not found" as page_not_found %}{{ page_not_found }}'
+ "i18n35": (
+ '{% load i18n %}{% translate "Page not found" as page_not_found %}'
+ "{{ page_not_found }}"
+ )
}
)
def test_i18n35(self):
@@ -120,8 +125,10 @@ class I18nTransTagTests(SimpleTestCase):
@setup(
{
- "i18n36": "{% load i18n %}"
- '{% translate "Page not found" noop as page_not_found %}{{ page_not_found }}'
+ "i18n36": (
+ '{% load i18n %}{% translate "Page not found" noop as page_not_found %}'
+ "{{ page_not_found }}"
+ )
}
)
def test_i18n36(self):
@@ -157,16 +164,18 @@ class I18nTransTagTests(SimpleTestCase):
@setup({"template": '{% load i18n %}{% translate "Yes" context as var %}'})
def test_syntax_error_context_as(self, tag_name):
- msg = "Invalid argument 'as' provided to the '{}' tag for the context option".format(
- tag_name
+ msg = (
+ f"Invalid argument 'as' provided to the '{tag_name}' tag for the context "
+ f"option"
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
@setup({"template": '{% load i18n %}{% translate "Yes" context noop %}'})
def test_syntax_error_context_noop(self, tag_name):
- msg = "Invalid argument 'noop' provided to the '{}' tag for the context option".format(
- tag_name
+ msg = (
+ f"Invalid argument 'noop' provided to the '{tag_name}' tag for the context "
+ f"option"
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.render_to_string("template")
@@ -240,12 +249,14 @@ class TranslationTransTagTests(SimpleTestCase):
# Using 'as'
t = self.get_template(
- '{% load i18n %}{% translate "May" context "month name" as var %}Value: {{ var }}'
+ '{% load i18n %}{% translate "May" context "month name" as var %}'
+ "Value: {{ var }}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Value: Mai")
t = self.get_template(
- '{% load i18n %}{% translate "May" as var context "verb" %}Value: {{ var }}'
+ '{% load i18n %}{% translate "May" as var context "verb" %}Value: '
+ "{{ var }}"
)
rendered = t.render(Context())
self.assertEqual(rendered, "Value: Kann")
diff --git a/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py b/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
index dfb035999c..ac6a22ed46 100644
--- a/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
+++ b/tests/template_tests/syntax_tests/i18n/test_underscore_syntax.py
@@ -90,7 +90,10 @@ class I18nStringLiteralTests(SimpleTestCase):
@setup(
{
- "i18n14": '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}'
+ "i18n14": (
+ '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} '
+ "{% cycle c %}"
+ )
}
)
def test_i18n14(self):
diff --git a/tests/template_tests/syntax_tests/test_autoescape.py b/tests/template_tests/syntax_tests/test_autoescape.py
index d3c5cb02da..a45b850fcf 100644
--- a/tests/template_tests/syntax_tests/test_autoescape.py
+++ b/tests/template_tests/syntax_tests/test_autoescape.py
@@ -28,7 +28,10 @@ class AutoescapeTagTests(SimpleTestCase):
# Autoescape disabling and enabling nest in a predictable way.
@setup(
{
- "autoescape-tag04": "{% autoescape off %}{{ first }} {% autoescape on %}{{ first }}{% endautoescape %}{% endautoescape %}"
+ "autoescape-tag04": (
+ "{% autoescape off %}{{ first }} {% autoescape on %}{{ first }}"
+ "{% endautoescape %}{% endautoescape %}"
+ )
}
)
def test_autoescape_tag04(self):
@@ -60,7 +63,10 @@ class AutoescapeTagTests(SimpleTestCase):
@setup(
{
- "autoescape-tag08": r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}'
+ "autoescape-tag08": (
+ r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}'
+ r"{% endautoescape %}"
+ )
}
)
def test_autoescape_tag08(self):
@@ -86,7 +92,9 @@ class AutoescapeTagTests(SimpleTestCase):
@setup(
{
- "autoescape-filtertag01": "{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}"
+ "autoescape-filtertag01": (
+ "{{ first }}{% filter safe %}{{ first }} x<y{% endfilter %}"
+ )
}
)
def test_autoescape_filtertag01(self):
@@ -143,7 +151,9 @@ class AutoescapeTagTests(SimpleTestCase):
@setup(
{
- "autoescape-incorrect-arg": "{% autoescape true %}{{ var.key }}{% endautoescape %}"
+ "autoescape-incorrect-arg": (
+ "{% autoescape true %}{{ var.key }}{% endautoescape %}"
+ )
}
)
def test_invalid_arg(self):
diff --git a/tests/template_tests/syntax_tests/test_cache.py b/tests/template_tests/syntax_tests/test_cache.py
index a722420637..9dcf9a6b5a 100644
--- a/tests/template_tests/syntax_tests/test_cache.py
+++ b/tests/template_tests/syntax_tests/test_cache.py
@@ -105,7 +105,10 @@ class CacheTagTests(SimpleTestCase):
@setup(
{
- "cache17": "{% load cache %}{% cache 10 long_cache_key poem %}Some Content{% endcache %}"
+ "cache17": (
+ "{% load cache %}{% cache 10 long_cache_key poem %}Some Content"
+ "{% endcache %}"
+ )
}
)
def test_cache17(self):
@@ -119,8 +122,8 @@ class CacheTagTests(SimpleTestCase):
"Oh freddled gruntbuggly/Thy micturations are to me/"
"As plurdled gabbleblotchits/On a lurgid bee/"
"That mordiously hath bitled out/Its earted jurtles/"
- "Into a rancid festering/Or else I shall rend thee in the gobberwarts"
- "with my blurglecruncheon/See if I don't."
+ "Into a rancid festering/Or else I shall rend thee in the "
+ "gobberwarts with my blurglecruncheon/See if I don't."
),
},
)
@@ -128,7 +131,10 @@ class CacheTagTests(SimpleTestCase):
@setup(
{
- "cache18": '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}'
+ "cache18": (
+ '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18'
+ "{% endcache %}"
+ )
}
)
def test_cache18(self):
@@ -141,7 +147,9 @@ class CacheTagTests(SimpleTestCase):
@setup(
{
"first": "{% load cache %}{% cache None fragment19 %}content{% endcache %}",
- "second": "{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}",
+ "second": (
+ "{% load cache %}{% cache None fragment19 %}not rendered{% endcache %}"
+ ),
}
)
def test_none_timeout(self):
diff --git a/tests/template_tests/syntax_tests/test_cycle.py b/tests/template_tests/syntax_tests/test_cycle.py
index d4233fac3e..cff0363e38 100644
--- a/tests/template_tests/syntax_tests/test_cycle.py
+++ b/tests/template_tests/syntax_tests/test_cycle.py
@@ -35,7 +35,10 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle12": "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}"
+ "cycle12": (
+ "{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}"
+ "{% cycle abc %}"
+ )
}
)
def test_cycle12(self):
@@ -106,7 +109,10 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle22": "{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}"
+ "cycle22": (
+ "{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}"
+ "{% endfor %}"
+ )
}
)
def test_cycle22(self):
@@ -125,8 +131,11 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle24": "{% for x in values %}"
- "{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}",
+ "cycle24": (
+ "{% for x in values %}"
+ "{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}"
+ "{% endfor %}"
+ ),
"included-cycle": "{{ abc }}",
}
)
@@ -146,7 +155,10 @@ class CycleTagTests(SimpleTestCase):
@setup(
{
- "cycle27": "{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}{% endautoescape %}"
+ "cycle27": (
+ "{% autoescape off %}{% cycle a b as ab %}{% cycle ab %}"
+ "{% endautoescape %}"
+ )
}
)
def test_cycle27(self):
diff --git a/tests/template_tests/syntax_tests/test_exceptions.py b/tests/template_tests/syntax_tests/test_exceptions.py
index 7000b45afd..b6d86ac42b 100644
--- a/tests/template_tests/syntax_tests/test_exceptions.py
+++ b/tests/template_tests/syntax_tests/test_exceptions.py
@@ -42,13 +42,17 @@ class ExceptionsTests(SimpleTestCase):
@setup(
{
- "exception04": "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678{% endblock %}"
+ "exception04": (
+ "{% extends 'inheritance17' %}{% block first %}{% echo 400 %}5678"
+ "{% endblock %}"
+ )
},
inheritance_templates,
)
def test_exception04(self):
"""
- Raise exception for custom tags used in child with {% load %} tag in parent, not in child
+ Raise exception for custom tags used in child with {% load %} tag in
+ parent, not in child
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.get_template("exception04")
diff --git a/tests/template_tests/syntax_tests/test_extends.py b/tests/template_tests/syntax_tests/test_extends.py
index ce073fb909..9f5dae0db4 100644
--- a/tests/template_tests/syntax_tests/test_extends.py
+++ b/tests/template_tests/syntax_tests/test_extends.py
@@ -6,7 +6,9 @@ from django.test import SimpleTestCase
from ..utils import setup
inheritance_templates = {
- "inheritance01": "1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}",
+ "inheritance01": (
+ "1{% block first %}&{% endblock %}3{% block second %}_{% endblock %}"
+ ),
"inheritance02": "{% extends 'inheritance01' %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
"inheritance03": "{% extends 'inheritance02' %}",
@@ -22,7 +24,9 @@ inheritance_templates = {
"inheritance12": "{% extends 'inheritance07' %}{% block first %}2{% endblock %}",
"inheritance13": "{% extends 'inheritance02' %}"
"{% block first %}a{% endblock %}{% block second %}b{% endblock %}",
- "inheritance14": "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}",
+ "inheritance14": (
+ "{% extends 'inheritance01' %}{% block newblock %}NO DISPLAY{% endblock %}"
+ ),
"inheritance15": "{% extends 'inheritance01' %}"
"{% block first %}2{% block inner %}inner{% endblock %}{% endblock %}",
"inheritance16": "{% extends 'inheritance15' %}{% block inner %}out{% endblock %}",
@@ -30,10 +34,18 @@ inheritance_templates = {
"inheritance18": "{% load testtags %}{% echo this that theother %}5678",
"inheritance19": "{% extends 'inheritance01' %}"
"{% block first %}{% load testtags %}{% echo 400 %}5678{% endblock %}",
- "inheritance20": "{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}",
- "inheritance21": "{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}",
- "inheritance22": "{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}",
- "inheritance23": "{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}",
+ "inheritance20": (
+ "{% extends 'inheritance01' %}{% block first %}{{ block.super }}a{% endblock %}"
+ ),
+ "inheritance21": (
+ "{% extends 'inheritance02' %}{% block first %}{{ block.super }}a{% endblock %}"
+ ),
+ "inheritance22": (
+ "{% extends 'inheritance04' %}{% block first %}{{ block.super }}a{% endblock %}"
+ ),
+ "inheritance23": (
+ "{% extends 'inheritance20' %}{% block first %}{{ block.super }}b{% endblock %}"
+ ),
"inheritance24": "{% extends context_template %}"
"{% block first %}2{% endblock %}{% block second %}4{% endblock %}",
"inheritance25": "{% extends context_template.1 %}"
@@ -45,19 +57,32 @@ inheritance_templates = {
"inheritance30": "1{% if optional %}{% block opt %}2{% endblock %}{% endif %}3",
"inheritance31": "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}",
"inheritance32": "{% extends 'inheritance30' %}{% block opt %}two{% endblock %}",
- "inheritance33": "1{% if optional == 1 %}{% block opt %}2{% endblock %}{% endif %}3",
+ "inheritance33": (
+ "1{% if optional == 1 %}{% block opt %}2{% endblock %}{% endif %}3"
+ ),
"inheritance34": "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}",
"inheritance35": "{% extends 'inheritance33' %}{% block opt %}two{% endblock %}",
- "inheritance36": "{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_",
+ "inheritance36": (
+ "{% for n in numbers %}_{% block opt %}{{ n }}{% endblock %}{% endfor %}_"
+ ),
"inheritance37": "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}",
"inheritance38": "{% extends 'inheritance36' %}{% block opt %}X{% endblock %}",
- "inheritance39": "{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}",
- "inheritance40": "{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}",
- "inheritance41": "{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}",
+ "inheritance39": (
+ "{% extends 'inheritance30' %}{% block opt %}new{{ block.super }}{% endblock %}"
+ ),
+ "inheritance40": (
+ "{% extends 'inheritance33' %}{% block opt %}new{{ block.super }}{% endblock %}"
+ ),
+ "inheritance41": (
+ "{% extends 'inheritance36' %}{% block opt %}new{{ block.super }}{% endblock %}"
+ ),
"inheritance42": "{% extends 'inheritance02'|cut:' ' %}",
"inheritance_empty": "{% extends %}",
"extends_duplicate": "{% extends 'base.html' %}{% extends 'base.html' %}",
- "duplicate_block": "{% extends 'base.html' %}{% block content %}2{% endblock %}{% block content %}4{% endblock %}",
+ "duplicate_block": (
+ "{% extends 'base.html' %}{% block content %}2{% endblock %}{% block content %}"
+ "4{% endblock %}"
+ ),
}
diff --git a/tests/template_tests/syntax_tests/test_for.py b/tests/template_tests/syntax_tests/test_for.py
index ad1d158f9b..a47a99ac65 100644
--- a/tests/template_tests/syntax_tests/test_for.py
+++ b/tests/template_tests/syntax_tests/test_for.py
@@ -34,7 +34,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-vars03": "{% for val in values %}{{ forloop.revcounter }}{% endfor %}"
+ "for-tag-vars03": (
+ "{% for val in values %}{{ forloop.revcounter }}{% endfor %}"
+ )
}
)
def test_for_tag_vars03(self):
@@ -43,7 +45,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-vars04": "{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}"
+ "for-tag-vars04": (
+ "{% for val in values %}{{ forloop.revcounter0 }}{% endfor %}"
+ )
}
)
def test_for_tag_vars04(self):
@@ -72,7 +76,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack01": "{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack01": (
+ "{% for key,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack01(self):
@@ -83,7 +89,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack03": "{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack03": (
+ "{% for key, value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack03(self):
@@ -94,7 +102,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack04": "{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack04": (
+ "{% for key , value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack04(self):
@@ -105,7 +115,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack05": "{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack05": (
+ "{% for key ,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack05(self):
@@ -116,7 +128,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack06": "{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack06": (
+ "{% for key value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack06(self):
@@ -128,7 +142,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack07": "{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack07": (
+ "{% for key,,value in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack07(self):
@@ -140,7 +156,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack08": "{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}"
+ "for-tag-unpack08": (
+ "{% for key,value, in items %}{{ key }}:{{ value }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack08(self):
@@ -170,7 +188,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack09": "{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}"
+ "for-tag-unpack09": (
+ "{% for val in items %}{{ val.0 }}:{{ val.1 }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack09(self):
@@ -184,7 +204,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack13": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ "for-tag-unpack13": (
+ "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack13(self):
@@ -198,7 +220,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-empty01": "{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}"
+ "for-tag-empty01": (
+ "{% for val in values %}{{ val }}{% empty %}empty text{% endfor %}"
+ )
}
)
def test_for_tag_empty01(self):
@@ -207,7 +231,10 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-empty02": "{% for val in values %}{{ val }}{% empty %}values array empty{% endfor %}"
+ "for-tag-empty02": (
+ "{% for val in values %}{{ val }}{% empty %}values array empty"
+ "{% endfor %}"
+ )
}
)
def test_for_tag_empty02(self):
@@ -226,7 +253,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-filter-ws": "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}"
+ "for-tag-filter-ws": (
+ "{% load custom %}{% for x in s|noop:'x y' %}{{ x }}{% endfor %}"
+ )
}
)
def test_for_tag_filter_ws(self):
@@ -257,7 +286,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack11": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ "for-tag-unpack11": (
+ "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack11(self):
@@ -271,7 +302,9 @@ class ForTagTests(SimpleTestCase):
@setup(
{
- "for-tag-unpack12": "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ "for-tag-unpack12": (
+ "{% for x,y,z in items %}{{ x }}:{{ y }},{{ z }}/{% endfor %}"
+ )
}
)
def test_for_tag_unpack12(self):
diff --git a/tests/template_tests/syntax_tests/test_if.py b/tests/template_tests/syntax_tests/test_if.py
index fda44b0672..36077f0687 100644
--- a/tests/template_tests/syntax_tests/test_if.py
+++ b/tests/template_tests/syntax_tests/test_if.py
@@ -53,7 +53,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag10": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag10": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag10(self):
@@ -62,7 +65,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag11": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag11": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag11(self):
@@ -71,7 +77,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag12": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag12": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag12(self):
@@ -80,7 +89,10 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag13": "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing{% endif %}"
+ "if-tag13": (
+ "{% if foo %}foo{% elif bar %}bar{% elif baz %}baz{% else %}nothing"
+ "{% endif %}"
+ )
}
)
def test_if_tag13(self):
@@ -588,7 +600,9 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "else-if-tag-error01": "{% if foo is bar %} yes {% else if foo is not bar %} no {% endif %}"
+ "else-if-tag-error01": (
+ "{% if foo is bar %} yes {% else if foo is not bar %} no {% endif %}"
+ )
}
)
def test_else_if_tag_error01(self):
@@ -598,7 +612,9 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag-shortcircuit01": "{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}"
+ "if-tag-shortcircuit01": (
+ "{% if x.is_true or x.is_bad %}yes{% else %}no{% endif %}"
+ )
}
)
def test_if_tag_shortcircuit01(self):
@@ -610,7 +626,9 @@ class IfTagTests(SimpleTestCase):
@setup(
{
- "if-tag-shortcircuit02": "{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}"
+ "if-tag-shortcircuit02": (
+ "{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}"
+ )
}
)
def test_if_tag_shortcircuit02(self):
diff --git a/tests/template_tests/syntax_tests/test_if_changed.py b/tests/template_tests/syntax_tests/test_if_changed.py
index 3835e52d78..fb0a693460 100644
--- a/tests/template_tests/syntax_tests/test_if_changed.py
+++ b/tests/template_tests/syntax_tests/test_if_changed.py
@@ -9,7 +9,9 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged01": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ "ifchanged01": (
+ "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ )
}
)
def test_ifchanged01(self):
@@ -18,7 +20,9 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged02": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ "ifchanged02": (
+ "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ )
}
)
def test_ifchanged02(self):
@@ -27,7 +31,9 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged03": "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ "ifchanged03": (
+ "{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}"
+ )
}
)
def test_ifchanged03(self):
@@ -108,8 +114,10 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param01": "{% for n in num %}{% ifchanged n %}..{% endifchanged %}"
- "{{ n }}{% endfor %}"
+ "ifchanged-param01": (
+ "{% for n in num %}{% ifchanged n %}..{% endifchanged %}"
+ "{{ n }}{% endfor %}"
+ )
}
)
def test_ifchanged_param01(self):
@@ -121,8 +129,11 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param02": "{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}"
- "{{ x }}{% endfor %}{% endfor %}"
+ "ifchanged-param02": (
+ "{% for n in num %}{% for x in numx %}"
+ "{% ifchanged n %}..{% endifchanged %}{{ x }}"
+ "{% endfor %}{% endfor %}"
+ )
}
)
def test_ifchanged_param02(self):
@@ -149,9 +160,11 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param04": "{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}"
- "{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}"
- "{% endfor %}{% endfor %}"
+ "ifchanged-param04": (
+ "{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}"
+ "{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}"
+ "{% endfor %}{% endfor %}"
+ )
}
)
def test_ifchanged_param04(self):
@@ -167,9 +180,11 @@ class IfChangedTagTests(SimpleTestCase):
@setup(
{
- "ifchanged-param05": "{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}"
- "{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}"
- "{% endfor %}{% endfor %}"
+ "ifchanged-param05": (
+ "{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}"
+ "{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}"
+ "{% endfor %}{% endfor %}"
+ )
}
)
def test_ifchanged_param05(self):
@@ -275,7 +290,8 @@ class IfChangedTests(SimpleTestCase):
yield 1
yield 2
# Simulate that another thread is now rendering.
- # When the IfChangeNode stores state at 'self' it stays at '3' and skip the last yielded value below.
+ # When the IfChangeNode stores state at 'self' it stays at '3' and
+ # skip the last yielded value below.
iter2 = iter([1, 2, 3])
output2 = template.render(
Context({"foo": range(3), "get_value": lambda: next(iter2)})
@@ -319,7 +335,9 @@ class IfChangedTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- "template": '{% for x in vars %}{% include "include" %}{% endfor %}',
+ "template": (
+ '{% for x in vars %}{% include "include" %}{% endfor %}'
+ ),
"include": "{% ifchanged %}{{ x }}{% endifchanged %}",
},
),
@@ -335,7 +353,10 @@ class IfChangedTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- "template": '{% for x in vars %}{% include "include" %}{% include "include" %}{% endfor %}',
+ "template": (
+ '{% for x in vars %}{% include "include" %}'
+ '{% include "include" %}{% endfor %}'
+ ),
"include": "{% ifchanged %}{{ x }}{% endifchanged %}",
},
),
diff --git a/tests/template_tests/syntax_tests/test_include.py b/tests/template_tests/syntax_tests/test_include.py
index add2ca139f..3ee99b3798 100644
--- a/tests/template_tests/syntax_tests/test_include.py
+++ b/tests/template_tests/syntax_tests/test_include.py
@@ -73,9 +73,12 @@ class IncludeTagTests(SimpleTestCase):
@setup(
{
- "include09": "{{ first }}--"
- '{% include "basic-syntax03" with first=second|lower|upper second=first|upper %}'
- "--{{ second }}"
+ "include09": (
+ "{{ first }}--"
+ '{% include "basic-syntax03" with '
+ "first=second|lower|upper second=first|upper %}"
+ "--{{ second }}"
+ )
},
basic_templates,
)
@@ -117,7 +120,9 @@ class IncludeTagTests(SimpleTestCase):
@setup(
{
- "include13": '{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}'
+ "include13": (
+ '{% autoescape off %}{% include "basic-syntax03" %}{% endautoescape %}'
+ )
},
basic_templates,
)
@@ -350,7 +355,9 @@ class IncludeTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- "template": '{% for x in vars %}{% include "include" %}{% endfor %}',
+ "template": (
+ '{% for x in vars %}{% include "include" %}{% endfor %}'
+ ),
"include": '{% include "next" %}',
"next": "{% load custom %}{% counter %}",
},
diff --git a/tests/template_tests/syntax_tests/test_invalid_string.py b/tests/template_tests/syntax_tests/test_invalid_string.py
index e65ac938ec..d8601febf1 100644
--- a/tests/template_tests/syntax_tests/test_invalid_string.py
+++ b/tests/template_tests/syntax_tests/test_invalid_string.py
@@ -55,7 +55,9 @@ class InvalidStringTests(SimpleTestCase):
@setup(
{
- "invalidstr07": "{% load i18n %}{% blocktranslate %}{{ var }}{% endblocktranslate %}"
+ "invalidstr07": (
+ "{% load i18n %}{% blocktranslate %}{{ var }}{% endblocktranslate %}"
+ )
}
)
def test_invalidstr07(self):
diff --git a/tests/template_tests/syntax_tests/test_load.py b/tests/template_tests/syntax_tests/test_load.py
index ae5f1d4b48..a13871b247 100644
--- a/tests/template_tests/syntax_tests/test_load.py
+++ b/tests/template_tests/syntax_tests/test_load.py
@@ -12,7 +12,9 @@ class LoadTagTests(SimpleTestCase):
@setup(
{
- "load01": '{% load testtags subpackage.echo %}{% echo test %} {% echo2 "test" %}'
+ "load01": (
+ '{% load testtags subpackage.echo %}{% echo test %} {% echo2 "test" %}'
+ )
}
)
def test_load01(self):
@@ -64,24 +66,36 @@ class LoadTagTests(SimpleTestCase):
@setup({"load08": "{% load echo other_echo bad_tag from %}"})
def test_load08(self):
- msg = "'echo' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'echo' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load08")
@setup({"load09": "{% load from testtags %}"})
def test_load09(self):
- msg = "'from' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'from' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load09")
@setup({"load10": "{% load echo from bad_library %}"})
def test_load10(self):
- msg = "'bad_library' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'bad_library' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load10")
@setup({"load12": "{% load subpackage.missing %}"})
def test_load12(self):
- msg = "'subpackage.missing' is not a registered tag library. Must be one of:\nsubpackage.echo\ntesttags"
+ msg = (
+ "'subpackage.missing' is not a registered tag library. Must be one of:\n"
+ "subpackage.echo\ntesttags"
+ )
with self.assertRaisesMessage(TemplateSyntaxError, msg):
self.engine.get_template("load12")
diff --git a/tests/template_tests/syntax_tests/test_named_endblock.py b/tests/template_tests/syntax_tests/test_named_endblock.py
index 2230edf52b..7469a28778 100644
--- a/tests/template_tests/syntax_tests/test_named_endblock.py
+++ b/tests/template_tests/syntax_tests/test_named_endblock.py
@@ -48,7 +48,9 @@ class NamedEndblockTests(SimpleTestCase):
@setup(
{
- "namedendblocks05": "1{% block first %}_{% block second %}2{% endblock first %}"
+ "namedendblocks05": (
+ "1{% block first %}_{% block second %}2{% endblock first %}"
+ )
}
)
def test_namedendblocks05(self):
diff --git a/tests/template_tests/syntax_tests/test_resetcycle.py b/tests/template_tests/syntax_tests/test_resetcycle.py
index 6d7365a6ec..fb67b3368e 100644
--- a/tests/template_tests/syntax_tests/test_resetcycle.py
+++ b/tests/template_tests/syntax_tests/test_resetcycle.py
@@ -33,7 +33,9 @@ class ResetCycleTagTests(SimpleTestCase):
@setup(
{
- "resetcycle05": "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}"
+ "resetcycle05": (
+ "{% for i in test %}{% cycle 'a' 'b' %}{% resetcycle %}{% endfor %}"
+ )
}
)
def test_resetcycle05(self):
diff --git a/tests/template_tests/syntax_tests/test_spaceless.py b/tests/template_tests/syntax_tests/test_spaceless.py
index 8bb20dba6c..e86c60f06b 100644
--- a/tests/template_tests/syntax_tests/test_spaceless.py
+++ b/tests/template_tests/syntax_tests/test_spaceless.py
@@ -6,7 +6,9 @@ from ..utils import setup
class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless01": "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}"
+ "spaceless01": (
+ "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}"
+ )
}
)
def test_spaceless01(self):
@@ -15,7 +17,9 @@ class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless02": "{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}"
+ "spaceless02": (
+ "{% spaceless %} <b> \n <i> text </i> \n </b> {% endspaceless %}"
+ )
}
)
def test_spaceless02(self):
@@ -29,7 +33,9 @@ class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless04": "{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}"
+ "spaceless04": (
+ "{% spaceless %}<b> <i>{{ text }}</i> </b>{% endspaceless %}"
+ )
}
)
def test_spaceless04(self):
@@ -49,7 +55,9 @@ class SpacelessTagTests(SimpleTestCase):
@setup(
{
- "spaceless06": "{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}"
+ "spaceless06": (
+ "{% spaceless %}<b> <i>{{ text|safe }}</i> </b>{% endspaceless %}"
+ )
}
)
def test_spaceless06(self):
diff --git a/tests/template_tests/syntax_tests/test_static.py b/tests/template_tests/syntax_tests/test_static.py
index cd63350cb5..63265f57f3 100644
--- a/tests/template_tests/syntax_tests/test_static.py
+++ b/tests/template_tests/syntax_tests/test_static.py
@@ -44,7 +44,10 @@ class StaticTagTests(SimpleTestCase):
@setup(
{
- "t": "{% load static %}{% get_media_prefix ad media_prefix %}{{ media_prefix }}"
+ "t": (
+ "{% load static %}{% get_media_prefix ad media_prefix %}"
+ "{{ media_prefix }}"
+ )
}
)
def test_static_prefixtag_without_as(self):
@@ -66,7 +69,9 @@ class StaticTagTests(SimpleTestCase):
@setup(
{
- "static-statictag03": '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'
+ "static-statictag03": (
+ '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'
+ )
}
)
def test_static_statictag03(self):
@@ -84,7 +89,9 @@ class StaticTagTests(SimpleTestCase):
@setup(
{
- "static-statictag05": '{% load static %}{% static "special?chars&quoted.html" %}'
+ "static-statictag05": (
+ '{% load static %}{% static "special?chars&quoted.html" %}'
+ )
}
)
def test_static_quotes_urls(self):
diff --git a/tests/template_tests/syntax_tests/test_verbatim.py b/tests/template_tests/syntax_tests/test_verbatim.py
index afb08e013a..16e0239177 100644
--- a/tests/template_tests/syntax_tests/test_verbatim.py
+++ b/tests/template_tests/syntax_tests/test_verbatim.py
@@ -24,7 +24,9 @@ class VerbatimTagTests(SimpleTestCase):
@setup(
{
- "verbatim-tag04": "{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}"
+ "verbatim-tag04": (
+ "{% verbatim %}{% verbatim %}{% endverbatim %}{% endverbatim %}"
+ )
}
)
def test_verbatim_tag04(self):
@@ -33,7 +35,9 @@ class VerbatimTagTests(SimpleTestCase):
@setup(
{
- "verbatim-tag05": "{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}"
+ "verbatim-tag05": (
+ "{% verbatim %}{% endverbatim %}{% verbatim %}{% endverbatim %}"
+ )
}
)
def test_verbatim_tag05(self):
diff --git a/tests/template_tests/templatetags/inclusion.py b/tests/template_tests/templatetags/inclusion.py
index f9e457bbc1..c4455e4fa4 100644
--- a/tests/template_tests/templatetags/inclusion.py
+++ b/tests/template_tests/templatetags/inclusion.py
@@ -75,7 +75,9 @@ inclusion_explicit_no_context_from_template.anything = (
def inclusion_no_params_with_context(context):
"""Expected inclusion_no_params_with_context __doc__"""
return {
- "result": "inclusion_no_params_with_context - Expected result (context value: %s)"
+ "result": (
+ "inclusion_no_params_with_context - Expected result (context value: %s)"
+ )
% context["value"]
}
@@ -90,9 +92,10 @@ def inclusion_no_params_with_context_from_template(context):
"""Expected inclusion_no_params_with_context_from_template __doc__"""
return {
"result": (
- "inclusion_no_params_with_context_from_template - Expected result (context value: %s)"
- % context["value"]
+ "inclusion_no_params_with_context_from_template - Expected result (context "
+ "value: %s)"
)
+ % context["value"]
}
@@ -105,7 +108,9 @@ inclusion_no_params_with_context_from_template.anything = (
def inclusion_params_and_context(context, arg):
"""Expected inclusion_params_and_context __doc__"""
return {
- "result": "inclusion_params_and_context - Expected result (context value: %s): %s"
+ "result": (
+ "inclusion_params_and_context - Expected result (context value: %s): %s"
+ )
% (context["value"], arg)
}
diff --git a/tests/template_tests/test_custom.py b/tests/template_tests/test_custom.py
index acfb6890a5..1697d16ef5 100644
--- a/tests/template_tests/test_custom.py
+++ b/tests/template_tests/test_custom.py
@@ -111,8 +111,11 @@ class SimpleTagTests(TagTestCase):
"simple_only_unlimited_args - Expected result: 37, 42, 56, 89",
),
(
- '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}',
- "simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4",
+ "{% load custom %}"
+ '{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" '
+ "four=1|add:3 %}",
+ "simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / "
+ "eggs=scrambled, four=4",
),
]
@@ -141,7 +144,8 @@ class SimpleTagTests(TagTestCase):
"{% load custom %}{% simple_one_default 37 42 56 %}",
),
(
- "'simple_keyword_only_param' did not receive value(s) for the argument(s): 'kwarg'",
+ "'simple_keyword_only_param' did not receive value(s) for the "
+ "argument(s): 'kwarg'",
"{% load custom %}{% simple_keyword_only_param %}",
),
(
@@ -156,12 +160,18 @@ class SimpleTagTests(TagTestCase):
"kwarg=37 %}",
),
(
- "'simple_unlimited_args_kwargs' received some positional argument(s) after some keyword argument(s)",
- '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}',
+ "'simple_unlimited_args_kwargs' received some positional argument(s) "
+ "after some keyword argument(s)",
+ "{% load custom %}"
+ "{% simple_unlimited_args_kwargs 37 40|add:2 "
+ 'eggs="scrambled" 56 four=1|add:3 %}',
),
(
- "'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
- '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}',
+ "'simple_unlimited_args_kwargs' received multiple values for keyword "
+ "argument 'eggs'",
+ "{% load custom %}"
+ "{% simple_unlimited_args_kwargs 37 "
+ 'eggs="scrambled" eggs="scrambled" %}',
),
]
@@ -252,11 +262,13 @@ class InclusionTagTests(TagTestCase):
),
(
"{% load inclusion %}{% inclusion_no_params_with_context %}",
- "inclusion_no_params_with_context - Expected result (context value: 42)\n",
+ "inclusion_no_params_with_context - Expected result (context value: "
+ "42)\n",
),
(
"{% load inclusion %}{% inclusion_params_and_context 37 %}",
- "inclusion_params_and_context - Expected result (context value: 42): 37\n",
+ "inclusion_params_and_context - Expected result (context value: 42): "
+ "37\n",
),
(
"{% load inclusion %}{% inclusion_two_params 37 42 %}",
@@ -299,8 +311,11 @@ class InclusionTagTests(TagTestCase):
"inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n",
),
(
- '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}',
- "inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n",
+ "{% load inclusion %}"
+ '{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" '
+ "four=1|add:3 %}",
+ "inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / "
+ "eggs=scrambled, four=4\n",
),
]
@@ -312,7 +327,8 @@ class InclusionTagTests(TagTestCase):
errors = [
(
"'inclusion_one_default' received unexpected keyword argument 'three'",
- '{% load inclusion %}{% inclusion_one_default 99 two="hello" three="foo" %}',
+ "{% load inclusion %}"
+ '{% inclusion_one_default 99 two="hello" three="foo" %}',
),
(
"'inclusion_two_params' received too many positional arguments",
@@ -323,7 +339,8 @@ class InclusionTagTests(TagTestCase):
"{% load inclusion %}{% inclusion_one_default 37 42 56 %}",
),
(
- "'inclusion_one_default' did not receive value(s) for the argument(s): 'one'",
+ "'inclusion_one_default' did not receive value(s) for the argument(s): "
+ "'one'",
"{% load inclusion %}{% inclusion_one_default %}",
),
(
@@ -333,17 +350,23 @@ class InclusionTagTests(TagTestCase):
"kwarg=37 kwarg=42 %}",
),
(
- "'inclusion_unlimited_args' did not receive value(s) for the argument(s): 'one'",
+ "'inclusion_unlimited_args' did not receive value(s) for the "
+ "argument(s): 'one'",
"{% load inclusion %}{% inclusion_unlimited_args %}",
),
(
- "'inclusion_unlimited_args_kwargs' received some positional argument(s) "
- "after some keyword argument(s)",
- '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="boiled" 56 four=1|add:3 %}',
+ "'inclusion_unlimited_args_kwargs' received some positional "
+ "argument(s) after some keyword argument(s)",
+ "{% load inclusion %}"
+ "{% inclusion_unlimited_args_kwargs 37 40|add:2 "
+ 'eggs="boiled" 56 four=1|add:3 %}',
),
(
- "'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
- '{% load inclusion %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}',
+ "'inclusion_unlimited_args_kwargs' received multiple values for "
+ "keyword argument 'eggs'",
+ "{% load inclusion %}"
+ "{% inclusion_unlimited_args_kwargs 37 "
+ 'eggs="scrambled" eggs="scrambled" %}',
),
]
@@ -385,16 +408,21 @@ class InclusionTagTests(TagTestCase):
"inclusion_one_param_from_template - Expected result: 37\n",
),
(
- "{% load inclusion %}{% inclusion_explicit_no_context_from_template 37 %}",
+ "{% load inclusion %}"
+ "{% inclusion_explicit_no_context_from_template 37 %}",
"inclusion_explicit_no_context_from_template - Expected result: 37\n",
),
(
- "{% load inclusion %}{% inclusion_no_params_with_context_from_template %}",
- "inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n",
+ "{% load inclusion %}"
+ "{% inclusion_no_params_with_context_from_template %}",
+ "inclusion_no_params_with_context_from_template - Expected result "
+ "(context value: 42)\n",
),
(
- "{% load inclusion %}{% inclusion_params_and_context_from_template 37 %}",
- "inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n",
+ "{% load inclusion %}"
+ "{% inclusion_params_and_context_from_template 37 %}",
+ "inclusion_params_and_context_from_template - Expected result (context "
+ "value: 42): 37\n",
),
(
"{% load inclusion %}{% inclusion_two_params_from_template 37 42 %}",
@@ -413,16 +441,20 @@ class InclusionTagTests(TagTestCase):
"inclusion_unlimited_args_from_template - Expected result: 37, hi\n",
),
(
- "{% load inclusion %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}",
- "inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n",
+ "{% load inclusion %}"
+ "{% inclusion_unlimited_args_from_template 37 42 56 89 %}",
+ "inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, "
+ "89\n",
),
(
"{% load inclusion %}{% inclusion_only_unlimited_args_from_template %}",
"inclusion_only_unlimited_args_from_template - Expected result: \n",
),
(
- "{% load inclusion %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}",
- "inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n",
+ "{% load inclusion %}"
+ "{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}",
+ "inclusion_only_unlimited_args_from_template - Expected result: 37, "
+ "42, 56, 89\n",
),
]
diff --git a/tests/template_tests/test_extends.py b/tests/template_tests/test_extends.py
index bce5162d83..ce1838654b 100644
--- a/tests/template_tests/test_extends.py
+++ b/tests/template_tests/test_extends.py
@@ -45,13 +45,16 @@ class ExtendsBehaviorTests(SimpleTestCase):
"django.template.loaders.locmem.Loader",
{
"one.html": (
- '{% extends "one.html" %}{% block content %}{{ block.super }} locmem-one{% endblock %}'
+ '{% extends "one.html" %}{% block content %}'
+ "{{ block.super }} locmem-one{% endblock %}"
),
"two.html": (
- '{% extends "two.html" %}{% block content %}{{ block.super }} locmem-two{% endblock %}'
+ '{% extends "two.html" %}{% block content %}'
+ "{{ block.super }} locmem-two{% endblock %}"
),
"three.html": (
- '{% extends "three.html" %}{% block content %}{{ block.super }} locmem-three{% endblock %}'
+ '{% extends "three.html" %}{% block content %}'
+ "{{ block.super }} locmem-three{% endblock %}"
),
},
),
@@ -126,7 +129,10 @@ class ExtendsBehaviorTests(SimpleTestCase):
[
"django.template.loaders.locmem.Loader",
{
- "base.html": '{% extends "base.html" %}{% block content %}{{ block.super }} loader1{% endblock %}',
+ "base.html": (
+ '{% extends "base.html" %}{% block content %}'
+ "{{ block.super }} loader1{% endblock %}"
+ ),
},
],
[
@@ -151,14 +157,23 @@ class ExtendsBehaviorTests(SimpleTestCase):
[
"django.template.loaders.locmem.Loader",
{
- "base.html": "{% extends 'base.html' %}{% block base %}{{ block.super }}2{% endblock %}",
- "included.html": "{% extends 'included.html' %}{% block included %}{{ block.super }}B{% endblock %}",
+ "base.html": (
+ "{% extends 'base.html' %}{% block base %}{{ block.super }}"
+ "2{% endblock %}"
+ ),
+ "included.html": (
+ "{% extends 'included.html' %}{% block included %}"
+ "{{ block.super }}B{% endblock %}"
+ ),
},
],
[
"django.template.loaders.locmem.Loader",
{
- "base.html": "{% block base %}1{% endblock %}{% include 'included.html' %}",
+ "base.html": (
+ "{% block base %}1{% endblock %}"
+ "{% include 'included.html' %}"
+ ),
"included.html": "{% block included %}A{% endblock %}",
},
],
diff --git a/tests/template_tests/test_parser.py b/tests/template_tests/test_parser.py
index ee9b9b1b12..e40a5611e2 100644
--- a/tests/template_tests/test_parser.py
+++ b/tests/template_tests/test_parser.py
@@ -1,5 +1,6 @@
"""
-Testing some internals of the template processing. These are *not* examples to be copied in user code.
+Testing some internals of the template processing.
+These are *not* examples to be copied in user code.
"""
from django.template import Library, TemplateSyntaxError
from django.template.base import (
diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py
index 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 = """<?xml version="1.0" encoding="utf-8"?>
- <library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>
+ <library><book><title>Blink</title><author>Malcolm Gladwell</author></book>
+ </library>
"""
response = self.client.post(
"/raw_post_view/", test_doc, content_type="text/xml"
@@ -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):
<tr><th><label for="id_last_name">Last name:</label></th>
<td><input type="text" id="id_last_name" name="last_name" value="Lennon" /></td></tr>
<tr><th><label for="id_birthday">Birthday:</label></th>
-<td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""",
+<td><input type="text" value="1940-10-9" name="birthday" id="id_birthday" /></td></tr>""", # NOQA
"""
<tr><th>
<label for="id_first_name">First name:</label></th><td>
@@ -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):
(
(
"&<>",
- '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>',
+ '<script id="test_id" type="application/json">'
+ '"\\u0026\\u003C\\u003E"</script>',
)
),
# "<", ">" and "&" are quoted inside JSON objects
(
{"a": "<script>test&ing</script>"},
'<script id="test_id" type="application/json">'
- '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>',
+ '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}'
+ "</script>",
),
# Lazy strings are quoted
(
lazystr("&<>"),
- '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"</script>',
+ '<script id="test_id" type="application/json">"\\u0026\\u003C\\u003E"'
+ "</script>",
),
(
{"a": lazystr("<script>test&ing</script>")},
'<script id="test_id" type="application/json">'
- '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}</script>',
+ '{"a": "\\u003Cscript\\u003Etest\\u0026ing\\u003C/script\\u003E"}'
+ "</script>",
),
)
for arg, expected in tests:
@@ -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 <a href="http://google.com/?q=">google.com/?q=</a>! and see.',
+ 'Search for <a href="http://google.com/?q=">google.com/?q=</a>! and '
+ "see.",
),
(
"Search for google.com/?q=1&lt! and see.",
- 'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1&lt</a>! and see.',
+ 'Search for <a href="http://google.com/?q=1%3C">google.com/?q=1&lt'
+ "</a>! and see.",
),
(
lazystr("Search for google.com/?q=!"),
diff --git a/tests/utils_tests/test_jslex.py b/tests/utils_tests/test_jslex.py
index 0963dd0f16..ee13eb4d64 100644
--- a/tests/utils_tests/test_jslex.py
+++ b/tests/utils_tests/test_jslex.py
@@ -72,7 +72,7 @@ class JsTokensTest(SimpleTestCase):
(r"a=/\//,1", ["id a", "punct =", r"regex /\//", "punct ,", "dnum 1"]),
# next two are from https://www-archive.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions # NOQA
(
- """for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);}""",
+ 'for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);}',
[
"keyword for",
"punct (",
@@ -104,7 +104,7 @@ class JsTokensTest(SimpleTestCase):
],
),
(
- """for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);}""",
+ 'for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);}',
[
"keyword for",
"punct (",
@@ -240,7 +240,8 @@ class JsTokensTest(SimpleTestCase):
],
),
(
- r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """,
+ r' this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\")'
+ r'.replace(/"/g, "\\\"") + "\")"; ',
[
"keyword this",
"punct .",
diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py
index 131d893a44..9ccae595f4 100644
--- a/tests/utils_tests/test_lazyobject.py
+++ b/tests/utils_tests/test_lazyobject.py
@@ -126,7 +126,8 @@ class LazyObjectTestCase(TestCase):
for needle, haystack in test_data:
self.assertIn(needle, self.lazy_wrap(haystack))
- # __contains__ doesn't work when the haystack is a string and the needle a LazyObject
+ # __contains__ doesn't work when the haystack is a string and the
+ # needle a LazyObject.
for needle_haystack in test_data[1:]:
self.assertIn(self.lazy_wrap(needle), haystack)
self.assertIn(self.lazy_wrap(needle), self.lazy_wrap(haystack))
diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py
index caab19a55d..cb2959fe15 100644
--- a/tests/utils_tests/test_text.py
+++ b/tests/utils_tests/test_text.py
@@ -122,10 +122,12 @@ class TestUtilsText(SimpleTestCase):
def test_truncate_html_words(self):
truncator = text.Truncator(
- '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>'
+ '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>'
+ "</strong></p>"
)
self.assertEqual(
- '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em></strong></p>',
+ '<p id="par"><strong><em>The quick brown fox jumped over the lazy dog.</em>'
+ "</strong></p>",
truncator.words(10, html=True),
)
self.assertEqual(
@@ -143,7 +145,8 @@ class TestUtilsText(SimpleTestCase):
# Test with new line inside tag
truncator = text.Truncator(
- '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over the lazy dog.</p>'
+ '<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over '
+ "the lazy dog.</p>"
)
self.assertEqual(
'<p>The quick <a href="xyz.html"\n id="mylink">brown…</a></p>',
diff --git a/tests/validation/test_error_messages.py b/tests/validation/test_error_messages.py
index 470c055eef..ffc660aad6 100644
--- a/tests/validation/test_error_messages.py
+++ b/tests/validation/test_error_messages.py
@@ -52,28 +52,32 @@ class ValidationMessagesTest(TestCase):
f,
"fõo",
[
- "“fõo” value has an invalid date format. It must be in YYYY-MM-DD format."
+ "“fõo” value has an invalid date format. It must be in YYYY-MM-DD "
+ "format."
],
)
self._test_validation_messages(
f,
"aaaa-10-10",
[
- "“aaaa-10-10” value has an invalid date format. It must be in YYYY-MM-DD format."
+ "“aaaa-10-10” value has an invalid date format. It must be in "
+ "YYYY-MM-DD format."
],
)
self._test_validation_messages(
f,
"2011-13-10",
[
- "“2011-13-10” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ "“2011-13-10” value has the correct format (YYYY-MM-DD) but it is an "
+ "invalid date."
],
)
self._test_validation_messages(
f,
"2011-10-32",
[
- "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an "
+ "invalid date."
],
)
@@ -84,7 +88,8 @@ class ValidationMessagesTest(TestCase):
f,
"fõo",
[
- "“fõo” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
+ "“fõo” value has an invalid format. It must be in "
+ "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."
],
)
# Correct format but invalid date
@@ -92,7 +97,8 @@ class ValidationMessagesTest(TestCase):
f,
"2011-10-32",
[
- "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an invalid date."
+ "“2011-10-32” value has the correct format (YYYY-MM-DD) but it is an "
+ "invalid date."
],
)
# Correct format but invalid date/time
@@ -100,8 +106,8 @@ class ValidationMessagesTest(TestCase):
f,
"2011-10-32 10:10",
[
- "“2011-10-32 10:10” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
- "but it is an invalid date/time."
+ "“2011-10-32 10:10” value has the correct format "
+ "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time."
],
)
@@ -112,7 +118,8 @@ class ValidationMessagesTest(TestCase):
f,
"fõo",
[
- "“fõo” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."
+ "“fõo” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] "
+ "format."
],
)
# Correct format but invalid time
@@ -120,6 +127,7 @@ class ValidationMessagesTest(TestCase):
f,
"25:50",
[
- "“25:50” value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an invalid time."
+ "“25:50” value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is "
+ "an invalid time."
],
)
diff --git a/tests/view_tests/tests/test_csrf.py b/tests/view_tests/tests/test_csrf.py
index c0f812431d..2f4542c143 100644
--- a/tests/view_tests/tests/test_csrf.py
+++ b/tests/view_tests/tests/test_csrf.py
@@ -96,7 +96,9 @@ class CsrfViewTests(SimpleTestCase):
(
"django.template.loaders.locmem.Loader",
{
- CSRF_FAILURE_TEMPLATE_NAME: "Test template for CSRF failure"
+ CSRF_FAILURE_TEMPLATE_NAME: (
+ "Test template for CSRF failure"
+ )
},
),
],
diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py
index 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
- # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
+ # '<div class="context" id="c38123208">',
+ # not '<div class="context" id="c38,123,208"'.
self.assertContains(response, '<div class="context" id="', status_code=500)
match = re.search(
b'<div class="context" id="(?P<id>[^"]+)">', response.content
@@ -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 &lt;source code not available&gt;',
+ '"generated", line 2, in funcName\n'
+ " &lt;source code not available&gt;",
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(
- '<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre></td>',
+ '<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre>'
+ "</td>",
html,
)
diff --git a/tests/view_tests/tests/test_defaults.py b/tests/view_tests/tests/test_defaults.py
index 0c4fc7c7da..f99066e5bb 100644
--- a/tests/view_tests/tests/test_defaults.py
+++ b/tests/view_tests/tests/test_defaults.py
@@ -111,8 +111,11 @@ class DefaultsTests(TestCase):
(
"django.template.loaders.locmem.Loader",
{
- "404.html": "This is a test template for a 404 error "
- "(path: {{ request_path }}, exception: {{ exception }}).",
+ "404.html": (
+ "This is a test template for a 404 error "
+ "(path: {{ request_path }}, "
+ "exception: {{ exception }})."
+ ),
"500.html": "This is a test template for a 500 error.",
},
),
diff --git a/tests/view_tests/tests/test_i18n.py b/tests/view_tests/tests/test_i18n.py
index 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!",
],
)