diff options
| author | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2024-01-26 12:45:07 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-01-26 12:45:07 +0100 |
| commit | 305757aec19c9d5111e4d76095ae0acd66163e4b (patch) | |
| tree | 04aa017e66c06b3b19cb466ed4e1d73cd871523d /tests | |
| parent | 3f6d939c62efd967f548c27a265748cc2cc47ca5 (diff) | |
Applied Black's 2024 stable style.
https://github.com/psf/black/releases/tag/24.1.0
Diffstat (limited to 'tests')
91 files changed, 407 insertions, 259 deletions
diff --git a/tests/admin_changelist/test_date_hierarchy.py b/tests/admin_changelist/test_date_hierarchy.py index 03afaa33d9..94a6a8eb6c 100644 --- a/tests/admin_changelist/test_date_hierarchy.py +++ b/tests/admin_changelist/test_date_hierarchy.py @@ -90,7 +90,8 @@ class DateHierarchyTests(TestCase): {"year": 2017, "month": 12, "day": 0}, ) for invalid_query in tests: - with self.subTest(query=invalid_query), self.assertRaises( - IncorrectLookupParameters + with ( + self.subTest(query=invalid_query), + self.assertRaises(IncorrectLookupParameters), ): self.assertDateParams(invalid_query, None, None) diff --git a/tests/admin_inlines/models.py b/tests/admin_inlines/models.py index a8d2ee02e1..eca5bae422 100644 --- a/tests/admin_inlines/models.py +++ b/tests/admin_inlines/models.py @@ -1,6 +1,7 @@ """ Testing of admin inline formsets. """ + import random from django.contrib.contenttypes.fields import GenericForeignKey diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py index 7f39d7fcfc..50e8d4a3b1 100644 --- a/tests/admin_scripts/tests.py +++ b/tests/admin_scripts/tests.py @@ -3,6 +3,7 @@ A series of tests to establish that the command-line management tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ + import os import re import shutil @@ -757,7 +758,9 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase): with open(os.path.join(app_path, "apps.py"), encoding="utf8") as f: content = f.read() self.assertIn("class こんにちはConfig(AppConfig)", content) - self.assertIn('name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content) + self.assertIn( + 'name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content + ) def test_builtin_command(self): """ diff --git a/tests/admin_views/custom_has_permission_admin.py b/tests/admin_views/custom_has_permission_admin.py index 6dc2011b24..17b6498aab 100644 --- a/tests/admin_views/custom_has_permission_admin.py +++ b/tests/admin_views/custom_has_permission_admin.py @@ -1,6 +1,7 @@ """ A custom AdminSite for AdminViewPermissionsTest.test_login_has_permission(). """ + from django.contrib import admin from django.contrib.auth import get_permission_codename from django.contrib.auth.forms import AuthenticationForm diff --git a/tests/admin_views/customadmin.py b/tests/admin_views/customadmin.py index e3429ec4bc..4b30c5c30f 100644 --- a/tests/admin_views/customadmin.py +++ b/tests/admin_views/customadmin.py @@ -1,6 +1,7 @@ """ A second, custom AdminSite -- see tests.CustomAdminSiteTests. """ + from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py index bfb3919b23..9199bf3eba 100644 --- a/tests/aggregation_regress/tests.py +++ b/tests/aggregation_regress/tests.py @@ -1564,8 +1564,9 @@ class AggregationTests(TestCase): "django.db.connection.features.allows_group_by_selected_pks_on_model", return_value=True, ): - with mock.patch.object(Book._meta, "managed", False), mock.patch.object( - Author._meta, "managed", False + with ( + mock.patch.object(Book._meta, "managed", False), + mock.patch.object(Author._meta, "managed", False), ): _, _, grouping = qs.query.get_compiler(using="default").pre_sql_setup() self.assertEqual(len(grouping), 2) diff --git a/tests/auth_tests/models/custom_permissions.py b/tests/auth_tests/models/custom_permissions.py index 52d28bd276..385de4e846 100644 --- a/tests/auth_tests/models/custom_permissions.py +++ b/tests/auth_tests/models/custom_permissions.py @@ -3,6 +3,7 @@ The CustomPermissionsUser users email as the identifier, but uses the normal Django permissions model. This allows us to check that the PermissionsMixin includes everything that is needed to interact with the ModelBackend. """ + from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py index 14d71572da..14604cd2e6 100644 --- a/tests/auth_tests/test_forms.py +++ b/tests/auth_tests/test_forms.py @@ -486,8 +486,9 @@ class AuthenticationFormTest(TestDataMixin, TestCase): user_login_failed.disconnect(signal_handler) def test_inactive_user_i18n(self): - with self.settings(USE_I18N=True), translation.override( - "pt-br", deactivate=True + with ( + self.settings(USE_I18N=True), + translation.override("pt-br", deactivate=True), ): # The user is inactive. data = { @@ -906,9 +907,9 @@ class UserChangeFormTest(TestDataMixin, TestCase): class MyUserForm(UserChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self.fields[ - "groups" - ].help_text = "These groups give users different permissions" + self.fields["groups"].help_text = ( + "These groups give users different permissions" + ) class Meta(UserChangeForm.Meta): fields = ("groups",) diff --git a/tests/auth_tests/test_hashers.py b/tests/auth_tests/test_hashers.py index e0b640a998..1b0d2c65be 100644 --- a/tests/auth_tests/test_hashers.py +++ b/tests/auth_tests/test_hashers.py @@ -213,8 +213,9 @@ class TestUtilsHashPass(SimpleTestCase): with mock.patch.object(hasher, "rounds", 4): encoded = make_password("letmein", hasher="bcrypt") - with mock.patch.object(hasher, "rounds", 6), mock.patch.object( - hasher, "encode", side_effect=hasher.encode + with ( + mock.patch.object(hasher, "rounds", 6), + mock.patch.object(hasher, "encode", side_effect=hasher.encode), ): hasher.harden_runtime("wrong_password", encoded) @@ -388,8 +389,9 @@ class TestUtilsHashPass(SimpleTestCase): with mock.patch.object(hasher, "iterations", 1): encoded = make_password("letmein") - with mock.patch.object(hasher, "iterations", 6), mock.patch.object( - hasher, "encode", side_effect=hasher.encode + with ( + mock.patch.object(hasher, "iterations", 6), + mock.patch.object(hasher, "encode", side_effect=hasher.encode), ): hasher.harden_runtime("wrong_password", encoded) @@ -437,8 +439,9 @@ class TestUtilsHashPass(SimpleTestCase): hasher = get_hasher("default") encoded = make_password("letmein") - with mock.patch.object(hasher, "harden_runtime"), mock.patch.object( - hasher, "must_update", return_value=True + with ( + mock.patch.object(hasher, "harden_runtime"), + mock.patch.object(hasher, "must_update", return_value=True), ): # Correct password supplied, no hardening needed check_password("letmein", encoded) diff --git a/tests/auth_tests/test_views.py b/tests/auth_tests/test_views.py index ba0a77a4dc..f4cf6ed2f4 100644 --- a/tests/auth_tests/test_views.py +++ b/tests/auth_tests/test_views.py @@ -818,9 +818,9 @@ class LoginTest(AuthViewsTestCase): # Use POST request to log in SessionMiddleware(get_response).process_request(req) CsrfViewMiddleware(get_response).process_view(req, LoginView.as_view(), (), {}) - req.META[ - "SERVER_NAME" - ] = "testserver" # Required to have redirect work in login view + req.META["SERVER_NAME"] = ( + "testserver" # Required to have redirect work in login view + ) req.META["SERVER_PORT"] = 80 resp = CsrfViewMiddleware(LoginView.as_view())(req) csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) diff --git a/tests/backends/base/test_base.py b/tests/backends/base/test_base.py index 9f2fa4e576..03356fbf10 100644 --- a/tests/backends/base/test_base.py +++ b/tests/backends/base/test_base.py @@ -168,8 +168,9 @@ class ExecuteWrapperTests(TestCase): def test_nested_wrapper_invoked(self): outer_wrapper = self.mock_wrapper() inner_wrapper = self.mock_wrapper() - with connection.execute_wrapper(outer_wrapper), connection.execute_wrapper( - inner_wrapper + with ( + connection.execute_wrapper(outer_wrapper), + connection.execute_wrapper(inner_wrapper), ): self.call_execute(connection) self.assertEqual(inner_wrapper.call_count, 1) @@ -182,8 +183,10 @@ class ExecuteWrapperTests(TestCase): wrapper = self.mock_wrapper() c = connection # This alias shortens the next line. - with c.execute_wrapper(wrapper), c.execute_wrapper(blocker), c.execute_wrapper( - wrapper + with ( + c.execute_wrapper(wrapper), + c.execute_wrapper(blocker), + c.execute_wrapper(wrapper), ): with c.cursor() as cursor: cursor.execute("The database never sees this") diff --git a/tests/backends/test_utils.py b/tests/backends/test_utils.py index 03d4b036fd..704498836e 100644 --- a/tests/backends/test_utils.py +++ b/tests/backends/test_utils.py @@ -1,4 +1,5 @@ """Tests for django.db.backends.utils""" + from decimal import Decimal, Rounded from django.db import NotSupportedError, connection diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 5c562682f0..08a21d8ded 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -1,4 +1,5 @@ """Tests related to django.db.backends that haven't been organized.""" + import datetime import threading import unittest diff --git a/tests/bash_completion/tests.py b/tests/bash_completion/tests.py index 856e351dfa..324e980937 100644 --- a/tests/bash_completion/tests.py +++ b/tests/bash_completion/tests.py @@ -1,6 +1,7 @@ """ A series of tests to establish that the command-line bash completion works. """ + import os import sys import unittest diff --git a/tests/basic/models.py b/tests/basic/models.py index 6802f825ff..236884f4cc 100644 --- a/tests/basic/models.py +++ b/tests/basic/models.py @@ -3,6 +3,7 @@ Bare-bones model This is a basic model with only two non-primary-key fields. """ + import uuid from django.db import models diff --git a/tests/check_framework/test_security.py b/tests/check_framework/test_security.py index b1839f48c3..cb035a90a4 100644 --- a/tests/check_framework/test_security.py +++ b/tests/check_framework/test_security.py @@ -593,8 +593,9 @@ class CheckReferrerPolicyTest(SimpleTestCase): ("strict-origin", "origin"), ) for value in tests: - with self.subTest(value=value), override_settings( - SECURE_REFERRER_POLICY=value + with ( + self.subTest(value=value), + override_settings(SECURE_REFERRER_POLICY=value), ): self.assertEqual(base.check_referrer_policy(None), []) @@ -663,8 +664,11 @@ class CheckCrossOriginOpenerPolicyTest(SimpleTestCase): def test_with_coop(self): tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"] for value in tests: - with self.subTest(value=value), override_settings( - SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + with ( + self.subTest(value=value), + override_settings( + SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + ), ): self.assertEqual(base.check_cross_origin_opener_policy(None), []) diff --git a/tests/contenttypes_tests/test_management.py b/tests/contenttypes_tests/test_management.py index eb472d80ce..14ff4e5952 100644 --- a/tests/contenttypes_tests/test_management.py +++ b/tests/contenttypes_tests/test_management.py @@ -88,9 +88,10 @@ class RemoveStaleContentTypesTests(TestCase): def test_contenttypes_removed_in_installed_apps_without_models(self): ContentType.objects.create(app_label="empty_models", model="Fake 1") ContentType.objects.create(app_label="no_models", model="Fake 2") - with mock.patch( - "builtins.input", return_value="yes" - ), captured_stdout() as stdout: + with ( + mock.patch("builtins.input", return_value="yes"), + captured_stdout() as stdout, + ): call_command("remove_stale_contenttypes", verbosity=2) self.assertNotIn( "Deleting stale content type 'empty_models | Fake 1'", @@ -106,9 +107,10 @@ class RemoveStaleContentTypesTests(TestCase): def test_contenttypes_removed_for_apps_not_in_installed_apps(self): ContentType.objects.create(app_label="empty_models", model="Fake 1") ContentType.objects.create(app_label="no_models", model="Fake 2") - with mock.patch( - "builtins.input", return_value="yes" - ), captured_stdout() as stdout: + with ( + mock.patch("builtins.input", return_value="yes"), + captured_stdout() as stdout, + ): call_command( "remove_stale_contenttypes", include_stale_apps=True, verbosity=2 ) diff --git a/tests/contenttypes_tests/test_models.py b/tests/contenttypes_tests/test_models.py index 02036de83f..88f715ceff 100644 --- a/tests/contenttypes_tests/test_models.py +++ b/tests/contenttypes_tests/test_models.py @@ -323,8 +323,9 @@ class ContentTypesMultidbTests(TestCase): db_for_read(). """ ContentType.objects.clear_cache() - with self.assertNumQueries(0, using="default"), self.assertNumQueries( - 1, using="other" + with ( + self.assertNumQueries(0, using="default"), + self.assertNumQueries(1, using="other"), ): ContentType.objects.get_for_model(Author) diff --git a/tests/contenttypes_tests/test_views.py b/tests/contenttypes_tests/test_views.py index 4d85d15065..75f39a7bab 100644 --- a/tests/contenttypes_tests/test_views.py +++ b/tests/contenttypes_tests/test_views.py @@ -150,10 +150,8 @@ class ContentTypesViewsSiteRelTests(TestCase): """ The shortcut view works if a model's ForeignKey to site is None. """ - get_model.side_effect = ( - lambda *args, **kwargs: MockSite - if args[0] == "sites.Site" - else ModelWithNullFKToSite + get_model.side_effect = lambda *args, **kwargs: ( + MockSite if args[0] == "sites.Site" else ModelWithNullFKToSite ) obj = ModelWithNullFKToSite.objects.create(title="title") @@ -172,10 +170,8 @@ class ContentTypesViewsSiteRelTests(TestCase): site if it's attached to the object or to the domain of the first site found in the m2m relationship. """ - get_model.side_effect = ( - lambda *args, **kwargs: MockSite - if args[0] == "sites.Site" - else ModelWithM2MToSite + get_model.side_effect = lambda *args, **kwargs: ( + MockSite if args[0] == "sites.Site" else ModelWithM2MToSite ) # get_current_site() will lookup a Site object, so these must match the diff --git a/tests/context_processors/tests.py b/tests/context_processors/tests.py index 23f9d59149..ba92ff8b05 100644 --- a/tests/context_processors/tests.py +++ b/tests/context_processors/tests.py @@ -1,6 +1,7 @@ """ Tests for Django's bundled context processors. """ + from django.test import SimpleTestCase, TestCase, override_settings diff --git a/tests/custom_lookups/tests.py b/tests/custom_lookups/tests.py index 8fc31d4e6b..f107c5320a 100644 --- a/tests/custom_lookups/tests.py +++ b/tests/custom_lookups/tests.py @@ -238,10 +238,11 @@ class LookupTests(TestCase): def test_custom_name_lookup(self): a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) - with register_lookup(models.DateField, YearTransform), register_lookup( - models.DateField, YearTransform, lookup_name="justtheyear" - ), register_lookup(YearTransform, Exactly), register_lookup( - YearTransform, Exactly, lookup_name="isactually" + with ( + register_lookup(models.DateField, YearTransform), + register_lookup(models.DateField, YearTransform, lookup_name="justtheyear"), + register_lookup(YearTransform, Exactly), + register_lookup(YearTransform, Exactly, lookup_name="isactually"), ): qs1 = Author.objects.filter(birthdate__testyear__exactly=1981) qs2 = Author.objects.filter(birthdate__justtheyear__isactually=1981) diff --git a/tests/db_functions/comparison/test_nullif.py b/tests/db_functions/comparison/test_nullif.py index 9839e6b4c5..cdbc3d6960 100644 --- a/tests/db_functions/comparison/test_nullif.py +++ b/tests/db_functions/comparison/test_nullif.py @@ -23,9 +23,11 @@ class NullIfTests(TestCase): [ ("smithj",), ( - "" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ), ], ) diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py index 29212b6e24..e576e6e464 100644 --- a/tests/db_functions/datetime/test_extract_trunc.py +++ b/tests/db_functions/datetime/test_extract_trunc.py @@ -113,9 +113,11 @@ class DateFunctionTests(TestCase): end_date=end_datetime.date() if end_datetime else None, start_time=start_datetime.time() if start_datetime else None, end_time=end_datetime.time() if end_datetime else None, - duration=(end_datetime - start_datetime) - if start_datetime and end_datetime - else None, + duration=( + (end_datetime - start_datetime) + if start_datetime and end_datetime + else None + ), ) def test_extract_year_exact_lookup(self): diff --git a/tests/db_functions/models.py b/tests/db_functions/models.py index d6a06511bc..c126f1bae1 100644 --- a/tests/db_functions/models.py +++ b/tests/db_functions/models.py @@ -1,6 +1,7 @@ """ Tests for built in Function expressions. """ + from django.db import models diff --git a/tests/db_functions/text/test_md5.py b/tests/db_functions/text/test_md5.py index fd0aec58f2..4fd66f0397 100644 --- a/tests/db_functions/text/test_md5.py +++ b/tests/db_functions/text/test_md5.py @@ -35,9 +35,11 @@ class MD5Tests(TestCase): "ca6d48f6772000141e66591aee49d56c", "bf2c13bc1154e3d2e7df848cbc8be73d", "d41d8cd98f00b204e9800998ecf8427e", - "d41d8cd98f00b204e9800998ecf8427e" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "d41d8cd98f00b204e9800998ecf8427e" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha1.py b/tests/db_functions/text/test_sha1.py index 175c5727ff..ef846d07aa 100644 --- a/tests/db_functions/text/test_sha1.py +++ b/tests/db_functions/text/test_sha1.py @@ -35,9 +35,11 @@ class SHA1Tests(TestCase): "0781e0745a2503e6ded05ed5bc554c421d781b0c", "198d15ea139de04060caf95bc3e0ec5883cba881", "da39a3ee5e6b4b0d3255bfef95601890afd80709", - "da39a3ee5e6b4b0d3255bfef95601890afd80709" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "da39a3ee5e6b4b0d3255bfef95601890afd80709" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha224.py b/tests/db_functions/text/test_sha224.py index a6254f43e3..60d9e378a6 100644 --- a/tests/db_functions/text/test_sha224.py +++ b/tests/db_functions/text/test_sha224.py @@ -37,9 +37,11 @@ class SHA224Tests(TestCase): "2297904883e78183cb118fc3dc21a610d60daada7b6ebdbc85139f4d", "eba942746e5855121d9d8f79e27dfdebed81adc85b6bf41591203080", "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", - "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha256.py b/tests/db_functions/text/test_sha256.py index b399dbecd3..0cf72783e7 100644 --- a/tests/db_functions/text/test_sha256.py +++ b/tests/db_functions/text/test_sha256.py @@ -35,9 +35,11 @@ class SHA256Tests(TestCase): "6e4cce20cd83fc7c202f21a8b2452a68509cf24d1c272a045b5e0cfc43f0d94e", "3ad2039e3ec0c88973ae1c0fce5a3dbafdd5a1627da0a92312c54ebfcf43988e", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha384.py b/tests/db_functions/text/test_sha384.py index 250cadda4a..a4d07d3295 100644 --- a/tests/db_functions/text/test_sha384.py +++ b/tests/db_functions/text/test_sha384.py @@ -39,10 +39,12 @@ class SHA384Tests(TestCase): "26676a43c7ba378621175853b0", "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede" "bfe76f65fbd51ad2f14898b95b", - "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede" - "bfe76f65fbd51ad2f14898b95b" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da27" + "4edebfe76f65fbd51ad2f14898b95b" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha512.py b/tests/db_functions/text/test_sha512.py index f5a7ad4ae5..b4c7a4bbd8 100644 --- a/tests/db_functions/text/test_sha512.py +++ b/tests/db_functions/text/test_sha512.py @@ -39,10 +39,12 @@ class SHA512Tests(TestCase): "172d88798345a3a7666faf5f35a144c60812d3234dcd35f444624f2faee16857", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", - "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" - "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" + "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_utils/tests.py b/tests/db_utils/tests.py index a2d9cc7b5e..4028a8acdf 100644 --- a/tests/db_utils/tests.py +++ b/tests/db_utils/tests.py @@ -1,4 +1,5 @@ """Tests for django.db.utils.""" + import unittest from django.core.exceptions import ImproperlyConfigured diff --git a/tests/dbshell/test_sqlite.py b/tests/dbshell/test_sqlite.py index faf9882ad9..e795f7619b 100644 --- a/tests/dbshell/test_sqlite.py +++ b/tests/dbshell/test_sqlite.py @@ -35,8 +35,11 @@ class SqliteDbshellCommandTestCase(SimpleTestCase): cmd_args = self.settings_to_cmd_args_env(sqlite_with_path)[0] msg = '"sqlite3 test.db.sqlite3" returned non-zero exit status 1.' - with mock.patch( - "django.db.backends.sqlite3.client.DatabaseClient.runshell", - side_effect=subprocess.CalledProcessError(returncode=1, cmd=cmd_args), - ), self.assertRaisesMessage(CommandError, msg): + with ( + mock.patch( + "django.db.backends.sqlite3.client.DatabaseClient.runshell", + side_effect=subprocess.CalledProcessError(returncode=1, cmd=cmd_args), + ), + self.assertRaisesMessage(CommandError, msg), + ): call_command("dbshell") diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py index b80878bbf2..93b3f27aec 100644 --- a/tests/distinct_on_fields/tests.py +++ b/tests/distinct_on_fields/tests.py @@ -76,9 +76,11 @@ class DistinctOnTests(TestCase): (StaffTag.objects.distinct("staff", "tag"), [self.st1]), ( Tag.objects.order_by("parent__pk", "pk").distinct("parent"), - [self.t2, self.t4, self.t1] - if connection.features.nulls_order_largest - else [self.t1, self.t2, self.t4], + ( + [self.t2, self.t4, self.t1] + if connection.features.nulls_order_largest + else [self.t1, self.t2, self.t4] + ), ), ( StaffTag.objects.select_related("staff") diff --git a/tests/expressions/models.py b/tests/expressions/models.py index bd4db9050e..43dd235fb5 100644 --- a/tests/expressions/models.py +++ b/tests/expressions/models.py @@ -1,6 +1,7 @@ """ Tests for F() query expression syntax. """ + import uuid from django.db import models diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py index 9fdef57324..6db8f9022d 100644 --- a/tests/file_uploads/tests.py +++ b/tests/file_uploads/tests.py @@ -452,9 +452,10 @@ class FileUploadTests(TestCase): def test_file_content(self): file = tempfile.NamedTemporaryFile - with file(suffix=".ctype_extra") as no_content_type, file( - suffix=".ctype_extra" - ) as simple_file: + with ( + file(suffix=".ctype_extra") as no_content_type, + file(suffix=".ctype_extra") as simple_file, + ): no_content_type.write(b"no content") no_content_type.seek(0) @@ -483,9 +484,10 @@ class FileUploadTests(TestCase): def test_content_type_extra(self): """Uploaded files may have content type parameters available.""" file = tempfile.NamedTemporaryFile - with file(suffix=".ctype_extra") as no_content_type, file( - suffix=".ctype_extra" - ) as simple_file: + with ( + file(suffix=".ctype_extra") as no_content_type, + file(suffix=".ctype_extra") as simple_file, + ): no_content_type.write(b"something") no_content_type.seek(0) diff --git a/tests/file_uploads/uploadhandler.py b/tests/file_uploads/uploadhandler.py index a1e1a5af05..d3c88ac305 100644 --- a/tests/file_uploads/uploadhandler.py +++ b/tests/file_uploads/uploadhandler.py @@ -1,6 +1,7 @@ """ Upload handlers to test the upload API. """ + import os from tempfile import NamedTemporaryFile diff --git a/tests/files/tests.py b/tests/files/tests.py index 7dc5c04668..9d3a471cb3 100644 --- a/tests/files/tests.py +++ b/tests/files/tests.py @@ -144,35 +144,40 @@ class FileTests(unittest.TestCase): self.assertEqual(list(f), ["one\n", "two\n", "three"]) def test_readable(self): - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): self.assertTrue(test_file.readable()) self.assertFalse(test_file.readable()) def test_writable(self): - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): self.assertTrue(test_file.writable()) self.assertFalse(test_file.writable()) - with tempfile.TemporaryFile("rb") as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile("rb") as temp, + File(temp, name="something.txt") as test_file, + ): self.assertFalse(test_file.writable()) def test_seekable(self): - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): self.assertTrue(test_file.seekable()) self.assertFalse(test_file.seekable()) def test_io_wrapper(self): content = "vive l'été\n" - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): test_file.write(content.encode()) test_file.seek(0) wrapper = TextIOWrapper(test_file, "utf-8", newline="\n") diff --git a/tests/force_insert_update/models.py b/tests/force_insert_update/models.py index b95b197454..e6fdfbd827 100644 --- a/tests/force_insert_update/models.py +++ b/tests/force_insert_update/models.py @@ -2,6 +2,7 @@ Tests for forcing insert and update queries (instead of Django's normal automatic behavior). """ + from django.db import models diff --git a/tests/forms_tests/field_tests/test_decimalfield.py b/tests/forms_tests/field_tests/test_decimalfield.py index 9d26bc88b0..cb13e5b71b 100644 --- a/tests/forms_tests/field_tests/test_decimalfield.py +++ b/tests/forms_tests/field_tests/test_decimalfield.py @@ -80,8 +80,9 @@ class DecimalFieldTest(FormFieldAssertionsMixin, SimpleTestCase): "--0.12", ) for value in values: - with self.subTest(value=value), self.assertRaisesMessage( - ValidationError, "'Enter a number.'" + with ( + self.subTest(value=value), + self.assertRaisesMessage(ValidationError, "'Enter a number.'"), ): f.clean(value) diff --git a/tests/forms_tests/field_tests/test_filefield.py b/tests/forms_tests/field_tests/test_filefield.py index 11388bdc09..9744981471 100644 --- a/tests/forms_tests/field_tests/test_filefield.py +++ b/tests/forms_tests/field_tests/test_filefield.py @@ -53,7 +53,8 @@ class FileFieldTest(SimpleTestCase): self.assertIsInstance( f.clean( SimpleUploadedFile( - "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() + "我隻氣墊船裝滿晒鱔.txt", + "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode(), ) ), SimpleUploadedFile, diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index 3c260010c2..f80c1dc09e 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -217,9 +217,12 @@ class FormsFormsetTestCase(SimpleTestCase): [("Calexico", "100"), ("Any1", "42"), ("Any2", "101")] ) - with mock.patch( - "django.forms.formsets.ManagementForm.is_valid", mocked_is_valid - ), mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean): + with ( + mock.patch( + "django.forms.formsets.ManagementForm.is_valid", mocked_is_valid + ), + mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean), + ): self.assertTrue(formset.is_valid()) self.assertEqual(is_valid_counter.call_count, 1) self.assertEqual(full_clean_counter.call_count, 4) diff --git a/tests/gis_tests/gdal_tests/test_raster.py b/tests/gis_tests/gdal_tests/test_raster.py index 67108cbb32..a5f1edef0b 100644 --- a/tests/gis_tests/gdal_tests/test_raster.py +++ b/tests/gis_tests/gdal_tests/test_raster.py @@ -102,8 +102,9 @@ class GDALRasterTests(SimpleTestCase): ] msg = "Geotransform must consist of 6 numeric values." for geotransform in error_geotransforms: - with self.subTest(i=geotransform), self.assertRaisesMessage( - ValueError, msg + with ( + self.subTest(i=geotransform), + self.assertRaisesMessage(ValueError, msg), ): rsmem.geotransform = geotransform diff --git a/tests/gis_tests/geogapp/tests.py b/tests/gis_tests/geogapp/tests.py index 8565608993..cb783b9465 100644 --- a/tests/gis_tests/geogapp/tests.py +++ b/tests/gis_tests/geogapp/tests.py @@ -1,6 +1,7 @@ """ Tests for geography support in PostGIS """ + import os from django.contrib.gis.db import models diff --git a/tests/gis_tests/test_data.py b/tests/gis_tests/test_data.py index 0a94907320..8dd6042175 100644 --- a/tests/gis_tests/test_data.py +++ b/tests/gis_tests/test_data.py @@ -2,6 +2,7 @@ This module has the mock object definitions used to hold reference geometry for the GEOS and GDAL tests. """ + import json import os diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py index 76d99e2504..7a5a287da7 100644 --- a/tests/handlers/tests.py +++ b/tests/handlers/tests.py @@ -240,8 +240,9 @@ class HandlerRequestTests(SimpleTestCase): ("/no_response_cbv/", "handlers.views.NoResponse.__call__"), ) for url, view in tests: - with self.subTest(url=url), self.assertRaisesMessage( - ValueError, msg % view + with ( + self.subTest(url=url), + self.assertRaisesMessage(ValueError, msg % view), ): self.client.get(url) diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index cce8402d3f..2197c6f7ea 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -352,9 +352,9 @@ class HttpResponseTests(SimpleTestCase): h.headers["Content-Disposition"] = 'attachment; filename="%s"' % f # This one is triggering https://bugs.python.org/issue20747, that is Python # will itself insert a newline in the header - h.headers[ - "Content-Disposition" - ] = 'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"' + h.headers["Content-Disposition"] = ( + 'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"' + ) def test_newlines_in_headers(self): # Bug #10188: Do not allow newlines in headers (CR or LF) diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py index f22f273c9a..9d9a09d34e 100644 --- a/tests/invalid_models_tests/test_models.py +++ b/tests/invalid_models_tests/test_models.py @@ -1898,15 +1898,18 @@ class ConstraintsTests(TestCase): self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the nonexistent field 'missing_field'.", - obj=Model, - id="models.E012", - ), - ] - if connection.features.supports_table_check_constraints - else [], + ( + [ + Error( + "'constraints' refers to the nonexistent field " + "'missing_field'.", + obj=Model, + id="models.E012", + ), + ] + if connection.features.supports_table_check_constraints + else [] + ), ) @skipUnlessDBFeature("supports_table_check_constraints") @@ -2252,15 +2255,18 @@ class ConstraintsTests(TestCase): self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the nonexistent field 'missing_field'.", - obj=Model, - id="models.E012", - ), - ] - if connection.features.supports_partial_indexes - else [], + ( + [ + Error( + "'constraints' refers to the nonexistent field " + "'missing_field'.", + obj=Model, + id="models.E012", + ), + ] + if connection.features.supports_partial_indexes + else [] + ), ) def test_unique_constraint_condition_pointing_to_joined_fields(self): @@ -2280,15 +2286,17 @@ class ConstraintsTests(TestCase): self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the joined field 'parent__age__lt'.", - obj=Model, - id="models.E041", - ) - ] - if connection.features.supports_partial_indexes - else [], + ( + [ + Error( + "'constraints' refers to the joined field 'parent__age__lt'.", + obj=Model, + id="models.E041", + ) + ] + if connection.features.supports_partial_indexes + else [] + ), ) def test_unique_constraint_pointing_to_reverse_o2o(self): @@ -2307,15 +2315,17 @@ class ConstraintsTests(TestCase): self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the nonexistent field 'model'.", - obj=Model, - id="models.E012", - ), - ] - if connection.features.supports_partial_indexes - else [], + ( + [ + Error( + "'constraints' refers to the nonexistent field 'model'.", + obj=Model, + id="models.E012", + ), + ] + if connection.features.supports_partial_indexes + else [] + ), ) def test_deferrable_unique_constraint(self): diff --git a/tests/m2m_and_m2o/models.py b/tests/m2m_and_m2o/models.py index 6a5b0b29c9..4cbd1eb4e8 100644 --- a/tests/m2m_and_m2o/models.py +++ b/tests/m2m_and_m2o/models.py @@ -3,6 +3,7 @@ Many-to-many and many-to-one relationships to the same table Make sure to set ``related_name`` if you use relationships to the same table. """ + from django.db import models diff --git a/tests/m2m_intermediary/models.py b/tests/m2m_intermediary/models.py index 1333d14b41..f82498651f 100644 --- a/tests/m2m_intermediary/models.py +++ b/tests/m2m_intermediary/models.py @@ -9,6 +9,7 @@ each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field, which specifies the ``Reporter``'s position for the given article (e.g. "Staff writer"). """ + from django.db import models diff --git a/tests/mail/tests.py b/tests/mail/tests.py index cd981b6e9e..dd6b72ab49 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -1392,8 +1392,9 @@ class BaseEmailBackendTests(HeadersCheckMixin): ): msg = "The %s setting must be a list of 2-tuples." % setting for value in tests: - with self.subTest(setting=setting, value=value), self.settings( - **{setting: value} + with ( + self.subTest(setting=setting, value=value), + self.settings(**{setting: value}), ): with self.assertRaisesMessage(ValueError, msg): mail_func("subject", "content") diff --git a/tests/many_to_many/models.py b/tests/many_to_many/models.py index 541928e94d..42fc426990 100644 --- a/tests/many_to_many/models.py +++ b/tests/many_to_many/models.py @@ -6,6 +6,7 @@ To define a many-to-many relationship, use ``ManyToManyField()``. In this example, an ``Article`` can be published in multiple ``Publication`` objects, and a ``Publication`` has multiple ``Article`` objects. """ + from django.db import models diff --git a/tests/many_to_one/models.py b/tests/many_to_one/models.py index cca7e79817..56e660592a 100644 --- a/tests/many_to_one/models.py +++ b/tests/many_to_one/models.py @@ -3,6 +3,7 @@ Many-to-one relationships To define a many-to-one relationship, use ``ForeignKey()``. """ + from django.db import models diff --git a/tests/middleware/test_security.py b/tests/middleware/test_security.py index dd220b8f4c..339b9181c3 100644 --- a/tests/middleware/test_security.py +++ b/tests/middleware/test_security.py @@ -248,8 +248,9 @@ class SecurityMiddlewareTest(SimpleTestCase): (("strict-origin", "origin"), "strict-origin,origin"), ) for value, expected in tests: - with self.subTest(value=value), override_settings( - SECURE_REFERRER_POLICY=value + with ( + self.subTest(value=value), + override_settings(SECURE_REFERRER_POLICY=value), ): self.assertEqual( self.process_response().headers["Referrer-Policy"], @@ -287,8 +288,11 @@ class SecurityMiddlewareTest(SimpleTestCase): """ tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"] for value in tests: - with self.subTest(value=value), override_settings( - SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + with ( + self.subTest(value=value), + override_settings( + SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + ), ): self.assertEqual( self.process_response().headers["Cross-Origin-Opener-Policy"], diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index 4dc1c83c42..4c17b4ec34 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -854,9 +854,9 @@ class GZipMiddlewareTest(SimpleTestCase): def setUp(self): self.req = self.request_factory.get("/") self.req.META["HTTP_ACCEPT_ENCODING"] = "gzip, deflate" - self.req.META[ - "HTTP_USER_AGENT" - ] = "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1" + self.req.META["HTTP_USER_AGENT"] = ( + "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1" + ) self.resp = HttpResponse() self.resp.status_code = 200 self.resp.content = self.compressible_string diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 263b25ab61..1f8b3fb011 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -3102,9 +3102,11 @@ class OptimizeMigrationTests(MigrationTestBase): with open(initial_migration_file) as fp: content = fp.read() self.assertIn( - '("bool", models.BooleanField' - if HAS_BLACK - else "('bool', models.BooleanField", + ( + '("bool", models.BooleanField' + if HAS_BLACK + else "('bool', models.BooleanField" + ), content, ) self.assertEqual( @@ -3131,9 +3133,11 @@ class OptimizeMigrationTests(MigrationTestBase): with open(initial_migration_file) as fp: content = fp.read() self.assertIn( - '("bool", models.BooleanField' - if HAS_BLACK - else "('bool', models.BooleanField", + ( + '("bool", models.BooleanField' + if HAS_BLACK + else "('bool', models.BooleanField" + ), content, ) self.assertEqual(out.getvalue(), "") diff --git a/tests/migrations/test_executor.py b/tests/migrations/test_executor.py index 6232b44b98..571cb3e1a2 100644 --- a/tests/migrations/test_executor.py +++ b/tests/migrations/test_executor.py @@ -405,9 +405,9 @@ class ExecutorTests(MigrationTestBase): migrations_apps = executor.loader.project_state( ("migrations", "0001_initial"), ).apps - global_apps.get_app_config("migrations").models[ - "author" - ] = migrations_apps.get_model("migrations", "author") + global_apps.get_app_config("migrations").models["author"] = ( + migrations_apps.get_model("migrations", "author") + ) try: migration = executor.loader.get_migration("auth", "0001_initial") self.assertIs(executor.detect_soft_applied(None, migration)[0], True) diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py index 52e43d20f9..5733ba7618 100644 --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -3614,15 +3614,17 @@ class OperationTests(OperationTestBase): operation.state_forwards(app_label, new_state) # Rename index. expected_queries = 1 if connection.features.can_rename_index else 2 - with connection.schema_editor() as editor, self.assertNumQueries( - expected_queries + with ( + connection.schema_editor() as editor, + self.assertNumQueries(expected_queries), ): operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, "pony_pink_idx") self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reversal. - with connection.schema_editor() as editor, self.assertNumQueries( - expected_queries + with ( + connection.schema_editor() as editor, + self.assertNumQueries(expected_queries), ): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "pony_pink_idx") @@ -4281,9 +4283,10 @@ class OperationTests(OperationTestBase): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_deferrable_unique_constraints: @@ -4342,9 +4345,10 @@ class OperationTests(OperationTestBase): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) @@ -4405,9 +4409,10 @@ class OperationTests(OperationTestBase): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_covering_indexes: @@ -4453,9 +4458,10 @@ class OperationTests(OperationTestBase): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) diff --git a/tests/model_inheritance/models.py b/tests/model_inheritance/models.py index 47aae186e0..ffb9f28cfa 100644 --- a/tests/model_inheritance/models.py +++ b/tests/model_inheritance/models.py @@ -11,6 +11,7 @@ Model inheritance exists in two varieties: Both styles are demonstrated here. """ + from django.db import models # diff --git a/tests/model_inheritance/tests.py b/tests/model_inheritance/tests.py index 5bf1ef5db5..6b005fcef0 100644 --- a/tests/model_inheritance/tests.py +++ b/tests/model_inheritance/tests.py @@ -216,9 +216,11 @@ class ModelInheritanceTests(TestCase): GrandChild().save() for i, test in enumerate([a, b]): - with self.subTest(i=i), self.assertNumQueries(4), CaptureQueriesContext( - connection - ) as queries: + with ( + self.subTest(i=i), + self.assertNumQueries(4), + CaptureQueriesContext(connection) as queries, + ): test() for query in queries: sql = query["sql"] diff --git a/tests/model_inheritance_regress/tests.py b/tests/model_inheritance_regress/tests.py index 1a9f953d6f..ba31048ac2 100644 --- a/tests/model_inheritance_regress/tests.py +++ b/tests/model_inheritance_regress/tests.py @@ -1,6 +1,7 @@ """ Regression tests for Model inheritance behavior. """ + import datetime from operator import attrgetter from unittest import expectedFailure diff --git a/tests/null_fk_ordering/models.py b/tests/null_fk_ordering/models.py index adfdbf3bea..d7b6ad8238 100644 --- a/tests/null_fk_ordering/models.py +++ b/tests/null_fk_ordering/models.py @@ -5,6 +5,7 @@ Regression tests for proper working of ForeignKey(null=True). Tests these bugs: unexpected results """ + from django.db import models diff --git a/tests/one_to_one/models.py b/tests/one_to_one/models.py index ca459e9edf..20b2eeec7d 100644 --- a/tests/one_to_one/models.py +++ b/tests/one_to_one/models.py @@ -5,6 +5,7 @@ To define a one-to-one relationship, use ``OneToOneField()``. In this example, a ``Place`` optionally can be a ``Restaurant``. """ + from django.db import models diff --git a/tests/order_with_respect_to/base_tests.py b/tests/order_with_respect_to/base_tests.py index ea548ca076..5170c6d957 100644 --- a/tests/order_with_respect_to/base_tests.py +++ b/tests/order_with_respect_to/base_tests.py @@ -2,6 +2,7 @@ The tests are shared with contenttypes_tests and so shouldn't import or reference any models directly. Subclasses should inherit django.test.TestCase. """ + from operator import attrgetter @@ -117,8 +118,11 @@ class BaseOrderWithRespectToTests: return "other" with self.settings(DATABASE_ROUTERS=[WriteToOtherRouter()]): - with self.assertNumQueries(0, using="default"), self.assertNumQueries( - 1, - using="other", + with ( + self.assertNumQueries(0, using="default"), + self.assertNumQueries( + 1, + using="other", + ), ): self.q1.set_answer_order([3, 1, 2, 4]) diff --git a/tests/postgres_tests/fields.py b/tests/postgres_tests/fields.py index c2513fca0c..c5dddf197f 100644 --- a/tests/postgres_tests/fields.py +++ b/tests/postgres_tests/fields.py @@ -2,6 +2,7 @@ Indirection layer for PostgreSQL-specific fields, so the tests don't fail when run with a backend other than PostgreSQL. """ + import enum from django.db import models diff --git a/tests/postgres_tests/test_constraints.py b/tests/postgres_tests/test_constraints.py index bf47833743..e5a8e9dbe9 100644 --- a/tests/postgres_tests/test_constraints.py +++ b/tests/postgres_tests/test_constraints.py @@ -300,8 +300,9 @@ class ExclusionConstraintTests(PostgreSQLTestCase): def test_empty_expressions(self): msg = "At least one expression is required to define an exclusion constraint." for empty_expressions in (None, []): - with self.subTest(empty_expressions), self.assertRaisesMessage( - ValueError, msg + with ( + self.subTest(empty_expressions), + self.assertRaisesMessage(ValueError, msg), ): ExclusionConstraint( index_type="GIST", diff --git a/tests/postgres_tests/test_search.py b/tests/postgres_tests/test_search.py index 6f6318899c..472dca6c7b 100644 --- a/tests/postgres_tests/test_search.py +++ b/tests/postgres_tests/test_search.py @@ -5,6 +5,7 @@ These tests use dialogue from the 1975 film Monty Python and the Holy Grail. All text copyright Python (Monty) Pictures. Thanks to sacred-texts.com for the transcript. """ + from django.db.models import F, Value from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py index 08f87d55de..a418beb5a5 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -1620,8 +1620,9 @@ class MultiDbTests(TestCase): ) # Explicit using on a different db. - with self.assertNumQueries(1, using="default"), self.assertNumQueries( - 1, using="other" + with ( + self.assertNumQueries(1, using="default"), + self.assertNumQueries(1, using="other"), ): prefetch = Prefetch( "first_time_authors", queryset=Author.objects.using("default") diff --git a/tests/proxy_models/models.py b/tests/proxy_models/models.py index 604136b5ac..c0277e093f 100644 --- a/tests/proxy_models/models.py +++ b/tests/proxy_models/models.py @@ -4,6 +4,7 @@ they will take data directly from the table of their base class table rather than using a new table of their own. This allows them to act as simple proxies, providing a modified interface to the data from the base class. """ + from django.db import models # A couple of managers for testing managing overriding in proxy model cases. diff --git a/tests/queries/models.py b/tests/queries/models.py index 23c41e3374..9f4cf040b6 100644 --- a/tests/queries/models.py +++ b/tests/queries/models.py @@ -1,6 +1,7 @@ """ Various complex queries that have been problematic in the past. """ + import datetime from django.db import models diff --git a/tests/requests_tests/test_accept_header.py b/tests/requests_tests/test_accept_header.py index c6eed0e479..5afb9e9993 100644 --- a/tests/requests_tests/test_accept_header.py +++ b/tests/requests_tests/test_accept_header.py @@ -68,9 +68,9 @@ class AcceptHeaderTests(TestCase): def test_accept_headers(self): request = HttpRequest() - request.META[ - "HTTP_ACCEPT" - ] = "text/html, application/xhtml+xml,application/xml ;q=0.9,*/*;q=0.8" + request.META["HTTP_ACCEPT"] = ( + "text/html, application/xhtml+xml,application/xml ;q=0.9,*/*;q=0.8" + ) self.assertEqual( [str(accepted_type) for accepted_type in request.accepted_types], [ @@ -94,9 +94,9 @@ class AcceptHeaderTests(TestCase): def test_request_accepts_some(self): request = HttpRequest() - request.META[ - "HTTP_ACCEPT" - ] = "text/html,application/xhtml+xml,application/xml;q=0.9" + request.META["HTTP_ACCEPT"] = ( + "text/html,application/xhtml+xml,application/xml;q=0.9" + ) self.assertIs(request.accepts("text/html"), True) self.assertIs(request.accepts("application/xhtml+xml"), True) self.assertIs(request.accepts("application/xml"), True) diff --git a/tests/save_delete_hooks/models.py b/tests/save_delete_hooks/models.py index e7c598aeae..8b9826eb14 100644 --- a/tests/save_delete_hooks/models.py +++ b/tests/save_delete_hooks/models.py @@ -4,6 +4,7 @@ Adding hooks before/after saving and deleting To execute arbitrary code around ``save()`` and ``delete()``, just subclass the methods. """ + from django.db import models diff --git a/tests/schema/fields.py b/tests/schema/fields.py index 998cb28b8c..24a26b2c2c 100644 --- a/tests/schema/fields.py +++ b/tests/schema/fields.py @@ -41,9 +41,11 @@ class CustomManyToManyField(RelatedField): related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, - symmetrical=symmetrical - if symmetrical is not None - else (to == RECURSIVE_RELATIONSHIP_CONSTANT), + symmetrical=( + symmetrical + if symmetrical is not None + else (to == RECURSIVE_RELATIONSHIP_CONSTANT) + ), through=through, through_fields=through_fields, db_constraint=db_constraint, diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 61244f75b4..3a026281bd 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -640,9 +640,10 @@ class SchemaTests(TransactionTestCase): # Add the new field new_field = IntegerField(null=True) new_field.set_attributes_from_name("age") - with CaptureQueriesContext( - connection - ) as ctx, connection.schema_editor() as editor: + with ( + CaptureQueriesContext(connection) as ctx, + connection.schema_editor() as editor, + ): editor.add_field(Author, new_field) drop_default_sql = editor.sql_alter_column_no_default % { "column": editor.quote_name(new_field.name), @@ -2483,9 +2484,10 @@ class SchemaTests(TransactionTestCase): with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Add the field - with CaptureQueriesContext( - connection - ) as ctx, connection.schema_editor() as editor: + with ( + CaptureQueriesContext(connection) as ctx, + connection.schema_editor() as editor, + ): editor.add_field(LocalAuthorWithM2M, new_field) # Table is not rebuilt. self.assertEqual( @@ -2963,9 +2965,11 @@ class SchemaTests(TransactionTestCase): ) # Redundant foreign key index is not added. self.assertEqual( - len(old_constraints) - 1 - if connection.features.supports_partial_indexes - else len(old_constraints), + ( + len(old_constraints) - 1 + if connection.features.supports_partial_indexes + else len(old_constraints) + ), len(new_constraints), ) diff --git a/tests/serializers/models/base.py b/tests/serializers/models/base.py index c5a4a0f580..e4fcee366d 100644 --- a/tests/serializers/models/base.py +++ b/tests/serializers/models/base.py @@ -4,6 +4,7 @@ Serialization ``django.core.serializers`` provides interfaces to converting Django ``QuerySet`` objects to and from "flat" data (i.e. strings). """ + from decimal import Decimal from django.db import models diff --git a/tests/serializers/models/data.py b/tests/serializers/models/data.py index 3d863a3fb2..a0e8751461 100644 --- a/tests/serializers/models/data.py +++ b/tests/serializers/models/data.py @@ -4,6 +4,7 @@ The following classes are for testing basic data marshalling, including NULL values, where allowed. The basic idea is to have a model for each Django data type. """ + import uuid from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation diff --git a/tests/serializers/models/natural.py b/tests/serializers/models/natural.py index 1e439b34eb..cfc57b1127 100644 --- a/tests/serializers/models/natural.py +++ b/tests/serializers/models/natural.py @@ -1,4 +1,5 @@ """Models for test_natural.py""" + import uuid from django.db import models diff --git a/tests/serializers/test_data.py b/tests/serializers/test_data.py index e1cb776d83..6361dc0c05 100644 --- a/tests/serializers/test_data.py +++ b/tests/serializers/test_data.py @@ -6,6 +6,7 @@ test case that is capable of testing the capabilities of the serializers. This includes all valid data values, plus forward, backwards and self references. """ + import datetime import decimal import uuid diff --git a/tests/servers/tests.py b/tests/servers/tests.py index ea49c11534..05898009d5 100644 --- a/tests/servers/tests.py +++ b/tests/servers/tests.py @@ -1,6 +1,7 @@ """ Tests for django.core.servers. """ + import errno import os import socket diff --git a/tests/sessions_tests/models.py b/tests/sessions_tests/models.py index 6eda26f22a..93f80b347d 100644 --- a/tests/sessions_tests/models.py +++ b/tests/sessions_tests/models.py @@ -3,6 +3,7 @@ This custom Session model adds an extra column to store an account ID. In real-world applications, it gives you the option of querying the database for all active sessions for a particular account. """ + from django.contrib.sessions.backends.db import SessionStore as DBStore from django.contrib.sessions.base_session import AbstractBaseSession from django.db import models diff --git a/tests/signals/models.py b/tests/signals/models.py index b758244749..5fb9f9f772 100644 --- a/tests/signals/models.py +++ b/tests/signals/models.py @@ -1,6 +1,7 @@ """ Testing signals before/after saving and deleting. """ + from django.db import models diff --git a/tests/template_tests/test_parser.py b/tests/template_tests/test_parser.py index e40a5611e2..eb3bb49113 100644 --- a/tests/template_tests/test_parser.py +++ b/tests/template_tests/test_parser.py @@ -2,6 +2,7 @@ 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 ( FilterExpression, diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index cfd040f7bc..18b7aaef6c 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -19,6 +19,7 @@ testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ + import copy import itertools import tempfile diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index a3545ebfc7..4d47fb63af 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -1,6 +1,7 @@ """ Regression tests for the Test Client, especially the customized assertions. """ + import itertools import os diff --git a/tests/test_runner/test_discover_runner.py b/tests/test_runner/test_discover_runner.py index 5fc35b7bf2..a845f6dd67 100644 --- a/tests/test_runner/test_discover_runner.py +++ b/tests/test_runner/test_discover_runner.py @@ -658,9 +658,10 @@ class DiscoverRunnerTests(SimpleTestCase): @mock.patch("faulthandler.enable") def test_faulthandler_enabled_fileno(self, mocked_enable): # sys.stderr that is not an actual file. - with mock.patch( - "faulthandler.is_enabled", return_value=False - ), captured_stderr(): + with ( + mock.patch("faulthandler.is_enabled", return_value=False), + captured_stderr(), + ): DiscoverRunner(enable_faulthandler=True) mocked_enable.assert_called() diff --git a/tests/test_runner/tests.py b/tests/test_runner/tests.py index 569fd7e862..b900ff69ea 100644 --- a/tests/test_runner/tests.py +++ b/tests/test_runner/tests.py @@ -1,6 +1,7 @@ """ Tests for django test runner """ + import collections.abc import multiprocessing import os @@ -992,17 +993,21 @@ class RunTestsExceptionHandlingTests(unittest.TestCase): """ Teardown functions are run when run_checks() raises SystemCheckError. """ - with mock.patch( - "django.test.runner.DiscoverRunner.setup_test_environment" - ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( - "django.test.runner.DiscoverRunner.build_suite" - ), mock.patch( - "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError - ), mock.patch( - "django.test.runner.DiscoverRunner.teardown_databases" - ) as teardown_databases, mock.patch( - "django.test.runner.DiscoverRunner.teardown_test_environment" - ) as teardown_test_environment: + with ( + mock.patch("django.test.runner.DiscoverRunner.setup_test_environment"), + mock.patch("django.test.runner.DiscoverRunner.setup_databases"), + mock.patch("django.test.runner.DiscoverRunner.build_suite"), + mock.patch( + "django.test.runner.DiscoverRunner.run_checks", + side_effect=SystemCheckError, + ), + mock.patch( + "django.test.runner.DiscoverRunner.teardown_databases" + ) as teardown_databases, + mock.patch( + "django.test.runner.DiscoverRunner.teardown_test_environment" + ) as teardown_test_environment, + ): runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( @@ -1016,18 +1021,22 @@ class RunTestsExceptionHandlingTests(unittest.TestCase): SystemCheckError is surfaced when run_checks() raises SystemCheckError and teardown databases() raises ValueError. """ - with mock.patch( - "django.test.runner.DiscoverRunner.setup_test_environment" - ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( - "django.test.runner.DiscoverRunner.build_suite" - ), mock.patch( - "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError - ), mock.patch( - "django.test.runner.DiscoverRunner.teardown_databases", - side_effect=ValueError, - ) as teardown_databases, mock.patch( - "django.test.runner.DiscoverRunner.teardown_test_environment" - ) as teardown_test_environment: + with ( + mock.patch("django.test.runner.DiscoverRunner.setup_test_environment"), + mock.patch("django.test.runner.DiscoverRunner.setup_databases"), + mock.patch("django.test.runner.DiscoverRunner.build_suite"), + mock.patch( + "django.test.runner.DiscoverRunner.run_checks", + side_effect=SystemCheckError, + ), + mock.patch( + "django.test.runner.DiscoverRunner.teardown_databases", + side_effect=ValueError, + ) as teardown_databases, + mock.patch( + "django.test.runner.DiscoverRunner.teardown_test_environment" + ) as teardown_test_environment, + ): runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( @@ -1041,18 +1050,19 @@ class RunTestsExceptionHandlingTests(unittest.TestCase): Exceptions on teardown are surfaced if no exceptions happen during run_checks(). """ - with mock.patch( - "django.test.runner.DiscoverRunner.setup_test_environment" - ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( - "django.test.runner.DiscoverRunner.build_suite" - ), mock.patch( - "django.test.runner.DiscoverRunner.run_checks" - ), mock.patch( - "django.test.runner.DiscoverRunner.teardown_databases", - side_effect=ValueError, - ) as teardown_databases, mock.patch( - "django.test.runner.DiscoverRunner.teardown_test_environment" - ) as teardown_test_environment: + with ( + mock.patch("django.test.runner.DiscoverRunner.setup_test_environment"), + mock.patch("django.test.runner.DiscoverRunner.setup_databases"), + mock.patch("django.test.runner.DiscoverRunner.build_suite"), + mock.patch("django.test.runner.DiscoverRunner.run_checks"), + mock.patch( + "django.test.runner.DiscoverRunner.teardown_databases", + side_effect=ValueError, + ) as teardown_databases, + mock.patch( + "django.test.runner.DiscoverRunner.teardown_test_environment" + ) as teardown_test_environment, + ): runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(ValueError): # Suppress the output when running TestDjangoTestCase. diff --git a/tests/transactions/models.py b/tests/transactions/models.py index 9506bace35..3d4c7d7e44 100644 --- a/tests/transactions/models.py +++ b/tests/transactions/models.py @@ -6,6 +6,7 @@ each transaction upon a write, but you can decorate a function to get commit-on-success behavior. Alternatively, you can manage the transaction manually. """ + from django.db import models diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py index 89dfd0deba..8384f55b3c 100644 --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -1,6 +1,7 @@ """ Unit tests for reverse URL lookups. """ + import pickle import sys import threading diff --git a/tests/urls.py b/tests/urls.py index 7d3a3a790a..67c4d4091b 100644 --- a/tests/urls.py +++ b/tests/urls.py @@ -3,5 +3,4 @@ should be added within the test folders, and use TestCase.urls to set them. This helps the tests remain isolated. """ - urlpatterns = [] diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py index 07229f25ed..d5d90b68fc 100644 --- a/tests/utils_tests/test_datastructures.py +++ b/tests/utils_tests/test_datastructures.py @@ -1,6 +1,7 @@ """ Tests for stuff in django.utils.datastructures. """ + import collections.abc import copy import pickle diff --git a/tests/utils_tests/test_jslex.py b/tests/utils_tests/test_jslex.py index ee13eb4d64..59551930c6 100644 --- a/tests/utils_tests/test_jslex.py +++ b/tests/utils_tests/test_jslex.py @@ -1,4 +1,5 @@ """Tests for jslex.""" + # originally from https://bitbucket.org/ned/jslex from django.test import SimpleTestCase diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py index 54c5da056e..03db07a61c 100644 --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -332,14 +332,19 @@ class DebugViewTests(SimpleTestCase): with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) - with override_settings( - TEMPLATES=[ - { - "BACKEND": "django.template.backends.django.DjangoTemplates", - "DIRS": [tempdir], - } - ] - ), self.assertLogs("django.request", "ERROR"): + with ( + override_settings( + TEMPLATES=[ + { + "BACKEND": ( + "django.template.backends.django.DjangoTemplates" + ), + "DIRS": [tempdir], + } + ] + ), + self.assertLogs("django.request", "ERROR"), + ): response = self.client.get( reverse( "raises_template_does_not_exist", kwargs={"path": template_name} |
