diff --git a/django/contrib/messages/storage/fallback.py b/django/contrib/messages/storage/fallback.py index 9fbf522bb2..97f82d7654 100644 --- a/django/contrib/messages/storage/fallback.py +++ b/django/contrib/messages/storage/fallback.py @@ -45,8 +45,7 @@ class FallbackStorage(BaseStorage): """ for storage in self.storages: if messages: - messages = storage._store(messages, response, - remove_oldest=False) + messages = storage._store(messages, response, remove_oldest=False) # Even if there are no more messages, continue iterating to ensure # storages which contained messages are flushed. elif storage in self._used_storages: diff --git a/django/core/mail/message.py b/django/core/mail/message.py index b25d23881b..c36fdcff09 100644 --- a/django/core/mail/message.py +++ b/django/core/mail/message.py @@ -397,8 +397,7 @@ class EmailMessage: filename.encode('ascii') except UnicodeEncodeError: filename = ('utf-8', '', filename) - attachment.add_header('Content-Disposition', 'attachment', - filename=filename) + attachment.add_header('Content-Disposition', 'attachment', filename=filename) return attachment def _set_list_header_if_not_empty(self, msg, header, values): diff --git a/django/db/backends/postgresql/base.py b/django/db/backends/postgresql/base.py index 1982a8aedb..0c060e57eb 100644 --- a/django/db/backends/postgresql/base.py +++ b/django/db/backends/postgresql/base.py @@ -263,7 +263,8 @@ class DatabaseWrapper(BaseDatabaseWrapper): nodb_connection = self.__class__( self.settings_dict.copy(), alias=self.alias, - allow_thread_sharing=False) + allow_thread_sharing=False, + ) return nodb_connection @cached_property diff --git a/django/forms/forms.py b/django/forms/forms.py index 86f9399001..51e6465539 100644 --- a/django/forms/forms.py +++ b/django/forms/forms.py @@ -281,7 +281,8 @@ class BaseForm: error_row='
s." @@ -299,7 +301,8 @@ class BaseForm: error_row='%s', row_ender='
', help_text_html=' %s', - errors_on_separate_row=True) + errors_on_separate_row=True, + ) def non_field_errors(self): """ diff --git a/django/middleware/common.py b/django/middleware/common.py index 2a74774654..bea3f7448a 100644 --- a/django/middleware/common.py +++ b/django/middleware/common.py @@ -130,7 +130,8 @@ class BrokenLinkEmailsMiddleware(MiddlewareMixin): ), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" "IP address: %s\n" % (referer, path, ua, ip), - fail_silently=True) + fail_silently=True, + ) return response def is_internal_request(self, domain, referer): diff --git a/django/test/runner.py b/django/test/runner.py index 9ed78a6be8..9bd9f2b506 100644 --- a/django/test/runner.py +++ b/django/test/runner.py @@ -356,7 +356,8 @@ class ParallelTestSuite(unittest.TestSuite): pool = multiprocessing.Pool( processes=self.processes, initializer=self.init_worker.__func__, - initargs=[counter]) + initargs=[counter], + ) args = [ (self.runner_class, index, subsuite, self.failfast) for index, subsuite in enumerate(self.subsuites) diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index af11c2ac35..a0cff0837b 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -146,7 +146,8 @@ class DjangoTranslation(gettext_module.GNUTranslations): localedir=localedir, languages=[self.__locale], codeset='utf-8', - fallback=use_null_fallback) + fallback=use_null_fallback, + ) def _init_translation_catalog(self): """Create a base catalog using global django translations.""" diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index ceae4c11a2..9e6ce63077 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -282,8 +282,7 @@ download.short_description = 'Download subscription' def no_perm(modeladmin, request, selected): - return HttpResponse(content='No permission to perform this action', - status=403) + return HttpResponse(content='No permission to perform this action', status=403) no_perm.short_description = 'No permission to run' @@ -685,11 +684,7 @@ class ReportAdmin(admin.ModelAdmin): def get_urls(self): # Corner case: Don't call parent implementation - return [ - url(r'^extra/$', - self.extra, - name='cable_extra'), - ] + return [url(r'^extra/$', self.extra, name='cable_extra')] class CustomTemplateBooleanFieldListFilter(BooleanFieldListFilter): diff --git a/tests/annotations/tests.py b/tests/annotations/tests.py index ee1c50cfdf..d7759c8552 100644 --- a/tests/annotations/tests.py +++ b/tests/annotations/tests.py @@ -283,9 +283,10 @@ class NonAggregateAnnotationTestCase(TestCase): def test_annotation_reverse_m2m(self): books = Book.objects.annotate( - store_name=F('store__name')).filter( - name='Practical Django Projects').order_by( - 'store_name') + store_name=F('store__name'), + ).filter( + name='Practical Django Projects', + ).order_by('store_name') self.assertQuerysetEqual( books, [ @@ -497,7 +498,8 @@ class NonAggregateAnnotationTestCase(TestCase): F('ticker_name'), F('description'), Value('No Tag'), - function='COALESCE') + function='COALESCE', + ) ).annotate( tagline_lower=Lower(F('tagline'), output_field=CharField()) ).order_by('name') diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py index 390d26ea9b..1a1950e989 100644 --- a/tests/auth_tests/test_auth_backends.py +++ b/tests/auth_tests/test_auth_backends.py @@ -559,8 +559,8 @@ class ChangedBackendSettingsTest(TestCase): # Get a session for the test user self.assertTrue(self.client.login( username=self.TEST_USERNAME, - password=self.TEST_PASSWORD) - ) + password=self.TEST_PASSWORD, + )) # Prepare a request object request = HttpRequest() request.session = self.client.session diff --git a/tests/check_framework/test_security.py b/tests/check_framework/test_security.py index cfc90f95e9..e6fe1f6cb7 100644 --- a/tests/check_framework/test_security.py +++ b/tests/check_framework/test_security.py @@ -13,7 +13,8 @@ class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], - MIDDLEWARE=[]) + MIDDLEWARE=[], + ) def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is @@ -24,7 +25,8 @@ class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=[], - MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"]) + MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], + ) def test_session_cookie_secure_with_middleware(self): """ Warn if SESSION_COOKIE_SECURE is off and @@ -36,7 +38,8 @@ class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], - MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"]) + MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], + ) def test_session_cookie_secure_both(self): """ If SESSION_COOKIE_SECURE is off and we find both the session app and @@ -47,7 +50,8 @@ class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=True, INSTALLED_APPS=["django.contrib.sessions"], - MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"]) + MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], + ) def test_session_cookie_secure_true(self): """ If SESSION_COOKIE_SECURE is on, there's no warning about it. @@ -64,7 +68,8 @@ class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], - MIDDLEWARE=[]) + MIDDLEWARE=[], + ) def test_session_cookie_httponly_with_installed_app(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" @@ -75,7 +80,8 @@ class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=[], - MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"]) + MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], + ) def test_session_cookie_httponly_with_middleware(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and @@ -87,7 +93,8 @@ class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], - MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"]) + MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], + ) def test_session_cookie_httponly_both(self): """ If SESSION_COOKIE_HTTPONLY is off and we find both the session app and @@ -98,7 +105,8 @@ class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=True, INSTALLED_APPS=["django.contrib.sessions"], - MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"]) + MIDDLEWARE=['django.contrib.sessions.middleware.SessionMiddleware'], + ) def test_session_cookie_httponly_true(self): """ If SESSION_COOKIE_HTTPONLY is on, there's no warning about it. @@ -119,8 +127,7 @@ class CheckCSRFMiddlewareTest(SimpleTestCase): """ self.assertEqual(self.func(None), [csrf.W003]) - @override_settings( - MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"]) + @override_settings(MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware']) def test_with_csrf_middleware(self): self.assertEqual(self.func(None), []) @@ -133,7 +140,8 @@ class CheckCSRFCookieSecureTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], - CSRF_COOKIE_SECURE=False) + CSRF_COOKIE_SECURE=False, + ) def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE but @@ -144,7 +152,8 @@ class CheckCSRFCookieSecureTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_USE_SESSIONS=True, - CSRF_COOKIE_SECURE=False) + CSRF_COOKIE_SECURE=False, + ) def test_use_sessions_with_csrf_cookie_secure_false(self): """ No warning if CSRF_COOKIE_SECURE isn't True while CSRF_USE_SESSIONS @@ -162,7 +171,8 @@ class CheckCSRFCookieSecureTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], - CSRF_COOKIE_SECURE=True) + CSRF_COOKIE_SECURE=True, + ) def test_with_csrf_cookie_secure_true(self): self.assertEqual(self.func(None), []) @@ -180,8 +190,7 @@ class CheckSecurityMiddlewareTest(SimpleTestCase): """ self.assertEqual(self.func(None), [base.W001]) - @override_settings( - MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) + @override_settings(MIDDLEWARE=['django.middleware.security.SecurityMiddleware']) def test_with_security_middleware(self): self.assertEqual(self.func(None), []) @@ -194,16 +203,15 @@ class CheckStrictTransportSecurityTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_HSTS_SECONDS=0) + SECURE_HSTS_SECONDS=0, + ) def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(self.func(None), [base.W004]) - @override_settings( - MIDDLEWARE=[], - SECURE_HSTS_SECONDS=0) + @override_settings(MIDDLEWARE=[], SECURE_HSTS_SECONDS=0) def test_no_sts_no_middleware(self): """ Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't @@ -213,7 +221,8 @@ class CheckStrictTransportSecurityTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_HSTS_SECONDS=3600) + SECURE_HSTS_SECONDS=3600, + ) def test_with_sts(self): self.assertEqual(self.func(None), []) @@ -227,7 +236,8 @@ class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, - SECURE_HSTS_SECONDS=3600) + SECURE_HSTS_SECONDS=3600, + ) def test_no_sts_subdomains(self): """ Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True. @@ -237,7 +247,8 @@ class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=[], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, - SECURE_HSTS_SECONDS=3600) + SECURE_HSTS_SECONDS=3600, + ) def test_no_sts_subdomains_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. @@ -247,7 +258,8 @@ class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, - SECURE_HSTS_SECONDS=None) + SECURE_HSTS_SECONDS=None, + ) def test_no_sts_subdomains_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. @@ -257,7 +269,8 @@ class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=True, - SECURE_HSTS_SECONDS=3600) + SECURE_HSTS_SECONDS=3600, + ) def test_with_sts_subdomains(self): self.assertEqual(self.func(None), []) @@ -365,16 +378,15 @@ class CheckContentTypeNosniffTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_CONTENT_TYPE_NOSNIFF=False) + SECURE_CONTENT_TYPE_NOSNIFF=False, + ) def test_no_content_type_nosniff(self): """ Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True. """ self.assertEqual(self.func(None), [base.W006]) - @override_settings( - MIDDLEWARE=[], - SECURE_CONTENT_TYPE_NOSNIFF=False) + @override_settings(MIDDLEWARE=[], SECURE_CONTENT_TYPE_NOSNIFF=False) def test_no_content_type_nosniff_no_middleware(self): """ Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and @@ -384,7 +396,8 @@ class CheckContentTypeNosniffTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_CONTENT_TYPE_NOSNIFF=True) + SECURE_CONTENT_TYPE_NOSNIFF=True, + ) def test_with_content_type_nosniff(self): self.assertEqual(self.func(None), []) @@ -397,16 +410,15 @@ class CheckXssFilterTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_BROWSER_XSS_FILTER=False) + SECURE_BROWSER_XSS_FILTER=False, + ) def test_no_xss_filter(self): """ Warn if SECURE_BROWSER_XSS_FILTER isn't True. """ self.assertEqual(self.func(None), [base.W007]) - @override_settings( - MIDDLEWARE=[], - SECURE_BROWSER_XSS_FILTER=False) + @override_settings(MIDDLEWARE=[], SECURE_BROWSER_XSS_FILTER=False) def test_no_xss_filter_no_middleware(self): """ Don't warn if SECURE_BROWSER_XSS_FILTER isn't True and @@ -416,7 +428,8 @@ class CheckXssFilterTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_BROWSER_XSS_FILTER=True) + SECURE_BROWSER_XSS_FILTER=True, + ) def test_with_xss_filter(self): self.assertEqual(self.func(None), []) @@ -429,16 +442,15 @@ class CheckSSLRedirectTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_SSL_REDIRECT=False) + SECURE_SSL_REDIRECT=False, + ) def test_no_ssl_redirect(self): """ Warn if SECURE_SSL_REDIRECT isn't True. """ self.assertEqual(self.func(None), [base.W008]) - @override_settings( - MIDDLEWARE=[], - SECURE_SSL_REDIRECT=False) + @override_settings(MIDDLEWARE=[], SECURE_SSL_REDIRECT=False) def test_no_ssl_redirect_no_middleware(self): """ Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't @@ -448,7 +460,8 @@ class CheckSSLRedirectTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], - SECURE_SSL_REDIRECT=True) + SECURE_SSL_REDIRECT=True, + ) def test_with_ssl_redirect(self): self.assertEqual(self.func(None), []) diff --git a/tests/defer/tests.py b/tests/defer/tests.py index a3ef1c58b1..dbb1299255 100644 --- a/tests/defer/tests.py +++ b/tests/defer/tests.py @@ -233,8 +233,7 @@ class TestDefer2(AssertionMixin, TestCase): fetched parent model PK if it happens to be available. """ s1 = Secondary.objects.create(first="x1", second="y1") - bc = BigChild.objects.create(name="b1", value="foo", related=s1, - other="bar") + bc = BigChild.objects.create(name='b1', value='foo', related=s1, other='bar') bc_deferred = BigChild.objects.only('name').get(pk=bc.pk) with self.assertNumQueries(0): bc_deferred.id diff --git a/tests/delete_regress/tests.py b/tests/delete_regress/tests.py index a8b1cb0386..d4d39843e3 100644 --- a/tests/delete_regress/tests.py +++ b/tests/delete_regress/tests.py @@ -61,8 +61,7 @@ class DeleteCascadeTests(TestCase): """ person = Person.objects.create(name='Nelson Mandela') award = Award.objects.create(name='Nobel', content_object=person) - AwardNote.objects.create(note='a peace prize', - award=award) + AwardNote.objects.create(note='a peace prize', award=award) self.assertEqual(AwardNote.objects.count(), 1) person.delete() self.assertEqual(Award.objects.count(), 0) @@ -78,10 +77,8 @@ class DeleteCascadeTests(TestCase): """ juan = Child.objects.create(name='Juan') paints = Toy.objects.create(name='Paints') - played = PlayedWith.objects.create(child=juan, toy=paints, - date=datetime.date.today()) - PlayedWithNote.objects.create(played=played, - note='the next Jackson Pollock') + played = PlayedWith.objects.create(child=juan, toy=paints, date=datetime.date.today()) + PlayedWithNote.objects.create(played=played, note='the next Jackson Pollock') self.assertEqual(PlayedWithNote.objects.count(), 1) paints.delete() self.assertEqual(PlayedWith.objects.count(), 0) diff --git a/tests/expressions/models.py b/tests/expressions/models.py index 34fd9dff16..42e4a37bb0 100644 --- a/tests/expressions/models.py +++ b/tests/expressions/models.py @@ -22,12 +22,14 @@ class Company(models.Model): ceo = models.ForeignKey( Employee, models.CASCADE, - related_name='company_ceo_set') + related_name='company_ceo_set', + ) point_of_contact = models.ForeignKey( Employee, models.SET_NULL, related_name='company_point_of_contact_set', - null=True) + null=True, + ) def __str__(self): return self.name diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index 7453838839..b57a16c35f 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -373,7 +373,8 @@ class BasicExpressionsTests(TestCase): # other lookups could not reuse. qs = Employee.objects.filter( company_ceo_set__num_chairs=F('company_ceo_set__num_employees'), - company_ceo_set__num_chairs__gte=1) + company_ceo_set__num_chairs__gte=1, + ) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_ticket_18375_kwarg_ordering_2(self): @@ -793,17 +794,20 @@ class ExpressionsTests(TestCase): self.assertQuerysetEqual( Employee.objects.filter(firstname__contains=F('lastname')), ["Non-field error.
', - code='secret', - params={'a': 1, 'b': 2}) + raise ValidationError( + 'Non-field error.
', + code='secret', + params={'a': 1, 'b': 2}, + ) control = { 'foo': [{'code': 'required', 'message': 'This field is required.'}], diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index fc8eaa2b8f..b4c2ce4c9d 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -629,13 +629,11 @@ class KeepPotFileExtractorTests(ExtractorTests): self.assertFalse(os.path.exists(self.POT_FILE)) def test_keep_pot_explicitly_disabled(self): - management.call_command('makemessages', locale=[LOCALE], verbosity=0, - keep_pot=False) + management.call_command('makemessages', locale=[LOCALE], verbosity=0, keep_pot=False) self.assertFalse(os.path.exists(self.POT_FILE)) def test_keep_pot_enabled(self): - management.call_command('makemessages', locale=[LOCALE], verbosity=0, - keep_pot=True) + management.call_command('makemessages', locale=[LOCALE], verbosity=0, keep_pot=True) self.assertTrue(os.path.exists(self.POT_FILE)) diff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py index 281779828d..a3c3a70808 100644 --- a/tests/invalid_models_tests/test_ordinary_fields.py +++ b/tests/invalid_models_tests/test_ordinary_fields.py @@ -67,7 +67,8 @@ class CharFieldTests(TestCase): ('1', 'item1'), ('2', 'item2'), ], - db_index=True) + db_index=True, + ) field = Model._meta.get_field('field') self.assertEqual(field.check(), []) diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py index 8b2b093339..0330fdccf5 100644 --- a/tests/logging_tests/tests.py +++ b/tests/logging_tests/tests.py @@ -390,8 +390,10 @@ class SetupConfigureLogging(SimpleTestCase): """ Calling django.setup() initializes the logging configuration. """ - @override_settings(LOGGING_CONFIG='logging_tests.tests.dictConfig', - LOGGING=OLD_LOGGING) + @override_settings( + LOGGING_CONFIG='logging_tests.tests.dictConfig', + LOGGING=OLD_LOGGING, + ) def test_configure_initializes_logging(self): from django import setup setup() diff --git a/tests/mail/tests.py b/tests/mail/tests.py index b8d0089ee3..77e1378192 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -1300,7 +1300,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): @override_settings( EMAIL_HOST_USER="not empty username", - EMAIL_HOST_PASSWORD="not empty password") + EMAIL_HOST_PASSWORD='not empty password', + ) def test_email_authentication_use_settings(self): backend = smtp.EmailBackend() self.assertEqual(backend.username, 'not empty username') @@ -1308,7 +1309,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): @override_settings( EMAIL_HOST_USER="not empty username", - EMAIL_HOST_PASSWORD="not empty password") + EMAIL_HOST_PASSWORD='not empty password', + ) def test_email_authentication_override_settings(self): backend = smtp.EmailBackend(username='username', password='password') self.assertEqual(backend.username, 'username') @@ -1316,7 +1318,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase): @override_settings( EMAIL_HOST_USER="not empty username", - EMAIL_HOST_PASSWORD="not empty password") + EMAIL_HOST_PASSWORD='not empty password', + ) def test_email_disabled_authentication(self): backend = smtp.EmailBackend(username='', password='') self.assertEqual(backend.username, '') diff --git a/tests/middleware/test_security.py b/tests/middleware/test_security.py index 31a3dbb74c..eaefb22ee4 100644 --- a/tests/middleware/test_security.py +++ b/tests/middleware/test_security.py @@ -48,7 +48,8 @@ class SecurityMiddlewareTest(SimpleTestCase): """ self.assertEqual( self.process_response(secure=True)["strict-transport-security"], - "max-age=3600") + 'max-age=3600', + ) @override_settings(SECURE_HSTS_SECONDS=3600) def test_sts_already_present(self): diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py index 43c3a1941a..e262a8ee52 100644 --- a/tests/migrations/test_autodetector.py +++ b/tests/migrations/test_autodetector.py @@ -783,8 +783,10 @@ class AutodetectorTests(TestCase): self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default='Ada Lovelace') - @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', - return_value=models.NOT_PROVIDED) + @mock.patch( + 'django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', + return_value=models.NOT_PROVIDED, + ) def test_alter_field_to_not_null_without_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. @@ -797,8 +799,10 @@ class AutodetectorTests(TestCase): self.assertOperationAttributes(changes, "testapp", 0, 0, name="name", preserve_default=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, default=models.NOT_PROVIDED) - @mock.patch('django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', - return_value='Some Name') + @mock.patch( + 'django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration', + return_value='Some Name', + ) def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. diff --git a/tests/model_fields/test_imagefield.py b/tests/model_fields/test_imagefield.py index 50af786f5a..8fb64be464 100644 --- a/tests/model_fields/test_imagefield.py +++ b/tests/model_fields/test_imagefield.py @@ -64,8 +64,7 @@ class ImageFieldTestMixin(SerializeMixin): self.file2.close() shutil.rmtree(temp_storage_dir) - def check_dimensions(self, instance, width, height, - field_name='mugshot'): + def check_dimensions(self, instance, width, height, field_name='mugshot'): """ Asserts that the given width and height values match both the field's height and width attributes and the height and width fields @@ -363,8 +362,7 @@ class TwoImageFieldTests(ImageFieldTestMixin, TestCase): self.check_dimensions(p, 8, 4, 'headshot') def test_create(self): - p = self.PersonModel.objects.create(mugshot=self.file1, - headshot=self.file2) + p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8) self.check_dimensions(p, 8, 4, 'headshot') diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index e3c347aee6..9bbb51aef4 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -173,8 +173,7 @@ class CustomErrorMessageForm(forms.ModelForm): class ModelFormBaseTest(TestCase): def test_base_form(self): - self.assertEqual(list(BaseCategoryForm.base_fields), - ['name', 'slug', 'url']) + self.assertEqual(list(BaseCategoryForm.base_fields), ['name', 'slug', 'url']) def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): @@ -224,8 +223,7 @@ class ModelFormBaseTest(TestCase): super().__init__(*args, **kwargs) self.fields['character'].required = False - char = Character.objects.create(username='user', - last_action=datetime.datetime.today()) + char = Character.objects.create(username='user', last_action=datetime.datetime.today()) data = {'study': 'Engineering'} data2 = {'study': 'Engineering', 'character': char.pk} @@ -514,8 +512,7 @@ class ModelFormBaseTest(TestCase): """ pass - self.assertEqual(list(SubCategoryForm.base_fields), - ['name', 'slug', 'url']) + self.assertEqual(list(SubCategoryForm.base_fields), ['name', 'slug', 'url']) def test_subclassmeta_form(self): class SomeCategoryForm(forms.ModelForm): @@ -565,8 +562,7 @@ class ModelFormBaseTest(TestCase): fields = ['slug', 'url', 'name'] exclude = ['url'] - self.assertEqual(list(OrderFields2.base_fields), - ['slug', 'name']) + self.assertEqual(list(OrderFields2.base_fields), ['slug', 'name']) def test_default_populated_on_optional_field(self): class PubForm(forms.ModelForm): @@ -934,8 +930,10 @@ class UniqueTest(TestCase): }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) - self.assertEqual(form.errors['__all__'], - ['Derived book with this Suffix1 and Suffix2 already exists.']) + self.assertEqual( + form.errors['__all__'], + ['Derived book with this Suffix1 and Suffix2 already exists.'], + ) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" @@ -1107,12 +1105,9 @@ class UniqueTest(TestCase): class ModelFormBasicTests(TestCase): def create_basic_data(self): - self.c1 = Category.objects.create( - name="Entertainment", slug="entertainment", url="entertainment") - self.c2 = Category.objects.create( - name="It's a test", slug="its-test", url="test") - self.c3 = Category.objects.create( - name="Third test", slug="third-test", url="third") + self.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') + self.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') + self.c3 = Category.objects.create(name='Third test', slug='third-test', url='third') self.w_royko = Writer.objects.create(name='Mike Royko') self.w_woodward = Writer.objects.create(name='Bob Woodward') @@ -1249,8 +1244,11 @@ class ModelFormBasicTests(TestCase): return db_field.formfield(**kwargs) # Create a ModelForm, instantiate it, and check that the output is as expected - ModelForm = modelform_factory(Article, fields=['headline', 'categories'], - formfield_callback=formfield_for_dbfield) + ModelForm = modelform_factory( + Article, + fields=['headline', 'categories'], + formfield_callback=formfield_for_dbfield, + ) form = ModelForm() self.assertHTMLEqual( form.as_ul(), @@ -1558,12 +1556,9 @@ class ModelFormBasicTests(TestCase): class ModelMultipleChoiceFieldTests(TestCase): def setUp(self): - self.c1 = Category.objects.create( - name="Entertainment", slug="entertainment", url="entertainment") - self.c2 = Category.objects.create( - name="It's a test", slug="its-test", url="test") - self.c3 = Category.objects.create( - name="Third", slug="third-test", url="third") + self.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') + self.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') + self.c3 = Category.objects.create(name='Third', slug='third-test', url='third') def test_model_multiple_choice_field(self): f = forms.ModelMultipleChoiceField(Category.objects.all()) @@ -1669,9 +1664,7 @@ class ModelMultipleChoiceFieldTests(TestCase): def my_validator(value): self._validator_run = True - f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all(), - validators=[my_validator]) - + f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all(), validators=[my_validator]) f.clean([p.pk for p in Writer.objects.all()[8:9]]) self.assertTrue(self._validator_run) @@ -1680,8 +1673,7 @@ class ModelMultipleChoiceFieldTests(TestCase): Test support of show_hidden_initial by ModelMultipleChoiceField. """ class WriterForm(forms.Form): - persons = forms.ModelMultipleChoiceField(show_hidden_initial=True, - queryset=Writer.objects.all()) + persons = forms.ModelMultipleChoiceField(show_hidden_initial=True, queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") person2 = Writer.objects.create(name="Person 2") @@ -1777,8 +1769,7 @@ class ModelOneToOneFieldTests(TestCase): fields = '__all__' bw = BetterWriter.objects.create(name='Joe Better', score=10) - self.assertEqual(sorted(model_to_dict(bw)), - ['id', 'name', 'score', 'writer_ptr']) + self.assertEqual(sorted(model_to_dict(bw)), ['id', 'name', 'score', 'writer_ptr']) form = BetterWriterForm({'name': 'Some Name', 'score': 12}) self.assertTrue(form.is_valid()) @@ -1918,9 +1909,11 @@ class FileAndImageFieldTests(TestCase): form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) - form = DocumentForm(instance=doc, - files={'myfile': SimpleUploadedFile('something.txt', b'content')}, - data={'myfile-clear': 'true'}) + form = DocumentForm( + instance=doc, + files={'myfile': SimpleUploadedFile('something.txt', b'content')}, + data={'myfile-clear': 'true'}, + ) self.assertTrue(not form.is_valid()) self.assertEqual(form.errors['myfile'], ['Please either submit a file or check the clear checkbox, not both.']) @@ -1951,7 +1944,8 @@ class FileAndImageFieldTests(TestCase): # Upload a file and ensure it all works as expected. f = TextFileForm( data={'description': 'Assistance'}, - files={'file': SimpleUploadedFile('test1.txt', b'hello world')}) + files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, + ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() @@ -1961,7 +1955,8 @@ class FileAndImageFieldTests(TestCase): # If the previous file has been deleted, the file name can be reused f = TextFileForm( data={'description': 'Assistance'}, - files={'file': SimpleUploadedFile('test1.txt', b'hello world')}) + files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, + ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() @@ -1970,14 +1965,13 @@ class FileAndImageFieldTests(TestCase): # Check if the max_length attribute has been inherited from the model. f = TextFileForm( data={'description': 'Assistance'}, - files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')}) + files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')}, + ) self.assertFalse(f.is_valid()) # Edit an instance that already has the file defined in the model. This will not # save the file again, but leave it exactly as it is. - f = TextFileForm( - data={'description': 'Assistance'}, - instance=instance) + f = TextFileForm({'description': 'Assistance'}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['file'].name, 'tests/test1.txt') instance = f.save() @@ -1989,7 +1983,9 @@ class FileAndImageFieldTests(TestCase): # Override the file by uploading a new one. f = TextFileForm( data={'description': 'Assistance'}, - files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, instance=instance) + files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, + instance=instance, + ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test2.txt') @@ -2008,15 +2004,15 @@ class FileAndImageFieldTests(TestCase): f = TextFileForm( data={'description': 'Assistance'}, - files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance) + files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, + instance=instance, + ) self.assertTrue(f.is_valid()) 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. - f = TextFileForm( - data={'description': 'New Description'}, - instance=instance) + f = TextFileForm({'description': 'New Description'}, instance=instance) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() @@ -2094,7 +2090,8 @@ class FileAndImageFieldTests(TestCase): f = ImageFileForm( data={'description': 'An image'}, - files={'image': SimpleUploadedFile('test.png', image_data)}) + files={'image': SimpleUploadedFile('test.png', image_data)}, + ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() @@ -2107,7 +2104,8 @@ class FileAndImageFieldTests(TestCase): instance.image.delete(save=False) f = ImageFileForm( data={'description': 'An image'}, - files={'image': SimpleUploadedFile('test.png', image_data)}) + files={'image': SimpleUploadedFile('test.png', image_data)}, + ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() @@ -2133,7 +2131,9 @@ class FileAndImageFieldTests(TestCase): f = ImageFileForm( data={'description': 'Changed it'}, - files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance) + files={'image': SimpleUploadedFile('test2.png', image_data2)}, + instance=instance, + ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') @@ -2147,7 +2147,8 @@ class FileAndImageFieldTests(TestCase): f = ImageFileForm( data={'description': 'Changed it'}, - files={'image': SimpleUploadedFile('test2.png', image_data2)}) + files={'image': SimpleUploadedFile('test2.png', image_data2)}, + ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') @@ -2176,7 +2177,9 @@ class FileAndImageFieldTests(TestCase): f = OptionalImageFileForm( data={'description': 'And a final one'}, - files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance) + files={'image': SimpleUploadedFile('test3.png', image_data)}, + instance=instance, + ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test3.png') @@ -2185,9 +2188,7 @@ class FileAndImageFieldTests(TestCase): # Editing the instance without re-uploading the image should not affect # the image or its width/height properties. - f = OptionalImageFileForm( - data={'description': 'New Description'}, - instance=instance) + f = OptionalImageFileForm({'description': 'New Description'}, instance=instance) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') @@ -2212,7 +2213,8 @@ class FileAndImageFieldTests(TestCase): # Test 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)}) + files={'image': SimpleUploadedFile('test4.png', image_data)}, + ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'foo/test4.png') @@ -2378,8 +2380,7 @@ class OtherModelFormTests(TestCase): model = Category fields = ['description', 'url'] - self.assertEqual(list(CategoryForm.base_fields), - ['description', 'url']) + self.assertEqual(list(CategoryForm.base_fields), ['description', 'url']) self.assertHTMLEqual( str(CategoryForm()), @@ -2400,8 +2401,7 @@ class OtherModelFormTests(TestCase): self.assertQuerysetEqual(form.cleaned_data['items'], ['Core', 'Pear']) def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self): - self.assertEqual(list(CustomFieldForExclusionForm.base_fields), - ['name']) + self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ['name']) self.assertHTMLEqual( str(CustomFieldForExclusionForm()), '''