diff --git a/setup.cfg b/setup.cfg index 271b443b4f..5c671b97b7 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh [flake8] exclude = build,.git,./django/utils/lru_cache.py,./django/utils/six.py,./django/conf/app_template/*,./django/dispatch/weakref_backports.py,./tests/.env,./xmlrunner,tests/view_tests/tests/py3_test_debug.py,tests/template_tests/annotated_tag_function.py -ignore = E128,W601 +ignore = W601 max-line-length = 119 [isort] diff --git a/tests/admin_changelist/admin.py b/tests/admin_changelist/admin.py index 9402ff7291..a630c26140 100644 --- a/tests/admin_changelist/admin.py +++ b/tests/admin_changelist/admin.py @@ -12,8 +12,7 @@ site.register(User, UserAdmin) class CustomPaginator(Paginator): def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True): - super(CustomPaginator, self).__init__(queryset, 5, orphans=2, - allow_empty_first_page=allow_empty_first_page) + super(CustomPaginator, self).__init__(queryset, 5, orphans=2, allow_empty_first_page=allow_empty_first_page) class EventAdmin(admin.ModelAdmin): diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py index 505c981768..9756c0ea53 100644 --- a/tests/admin_changelist/tests.py +++ b/tests/admin_changelist/tests.py @@ -130,8 +130,7 @@ class ChangeListTests(TestCase): 'name' '-' % link ) - self.assertNotEqual(table_output.find(row_html), -1, - 'Failed to find expected row element: %s' % table_output) + self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_set_empty_value_display_on_admin_site(self): """ @@ -152,8 +151,7 @@ class ChangeListTests(TestCase): 'name' '???' % link ) - self.assertNotEqual(table_output.find(row_html), -1, - 'Failed to find expected row element: %s' % table_output) + self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_set_empty_value_display_in_model_admin(self): """ @@ -172,8 +170,7 @@ class ChangeListTests(TestCase): 'name' '†-empty-' % link ) - self.assertNotEqual(table_output.find(row_html), -1, - 'Failed to find expected row element: %s' % table_output) + self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_html(self): """ @@ -194,8 +191,7 @@ class ChangeListTests(TestCase): 'name' 'Parent object' % link ) - self.assertNotEqual(table_output.find(row_html), -1, - 'Failed to find expected row element: %s' % table_output) + self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output) def test_result_list_editable_html(self): """ @@ -894,8 +890,7 @@ class SeleniumTests(AdminSeleniumTestCase): Ensure that the status line for selected rows gets updated correctly (#22038) """ self.admin_login(username='super', password='secret') - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:auth_user_changelist'))) + self.selenium.get(self.live_server_url + reverse('admin:auth_user_changelist')) form_id = '#changelist-form' diff --git a/tests/admin_custom_urls/tests.py b/tests/admin_custom_urls/tests.py index 0a78b1afe9..11a0375ae2 100644 --- a/tests/admin_custom_urls/tests.py +++ b/tests/admin_custom_urls/tests.py @@ -73,15 +73,16 @@ class AdminCustomUrlsTest(TestCase): """ # Should get the change_view for model instance with PK 'add', not show # the add_view - url = reverse('admin_custom_urls:%s_action_change' % Action._meta.app_label, - args=(quote('add'),)) + url = reverse('admin_custom_urls:%s_action_change' % Action._meta.app_label, args=(quote('add'),)) response = self.client.get(url) self.assertContains(response, 'Change action') # Should correctly get the change_view for the model instance with the # funny-looking PK (the one with a 'path/to/html/document.html' value) - url = reverse('admin_custom_urls:%s_action_change' % Action._meta.app_label, - args=(quote("path/to/html/document.html"),)) + url = reverse( + 'admin_custom_urls:%s_action_change' % Action._meta.app_label, + args=(quote("path/to/html/document.html"),) + ) response = self.client.get(url) self.assertContains(response, 'Change action') self.assertContains(response, 'value="path/to/html/document.html"') @@ -95,12 +96,11 @@ class AdminCustomUrlsTest(TestCase): """ post_data = {'name': 'John Doe'} self.assertEqual(Person.objects.count(), 0) - response = self.client.post( - reverse('admin_custom_urls:admin_custom_urls_person_add'), post_data) + response = self.client.post(reverse('admin_custom_urls:admin_custom_urls_person_add'), post_data) persons = Person.objects.all() self.assertEqual(len(persons), 1) - self.assertRedirects( - response, reverse('admin_custom_urls:admin_custom_urls_person_history', args=[persons[0].pk])) + redirect_url = reverse('admin_custom_urls:admin_custom_urls_person_history', args=[persons[0].pk]) + self.assertRedirects(response, redirect_url) def test_post_save_change_redirect(self): """ @@ -112,11 +112,9 @@ class AdminCustomUrlsTest(TestCase): Person.objects.create(name='John Doe') self.assertEqual(Person.objects.count(), 1) person = Person.objects.all()[0] - post_data = {'name': 'Jack Doe'} - response = self.client.post( - reverse('admin_custom_urls:admin_custom_urls_person_change', args=[person.pk]), post_data) - self.assertRedirects( - response, reverse('admin_custom_urls:admin_custom_urls_person_delete', args=[person.pk])) + post_url = reverse('admin_custom_urls:admin_custom_urls_person_change', args=[person.pk]) + response = self.client.post(post_url, {'name': 'Jack Doe'}) + self.assertRedirects(response, reverse('admin_custom_urls:admin_custom_urls_person_delete', args=[person.pk])) def test_post_url_continue(self): """ @@ -125,9 +123,7 @@ class AdminCustomUrlsTest(TestCase): """ post_data = {'name': 'SuperFast', '_continue': '1'} self.assertEqual(Car.objects.count(), 0) - response = self.client.post( - reverse('admin_custom_urls:admin_custom_urls_car_add'), post_data) + response = self.client.post(reverse('admin_custom_urls:admin_custom_urls_car_add'), post_data) cars = Car.objects.all() self.assertEqual(len(cars), 1) - self.assertRedirects( - response, reverse('admin_custom_urls:admin_custom_urls_car_history', args=[cars[0].pk])) + self.assertRedirects(response, reverse('admin_custom_urls:admin_custom_urls_car_history', args=[cars[0].pk])) diff --git a/tests/admin_docs/tests.py b/tests/admin_docs/tests.py index 20c542a53b..ec35f92627 100644 --- a/tests/admin_docs/tests.py +++ b/tests/admin_docs/tests.py @@ -54,14 +54,11 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): self.client.logout() response = self.client.get(reverse('django-admindocs-docroot'), follow=True) # Should display the login screen - self.assertContains(response, - '', html=True) + self.assertContains(response, '', html=True) self.client.force_login(self.superuser) response = self.client.get(reverse('django-admindocs-docroot')) self.assertContains(response, '

Documentation

', html=True) - self.assertContains(response, - '

Django ' - 'administration

') + self.assertContains(response, '

Django administration

') def test_bookmarklets(self): response = self.client.get(reverse('django-admindocs-bookmarklets')) @@ -77,16 +74,17 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): def test_view_index(self): response = self.client.get(reverse('django-admindocs-views-index')) - self.assertContains(response, + self.assertContains( + response, '

/admindocs/

', - html=True) + html=True + ) self.assertContains(response, 'Views by namespace test') self.assertContains(response, 'Name: test:func.') def test_view_detail(self): - response = self.client.get( - reverse('django-admindocs-views-detail', - args=['django.contrib.admindocs.views.BaseAdminDocsView'])) + url = reverse('django-admindocs-views-detail', args=['django.contrib.admindocs.views.BaseAdminDocsView']) + response = self.client.get(url) # View docstring self.assertContains(response, 'Base view for admindocs views.') @@ -94,9 +92,8 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): """ #23601 - Ensure the view exists in the URLconf. """ - response = self.client.get( - reverse('django-admindocs-views-detail', - args=['urlpatterns_reverse.nonimported_module.view'])) + url = reverse('django-admindocs-views-detail', args=['urlpatterns_reverse.nonimported_module.view']) + response = self.client.get(url) self.assertEqual(response.status_code, 404) self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules) @@ -109,22 +106,20 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase): ) def test_template_detail(self): - response = self.client.get(reverse('django-admindocs-templates', - args=['admin_doc/template_detail.html'])) - self.assertContains(response, - '

Template: "admin_doc/template_detail.html"

', html=True) + response = self.client.get(reverse('django-admindocs-templates', args=['admin_doc/template_detail.html'])) + self.assertContains(response, '

Template: "admin_doc/template_detail.html"

', html=True) def test_missing_docutils(self): utils.docutils_is_available = False try: response = self.client.get(reverse('django-admindocs-docroot')) - self.assertContains(response, + self.assertContains( + response, '

The admin documentation system requires Python\'s ' 'docutils library.

', - html=True) - self.assertContains(response, - '

Django ' - 'administration

') + html=True + ) + self.assertContains(response, '

Django administration

') finally: utils.docutils_is_available = True @@ -200,18 +195,12 @@ class DefaultRoleTest(AdminDocsTestCase): ``django.contrib.admindocs.utils.parse_rst`` should use ``cmsreference`` as the default role. """ - markup = ('

' - 'title

\n') - self.assertEqual(utils.parse_rst('`title`', 'model'), - markup % 'models/title/') - self.assertEqual(utils.parse_rst('`title`', 'view'), - markup % 'views/title/') - self.assertEqual(utils.parse_rst('`title`', 'template'), - markup % 'templates/title/') - self.assertEqual(utils.parse_rst('`title`', 'filter'), - markup % 'filters/#title') - self.assertEqual(utils.parse_rst('`title`', 'tag'), - markup % 'tags/#title') + markup = '

title

\n' + self.assertEqual(utils.parse_rst('`title`', 'model'), markup % 'models/title/') + self.assertEqual(utils.parse_rst('`title`', 'view'), markup % 'views/title/') + self.assertEqual(utils.parse_rst('`title`', 'template'), markup % 'templates/title/') + self.assertEqual(utils.parse_rst('`title`', 'filter'), markup % 'filters/#title') + self.assertEqual(utils.parse_rst('`title`', 'tag'), markup % 'tags/#title') def test_publish_parts(self): """ @@ -220,8 +209,7 @@ class DefaultRoleTest(AdminDocsTestCase): ``cmsreference``. See #6681. """ import docutils - self.assertNotEqual(docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, - 'cmsreference') + self.assertNotEqual(docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, 'cmsreference') source = 'reST, `interpreted text`, default role.' markup = '

reST, interpreted text, default role.

\n' parts = docutils.core.publish_parts(source=source, writer_name="html4css1") @@ -286,21 +274,9 @@ class TestModelDetailView(TestDataMixin, AdminDocsTestCase): by a method """ company = Company.objects.create(name="Django") - person = Person.objects.create( - first_name="Human", - last_name="User", - company=company - ) - - self.assertEqual( - get_return_data_type(person.get_status_count.__name__), - 'Integer' - ) - - self.assertEqual( - get_return_data_type(person.get_groups_list.__name__), - 'List' - ) + person = Person.objects.create(first_name="Human", last_name="User", company=company) + self.assertEqual(get_return_data_type(person.get_status_count.__name__), 'Integer') + self.assertEqual(get_return_data_type(person.get_groups_list.__name__), 'List') def test_descriptions_render_correctly(self): """ @@ -361,10 +337,7 @@ class TestModelDetailView(TestDataMixin, AdminDocsTestCase): A model with ``related_name`` of `+` should not show backward relationship links in admin docs """ - response = self.client.get( - reverse('django-admindocs-models-detail', - args=['admin_docs', 'family'])) - + response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'family'])) fields = response.context_data.get('fields') self.assertEqual(len(fields), 2) diff --git a/tests/admin_inlines/admin.py b/tests/admin_inlines/admin.py index b7fd6424d6..64c89ebe99 100644 --- a/tests/admin_inlines/admin.py +++ b/tests/admin_inlines/admin.py @@ -37,9 +37,10 @@ class EditablePKBookStackedInline(admin.StackedInline): class AuthorAdmin(admin.ModelAdmin): - inlines = [BookInline, - NonAutoPKBookTabularInline, NonAutoPKBookStackedInline, - EditablePKBookTabularInline, EditablePKBookStackedInline] + inlines = [ + BookInline, NonAutoPKBookTabularInline, NonAutoPKBookStackedInline, + EditablePKBookTabularInline, EditablePKBookStackedInline, + ] class InnerInline(admin.StackedInline): diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py index 9a3dc4888a..dc94999de4 100644 --- a/tests/admin_inlines/tests.py +++ b/tests/admin_inlines/tests.py @@ -185,22 +185,28 @@ class TestInline(TestDataMixin, TestCase): prefixes. Bug #16838. """ response = self.client.get(reverse('admin:admin_inlines_capofamiglia_add')) - - self.assertContains(response, - '', html=True) - self.assertContains(response, - '', html=True) - self.assertContains(response, - '', html=True) - - self.assertContains(response, - '', html=True) - self.assertContains(response, - '', html=True) - self.assertContains(response, - '', html=True) + self.assertContains(response, '', html=True) + self.assertContains( + response, + '', + html=True + ) + self.assertContains( + response, + '', + html=True + ) + self.assertContains(response, '', html=True) + self.assertContains( + response, + '', + html=True + ) + self.assertContains( + response, + '', + html=True + ) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_localize_pk_shortcut(self): @@ -622,8 +628,11 @@ class TestInlinePermissions(TestCase): 'name="inner2_set-TOTAL_FORMS" />', html=True ) - self.assertNotContains(response, '' % self.inner2_id, html=True) + self.assertNotContains( + response, + '' % self.inner2_id, + html=True + ) def test_inline_change_fk_change_perm(self): permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) @@ -632,13 +641,21 @@ class TestInlinePermissions(TestCase): # Change permission on inner2s, so we can change existing but not add new self.assertContains(response, '

Inner2s

') # Just the one form for existing instances - self.assertContains(response, '', html=True) - self.assertContains(response, '' % self.inner2_id, html=True) + self.assertContains( + response, '', + html=True + ) + self.assertContains( + response, + '' % self.inner2_id, + html=True + ) # max-num 0 means we can't add new ones - self.assertContains(response, '', html=True) + self.assertContains( + response, + '', + html=True + ) def test_inline_change_fk_add_change_perm(self): permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) @@ -649,10 +666,15 @@ class TestInlinePermissions(TestCase): # Add/change perm, so we can add new and change existing self.assertContains(response, '

Inner2s

') # One form for existing instance and three extra for new - self.assertContains(response, '', html=True) - self.assertContains(response, '' % self.inner2_id, html=True) + self.assertContains( + response, '', + html=True + ) + self.assertContains( + response, + '' % self.inner2_id, + html=True + ) def test_inline_change_fk_change_del_perm(self): permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) @@ -663,10 +685,16 @@ class TestInlinePermissions(TestCase): # Change/delete perm on inner2s, so we can change/delete existing self.assertContains(response, '

Inner2s

') # One form for existing instance only, no new - self.assertContains(response, '', html=True) - self.assertContains(response, '' % self.inner2_id, html=True) + self.assertContains( + response, + '', + html=True + ) + self.assertContains( + response, + '' % self.inner2_id, + html=True + ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') def test_inline_change_fk_all_perms(self): @@ -680,10 +708,16 @@ class TestInlinePermissions(TestCase): # All perms on inner2s, so we can add/change/delete self.assertContains(response, '

Inner2s

') # One form for existing instance only, three for new - self.assertContains(response, '', html=True) - self.assertContains(response, '' % self.inner2_id, html=True) + self.assertContains( + response, + '', + html=True + ) + self.assertContains( + response, + '' % self.inner2_id, + html=True + ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') @@ -701,8 +735,7 @@ class SeleniumTests(AdminSeleniumTestCase): stacked formset. """ self.admin_login(username='super', password='secret') - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_inlines_holder4_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_holder4_add')) inline_id = '#inner4stacked_set-group' @@ -718,8 +751,7 @@ class SeleniumTests(AdminSeleniumTestCase): def test_delete_stackeds(self): self.admin_login(username='super', password='secret') - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_inlines_holder4_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_holder4_add')) inline_id = '#inner4stacked_set-group' @@ -733,8 +765,7 @@ class SeleniumTests(AdminSeleniumTestCase): add_button.click() self.assertEqual(rows_length(), 5, msg="sanity check") - for delete_link in self.selenium.find_elements_by_css_selector( - '%s .inline-deletelink' % inline_id): + for delete_link in self.selenium.find_elements_by_css_selector('%s .inline-deletelink' % inline_id): delete_link.click() self.assertEqual(rows_length(), 3) @@ -744,8 +775,7 @@ class SeleniumTests(AdminSeleniumTestCase): inline form. """ self.admin_login(username='super', password='secret') - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_inlines_profilecollection_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add')) # Check that there's only one inline to start with and that it has the # correct ID. @@ -764,8 +794,7 @@ class SeleniumTests(AdminSeleniumTestCase): # Check that the inline has been added, that it has the right id, and # that it contains the right fields. - self.assertEqual(len(self.selenium.find_elements_by_css_selector( - '.dynamic-profile_set')), 2) + self.assertEqual(len(self.selenium.find_elements_by_css_selector('.dynamic-profile_set')), 2) self.assertEqual(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set')[1].get_attribute('id'), 'profile_set-1') self.assertEqual(len(self.selenium.find_elements_by_css_selector( @@ -775,8 +804,7 @@ class SeleniumTests(AdminSeleniumTestCase): # Let's add another one to be sure self.selenium.find_element_by_link_text('Add another Profile').click() - self.assertEqual(len(self.selenium.find_elements_by_css_selector( - '.dynamic-profile_set')), 3) + self.assertEqual(len(self.selenium.find_elements_by_css_selector('.dynamic-profile_set')), 3) self.assertEqual(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set')[2].get_attribute('id'), 'profile_set-2') self.assertEqual(len(self.selenium.find_elements_by_css_selector( @@ -801,8 +829,7 @@ class SeleniumTests(AdminSeleniumTestCase): def test_delete_inlines(self): self.admin_login(username='super', password='secret') - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_inlines_profilecollection_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add')) # Add a few inlines self.selenium.find_element_by_link_text('Add another Profile').click() @@ -839,8 +866,7 @@ class SeleniumTests(AdminSeleniumTestCase): def test_alternating_rows(self): self.admin_login(username='super', password='secret') - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_inlines_profilecollection_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add')) # Add a few inlines self.selenium.find_element_by_link_text('Add another Profile').click() diff --git a/tests/admin_scripts/management/commands/custom_startproject.py b/tests/admin_scripts/management/commands/custom_startproject.py index 0d9c7d339e..3fa19d98cc 100644 --- a/tests/admin_scripts/management/commands/custom_startproject.py +++ b/tests/admin_scripts/management/commands/custom_startproject.py @@ -4,5 +4,4 @@ from django.core.management.commands.startproject import Command as BaseCommand class Command(BaseCommand): def add_arguments(self, parser): super(Command, self).add_arguments(parser) - parser.add_argument('--extra', - help='An arbitrary extra value passed to the context') + parser.add_argument('--extra', help='An arbitrary extra value passed to the context') diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py index b7b1ecbf97..fd7b7869ba 100644 --- a/tests/admin_scripts/tests.py +++ b/tests/admin_scripts/tests.py @@ -161,9 +161,11 @@ class AdminScriptTestCase(unittest.TestCase): # Move to the test directory and run os.chdir(self.test_dir) - out, err = subprocess.Popen([sys.executable, script] + args, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - env=test_environ, universal_newlines=True).communicate() + out, err = subprocess.Popen( + [sys.executable, script] + args, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + env=test_environ, universal_newlines=True, + ).communicate() # Move back to the old working directory os.chdir(old_cwd) @@ -204,8 +206,10 @@ class AdminScriptTestCase(unittest.TestCase): "Utility assertion: assert that the given message exists in the output" stream = force_text(stream) if regex: - self.assertIsNotNone(re.search(msg, stream), - "'%s' does not match actual output text '%s'" % (msg, stream)) + self.assertIsNotNone( + re.search(msg, stream), + "'%s' does not match actual output text '%s'" % (msg, stream) + ) else: self.assertIn(msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream)) @@ -1146,9 +1150,11 @@ class ManageCheck(AdminScriptTestCase): """ manage.py check reports an error on a non-existent app in INSTALLED_APPS """ - self.write_settings('settings.py', + self.write_settings( + 'settings.py', apps=['admin_scriptz.broken_app'], - sdict={'USE_I18N': False}) + sdict={'USE_I18N': False}, + ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(out) @@ -1192,12 +1198,16 @@ class ManageCheck(AdminScriptTestCase): """ manage.py check does not raise errors when an app imports a base class that itself has an abstract base. """ - self.write_settings('settings.py', - apps=['admin_scripts.app_with_import', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sites'], - sdict={'DEBUG': True}) + self.write_settings( + 'settings.py', + apps=[ + 'admin_scripts.app_with_import', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sites', + ], + sdict={'DEBUG': True}, + ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(err) @@ -1206,11 +1216,15 @@ class ManageCheck(AdminScriptTestCase): def test_output_format(self): """ All errors/warnings should be sorted by level and by message. """ - self.write_settings('settings.py', - apps=['admin_scripts.app_raising_messages', - 'django.contrib.auth', - 'django.contrib.contenttypes'], - sdict={'DEBUG': True}) + self.write_settings( + 'settings.py', + apps=[ + 'admin_scripts.app_raising_messages', + 'django.contrib.auth', + 'django.contrib.contenttypes', + ], + sdict={'DEBUG': True}, + ) args = ['check'] out, err = self.run_manage(args) expected_err = ( @@ -1239,11 +1253,15 @@ class ManageCheck(AdminScriptTestCase): In this test we also test output format. """ - self.write_settings('settings.py', - apps=['admin_scripts.app_raising_warning', - 'django.contrib.auth', - 'django.contrib.contenttypes'], - sdict={'DEBUG': True}) + self.write_settings( + 'settings.py', + apps=[ + 'admin_scripts.app_raising_warning', + 'django.contrib.auth', + 'django.contrib.contenttypes', + ], + sdict={'DEBUG': True}, + ) args = ['check'] out, err = self.run_manage(args) expected_err = ( @@ -2049,8 +2067,7 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase): for f in ('Procfile', 'additional_file.py', 'requirements.txt'): self.assertTrue(os.path.exists(os.path.join(base_path, f))) with open(os.path.join(base_path, f)) as fh: - self.assertEqual(fh.read().strip(), - '# some file for customtestproject test project') + self.assertEqual(fh.read().strip(), '# some file for customtestproject test project') def test_custom_project_template_context_variables(self): "Make sure template context variables are rendered with proper values" diff --git a/tests/admin_utils/tests.py b/tests/admin_utils/tests.py index 0da9143c19..93c78d0e90 100644 --- a/tests/admin_utils/tests.py +++ b/tests/admin_utils/tests.py @@ -263,9 +263,7 @@ class UtilsTests(SimpleTestCase): "not Really the Model" ) self.assertEqual( - label_for_field("test_from_model", Article, - model_admin=MockModelAdmin, - return_attr=True), + label_for_field("test_from_model", Article, model_admin=MockModelAdmin, return_attr=True), ("not Really the Model", MockModelAdmin.test_from_model) ) diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index a4ddde3af5..f4dfb91bef 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -208,8 +208,7 @@ class PersonAdmin(admin.ModelAdmin): save_as = True def get_changelist_formset(self, request, **kwargs): - return super(PersonAdmin, self).get_changelist_formset(request, - formset=BasePersonModelFormSet, **kwargs) + return super(PersonAdmin, self).get_changelist_formset(request, formset=BasePersonModelFormSet, **kwargs) def get_queryset(self, request): # Order by a field that isn't in list display, to be able to test diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py index 7cd5bdd8b9..301955efd8 100644 --- a/tests/admin_views/models.py +++ b/tests/admin_views/models.py @@ -812,8 +812,10 @@ class Simple(models.Model): class Choice(models.Model): - choice = models.IntegerField(blank=True, null=True, - choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion'))) + choice = models.IntegerField( + blank=True, null=True, + choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion')), + ) class ParentWithDependentChildren(models.Model): diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py index ab82f64793..48ce1770fb 100644 --- a/tests/admin_views/tests.py +++ b/tests/admin_views/tests.py @@ -230,8 +230,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase): def test_add_with_GET_args(self): response = self.client.get(reverse('admin:admin_views_section_add'), {'name': 'My Section'}) - self.assertContains(response, 'value="My Section"', - msg_prefix="Couldn't find an input with the right value in the response") + self.assertContains( + response, 'value="My Section"', + msg_prefix="Couldn't find an input with the right value in the response" + ) def test_basic_edit_GET(self): """ @@ -352,10 +354,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase): (column 2 is callable_year in ArticleAdmin) """ response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': 2}) - self.assertContentBefore(response, 'Oldest content', 'Middle content', - "Results of sorting on callable are out of order.") - self.assertContentBefore(response, 'Middle content', 'Newest content', - "Results of sorting on callable are out of order.") + self.assertContentBefore( + response, 'Oldest content', 'Middle content', + "Results of sorting on callable are out of order." + ) + self.assertContentBefore( + response, 'Middle content', 'Newest content', + "Results of sorting on callable are out of order." + ) def test_change_list_sorting_model(self): """ @@ -363,10 +369,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase): (column 3 is 'model_year' in ArticleAdmin) """ response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '-3'}) - self.assertContentBefore(response, 'Newest content', 'Middle content', - "Results of sorting on Model method are out of order.") - self.assertContentBefore(response, 'Middle content', 'Oldest content', - "Results of sorting on Model method are out of order.") + self.assertContentBefore( + response, 'Newest content', 'Middle content', + "Results of sorting on Model method are out of order." + ) + self.assertContentBefore( + response, 'Middle content', 'Oldest content', + "Results of sorting on Model method are out of order." + ) def test_change_list_sorting_model_admin(self): """ @@ -374,10 +384,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase): (column 4 is 'modeladmin_year' in ArticleAdmin) """ response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '4'}) - self.assertContentBefore(response, 'Oldest content', 'Middle content', - "Results of sorting on ModelAdmin method are out of order.") - self.assertContentBefore(response, 'Middle content', 'Newest content', - "Results of sorting on ModelAdmin method are out of order.") + self.assertContentBefore( + response, 'Oldest content', 'Middle content', + "Results of sorting on ModelAdmin method are out of order." + ) + self.assertContentBefore( + response, 'Middle content', 'Newest content', + "Results of sorting on ModelAdmin method are out of order." + ) def test_change_list_sorting_model_admin_reverse(self): """ @@ -386,17 +400,25 @@ class AdminViewBasicTest(AdminViewBasicTestCase): (column 6 is 'model_year_reverse' in ArticleAdmin) """ response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '6'}) - self.assertContentBefore(response, '2009', '2008', - "Results of sorting on ModelAdmin method are out of order.") - self.assertContentBefore(response, '2008', '2000', - "Results of sorting on ModelAdmin method are out of order.") + self.assertContentBefore( + response, '2009', '2008', + "Results of sorting on ModelAdmin method are out of order." + ) + self.assertContentBefore( + response, '2008', '2000', + "Results of sorting on ModelAdmin method are out of order." + ) # Let's make sure the ordering is right and that we don't get a # FieldError when we change to descending order response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '-6'}) - self.assertContentBefore(response, '2000', '2008', - "Results of sorting on ModelAdmin method are out of order.") - self.assertContentBefore(response, '2008', '2009', - "Results of sorting on ModelAdmin method are out of order.") + self.assertContentBefore( + response, '2000', '2008', + "Results of sorting on ModelAdmin method are out of order." + ) + self.assertContentBefore( + response, '2008', '2009', + "Results of sorting on ModelAdmin method are out of order." + ) def test_change_list_sorting_multiple(self): p1 = Person.objects.create(name="Chris", gender=1, alive=True) @@ -521,10 +543,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase): This also tests relation-spanning filters (e.g. 'color__value'). """ response = self.client.get(reverse('admin:admin_views_thing_changelist')) - self.assertContains(response, '
', - msg_prefix="Expected filter not found in changelist view") - self.assertNotContains(response, 'Blue', - msg_prefix="Changelist filter not correctly limited by limit_choices_to") + self.assertContains( + response, '
', + msg_prefix="Expected filter not found in changelist view" + ) + self.assertNotContains( + response, 'Blue', + msg_prefix="Changelist filter not correctly limited by limit_choices_to" + ) def test_relation_spanning_filters(self): changelist_url = reverse('admin:admin_views_chapterxtra1_changelist') @@ -626,10 +652,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase): "field 'choices' option named group." ) self.assertContains(response, '
') - self.assertContains(response, - 'Horizontal', msg_prefix=fail_msg, html=True) - self.assertContains(response, - 'Vertical', msg_prefix=fail_msg, html=True) + self.assertContains(response, 'Horizontal', msg_prefix=fail_msg, html=True) + self.assertContains(response, 'Vertical', msg_prefix=fail_msg, html=True) def test_change_list_null_boolean_display(self): Post.objects.create(public=None) @@ -789,8 +813,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase): user.save() self.client.force_login(user) response = self.client.get(reverse('admin:index')) - self.assertNotContains(response, reverse('admin:password_change'), - msg_prefix='The "change password" link should not be displayed if a user does not have a usable password.') + self.assertNotContains( + response, reverse('admin:password_change'), + msg_prefix='The "change password" link should not be displayed if a user does not have a usable password.' + ) def test_change_view_with_show_delete_extra_context(self): """ @@ -1514,8 +1540,10 @@ class AdminViewPermissionsTest(TestCase): self.client.force_login(self.adduser) addpage = self.client.get(reverse('admin:admin_views_article_add')) change_list_link = '› Articles' % reverse('admin:admin_views_article_changelist') - self.assertNotContains(addpage, change_list_link, - msg_prefix='User restricted to add permission is given link to change list view in breadcrumbs.') + self.assertNotContains( + addpage, change_list_link, + msg_prefix='User restricted to add permission is given link to change list view in breadcrumbs.' + ) post = self.client.post(reverse('admin:admin_views_article_add'), add_dict) self.assertRedirects(post, self.index_url) self.assertEqual(Article.objects.count(), 4) @@ -1537,8 +1565,10 @@ class AdminViewPermissionsTest(TestCase): # Super can add too, but is redirected to the change list view self.client.force_login(self.superuser) addpage = self.client.get(reverse('admin:admin_views_article_add')) - self.assertContains(addpage, change_list_link, - msg_prefix='Unrestricted user is not given link to change list view in breadcrumbs.') + self.assertContains( + addpage, change_list_link, + msg_prefix='Unrestricted user is not given link to change list view in breadcrumbs.' + ) post = self.client.post(reverse('admin:admin_views_article_add'), add_dict) self.assertRedirects(post, reverse('admin:admin_views_article_changelist')) self.assertEqual(Article.objects.count(), 5) @@ -1584,13 +1614,17 @@ class AdminViewPermissionsTest(TestCase): # one error in form should produce singular error message, multiple errors plural change_dict['title'] = '' post = self.client.post(article_change_url, change_dict) - self.assertContains(post, 'Please correct the error below.', - msg_prefix='Singular error message not found in response to post with one error') + self.assertContains( + post, 'Please correct the error below.', + msg_prefix='Singular error message not found in response to post with one error' + ) change_dict['content'] = '' post = self.client.post(article_change_url, change_dict) - self.assertContains(post, 'Please correct the errors below.', - msg_prefix='Plural error message not found in response to post with multiple errors') + self.assertContains( + post, 'Please correct the errors below.', + msg_prefix='Plural error message not found in response to post with multiple errors' + ) self.client.get(reverse('admin:logout')) # Test redirection when using row-level change permissions. Refs #11513. @@ -2292,14 +2326,16 @@ class AdminViewStringPrimaryKeyTest(TestCase): def test_change_view_history_link(self): """Object history button link should work and contain the pk value quoted.""" - url = reverse('admin:%s_modelwithstringprimarykey_change' % - ModelWithStringPrimaryKey._meta.app_label, - args=(quote(self.pk),)) + url = reverse( + 'admin:%s_modelwithstringprimarykey_change' % ModelWithStringPrimaryKey._meta.app_label, + args=(quote(self.pk),) + ) response = self.client.get(url) self.assertEqual(response.status_code, 200) - expected_link = reverse('admin:%s_modelwithstringprimarykey_history' % - ModelWithStringPrimaryKey._meta.app_label, - args=(quote(self.pk),)) + expected_link = reverse( + 'admin:%s_modelwithstringprimarykey_history' % ModelWithStringPrimaryKey._meta.app_label, + args=(quote(self.pk),) + ) self.assertContains(response, '1 result (3 total)""", - html=True) + html=True + ) def test_no_total_count(self): """ @@ -2952,9 +2989,11 @@ class AdminSearchTest(TestCase): # + 1 for filtered result + 1 for filtered count with self.assertNumQueries(4): response = self.client.get(reverse('admin:admin_views_recommendation_changelist') + '?q=bar') - self.assertContains(response, + self.assertContains( + response, """1 result (Show all)""", - html=True) + html=True + ) self.assertTrue(response.context['cl'].show_admin_actions) @@ -3244,16 +3283,20 @@ action) "Tests a ModelAdmin without any action" response = self.client.get(reverse('admin:admin_views_oldsubscriber_changelist')) self.assertEqual(response.context["action_form"], None) - self.assertNotContains(response, 'Awesomeness level:") + self.assertContains(response, "") self.assertContains(response, "Very awesome.") self.assertContains(response, "Unknown coolness.") self.assertContains(response, "foo") @@ -4511,8 +4536,7 @@ class ReadonlyTest(AdminFieldExtractionMixin, TestCase): # Remove only this last line when the deprecation completes. self.assertContains(response, "

Multiline
html
content
with allow tags

", html=True) - self.assertContains(response, - formats.localize(datetime.date.today() - datetime.timedelta(days=7))) + self.assertContains(response, formats.localize(datetime.date.today() - datetime.timedelta(days=7))) self.assertContains(response, '
') self.assertContains(response, '
') @@ -4828,8 +4852,7 @@ class UserAdminTest(TestCase): self.assertEqual(response.status_code, 200) adminform = response.context['adminform'] self.assertNotIn('password', adminform.form.errors) - self.assertEqual(adminform.form.errors['password2'], - ["The two password fields didn't match."]) + self.assertEqual(adminform.form.errors['password2'], ["The two password fields didn't match."]) def test_user_fk_add_popup(self): """User addition through a FK popup should return the appropriate JavaScript response.""" @@ -5019,26 +5042,22 @@ class CSSTest(TestCase): Ensure app and model tag are correctly read by change_form template """ response = self.client.get(reverse('admin:admin_views_section_add')) - self.assertContains(response, - '') - self.assertContains( - response, '') - self.assertContains( - response, '') + self.assertContains(response, '') + self.assertContains(response, '') + self.assertContains(response, '') try: diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py index 18d3f7b7e1..058f303016 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -215,18 +215,15 @@ class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase): # Try posting with a non-existent pk in a raw id field: this # should result in an error message, not a server exception. response = self.client.post(reverse('admin:admin_widgets_event_add'), post_data) - self.assertContains(response, - 'Select a valid choice. That choice is not one of the available choices.') + self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_invalid_target_id(self): for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): # This should result in an error message, not a server exception. - response = self.client.post(reverse('admin:admin_widgets_event_add'), - {"main_band": test_str}) + response = self.client.post(reverse('admin:admin_widgets_event_add'), {"main_band": test_str}) - self.assertContains(response, - 'Select a valid choice. That choice is not one of the available choices.') + self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.') def test_url_params_from_lookup_dict_any_iterable(self): lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')}) @@ -634,33 +631,27 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_widgets_member_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # First, with the date picker widget --------------------------------- # Check that the date picker is hidden - self.assertEqual( - self.get_css_value('#calendarbox0', 'display'), 'none') + self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none') # Click the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # Check that the date picker is visible - self.assertEqual( - self.get_css_value('#calendarbox0', 'display'), 'block') + self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'block') # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # Check that the date picker is hidden again - self.assertEqual( - self.get_css_value('#calendarbox0', 'display'), 'none') + self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none') # Then, with the time picker widget ---------------------------------- # Check that the time picker is hidden - self.assertEqual( - self.get_css_value('#clockbox0', 'display'), 'none') + self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'none') # Click the time icon self.selenium.find_element_by_id('clocklink0').click() # Check that the time picker is visible - self.assertEqual( - self.get_css_value('#clockbox0', 'display'), 'block') + self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'block') self.assertEqual( [ x.text for x in @@ -671,8 +662,7 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): # Press the ESC key self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) # Check that the time picker is hidden again - self.assertEqual( - self.get_css_value('#clockbox0', 'display'), 'none') + self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'none') def test_calendar_nonday_class(self): """ @@ -681,8 +671,7 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): """ self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_widgets_member_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # fill in the birth date. self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01') @@ -705,8 +694,7 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): """ self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_widgets_member_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # fill in the birth date. self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01') @@ -731,8 +719,7 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): """ self.admin_login(username='super', password='secret', login_url='/') # Open a page that has a date and time picker widgets - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_widgets_member_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) # Click the calendar icon self.selenium.find_element_by_id('calendarlink0').click() @@ -777,9 +764,8 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase): with override_settings(LANGUAGE_CODE=language_code, USE_L10N=True): # Open a page that has a date picker widget - self.selenium.get('{}{}'.format(self.live_server_url, - reverse('admin:admin_widgets_member_change', args=(member.pk,)))) - + url = reverse('admin:admin_widgets_member_change', args=(member.pk,)) + self.selenium.get(self.live_server_url + url) # Click on the calendar icon self.selenium.find_element_by_id('calendarlink0').click() # Make sure that the right month and year are displayed @@ -813,14 +799,12 @@ class DateTimePickerShortcutsSeleniumTests(AdminWidgetSeleniumTestCase): now = datetime.now() - self.selenium.get('%s%s' % (self.live_server_url, - reverse('admin:admin_widgets_member_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add')) self.selenium.find_element_by_id('id_name').send_keys('test') # Click on the "today" and "now" shortcuts. - shortcuts = self.selenium.find_elements_by_css_selector( - '.field-birthdate .datetimeshortcuts') + shortcuts = self.selenium.find_elements_by_css_selector('.field-birthdate .datetimeshortcuts') for shortcut in shortcuts: shortcut.find_element_by_tag_name('a').click() @@ -829,8 +813,7 @@ class DateTimePickerShortcutsSeleniumTests(AdminWidgetSeleniumTestCase): # Warning: This would effectively fail if the TIME_ZONE defined in the # settings has the same UTC offset as "Asia/Singapore" because the # mismatch warning would be rightfully missing from the page. - self.selenium.find_elements_by_css_selector( - '.field-birthdate .timezonewarning') + self.selenium.find_elements_by_css_selector('.field-birthdate .timezonewarning') # Submit the form. self.selenium.find_element_by_tag_name('form').submit() @@ -864,8 +847,7 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): self.arthur = models.Student.objects.create(name='Arthur') self.school = models.School.objects.create(name='School of Awesome') - def assertActiveButtons(self, mode, field_name, choose, remove, - choose_all=None, remove_all=None): + def assertActiveButtons(self, mode, field_name, choose, remove, choose_all=None, remove_all=None): choose_link = '#id_%s_add_link' % field_name choose_all_link = '#id_%s_add_all_link' % field_name remove_link = '#id_%s_remove_link' % field_name @@ -885,12 +867,12 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): remove_all_link = 'id_%s_remove_all_link' % field_name # Initial positions --------------------------------------------------- - self.assertSelectOptions(from_box, - [str(self.arthur.id), str(self.bob.id), - str(self.cliff.id), str(self.jason.id), - str(self.jenny.id), str(self.john.id)]) - self.assertSelectOptions(to_box, - [str(self.lisa.id), str(self.peter.id)]) + self.assertSelectOptions(from_box, [ + str(self.arthur.id), str(self.bob.id), + str(self.cliff.id), str(self.jason.id), + str(self.jenny.id), str(self.john.id), + ]) + self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)]) self.assertActiveButtons(mode, field_name, False, False, True, True) # Click 'Choose all' -------------------------------------------------- @@ -903,11 +885,12 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): option.click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, []) - self.assertSelectOptions(to_box, - [str(self.lisa.id), str(self.peter.id), - str(self.arthur.id), str(self.bob.id), - str(self.cliff.id), str(self.jason.id), - str(self.jenny.id), str(self.john.id)]) + self.assertSelectOptions(to_box, [ + str(self.lisa.id), str(self.peter.id), + str(self.arthur.id), str(self.bob.id), + str(self.cliff.id), str(self.jason.id), + str(self.jenny.id), str(self.john.id), + ]) self.assertActiveButtons(mode, field_name, False, False, False, True) # Click 'Remove all' -------------------------------------------------- @@ -919,11 +902,12 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'): option.click() self.selenium.find_element_by_id(remove_link).click() - self.assertSelectOptions(from_box, - [str(self.lisa.id), str(self.peter.id), - str(self.arthur.id), str(self.bob.id), - str(self.cliff.id), str(self.jason.id), - str(self.jenny.id), str(self.john.id)]) + self.assertSelectOptions(from_box, [ + str(self.lisa.id), str(self.peter.id), + str(self.arthur.id), str(self.bob.id), + str(self.cliff.id), str(self.jason.id), + str(self.jenny.id), str(self.john.id), + ]) self.assertSelectOptions(to_box, []) self.assertActiveButtons(mode, field_name, False, False, True, False) @@ -941,12 +925,14 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): self.selenium.find_element_by_id(choose_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) - self.assertSelectOptions(from_box, - [str(self.peter.id), str(self.arthur.id), - str(self.cliff.id), str(self.jenny.id)]) - self.assertSelectOptions(to_box, - [str(self.lisa.id), str(self.bob.id), - str(self.jason.id), str(self.john.id)]) + self.assertSelectOptions(from_box, [ + str(self.peter.id), str(self.arthur.id), + str(self.cliff.id), str(self.jenny.id), + ]) + self.assertSelectOptions(to_box, [ + str(self.lisa.id), str(self.bob.id), + str(self.jason.id), str(self.john.id), + ]) # Check the tooltip is still there after moving: ticket #20821 to_lisa_select_option = self.get_select_option(to_box, str(self.lisa.id)) @@ -959,32 +945,33 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): self.selenium.find_element_by_id(remove_link).click() self.assertActiveButtons(mode, field_name, False, False, True, True) - self.assertSelectOptions(from_box, - [str(self.peter.id), str(self.arthur.id), - str(self.cliff.id), str(self.jenny.id), - str(self.lisa.id), str(self.bob.id)]) - self.assertSelectOptions(to_box, - [str(self.jason.id), str(self.john.id)]) + self.assertSelectOptions(from_box, [ + str(self.peter.id), str(self.arthur.id), + str(self.cliff.id), str(self.jenny.id), + str(self.lisa.id), str(self.bob.id) + ]) + self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)]) # Choose some more options -------------------------------------------- self.get_select_option(from_box, str(self.arthur.id)).click() self.get_select_option(from_box, str(self.cliff.id)).click() self.selenium.find_element_by_id(choose_link).click() - self.assertSelectOptions(from_box, - [str(self.peter.id), str(self.jenny.id), - str(self.lisa.id), str(self.bob.id)]) - self.assertSelectOptions(to_box, - [str(self.jason.id), str(self.john.id), - str(self.arthur.id), str(self.cliff.id)]) + self.assertSelectOptions(from_box, [ + str(self.peter.id), str(self.jenny.id), + str(self.lisa.id), str(self.bob.id), + ]) + self.assertSelectOptions(to_box, [ + str(self.jason.id), str(self.john.id), + str(self.arthur.id), str(self.cliff.id), + ]) def test_basic(self): self.school.students.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username='super', password='secret', login_url='/') - self.selenium.get('%s%s' % ( - self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,)))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_school_change', args=(self.school.id,))) self.wait_page_loaded() self.execute_basic_operations('vertical', 'students') @@ -994,10 +981,8 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database - self.assertEqual(list(self.school.students.all()), - [self.arthur, self.cliff, self.jason, self.john]) - self.assertEqual(list(self.school.alumni.all()), - [self.arthur, self.cliff, self.jason, self.john]) + self.assertEqual(list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john]) + self.assertEqual(list(self.school.alumni.all()), [self.arthur, self.cliff, self.jason, self.john]) def test_filter(self): """ @@ -1010,8 +995,7 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): self.school.alumni.set([self.lisa, self.peter]) self.admin_login(username='super', password='secret', login_url='/') - self.selenium.get( - '%s%s' % (self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,)))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_school_change', args=(self.school.id,))) for field_name in ['students', 'alumni']: from_box = '#id_%s_from' % field_name @@ -1021,10 +1005,11 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): input = self.selenium.find_element_by_id('id_%s_input' % field_name) # Initial values - self.assertSelectOptions(from_box, - [str(self.arthur.id), str(self.bob.id), - str(self.cliff.id), str(self.jason.id), - str(self.jenny.id), str(self.john.id)]) + self.assertSelectOptions(from_box, [ + str(self.arthur.id), str(self.bob.id), + str(self.cliff.id), str(self.jason.id), + str(self.jenny.id), str(self.john.id), + ]) # Typing in some characters filters out non-matching options input.send_keys('a') @@ -1036,10 +1021,11 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): input.send_keys([Keys.BACK_SPACE]) self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) - self.assertSelectOptions(from_box, - [str(self.arthur.id), str(self.bob.id), - str(self.cliff.id), str(self.jason.id), - str(self.jenny.id), str(self.john.id)]) + self.assertSelectOptions(from_box, [ + str(self.arthur.id), str(self.bob.id), + str(self.cliff.id), str(self.jason.id), + str(self.jenny.id), str(self.john.id), + ]) # ----------------------------------------------------------------- # Check that choosing a filtered option sends it properly to the @@ -1049,24 +1035,22 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): self.get_select_option(from_box, str(self.jason.id)).click() self.selenium.find_element_by_id(choose_link).click() self.assertSelectOptions(from_box, [str(self.arthur.id)]) - self.assertSelectOptions(to_box, - [str(self.lisa.id), str(self.peter.id), - str(self.jason.id)]) + self.assertSelectOptions(to_box, [ + str(self.lisa.id), str(self.peter.id), str(self.jason.id), + ]) self.get_select_option(to_box, str(self.lisa.id)).click() self.selenium.find_element_by_id(remove_link).click() - self.assertSelectOptions(from_box, - [str(self.arthur.id), str(self.lisa.id)]) - self.assertSelectOptions(to_box, - [str(self.peter.id), str(self.jason.id)]) + self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)]) + self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) input.send_keys([Keys.BACK_SPACE]) # Clear text box - self.assertSelectOptions(from_box, - [str(self.arthur.id), str(self.bob.id), - str(self.cliff.id), str(self.jenny.id), - str(self.john.id), str(self.lisa.id)]) - self.assertSelectOptions(to_box, - [str(self.peter.id), str(self.jason.id)]) + self.assertSelectOptions(from_box, [ + str(self.arthur.id), str(self.bob.id), + str(self.cliff.id), str(self.jenny.id), + str(self.john.id), str(self.lisa.id), + ]) + self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) # ----------------------------------------------------------------- # Check that pressing enter on a filtered option sends it properly @@ -1083,10 +1067,8 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase): self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() self.school = models.School.objects.get(id=self.school.id) # Reload from database - self.assertEqual(list(self.school.students.all()), - [self.jason, self.peter]) - self.assertEqual(list(self.school.alumni.all()), - [self.jason, self.peter]) + self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) + self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) def test_back_button_bug(self): """ @@ -1147,14 +1129,11 @@ class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def test_ForeignKey(self): self.admin_login(username='super', password='secret', login_url='/') - self.selenium.get( - '%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_event_add')) main_window = self.selenium.current_window_handle # No value has been selected yet - self.assertEqual( - self.selenium.find_element_by_id('id_main_band').get_attribute('value'), - '') + self.assertEqual(self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '') # Open the popup window and click on a band self.selenium.find_element_by_id('lookup_id_main_band').click() @@ -1182,14 +1161,11 @@ class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def test_many_to_many(self): self.admin_login(username='super', password='secret', login_url='/') - self.selenium.get( - '%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_event_add')) main_window = self.selenium.current_window_handle # No value has been selected yet - self.assertEqual( - self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), - '') + self.assertEqual(self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '') # Help text for the field is displayed self.assertEqual( @@ -1226,9 +1202,7 @@ class RelatedFieldWidgetSeleniumTests(AdminWidgetSeleniumTestCase): def test_ForeignKey_using_to_field(self): self.admin_login(username='super', password='secret', login_url='/') - self.selenium.get('%s%s' % ( - self.live_server_url, - reverse('admin:admin_widgets_profile_add'))) + self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_profile_add')) main_window = self.selenium.current_window_handle # Click the Add User button to add new diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py index 6d6ca3480f..5f8f8a44fc 100644 --- a/tests/aggregation_regress/tests.py +++ b/tests/aggregation_regress/tests.py @@ -1238,19 +1238,27 @@ class AggregationTests(TestCase): tests aggregations with generic reverse relations """ django_book = Book.objects.get(name='Practical Django Projects') - ItemTag.objects.create(object_id=django_book.id, tag='intermediate', - content_type=ContentType.objects.get_for_model(django_book)) - ItemTag.objects.create(object_id=django_book.id, tag='django', - content_type=ContentType.objects.get_for_model(django_book)) + ItemTag.objects.create( + object_id=django_book.id, tag='intermediate', + content_type=ContentType.objects.get_for_model(django_book), + ) + ItemTag.objects.create( + object_id=django_book.id, tag='django', + content_type=ContentType.objects.get_for_model(django_book), + ) # Assign a tag to model with same PK as the book above. If the JOIN # used in aggregation doesn't have content type as part of the # condition the annotation will also count the 'hi mom' tag for b. wmpk = WithManualPK.objects.create(id=django_book.pk) - ItemTag.objects.create(object_id=wmpk.id, tag='hi mom', - content_type=ContentType.objects.get_for_model(wmpk)) + ItemTag.objects.create( + object_id=wmpk.id, tag='hi mom', + content_type=ContentType.objects.get_for_model(wmpk), + ) ai_book = Book.objects.get(name__startswith='Paradigms of Artificial Intelligence') - ItemTag.objects.create(object_id=ai_book.id, tag='intermediate', - content_type=ContentType.objects.get_for_model(ai_book)) + ItemTag.objects.create( + object_id=ai_book.id, tag='intermediate', + content_type=ContentType.objects.get_for_model(ai_book), + ) self.assertEqual(Book.objects.aggregate(Count('tags')), {'tags__count': 3}) results = Book.objects.annotate(Count('tags')).order_by('-tags__count', 'name') diff --git a/tests/annotations/models.py b/tests/annotations/models.py index 1c6faaf884..a92ca0b43a 100644 --- a/tests/annotations/models.py +++ b/tests/annotations/models.py @@ -81,8 +81,8 @@ class Company(models.Model): description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): - return ('Company(name=%s, motto=%s, ticker_name=%s, description=%s)' - % (self.name, self.motto, self.ticker_name, self.description) + return 'Company(name=%s, motto=%s, ticker_name=%s, description=%s)' % ( + self.name, self.motto, self.ticker_name, self.description, ) diff --git a/tests/apps/tests.py b/tests/apps/tests.py index 701be50803..c7fff0e738 100644 --- a/tests/apps/tests.py +++ b/tests/apps/tests.py @@ -244,8 +244,7 @@ class AppsTests(SimpleTestCase): body = {} body['Meta'] = type(str("Meta"), tuple(), meta_contents) body['__module__'] = TotallyNormal.__module__ + '.whatever' - with six.assertRaisesRegex(self, RuntimeError, - "Conflicting 'southponies' models in application 'apps':.*"): + with self.assertRaisesMessage(RuntimeError, "Conflicting 'southponies' models in application 'apps':"): type(str("SouthPonies"), (models.Model,), body) def test_get_containing_app_config_apps_not_ready(self): diff --git a/tests/auth_tests/test_decorators.py b/tests/auth_tests/test_decorators.py index bff1c11427..42632049bc 100644 --- a/tests/auth_tests/test_decorators.py +++ b/tests/auth_tests/test_decorators.py @@ -51,8 +51,7 @@ class LoginRequiredTestCase(AuthViewsTestCase): Check that login_required works on a simple view wrapped in a login_required decorator with a login_url set. """ - self.testLoginRequired(view_url='/login_required_login_url/', - login_url='/somewhere/') + self.testLoginRequired(view_url='/login_required_login_url/', login_url='/somewhere/') class PermissionsRequiredDecoratorTest(TestCase): diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py index 0e0ba71504..ac23c2e96a 100644 --- a/tests/auth_tests/test_forms.py +++ b/tests/auth_tests/test_forms.py @@ -180,10 +180,13 @@ class AuthenticationFormTest(TestDataMixin, TestCase): } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) - self.assertEqual(form.non_field_errors(), - [force_text(form.error_messages['invalid_login'] % { + self.assertEqual( + form.non_field_errors(), [ + force_text(form.error_messages['invalid_login'] % { 'username': User._meta.get_field('username').verbose_name - })]) + }) + ] + ) def test_inactive_user(self): # The user is inactive. @@ -193,8 +196,7 @@ class AuthenticationFormTest(TestDataMixin, TestCase): } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) - self.assertEqual(form.non_field_errors(), - [force_text(form.error_messages['inactive'])]) + self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])]) def test_inactive_user_i18n(self): with self.settings(USE_I18N=True), translation.override('pt-br', deactivate=True): @@ -205,8 +207,7 @@ class AuthenticationFormTest(TestDataMixin, TestCase): } form = AuthenticationForm(None, data) self.assertFalse(form.is_valid()) - self.assertEqual(form.non_field_errors(), - [force_text(form.error_messages['inactive'])]) + self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])]) def test_custom_login_allowed_policy(self): # The user is inactive, but our custom form policy allows them to log in. @@ -298,8 +299,10 @@ class SetPasswordFormTest(TestDataMixin, TestCase): } form = SetPasswordForm(user, data) self.assertFalse(form.is_valid()) - self.assertEqual(form["new_password2"].errors, - [force_text(form.error_messages['password_mismatch'])]) + self.assertEqual( + form["new_password2"].errors, + [force_text(form.error_messages['password_mismatch'])] + ) @mock.patch('django.contrib.auth.password_validation.password_changed') def test_success(self, password_changed): @@ -359,8 +362,7 @@ class PasswordChangeFormTest(TestDataMixin, TestCase): } form = PasswordChangeForm(user, data) self.assertFalse(form.is_valid()) - self.assertEqual(form["old_password"].errors, - [force_text(form.error_messages['password_incorrect'])]) + self.assertEqual(form["old_password"].errors, [force_text(form.error_messages['password_incorrect'])]) def test_password_verification(self): # The two new passwords do not match. @@ -372,8 +374,7 @@ class PasswordChangeFormTest(TestDataMixin, TestCase): } form = PasswordChangeForm(user, data) self.assertFalse(form.is_valid()) - self.assertEqual(form["new_password2"].errors, - [force_text(form.error_messages['password_mismatch'])]) + self.assertEqual(form["new_password2"].errors, [force_text(form.error_messages['password_mismatch'])]) @mock.patch('django.contrib.auth.password_validation.password_changed') def test_success(self, password_changed): @@ -394,8 +395,7 @@ class PasswordChangeFormTest(TestDataMixin, TestCase): def test_field_order(self): # Regression test - check the order of fields: user = User.objects.get(username='testclient') - self.assertEqual(list(PasswordChangeForm(user, {}).fields), - ['old_password', 'new_password1', 'new_password2']) + self.assertEqual(list(PasswordChangeForm(user, {}).fields), ['old_password', 'new_password1', 'new_password2']) def test_password_whitespace_not_stripped(self): user = User.objects.get(username='testclient') @@ -452,14 +452,12 @@ class UserChangeFormTest(TestDataMixin, TestCase): def test_bug_17944_unmanageable_password(self): user = User.objects.get(username='unmanageable_password') form = UserChangeForm(instance=user) - self.assertIn(_("Invalid password format or unknown hashing algorithm."), - form.as_table()) + self.assertIn(_("Invalid password format or unknown hashing algorithm."), form.as_table()) def test_bug_17944_unknown_password_algorithm(self): user = User.objects.get(username='unknown_password') form = UserChangeForm(instance=user) - self.assertIn(_("Invalid password format or unknown hashing algorithm."), - form.as_table()) + self.assertIn(_("Invalid password format or unknown hashing algorithm."), form.as_table()) def test_bug_19133(self): "The change form does not return the password value" @@ -574,8 +572,10 @@ class PasswordResetFormTest(TestDataMixin, TestCase): None, [to_email], ['site_monitor@example.com'], headers={'Reply-To': 'webmaster@example.com'}, - alternatives=[("Really sorry to hear you forgot your password.", - "text/html")]).send() + alternatives=[ + ("Really sorry to hear you forgot your password.", "text/html") + ], + ).send() form = CustomEmailPasswordResetForm(data) self.assertTrue(form.is_valid()) @@ -663,10 +663,10 @@ class PasswordResetFormTest(TestDataMixin, TestCase): self.assertEqual(message.get_payload(1).get_content_type(), 'text/html') self.assertEqual(message.get_all('to'), [email]) self.assertTrue(re.match(r'^http://example.com/reset/[\w/-]+', message.get_payload(0).get_payload())) - self.assertTrue( - re.match(r'^Link$', - message.get_payload(1).get_payload()) - ) + self.assertTrue(re.match( + r'^Link$', + message.get_payload(1).get_payload() + )) class ReadOnlyPasswordHashTest(SimpleTestCase): diff --git a/tests/auth_tests/test_hashers.py b/tests/auth_tests/test_hashers.py index 845deee646..2525c2cae0 100644 --- a/tests/auth_tests/test_hashers.py +++ b/tests/auth_tests/test_hashers.py @@ -57,8 +57,7 @@ class TestUtilsHashPass(SimpleTestCase): def test_pbkdf2(self): encoded = make_password('lètmein', 'seasalt', 'pbkdf2_sha256') - self.assertEqual(encoded, - 'pbkdf2_sha256$30000$seasalt$VrX+V8drCGo68wlvy6rfu8i1d1pfkdeXA4LJkRGJodY=') + self.assertEqual(encoded, 'pbkdf2_sha256$30000$seasalt$VrX+V8drCGo68wlvy6rfu8i1d1pfkdeXA4LJkRGJodY=') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) @@ -73,8 +72,7 @@ class TestUtilsHashPass(SimpleTestCase): @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher']) def test_sha1(self): encoded = make_password('lètmein', 'seasalt', 'sha1') - self.assertEqual(encoded, - 'sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8') + self.assertEqual(encoded, 'sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) @@ -89,8 +87,7 @@ class TestUtilsHashPass(SimpleTestCase): @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.MD5PasswordHasher']) def test_md5(self): encoded = make_password('lètmein', 'seasalt', 'md5') - self.assertEqual(encoded, - 'md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3') + self.assertEqual(encoded, 'md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3') self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmeinz', encoded)) @@ -165,8 +162,10 @@ class TestUtilsHashPass(SimpleTestCase): self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256") # Verify that password truncation no longer works - password = ('VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5' - 'JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN') + password = ( + 'VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5' + 'JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN' + ) encoded = make_password(password, hasher='bcrypt_sha256') self.assertTrue(check_password(password, encoded)) self.assertFalse(check_password(password[:72], encoded)) @@ -282,15 +281,13 @@ class TestUtilsHashPass(SimpleTestCase): def test_low_level_pbkdf2(self): hasher = PBKDF2PasswordHasher() encoded = hasher.encode('lètmein', 'seasalt2') - self.assertEqual(encoded, - 'pbkdf2_sha256$30000$seasalt2$a75qzbogeVhNFeMqhdgyyoqGKpIzYUo651sq57RERew=') + self.assertEqual(encoded, 'pbkdf2_sha256$30000$seasalt2$a75qzbogeVhNFeMqhdgyyoqGKpIzYUo651sq57RERew=') self.assertTrue(hasher.verify('lètmein', encoded)) def test_low_level_pbkdf2_sha1(self): hasher = PBKDF2SHA1PasswordHasher() encoded = hasher.encode('lètmein', 'seasalt2') - self.assertEqual(encoded, - 'pbkdf2_sha1$30000$seasalt2$pMzU1zNPcydf6wjnJFbiVKwgULc=') + self.assertEqual(encoded, 'pbkdf2_sha1$30000$seasalt2$pMzU1zNPcydf6wjnJFbiVKwgULc=') self.assertTrue(hasher.verify('lètmein', encoded)) @override_settings( @@ -433,15 +430,13 @@ class TestUtilsHashPass(SimpleTestCase): def test_load_library_no_algorithm(self): with self.assertRaises(ValueError) as e: BasePasswordHasher()._load_library() - self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a " - "library attribute", str(e.exception)) + self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a library attribute", str(e.exception)) def test_load_library_importerror(self): - PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), - {'algorithm': 'plain', 'library': 'plain'}) + PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'}) # Python 3 adds quotes around module name - with six.assertRaisesRegex(self, ValueError, - "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?"): + msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?" + with six.assertRaisesRegex(self, ValueError, msg): PlainHasher()._load_library() diff --git a/tests/auth_tests/test_models.py b/tests/auth_tests/test_models.py index 8f8f3ff900..975cf230af 100644 --- a/tests/auth_tests/test_models.py +++ b/tests/auth_tests/test_models.py @@ -154,8 +154,12 @@ class AbstractUserTestCase(TestCase): "html_message": None, } abstract_user = AbstractUser(email='foo@bar.com') - abstract_user.email_user(subject="Subject here", - message="This is a message", from_email="from@domain.com", **kwargs) + abstract_user.email_user( + subject="Subject here", + message="This is a message", + from_email="from@domain.com", + **kwargs + ) # Test that one message has been sent. self.assertEqual(len(mail.outbox), 1) # Verify that test email contains the correct attributes: diff --git a/tests/auth_tests/test_views.py b/tests/auth_tests/test_views.py index 2df2c75122..5b4b877c47 100644 --- a/tests/auth_tests/test_views.py +++ b/tests/auth_tests/test_views.py @@ -255,8 +255,7 @@ class PasswordResetTest(AuthViewsTestCase): def test_confirm_complete(self): url, path = self._test_confirm_start() - response = self.client.post(path, {'new_password1': 'anewpassword', - 'new_password2': 'anewpassword'}) + response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) # Check the password has been changed u = User.objects.get(email='staffmember@example.com') self.assertTrue(u.check_password("anewpassword")) @@ -267,48 +266,41 @@ class PasswordResetTest(AuthViewsTestCase): def test_confirm_different_passwords(self): url, path = self._test_confirm_start() - response = self.client.post(path, {'new_password1': 'anewpassword', - 'new_password2': 'x'}) + response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'x'}) self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch']) def test_reset_redirect_default(self): - response = self.client.post('/password_reset/', - {'email': 'staffmember@example.com'}) + response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/done/') def test_reset_custom_redirect(self): - response = self.client.post('/password_reset/custom_redirect/', - {'email': 'staffmember@example.com'}) + response = self.client.post('/password_reset/custom_redirect/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def test_reset_custom_redirect_named(self): - response = self.client.post('/password_reset/custom_redirect/named/', - {'email': 'staffmember@example.com'}) + response = self.client.post('/password_reset/custom_redirect/named/', {'email': 'staffmember@example.com'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') def test_confirm_redirect_default(self): url, path = self._test_confirm_start() - response = self.client.post(path, {'new_password1': 'anewpassword', - 'new_password2': 'anewpassword'}) + response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/reset/done/') def test_confirm_redirect_custom(self): url, path = self._test_confirm_start() path = path.replace('/reset/', '/reset/custom/') - response = self.client.post(path, {'new_password1': 'anewpassword', - 'new_password2': 'anewpassword'}) + response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/custom/') def test_confirm_redirect_custom_named(self): url, path = self._test_confirm_start() path = path.replace('/reset/', '/reset/custom/named/') - response = self.client.post(path, {'new_password1': 'anewpassword', - 'new_password2': 'anewpassword'}) + response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'}) self.assertEqual(response.status_code, 302) self.assertURLEqual(response.url, '/password_reset/') diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 1d27dcab87..2cb5703e9d 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -40,8 +40,7 @@ class DummyBackendTest(SimpleTestCase): """ DATABASES = {} conns = ConnectionHandler(DATABASES) - self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'], - 'django.db.backends.dummy') + self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'], 'django.db.backends.dummy') with self.assertRaises(ImproperlyConfigured): conns[DEFAULT_DB_ALIAS].ensure_connection() @@ -119,9 +118,11 @@ class SQLiteTests(TestCase): statements = editor.collected_sql match = re.search('"id" ([^,]+),', statements[0]) self.assertIsNotNone(match) - self.assertEqual('integer NOT NULL PRIMARY KEY AUTOINCREMENT', - match.group(1), "Wrong SQL used to create an auto-increment " - "column on SQLite") + self.assertEqual( + 'integer NOT NULL PRIMARY KEY AUTOINCREMENT', + match.group(1), + "Wrong SQL used to create an auto-increment column on SQLite" + ) def test_aggregation(self): """ @@ -672,11 +673,15 @@ class BackendTestCase(TransactionTestCase): models.Person(first_name="Clark", last_name="Kent").save() opts2 = models.Person._meta f3, f4 = opts2.get_field('first_name'), opts2.get_field('last_name') - query2 = ('SELECT %s, %s FROM %s ORDER BY %s' - % (qn(f3.column), qn(f4.column), connection.introspection.table_name_converter(opts2.db_table), - qn(f3.column))) cursor = connection.cursor() - cursor.execute(query2) + cursor.execute( + 'SELECT %s, %s FROM %s ORDER BY %s' % ( + qn(f3.column), + qn(f4.column), + connection.introspection.table_name_converter(opts2.db_table), + qn(f3.column), + ) + ) self.assertEqual(cursor.fetchone(), ('Clark', 'Kent')) self.assertEqual(list(cursor.fetchmany(2)), [('Jane', 'Doe'), ('John', 'Doe')]) self.assertEqual(list(cursor.fetchall()), [('Mary', 'Agnelline'), ('Peter', 'Parker')]) @@ -818,9 +823,10 @@ class BackendTestCase(TransactionTestCase): with warnings.catch_warnings(record=True) as w: self.assertEqual(3, len(new_connection.queries)) self.assertEqual(1, len(w)) - self.assertEqual(str(w[0].message), "Limit for query logging " - "exceeded, only the last 3 queries will be returned.") - + self.assertEqual( + str(w[0].message), + "Limit for query logging exceeded, only the last 3 queries will be returned." + ) finally: BaseDatabaseWrapper.queries_limit = old_queries_limit new_connection.close() diff --git a/tests/bash_completion/management/commands/test_command.py b/tests/bash_completion/management/commands/test_command.py index d2adf91e5a..91ec36c2af 100644 --- a/tests/bash_completion/management/commands/test_command.py +++ b/tests/bash_completion/management/commands/test_command.py @@ -3,8 +3,7 @@ from django.core.management.base import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): - parser.add_argument("--list", action="store_true", dest="list", - help="Print all options") + parser.add_argument("--list", action="store_true", dest="list", help="Print all options") def handle(self, *args, **options): pass diff --git a/tests/bash_completion/tests.py b/tests/bash_completion/tests.py index b12a0cecdc..1d35e1f28e 100644 --- a/tests/bash_completion/tests.py +++ b/tests/bash_completion/tests.py @@ -97,7 +97,8 @@ class BashCompletionTests(unittest.TestCase): "Application names will be autocompleted for an AppCommand" self._user_input('django-admin sqlmigrate a') output = self._run_autocomplete() - a_labels = sorted(app_config.label - for app_config in apps.get_app_configs() - if app_config.label.startswith('a')) + a_labels = sorted( + app_config.label for app_config in apps.get_app_configs() + if app_config.label.startswith('a') + ) self.assertEqual(output, a_labels) diff --git a/tests/basic/tests.py b/tests/basic/tests.py index a69a43a0f4..6ff037a31a 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -99,16 +99,14 @@ class ModelInstanceCreationTests(TestCase): pub_date=datetime(2005, 7, 31, 12, 30), ) a1.save() - self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, - datetime(2005, 7, 31, 12, 30)) + self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30)) a2 = Article( headline='Article 8', pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a2.save() - self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, - datetime(2005, 7, 31, 12, 30, 45)) + self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45)) def test_saving_an_object_again_does_not_create_a_new_object(self): a = Article(headline='original', pub_date=datetime(2014, 5, 16)) @@ -150,14 +148,15 @@ class ModelTest(TestCase): some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() - self.assertQuerysetEqual(Article.objects.all().order_by('headline'), + self.assertQuerysetEqual( + Article.objects.all().order_by('headline'), ["", "", "", - ""]) + ""] + ) Article.objects.filter(headline__startswith='A').delete() - self.assertQuerysetEqual(Article.objects.all().order_by('headline'), - [""]) + self.assertQuerysetEqual(Article.objects.all().order_by('headline'), [""]) def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self): some_pub_date = datetime(2014, 5, 16, 12, 1) @@ -176,8 +175,7 @@ class ModelTest(TestCase): pub_date=datetime(2005, 7, 31, 12, 30, 45, 180), ) a9.save() - self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, - datetime(2005, 7, 31, 12, 30, 45, 180)) + self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180)) @skipIfDBFeature('supports_microsecond_precision') def test_microsecond_precision_not_supported(self): @@ -236,8 +234,10 @@ class ModelTest(TestCase): headline='Article 12', pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), ) - self.assertQuerysetEqual(Article.objects.filter(pub_date__year=2008), - ["", ""]) + self.assertQuerysetEqual( + Article.objects.filter(pub_date__year=2008), + ["", ""] + ) def test_unicode_data(self): # Unicode data works, too. @@ -246,8 +246,7 @@ class ModelTest(TestCase): pub_date=datetime(2005, 7, 28), ) a.save() - self.assertEqual(Article.objects.get(pk=a.id).headline, - '\u6797\u539f \u3081\u3050\u307f') + self.assertEqual(Article.objects.get(pk=a.id).headline, '\u6797\u539f \u3081\u3050\u307f') def test_hash_function(self): # Model instances have a hash function, so they can be used in sets @@ -304,8 +303,10 @@ class ModelTest(TestCase): dicts = Article.objects.filter( pub_date__year=2008).extra( select={'dashed-value': '1'}).values('headline', 'dashed-value') - self.assertEqual([sorted(d.items()) for d in dicts], - [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]]) + self.assertEqual( + [sorted(d.items()) for d in dicts], + [[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]] + ) def test_extra_method_select_argument_with_dashes(self): # If you use 'select' with extra() and names containing dashes on a @@ -438,8 +439,7 @@ class ModelLookupTest(TestCase): self.a.save() # Article.objects.all() returns all the articles in the database. - self.assertQuerysetEqual(Article.objects.all(), - ['']) + self.assertQuerysetEqual(Article.objects.all(), ['']) def test_rich_lookup(self): # Django provides a rich database lookup API. @@ -496,8 +496,7 @@ class ModelLookupTest(TestCase): self.assertEqual(Article.objects.get(pk=self.a.id), self.a) # pk can be used as a shortcut for the primary key name in any query. - self.assertQuerysetEqual(Article.objects.filter(pk__in=[self.a.id]), - [""]) + self.assertQuerysetEqual(Article.objects.filter(pk__in=[self.a.id]), [""]) # Model instances of the same type and same ID are considered equal. a = Article.objects.get(pk=self.a.id) diff --git a/tests/cache/tests.py b/tests/cache/tests.py index ee1501a029..1e74df1e56 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -772,54 +772,42 @@ class BaseCacheTests(object): def test_cache_versioning_get_set_many(self): # set, using default version = 1 cache.set_many({'ford1': 37, 'arthur1': 42}) - self.assertDictEqual(cache.get_many(['ford1', 'arthur1']), - {'ford1': 37, 'arthur1': 42}) - self.assertDictEqual(cache.get_many(['ford1', 'arthur1'], version=1), - {'ford1': 37, 'arthur1': 42}) + self.assertDictEqual(cache.get_many(['ford1', 'arthur1']), {'ford1': 37, 'arthur1': 42}) + self.assertDictEqual(cache.get_many(['ford1', 'arthur1'], version=1), {'ford1': 37, 'arthur1': 42}) self.assertDictEqual(cache.get_many(['ford1', 'arthur1'], version=2), {}) self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1']), {}) - self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=1), - {'ford1': 37, 'arthur1': 42}) + self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=1), {'ford1': 37, 'arthur1': 42}) self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=2), {}) # set, default version = 1, but manually override version = 2 cache.set_many({'ford2': 37, 'arthur2': 42}, version=2) self.assertDictEqual(cache.get_many(['ford2', 'arthur2']), {}) self.assertDictEqual(cache.get_many(['ford2', 'arthur2'], version=1), {}) - self.assertDictEqual(cache.get_many(['ford2', 'arthur2'], version=2), - {'ford2': 37, 'arthur2': 42}) + self.assertDictEqual(cache.get_many(['ford2', 'arthur2'], version=2), {'ford2': 37, 'arthur2': 42}) - self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2']), - {'ford2': 37, 'arthur2': 42}) + self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2']), {'ford2': 37, 'arthur2': 42}) self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=1), {}) - self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=2), - {'ford2': 37, 'arthur2': 42}) + self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=2), {'ford2': 37, 'arthur2': 42}) # v2 set, using default version = 2 caches['v2'].set_many({'ford3': 37, 'arthur3': 42}) self.assertDictEqual(cache.get_many(['ford3', 'arthur3']), {}) self.assertDictEqual(cache.get_many(['ford3', 'arthur3'], version=1), {}) - self.assertDictEqual(cache.get_many(['ford3', 'arthur3'], version=2), - {'ford3': 37, 'arthur3': 42}) + self.assertDictEqual(cache.get_many(['ford3', 'arthur3'], version=2), {'ford3': 37, 'arthur3': 42}) - self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3']), - {'ford3': 37, 'arthur3': 42}) + self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3']), {'ford3': 37, 'arthur3': 42}) self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=1), {}) - self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=2), - {'ford3': 37, 'arthur3': 42}) + self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=2), {'ford3': 37, 'arthur3': 42}) # v2 set, default version = 2, but manually override version = 1 caches['v2'].set_many({'ford4': 37, 'arthur4': 42}, version=1) - self.assertDictEqual(cache.get_many(['ford4', 'arthur4']), - {'ford4': 37, 'arthur4': 42}) - self.assertDictEqual(cache.get_many(['ford4', 'arthur4'], version=1), - {'ford4': 37, 'arthur4': 42}) + self.assertDictEqual(cache.get_many(['ford4', 'arthur4']), {'ford4': 37, 'arthur4': 42}) + self.assertDictEqual(cache.get_many(['ford4', 'arthur4'], version=1), {'ford4': 37, 'arthur4': 42}) self.assertDictEqual(cache.get_many(['ford4', 'arthur4'], version=2), {}) self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4']), {}) - self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=1), - {'ford4': 37, 'arthur4': 42}) + self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=1), {'ford4': 37, 'arthur4': 42}) self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=2), {}) def test_incr_version(self): @@ -988,8 +976,7 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase): def test_second_call_doesnt_crash(self): out = six.StringIO() management.call_command('createcachetable', stdout=out) - self.assertEqual(out.getvalue(), - "Cache table 'test cache table' already exists.\n" * len(settings.CACHES)) + self.assertEqual(out.getvalue(), "Cache table 'test cache table' already exists.\n" * len(settings.CACHES)) @override_settings(CACHES=caches_setting_for_tests( BACKEND='django.core.cache.backends.db.DatabaseCache', @@ -1015,8 +1002,7 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase): verbosity=2, stdout=out, ) - self.assertEqual(out.getvalue(), - "Cache table 'test cache table' created.\n") + self.assertEqual(out.getvalue(), "Cache table 'test cache table' created.\n") @override_settings(USE_TZ=True) @@ -1732,13 +1718,17 @@ class CacheI18nTest(TestCase): with timezone.override(CustomTzName()): CustomTzName.name = 'Hora estándar de Argentina'.encode('UTF-8') # UTF-8 string sanitized_name = 'Hora_estndar_de_Argentina' - self.assertIn(sanitized_name, learn_cache_key(request, response), - "Cache keys should include the time zone name when time zones are active") + self.assertIn( + sanitized_name, learn_cache_key(request, response), + "Cache keys should include the time zone name when time zones are active" + ) CustomTzName.name = 'Hora estándar de Argentina' # unicode sanitized_name = 'Hora_estndar_de_Argentina' - self.assertIn(sanitized_name, learn_cache_key(request, response), - "Cache keys should include the time zone name when time zones are active") + self.assertIn( + sanitized_name, learn_cache_key(request, response), + "Cache keys should include the time zone name when time zones are active" + ) @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX="test", @@ -2151,18 +2141,15 @@ class TestMakeTemplateFragmentKey(SimpleTestCase): def test_with_one_vary_on(self): key = make_template_fragment_key('foo', ['abc']) - self.assertEqual(key, - 'template.cache.foo.900150983cd24fb0d6963f7d28e17f72') + self.assertEqual(key, 'template.cache.foo.900150983cd24fb0d6963f7d28e17f72') def test_with_many_vary_on(self): key = make_template_fragment_key('bar', ['abc', 'def']) - self.assertEqual(key, - 'template.cache.bar.4b35f12ab03cec09beec4c21b2d2fa88') + self.assertEqual(key, 'template.cache.bar.4b35f12ab03cec09beec4c21b2d2fa88') def test_proper_escaping(self): key = make_template_fragment_key('spam', ['abc:def%']) - self.assertEqual(key, - 'template.cache.spam.f27688177baec990cdf3fbd9d9c3f469') + self.assertEqual(key, 'template.cache.spam.f27688177baec990cdf3fbd9d9c3f469') class CacheHandlerTest(SimpleTestCase): diff --git a/tests/contenttypes_tests/test_models.py b/tests/contenttypes_tests/test_models.py index 7644a8ea30..d388990c06 100644 --- a/tests/contenttypes_tests/test_models.py +++ b/tests/contenttypes_tests/test_models.py @@ -40,8 +40,7 @@ class ContentTypesTests(TestCase): with self.assertNumQueries(0): ContentType.objects.get_for_id(ct.id) with self.assertNumQueries(0): - ContentType.objects.get_by_natural_key('contenttypes', - 'contenttype') + ContentType.objects.get_by_natural_key('contenttypes', 'contenttype') # Once we clear the cache, another lookup will again hit the DB ContentType.objects.clear_cache() @@ -51,12 +50,10 @@ class ContentTypesTests(TestCase): # The same should happen with a lookup by natural key ContentType.objects.clear_cache() with self.assertNumQueries(1): - ContentType.objects.get_by_natural_key('contenttypes', - 'contenttype') + ContentType.objects.get_by_natural_key('contenttypes', 'contenttype') # And a second hit shouldn't hit the DB with self.assertNumQueries(0): - ContentType.objects.get_by_natural_key('contenttypes', - 'contenttype') + ContentType.objects.get_by_natural_key('contenttypes', 'contenttype') def test_get_for_models_empty_cache(self): # Empty cache. @@ -94,17 +91,10 @@ class ContentTypesTests(TestCase): with concrete, proxy and deferred models """ concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) + self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(ProxyModel)) + self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(ConcreteModel, for_concrete_model=False)) - self.assertEqual(concrete_model_ct, - ContentType.objects.get_for_model(ProxyModel)) - - self.assertEqual(concrete_model_ct, - ContentType.objects.get_for_model(ConcreteModel, - for_concrete_model=False)) - - proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, - for_concrete_model=False) - + proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, for_concrete_model=False) self.assertNotEqual(concrete_model_ct, proxy_model_ct) # Make sure deferred model are correctly handled @@ -112,19 +102,16 @@ class ContentTypesTests(TestCase): DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__ DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__ - self.assertEqual(concrete_model_ct, - ContentType.objects.get_for_model(DeferredConcreteModel)) - - self.assertEqual(concrete_model_ct, - ContentType.objects.get_for_model(DeferredConcreteModel, - for_concrete_model=False)) - - self.assertEqual(concrete_model_ct, - ContentType.objects.get_for_model(DeferredProxyModel)) - - self.assertEqual(proxy_model_ct, - ContentType.objects.get_for_model(DeferredProxyModel, - for_concrete_model=False)) + self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredConcreteModel)) + self.assertEqual( + concrete_model_ct, + ContentType.objects.get_for_model(DeferredConcreteModel, for_concrete_model=False) + ) + self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredProxyModel)) + self.assertEqual( + proxy_model_ct, + ContentType.objects.get_for_model(DeferredProxyModel, for_concrete_model=False) + ) def test_get_for_concrete_models(self): """ @@ -139,10 +126,8 @@ class ContentTypesTests(TestCase): ProxyModel: concrete_model_ct, }) - proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, - for_concrete_model=False) - cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel, - for_concrete_models=False) + proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, for_concrete_model=False) + cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel, for_concrete_models=False) self.assertEqual(cts, { ConcreteModel: concrete_model_ct, ProxyModel: proxy_model_ct, @@ -153,16 +138,15 @@ class ContentTypesTests(TestCase): DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__ DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__ - cts = ContentType.objects.get_for_models(DeferredConcreteModel, - DeferredProxyModel) + cts = ContentType.objects.get_for_models(DeferredConcreteModel, DeferredProxyModel) self.assertEqual(cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: concrete_model_ct, }) - cts = ContentType.objects.get_for_models(DeferredConcreteModel, - DeferredProxyModel, - for_concrete_models=False) + cts = ContentType.objects.get_for_models( + DeferredConcreteModel, DeferredProxyModel, for_concrete_models=False + ) self.assertEqual(cts, { DeferredConcreteModel: concrete_model_ct, DeferredProxyModel: proxy_model_ct, @@ -198,13 +182,14 @@ class ContentTypesTests(TestCase): with self.modify_settings(INSTALLED_APPS={'append': 'django.contrib.sites'}): response = shortcut(request, user_ct.id, obj.id) - self.assertEqual("http://%s/users/john/" % get_current_site(request).domain, - response._headers.get("location")[1]) + self.assertEqual( + "http://%s/users/john/" % get_current_site(request).domain, + response._headers.get("location")[1] + ) with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}): response = shortcut(request, user_ct.id, obj.id) - self.assertEqual("http://Example.com/users/john/", - response._headers.get("location")[1]) + self.assertEqual("http://Example.com/users/john/", response._headers.get("location")[1]) def test_shortcut_view_without_get_absolute_url(self): """ diff --git a/tests/contenttypes_tests/tests.py b/tests/contenttypes_tests/tests.py index 7000c6fe48..c2377bf82e 100644 --- a/tests/contenttypes_tests/tests.py +++ b/tests/contenttypes_tests/tests.py @@ -252,9 +252,11 @@ class GenericRelationshipTests(SimpleTestCase): 'custom_content_type', 'custom_object_id') class Bookmark(models.Model): - tags = GenericRelation('TaggedItem', + tags = GenericRelation( + 'TaggedItem', content_type_field='custom_content_type', - object_id_field='custom_object_id') + object_id_field='custom_object_id', + ) errors = Bookmark.tags.field.check() self.assertEqual(errors, []) diff --git a/tests/custom_managers/models.py b/tests/custom_managers/models.py index 7fd50dc7f5..22ba66cb8f 100644 --- a/tests/custom_managers/models.py +++ b/tests/custom_managers/models.py @@ -116,7 +116,6 @@ class FunPerson(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) fun = models.BooleanField(default=True) - favorite_book = models.ForeignKey( 'Book', models.SET_NULL, @@ -141,12 +140,16 @@ class Book(models.Model): published_objects = PublishedBookManager() authors = models.ManyToManyField(Person, related_name='books') fun_authors = models.ManyToManyField(FunPerson, related_name='books') - - favorite_things = GenericRelation(Person, - content_type_field='favorite_thing_type', object_id_field='favorite_thing_id') - - fun_people_favorite_things = GenericRelation(FunPerson, - content_type_field='favorite_thing_type', object_id_field='favorite_thing_id') + favorite_things = GenericRelation( + Person, + content_type_field='favorite_thing_type', + object_id_field='favorite_thing_id', + ) + fun_people_favorite_things = GenericRelation( + FunPerson, + content_type_field='favorite_thing_type', + object_id_field='favorite_thing_id', + ) def __str__(self): return self.title diff --git a/tests/datatypes/tests.py b/tests/datatypes/tests.py index 612b1ae2e4..f45c429ef2 100644 --- a/tests/datatypes/tests.py +++ b/tests/datatypes/tests.py @@ -47,25 +47,28 @@ class DataTypesTestCase(TestCase): def test_year_boundaries(self): """Year boundary tests (ticket #3689)""" - Donut.objects.create(name='Date Test 2007', - baked_date=datetime.datetime(year=2007, month=12, day=31), - consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) - Donut.objects.create(name='Date Test 2006', + Donut.objects.create( + name='Date Test 2007', + baked_date=datetime.datetime(year=2007, month=12, day=31), + consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59), + ) + Donut.objects.create( + name='Date Test 2006', baked_date=datetime.datetime(year=2006, month=1, day=1), - consumed_at=datetime.datetime(year=2006, month=1, day=1)) + consumed_at=datetime.datetime(year=2006, month=1, day=1), + ) + self.assertEqual("Date Test 2007", Donut.objects.filter(baked_date__year=2007)[0].name) + self.assertEqual("Date Test 2006", Donut.objects.filter(baked_date__year=2006)[0].name) - self.assertEqual("Date Test 2007", - Donut.objects.filter(baked_date__year=2007)[0].name) - - self.assertEqual("Date Test 2006", - Donut.objects.filter(baked_date__year=2006)[0].name) - - Donut.objects.create(name='Apple Fritter', - consumed_at=datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59)) - - self.assertEqual(['Apple Fritter', 'Date Test 2007'], - list(Donut.objects.filter(consumed_at__year=2007).order_by('name').values_list('name', flat=True))) + Donut.objects.create( + name='Apple Fritter', + consumed_at=datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59), + ) + self.assertEqual( + ['Apple Fritter', 'Date Test 2007'], + list(Donut.objects.filter(consumed_at__year=2007).order_by('name').values_list('name', flat=True)) + ) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2005).count()) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count()) diff --git a/tests/defer_regress/tests.py b/tests/defer_regress/tests.py index 2594ffcdb8..eb2fb8ecfc 100644 --- a/tests/defer_regress/tests.py +++ b/tests/defer_regress/tests.py @@ -286,12 +286,18 @@ class DeferAnnotateSelectRelatedTest(TestCase): def test_defer_annotate_select_related(self): location = Location.objects.create() Request.objects.create(location=location) - self.assertIsInstance(list(Request.objects - .annotate(Count('items')).select_related('profile', 'location') - .only('profile', 'location')), list) - self.assertIsInstance(list(Request.objects - .annotate(Count('items')).select_related('profile', 'location') - .only('profile__profile1', 'location__location1')), list) - self.assertIsInstance(list(Request.objects - .annotate(Count('items')).select_related('profile', 'location') - .defer('request1', 'request2', 'request3', 'request4')), list) + self.assertIsInstance( + list(Request.objects.annotate(Count('items')).select_related('profile', 'location') + .only('profile', 'location')), + list + ) + self.assertIsInstance( + list(Request.objects.annotate(Count('items')).select_related('profile', 'location') + .only('profile__profile1', 'location__location1')), + list + ) + self.assertIsInstance( + list(Request.objects.annotate(Count('items')).select_related('profile', 'location') + .defer('request1', 'request2', 'request3', 'request4')), + list + ) diff --git a/tests/delete/models.py b/tests/delete/models.py index 60e7f5957c..8a6f4903d6 100644 --- a/tests/delete/models.py +++ b/tests/delete/models.py @@ -36,32 +36,25 @@ class A(models.Model): name = models.CharField(max_length=30) auto = models.ForeignKey(R, models.CASCADE, related_name="auto_set") - auto_nullable = models.ForeignKey(R, models.CASCADE, null=True, - related_name='auto_nullable_set') - setvalue = models.ForeignKey(R, models.SET(get_default_r), - related_name='setvalue') - setnull = models.ForeignKey(R, models.SET_NULL, null=True, - related_name='setnull_set') - setdefault = models.ForeignKey(R, models.SET_DEFAULT, - default=get_default_r, related_name='setdefault_set') - setdefault_none = models.ForeignKey(R, models.SET_DEFAULT, - default=None, null=True, related_name='setnull_nullable_set') - cascade = models.ForeignKey(R, models.CASCADE, - related_name='cascade_set') - cascade_nullable = models.ForeignKey(R, models.CASCADE, null=True, - related_name='cascade_nullable_set') + auto_nullable = models.ForeignKey(R, models.CASCADE, null=True, related_name='auto_nullable_set') + setvalue = models.ForeignKey(R, models.SET(get_default_r), related_name='setvalue') + setnull = models.ForeignKey(R, models.SET_NULL, null=True, related_name='setnull_set') + setdefault = models.ForeignKey(R, models.SET_DEFAULT, default=get_default_r, related_name='setdefault_set') + setdefault_none = models.ForeignKey( + R, models.SET_DEFAULT, + default=None, null=True, related_name='setnull_nullable_set', + ) + cascade = models.ForeignKey(R, models.CASCADE, related_name='cascade_set') + cascade_nullable = models.ForeignKey(R, models.CASCADE, null=True, related_name='cascade_nullable_set') protect = models.ForeignKey(R, models.PROTECT, null=True) - donothing = models.ForeignKey(R, models.DO_NOTHING, null=True, - related_name='donothing_set') + donothing = models.ForeignKey(R, models.DO_NOTHING, null=True, related_name='donothing_set') child = models.ForeignKey(RChild, models.CASCADE, related_name="child") - child_setnull = models.ForeignKey(RChild, models.SET_NULL, null=True, - related_name="child_setnull") + child_setnull = models.ForeignKey(RChild, models.SET_NULL, null=True, related_name="child_setnull") # A OneToOneField is just a ForeignKey unique=True, so we don't duplicate # all the tests; just one smoke test to ensure on_delete works for it as # well. - o2o_setnull = models.ForeignKey(R, models.SET_NULL, null=True, - related_name="o2o_nullable_set") + o2o_setnull = models.ForeignKey(R, models.SET_NULL, null=True, related_name="o2o_nullable_set") def create_a(name): @@ -79,10 +72,8 @@ def create_a(name): class M(models.Model): m2m = models.ManyToManyField(R, related_name="m_set") - m2m_through = models.ManyToManyField(R, through="MR", - related_name="m_through_set") - m2m_through_null = models.ManyToManyField(R, through="MRNull", - related_name="m_through_null_set") + m2m_through = models.ManyToManyField(R, through="MR", related_name="m_through_set") + m2m_through_null = models.ManyToManyField(R, through="MRNull", related_name="m_through_null_set") class MR(models.Model): diff --git a/tests/deprecation/tests.py b/tests/deprecation/tests.py index f50b2b624d..2ad3576676 100644 --- a/tests/deprecation/tests.py +++ b/tests/deprecation/tests.py @@ -36,8 +36,7 @@ class RenameMethodsTests(SimpleTestCase): pass self.assertEqual(len(recorded), 1) msg = str(recorded[0].message) - self.assertEqual(msg, - '`Manager.old` method should be renamed `new`.') + self.assertEqual(msg, '`Manager.old` method should be renamed `new`.') def test_get_new_defined(self): """ @@ -56,8 +55,7 @@ class RenameMethodsTests(SimpleTestCase): manager.old() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) - self.assertEqual(msg, - '`Manager.old` is deprecated, use `new` instead.') + self.assertEqual(msg, '`Manager.old` is deprecated, use `new` instead.') def test_get_old_defined(self): """ @@ -76,8 +74,7 @@ class RenameMethodsTests(SimpleTestCase): manager.old() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) - self.assertEqual(msg, - '`Manager.old` is deprecated, use `new` instead.') + self.assertEqual(msg, '`Manager.old` is deprecated, use `new` instead.') def test_deprecated_subclass_renamed(self): """ @@ -99,8 +96,7 @@ class RenameMethodsTests(SimpleTestCase): deprecated.new() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) - self.assertEqual(msg, - '`Renamed.old` is deprecated, use `new` instead.') + self.assertEqual(msg, '`Renamed.old` is deprecated, use `new` instead.') recorded[:] = [] deprecated.old() self.assertEqual(len(recorded), 2) @@ -132,8 +128,7 @@ class RenameMethodsTests(SimpleTestCase): renamed.old() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) - self.assertEqual(msg, - '`Renamed.old` is deprecated, use `new` instead.') + self.assertEqual(msg, '`Renamed.old` is deprecated, use `new` instead.') def test_deprecated_subclass_renamed_and_mixins(self): """ @@ -163,8 +158,7 @@ class RenameMethodsTests(SimpleTestCase): deprecated.new() self.assertEqual(len(recorded), 1) msg = str(recorded.pop().message) - self.assertEqual(msg, - '`RenamedMixin.old` is deprecated, use `new` instead.') + self.assertEqual(msg, '`RenamedMixin.old` is deprecated, use `new` instead.') deprecated.old() self.assertEqual(len(recorded), 2) msgs = [str(warning.message) for warning in recorded] diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index df02463af7..478754b6fa 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -52,8 +52,10 @@ class BasicExpressionsTests(TestCase): companies = Company.objects.annotate( salaries=F('ceo__salary'), ).values('num_employees', 'salaries').aggregate( - result=Sum(F('salaries') + F('num_employees'), - output_field=models.IntegerField()), + result=Sum( + F('salaries') + F('num_employees'), + output_field=models.IntegerField() + ), ) self.assertEqual(companies['result'], 2395) @@ -572,24 +574,21 @@ class ExpressionOperatorTests(TestCase): def test_lefthand_subtraction(self): # LH Subtraction of floats and integers - Number.objects.filter(pk=self.n.pk).update(integer=F('integer') - 15, - float=F('float') - 42.7) + Number.objects.filter(pk=self.n.pk).update(integer=F('integer') - 15, float=F('float') - 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 27) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(-27.200, places=3)) def test_lefthand_multiplication(self): # Multiplication of floats and integers - Number.objects.filter(pk=self.n.pk).update(integer=F('integer') * 15, - float=F('float') * 42.7) + Number.objects.filter(pk=self.n.pk).update(integer=F('integer') * 15, float=F('float') * 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) def test_lefthand_division(self): # LH Division of floats and integers - Number.objects.filter(pk=self.n.pk).update(integer=F('integer') / 2, - float=F('float') / 42.7) + Number.objects.filter(pk=self.n.pk).update(integer=F('integer') / 2, float=F('float') / 42.7) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 21) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(0.363, places=3)) @@ -618,23 +617,20 @@ class ExpressionOperatorTests(TestCase): def test_lefthand_power(self): # LH Powert arithmetic operation on floats and integers - Number.objects.filter(pk=self.n.pk).update(integer=F('integer') ** 2, - float=F('float') ** 1.5) + Number.objects.filter(pk=self.n.pk).update(integer=F('integer') ** 2, float=F('float') ** 1.5) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 1764) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(61.02, places=2)) def test_right_hand_addition(self): # Right hand operators - Number.objects.filter(pk=self.n.pk).update(integer=15 + F('integer'), - float=42.7 + F('float')) + Number.objects.filter(pk=self.n.pk).update(integer=15 + F('integer'), float=42.7 + F('float')) # RH Addition of floats and integers self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 57) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)) def test_right_hand_subtraction(self): - Number.objects.filter(pk=self.n.pk).update(integer=15 - F('integer'), - float=42.7 - F('float')) + Number.objects.filter(pk=self.n.pk).update(integer=15 - F('integer'), float=42.7 - F('float')) # RH Subtraction of floats and integers self.assertEqual(Number.objects.get(pk=self.n.pk).integer, -27) @@ -642,16 +638,14 @@ class ExpressionOperatorTests(TestCase): def test_right_hand_multiplication(self): # RH Multiplication of floats and integers - Number.objects.filter(pk=self.n.pk).update(integer=15 * F('integer'), - float=42.7 * F('float')) + Number.objects.filter(pk=self.n.pk).update(integer=15 * F('integer'), float=42.7 * F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 630) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) def test_right_hand_division(self): # RH Division of floats and integers - Number.objects.filter(pk=self.n.pk).update(integer=640 / F('integer'), - float=42.7 / F('float')) + Number.objects.filter(pk=self.n.pk).update(integer=640 / F('integer'), float=42.7 / F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 15) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(2.755, places=3)) @@ -665,8 +659,7 @@ class ExpressionOperatorTests(TestCase): def test_righthand_power(self): # RH Powert arithmetic operation on floats and integers - Number.objects.filter(pk=self.n.pk).update(integer=2 ** F('integer'), - float=1.5 ** F('float')) + Number.objects.filter(pk=self.n.pk).update(integer=2 ** F('integer'), float=1.5 ** F('float')) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, 4398046511104) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(536.308, places=3)) @@ -693,11 +686,12 @@ class FTimeDeltaTests(TestCase): # e0: started same day as assigned, zero duration end = stime + delta0 - e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime, - end=end, completed=end.date(), estimated_time=delta0) + e0 = Experiment.objects.create( + name='e0', assigned=sday, start=stime, end=end, + completed=end.date(), estimated_time=delta0, + ) cls.deltas.append(delta0) - cls.delays.append(e0.start - - datetime.datetime.combine(e0.assigned, midnight)) + cls.delays.append(e0.start - datetime.datetime.combine(e0.assigned, midnight)) cls.days_long.append(e0.completed - e0.assigned) # e1: started one day after assigned, tiny duration, data @@ -708,41 +702,43 @@ class FTimeDeltaTests(TestCase): if connection.features.supports_microsecond_precision: delay = datetime.timedelta(1) end = stime + delay + delta1 - e1 = Experiment.objects.create(name='e1', assigned=sday, - start=stime + delay, end=end, completed=end.date(), estimated_time=delta1) + e1 = Experiment.objects.create( + name='e1', assigned=sday, start=stime + delay, end=end, + completed=end.date(), estimated_time=delta1, + ) cls.deltas.append(delta1) - cls.delays.append(e1.start - - datetime.datetime.combine(e1.assigned, midnight)) + cls.delays.append(e1.start - datetime.datetime.combine(e1.assigned, midnight)) cls.days_long.append(e1.completed - e1.assigned) # e2: started three days after assigned, small duration end = stime + delta2 - e2 = Experiment.objects.create(name='e2', - assigned=sday - datetime.timedelta(3), start=stime, end=end, - completed=end.date(), estimated_time=datetime.timedelta(hours=1)) + e2 = Experiment.objects.create( + name='e2', assigned=sday - datetime.timedelta(3), start=stime, + end=end, completed=end.date(), estimated_time=datetime.timedelta(hours=1), + ) cls.deltas.append(delta2) - cls.delays.append(e2.start - - datetime.datetime.combine(e2.assigned, midnight)) + cls.delays.append(e2.start - datetime.datetime.combine(e2.assigned, midnight)) cls.days_long.append(e2.completed - e2.assigned) # e3: started four days after assigned, medium duration delay = datetime.timedelta(4) end = stime + delay + delta3 - e3 = Experiment.objects.create(name='e3', - assigned=sday, start=stime + delay, end=end, completed=end.date(), estimated_time=delta3) + e3 = Experiment.objects.create( + name='e3', assigned=sday, start=stime + delay, end=end, + completed=end.date(), estimated_time=delta3, + ) cls.deltas.append(delta3) - cls.delays.append(e3.start - - datetime.datetime.combine(e3.assigned, midnight)) + cls.delays.append(e3.start - datetime.datetime.combine(e3.assigned, midnight)) cls.days_long.append(e3.completed - e3.assigned) # e4: started 10 days after assignment, long duration end = stime + delta4 - e4 = Experiment.objects.create(name='e4', - assigned=sday - datetime.timedelta(10), start=stime, end=end, - completed=end.date(), estimated_time=delta4 - datetime.timedelta(1)) + e4 = Experiment.objects.create( + name='e4', assigned=sday - datetime.timedelta(10), start=stime, + end=end, completed=end.date(), estimated_time=delta4 - datetime.timedelta(1), + ) cls.deltas.append(delta4) - cls.delays.append(e4.start - - datetime.datetime.combine(e4.assigned, midnight)) + cls.delays.append(e4.start - datetime.datetime.combine(e4.assigned, midnight)) cls.days_long.append(e4.completed - e4.assigned) cls.expnames = [e.name for e in Experiment.objects.all()] @@ -764,49 +760,40 @@ class FTimeDeltaTests(TestCase): def test_delta_add(self): for i in range(len(self.deltas)): delta = self.deltas[i] - test_set = [e.name for e in - Experiment.objects.filter(end__lt=F('start') + delta)] + test_set = [e.name for e in Experiment.objects.filter(end__lt=F('start') + delta)] self.assertEqual(test_set, self.expnames[:i]) - test_set = [e.name for e in - Experiment.objects.filter(end__lt=delta + F('start'))] + test_set = [e.name for e in Experiment.objects.filter(end__lt=delta + F('start'))] self.assertEqual(test_set, self.expnames[:i]) - test_set = [e.name for e in - Experiment.objects.filter(end__lte=F('start') + delta)] + test_set = [e.name for e in Experiment.objects.filter(end__lte=F('start') + delta)] self.assertEqual(test_set, self.expnames[:i + 1]) def test_delta_subtract(self): for i in range(len(self.deltas)): delta = self.deltas[i] - test_set = [e.name for e in - Experiment.objects.filter(start__gt=F('end') - delta)] + test_set = [e.name for e in Experiment.objects.filter(start__gt=F('end') - delta)] self.assertEqual(test_set, self.expnames[:i]) - test_set = [e.name for e in - Experiment.objects.filter(start__gte=F('end') - delta)] + test_set = [e.name for e in Experiment.objects.filter(start__gte=F('end') - delta)] self.assertEqual(test_set, self.expnames[:i + 1]) def test_exclude(self): for i in range(len(self.deltas)): delta = self.deltas[i] - test_set = [e.name for e in - Experiment.objects.exclude(end__lt=F('start') + delta)] + test_set = [e.name for e in Experiment.objects.exclude(end__lt=F('start') + delta)] self.assertEqual(test_set, self.expnames[i:]) - test_set = [e.name for e in - Experiment.objects.exclude(end__lte=F('start') + delta)] + test_set = [e.name for e in Experiment.objects.exclude(end__lte=F('start') + delta)] self.assertEqual(test_set, self.expnames[i + 1:]) def test_date_comparison(self): for i in range(len(self.days_long)): days = self.days_long[i] - test_set = [e.name for e in - Experiment.objects.filter(completed__lt=F('assigned') + days)] + test_set = [e.name for e in Experiment.objects.filter(completed__lt=F('assigned') + days)] self.assertEqual(test_set, self.expnames[:i]) - test_set = [e.name for e in - Experiment.objects.filter(completed__lte=F('assigned') + days)] + test_set = [e.name for e in Experiment.objects.filter(completed__lte=F('assigned') + days)] self.assertEqual(test_set, self.expnames[:i + 1]) @skipUnlessDBFeature("supports_mixed_date_datetime_comparisons") @@ -815,25 +802,22 @@ class FTimeDeltaTests(TestCase): delay = self.delays[i] if not connection.features.supports_microsecond_precision: delay = datetime.timedelta(delay.days, delay.seconds) - test_set = [e.name for e in - Experiment.objects.filter(assigned__gt=F('start') - delay)] + test_set = [e.name for e in Experiment.objects.filter(assigned__gt=F('start') - delay)] self.assertEqual(test_set, self.expnames[:i]) - test_set = [e.name for e in - Experiment.objects.filter(assigned__gte=F('start') - delay)] + test_set = [e.name for e in Experiment.objects.filter(assigned__gte=F('start') - delay)] self.assertEqual(test_set, self.expnames[:i + 1]) def test_mixed_comparisons2(self): delays = [datetime.timedelta(delay.days) for delay in self.delays] for i in range(len(delays)): delay = delays[i] - test_set = [e.name for e in - Experiment.objects.filter(start__lt=F('assigned') + delay)] + test_set = [e.name for e in Experiment.objects.filter(start__lt=F('assigned') + delay)] self.assertEqual(test_set, self.expnames[:i]) - test_set = [e.name for e in - Experiment.objects.filter(start__lte=F('assigned') + delay + - datetime.timedelta(1))] + test_set = [ + e.name for e in Experiment.objects.filter(start__lte=F('assigned') + delay + datetime.timedelta(1)) + ] self.assertEqual(test_set, self.expnames[:i + 1]) def test_delta_update(self): @@ -858,16 +842,16 @@ class FTimeDeltaTests(TestCase): list(Experiment.objects.filter(start=F('start') * datetime.timedelta(0))) def test_durationfield_add(self): - zeros = [e.name for e in - Experiment.objects.filter(start=F('start') + F('estimated_time'))] + zeros = [e.name for e in Experiment.objects.filter(start=F('start') + F('estimated_time'))] self.assertEqual(zeros, ['e0']) - end_less = [e.name for e in - Experiment.objects.filter(end__lt=F('start') + F('estimated_time'))] + end_less = [e.name for e in Experiment.objects.filter(end__lt=F('start') + F('estimated_time'))] self.assertEqual(end_less, ['e2']) - delta_math = [e.name for e in - Experiment.objects.filter(end__gte=F('start') + F('estimated_time') + datetime.timedelta(hours=1))] + delta_math = [ + e.name for e in + Experiment.objects.filter(end__gte=F('start') + F('estimated_time') + datetime.timedelta(hours=1)) + ] self.assertEqual(delta_math, ['e4']) @skipUnlessDBFeature('supports_temporal_subtraction') @@ -906,12 +890,14 @@ class FTimeDeltaTests(TestCase): @skipUnlessDBFeature('supports_temporal_subtraction') def test_datetime_subtraction(self): - under_estimate = [e.name for e in - Experiment.objects.filter(estimated_time__gt=F('end') - F('start'))] + under_estimate = [ + e.name for e in Experiment.objects.filter(estimated_time__gt=F('end') - F('start')) + ] self.assertEqual(under_estimate, ['e2']) - over_estimate = [e.name for e in - Experiment.objects.filter(estimated_time__lt=F('end') - F('start'))] + over_estimate = [ + e.name for e in Experiment.objects.filter(estimated_time__lt=F('end') - F('start')) + ] self.assertEqual(over_estimate, ['e4']) def test_duration_with_datetime(self): diff --git a/tests/extra_regress/tests.py b/tests/extra_regress/tests.py index 242487a060..6a0d7039ae 100644 --- a/tests/extra_regress/tests.py +++ b/tests/extra_regress/tests.py @@ -46,15 +46,15 @@ class ExtraRegressTests(TestCase): }] ) - self.assertQuerysetEqual(qs, - [('Second Revision', 'First Revision')], + self.assertQuerysetEqual( + qs, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title) ) # Queryset to search for string in title: qs2 = RevisionableModel.objects.filter(title__contains="Revision") - self.assertQuerysetEqual(qs2, - [ + self.assertQuerysetEqual( + qs2, [ ('First Revision', 'First Revision'), ('Second Revision', 'First Revision'), ], @@ -63,7 +63,8 @@ class ExtraRegressTests(TestCase): ) # Following queryset should return the most recent revision: - self.assertQuerysetEqual(qs & qs2, + self.assertQuerysetEqual( + qs & qs2, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title), ordered=False @@ -111,10 +112,8 @@ class ExtraRegressTests(TestCase): query as well. """ self.assertEqual( - list(User.objects - .extra(select={"alpha": "%s"}, select_params=(-6,)) - .filter(id=self.u.id) - .values_list('id', flat=True)), + list(User.objects.extra(select={"alpha": "%s"}, select_params=(-6,)) + .filter(id=self.u.id).values_list('id', flat=True)), [self.u.id] ) diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index e027d51249..d1ea0021c5 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -69,10 +69,8 @@ class GetStorageClassTests(SimpleTestCase): get_storage_class raises an error if the requested module don't exist. """ # Error message may or may not be the fully qualified path. - with six.assertRaisesRegex(self, ImportError, - "No module named '?(django.core.files.)?non_existing_storage'?"): - get_storage_class( - 'django.core.files.non_existing_storage.NonExistingStorage') + with six.assertRaisesRegex(self, ImportError, "No module named '?(django.core.files.)?non_existing_storage'?"): + get_storage_class('django.core.files.non_existing_storage.NonExistingStorage') class FileStorageDeconstructionTests(unittest.TestCase): @@ -103,8 +101,7 @@ class FileStorageTests(TestCase): def setUp(self): self.temp_dir = tempfile.mkdtemp() - self.storage = self.storage_class(location=self.temp_dir, - base_url='/test_media_url/') + self.storage = self.storage_class(location=self.temp_dir, base_url='/test_media_url/') # Set up a second temporary directory which is ensured to have a mixed # case name. self.temp_dir2 = tempfile.mkdtemp(suffix='aBc') @@ -345,8 +342,7 @@ class FileStorageTests(TestCase): Saving a pathname should create intermediate directories as necessary. """ self.assertFalse(self.storage.exists('path/to')) - self.storage.save('path/to/test.file', - ContentFile('file saved with path')) + self.storage.save('path/to/test.file', ContentFile('file saved with path')) self.assertTrue(self.storage.exists('path/to')) with self.storage.open('path/to/test.file') as f: @@ -366,8 +362,7 @@ class FileStorageTests(TestCase): self.assertFalse(file.closed) self.assertFalse(file.file.closed) - file = InMemoryUploadedFile(six.StringIO('1'), '', 'test', - 'text/plain', 1, 'utf8') + file = InMemoryUploadedFile(six.StringIO('1'), '', 'test', 'text/plain', 1, 'utf8') with file: self.assertFalse(file.closed) self.storage.save('path/to/test.file', file) @@ -383,8 +378,7 @@ class FileStorageTests(TestCase): f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) - self.assertEqual(self.storage.path(f_name), - os.path.join(self.temp_dir, f_name)) + self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name)) self.storage.delete(f_name) @@ -392,18 +386,18 @@ class FileStorageTests(TestCase): """ File storage returns a url to access a given file from the Web. """ - self.assertEqual(self.storage.url('test.file'), - '%s%s' % (self.storage.base_url, 'test.file')) + self.assertEqual(self.storage.url('test.file'), self.storage.base_url + 'test.file') # should encode special chars except ~!*()' # like encodeURIComponent() JavaScript function do - self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+ =.file"""), - """/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file""") - self.assertEqual(self.storage.url("""ab\0c"""), """/test_media_url/ab%00c""") + self.assertEqual( + self.storage.url(r"~!*()'@#$%^&*abc`+ =.file"), + "/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file" + ) + self.assertEqual(self.storage.url("ab\0c"), "/test_media_url/ab%00c") # should translate os path separator(s) to the url path separator - self.assertEqual(self.storage.url("""a/b\\c.file"""), - """/test_media_url/a/b/c.file""") + self.assertEqual(self.storage.url("""a/b\\c.file"""), "/test_media_url/a/b/c.file") # #25905: remove leading slashes from file names to prevent unsafe url output self.assertEqual(self.storage.url("/evil.com"), "/test_media_url/evil.com") @@ -422,8 +416,7 @@ class FileStorageTests(TestCase): self.storage.url('test.file') # #22717: missing ending slash in base_url should be auto-corrected - storage = self.storage_class(location=self.temp_dir, - base_url='/no_ending_slash') + storage = self.storage_class(location=self.temp_dir, base_url='/no_ending_slash') self.assertEqual( storage.url('test.file'), '%s%s' % (storage.base_url, 'test.file') @@ -443,8 +436,7 @@ class FileStorageTests(TestCase): dirs, files = self.storage.listdir('') self.assertEqual(set(dirs), {'storage_dir_1'}) - self.assertEqual(set(files), - {'storage_test_1', 'storage_test_2'}) + self.assertEqual(set(files), {'storage_test_1', 'storage_test_2'}) self.storage.delete('storage_test_1') self.storage.delete('storage_test_2') @@ -470,8 +462,7 @@ class FileStorageTests(TestCase): file = other_temp_storage.open(mixed_case, 'w') file.write('storage contents') file.close() - self.assertEqual(os.path.join(self.temp_dir2, mixed_case), - other_temp_storage.path(mixed_case)) + self.assertEqual(os.path.join(self.temp_dir2, mixed_case), other_temp_storage.path(mixed_case)) other_temp_storage.delete(mixed_case) def test_makedirs_race_handling(self): @@ -496,13 +487,11 @@ class FileStorageTests(TestCase): try: os.makedirs = fake_makedirs - self.storage.save('normal/test.file', - ContentFile('saved normally')) + self.storage.save('normal/test.file', ContentFile('saved normally')) with self.storage.open('normal/test.file') as f: self.assertEqual(f.read(), b'saved normally') - self.storage.save('raced/test.file', - ContentFile('saved with race')) + self.storage.save('raced/test.file', ContentFile('saved with race')) with self.storage.open('raced/test.file') as f: self.assertEqual(f.read(), b'saved with race') diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py index 66bae79e0e..924b13bec1 100644 --- a/tests/file_uploads/tests.py +++ b/tests/file_uploads/tests.py @@ -585,8 +585,7 @@ class DirectoryCreationTests(SimpleTestCase): self.obj.testfile.save('foo.txt', file, save=False) # The test needs to be done on a specific string as IOError # is raised even without the patch (just not early enough) - self.assertEqual(exc_info.exception.args[0], - "%s exists and is not a directory." % UPLOAD_TO) + self.assertEqual(exc_info.exception.args[0], "%s exists and is not a directory." % UPLOAD_TO) class MultiParserTests(unittest.TestCase): diff --git a/tests/fixtures/tests.py b/tests/fixtures/tests.py index 6da0054873..b021d927f0 100644 --- a/tests/fixtures/tests.py +++ b/tests/fixtures/tests.py @@ -664,8 +664,8 @@ class NonExistentFixtureTests(TestCase): @mock.patch('django.db.connection.enable_constraint_checking') @mock.patch('django.db.connection.disable_constraint_checking') - def test_nonexistent_fixture_no_constraint_checking(self, - disable_constraint_checking, enable_constraint_checking): + def test_nonexistent_fixture_no_constraint_checking( + self, disable_constraint_checking, enable_constraint_checking): """ If no fixtures match the loaddata command, constraints checks on the database shouldn't be disabled. This is performance critical on MSSQL. diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py index 3a47d2617f..150ea9577c 100644 --- a/tests/fixtures_regress/tests.py +++ b/tests/fixtures_regress/tests.py @@ -215,8 +215,7 @@ class TestFixtures(TestCase): """ Test that failing serializer import raises the proper error """ - with six.assertRaisesRegex(self, ImportError, - r"No module named.*unexistent"): + with six.assertRaisesRegex(self, ImportError, r"No module named.*unexistent"): management.call_command( 'loaddata', 'bad_fixture1.unkn', @@ -277,8 +276,7 @@ class TestFixtures(TestCase): ) warning = warning_list.pop() self.assertEqual(warning.category, RuntimeWarning) - self.assertEqual(str(warning.message), - "No fixture data found for 'empty'. (File format may be invalid.)") + self.assertEqual(str(warning.message), "No fixture data found for 'empty'. (File format may be invalid.)") def test_error_message(self): """ diff --git a/tests/flatpages_tests/test_forms.py b/tests/flatpages_tests/test_forms.py index 0ea706010b..ae9da29f5c 100644 --- a/tests/flatpages_tests/test_forms.py +++ b/tests/flatpages_tests/test_forms.py @@ -47,16 +47,14 @@ class FlatpageAdminFormTests(TestCase): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a leading slash."]) - @override_settings(APPEND_SLASH=True, - MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware']) + @override_settings(APPEND_SLASH=True, MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware']) def test_flatpage_requires_trailing_slash_with_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."]) - @override_settings(APPEND_SLASH=False, - MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware']) + @override_settings(APPEND_SLASH=False, MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware']) def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) self.assertTrue(form.is_valid()) diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py index bd33cff4fd..41a3a5185e 100644 --- a/tests/forms_tests/tests/test_fields.py +++ b/tests/forms_tests/tests/test_fields.py @@ -850,8 +850,10 @@ class FieldsTests(SimpleTestCase): self.assertEqual('person@example.com', f.clean('person@example.com')) with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): f.clean('foo') - self.assertEqual('local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', - f.clean('local@domain.with.idn.xyzäöüßabc.part.com')) + self.assertEqual( + 'local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', + f.clean('local@domain.with.idn.xyzäöüßabc.part.com') + ) def test_email_regexp_for_performance(self): f = EmailField() @@ -1259,9 +1261,11 @@ class FieldsTests(SimpleTestCase): def test_choicefield_disabled(self): f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True) - self.assertWidgetRendersTo(f, + self.assertWidgetRendersTo( + f, '') + '' + ) # TypedChoiceField ############################################################ # TypedChoiceField is just like ChoiceField, except that coerced types will @@ -1434,8 +1438,8 @@ class FieldsTests(SimpleTestCase): f.clean('hello') self.assertEqual([], f.clean([])) self.assertEqual([], f.clean(())) - with self.assertRaisesMessage(ValidationError, - "'Select a valid choice. 3 is not one of the available choices.'"): + msg = "'Select a valid choice. 3 is not one of the available choices.'" + with self.assertRaisesMessage(ValidationError, msg): f.clean(['3']) def test_multiplechoicefield_3(self): diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index 99bcfe3417..a8bff32a8c 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -1493,11 +1493,13 @@ value="Should escape < & > and <script>alert('xss')</ address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), - """
  • Username:
  • + self.assertHTMLEqual( + p.as_ul(), + """
  • Username:
  • Password:
  • Realname:
  • -
  • Address:
  • """) +
  • Address:
  • """ + ) # If you specify a custom "attrs" that includes the "maxlength" attribute, # the Field's max_length attribute will override whatever "maxlength" you specify @@ -1507,9 +1509,11 @@ value="Should escape < & > and <script>alert('xss')</ password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), - """
  • Username:
  • -
  • Password:
  • """) + self.assertHTMLEqual( + p.as_ul(), + """
  • Username:
  • +
  • Password:
  • """ + ) def test_specifying_labels(self): # You can specify the label for a field by using the 'label' argument to a Field @@ -1521,10 +1525,12 @@ value="Should escape < & > and <script>alert('xss')</ password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)') p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), - """
  • Your username:
  • + self.assertHTMLEqual( + p.as_ul(), + """
  • Your username:
  • Password1:
  • -
  • Contraseña (de nuevo):
  • """) +
  • Contraseña (de nuevo):
  • """ + ) # Labels for as_* methods will only end in a colon if they don't end in other # punctuation already. @@ -1574,9 +1580,11 @@ value="Should escape < & > and <script>alert('xss')</ password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) - self.assertHTMLEqual(p.as_ul(), - """
  • Username:
  • -
  • Password:
  • """) + self.assertHTMLEqual( + p.as_ul(), + """
  • Username:
  • +
  • Password:
  • """ + ) p = UserRegistration(auto_id='id_%s') self.assertHTMLEqual( p.as_ul(), @@ -1861,8 +1869,7 @@ Password: last_name = CharField(initial='Greatel') birthday = DateField(initial=datetime.date(1974, 8, 16)) - p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', - 'birthday': '1974-08-16'}) + p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16'}) self.assertTrue(p.is_valid()) self.assertNotIn('first_name', p.changed_data) self.assertIn('last_name', p.changed_data) @@ -1876,8 +1883,10 @@ Password: class Person2(Person): pedantic = PedanticField(initial='whatever', show_hidden_initial=True) - p = Person2(data={'first_name': 'Hans', 'last_name': 'Scrmbl', - 'birthday': '1974-08-16', 'initial-pedantic': 'whatever'}) + p = Person2(data={ + 'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16', + 'initial-pedantic': 'whatever', + }) self.assertFalse(p.is_valid()) self.assertIn('pedantic', p.changed_data) @@ -2700,9 +2709,10 @@ Good luck picking a username that doesn't already exist.

    """ class ChoicesField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): - fields = (ChoiceField(label='Rank', - choices=((1, 1), (2, 2))), - CharField(label='Name', max_length=10)) + fields = ( + ChoiceField(label='Rank', choices=((1, 1), (2, 2))), + CharField(label='Name', max_length=10), + ) super(ChoicesField, self).__init__(fields=fields, *args, **kwargs) field = ChoicesField() @@ -2787,8 +2797,10 @@ Good luck picking a username that doesn't already exist.

    with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) - six.assertRaisesRegex(self, ValidationError, - "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) + six.assertRaisesRegex( + self, ValidationError, + "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'] + ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) @@ -2801,8 +2813,10 @@ Good luck picking a username that doesn't already exist.

    with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(['+61']) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) - six.assertRaisesRegex(self, ValidationError, - "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) + six.assertRaisesRegex( + self, ValidationError, + "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'] + ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(['61', '287654321', '123', 'Home']) diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index eb1b04b4e3..f367d22397 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -46,8 +46,7 @@ class EmptyFsetWontValidate(BaseFormSet): # Let's define a FormSet that takes a list of favorite drinks, but raises an # error if there are any duplicates. Used in ``test_clean_hook``, # ``test_regression_6926`` & ``test_regression_12878``. -FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, - formset=BaseFavoriteDrinksFormSet, extra=3) +FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3) # Used in ``test_formset_splitdatetimefield``. @@ -65,7 +64,8 @@ class CustomKwargForm(Form): class FormsFormsetTestCase(SimpleTestCase): - def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet, + def make_choiceformset( + self, formset_data=None, formset_class=ChoiceFormSet, total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs): """ Make a ChoiceFormset from the given formset_data. @@ -1162,8 +1162,7 @@ class FormsFormsetTestCase(SimpleTestCase): ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) formset = ChoiceFormSet(data, auto_id=False, prefix='choices') self.assertIsInstance(formset.non_form_errors(), ErrorList) - self.assertEqual(list(formset.non_form_errors()), - ['This is a non-form error']) + self.assertEqual(list(formset.non_form_errors()), ['This is a non-form error']) def test_validate_max_ignores_forms_marked_for_deletion(self): class CheckForm(Form): diff --git a/tests/forms_tests/tests/test_utils.py b/tests/forms_tests/tests/test_utils.py index 260306165f..9104d235dd 100644 --- a/tests/forms_tests/tests/test_utils.py +++ b/tests/forms_tests/tests/test_utils.py @@ -59,27 +59,30 @@ class FormsUtilsTestCase(SimpleTestCase): ################### # Can take a string. - self.assertHTMLEqual(str(ErrorList(ValidationError("There was an error.").messages)), - '
    • There was an error.
    ') - + self.assertHTMLEqual( + str(ErrorList(ValidationError("There was an error.").messages)), + '
    • There was an error.
    ' + ) # Can take a unicode string. - self.assertHTMLEqual(six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)), - '
    • Not π.
    ') - + self.assertHTMLEqual( + six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)), + '
    • Not π.
    ' + ) # Can take a lazy string. - self.assertHTMLEqual(str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)), - '
    • Error.
    ') - + self.assertHTMLEqual( + str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)), + '
    • Error.
    ' + ) # Can take a list. - self.assertHTMLEqual(str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), - '
    • Error one.
    • Error two.
    ') - + self.assertHTMLEqual( + str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), + '
    • Error one.
    • Error two.
    ' + ) # Can take a dict. self.assertHTMLEqual( str(ErrorList(sorted(ValidationError({'error_1': "1. Error one.", 'error_2': "2. Error two."}).messages))), '
    • 1. Error one.
    • 2. Error two.
    ' ) - # Can take a mixture in a list. self.assertHTMLEqual( str(ErrorList(sorted(ValidationError([ diff --git a/tests/forms_tests/tests/test_widgets.py b/tests/forms_tests/tests/test_widgets.py index 261cb4bc38..8f84ddcb9b 100644 --- a/tests/forms_tests/tests/test_widgets.py +++ b/tests/forms_tests/tests/test_widgets.py @@ -170,8 +170,7 @@ class LiveWidgetTests(AdminSeleniumTestCase): Test that a roundtrip on a ModelForm doesn't alter the TextField value """ article = Article.objects.create(content="\nTst\n") - self.selenium.get('%s%s' % (self.live_server_url, - reverse('article_form', args=[article.pk]))) + self.selenium.get(self.live_server_url + reverse('article_form', args=[article.pk])) self.selenium.find_element_by_id('submit').submit() article = Article.objects.get(pk=article.pk) # Should be "\nTst\n" after #19251 is fixed diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py index 0b35bb506d..b047cc7a53 100644 --- a/tests/generic_inline_admin/tests.py +++ b/tests/generic_inline_admin/tests.py @@ -191,8 +191,7 @@ class GenericAdminViewTest(TestDataMixin, TestCase): def test_generic_inline_formset_factory(self): # Regression test for #10522. - inline_formset = generic_inlineformset_factory(Media, - exclude=('url',)) + inline_formset = generic_inlineformset_factory(Media, exclude=('url',)) # Regression test for #12340. e = Episode.objects.get(name='This Week in Django') diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py index 806f8ca91a..91b1640b57 100644 --- a/tests/generic_relations/tests.py +++ b/tests/generic_relations/tests.py @@ -524,8 +524,7 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id" />

    """ % tag def test_get_or_create(self): # get_or_create should work with virtual fields (content_object) quartz = Mineral.objects.create(name="Quartz", hardness=7) - tag, created = TaggedItem.objects.get_or_create(tag="shiny", - defaults={'content_object': quartz}) + tag, created = TaggedItem.objects.get_or_create(tag="shiny", defaults={'content_object': quartz}) self.assertTrue(created) self.assertEqual(tag.tag, "shiny") self.assertEqual(tag.content_object.id, quartz.id) @@ -534,13 +533,11 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id" />

    """ % tag # update_or_create should work with virtual fields (content_object) quartz = Mineral.objects.create(name="Quartz", hardness=7) diamond = Mineral.objects.create(name="Diamond", hardness=7) - tag, created = TaggedItem.objects.update_or_create(tag="shiny", - defaults={'content_object': quartz}) + tag, created = TaggedItem.objects.update_or_create(tag="shiny", defaults={'content_object': quartz}) self.assertTrue(created) self.assertEqual(tag.content_object.id, quartz.id) - tag, created = TaggedItem.objects.update_or_create(tag="shiny", - defaults={'content_object': diamond}) + tag, created = TaggedItem.objects.update_or_create(tag="shiny", defaults={'content_object': diamond}) self.assertFalse(created) self.assertEqual(tag.content_object.id, diamond.id) @@ -589,8 +586,7 @@ class GenericInlineFormsetTest(TestCase): self.instance.saved_by = "custom method" return super(SaveTestForm, self).save(*args, **kwargs) - Formset = generic_inlineformset_factory( - ForProxyModelModel, fields='__all__', form=SaveTestForm) + Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', form=SaveTestForm) instance = ProxyRelatedModel.objects.create() @@ -607,8 +603,7 @@ class GenericInlineFormsetTest(TestCase): self.assertEqual(new_obj.saved_by, "custom method") def test_save_new_for_proxy(self): - Formset = generic_inlineformset_factory(ForProxyModelModel, - fields='__all__', for_concrete_model=False) + Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', for_concrete_model=False) instance = ProxyRelatedModel.objects.create() @@ -626,8 +621,7 @@ class GenericInlineFormsetTest(TestCase): self.assertEqual(new_obj.obj, instance) def test_save_new_for_concrete(self): - Formset = generic_inlineformset_factory(ForProxyModelModel, - fields='__all__', for_concrete_model=True) + Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', for_concrete_model=True) instance = ProxyRelatedModel.objects.create() diff --git a/tests/generic_views/test_edit.py b/tests/generic_views/test_edit.py index b4b2986eed..c1b9eba9d8 100644 --- a/tests/generic_views/test_edit.py +++ b/tests/generic_views/test_edit.py @@ -103,31 +103,27 @@ class CreateViewTests(TestCase): self.assertNotIn('author', res.context) self.assertTemplateUsed(res, 'generic_views/author_form.html') - res = self.client.post('/edit/authors/create/', - {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) + res = self.client.post('/edit/authors/create/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/list/authors/') self.assertQuerysetEqual(Author.objects.all(), ['']) def test_create_invalid(self): - res = self.client.post('/edit/authors/create/', - {'name': 'A' * 101, 'slug': 'randall-munroe'}) + res = self.client.post('/edit/authors/create/', {'name': 'A' * 101, 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertEqual(len(res.context['form'].errors), 1) self.assertEqual(Author.objects.count(), 0) def test_create_with_object_url(self): - res = self.client.post('/edit/artists/create/', - {'name': 'Rene Magritte'}) + res = self.client.post('/edit/artists/create/', {'name': 'Rene Magritte'}) self.assertEqual(res.status_code, 302) artist = Artist.objects.get(name='Rene Magritte') self.assertRedirects(res, '/detail/artist/%d/' % artist.pk) self.assertQuerysetEqual(Artist.objects.all(), ['']) def test_create_with_redirect(self): - res = self.client.post('/edit/authors/create/redirect/', - {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) + res = self.client.post('/edit/authors/create/redirect/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/edit/authors/create/') self.assertQuerysetEqual(Author.objects.all(), ['']) @@ -158,24 +154,21 @@ class CreateViewTests(TestCase): self.assertNotIn('author', res.context) self.assertTemplateUsed(res, 'generic_views/form.html') - res = self.client.post('/edit/authors/create/special/', - {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) + res = self.client.post('/edit/authors/create/special/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) obj = Author.objects.get(slug='randall-munroe') self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk})) self.assertQuerysetEqual(Author.objects.all(), ['']) def test_create_without_redirect(self): - try: - self.client.post('/edit/authors/create/naive/', - {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) - self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided') - except ImproperlyConfigured: - pass + with self.assertRaises(ImproperlyConfigured): + self.client.post('/edit/authors/create/naive/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) def test_create_restricted(self): - res = self.client.post('/edit/authors/create/restricted/', - {'name': 'Randall Munroe', 'slug': 'randall-munroe'}) + res = self.client.post( + '/edit/authors/create/restricted/', + {'name': 'Randall Munroe', 'slug': 'randall-munroe'} + ) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/accounts/login/?next=/edit/authors/create/restricted/') @@ -185,16 +178,14 @@ class CreateViewTests(TestCase): model = Author fields = ['name'] - self.assertEqual(list(MyCreateView().get_form_class().base_fields), - ['name']) + self.assertEqual(list(MyCreateView().get_form_class().base_fields), ['name']) def test_create_view_all_fields(self): class MyCreateView(CreateView): model = Author fields = '__all__' - self.assertEqual(list(MyCreateView().get_form_class().base_fields), - ['name', 'slug']) + self.assertEqual(list(MyCreateView().get_form_class().base_fields), ['name', 'slug']) def test_create_view_without_explicit_fields(self): class MyCreateView(CreateView): @@ -235,8 +226,10 @@ class UpdateViewTests(TestCase): self.assertEqual(res.context['view'].get_form_called_count, 1) # Modification with both POST and PUT (browser compatible) - res = self.client.post('/edit/author/%d/update/' % a.pk, - {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}) + res = self.client.post( + '/edit/author/%d/update/' % a.pk, + {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'} + ) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/list/authors/') self.assertQuerysetEqual(Author.objects.all(), ['']) @@ -246,8 +239,7 @@ class UpdateViewTests(TestCase): name='Randall Munroe', slug='randall-munroe', ) - res = self.client.post('/edit/author/%d/update/' % a.pk, - {'name': 'A' * 101, 'slug': 'randall-munroe'}) + res = self.client.post('/edit/author/%d/update/' % a.pk, {'name': 'A' * 101, 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 200) self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertEqual(len(res.context['form'].errors), 1) @@ -256,8 +248,7 @@ class UpdateViewTests(TestCase): def test_update_with_object_url(self): a = Artist.objects.create(name='Rene Magritte') - res = self.client.post('/edit/artists/%d/update/' % a.pk, - {'name': 'Rene Magritte'}) + res = self.client.post('/edit/artists/%d/update/' % a.pk, {'name': 'Rene Magritte'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/detail/artist/%d/' % a.pk) self.assertQuerysetEqual(Artist.objects.all(), ['']) @@ -267,8 +258,10 @@ class UpdateViewTests(TestCase): name='Randall Munroe', slug='randall-munroe', ) - res = self.client.post('/edit/author/%d/update/redirect/' % a.pk, - {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) + res = self.client.post( + '/edit/author/%d/update/redirect/' % a.pk, + {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'} + ) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/edit/authors/create/') self.assertQuerysetEqual(Author.objects.all(), ['']) @@ -308,8 +301,10 @@ class UpdateViewTests(TestCase): self.assertNotIn('author', res.context) self.assertTemplateUsed(res, 'generic_views/form.html') - res = self.client.post('/edit/author/%d/update/special/' % a.pk, - {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) + res = self.client.post( + '/edit/author/%d/update/special/' % a.pk, + {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'} + ) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/detail/author/%d/' % a.pk) self.assertQuerysetEqual(Author.objects.all(), ['']) @@ -322,8 +317,10 @@ class UpdateViewTests(TestCase): # Should raise exception -- No redirect URL provided, and no # get_absolute_url provided with self.assertRaises(ImproperlyConfigured): - self.client.post('/edit/author/%d/update/naive/' % a.pk, - {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) + self.client.post( + '/edit/author/%d/update/naive/' % a.pk, + {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'} + ) def test_update_get_object(self): a = Author.objects.create( @@ -340,8 +337,7 @@ class UpdateViewTests(TestCase): self.assertTemplateUsed(res, 'generic_views/author_form.html') # Modification with both POST and PUT (browser compatible) - res = self.client.post('/edit/author/update/', - {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}) + res = self.client.post('/edit/author/update/', {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}) self.assertEqual(res.status_code, 302) self.assertRedirects(res, '/list/authors/') self.assertQuerysetEqual(Author.objects.all(), ['']) diff --git a/tests/generic_views/test_list.py b/tests/generic_views/test_list.py index fb2ac20951..81993eaac0 100644 --- a/tests/generic_views/test_list.py +++ b/tests/generic_views/test_list.py @@ -238,8 +238,7 @@ class ListViewTests(TestCase): self._make_authors(1) res = self.client.get('/list/authors/paginated/2/') self.assertEqual(res.status_code, 404) - self.assertEqual(force_str(res.context.get('reason')), - "Invalid page (2): That page contains no results") + self.assertEqual(force_str(res.context.get('reason')), "Invalid page (2): That page contains no results") def _make_authors(self, n): Author.objects.all().delete() diff --git a/tests/gis_tests/gdal_tests/test_ds.py b/tests/gis_tests/gdal_tests/test_ds.py index 83517bba8f..8bd0e13303 100644 --- a/tests/gis_tests/gdal_tests/test_ds.py +++ b/tests/gis_tests/gdal_tests/test_ds.py @@ -12,7 +12,8 @@ if HAS_GDAL: # List of acceptable data sources. ds_list = ( - TestDS('test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile', + TestDS( + 'test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile', fields={'dbl': OFTReal, 'int': OFTInteger, 'str': OFTString}, extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS srs_wkt=( @@ -27,7 +28,8 @@ if HAS_GDAL: }, fids=range(5) ), - TestDS('test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', + TestDS( + 'test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', driver='OGR_VRT' if GDAL_VERSION >= (2, 0) else 'VRT', fields={ 'POINT_X': OFTString, @@ -42,7 +44,8 @@ if HAS_GDAL: }, fids=range(1, 4) ), - TestDS('test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3, + TestDS( + 'test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3, driver='ESRI Shapefile', fields={'float': OFTReal, 'int': OFTInteger, 'str': OFTString}, extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS diff --git a/tests/gis_tests/gdal_tests/test_geom.py b/tests/gis_tests/gdal_tests/test_geom.py index 07a79f6d12..163399289a 100644 --- a/tests/gis_tests/gdal_tests/test_geom.py +++ b/tests/gis_tests/gdal_tests/test_geom.py @@ -15,9 +15,10 @@ except ImportError: if HAS_GDAL: - from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType, - GDALException, OGRIndexError, SpatialReference, CoordTransform, - GDAL_VERSION) + from django.contrib.gis.gdal import ( + OGRGeometry, OGRGeomType, GDALException, OGRIndexError, + SpatialReference, CoordTransform, GDAL_VERSION, + ) @skipUnless(HAS_GDAL, "GDAL is required") diff --git a/tests/gis_tests/gdal_tests/test_raster.py b/tests/gis_tests/gdal_tests/test_raster.py index 18453e6eb4..9ea2d4f027 100644 --- a/tests/gis_tests/gdal_tests/test_raster.py +++ b/tests/gis_tests/gdal_tests/test_raster.py @@ -96,8 +96,10 @@ class GDALRasterTests(unittest.TestCase): def test_geotransform_and_friends(self): # Assert correct values for file based raster - self.assertEqual(self.rs.geotransform, - [511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0]) + self.assertEqual( + self.rs.geotransform, + [511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0] + ) self.assertEqual(self.rs.origin, [511700.4680706557, 435103.3771231986]) self.assertEqual(self.rs.origin.x, 511700.4680706557) self.assertEqual(self.rs.origin.y, 435103.3771231986) @@ -124,9 +126,10 @@ class GDALRasterTests(unittest.TestCase): self.assertEqual(rsmem.height, 5) def test_rs_extent(self): - self.assertEqual(self.rs.extent, - (511700.4680706557, 417703.3771231986, - 528000.4680706557, 435103.3771231986)) + self.assertEqual( + self.rs.extent, + (511700.4680706557, 417703.3771231986, 528000.4680706557, 435103.3771231986) + ) def test_rs_bands(self): self.assertEqual(len(self.rs.bands), 1) @@ -305,8 +308,7 @@ class GDALRasterTests(unittest.TestCase): @unittest.skipUnless(HAS_GDAL, "GDAL is required") class GDALBandTests(SimpleTestCase): def setUp(self): - self.rs_path = os.path.join(os.path.dirname(upath(__file__)), - '../data/rasters/raster.tif') + self.rs_path = os.path.join(os.path.dirname(upath(__file__)), '../data/rasters/raster.tif') rs = GDALRaster(self.rs_path) self.band = rs.bands[0] diff --git a/tests/gis_tests/geoapp/test_serializers.py b/tests/gis_tests/geoapp/test_serializers.py index 69ec73db74..4dfc250621 100644 --- a/tests/gis_tests/geoapp/test_serializers.py +++ b/tests/gis_tests/geoapp/test_serializers.py @@ -73,8 +73,9 @@ class GeoJSONSerializerTests(TestCase): the 'properties' of the generated output. """ PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)') - geojson = serializers.serialize('geojson', PennsylvaniaCity.objects.all(), - fields=('county', 'point')) + geojson = serializers.serialize( + 'geojson', PennsylvaniaCity.objects.all(), fields=('county', 'point'), + ) geodata = json.loads(geojson) self.assertIn('county', geodata['features'][0]['properties']) self.assertNotIn('founded', geodata['features'][0]['properties']) @@ -85,7 +86,8 @@ class GeoJSONSerializerTests(TestCase): geodata = json.loads(geojson) self.assertEqual( [int(c) for c in geodata['features'][0]['geometry']['coordinates']], - [1564802, 5613214]) + [1564802, 5613214] + ) @mock.patch('django.contrib.gis.serializers.geojson.HAS_GDAL', False) def test_without_gdal(self): diff --git a/tests/gis_tests/geos_tests/test_geos_mutation.py b/tests/gis_tests/geos_tests/test_geos_mutation.py index d235aeb2fc..b540fc1aa7 100644 --- a/tests/gis_tests/geos_tests/test_geos_mutation.py +++ b/tests/gis_tests/geos_tests/test_geos_mutation.py @@ -147,8 +147,7 @@ class GEOSMutationTest(unittest.TestCase): 'Polygon _get_single_external(1)') # _set_list - pg._set_list(2, (((1, 2), (10, 0), (12, 9), (-1, 15), (1, 2)), - ((4, 2), (5, 2), (5, 3), (4, 2)))) + pg._set_list(2, (((1, 2), (10, 0), (12, 9), (-1, 15), (1, 2)), ((4, 2), (5, 2), (5, 3), (4, 2)))) self.assertEqual( pg.coords, (((1.0, 2.0), (10.0, 0.0), (12.0, 9.0), (-1.0, 15.0), (1.0, 2.0)), @@ -161,8 +160,11 @@ class GEOSMutationTest(unittest.TestCase): def test06_Collection(self): 'Testing Collection mutations' - for mp in (MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))), - fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)')): + points = ( + MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))), + fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)'), + ) + for mp in points: self.assertEqual(mp._get_single_external(2), Point(5, -4), 'Collection _get_single_external') mp._set_list(3, map(Point, ((5, 5), (3, -2), (8, 1)))) diff --git a/tests/gis_tests/gis_migrations/test_operations.py b/tests/gis_tests/gis_migrations/test_operations.py index 680742f41d..e2f5e106d7 100644 --- a/tests/gis_tests/gis_migrations/test_operations.py +++ b/tests/gis_tests/gis_migrations/test_operations.py @@ -73,7 +73,7 @@ class OperationTests(TransactionTestCase): self.assertIn(column, indexes) def alter_gis_model(self, migration_class, model_name, field_name, - blank=False, field_class=None): + blank=False, field_class=None): project_state = self.set_up_test_model() self.current_state = project_state args = [model_name, field_name] @@ -90,8 +90,7 @@ class OperationTests(TransactionTestCase): """ Test the AddField operation with a geometry-enabled column. """ - self.alter_gis_model(migrations.AddField, 'Neighborhood', - 'path', False, fields.LineStringField) + self.alter_gis_model(migrations.AddField, 'Neighborhood', 'path', False, fields.LineStringField) self.assertColumnExists('gis_neighborhood', 'path') # Test GeometryColumns when available @@ -107,8 +106,7 @@ class OperationTests(TransactionTestCase): """ Test the AddField operation with a raster-enabled column. """ - self.alter_gis_model(migrations.AddField, 'Neighborhood', - 'heatmap', False, fields.RasterField) + self.alter_gis_model(migrations.AddField, 'Neighborhood', 'heatmap', False, fields.RasterField) self.assertColumnExists('gis_neighborhood', 'heatmap') # Test spatial indices when available @@ -140,8 +138,7 @@ class OperationTests(TransactionTestCase): """ Should be able to add a GeometryField with blank=True. """ - self.alter_gis_model(migrations.AddField, 'Neighborhood', - 'path', True, fields.LineStringField) + self.alter_gis_model(migrations.AddField, 'Neighborhood', 'path', True, fields.LineStringField) self.assertColumnExists('gis_neighborhood', 'path') # Test GeometryColumns when available @@ -157,8 +154,7 @@ class OperationTests(TransactionTestCase): """ Should be able to add a RasterField with blank=True. """ - self.alter_gis_model(migrations.AddField, 'Neighborhood', - 'heatmap', True, fields.RasterField) + self.alter_gis_model(migrations.AddField, 'Neighborhood', 'heatmap', True, fields.RasterField) self.assertColumnExists('gis_neighborhood', 'heatmap') # Test spatial indices when available diff --git a/tests/gis_tests/layermap/tests.py b/tests/gis_tests/layermap/tests.py index 7713706704..7dc8683595 100644 --- a/tests/gis_tests/layermap/tests.py +++ b/tests/gis_tests/layermap/tests.py @@ -15,13 +15,16 @@ from django.test import TestCase, override_settings, skipUnlessDBFeature from django.utils._os import upath if HAS_GEOS and HAS_GDAL: - from django.contrib.gis.utils.layermapping import (LayerMapping, - LayerMapError, InvalidDecimal, InvalidString, MissingForeignKey) + from django.contrib.gis.utils.layermapping import ( + LayerMapping, LayerMapError, InvalidDecimal, InvalidString, + MissingForeignKey, + ) from django.contrib.gis.gdal import DataSource from .models import ( City, County, CountyFeat, Interstate, ICity1, ICity2, Invalid, State, - city_mapping, co_mapping, cofeat_mapping, inter_mapping) + city_mapping, co_mapping, cofeat_mapping, inter_mapping, + ) shp_path = os.path.realpath(os.path.join(os.path.dirname(upath(__file__)), os.pardir, 'data')) diff --git a/tests/gis_tests/test_geoip.py b/tests/gis_tests/test_geoip.py index 2d037d74d6..15d18165e5 100644 --- a/tests/gis_tests/test_geoip.py +++ b/tests/gis_tests/test_geoip.py @@ -26,8 +26,10 @@ if HAS_GEOIP: # 'GeoLiteCity.dat'. -@skipUnless(HAS_GEOIP and getattr(settings, "GEOIP_PATH", None), - "GeoIP is required along with the GEOIP_PATH setting.") +@skipUnless( + HAS_GEOIP and getattr(settings, "GEOIP_PATH", None), + "GeoIP is required along with the GEOIP_PATH setting." +) @ignore_warnings(category=RemovedInDjango20Warning) class GeoIPTest(unittest.TestCase): addr = '128.249.1.1' diff --git a/tests/gis_tests/test_geoip2.py b/tests/gis_tests/test_geoip2.py index 89dd2f5870..7db1648cca 100644 --- a/tests/gis_tests/test_geoip2.py +++ b/tests/gis_tests/test_geoip2.py @@ -19,8 +19,10 @@ if HAS_GEOIP2: # The GEOIP_DATA path should be the only setting set (the directory # should contain links or the actual database files 'GeoLite2-City.mmdb' and # 'GeoLite2-City.mmdb'. -@skipUnless(HAS_GEOIP2 and getattr(settings, "GEOIP_PATH", None), - "GeoIP is required along with the GEOIP_PATH setting.") +@skipUnless( + HAS_GEOIP2 and getattr(settings, "GEOIP_PATH", None), + "GeoIP is required along with the GEOIP_PATH setting." +) class GeoIPTest(unittest.TestCase): addr = '128.249.1.1' fqdn = 'tmc.edu' diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index e42d4918eb..59ff3f4a70 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -461,9 +461,11 @@ class HttpResponseSubclassesTests(SimpleTestCase): response = HttpResponseRedirect('/redirected/') self.assertEqual(response.status_code, 302) # Test that standard HttpResponse init args can be used - response = HttpResponseRedirect('/redirected/', + response = HttpResponseRedirect( + '/redirected/', content='The resource has temporarily moved', - content_type='text/html') + content_type='text/html', + ) self.assertContains(response, 'The resource has temporarily moved', status_code=302) # Test that url attribute is right self.assertEqual(response.url, response['Location']) @@ -490,9 +492,7 @@ class HttpResponseSubclassesTests(SimpleTestCase): response = HttpResponseNotAllowed(['GET']) self.assertEqual(response.status_code, 405) # Test that standard HttpResponse init args can be used - response = HttpResponseNotAllowed(['GET'], - content='Only the GET method is allowed', - content_type='text/html') + response = HttpResponseNotAllowed(['GET'], content='Only the GET method is allowed', content_type='text/html') self.assertContains(response, 'Only the GET method is allowed', status_code=405) def test_not_allowed_repr(self): diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py index f5dc3edfc7..e2fa66976a 100644 --- a/tests/humanize_tests/tests.py +++ b/tests/humanize_tests/tests.py @@ -70,24 +70,30 @@ class HumanizeTests(TestCase): self.humanize_tester(test_list, result_list, 'ordinal', lambda x: x) def test_intcomma(self): - test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25, - '100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'), - None) - result_list = ('100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', - '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567', - None) - + test_list = ( + 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000', + '10123', '10311', '1000000', '1234567.1234567', + Decimal('1234567.1234567'), None, + ) + result_list = ( + '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', + '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', + '1,234,567.1234567', None, + ) with translation.override('en'): self.humanize_tester(test_list, result_list, 'intcomma') def test_l10n_intcomma(self): - test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25, - '100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'), - None) - result_list = ('100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', - '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567', - None) - + test_list = ( + 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000', + '10123', '10311', '1000000', '1234567.1234567', + Decimal('1234567.1234567'), None, + ) + result_list = ( + '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', + '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', + '1,234,567.1234567', None, + ) with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False): with translation.override('en'): self.humanize_tester(test_list, result_list, 'intcomma') @@ -98,14 +104,16 @@ class HumanizeTests(TestCase): self.humanize_tester([100], ['100'], 'intcomma') def test_intword(self): - test_list = ('100', '1000000', '1200000', '1290000', - '1000000000', '2000000000', '6000000000000', - '1300000000000000', '3500000000000000000000', - '8100000000000000000000000000000000', None) - result_list = ('100', '1.0 million', '1.2 million', '1.3 million', - '1.0 billion', '2.0 billion', '6.0 trillion', - '1.3 quadrillion', '3.5 sextillion', - '8.1 decillion', None) + test_list = ( + '100', '1000000', '1200000', '1290000', '1000000000', '2000000000', + '6000000000000', '1300000000000000', '3500000000000000000000', + '8100000000000000000000000000000000', None, + ) + result_list = ( + '100', '1.0 million', '1.2 million', '1.3 million', '1.0 billion', + '2.0 billion', '6.0 trillion', '1.3 quadrillion', '3.5 sextillion', + '8.1 decillion', None, + ) with translation.override('en'): self.humanize_tester(test_list, result_list, 'intword') @@ -119,10 +127,14 @@ class HumanizeTests(TestCase): self.humanize_tester(test_list, result_list, 'intcomma') def test_i18n_intword(self): - test_list = ('100', '1000000', '1200000', '1290000', - '1000000000', '2000000000', '6000000000000') - result_list = ('100', '1,0 Million', '1,2 Millionen', '1,3 Millionen', - '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen') + test_list = ( + '100', '1000000', '1200000', '1290000', '1000000000', '2000000000', + '6000000000000', + ) + result_list = ( + '100', '1,0 Million', '1,2 Millionen', '1,3 Millionen', + '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen', + ) with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): with translation.override('de'): self.humanize_tester(test_list, result_list, 'intword') @@ -130,8 +142,7 @@ class HumanizeTests(TestCase): def test_apnumber(self): test_list = [str(x) for x in range(1, 11)] test_list.append(None) - result_list = ('one', 'two', 'three', 'four', 'five', 'six', - 'seven', 'eight', 'nine', '10', None) + result_list = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', '10', None) with translation.override('en'): self.humanize_tester(test_list, result_list, 'apnumber') diff --git a/tests/i18n/test_compilation.py b/tests/i18n/test_compilation.py index f60904ffa6..fdc5fce9b8 100644 --- a/tests/i18n/test_compilation.py +++ b/tests/i18n/test_compilation.py @@ -172,8 +172,7 @@ class CompilationErrorHandling(MessageCompilationTests): # Make sure the output of msgfmt is unaffected by the current locale. env = os.environ.copy() env.update({'LANG': 'C'}) - with mock.patch('django.core.management.utils.Popen', - lambda *args, **kwargs: Popen(*args, env=env, **kwargs)): + with mock.patch('django.core.management.utils.Popen', lambda *args, **kwargs: Popen(*args, env=env, **kwargs)): if six.PY2: # Various assertRaises on PY2 don't support unicode error messages. try: diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index 2f8056560d..6fdfbcb896 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -66,8 +66,7 @@ class ExtractorTests(SerializeMixin, SimpleTestCase): def _run_makemessages(self, **options): os.chdir(self.test_dir) out = StringIO() - management.call_command('makemessages', locale=[LOCALE], verbosity=2, - stdout=out, **options) + management.call_command('makemessages', locale=[LOCALE], verbosity=2, stdout=out, **options) output = out.getvalue() self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, 'r') as fp: @@ -776,10 +775,8 @@ class CustomLayoutExtractionTests(ExtractorTests): * translations outside of that app are in LOCALE_PATHS[0] """ os.chdir(self.test_dir) - self.addCleanup(shutil.rmtree, - os.path.join(settings.LOCALE_PATHS[0], LOCALE), True) - self.addCleanup(shutil.rmtree, - os.path.join(self.test_dir, 'app_with_locale', 'locale', LOCALE), True) + self.addCleanup(shutil.rmtree, os.path.join(settings.LOCALE_PATHS[0], LOCALE), True) + self.addCleanup(shutil.rmtree, os.path.join(self.test_dir, 'app_with_locale', 'locale', LOCALE), True) management.call_command('makemessages', locale=[LOCALE], verbosity=0) project_de_locale = os.path.join( diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py index d365f3be6d..e860702313 100644 --- a/tests/i18n/tests.py +++ b/tests/i18n/tests.py @@ -708,8 +708,7 @@ class FormattingTests(SimpleTestCase): # thousand separator and grouping when USE_L10N is False even # if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and # THOUSAND_SEPARATOR settings are specified - with self.settings(USE_THOUSAND_SEPARATOR=True, - NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'): + with self.settings(USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'): self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) @@ -1527,8 +1526,11 @@ class ResolutionOrderI18NTests(SimpleTestCase): def assertUgettext(self, msgid, msgstr): result = ugettext(msgid) - self.assertIn(msgstr, result, ("The string '%s' isn't in the " - "translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result))) + self.assertIn( + msgstr, result, + "The string '%s' isn't in the translation of '%s'; the actual result is '%s'." + % (msgstr, msgid, result) + ) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): diff --git a/tests/indexes/tests.py b/tests/indexes/tests.py index 270f796c85..6e27130f63 100644 --- a/tests/indexes/tests.py +++ b/tests/indexes/tests.py @@ -40,8 +40,7 @@ class SchemaIndexesTests(TestCase): index_sql = connection.schema_editor()._model_indexes_sql(IndexTogetherSingleList) self.assertEqual(len(index_sql), 1) - @skipUnless(connection.vendor == 'postgresql', - "This is a postgresql-specific issue") + @skipUnless(connection.vendor == 'postgresql', "This is a postgresql-specific issue") def test_postgresql_text_indexes(self): """Test creation of PostgreSQL-specific text indexes (#12234)""" from .models import IndexedArticle @@ -53,8 +52,7 @@ class SchemaIndexesTests(TestCase): # index (#19441). self.assertIn('("slug" varchar_pattern_ops)', index_sql[4]) - @skipUnless(connection.vendor == 'postgresql', - "This is a postgresql-specific issue") + @skipUnless(connection.vendor == 'postgresql', "This is a postgresql-specific issue") def test_postgresql_virtual_relation_indexes(self): """Test indexes are not created for related objects""" index_sql = connection.schema_editor()._model_indexes_sql(Article) diff --git a/tests/introspection/tests.py b/tests/introspection/tests.py index 949914ddbf..d36269d8cf 100644 --- a/tests/introspection/tests.py +++ b/tests/introspection/tests.py @@ -16,10 +16,8 @@ class IntrospectionTests(TransactionTestCase): def test_table_names(self): tl = connection.introspection.table_names() self.assertEqual(tl, sorted(tl)) - self.assertIn(Reporter._meta.db_table, tl, - "'%s' isn't in table_list()." % Reporter._meta.db_table) - self.assertIn(Article._meta.db_table, tl, - "'%s' isn't in table_list()." % Article._meta.db_table) + self.assertIn(Reporter._meta.db_table, tl, "'%s' isn't in table_list()." % Reporter._meta.db_table) + self.assertIn(Article._meta.db_table, tl, "'%s' isn't in table_list()." % Article._meta.db_table) def test_django_table_names(self): with connection.cursor() as cursor: @@ -48,10 +46,8 @@ class IntrospectionTests(TransactionTestCase): else: raise - self.assertIn('introspection_article_view', - connection.introspection.table_names(include_views=True)) - self.assertNotIn('introspection_article_view', - connection.introspection.table_names()) + self.assertIn('introspection_article_view', connection.introspection.table_names(include_views=True)) + self.assertNotIn('introspection_article_view', connection.introspection.table_names()) def test_unmanaged_through_model(self): tables = connection.introspection.django_table_names() @@ -65,8 +61,7 @@ class IntrospectionTests(TransactionTestCase): def test_sequence_list(self): sequences = connection.introspection.sequence_list() expected = {'table': Reporter._meta.db_table, 'column': 'id'} - self.assertIn(expected, sequences, - 'Reporter sequence not found in sequence_list()') + self.assertIn(expected, sequences, 'Reporter sequence not found in sequence_list()') def test_get_table_description_names(self): with connection.cursor() as cursor: diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py index e5d5406cc4..e4b3105574 100644 --- a/tests/invalid_models_tests/test_models.py +++ b/tests/invalid_models_tests/test_models.py @@ -267,8 +267,7 @@ class FieldNamesTests(SimpleTestCase): max_column_name_length, column_limit_db_alias = get_max_column_name_length() - @unittest.skipIf(max_column_name_length is None, - "The database doesn't have a column name length limit.") + @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.") def test_M2M_long_column_name(self): """ #13711 -- Model check for long M2M column names when database has @@ -333,8 +332,8 @@ class FieldNamesTests(SimpleTestCase): 'Autogenerated column name too long for M2M field "%s". ' 'Maximum length is "%s" for database "%s".' % (m2m_long_name, self.max_column_name_length, self.column_limit_db_alias), - hint=("Use 'through' to create a separate model for " - "M2M and then set column_name using 'db_column'."), + hint="Use 'through' to create a separate model for " + "M2M and then set column_name using 'db_column'.", obj=ModelWithLongField, id='models.E019', ) @@ -350,8 +349,8 @@ class FieldNamesTests(SimpleTestCase): 'Autogenerated column name too long for M2M field "%s_id". ' 'Maximum length is "%s" for database "%s".' % (long_field_name, self.max_column_name_length, self.column_limit_db_alias), - hint=("Use 'through' to create a separate model for " - "M2M and then set column_name using 'db_column'."), + hint="Use 'through' to create a separate model for " + "M2M and then set column_name using 'db_column'.", obj=ModelWithLongField, id='models.E019', ) @@ -359,8 +358,7 @@ class FieldNamesTests(SimpleTestCase): self.assertEqual(errors, expected) - @unittest.skipIf(max_column_name_length is None, - "The database doesn't have a column name length limit.") + @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.") def test_local_field_long_column_name(self): """ #13711 -- Model check for long column names @@ -724,10 +722,8 @@ class OtherModelTests(SimpleTestCase): pass class Group(models.Model): - primary = models.ManyToManyField(Person, - through="Membership", related_name="primary") - secondary = models.ManyToManyField(Person, through="Membership", - related_name="secondary") + primary = models.ManyToManyField(Person, through="Membership", related_name="primary") + secondary = models.ManyToManyField(Person, through="Membership", related_name="secondary") class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) diff --git a/tests/invalid_models_tests/test_relative_fields.py b/tests/invalid_models_tests/test_relative_fields.py index 6a61248eb6..8b95cf3e18 100644 --- a/tests/invalid_models_tests/test_relative_fields.py +++ b/tests/invalid_models_tests/test_relative_fields.py @@ -858,8 +858,7 @@ class AccessorClashTests(SimpleTestCase): pass class Model(models.Model): - children = models.ManyToManyField('Child', - related_name="m2m_clash", related_query_name="no_clash") + children = models.ManyToManyField('Child', related_name="m2m_clash", related_query_name="no_clash") class Parent(models.Model): m2m_clash = models.ManyToManyField('Target') @@ -1013,10 +1012,13 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase): def test_fk_to_integer(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.IntegerField(), - relative=models.ForeignKey('Target', + relative=models.ForeignKey( + 'Target', models.CASCADE, related_name=related_name, - related_query_name='clash')) + related_query_name='clash', + ) + ) def test_hidden_fk_to_integer(self, related_name=None): self.test_fk_to_integer(related_name='+') @@ -1024,10 +1026,13 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase): def test_fk_to_fk(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ForeignKey('Another', models.CASCADE), - relative=models.ForeignKey('Target', + relative=models.ForeignKey( + 'Target', models.CASCADE, related_name=related_name, - related_query_name='clash')) + related_query_name='clash', + ) + ) def test_hidden_fk_to_fk(self): self.test_fk_to_fk(related_name='+') @@ -1035,10 +1040,13 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase): def test_fk_to_m2m(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ManyToManyField('Another'), - relative=models.ForeignKey('Target', + relative=models.ForeignKey( + 'Target', models.CASCADE, related_name=related_name, - related_query_name='clash')) + related_query_name='clash', + ) + ) def test_hidden_fk_to_m2m(self): self.test_fk_to_m2m(related_name='+') @@ -1046,9 +1054,7 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase): def test_m2m_to_integer(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.IntegerField(), - relative=models.ManyToManyField('Target', - related_name=related_name, - related_query_name='clash')) + relative=models.ManyToManyField('Target', related_name=related_name, related_query_name='clash')) def test_hidden_m2m_to_integer(self): self.test_m2m_to_integer(related_name='+') @@ -1056,9 +1062,7 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase): def test_m2m_to_fk(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ForeignKey('Another', models.CASCADE), - relative=models.ManyToManyField('Target', - related_name=related_name, - related_query_name='clash')) + relative=models.ManyToManyField('Target', related_name=related_name, related_query_name='clash')) def test_hidden_m2m_to_fk(self): self.test_m2m_to_fk(related_name='+') @@ -1066,9 +1070,12 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase): def test_m2m_to_m2m(self, related_name=None): self._test_explicit_related_query_name_clash( target=models.ManyToManyField('Another'), - relative=models.ManyToManyField('Target', + relative=models.ManyToManyField( + 'Target', related_name=related_name, - related_query_name='clash')) + related_query_name='clash', + ) + ) def test_hidden_m2m_to_m2m(self): self.test_m2m_to_m2m(related_name='+') diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py index eb90b54430..829a6c893a 100644 --- a/tests/logging_tests/tests.py +++ b/tests/logging_tests/tests.py @@ -223,7 +223,8 @@ class AdminEmailHandlerTest(SimpleTestCase): admin_email_handler.filters = [] rf = RequestFactory() request = rf.get('/') - self.logger.error(message, token1, token2, + self.logger.error( + message, token1, token2, extra={ 'status_code': 403, 'request': request, diff --git a/tests/m2m_through_regress/tests.py b/tests/m2m_through_regress/tests.py index 4eaa4431b6..26e20fc97d 100644 --- a/tests/m2m_through_regress/tests.py +++ b/tests/m2m_through_regress/tests.py @@ -128,8 +128,7 @@ class M2MThroughSerializationTestCase(TestCase): ) out = StringIO() - management.call_command("dumpdata", "m2m_through_regress", format="xml", - indent=2, stdout=out) + management.call_command("dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out) self.assertXMLEqual(out.getvalue().strip(), """ diff --git a/tests/mail/tests.py b/tests/mail/tests.py index fe564ad765..36e3e3399e 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -31,8 +31,10 @@ if PY3: from email import message_from_bytes, message_from_binary_file else: from email.Utils import parseaddr - from email import (message_from_string as message_from_bytes, - message_from_file as message_from_binary_file) + from email import ( + message_from_string as message_from_bytes, + message_from_file as message_from_binary_file, + ) class HeadersCheckMixin(object): @@ -613,9 +615,10 @@ class BaseEmailBackendTests(HeadersCheckMixin, object): def get_the_message(self): mailbox = self.get_mailbox_content() - self.assertEqual(len(mailbox), 1, - "Expected exactly one message, got %d.\n%r" % (len(mailbox), [ - m.as_string() for m in mailbox])) + self.assertEqual( + len(mailbox), 1, + "Expected exactly one message, got %d.\n%r" % (len(mailbox), [m.as_string() for m in mailbox]) + ) return mailbox[0] def test_send(self): @@ -769,8 +772,7 @@ class BaseEmailBackendTests(HeadersCheckMixin, object): self.assertEqual(message.get('to'), 'to@xn--4ca9at.com') self.flush_mailbox() - m = EmailMessage('Subject', 'Content', 'from@öäü.com', - ['to@öäü.com'], cc=['cc@öäü.com']) + m = EmailMessage('Subject', 'Content', 'from@öäü.com', ['to@öäü.com'], cc=['cc@öäü.com']) m.send() message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') diff --git a/tests/many_to_one_null/tests.py b/tests/many_to_one_null/tests.py index 1a3785bd33..fbcfd682dc 100644 --- a/tests/many_to_one_null/tests.py +++ b/tests/many_to_one_null/tests.py @@ -34,10 +34,8 @@ class ManyToOneNullTests(TestCase): def test_related_set(self): # Reporter objects have access to their related Article objects. - self.assertQuerysetEqual(self.r.article_set.all(), - ['', '']) - self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='Fir'), - ['']) + self.assertQuerysetEqual(self.r.article_set.all(), ['', '']) + self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='Fir'), ['']) self.assertEqual(self.r.article_set.count(), 2) def test_created_without_related(self): @@ -50,24 +48,21 @@ class ManyToOneNullTests(TestCase): # if the reporter is set to None. self.assertEqual(a3.reporter, None) # To retrieve the articles with no reporters set, use "reporter__isnull=True". - self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), - ['']) + self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['']) # We can achieve the same thing by filtering for the case where the # reporter is None. - self.assertQuerysetEqual(Article.objects.filter(reporter=None), - ['']) + self.assertQuerysetEqual(Article.objects.filter(reporter=None), ['']) # Set the reporter for the Third article - self.assertQuerysetEqual(self.r.article_set.all(), - ['', '']) + self.assertQuerysetEqual(self.r.article_set.all(), ['', '']) self.r.article_set.add(a3) - self.assertQuerysetEqual(self.r.article_set.all(), - ['', '', '']) + self.assertQuerysetEqual( + self.r.article_set.all(), + ['', '', ''] + ) # Remove an article from the set, and check that it was removed. self.r.article_set.remove(a3) - self.assertQuerysetEqual(self.r.article_set.all(), - ['', '']) - self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), - ['']) + self.assertQuerysetEqual(self.r.article_set.all(), ['', '']) + self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['']) def test_remove_from_wrong_set(self): self.assertQuerysetEqual(self.r2.article_set.all(), ['']) @@ -80,30 +75,31 @@ class ManyToOneNullTests(TestCase): # Use manager.set() to allocate ForeignKey. Null is legal, so existing # members of the set that are not in the assignment set are set to null. self.r2.article_set.set([self.a2, self.a3]) - self.assertQuerysetEqual(self.r2.article_set.all(), - ['', '']) + self.assertQuerysetEqual(self.r2.article_set.all(), ['', '']) # Use manager.set(clear=True) self.r2.article_set.set([self.a3, self.a4], clear=True) - self.assertQuerysetEqual(self.r2.article_set.all(), - ['', '']) + self.assertQuerysetEqual(self.r2.article_set.all(), ['', '']) # Clear the rest of the set self.r2.article_set.set([]) self.assertQuerysetEqual(self.r2.article_set.all(), []) - self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), - ['', '', '']) + self.assertQuerysetEqual( + Article.objects.filter(reporter__isnull=True), + ['', '', ''] + ) def test_assign_clear_related_set(self): # Use descriptor assignment to allocate ForeignKey. Null is legal, so # existing members of the set that are not in the assignment set are # set to null. self.r2.article_set.set([self.a2, self.a3]) - self.assertQuerysetEqual(self.r2.article_set.all(), - ['', '']) + self.assertQuerysetEqual(self.r2.article_set.all(), ['', '']) # Clear the rest of the set self.r.article_set.clear() self.assertQuerysetEqual(self.r.article_set.all(), []) - self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), - ['', '']) + self.assertQuerysetEqual( + Article.objects.filter(reporter__isnull=True), + ['', ''] + ) def test_assign_with_queryset(self): # Ensure that querysets used in reverse FK assignments are pre-evaluated diff --git a/tests/messages_tests/base.py b/tests/messages_tests/base.py index 57c4137e62..3284522edf 100644 --- a/tests/messages_tests/base.py +++ b/tests/messages_tests/base.py @@ -353,18 +353,14 @@ class BaseTests(object): storage.level = 0 add_level_messages(storage) tags = [msg.tags for msg in storage] - self.assertEqual(tags, - ['info', '', 'extra-tag debug', 'warning', 'error', - 'success']) + self.assertEqual(tags, ['info', '', 'extra-tag debug', 'warning', 'error', 'success']) def test_level_tag(self): storage = self.get_storage() storage.level = 0 add_level_messages(storage) tags = [msg.level_tag for msg in storage] - self.assertEqual(tags, - ['info', '', 'debug', 'warning', 'error', - 'success']) + self.assertEqual(tags, ['info', '', 'debug', 'warning', 'error', 'success']) @override_settings_tags(MESSAGE_TAGS={ constants.INFO: 'info', @@ -379,5 +375,4 @@ class BaseTests(object): storage.level = 0 add_level_messages(storage) tags = [msg.tags for msg in storage] - self.assertEqual(tags, - ['info', 'custom', 'extra-tag', '', 'bad', 'success']) + self.assertEqual(tags, ['info', 'custom', 'extra-tag', '', 'bad', 'success']) diff --git a/tests/messages_tests/test_cookie.py b/tests/messages_tests/test_cookie.py index c70e253d7d..dfaf2f301c 100644 --- a/tests/messages_tests/test_cookie.py +++ b/tests/messages_tests/test_cookie.py @@ -127,9 +127,9 @@ class CookieTest(BaseTests, SimpleTestCase): messages = [ { 'message': Message(constants.INFO, 'Test message'), - 'message_list': [Message(constants.INFO, 'message %s') - for x in range(5)] + [{'another-message': - Message(constants.ERROR, 'error')}], + 'message_list': [ + Message(constants.INFO, 'message %s') for x in range(5) + ] + [{'another-message': Message(constants.ERROR, 'error')}], }, Message(constants.INFO, 'message %s'), ] diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index d0e4cf349e..2f88f94780 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -776,13 +776,17 @@ class ETagGZipMiddlewareTest(SimpleTestCase): ETag is changed after gzip compression is performed. """ request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate') - response = GZipMiddleware().process_response(request, - CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))) + response = GZipMiddleware().process_response( + request, + CommonMiddleware().process_response(request, HttpResponse(self.compressible_string)) + ) gzip_etag = response.get('ETag') request = self.rf.get('/', HTTP_ACCEPT_ENCODING='') - response = GZipMiddleware().process_response(request, - CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))) + response = GZipMiddleware().process_response( + request, + CommonMiddleware().process_response(request, HttpResponse(self.compressible_string)) + ) nogzip_etag = response.get('ETag') self.assertNotEqual(gzip_etag, nogzip_etag) diff --git a/tests/migrate_signals/tests.py b/tests/migrate_signals/tests.py index 2e729fec41..cdfffe5de7 100644 --- a/tests/migrate_signals/tests.py +++ b/tests/migrate_signals/tests.py @@ -63,9 +63,10 @@ class MigrateSignalTests(TestCase): def test_pre_migrate_args(self): r = PreMigrateReceiver() signals.pre_migrate.connect(r, sender=APP_CONFIG) - management.call_command('migrate', database=MIGRATE_DATABASE, - verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, - stdout=six.StringIO()) + management.call_command( + 'migrate', database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY, + interactive=MIGRATE_INTERACTIVE, stdout=six.StringIO(), + ) args = r.call_args self.assertEqual(r.call_counter, 1) @@ -83,9 +84,10 @@ class MigrateSignalTests(TestCase): r = PreMigrateReceiver() signals.pre_migrate.connect(r, sender=APP_CONFIG) stdout = six.StringIO() - management.call_command('migrate', database=MIGRATE_DATABASE, - verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, - stdout=stdout) + management.call_command( + 'migrate', database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY, + interactive=MIGRATE_INTERACTIVE, stdout=stdout, + ) args = r.call_args self.assertEqual(r.call_counter, 1) self.assertEqual(set(args), set(PRE_MIGRATE_ARGS)) diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py index fd34414ab7..ba9b4c8caa 100644 --- a/tests/migrations/test_autodetector.py +++ b/tests/migrations/test_autodetector.py @@ -1290,8 +1290,7 @@ class AutodetectorTests(TestCase): # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) - self.assertOperationAttributes(changes, 'testapp', 0, 0, - name="AuthorUnmanaged", options={"managed": False}) + self.assertOperationAttributes(changes, 'testapp', 0, 0, name="AuthorUnmanaged", options={"managed": False}) def test_unmanaged_to_managed(self): # Now, we test turning an unmanaged model into a managed model @@ -1302,8 +1301,7 @@ class AutodetectorTests(TestCase): # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelOptions"]) - self.assertOperationAttributes(changes, 'testapp', 0, 0, - name="authorunmanaged", options={}) + self.assertOperationAttributes(changes, 'testapp', 0, 0, name="authorunmanaged", options={}) def test_managed_to_unmanaged(self): # Now, we turn managed to unmanaged. @@ -1314,8 +1312,7 @@ class AutodetectorTests(TestCase): # Right number/type of migrations? self.assertNumberMigrations(changes, 'testapp', 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) - self.assertOperationAttributes(changes, "testapp", 0, 0, - name="authorunmanaged", options={"managed": False}) + self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False}) def test_unmanaged_custom_pk(self): """ diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 88aff5d021..9838ccf74f 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -338,16 +338,26 @@ class MigrateTests(MigrationTestBase): index_tx_end = output.find(connection.ops.end_transaction_sql().lower()) self.assertGreater(index_tx_start, -1, "Transaction start not found") - self.assertGreater(index_op_desc_author, index_tx_start, - "Operation description (author) not found or found before transaction start") - self.assertGreater(index_create_table, index_op_desc_author, - "CREATE TABLE not found or found before operation description (author)") - self.assertGreater(index_op_desc_tribble, index_create_table, - "Operation description (tribble) not found or found before CREATE TABLE (author)") - self.assertGreater(index_op_desc_unique_together, index_op_desc_tribble, - "Operation description (unique_together) not found or found before operation description (tribble)") - self.assertGreater(index_tx_end, index_op_desc_unique_together, - "Transaction end not found or found before operation description (unique_together)") + self.assertGreater( + index_op_desc_author, index_tx_start, + "Operation description (author) not found or found before transaction start" + ) + self.assertGreater( + index_create_table, index_op_desc_author, + "CREATE TABLE not found or found before operation description (author)" + ) + self.assertGreater( + index_op_desc_tribble, index_create_table, + "Operation description (tribble) not found or found before CREATE TABLE (author)" + ) + self.assertGreater( + index_op_desc_unique_together, index_op_desc_tribble, + "Operation description (unique_together) not found or found before operation description (tribble)" + ) + self.assertGreater( + index_tx_end, index_op_desc_unique_together, + "Transaction end not found or found before operation description (unique_together)" + ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_sqlmigrate_backwards(self): @@ -369,17 +379,27 @@ class MigrateTests(MigrationTestBase): index_tx_end = output.find(connection.ops.end_transaction_sql().lower()) self.assertGreater(index_tx_start, -1, "Transaction start not found") - self.assertGreater(index_op_desc_unique_together, index_tx_start, - "Operation description (unique_together) not found or found before transaction start") - self.assertGreater(index_op_desc_tribble, index_op_desc_unique_together, - "Operation description (tribble) not found or found before operation description (unique_together)") - self.assertGreater(index_op_desc_author, index_op_desc_tribble, - "Operation description (author) not found or found before operation description (tribble)") + self.assertGreater( + index_op_desc_unique_together, index_tx_start, + "Operation description (unique_together) not found or found before transaction start" + ) + self.assertGreater( + index_op_desc_tribble, index_op_desc_unique_together, + "Operation description (tribble) not found or found before operation description (unique_together)" + ) + self.assertGreater( + index_op_desc_author, index_op_desc_tribble, + "Operation description (author) not found or found before operation description (tribble)" + ) - self.assertGreater(index_drop_table, index_op_desc_author, - "DROP TABLE not found or found before operation description (author)") - self.assertGreater(index_tx_end, index_op_desc_unique_together, - "Transaction end not found or found before DROP TABLE") + self.assertGreater( + index_drop_table, index_op_desc_author, + "DROP TABLE not found or found before operation description (author)" + ) + self.assertGreater( + index_tx_end, index_op_desc_unique_together, + "Transaction end not found or found before DROP TABLE" + ) # Cleanup by unmigrating everything call_command("migrate", "migrations", "zero", verbosity=0) diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py index cde814aab5..1c6711bc8a 100644 --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -46,7 +46,8 @@ class OperationTestBase(MigrationTestBase): operation.state_forwards(app_label, new_state) return project_state, new_state - def set_up_test_model(self, app_label, second_model=False, third_model=False, + def set_up_test_model( + self, app_label, second_model=False, third_model=False, related_model=False, mti_model=False, proxy_model=False, manager_model=False, unique_together=False, options=False, db_table=None, index_together=False): """ diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py index ce12c5b96d..531ec2e131 100644 --- a/tests/migrations/test_state.py +++ b/tests/migrations/test_state.py @@ -817,23 +817,26 @@ class ModelStateTests(SimpleTestCase): def test_bound_field_sanity_check(self): field = models.CharField(max_length=1) field.model = models.Model - with self.assertRaisesMessage(ValueError, - 'ModelState.fields cannot be bound to a model - "field" is.'): + with self.assertRaisesMessage(ValueError, 'ModelState.fields cannot be bound to a model - "field" is.'): ModelState('app', 'Model', [('field', field)]) def test_sanity_check_to(self): field = models.ForeignKey(UnicodeModel, models.CASCADE) - with self.assertRaisesMessage(ValueError, - 'ModelState.fields cannot refer to a model class - "field.to" does. ' - 'Use a string reference instead.'): + with self.assertRaisesMessage( + ValueError, + 'ModelState.fields cannot refer to a model class - "field.to" does. ' + 'Use a string reference instead.' + ): ModelState('app', 'Model', [('field', field)]) def test_sanity_check_through(self): field = models.ManyToManyField('UnicodeModel') field.remote_field.through = UnicodeModel - with self.assertRaisesMessage(ValueError, - 'ModelState.fields cannot refer to a model class - "field.through" does. ' - 'Use a string reference instead.'): + with self.assertRaisesMessage( + ValueError, + 'ModelState.fields cannot refer to a model class - "field.through" does. ' + 'Use a string reference instead.' + ): ModelState('app', 'Model', [('field', field)]) def test_fields_immutability(self): diff --git a/tests/model_fields/test_field_flags.py b/tests/model_fields/test_field_flags.py index f86be8f45a..33f49a139d 100644 --- a/tests/model_fields/test_field_flags.py +++ b/tests/model_fields/test_field_flags.py @@ -103,8 +103,7 @@ class FieldFlagsTests(test.SimpleTestCase): def test_each_object_should_have_auto_created(self): self.assertTrue( - all(f.auto_created.__class__ == bool - for f in self.fields_and_reverse_objects) + all(f.auto_created.__class__ == bool for f in self.fields_and_reverse_objects) ) def test_non_concrete_fields(self): diff --git a/tests/model_fields/test_imagefield.py b/tests/model_fields/test_imagefield.py index ada8e12e3b..a27476ff8d 100644 --- a/tests/model_fields/test_imagefield.py +++ b/tests/model_fields/test_imagefield.py @@ -17,8 +17,10 @@ except ImproperlyConfigured: Image = None if Image: - from .models import (Person, PersonWithHeight, PersonWithHeightAndWidth, - PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile) + from .models import ( + Person, PersonWithHeight, PersonWithHeightAndWidth, + PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile, + ) from .models import temp_storage_dir else: # Pillow not available, create dummy classes (tests will be skipped anyway) diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py index 4688720ac0..2c3ff26cbe 100644 --- a/tests/model_forms/models.py +++ b/tests/model_forms/models.py @@ -388,13 +388,16 @@ class ColourfulItem(models.Model): class CustomErrorMessage(models.Model): - name1 = models.CharField(max_length=50, + name1 = models.CharField( + max_length=50, validators=[validators.validate_slug], - error_messages={'invalid': 'Model custom error message.'}) - - name2 = models.CharField(max_length=50, + error_messages={'invalid': 'Model custom error message.'}, + ) + name2 = models.CharField( + max_length=50, validators=[validators.validate_slug], - error_messages={'invalid': 'Model custom error message.'}) + error_messages={'invalid': 'Model custom error message.'}, + ) def clean(self): if self.name1 == 'FORBIDDEN_VALUE': diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index 873699f921..289c03416d 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -328,8 +328,7 @@ class ModelFormBaseTest(TestCase): model = Category fields = '__all__' - self.assertIsInstance(ReplaceField.base_fields['url'], - forms.fields.BooleanField) + self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_2(self): # Should have the same result as before, @@ -341,8 +340,7 @@ class ModelFormBaseTest(TestCase): model = Category fields = ['url'] - self.assertIsInstance(ReplaceField.base_fields['url'], - forms.fields.BooleanField) + self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_3(self): # Should have the same result as before, @@ -354,8 +352,7 @@ class ModelFormBaseTest(TestCase): model = Category fields = [] # url will still appear, since it is explicit above - self.assertIsInstance(ReplaceField.base_fields['url'], - forms.fields.BooleanField) + self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_override_field(self): class WriterForm(forms.ModelForm): @@ -390,8 +387,7 @@ class ModelFormBaseTest(TestCase): model = Category exclude = ['url'] - self.assertEqual(list(ExcludeFields.base_fields), - ['name', 'slug']) + self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug']) def test_exclude_nonexistent_field(self): class ExcludeFields(forms.ModelForm): @@ -399,8 +395,7 @@ class ModelFormBaseTest(TestCase): model = Category exclude = ['nonexistent'] - self.assertEqual(list(ExcludeFields.base_fields), - ['name', 'slug', 'url']) + self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug', 'url']) def test_exclude_fields_with_string(self): expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?" @@ -811,8 +806,10 @@ class UniqueTest(TestCase): self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) def test_unique_for_date(self): - p = Post.objects.create(title="Django 1.0 is released", - slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) + p = Post.objects.create( + title="Django 1.0 is released", slug="Django 1.0", + subtitle="Finally", posted=datetime.date(2008, 9, 3), + ) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) @@ -828,8 +825,8 @@ class UniqueTest(TestCase): form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) - form = PostForm({'subtitle': "Finally", "title": "Django 1.0 is released", - "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) + data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} + form = PostForm(data, instance=p) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released"}) self.assertFalse(form.is_valid()) @@ -847,9 +844,10 @@ class UniqueTest(TestCase): model = DateTimePost fields = '__all__' - DateTimePost.objects.create(title="Django 1.0 is released", - slug="Django 1.0", subtitle="Finally", - posted=datetime.datetime(2008, 9, 3, 10, 10, 1)) + DateTimePost.objects.create( + title="Django 1.0 is released", slug="Django 1.0", + subtitle="Finally", posted=datetime.datetime(2008, 9, 3, 10, 10, 1), + ) # 'title' has unique_for_date='posted' form = DateTimePostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) @@ -861,8 +859,10 @@ class UniqueTest(TestCase): self.assertTrue(form.is_valid()) def test_inherited_unique_for_date(self): - p = Post.objects.create(title="Django 1.0 is released", - slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) + p = Post.objects.create( + title="Django 1.0 is released", slug="Django 1.0", + subtitle="Finally", posted=datetime.date(2008, 9, 3), + ) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) @@ -878,8 +878,8 @@ class UniqueTest(TestCase): form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) - form = DerivedPostForm({'subtitle': "Finally", "title": "Django 1.0 is released", - "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) + data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} + form = DerivedPostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_unique_for_date_with_nullable_date(self): @@ -888,8 +888,10 @@ class UniqueTest(TestCase): model = FlexibleDatePost fields = '__all__' - p = FlexibleDatePost.objects.create(title="Django 1.0 is released", - slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) + p = FlexibleDatePost.objects.create( + title="Django 1.0 is released", slug="Django 1.0", + subtitle="Finally", posted=datetime.date(2008, 9, 3), + ) form = FlexDatePostForm({'title': "Django 1.0 is released"}) self.assertTrue(form.is_valid()) @@ -897,8 +899,8 @@ class UniqueTest(TestCase): self.assertTrue(form.is_valid()) form = FlexDatePostForm({'subtitle': "Finally"}) self.assertTrue(form.is_valid()) - form = FlexDatePostForm({'subtitle': "Finally", "title": "Django 1.0 is released", - "slug": "Django 1.0"}, instance=p) + data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0"} + form = FlexDatePostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_override_unique_message(self): @@ -941,8 +943,10 @@ class UniqueTest(TestCase): } } - Post.objects.create(title="Django 1.0 is released", - slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) + Post.objects.create( + title="Django 1.0 is released", slug="Django 1.0", + subtitle="Finally", posted=datetime.date(2008, 9, 3), + ) form = CustomPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ["Post's Title not unique for Posted date."]) @@ -1343,8 +1347,7 @@ class ModelFormBasicTests(TestCase): new_art = f.save() new_art = Article.objects.get(id=new_art.id) art_id_1 = new_art.id - self.assertQuerysetEqual(new_art.categories.order_by('name'), - ["Entertainment", "It's a test"]) + self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) # Now, submit form data with no categories. This deletes the existing categories. form_data['categories'] = [] @@ -1379,8 +1382,7 @@ class ModelFormBasicTests(TestCase): # Save the m2m data on the form f.save_m2m() - self.assertQuerysetEqual(new_art.categories.order_by('name'), - ["Entertainment", "It's a test"]) + self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) def test_custom_form_fields(self): # Here, we define a custom ModelForm. Because it happens to have the same fields as @@ -1594,12 +1596,18 @@ class ModelMultipleChoiceFieldTests(TestCase): self.assertQuerysetEqual(f.clean([self.c1.id]), ["Entertainment"]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) self.assertQuerysetEqual(f.clean([str(self.c1.id)]), ["Entertainment"]) - self.assertQuerysetEqual(f.clean([str(self.c1.id), str(self.c2.id)]), - ["Entertainment", "It's a test"], ordered=False) - self.assertQuerysetEqual(f.clean([self.c1.id, str(self.c2.id)]), - ["Entertainment", "It's a test"], ordered=False) - self.assertQuerysetEqual(f.clean((self.c1.id, str(self.c2.id))), - ["Entertainment", "It's a test"], ordered=False) + self.assertQuerysetEqual( + f.clean([str(self.c1.id), str(self.c2.id)]), + ["Entertainment", "It's a test"], ordered=False + ) + self.assertQuerysetEqual( + f.clean([self.c1.id, str(self.c2.id)]), + ["Entertainment", "It's a test"], ordered=False + ) + self.assertQuerysetEqual( + f.clean((self.c1.id, str(self.c2.id))), + ["Entertainment", "It's a test"], ordered=False + ) with self.assertRaises(ValidationError): f.clean(['100']) with self.assertRaises(ValidationError): @@ -1827,8 +1835,7 @@ class ModelOneToOneFieldTests(TestCase): model = Author fields = ['publication', 'full_name'] - publication = Publication.objects.create(title="Pravda", - date_published=datetime.date(1991, 8, 22)) + publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertTrue(form.is_valid()) @@ -1845,8 +1852,7 @@ class ModelOneToOneFieldTests(TestCase): model = Author1 fields = ['publication', 'full_name'] - publication = Publication.objects.create(title="Pravda", - date_published=datetime.date(1991, 8, 22)) + publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author1.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertFalse(form.is_valid()) diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py index cb93b2fce3..4e909e5f5b 100644 --- a/tests/model_formsets/tests.py +++ b/tests/model_formsets/tests.py @@ -1506,8 +1506,7 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data) self.assertFalse(formset.is_valid()) - self.assertEqual(formset._non_form_errors, - ['Please correct the duplicate data for slug.']) + self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for slug.']) FormSet = modelformset_factory(Price, fields="__all__", extra=2) data = { @@ -1521,8 +1520,10 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data) self.assertFalse(formset.is_valid()) - self.assertEqual(formset._non_form_errors, - ['Please correct the duplicate data for price and quantity, which must be unique.']) + self.assertEqual( + formset._non_form_errors, + ['Please correct the duplicate data for price and quantity, which must be unique.'] + ) # Only the price field is specified, this should skip any unique checks since # the unique_together is not fulfilled. This will fail with a KeyError if broken. @@ -1559,10 +1560,8 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data=data, instance=author) self.assertFalse(formset.is_valid()) - self.assertEqual(formset._non_form_errors, - ['Please correct the duplicate data for title.']) - self.assertEqual(formset.errors, - [{}, {'__all__': ['Please correct the duplicate values below.']}]) + self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for title.']) + self.assertEqual(formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}]) FormSet = modelformset_factory(Post, fields="__all__", extra=2) data = { @@ -1581,10 +1580,14 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data) self.assertFalse(formset.is_valid()) - self.assertEqual(formset._non_form_errors, - ['Please correct the duplicate data for title which must be unique for the date in posted.']) - self.assertEqual(formset.errors, - [{}, {'__all__': ['Please correct the duplicate values below.']}]) + self.assertEqual( + formset._non_form_errors, + ['Please correct the duplicate data for title which must be unique for the date in posted.'] + ) + self.assertEqual( + formset.errors, + [{}, {'__all__': ['Please correct the duplicate values below.']}] + ) data = { 'form-TOTAL_FORMS': '2', @@ -1602,8 +1605,10 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data) self.assertFalse(formset.is_valid()) - self.assertEqual(formset._non_form_errors, - ['Please correct the duplicate data for slug which must be unique for the year in posted.']) + self.assertEqual( + formset._non_form_errors, + ['Please correct the duplicate data for slug which must be unique for the year in posted.'] + ) data = { 'form-TOTAL_FORMS': '2', @@ -1621,8 +1626,10 @@ class ModelFormsetTest(TestCase): } formset = FormSet(data) self.assertFalse(formset.is_valid()) - self.assertEqual(formset._non_form_errors, - ['Please correct the duplicate data for subtitle which must be unique for the month in posted.']) + self.assertEqual( + formset._non_form_errors, + ['Please correct the duplicate data for subtitle which must be unique for the month in posted.'] + ) class TestModelFormsetOverridesTroughFormMeta(TestCase): diff --git a/tests/model_inheritance/tests.py b/tests/model_inheritance/tests.py index 72079a50f8..d47ad08680 100644 --- a/tests/model_inheritance/tests.py +++ b/tests/model_inheritance/tests.py @@ -336,10 +336,8 @@ class ModelInheritanceDataTests(TestCase): #23370 - Should be able to defer child fields when using select_related() from parent to child. """ - qs = (Restaurant.objects - .select_related("italianrestaurant") - .defer("italianrestaurant__serves_gnocchi") - .order_by("rating")) + qs = (Restaurant.objects.select_related("italianrestaurant") + .defer("italianrestaurant__serves_gnocchi").order_by("rating")) # Test that the field was actually deferred with self.assertNumQueries(2): diff --git a/tests/model_options/test_tablespaces.py b/tests/model_options/test_tablespaces.py index e8372e1bc7..2d4b9073e8 100644 --- a/tests/model_options/test_tablespaces.py +++ b/tests/model_options/test_tablespaces.py @@ -43,8 +43,7 @@ class TablespacesTests(TestCase): def assertNumContains(self, haystack, needle, count): real_count = haystack.count(needle) - self.assertEqual(real_count, count, "Found %d instances of '%s', " - "expected %d" % (real_count, needle, count)) + self.assertEqual(real_count, count, "Found %d instances of '%s', expected %d" % (real_count, needle, count)) @skipUnlessDBFeature('supports_tablespaces') def test_tablespace_for_model(self): diff --git a/tests/modeladmin/models.py b/tests/modeladmin/models.py index 54291354bc..2c2a910892 100644 --- a/tests/modeladmin/models.py +++ b/tests/modeladmin/models.py @@ -19,8 +19,7 @@ class Band(models.Model): class Concert(models.Model): main_band = models.ForeignKey(Band, models.CASCADE, related_name='main_concerts') - opening_band = models.ForeignKey(Band, models.CASCADE, related_name='opening_concerts', - blank=True) + opening_band = models.ForeignKey(Band, models.CASCADE, related_name='opening_concerts', blank=True) day = models.CharField(max_length=3, choices=((1, 'Fri'), (2, 'Sat'))) transport = models.CharField(max_length=100, choices=( (1, 'Plane'), diff --git a/tests/modeladmin/tests.py b/tests/modeladmin/tests.py index 790d24f66d..0de3fb5925 100644 --- a/tests/modeladmin/tests.py +++ b/tests/modeladmin/tests.py @@ -47,14 +47,9 @@ class ModelAdminTests(TestCase): def test_default_fields(self): ma = ModelAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['name', 'bio', 'sign_date']) - - self.assertEqual(list(ma.get_fields(request)), - ['name', 'bio', 'sign_date']) - - self.assertEqual(list(ma.get_fields(request, self.band)), - ['name', 'bio', 'sign_date']) + self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date']) + self.assertEqual(list(ma.get_fields(request)), ['name', 'bio', 'sign_date']) + self.assertEqual(list(ma.get_fields(request, self.band)), ['name', 'bio', 'sign_date']) def test_default_fieldsets(self): # fieldsets_add and fieldsets_change should return a special data structure that @@ -64,11 +59,9 @@ class ModelAdminTests(TestCase): # Here's the default case. There are no custom form_add/form_change methods, # no fields argument, and no fieldsets argument. ma = ModelAdmin(Band, self.site) - self.assertEqual(ma.get_fieldsets(request), - [(None, {'fields': ['name', 'bio', 'sign_date']})]) + self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name', 'bio', 'sign_date']})]) - self.assertEqual(ma.get_fieldsets(request, self.band), - [(None, {'fields': ['name', 'bio', 'sign_date']})]) + self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name', 'bio', 'sign_date']})]) def test_get_fieldsets(self): # Test that get_fieldsets is called when figuring out form fields. @@ -115,14 +108,9 @@ class ModelAdminTests(TestCase): ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_fields(request)), ['name']) - self.assertEqual(list(ma.get_fields(request, self.band)), ['name']) - - self.assertEqual(ma.get_fieldsets(request), - [(None, {'fields': ['name']})]) - - self.assertEqual(ma.get_fieldsets(request, self.band), - [(None, {'fields': ['name']})]) + self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name']})]) + self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name']})]) def test_field_arguments_restricted_on_form(self): # If we specify fields or fieldsets, it should exclude fields on the Form class @@ -137,8 +125,7 @@ class ModelAdminTests(TestCase): ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) - self.assertEqual(list(ma.get_form(request, self.band).base_fields), - ['name']) + self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name']) # Using `fieldsets`. class BandAdmin(ModelAdmin): @@ -146,24 +133,21 @@ class ModelAdminTests(TestCase): ma = BandAdmin(Band, self.site) self.assertEqual(list(ma.get_form(request).base_fields), ['name']) - self.assertEqual(list(ma.get_form(request, self.band).base_fields), - ['name']) + self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name']) # Using `exclude`. class BandAdmin(ModelAdmin): exclude = ['bio'] ma = BandAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['name', 'sign_date']) + self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) # You can also pass a tuple to `exclude`. class BandAdmin(ModelAdmin): exclude = ('bio',) ma = BandAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['name', 'sign_date']) + self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) # Using `fields` and `exclude`. class BandAdmin(ModelAdmin): @@ -171,8 +155,7 @@ class ModelAdminTests(TestCase): exclude = ['bio'] ma = BandAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['name']) + self.assertEqual(list(ma.get_form(request).base_fields), ['name']) def test_custom_form_meta_exclude_with_readonly(self): """ @@ -184,7 +167,6 @@ class ModelAdminTests(TestCase): # First, with `ModelAdmin` ----------------------- class AdminBandForm(forms.ModelForm): - class Meta: model = Band exclude = ['bio'] @@ -194,13 +176,11 @@ class ModelAdminTests(TestCase): form = AdminBandForm ma = BandAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['sign_date']) + self.assertEqual(list(ma.get_form(request).base_fields), ['sign_date']) # Then, with `InlineModelAdmin` ----------------- class AdminConcertForm(forms.ModelForm): - class Meta: model = Concert exclude = ['day'] @@ -261,7 +241,6 @@ class ModelAdminTests(TestCase): # First, with `ModelAdmin` ----------------------- class AdminBandForm(forms.ModelForm): - class Meta: model = Band exclude = ['bio'] @@ -271,8 +250,7 @@ class ModelAdminTests(TestCase): form = AdminBandForm ma = BandAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['bio', 'sign_date']) + self.assertEqual(list(ma.get_form(request).base_fields), ['bio', 'sign_date']) # Then, with `InlineModelAdmin` ----------------- @@ -296,7 +274,8 @@ class ModelAdminTests(TestCase): ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), - ['main_band', 'opening_band', 'day', 'id', 'DELETE']) + ['main_band', 'opening_band', 'day', 'id', 'DELETE'] + ) def test_custom_form_validation(self): # If we specify a form, it should use it allowing custom validation to work @@ -309,12 +288,8 @@ class ModelAdminTests(TestCase): form = AdminBandForm ma = BandAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['name', 'bio', 'sign_date', 'delete']) - - self.assertEqual( - type(ma.get_form(request).base_fields['sign_date'].widget), - AdminDateWidget) + self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date', 'delete']) + self.assertEqual(type(ma.get_form(request).base_fields['sign_date'].widget), AdminDateWidget) def test_form_exclude_kwarg_override(self): """ @@ -323,7 +298,6 @@ class ModelAdminTests(TestCase): """ class AdminBandForm(forms.ModelForm): - class Meta: model = Band exclude = ['name'] @@ -337,8 +311,7 @@ class ModelAdminTests(TestCase): return super(BandAdmin, self).get_form(request, obj, **kwargs) ma = BandAdmin(Band, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['name', 'sign_date']) + self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date']) def test_formset_exclude_kwarg_override(self): """ @@ -347,7 +320,6 @@ class ModelAdminTests(TestCase): """ class AdminConcertForm(forms.ModelForm): - class Meta: model = Concert exclude = ['day'] @@ -384,13 +356,15 @@ class ModelAdminTests(TestCase): ma = ConcertAdmin(Concert, self.site) form = ma.get_form(request)() - self.assertHTMLEqual(str(form["main_band"]), + self.assertHTMLEqual( + str(form["main_band"]), '' % (band2.id, self.band.id)) + '
    ' % (band2.id, self.band.id) + ) class AdminConcertForm(forms.ModelForm): def __init__(self, *args, **kwargs): @@ -403,12 +377,14 @@ class ModelAdminTests(TestCase): ma = ConcertAdminWithForm(Concert, self.site) form = ma.get_form(request)() - self.assertHTMLEqual(str(form["main_band"]), + self.assertHTMLEqual( + str(form["main_band"]), '' % self.band.id) + '
    ' % self.band.id + ) def test_regression_for_ticket_15820(self): """ @@ -455,24 +431,22 @@ class ModelAdminTests(TestCase): cma = ModelAdmin(Concert, self.site) cmafa = cma.get_form(request) - self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), - Select) + self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), Select) self.assertEqual( list(cmafa.base_fields['main_band'].widget.choices), [('', '---------'), (self.band.id, 'The Doors')]) - self.assertEqual( - type(cmafa.base_fields['opening_band'].widget.widget), Select) + self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), Select) self.assertEqual( list(cmafa.base_fields['opening_band'].widget.choices), - [('', '---------'), (self.band.id, 'The Doors')]) - + [('', '---------'), (self.band.id, 'The Doors')] + ) self.assertEqual(type(cmafa.base_fields['day'].widget), Select) - self.assertEqual(list(cmafa.base_fields['day'].widget.choices), - [('', '---------'), (1, 'Fri'), (2, 'Sat')]) - - self.assertEqual(type(cmafa.base_fields['transport'].widget), - Select) + self.assertEqual( + list(cmafa.base_fields['day'].widget.choices), + [('', '---------'), (1, 'Fri'), (2, 'Sat')] + ) + self.assertEqual(type(cmafa.base_fields['transport'].widget), Select) self.assertEqual( list(cmafa.base_fields['transport'].widget.choices), [('', '---------'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]) @@ -494,35 +468,29 @@ class ModelAdminTests(TestCase): cma = ConcertAdmin(Concert, self.site) cmafa = cma.get_form(request) - self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), - AdminRadioSelect) - self.assertEqual(cmafa.base_fields['main_band'].widget.attrs, - {'class': 'radiolist inline'}) - self.assertEqual(list(cmafa.base_fields['main_band'].widget.choices), - [(self.band.id, 'The Doors')]) - + self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), AdminRadioSelect) + self.assertEqual(cmafa.base_fields['main_band'].widget.attrs, {'class': 'radiolist inline'}) self.assertEqual( - type(cmafa.base_fields['opening_band'].widget.widget), - AdminRadioSelect) - self.assertEqual(cmafa.base_fields['opening_band'].widget.attrs, - {'class': 'radiolist'}) + list(cmafa.base_fields['main_band'].widget.choices), + [(self.band.id, 'The Doors')] + ) + + self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), AdminRadioSelect) + self.assertEqual(cmafa.base_fields['opening_band'].widget.attrs, {'class': 'radiolist'}) self.assertEqual( list(cmafa.base_fields['opening_band'].widget.choices), - [('', 'None'), (self.band.id, 'The Doors')]) + [('', 'None'), (self.band.id, 'The Doors')] + ) + self.assertEqual(type(cmafa.base_fields['day'].widget), AdminRadioSelect) + self.assertEqual(cmafa.base_fields['day'].widget.attrs, {'class': 'radiolist'}) + self.assertEqual(list(cmafa.base_fields['day'].widget.choices), [(1, 'Fri'), (2, 'Sat')]) - self.assertEqual(type(cmafa.base_fields['day'].widget), - AdminRadioSelect) - self.assertEqual(cmafa.base_fields['day'].widget.attrs, - {'class': 'radiolist'}) - self.assertEqual(list(cmafa.base_fields['day'].widget.choices), - [(1, 'Fri'), (2, 'Sat')]) - - self.assertEqual(type(cmafa.base_fields['transport'].widget), - AdminRadioSelect) - self.assertEqual(cmafa.base_fields['transport'].widget.attrs, - {'class': 'radiolist inline'}) - self.assertEqual(list(cmafa.base_fields['transport'].widget.choices), - [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]) + self.assertEqual(type(cmafa.base_fields['transport'].widget), AdminRadioSelect) + self.assertEqual(cmafa.base_fields['transport'].widget.attrs, {'class': 'radiolist inline'}) + self.assertEqual( + list(cmafa.base_fields['transport'].widget.choices), + [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')] + ) class AdminConcertForm(forms.ModelForm): class Meta: @@ -533,8 +501,7 @@ class ModelAdminTests(TestCase): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['main_band', 'opening_band', 'day']) + self.assertEqual(list(ma.get_form(request).base_fields), ['main_band', 'opening_band', 'day']) class AdminConcertForm(forms.ModelForm): extra = forms.CharField() @@ -547,8 +514,7 @@ class ModelAdminTests(TestCase): form = AdminConcertForm ma = ConcertAdmin(Concert, self.site) - self.assertEqual(list(ma.get_form(request).base_fields), - ['extra', 'transport']) + self.assertEqual(list(ma.get_form(request).base_fields), ['extra', 'transport']) class ConcertInline(TabularInline): form = AdminConcertForm @@ -564,13 +530,13 @@ class ModelAdminTests(TestCase): ma = BandAdmin(Band, self.site) self.assertEqual( list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), - ['extra', 'transport', 'id', 'DELETE', 'main_band']) + ['extra', 'transport', 'id', 'DELETE', 'main_band'] + ) class CheckTestCase(SimpleTestCase): - def assertIsInvalid(self, model_admin, model, msg, - id=None, hint=None, invalid_obj=None): + def assertIsInvalid(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None): invalid_obj = invalid_obj or model_admin admin_obj = model_admin(model, AdminSite()) errors = admin_obj.check() @@ -584,8 +550,7 @@ class CheckTestCase(SimpleTestCase): ] self.assertEqual(errors, expected) - def assertIsInvalidRegexp(self, model_admin, model, msg, - id=None, hint=None, invalid_obj=None): + def assertIsInvalidRegexp(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None): """ Same as assertIsInvalid but treats the given msg as a regexp. """ diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py index e174023012..fe1c4d86fb 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -33,8 +33,7 @@ class QueryTestCase(TestCase): def test_default_creation(self): "Objects created on the default database don't leak onto other databases" # Create a book on the default database using create() - Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) + Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) # Create a book on the default database using a save dive = Book() @@ -114,8 +113,7 @@ class QueryTestCase(TestCase): def test_basic_queries(self): "Queries are constrained to a single database" - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4)) self.assertEqual(dive.title, "Dive into Python") @@ -157,8 +155,7 @@ class QueryTestCase(TestCase): marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") @@ -195,18 +192,14 @@ class QueryTestCase(TestCase): mark = Person.objects.using('other').get(name="Mark Pilgrim") # Retrieve related object by descriptor. Related objects should be database-bound - self.assertEqual(list(dive.authors.all().values_list('name', flat=True)), - ['Mark Pilgrim']) + self.assertEqual(list(dive.authors.all().values_list('name', flat=True)), ['Mark Pilgrim']) - self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)), - ['Dive into Python']) + self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)), ['Dive into Python']) def test_m2m_forward_operations(self): "M2M forward manipulations are all constrained to a single DB" # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) - + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Save the author relations @@ -265,17 +258,14 @@ class QueryTestCase(TestCase): def test_m2m_reverse_operations(self): "M2M reverse manipulations are all constrained to a single DB" # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) - + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Save the author relations dive.authors.set([mark]) # Create a second book on the other database - grease = Book.objects.using('other').create(title="Greasemonkey Hacks", - published=datetime.date(2005, 11, 1)) + grease = Book.objects.using('other').create(title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1)) # Add a books to the m2m mark.book_set.add(grease) @@ -330,14 +320,12 @@ class QueryTestCase(TestCase): def test_m2m_cross_database_protection(self): "Operations that involve sharing M2M objects across databases raise an error" # Create a book and author on the default database - pro = Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) + pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key set with an object from a different database @@ -368,9 +356,7 @@ class QueryTestCase(TestCase): def test_m2m_deletion(self): "Cascaded deletions of m2m relations issue queries on the right database" # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) - + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") dive.authors.set([mark]) @@ -398,8 +384,7 @@ class QueryTestCase(TestCase): self.assertEqual(Book.authors.through.objects.using('other').count(), 0) # Now try deletion in the reverse direction. Set up the relation again - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) dive.authors.set([mark]) # Check the initial state @@ -428,15 +413,12 @@ class QueryTestCase(TestCase): def test_foreign_key_separation(self): "FK fields are constrained to a single database" # Create a book and author on the default database - pro = Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) + pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) george = Person.objects.create(name="George Vilches") # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) - + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) chris = Person.objects.using('other').create(name="Chris Mills") # Save the author's favorite books @@ -480,14 +462,11 @@ class QueryTestCase(TestCase): dive = Book.objects.using('other').get(title="Dive into Python") # Retrieve related object by descriptor. Related objects should be database-bound - self.assertEqual(list(chris.edited.values_list('title', flat=True)), - ['Dive into Python']) + self.assertEqual(list(chris.edited.values_list('title', flat=True)), ['Dive into Python']) def test_foreign_key_reverse_operations(self): "FK reverse manipulations are all constrained to a single DB" - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) - + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) chris = Person.objects.using('other').create(name="Chris Mills") # Save the author relations @@ -559,14 +538,11 @@ class QueryTestCase(TestCase): def test_foreign_key_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a book and author on the default database - pro = Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) - + pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) # Set a foreign key with an object from a different database with self.assertRaises(ValueError): @@ -701,23 +677,20 @@ class QueryTestCase(TestCase): self.assertEqual(charlie._state.db, 'other') # ... but it isn't saved yet - self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), - ['bob']) - self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog']) + self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), ['bob']) + self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), ['crunchy frog']) # When saved (no using required), new objects goes to 'other' charlie.save() bob_profile.save() new_bob_profile.save() - self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)), - ['alice']) - self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), - ['bob', 'charlie']) - self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), - ['chocolate']) - self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog', 'spring surprise']) + self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)), ['alice']) + self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), ['bob', 'charlie']) + self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate']) + self.assertEqual( + list(UserProfile.objects.using('other').values_list('flavor', flat=True)), + ['crunchy frog', 'spring surprise'] + ) # This also works if you assign the O2O relation in the constructor denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com') @@ -725,29 +698,28 @@ class QueryTestCase(TestCase): self.assertEqual(denise_profile._state.db, 'other') # ... but it isn't saved yet - self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), - ['chocolate']) - self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog', 'spring surprise']) + self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate']) + self.assertEqual( + list(UserProfile.objects.using('other').values_list('flavor', flat=True)), + ['crunchy frog', 'spring surprise'] + ) # When saved, the new profile goes to 'other' denise_profile.save() - self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), - ['chocolate']) - self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog', 'spring surprise', 'tofu']) + self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate']) + self.assertEqual( + list(UserProfile.objects.using('other').values_list('flavor', flat=True)), + ['crunchy frog', 'spring surprise', 'tofu'] + ) def test_generic_key_separation(self): "Generic fields are constrained to a single database" # Create a book and author on the default database - pro = Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) - + pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source="Python Monthly", content_object=pro) # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) @@ -761,17 +733,12 @@ class QueryTestCase(TestCase): dive = Book.objects.using('other').get(title="Dive into Python") # Retrieve related object by descriptor. Related objects should be database-bound - self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)), - ['Python Weekly']) + self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)), ['Python Weekly']) def test_generic_key_reverse_operations(self): "Generic reverse manipulations are all constrained to a single DB" - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) - - temp = Book.objects.using('other').create(title="Temp", - published=datetime.date(2009, 5, 4)) - + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) + temp = Book.objects.using('other').create(title="Temp", published=datetime.date(2009, 5, 4)) review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp) @@ -831,14 +798,11 @@ class QueryTestCase(TestCase): def test_generic_key_cross_database_protection(self): "Operations that involve sharing generic key objects across databases raise an error" # Create a book and author on the default database - pro = Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) - + pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source="Python Monthly", content_object=pro) # Create a book and author on the other database - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) Review.objects.using('other').create(source="Python Weekly", content_object=dive) @@ -884,8 +848,7 @@ class QueryTestCase(TestCase): def test_generic_key_deletion(self): "Cascaded deletions of Generic Key relations issue queries on the right database" - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) Review.objects.using('other').create(source="Python Weekly", content_object=dive) # Check the initial state @@ -907,22 +870,16 @@ class QueryTestCase(TestCase): def test_ordering(self): "get_next_by_XXX commands stick to a single database" - Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) - - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) - - learn = Book.objects.using('other').create(title="Learning Python", - published=datetime.date(2008, 7, 16)) + Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) + learn = Book.objects.using('other').create(title="Learning Python", published=datetime.date(2008, 7, 16)) self.assertEqual(learn.get_next_by_published().title, "Dive into Python") self.assertEqual(dive.get_previous_by_published().title, "Learning Python") def test_raw(self): "test the raw() method across databases" - dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book') self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk")) @@ -933,9 +890,11 @@ class QueryTestCase(TestCase): "Database assignment is retained if an object is retrieved with select_related()" # Create a book and author on the other database mark = Person.objects.using('other').create(name="Mark Pilgrim") - Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4), - editor=mark) + Book.objects.using('other').create( + title="Dive into Python", + published=datetime.date(2009, 5, 4), + editor=mark, + ) # Retrieve the Person using select_related() book = Book.objects.using('other').select_related('editor').get(title="Dive into Python") @@ -966,21 +925,10 @@ class QueryTestCase(TestCase): # extra_arg is removed by the BookManager's implementation of # create(); but the BookManager's implementation won't get called # unless edited returns a Manager, not a queryset - mark.book_set.create(title="Dive into Python", - published=datetime.date(2009, 5, 4), - extra_arg=True) - - mark.book_set.get_or_create(title="Dive into Python", - published=datetime.date(2009, 5, 4), - extra_arg=True) - - mark.edited.create(title="Dive into Water", - published=datetime.date(2009, 5, 4), - extra_arg=True) - - mark.edited.get_or_create(title="Dive into Water", - published=datetime.date(2009, 5, 4), - extra_arg=True) + mark.book_set.create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True) + mark.book_set.get_or_create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True) + mark.edited.create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True) + mark.edited.get_or_create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True) class ConnectionRouterTestCase(SimpleTestCase): @@ -989,21 +937,18 @@ class ConnectionRouterTestCase(SimpleTestCase): 'multiple_database.tests.WriteRouter']) def test_router_init_default(self): connection_router = ConnectionRouter() - self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], - ['TestRouter', 'WriteRouter']) + self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter']) def test_router_init_arg(self): connection_router = ConnectionRouter([ 'multiple_database.tests.TestRouter', 'multiple_database.tests.WriteRouter' ]) - self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], - ['TestRouter', 'WriteRouter']) + self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter']) # Init with instances instead of strings connection_router = ConnectionRouter([TestRouter(), WriteRouter()]) - self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], - ['TestRouter', 'WriteRouter']) + self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter']) # Make the 'other' database appear to be a replica of the 'default' @@ -1085,8 +1030,7 @@ class RouterTestCase(TestCase): pro.authors.set([marty]) # Create a book and author on the other database - Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) # An update query will be routed to the default database Book.objects.filter(title='Pro Django').update(pages=200) diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py index 8823dfef30..8990c7fb5c 100644 --- a/tests/pagination/tests.py +++ b/tests/pagination/tests.py @@ -37,9 +37,11 @@ class PaginationTests(unittest.TestCase): got = getattr(paginator, name) if coerce is not None: got = coerce(got) - self.assertEqual(expected, got, + self.assertEqual( + expected, got, "For '%s', expected %s but got %s. Paginator parameters were: %s" - % (name, expected, got, params)) + % (name, expected, got, params) + ) def test_paginator(self): """ @@ -156,12 +158,9 @@ class PaginationTests(unittest.TestCase): page_num = paginator.num_pages page = paginator.page(page_num) start, end = indexes - msg = ("For %s of page %s, expected %s but got %s." - " Paginator parameters were: %s") - self.assertEqual(start, page.start_index(), - msg % ('start index', page_num, start, page.start_index(), params)) - self.assertEqual(end, page.end_index(), - msg % ('end index', page_num, end, page.end_index(), params)) + msg = ("For %s of page %s, expected %s but got %s. Paginator parameters were: %s") + self.assertEqual(start, page.start_index(), msg % ('start index', page_num, start, page.start_index(), params)) + self.assertEqual(end, page.end_index(), msg % ('end index', page_num, end, page.end_index(), params)) def test_page_indexes(self): """ diff --git a/tests/postgres_tests/test_ranges.py b/tests/postgres_tests/test_ranges.py index dbf10bcf09..ce0b3e90a3 100644 --- a/tests/postgres_tests/test_ranges.py +++ b/tests/postgres_tests/test_ranges.py @@ -295,9 +295,11 @@ class TestSerialization(PostgreSQLTestCase): upper_dt = datetime.datetime(2014, 2, 2, 12, 12, 12, tzinfo=timezone.utc) def test_dumping(self): - instance = RangesModel(ints=NumericRange(0, 10), floats=NumericRange(empty=True), + instance = RangesModel( + ints=NumericRange(0, 10), floats=NumericRange(empty=True), timestamps=DateTimeTZRange(self.lower_dt, self.upper_dt), - dates=DateRange(self.lower_date, self.upper_date)) + dates=DateRange(self.lower_date, self.upper_date), + ) data = serializers.serialize('json', [instance]) dumped = json.loads(data) for field in ('ints', 'dates', 'timestamps'): diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py index 3c4a3a735e..ef32320c0a 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -135,8 +135,7 @@ class PrefetchRelatedTests(TestCase): lists = [[[six.text_type(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs] - self.assertEqual(lists, - [ + self.assertEqual(lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights @@ -149,8 +148,7 @@ class PrefetchRelatedTests(TestCase): lists = [[[six.text_type(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs] - self.assertEqual(lists, - [ + self.assertEqual(lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights @@ -161,8 +159,7 @@ class PrefetchRelatedTests(TestCase): lists = [[[six.text_type(r) for r in b.read_by.all()] for b in a.books.all()] for a in qs] - self.assertEqual(lists, - [ + self.assertEqual(lists, [ [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"]], # Anne - Poems [["Amy"], []], # Emily - Poems, Wuthering Heights @@ -176,8 +173,7 @@ class PrefetchRelatedTests(TestCase): # Need a double with self.assertNumQueries(3): author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte") - lists = [[six.text_type(r) for r in b.read_by.all()] - for b in author.books.all()] + lists = [[six.text_type(r) for r in b.read_by.all()] for b in author.books.all()] self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre def test_foreign_key_then_m2m(self): @@ -189,10 +185,7 @@ class PrefetchRelatedTests(TestCase): qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by') lists = [[six.text_type(r) for r in a.first_book.read_by.all()] for a in qs] - self.assertEqual(lists, [["Amy"], - ["Amy"], - ["Amy"], - ["Amy", "Belinda"]]) + self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]]) def test_reverse_one_to_one_then_m2m(self): """ @@ -907,8 +900,7 @@ class MultiTableInheritanceTest(TestCase): def test_foreignkey(self): with self.assertNumQueries(2): qs = AuthorWithAge.objects.prefetch_related('addresses') - addresses = [[six.text_type(address) for address in obj.addresses.all()] - for obj in qs] + addresses = [[six.text_type(address) for address in obj.addresses.all()] for obj in qs] self.assertEqual(addresses, [[six.text_type(self.author_address)], [], []]) def test_foreignkey_to_inherited(self): @@ -920,20 +912,16 @@ class MultiTableInheritanceTest(TestCase): def test_m2m_to_inheriting_model(self): qs = AuthorWithAge.objects.prefetch_related('books_with_year') with self.assertNumQueries(2): - lst = [[six.text_type(book) for book in author.books_with_year.all()] - for author in qs] + lst = [[six.text_type(book) for book in author.books_with_year.all()] for author in qs] qs = AuthorWithAge.objects.all() - lst2 = [[six.text_type(book) for book in author.books_with_year.all()] - for author in qs] + lst2 = [[six.text_type(book) for book in author.books_with_year.all()] for author in qs] self.assertEqual(lst, lst2) qs = BookWithYear.objects.prefetch_related('aged_authors') with self.assertNumQueries(2): - lst = [[six.text_type(author) for author in book.aged_authors.all()] - for book in qs] + lst = [[six.text_type(author) for author in book.aged_authors.all()] for book in qs] qs = BookWithYear.objects.all() - lst2 = [[six.text_type(author) for author in book.aged_authors.all()] - for book in qs] + lst2 = [[six.text_type(author) for author in book.aged_authors.all()] for book in qs] self.assertEqual(lst, lst2) def test_parent_link_prefetch(self): @@ -1248,14 +1236,10 @@ class Ticket21410Tests(TestCase): self.book3 = Book.objects.create(title="Wuthering Heights") self.book4 = Book.objects.create(title="Sense and Sensibility") - self.author1 = Author2.objects.create(name="Charlotte", - first_book=self.book1) - self.author2 = Author2.objects.create(name="Anne", - first_book=self.book1) - self.author3 = Author2.objects.create(name="Emily", - first_book=self.book1) - self.author4 = Author2.objects.create(name="Jane", - first_book=self.book4) + self.author1 = Author2.objects.create(name="Charlotte", first_book=self.book1) + self.author2 = Author2.objects.create(name="Anne", first_book=self.book1) + self.author3 = Author2.objects.create(name="Emily", first_book=self.book1) + self.author4 = Author2.objects.create(name="Jane", first_book=self.book4) self.author1.favorite_books.add(self.book1, self.book2, self.book3) self.author2.favorite_books.add(self.book1) diff --git a/tests/project_template/test_settings.py b/tests/project_template/test_settings.py index 25a95717a9..702ecec8c5 100644 --- a/tests/project_template/test_settings.py +++ b/tests/project_template/test_settings.py @@ -8,9 +8,11 @@ from django.utils import six from django.utils._os import upath -@unittest.skipIf(six.PY2, +@unittest.skipIf( + six.PY2, 'Python 2 cannot import the project template because ' - 'django/conf/project_template doesn\'t have an __init__.py file.') + 'django/conf/project_template doesn\'t have an __init__.py file.' +) class TestStartProjectSettings(TestCase): def setUp(self): # Ensure settings.py exists diff --git a/tests/proxy_models/tests.py b/tests/proxy_models/tests.py index 20899c68d5..ecbb70c7c4 100644 --- a/tests/proxy_models/tests.py +++ b/tests/proxy_models/tests.py @@ -295,8 +295,7 @@ class ProxyModelTests(TestCase): resp = [s.name for s in StateProxy.objects.select_related()] self.assertEqual(resp, ['New South Wales']) - self.assertEqual(StateProxy.objects.get(name='New South Wales').name, - 'New South Wales') + self.assertEqual(StateProxy.objects.get(name='New South Wales').name, 'New South Wales') resp = StateProxy.objects.select_related().get(name='New South Wales') self.assertEqual(resp.name, 'New South Wales') @@ -317,16 +316,15 @@ class ProxyModelTests(TestCase): ) def test_proxy_bug(self): - contributor = ProxyTrackerUser.objects.create(name='Contributor', - status='contrib') + contributor = ProxyTrackerUser.objects.create(name='Contributor', status='contrib') someone = BaseUser.objects.create(name='Someone') - Bug.objects.create(summary='fix this', version='1.1beta', - assignee=contributor, reporter=someone) - pcontributor = ProxyTrackerUser.objects.create(name='OtherContributor', - status='proxy') - Improvement.objects.create(summary='improve that', version='1.1beta', + Bug.objects.create(summary='fix this', version='1.1beta', assignee=contributor, reporter=someone) + pcontributor = ProxyTrackerUser.objects.create(name='OtherContributor', status='proxy') + Improvement.objects.create( + summary='improve that', version='1.1beta', assignee=contributor, reporter=pcontributor, - associated_bug=ProxyProxyBug.objects.all()[0]) + associated_bug=ProxyProxyBug.objects.all()[0], + ) # Related field filter on proxy resp = ProxyBug.objects.get(version__icontains='beta') diff --git a/tests/queries/tests.py b/tests/queries/tests.py index 87baef2da6..ba99590439 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -1474,10 +1474,8 @@ class Queries4Tests(BaseQuerysetTest): def test_ticket15316_filter_false(self): c1 = SimpleCategory.objects.create(name="category1") - c2 = SpecialCategory.objects.create(name="named category1", - special_name="special1") - c3 = SpecialCategory.objects.create(name="named category2", - special_name="special2") + c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") + c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) @@ -1489,10 +1487,8 @@ class Queries4Tests(BaseQuerysetTest): def test_ticket15316_exclude_false(self): c1 = SimpleCategory.objects.create(name="category1") - c2 = SpecialCategory.objects.create(name="named category1", - special_name="special1") - c3 = SpecialCategory.objects.create(name="named category2", - special_name="special2") + c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") + c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) @@ -1504,10 +1500,8 @@ class Queries4Tests(BaseQuerysetTest): def test_ticket15316_filter_true(self): c1 = SimpleCategory.objects.create(name="category1") - c2 = SpecialCategory.objects.create(name="named category1", - special_name="special1") - c3 = SpecialCategory.objects.create(name="named category2", - special_name="special2") + c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") + c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) @@ -1519,10 +1513,8 @@ class Queries4Tests(BaseQuerysetTest): def test_ticket15316_exclude_true(self): c1 = SimpleCategory.objects.create(name="category1") - c2 = SpecialCategory.objects.create(name="named category1", - special_name="special1") - c3 = SpecialCategory.objects.create(name="named category2", - special_name="special2") + c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") + c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) @@ -2260,15 +2252,20 @@ class QuerySetSupportsPythonIdioms(TestCase): def test_can_get_items_using_index_and_slice_notation(self): self.assertEqual(self.get_ordered_articles()[0].name, 'Article 1') - self.assertQuerysetEqual(self.get_ordered_articles()[1:3], - ["", ""]) + self.assertQuerysetEqual( + self.get_ordered_articles()[1:3], + ["", ""] + ) def test_slicing_with_steps_can_be_used(self): - self.assertQuerysetEqual(self.get_ordered_articles()[::2], - ["", - "", - "", - ""]) + self.assertQuerysetEqual( + self.get_ordered_articles()[::2], [ + "", + "", + "", + "" + ] + ) @unittest.skipUnless(six.PY2, "Python 2 only -- Python 3 doesn't have longs.") def test_slicing_works_with_longs(self): @@ -2276,11 +2273,14 @@ class QuerySetSupportsPythonIdioms(TestCase): self.assertEqual(self.get_ordered_articles()[long(0)].name, 'Article 1') # NOQA self.assertQuerysetEqual(self.get_ordered_articles()[long(1):long(3)], # NOQA ["", ""]) - self.assertQuerysetEqual(self.get_ordered_articles()[::long(2)], # NOQA - ["", - "", - "", - ""]) + self.assertQuerysetEqual( + self.get_ordered_articles()[::long(2)], [ # NOQA + "", + "", + "", + "" + ] + ) # And can be mixed with ints. self.assertQuerysetEqual(self.get_ordered_articles()[1:long(3)], # NOQA @@ -2295,25 +2295,29 @@ class QuerySetSupportsPythonIdioms(TestCase): self.get_ordered_articles()[0:5:3] def test_slicing_can_slice_again_after_slicing(self): - self.assertQuerysetEqual(self.get_ordered_articles()[0:5][0:2], - ["", - ""]) - self.assertQuerysetEqual(self.get_ordered_articles()[0:5][4:], - [""]) + self.assertQuerysetEqual( + self.get_ordered_articles()[0:5][0:2], + ["", ""] + ) + self.assertQuerysetEqual(self.get_ordered_articles()[0:5][4:], [""]) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][5:], []) # Some more tests! - self.assertQuerysetEqual(self.get_ordered_articles()[2:][0:2], - ["", ""]) - self.assertQuerysetEqual(self.get_ordered_articles()[2:][:2], - ["", ""]) - self.assertQuerysetEqual(self.get_ordered_articles()[2:][2:3], - [""]) + self.assertQuerysetEqual( + self.get_ordered_articles()[2:][0:2], + ["", ""] + ) + self.assertQuerysetEqual( + self.get_ordered_articles()[2:][:2], + ["", ""] + ) + self.assertQuerysetEqual(self.get_ordered_articles()[2:][2:3], [""]) # Using an offset without a limit is also possible. - self.assertQuerysetEqual(self.get_ordered_articles()[5:], - ["", - ""]) + self.assertQuerysetEqual( + self.get_ordered_articles()[5:], + ["", ""] + ) def test_slicing_cannot_filter_queryset_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot filter a query once a slice has been taken."): @@ -2343,9 +2347,10 @@ class QuerySetSupportsPythonIdioms(TestCase): def test_can_combine_queries_using_and_and_or_operators(self): s1 = Article.objects.filter(name__exact='Article 1') s2 = Article.objects.filter(name__exact='Article 2') - self.assertQuerysetEqual((s1 | s2).order_by('name'), - ["", - ""]) + self.assertQuerysetEqual( + (s1 | s2).order_by('name'), + ["", ""] + ) self.assertQuerysetEqual(s1 & s2, []) @@ -3488,8 +3493,7 @@ class RelatedLookupTypeTests(TestCase): with self.assertRaisesMessage(ValueError, self.error % (self.ob, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta__in=[self.poa, self.ob]) - with self.assertRaisesMessage(ValueError, - self.error % (self.ob, ChildObjectA._meta.object_name)): + with self.assertRaisesMessage(ValueError, self.error % (self.ob, ChildObjectA._meta.object_name)): ObjectC.objects.exclude(childobjecta__in=[self.coa, self.ob]) def test_wrong_backward_lookup(self): diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py index 694684e2f3..3b017196e4 100644 --- a/tests/raw_query/tests.py +++ b/tests/raw_query/tests.py @@ -44,7 +44,7 @@ class RawQueryTests(TestCase): cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4) def assertSuccessfulRawQuery(self, model, query, expected_results, - expected_annotations=(), params=[], translations=None): + expected_annotations=(), params=[], translations=None): """ Execute the passed query against the passed model and check the output """ @@ -280,10 +280,7 @@ class RawQueryTests(TestCase): Author.objects.raw(query)['test'] def test_inheritance(self): - # date is the end of the Cuban Missile Crisis, I have no idea when - # Wesley was born - f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun", - dob=date(1962, 10, 28)) + f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun", dob=date(1962, 10, 28)) query = "SELECT * FROM raw_query_friendlyauthor" self.assertEqual( [o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk] diff --git a/tests/redirects_tests/tests.py b/tests/redirects_tests/tests.py index faa8cfe023..2d9793b0a5 100644 --- a/tests/redirects_tests/tests.py +++ b/tests/redirects_tests/tests.py @@ -8,8 +8,7 @@ from django.test import TestCase, modify_settings, override_settings from django.utils import six -@modify_settings(MIDDLEWARE_CLASSES={'append': - 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'}) +@modify_settings(MIDDLEWARE_CLASSES={'append': 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'}) @override_settings(APPEND_SLASH=False, SITE_ID=1) class RedirectTests(TestCase): @@ -17,37 +16,29 @@ class RedirectTests(TestCase): self.site = Site.objects.get(pk=settings.SITE_ID) def test_model(self): - r1 = Redirect.objects.create( - site=self.site, old_path='/initial', new_path='/new_target') + r1 = Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target') self.assertEqual(six.text_type(r1), "/initial ---> /new_target") def test_redirect(self): - Redirect.objects.create( - site=self.site, old_path='/initial', new_path='/new_target') + Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target') response = self.client.get('/initial') - self.assertRedirects(response, - '/new_target', status_code=301, target_status_code=404) + self.assertRedirects(response, '/new_target', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash(self): - Redirect.objects.create( - site=self.site, old_path='/initial/', new_path='/new_target/') + Redirect.objects.create(site=self.site, old_path='/initial/', new_path='/new_target/') response = self.client.get('/initial') - self.assertRedirects(response, - '/new_target/', status_code=301, target_status_code=404) + self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash_and_query_string(self): - Redirect.objects.create( - site=self.site, old_path='/initial/?foo', new_path='/new_target/') + Redirect.objects.create(site=self.site, old_path='/initial/?foo', new_path='/new_target/') response = self.client.get('/initial?foo') - self.assertRedirects(response, - '/new_target/', status_code=301, target_status_code=404) + self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) def test_response_gone(self): """When the redirect target is '', return a 410""" - Redirect.objects.create( - site=self.site, old_path='/initial', new_path='') + Redirect.objects.create(site=self.site, old_path='/initial', new_path='') response = self.client.get('/initial') self.assertEqual(response.status_code, 410) @@ -63,8 +54,7 @@ class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware): response_redirect_class = http.HttpResponseRedirect -@modify_settings(MIDDLEWARE_CLASSES={'append': - 'redirects_tests.tests.OverriddenRedirectFallbackMiddleware'}) +@modify_settings(MIDDLEWARE_CLASSES={'append': 'redirects_tests.tests.OverriddenRedirectFallbackMiddleware'}) @override_settings(SITE_ID=1) class OverriddenRedirectMiddlewareTests(TestCase): @@ -72,13 +62,11 @@ class OverriddenRedirectMiddlewareTests(TestCase): self.site = Site.objects.get(pk=settings.SITE_ID) def test_response_gone_class(self): - Redirect.objects.create( - site=self.site, old_path='/initial/', new_path='') + Redirect.objects.create(site=self.site, old_path='/initial/', new_path='') response = self.client.get('/initial/') self.assertEqual(response.status_code, 403) def test_response_redirect_class(self): - Redirect.objects.create( - site=self.site, old_path='/initial/', new_path='/new_target/') + Redirect.objects.create(site=self.site, old_path='/initial/', new_path='/new_target/') response = self.client.get('/initial/') self.assertEqual(response.status_code, 302) diff --git a/tests/requests/tests.py b/tests/requests/tests.py index c09cf79bd5..b015e6dfff 100644 --- a/tests/requests/tests.py +++ b/tests/requests/tests.py @@ -184,13 +184,17 @@ class RequestsTests(SimpleTestCase): def test_httprequest_location(self): request = HttpRequest() - self.assertEqual(request.build_absolute_uri(location="https://www.example.com/asdf"), - 'https://www.example.com/asdf') + self.assertEqual( + request.build_absolute_uri(location="https://www.example.com/asdf"), + 'https://www.example.com/asdf' + ) request.get_host = lambda: 'www.example.com' request.path = '' - self.assertEqual(request.build_absolute_uri(location="/path/with:colons"), - 'http://www.example.com/path/with:colons') + self.assertEqual( + request.build_absolute_uri(location="/path/with:colons"), + 'http://www.example.com/path/with:colons' + ) def test_near_expiration(self): "Cookie will expire when an near expiration time is provided" diff --git a/tests/reserved_names/tests.py b/tests/reserved_names/tests.py index 99f2b4befe..429bb01e2d 100644 --- a/tests/reserved_names/tests.py +++ b/tests/reserved_names/tests.py @@ -10,21 +10,29 @@ from .models import Thing class ReservedNameTests(TestCase): def generate(self): day1 = datetime.date(2005, 1, 1) - Thing.objects.create(when='a', join='b', like='c', drop='d', - alter='e', having='f', where=day1, has_hyphen='h') + Thing.objects.create( + when='a', join='b', like='c', drop='d', alter='e', having='f', + where=day1, has_hyphen='h', + ) day2 = datetime.date(2006, 2, 2) - Thing.objects.create(when='h', join='i', like='j', drop='k', - alter='l', having='m', where=day2) + Thing.objects.create( + when='h', join='i', like='j', drop='k', alter='l', having='m', + where=day2, + ) def test_simple(self): day1 = datetime.date(2005, 1, 1) - t = Thing.objects.create(when='a', join='b', like='c', drop='d', - alter='e', having='f', where=day1, has_hyphen='h') + t = Thing.objects.create( + when='a', join='b', like='c', drop='d', + alter='e', having='f', where=day1, has_hyphen='h', + ) self.assertEqual(t.when, 'a') day2 = datetime.date(2006, 2, 2) - u = Thing.objects.create(when='h', join='i', like='j', drop='k', - alter='l', having='m', where=day2) + u = Thing.objects.create( + when='h', join='i', like='j', drop='k', alter='l', having='m', + where=day2, + ) self.assertEqual(u.when, 'h') def test_order_by(self): diff --git a/tests/runtests.py b/tests/runtests.py index 802922a7ee..aedd4aa932 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -376,56 +376,74 @@ def paired_tests(paired_test, options, test_labels, parallel): if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the Django test suite.") - parser.add_argument('modules', nargs='*', metavar='module', + parser.add_argument( + 'modules', nargs='*', metavar='module', help='Optional path(s) to test modules; e.g. "i18n" or ' - '"i18n.tests.TranslationTests.test_lazy_objects".') + '"i18n.tests.TranslationTests.test_lazy_objects".', + ) parser.add_argument( '-v', '--verbosity', default=1, type=int, choices=[0, 1, 2, 3], - help='Verbosity level; 0=minimal output, 1=normal output, 2=all output') + help='Verbosity level; 0=minimal output, 1=normal output, 2=all output', + ) parser.add_argument( '--noinput', action='store_false', dest='interactive', default=True, - help='Tells Django to NOT prompt the user for input of any kind.') + help='Tells Django to NOT prompt the user for input of any kind.', + ) parser.add_argument( '--failfast', action='store_true', dest='failfast', default=False, - help='Tells Django to stop running the test suite after first failed ' - 'test.') + help='Tells Django to stop running the test suite after first failed test.', + ) parser.add_argument( '-k', '--keepdb', action='store_true', dest='keepdb', default=False, - help='Tells Django to preserve the test database between runs.') + help='Tells Django to preserve the test database between runs.', + ) parser.add_argument( '--settings', help='Python path to settings module, e.g. "myproject.settings". If ' 'this isn\'t provided, either the DJANGO_SETTINGS_MODULE ' - 'environment variable or "test_sqlite" will be used.') - parser.add_argument('--bisect', + 'environment variable or "test_sqlite" will be used.', + ) + parser.add_argument( + '--bisect', help='Bisect the test suite to discover a test that causes a test ' - 'failure when combined with the named test.') - parser.add_argument('--pair', - help='Run the test suite in pairs with the named test to find problem ' - 'pairs.') - parser.add_argument('--reverse', action='store_true', default=False, + 'failure when combined with the named test.', + ) + parser.add_argument( + '--pair', + help='Run the test suite in pairs with the named test to find problem pairs.', + ) + parser.add_argument( + '--reverse', action='store_true', default=False, help='Sort test suites and test cases in opposite order to debug ' - 'test side effects not apparent with normal execution lineup.') - parser.add_argument('--liveserver', + 'test side effects not apparent with normal execution lineup.', + ) + parser.add_argument( + '--liveserver', help='Overrides the default address where the live server (used with ' 'LiveServerTestCase) is expected to run from. The default value ' - 'is localhost:8081-8179.') + 'is localhost:8081-8179.', + ) parser.add_argument( '--selenium', dest='selenium', action=ActionSelenium, metavar='BROWSERS', - help='A comma-separated list of browsers to run the Selenium tests against.') + help='A comma-separated list of browsers to run the Selenium tests against.', + ) parser.add_argument( '--debug-sql', action='store_true', dest='debug_sql', default=False, - help='Turn on the SQL query logger within tests.') + help='Turn on the SQL query logger within tests.', + ) parser.add_argument( '--parallel', dest='parallel', nargs='?', default=0, type=int, const=default_test_processes(), metavar='N', - help='Run tests using up to N parallel processes.') + help='Run tests using up to N parallel processes.', + ) parser.add_argument( '--tag', dest='tags', action='append', - help='Run only tests with the specified tags. Can be used multiple times.') + help='Run only tests with the specified tags. Can be used multiple times.', + ) parser.add_argument( '--exclude-tag', dest='exclude_tags', action='append', - help='Do not run tests with the specified tag. Can be used multiple times.') + help='Do not run tests with the specified tag. Can be used multiple times.', + ) options = parser.parse_args() diff --git a/tests/select_related/tests.py b/tests/select_related/tests.py index 59eac3802b..33752a6ff7 100644 --- a/tests/select_related/tests.py +++ b/tests/select_related/tests.py @@ -100,8 +100,7 @@ class SelectRelatedTests(TestCase): with self.assertNumQueries(5): world = Species.objects.all().select_related('genus__family') orders = [o.genus.family.order.name for o in world] - self.assertEqual(sorted(orders), - ['Agaricales', 'Diptera', 'Fabales', 'Primates']) + self.assertEqual(sorted(orders), ['Agaricales', 'Diptera', 'Fabales', 'Primates']) def test_select_related_with_extra(self): s = (Species.objects.all() @@ -120,8 +119,7 @@ class SelectRelatedTests(TestCase): with self.assertNumQueries(1): world = Species.objects.select_related('genus__family') families = [o.genus.family.name for o in world] - self.assertEqual(sorted(families), - ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae']) + self.assertEqual(sorted(families), ['Amanitacae', 'Drosophilidae', 'Fabaceae', 'Hominidae']) def test_more_certain_fields(self): """ @@ -162,9 +160,7 @@ class SelectRelatedTests(TestCase): """ Running select_related() after calling values() raises a TypeError """ - message = "Cannot call select_related() after .values() or .values_list()" - with self.assertRaisesMessage(TypeError, message): list(Species.objects.values('name').select_related('genus')) @@ -172,9 +168,7 @@ class SelectRelatedTests(TestCase): """ Running select_related() after calling values_list() raises a TypeError """ - message = "Cannot call select_related() after .values() or .values_list()" - with self.assertRaisesMessage(TypeError, message): list(Species.objects.values_list('name').select_related('genus')) diff --git a/tests/select_related_regress/tests.py b/tests/select_related_regress/tests.py index 640add4638..efa6a30f99 100644 --- a/tests/select_related_regress/tests.py +++ b/tests/select_related_regress/tests.py @@ -36,8 +36,10 @@ class SelectRelatedRegressTests(TestCase): c2 = Connection.objects.create(start=port2, end=port3) connections = Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id') - self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], - [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')]) + self.assertEqual( + [(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], + [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')] + ) connections = ( Connection.objects @@ -45,8 +47,10 @@ class SelectRelatedRegressTests(TestCase): .select_related() .order_by('id') ) - self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], - [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')]) + self.assertEqual( + [(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], + [(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')] + ) # This final query should only have seven tables (port, device and building # twice each, plus connection once). Thus, 6 joins plus the FROM table. diff --git a/tests/serializers/test_data.py b/tests/serializers/test_data.py index 560006759f..4318856307 100644 --- a/tests/serializers/test_data.py +++ b/tests/serializers/test_data.py @@ -120,15 +120,19 @@ def inherited_create(pk, klass, data): def data_compare(testcase, pk, klass, data): instance = klass.objects.get(id=pk) if klass == BinaryData and data is not None: - testcase.assertEqual(bytes(data), bytes(instance.data), - "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( - pk, repr(bytes(data)), type(data), repr(bytes(instance.data)), - type(instance.data)) + testcase.assertEqual( + bytes(data), bytes(instance.data), + "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( + pk, repr(bytes(data)), type(data), repr(bytes(instance.data)), + type(instance.data), + ) ) else: - testcase.assertEqual(data, instance.data, - "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( - pk, data, type(data), instance, type(instance.data)) + testcase.assertEqual( + data, instance.data, + "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( + pk, data, type(data), instance, type(instance.data), + ) ) diff --git a/tests/serializers/test_natural.py b/tests/serializers/test_natural.py index 6682e5cdd8..8f4d00d5a6 100644 --- a/tests/serializers/test_natural.py +++ b/tests/serializers/test_natural.py @@ -21,8 +21,7 @@ def natural_key_serializer_test(format, self): FKDataNaturalKey.objects.create(id=1102, data_id=None), ] # Serialize the test database - serialized_data = serializers.serialize(format, objects, indent=2, - use_natural_foreign_keys=True) + serialized_data = serializers.serialize(format, objects, indent=2, use_natural_foreign_keys=True) for obj in serializers.deserialize(format, serialized_data): obj.save() @@ -31,15 +30,19 @@ def natural_key_serializer_test(format, self): # as the original source for obj in objects: instance = obj.__class__.objects.get(id=obj.pk) - self.assertEqual(obj.data, instance.data, - "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( - obj.pk, obj.data, type(obj.data), instance, type(instance.data)) + self.assertEqual( + obj.data, instance.data, + "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)" % ( + obj.pk, obj.data, type(obj.data), instance, type(instance.data), + ) ) def natural_key_test(format, self): - book1 = {'data': '978-1590597255', 'title': 'The Definitive Guide to ' - 'Django: Web Development Done Right'} + book1 = { + 'data': '978-1590597255', + 'title': 'The Definitive Guide to Django: Web Development Done Right', + } book2 = {'data': '978-1590599969', 'title': 'Practical Django Projects'} # Create the books. @@ -47,9 +50,10 @@ def natural_key_test(format, self): james = NaturalKeyAnchor.objects.create(**book2) # Serialize the books. - string_data = serializers.serialize(format, NaturalKeyAnchor.objects.all(), - indent=2, use_natural_foreign_keys=True, - use_natural_primary_keys=True) + string_data = serializers.serialize( + format, NaturalKeyAnchor.objects.all(), indent=2, + use_natural_foreign_keys=True, use_natural_primary_keys=True, + ) # Delete one book (to prove that the natural key generation will only # restore the primary keys of books found in the database via the diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py index c18cdae7e0..96284ca642 100644 --- a/tests/serializers/tests.py +++ b/tests/serializers/tests.py @@ -124,14 +124,12 @@ class SerializersTestBase(object): def test_serialize(self): """Tests that basic serialization works.""" - serial_str = serializers.serialize(self.serializer_name, - Article.objects.all()) + serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) self.assertTrue(self._validate_output(serial_str)) def test_serializer_roundtrip(self): """Tests that serialized content can be deserialized.""" - serial_str = serializers.serialize(self.serializer_name, - Article.objects.all()) + serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) models = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(len(models), 2) @@ -174,8 +172,7 @@ class SerializersTestBase(object): """ old_headline = "Poker has no place on ESPN" new_headline = "Poker has no place on television" - serial_str = serializers.serialize(self.serializer_name, - Article.objects.all()) + serial_str = serializers.serialize(self.serializer_name, Article.objects.all()) serial_str = serial_str.replace(old_headline, new_headline) models = list(serializers.deserialize(self.serializer_name, serial_str)) @@ -196,11 +193,8 @@ class SerializersTestBase(object): (such as a OneToOneField), it doesn't appear in the serialized field list - it replaces the pk identifier. """ - profile = AuthorProfile(author=self.joe, - date_of_birth=datetime(1970, 1, 1)) - profile.save() - serial_str = serializers.serialize(self.serializer_name, - AuthorProfile.objects.all()) + AuthorProfile.objects.create(author=self.joe, date_of_birth=datetime(1970, 1, 1)) + serial_str = serializers.serialize(self.serializer_name, AuthorProfile.objects.all()) self.assertFalse(self._get_field_values(serial_str, 'author')) for obj in serializers.deserialize(self.serializer_name, serial_str): @@ -210,9 +204,7 @@ class SerializersTestBase(object): """Tests that output can be restricted to a subset of fields""" valid_fields = ('headline', 'pub_date') invalid_fields = ("author", "categories") - serial_str = serializers.serialize(self.serializer_name, - Article.objects.all(), - fields=valid_fields) + serial_str = serializers.serialize(self.serializer_name, Article.objects.all(), fields=valid_fields) for field_name in invalid_fields: self.assertFalse(self._get_field_values(serial_str, field_name)) @@ -269,8 +261,7 @@ class SerializersTestBase(object): pk_value = self._get_pk_values(serial_str)[0] self.assertFalse(pk_value) - cat_obj = list(serializers.deserialize(self.serializer_name, - serial_str))[0].object + cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0].object self.assertEqual(cat_obj.id, None) def test_float_serialization(self): @@ -278,8 +269,7 @@ class SerializersTestBase(object): sc = Score(score=3.4) sc.save() serial_str = serializers.serialize(self.serializer_name, [sc]) - deserial_objs = list(serializers.deserialize(self.serializer_name, - serial_str)) + deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) self.assertEqual(deserial_objs[0].object.score, Approximate(3.4, places=1)) def test_deferred_field_serialization(self): @@ -299,15 +289,13 @@ class SerializersTestBase(object): player.rank = 1 player.team = Team(team_str) player.save() - serial_str = serializers.serialize(self.serializer_name, - Player.objects.all()) + serial_str = serializers.serialize(self.serializer_name, Player.objects.all()) team = self._get_field_values(serial_str, "team") self.assertTrue(team) self.assertEqual(team[0], team_str) deserial_objs = list(serializers.deserialize(self.serializer_name, serial_str)) - self.assertEqual(deserial_objs[0].object.team.to_string(), - player.team.to_string()) + self.assertEqual(deserial_objs[0].object.team.to_string(), player.team.to_string()) def test_pre_1000ad_date(self): """Tests that year values before 1000AD are properly formatted""" @@ -327,8 +315,7 @@ class SerializersTestBase(object): Tests that serialized strings without PKs can be turned into models """ - deserial_objs = list(serializers.deserialize(self.serializer_name, - self.pkless_str)) + deserial_objs = list(serializers.deserialize(self.serializer_name, self.pkless_str)) for obj in deserial_objs: self.assertFalse(obj.object.id) obj.save() diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py index 6a8a7ee96b..5c4e133567 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -552,8 +552,10 @@ class FileSessionTests(SessionTestsMixin, unittest.TestCase): file_prefix = settings.SESSION_COOKIE_NAME def count_sessions(): - return len([session_file for session_file in os.listdir(storage_path) - if session_file.startswith(file_prefix)]) + return len([ + session_file for session_file in os.listdir(storage_path) + if session_file.startswith(file_prefix) + ]) self.assertEqual(0, count_sessions()) @@ -651,8 +653,10 @@ class SessionMiddlewareTests(TestCase): response = middleware.process_response(request, response) self.assertTrue( response.cookies[settings.SESSION_COOKIE_NAME]['httponly']) - self.assertIn(http_cookies.Morsel._reserved['httponly'], - str(response.cookies[settings.SESSION_COOKIE_NAME])) + self.assertIn( + http_cookies.Morsel._reserved['httponly'], + str(response.cookies[settings.SESSION_COOKIE_NAME]) + ) @override_settings(SESSION_COOKIE_HTTPONLY=False) def test_no_httponly_session_cookie(self): diff --git a/tests/settings_tests/tests.py b/tests/settings_tests/tests.py index 87352ba32a..8cee706d5b 100644 --- a/tests/settings_tests/tests.py +++ b/tests/settings_tests/tests.py @@ -11,7 +11,6 @@ from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, modify_settings, override_settings, signals, ) -from django.utils import six @modify_settings(ITEMS={ @@ -19,8 +18,7 @@ from django.utils import six 'append': ['d'], 'remove': ['a', 'e'] }) -@override_settings(ITEMS=['a', 'c', 'e'], ITEMS_OUTER=[1, 2, 3], - TEST='override', TEST_OUTER='outer') +@override_settings(ITEMS=['a', 'c', 'e'], ITEMS_OUTER=[1, 2, 3], TEST='override', TEST_OUTER='outer') class FullyDecoratedTranTestCase(TransactionTestCase): available_apps = [] @@ -215,8 +213,7 @@ class SettingsTests(SimpleTestCase): self.assertIsInstance(decorated, type) self.assertTrue(issubclass(decorated, SimpleTestCase)) - with six.assertRaisesRegex(self, Exception, - "Only subclasses of Django SimpleTestCase*"): + with self.assertRaisesMessage(Exception, "Only subclasses of Django SimpleTestCase"): decorated = override_settings(TEST='override')(UnittestTestCaseSubclass) def test_signal_callback_context_manager(self): @@ -310,10 +307,8 @@ class TestComplexSettingOverride(SimpleTestCase): self.assertEqual(len(w), 1) # File extension may by .py, .pyc, etc. Compare only basename. - self.assertEqual(os.path.splitext(w[0].filename)[0], - os.path.splitext(__file__)[0]) - self.assertEqual(str(w[0].message), - 'Overriding setting TEST_WARN can lead to unexpected behavior.') + self.assertEqual(os.path.splitext(w[0].filename)[0], os.path.splitext(__file__)[0]) + self.assertEqual(str(w[0].message), 'Overriding setting TEST_WARN can lead to unexpected behavior.') class TrailingSlashURLTests(SimpleTestCase): @@ -351,15 +346,13 @@ class TrailingSlashURLTests(SimpleTestCase): self.assertEqual('/foo/', self.settings_module.MEDIA_URL) self.settings_module.MEDIA_URL = 'http://media.foo.com/' - self.assertEqual('http://media.foo.com/', - self.settings_module.MEDIA_URL) + self.assertEqual('http://media.foo.com/', self.settings_module.MEDIA_URL) self.settings_module.STATIC_URL = '/foo/' self.assertEqual('/foo/', self.settings_module.STATIC_URL) self.settings_module.STATIC_URL = 'http://static.foo.com/' - self.assertEqual('http://static.foo.com/', - self.settings_module.STATIC_URL) + self.assertEqual('http://static.foo.com/', self.settings_module.STATIC_URL) def test_no_end_slash(self): """ @@ -387,15 +380,13 @@ class TrailingSlashURLTests(SimpleTestCase): self.assertEqual('/wrong//', self.settings_module.MEDIA_URL) self.settings_module.MEDIA_URL = 'http://media.foo.com/wrong//' - self.assertEqual('http://media.foo.com/wrong//', - self.settings_module.MEDIA_URL) + self.assertEqual('http://media.foo.com/wrong//', self.settings_module.MEDIA_URL) self.settings_module.STATIC_URL = '/wrong//' self.assertEqual('/wrong//', self.settings_module.STATIC_URL) self.settings_module.STATIC_URL = 'http://static.foo.com/wrong//' - self.assertEqual('http://static.foo.com/wrong//', - self.settings_module.STATIC_URL) + self.assertEqual('http://static.foo.com/wrong//', self.settings_module.STATIC_URL) class SecureProxySslHeaderTest(SimpleTestCase): diff --git a/tests/signals/tests.py b/tests/signals/tests.py index f3bbc05f65..b02b215958 100644 --- a/tests/signals/tests.py +++ b/tests/signals/tests.py @@ -267,9 +267,8 @@ class LazyModelRefTest(BaseSignalTest): self.received.append(kwargs) def test_invalid_sender_model_name(self): - with self.assertRaisesMessage(ValueError, - "Specified sender must either be a model or a " - "model name of the 'app_label.ModelName' form."): + msg = "Specified sender must either be a model or a model name of the 'app_label.ModelName' form." + with self.assertRaisesMessage(ValueError, msg): signals.post_init.connect(self.receiver, sender='invalid') def test_already_loaded_model(self): diff --git a/tests/signing/tests.py b/tests/signing/tests.py index 0b7e54189b..e2677dfc1e 100644 --- a/tests/signing/tests.py +++ b/tests/signing/tests.py @@ -22,8 +22,7 @@ class TestSigner(SimpleTestCase): ): self.assertEqual( signer.signature(s), - signing.base64_hmac(signer.salt + 'signer', s, - 'predictable-secret').decode() + signing.base64_hmac(signer.salt + 'signer', s, 'predictable-secret').decode() ) self.assertNotEqual(signer.signature(s), signer2.signature(s)) @@ -32,8 +31,7 @@ class TestSigner(SimpleTestCase): signer = signing.Signer('predictable-secret', salt='extra-salt') self.assertEqual( signer.signature('hello'), - signing.base64_hmac('extra-salt' + 'signer', - 'hello', 'predictable-secret').decode() + signing.base64_hmac('extra-salt' + 'signer', 'hello', 'predictable-secret').decode() ) self.assertNotEqual( signing.Signer('predictable-secret', salt='one').signature('hello'), @@ -134,8 +132,7 @@ class TestTimestampSigner(SimpleTestCase): with freeze_time(123456789): signer = signing.TimestampSigner('predictable-key') ts = signer.sign(value) - self.assertNotEqual(ts, - signing.Signer('predictable-key').sign(value)) + self.assertNotEqual(ts, signing.Signer('predictable-key').sign(value)) self.assertEqual(signer.unsign(ts), value) with freeze_time(123456800): diff --git a/tests/template_tests/filter_tests/test_center.py b/tests/template_tests/filter_tests/test_center.py index 306de33101..c37b7f80c0 100644 --- a/tests/template_tests/filter_tests/test_center.py +++ b/tests/template_tests/filter_tests/test_center.py @@ -7,8 +7,7 @@ from ..utils import setup class CenterTests(SimpleTestCase): - @setup({'center01': - '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.{% endautoescape %}'}) + @setup({'center01': '{% autoescape off %}.{{ a|center:"5" }}. .{{ b|center:"5" }}.{% endautoescape %}'}) def test_center01(self): output = self.engine.render_to_string('center01', {"a": "a&b", "b": mark_safe("a&b")}) self.assertEqual(output, ". a&b . . a&b .") diff --git a/tests/template_tests/filter_tests/test_chaining.py b/tests/template_tests/filter_tests/test_chaining.py index 1704715191..9bc3976f37 100644 --- a/tests/template_tests/filter_tests/test_chaining.py +++ b/tests/template_tests/filter_tests/test_chaining.py @@ -14,8 +14,10 @@ class ChainingTests(SimpleTestCase): output = self.engine.render_to_string('chaining01', {'a': 'a < b', 'b': mark_safe('a < b')}) self.assertEqual(output, ' A < b . A < b ') - @setup({'chaining02': - '{% autoescape off %}{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}{% endautoescape %}'}) + @setup({ + 'chaining02': + '{% autoescape off %}{{ a|capfirst|center:"7" }}.{{ b|capfirst|center:"7" }}{% endautoescape %}' + }) def test_chaining02(self): output = self.engine.render_to_string('chaining02', {'a': 'a < b', 'b': mark_safe('a < b')}) self.assertEqual(output, ' A < b . A < b ') @@ -26,8 +28,9 @@ class ChainingTests(SimpleTestCase): output = self.engine.render_to_string('chaining03', {'a': 'a < b', 'b': mark_safe('a < b')}) self.assertEqual(output, 'A < .A < ') - @setup({'chaining04': - '{% autoescape off %}{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}{% endautoescape %}'}) + @setup({ + 'chaining04': '{% autoescape off %}{{ a|cut:"b"|capfirst }}.{{ b|cut:"b"|capfirst }}{% endautoescape %}' + }) def test_chaining04(self): output = self.engine.render_to_string('chaining04', {'a': 'a < b', 'b': mark_safe('a < b')}) self.assertEqual(output, 'A < .A < ') diff --git a/tests/template_tests/filter_tests/test_floatformat.py b/tests/template_tests/filter_tests/test_floatformat.py index 5fe35ee378..099ec4d174 100644 --- a/tests/template_tests/filter_tests/test_floatformat.py +++ b/tests/template_tests/filter_tests/test_floatformat.py @@ -14,8 +14,7 @@ from ..utils import setup class FloatformatTests(SimpleTestCase): - @setup({'floatformat01': - '{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}'}) + @setup({'floatformat01': '{% autoescape off %}{{ a|floatformat }} {{ b|floatformat }}{% endautoescape %}'}) def test_floatformat01(self): output = self.engine.render_to_string('floatformat01', {"a": "1.42", "b": mark_safe("1.42")}) self.assertEqual(output, "1.4 1.4") diff --git a/tests/template_tests/filter_tests/test_linebreaks.py b/tests/template_tests/filter_tests/test_linebreaks.py index 144facf399..50a66f3c47 100644 --- a/tests/template_tests/filter_tests/test_linebreaks.py +++ b/tests/template_tests/filter_tests/test_linebreaks.py @@ -18,8 +18,7 @@ class LinebreaksTests(SimpleTestCase): output = self.engine.render_to_string('linebreaks01', {"a": "x&\ny", "b": mark_safe("x&\ny")}) self.assertEqual(output, "

    x&
    y

    x&
    y

    ") - @setup({'linebreaks02': - '{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}'}) + @setup({'linebreaks02': '{% autoescape off %}{{ a|linebreaks }} {{ b|linebreaks }}{% endautoescape %}'}) def test_linebreaks02(self): output = self.engine.render_to_string('linebreaks02', {"a": "x&\ny", "b": mark_safe("x&\ny")}) self.assertEqual(output, "

    x&
    y

    x&
    y

    ") diff --git a/tests/template_tests/filter_tests/test_linebreaksbr.py b/tests/template_tests/filter_tests/test_linebreaksbr.py index c702ba777f..83a15f97db 100644 --- a/tests/template_tests/filter_tests/test_linebreaksbr.py +++ b/tests/template_tests/filter_tests/test_linebreaksbr.py @@ -16,8 +16,7 @@ class LinebreaksbrTests(SimpleTestCase): output = self.engine.render_to_string('linebreaksbr01', {"a": "x&\ny", "b": mark_safe("x&\ny")}) self.assertEqual(output, "x&
    y x&
    y") - @setup({'linebreaksbr02': - '{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}'}) + @setup({'linebreaksbr02': '{% autoescape off %}{{ a|linebreaksbr }} {{ b|linebreaksbr }}{% endautoescape %}'}) def test_linebreaksbr02(self): output = self.engine.render_to_string('linebreaksbr02', {"a": "x&\ny", "b": mark_safe("x&\ny")}) self.assertEqual(output, "x&
    y x&
    y") diff --git a/tests/template_tests/filter_tests/test_linenumbers.py b/tests/template_tests/filter_tests/test_linenumbers.py index 36ec8de0d5..2ded01f421 100644 --- a/tests/template_tests/filter_tests/test_linenumbers.py +++ b/tests/template_tests/filter_tests/test_linenumbers.py @@ -17,18 +17,15 @@ class LinenumbersTests(SimpleTestCase): 'linenumbers01', {'a': 'one\n\nthree', 'b': mark_safe('one\n<two>\nthree')}, ) - self.assertEqual(output, '1. one\n2. <two>\n3. three ' - '1. one\n2. <two>\n3. three') + self.assertEqual(output, '1. one\n2. <two>\n3. three 1. one\n2. <two>\n3. three') - @setup({'linenumbers02': - '{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}'}) + @setup({'linenumbers02': '{% autoescape off %}{{ a|linenumbers }} {{ b|linenumbers }}{% endautoescape %}'}) def test_linenumbers02(self): output = self.engine.render_to_string( 'linenumbers02', {'a': 'one\n\nthree', 'b': mark_safe('one\n<two>\nthree')}, ) - self.assertEqual(output, '1. one\n2. \n3. three ' - '1. one\n2. <two>\n3. three') + self.assertEqual(output, '1. one\n2. \n3. three 1. one\n2. <two>\n3. three') class FunctionTests(SimpleTestCase): diff --git a/tests/template_tests/filter_tests/test_make_list.py b/tests/template_tests/filter_tests/test_make_list.py index 16db76057f..454b394d3b 100644 --- a/tests/template_tests/filter_tests/test_make_list.py +++ b/tests/template_tests/filter_tests/test_make_list.py @@ -22,8 +22,7 @@ class MakeListTests(SimpleTestCase): output = self.engine.render_to_string('make_list02', {"a": mark_safe("&")}) self.assertEqual(output, str_prefix("[%(_)s'&']")) - @setup({'make_list03': - '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}'}) + @setup({'make_list03': '{% autoescape off %}{{ a|make_list|stringformat:"s"|safe }}{% endautoescape %}'}) def test_make_list03(self): output = self.engine.render_to_string('make_list03', {"a": mark_safe("&")}) self.assertEqual(output, str_prefix("[%(_)s'&']")) diff --git a/tests/template_tests/filter_tests/test_phone2numeric.py b/tests/template_tests/filter_tests/test_phone2numeric.py index 4554d1712f..0c81a904ea 100644 --- a/tests/template_tests/filter_tests/test_phone2numeric.py +++ b/tests/template_tests/filter_tests/test_phone2numeric.py @@ -15,8 +15,7 @@ class Phone2numericTests(SimpleTestCase): ) self.assertEqual(output, '<1-800-2255-63> <1-800-2255-63>') - @setup({'phone2numeric02': - '{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}'}) + @setup({'phone2numeric02': '{% autoescape off %}{{ a|phone2numeric }} {{ b|phone2numeric }}{% endautoescape %}'}) def test_phone2numeric02(self): output = self.engine.render_to_string( 'phone2numeric02', diff --git a/tests/template_tests/filter_tests/test_safeseq.py b/tests/template_tests/filter_tests/test_safeseq.py index 9c68d69980..38b1cd6078 100644 --- a/tests/template_tests/filter_tests/test_safeseq.py +++ b/tests/template_tests/filter_tests/test_safeseq.py @@ -10,8 +10,7 @@ class SafeseqTests(SimpleTestCase): output = self.engine.render_to_string('safeseq01', {'a': ['&', '<']}) self.assertEqual(output, '&, < -- &, <') - @setup({'safeseq02': - '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}'}) + @setup({'safeseq02': '{% autoescape off %}{{ a|join:", " }} -- {{ a|safeseq|join:", " }}{% endautoescape %}'}) def test_safeseq02(self): output = self.engine.render_to_string('safeseq02', {'a': ['&', '<']}) self.assertEqual(output, '&, < -- &, <') diff --git a/tests/template_tests/filter_tests/test_stringformat.py b/tests/template_tests/filter_tests/test_stringformat.py index 36939892c5..9501878ebd 100644 --- a/tests/template_tests/filter_tests/test_stringformat.py +++ b/tests/template_tests/filter_tests/test_stringformat.py @@ -11,8 +11,10 @@ class StringformatTests(SimpleTestCase): formatting here only needs to deal with pre-escaped characters. """ - @setup({'stringformat01': - '{% autoescape off %}.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.{% endautoescape %}'}) + @setup({ + 'stringformat01': + '{% autoescape off %}.{{ a|stringformat:"5s" }}. .{{ b|stringformat:"5s" }}.{% endautoescape %}' + }) def test_stringformat01(self): output = self.engine.render_to_string('stringformat01', {'a': 'a'}) self.assertEqual(output, ' <a>') @@ -46,8 +48,10 @@ class AutoescapeTagTests(SimpleTestCase): output = self.engine.render_to_string('autoescape-tag07', {'first': mark_safe('Apple')}) self.assertEqual(output, 'Apple') - @setup({'autoescape-tag08': r'{% autoescape on %}' - r'{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}'}) + @setup({ + 'autoescape-tag08': + r'{% autoescape on %}{{ var|default_if_none:" endquote\" hah" }}{% endautoescape %}' + }) def test_autoescape_tag08(self): """ Literal string arguments to filters, if used in the result, are safe. diff --git a/tests/template_tests/syntax_tests/test_cache.py b/tests/template_tests/syntax_tests/test_cache.py index 2039e7808c..7f7a6cd2cb 100644 --- a/tests/template_tests/syntax_tests/test_cache.py +++ b/tests/template_tests/syntax_tests/test_cache.py @@ -100,16 +100,18 @@ class CacheTagTests(SimpleTestCase): """ Regression test for #11270. """ - output = self.engine.render_to_string('cache17', {'poem': 'Oh freddled gruntbuggly/' - 'Thy micturations are to me/' - 'As plurdled gabbleblotchits/' - 'On a lurgid bee/' - 'That mordiously hath bitled out/' - 'Its earted jurtles/' - 'Into a rancid festering/' - 'Or else I shall rend thee in the gobberwarts' - 'with my blurglecruncheon/' - 'See if I dont.'}) + output = self.engine.render_to_string( + 'cache17', + { + 'poem': ( + 'Oh freddled gruntbuggly/Thy micturations are to me/' + 'As plurdled gabbleblotchits/On a lurgid bee/' + 'That mordiously hath bitled out/Its earted jurtles/' + 'Into a rancid festering/Or else I shall rend thee in the gobberwarts' + 'with my blurglecruncheon/See if I dont.' + ), + } + ) self.assertEqual(output, 'Some Content') @setup({'cache18': '{% load cache custom %}{% cache 2|noop:"x y" cache18 %}cache18{% endcache %}'}) diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py index ff0b29073f..51dc9f248b 100644 --- a/tests/template_tests/tests.py +++ b/tests/template_tests/tests.py @@ -44,8 +44,7 @@ class TemplateTests(SimpleTestCase): while tb.tb_next is not None: tb = tb.tb_next depth += 1 - self.assertGreater(depth, 5, - "The traceback context was lost when reraising the traceback. See #19827") + self.assertGreater(depth, 5, "The traceback context was lost when reraising the traceback.") def test_no_wrapped_exception(self): """ diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index d7f33d90f7..b8d7c9963c 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -382,8 +382,7 @@ class AssertRedirectsTests(SimpleTestCase): def test_redirect_chain(self): "You can follow a redirect chain of multiple redirects" response = self.client.get('/redirects/further/more/', {}, follow=True) - self.assertRedirects(response, '/no_template_view/', - status_code=302, target_status_code=200) + self.assertRedirects(response, '/no_template_view/', status_code=302, target_status_code=200) self.assertEqual(len(response.redirect_chain), 1) self.assertEqual(response.redirect_chain[0], ('/no_template_view/', 302)) @@ -391,8 +390,7 @@ class AssertRedirectsTests(SimpleTestCase): def test_multiple_redirect_chain(self): "You can follow a redirect chain of multiple redirects" response = self.client.get('/redirects/', {}, follow=True) - self.assertRedirects(response, '/no_template_view/', - status_code=302, target_status_code=200) + self.assertRedirects(response, '/no_template_view/', status_code=302, target_status_code=200) self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(response.redirect_chain[0], ('/redirects/further/', 302)) @@ -402,8 +400,7 @@ class AssertRedirectsTests(SimpleTestCase): def test_redirect_chain_to_non_existent(self): "You can follow a chain to a non-existent view" response = self.client.get('/redirect_to_non_existent_view2/', {}, follow=True) - self.assertRedirects(response, '/non_existent_view/', - status_code=302, target_status_code=404) + self.assertRedirects(response, '/non_existent_view/', status_code=302, target_status_code=404) def test_redirect_chain_to_self(self): "Redirections to self are caught and escaped" @@ -411,8 +408,7 @@ class AssertRedirectsTests(SimpleTestCase): self.client.get('/redirect_to_self/', {}, follow=True) response = context.exception.last_response # The chain of redirects stops once the cycle is detected. - self.assertRedirects(response, '/redirect_to_self/', - status_code=302, target_status_code=302) + self.assertRedirects(response, '/redirect_to_self/', status_code=302, target_status_code=302) self.assertEqual(len(response.redirect_chain), 2) def test_redirect_to_self_with_changing_query(self): @@ -426,56 +422,46 @@ class AssertRedirectsTests(SimpleTestCase): self.client.get('/circular_redirect_1/', {}, follow=True) response = context.exception.last_response # The chain of redirects will get back to the starting point, but stop there. - self.assertRedirects(response, '/circular_redirect_2/', - status_code=302, target_status_code=302) + self.assertRedirects(response, '/circular_redirect_2/', status_code=302, target_status_code=302) self.assertEqual(len(response.redirect_chain), 4) def test_redirect_chain_post(self): "A redirect chain will be followed from an initial POST post" - response = self.client.post('/redirects/', - {'nothing': 'to_send'}, follow=True) - self.assertRedirects(response, - '/no_template_view/', 302, 200) + response = self.client.post('/redirects/', {'nothing': 'to_send'}, follow=True) + self.assertRedirects(response, '/no_template_view/', 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_head(self): "A redirect chain will be followed from an initial HEAD request" - response = self.client.head('/redirects/', - {'nothing': 'to_send'}, follow=True) - self.assertRedirects(response, - '/no_template_view/', 302, 200) + response = self.client.head('/redirects/', {'nothing': 'to_send'}, follow=True) + self.assertRedirects(response, '/no_template_view/', 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_options(self): "A redirect chain will be followed from an initial OPTIONS request" - response = self.client.options('/redirects/', - follow=True) - self.assertRedirects(response, - '/no_template_view/', 302, 200) + response = self.client.options('/redirects/', follow=True) + self.assertRedirects(response, '/no_template_view/', 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_put(self): "A redirect chain will be followed from an initial PUT request" - response = self.client.put('/redirects/', - follow=True) - self.assertRedirects(response, - '/no_template_view/', 302, 200) + response = self.client.put('/redirects/', follow=True) + self.assertRedirects(response, '/no_template_view/', 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_chain_delete(self): "A redirect chain will be followed from an initial DELETE request" - response = self.client.delete('/redirects/', - follow=True) - self.assertRedirects(response, - '/no_template_view/', 302, 200) + response = self.client.delete('/redirects/', follow=True) + self.assertRedirects(response, '/no_template_view/', 302, 200) self.assertEqual(len(response.redirect_chain), 3) def test_redirect_to_different_host(self): "The test client will preserve scheme, host and port changes" response = self.client.get('/redirect_other_host/', follow=True) - self.assertRedirects(response, - 'https://otherserver:8443/no_template_view/', - status_code=302, target_status_code=200) + self.assertRedirects( + response, 'https://otherserver:8443/no_template_view/', + status_code=302, target_status_code=200 + ) # We can't use is_secure() or get_host() # because response.request is a dictionary, not an HttpRequest self.assertEqual(response.request.get('wsgi.url_scheme'), 'https') @@ -715,152 +701,97 @@ class AssertFormsetErrorTests(SimpleTestCase): def test_unknown_formset(self): "An assertion is raised if the formset name is unknown" for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_form_errors, - 'wrong_formset', - 0, - 'Some_field', - 'Some error.', - **kwargs) - self.assertIn(prefix + "The formset 'wrong_formset' was not " - "used to render the response", - str(cm.exception)) + msg = prefix + "The formset 'wrong_formset' was not used to render the response" + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError( + self.response_form_errors, + 'wrong_formset', 0, 'Some_field', 'Some error.', **kwargs + ) def test_unknown_field(self): "An assertion is raised if the field name is unknown" for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - 0, - 'Some_field', - 'Some error.', - **kwargs) - self.assertIn(prefix + "The formset 'my_formset', " - "form 0 in context 0 " - "does not contain the field 'Some_field'", - str(cm.exception)) + msg = prefix + "The formset 'my_formset', form 0 in context 0 does not contain the field 'Some_field'" + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError( + self.response_form_errors, + 'my_formset', 0, 'Some_field', 'Some error.', **kwargs + ) def test_no_error_field(self): "An assertion is raised if the field doesn't have any errors" for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - 1, - 'value', - 'Some error.', - **kwargs) - self.assertIn(prefix + "The field 'value' " - "on formset 'my_formset', form 1 " - "in context 0 contains no errors", - str(cm.exception)) + msg = prefix + "The field 'value' on formset 'my_formset', form 1 in context 0 contains no errors" + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError(self.response_form_errors, 'my_formset', 1, 'value', 'Some error.', **kwargs) def test_unknown_error(self): "An assertion is raised if the field doesn't contain the specified error" for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - 0, - 'email', - 'Some error.', - **kwargs) - self.assertIn(str_prefix(prefix + "The field 'email' " - "on formset 'my_formset', form 0 in context 0 does not " - "contain the error 'Some error.' (actual errors: " - "[%(_)s'Enter a valid email address.'])"), - str(cm.exception)) + msg = str_prefix( + prefix + "The field 'email' on formset 'my_formset', form 0 " + "in context 0 does not contain the error 'Some error.' " + "(actual errors: [%(_)s'Enter a valid email address.'])" + ) + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError(self.response_form_errors, 'my_formset', 0, 'email', 'Some error.', **kwargs) def test_field_error(self): "No assertion is raised if the field contains the provided error" + error_msg = ['Enter a valid email address.'] for prefix, kwargs in self.msg_prefixes: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - 0, - 'email', - ['Enter a valid email address.'], - **kwargs) + self.assertFormsetError(self.response_form_errors, 'my_formset', 0, 'email', error_msg, **kwargs) def test_no_nonfield_error(self): "An assertion is raised if the formsets non-field errors doesn't contain any errors." for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - 1, - None, - 'Some error.', - **kwargs) - self.assertIn(prefix + "The formset 'my_formset', form 1 in " - "context 0 does not contain any " - "non-field errors.", - str(cm.exception)) + msg = prefix + "The formset 'my_formset', form 1 in context 0 does not contain any non-field errors." + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError(self.response_form_errors, 'my_formset', 1, None, 'Some error.', **kwargs) def test_unknown_nonfield_error(self): "An assertion is raised if the formsets non-field errors doesn't contain the provided error." for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - 0, - None, - 'Some error.', - **kwargs) - self.assertIn(str_prefix(prefix + - "The formset 'my_formset', form 0 in context 0 does not " + msg = str_prefix( + prefix + "The formset 'my_formset', form 0 in context 0 does not " "contain the non-field error 'Some error.' (actual errors: " - "[%(_)s'Non-field error.'])"), str(cm.exception)) + "[%(_)s'Non-field error.'])" + ) + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError(self.response_form_errors, 'my_formset', 0, None, 'Some error.', **kwargs) def test_nonfield_error(self): "No assertion is raised if the formsets non-field errors contains the provided error." for prefix, kwargs in self.msg_prefixes: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - 0, - None, - 'Non-field error.', - **kwargs) + self.assertFormsetError(self.response_form_errors, 'my_formset', 0, None, 'Non-field error.', **kwargs) def test_no_nonform_error(self): "An assertion is raised if the formsets non-form errors doesn't contain any errors." for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_form_errors, - 'my_formset', - None, - None, - 'Some error.', - **kwargs) - self.assertIn(prefix + "The formset 'my_formset' in context 0 " - "does not contain any non-form errors.", - str(cm.exception)) + msg = prefix + "The formset 'my_formset' in context 0 does not contain any non-form errors." + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError(self.response_form_errors, 'my_formset', None, None, 'Some error.', **kwargs) def test_unknown_nonform_error(self): "An assertion is raised if the formsets non-form errors doesn't contain the provided error." for prefix, kwargs in self.msg_prefixes: - with self.assertRaises(AssertionError) as cm: - self.assertFormsetError(self.response_nonform_errors, - 'my_formset', - None, - None, - 'Some error.', - **kwargs) - self.assertIn(str_prefix(prefix + + msg = str_prefix( + prefix + "The formset 'my_formset' in context 0 does not contain the " "non-form error 'Some error.' (actual errors: [%(_)s'Forms " - "in a set must have distinct email addresses.'])"), str(cm.exception)) + "in a set must have distinct email addresses.'])" + ) + with self.assertRaisesMessage(AssertionError, msg): + self.assertFormsetError( + self.response_nonform_errors, + 'my_formset', None, None, 'Some error.', **kwargs + ) def test_nonform_error(self): "No assertion is raised if the formsets non-form errors contains the provided error." + msg = 'Forms in a set must have distinct email addresses.' for prefix, kwargs in self.msg_prefixes: - self.assertFormsetError(self.response_nonform_errors, - 'my_formset', - None, - None, - 'Forms in a set must have distinct email ' - 'addresses.', - **kwargs) + self.assertFormsetError(self.response_nonform_errors, 'my_formset', None, None, msg, **kwargs) @override_settings(ROOT_URLCONF='test_client_regress.urls') @@ -1021,11 +952,9 @@ class ContextTests(TestDataMixin, TestCase): self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['data'], 'bacon') - try: + with self.assertRaises(KeyError) as cm: response.context['does-not-exist'] - self.fail('Should not be able to retrieve non-existent key') - except KeyError as e: - self.assertEqual(e.args[0], 'does-not-exist') + self.assertEqual(cm.exception.args[0], 'does-not-exist') def test_contextlist_keys(self): c1 = Context() @@ -1038,9 +967,7 @@ class ContextTests(TestDataMixin, TestCase): l = ContextList([c1, c2]) # None, True and False are builtins of BaseContext, and present # in every Context without needing to be added. - self.assertEqual({'None', 'True', 'False', 'hello', 'goodbye', - 'python', 'dolly'}, - l.keys()) + self.assertEqual({'None', 'True', 'False', 'hello', 'goodbye', 'python', 'dolly'}, l.keys()) def test_15368(self): # Need to insert a context processor that assumes certain things about @@ -1350,32 +1277,28 @@ class UnicodePayloadTests(SimpleTestCase): "A simple ASCII-only unicode JSON document can be POSTed" # Regression test for #10571 json = '{"english": "mountain pass"}' - response = self.client.post("/parse_unicode_json/", json, - content_type="application/json") + response = self.client.post("/parse_unicode_json/", json, content_type="application/json") self.assertEqual(response.content, json.encode()) def test_unicode_payload_utf8(self): "A non-ASCII unicode data encoded as UTF-8 can be POSTed" # Regression test for #10571 json = '{"dog": "собака"}' - response = self.client.post("/parse_unicode_json/", json, - content_type="application/json; charset=utf-8") + response = self.client.post("/parse_unicode_json/", json, content_type="application/json; charset=utf-8") self.assertEqual(response.content, json.encode('utf-8')) def test_unicode_payload_utf16(self): "A non-ASCII unicode data encoded as UTF-16 can be POSTed" # Regression test for #10571 json = '{"dog": "собака"}' - response = self.client.post("/parse_unicode_json/", json, - content_type="application/json; charset=utf-16") + response = self.client.post("/parse_unicode_json/", json, content_type="application/json; charset=utf-16") self.assertEqual(response.content, json.encode('utf-16')) def test_unicode_payload_non_utf(self): "A non-ASCII unicode data as a non-UTF based encoding can be POSTed" # Regression test for #10571 json = '{"dog": "собака"}' - response = self.client.post("/parse_unicode_json/", json, - content_type="application/json; charset=koi8-r") + response = self.client.post("/parse_unicode_json/", json, content_type="application/json; charset=koi8-r") self.assertEqual(response.content, json.encode('koi8-r')) @@ -1420,8 +1343,7 @@ class RequestHeadersTest(SimpleTestCase): "Test client headers are preserved through redirects" response = self.client.get("/check_headers_redirect/", follow=True, HTTP_X_ARG_CHECK='Testing 123') self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123") - self.assertRedirects(response, '/check_headers/', - status_code=302, target_status_code=200) + self.assertRedirects(response, '/check_headers/', status_code=302, target_status_code=200) @override_settings(ROOT_URLCONF='test_client_regress.urls') @@ -1452,19 +1374,13 @@ class ReadLimitedStreamTest(SimpleTestCase): """HttpRequest.read() on a test client PUT request with some payload should return that payload.""" payload = b'foobar' - self.assertEqual(self.client.put( - "/read_all/", - data=payload, - content_type='text/plain').content, payload) + self.assertEqual(self.client.put("/read_all/", data=payload, content_type='text/plain').content, payload) def test_read_numbytes_from_nonempty_request(self): """HttpRequest.read(LARGE_BUFFER) on a test client PUT request with some payload should return that payload.""" payload = b'foobar' - self.assertEqual( - self.client.put("/read_buffer/", - data=payload, - content_type='text/plain').content, payload) + self.assertEqual(self.client.put("/read_buffer/", data=payload, content_type='text/plain').content, payload) @override_settings(ROOT_URLCONF='test_client_regress.urls') @@ -1508,5 +1424,4 @@ class RequestFactoryEnvironmentTests(SimpleTestCase): self.assertEqual(request.META.get('SERVER_NAME'), 'testserver') self.assertEqual(request.META.get('SERVER_PORT'), '80') self.assertEqual(request.META.get('SERVER_PROTOCOL'), 'HTTP/1.1') - self.assertEqual(request.META.get('SCRIPT_NAME') + - request.META.get('PATH_INFO'), '/path/') + self.assertEqual(request.META.get('SCRIPT_NAME') + request.META.get('PATH_INFO'), '/path/') diff --git a/tests/test_runner/runner.py b/tests/test_runner/runner.py index ec79395663..e61de58a93 100644 --- a/tests/test_runner/runner.py +++ b/tests/test_runner/runner.py @@ -4,9 +4,10 @@ from django.test.runner import DiscoverRunner class CustomOptionsTestRunner(DiscoverRunner): def __init__(self, verbosity=1, interactive=True, failfast=True, - option_a=None, option_b=None, option_c=None, **kwargs): - super(CustomOptionsTestRunner, self).__init__(verbosity=verbosity, interactive=interactive, - failfast=failfast) + option_a=None, option_b=None, option_c=None, **kwargs): + super(CustomOptionsTestRunner, self).__init__( + verbosity=verbosity, interactive=interactive, failfast=failfast, + ) self.option_a = option_a self.option_b = option_b self.option_c = option_c diff --git a/tests/test_runner/tests.py b/tests/test_runner/tests.py index a35c26628b..fd0b895789 100644 --- a/tests/test_runner/tests.py +++ b/tests/test_runner/tests.py @@ -146,8 +146,7 @@ class ManageCommandTests(unittest.TestCase): def test_bad_test_runner(self): with self.assertRaises(AttributeError): - call_command('test', 'sites', - testrunner='test_runner.NonExistentRunner') + call_command('test', 'sites', testrunner='test_runner.NonExistentRunner') class CustomTestRunnerOptionsTests(AdminScriptTestCase): diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index c4d51833f4..fd552ad9c2 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -440,8 +440,10 @@ class HTMLEqualTests(SimpleTestCase): self.assertEqual(dom.children[0], "

    foo

    '' bar") def test_self_closing_tags(self): - self_closing_tags = ('br', 'hr', 'input', 'img', 'meta', 'spacer', - 'link', 'frame', 'base', 'col') + self_closing_tags = ( + 'br', 'hr', 'input', 'img', 'meta', 'spacer', 'link', 'frame', + 'base', 'col', + ) for tag in self_closing_tags: dom = parse_html('

    Hello <%s> world

    ' % tag) self.assertEqual(len(dom.children), 3) diff --git a/tests/timezones/tests.py b/tests/timezones/tests.py index e803927d36..dce48f6eae 100644 --- a/tests/timezones/tests.py +++ b/tests/timezones/tests.py @@ -692,8 +692,7 @@ class SerializationTests(SimpleTestCase): def assert_yaml_contains_datetime(self, yaml, dt): # Depending on the yaml dumper, '!timestamp' might be absent - six.assertRegex(self, yaml, - r"\n fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt)) + six.assertRegex(self, yaml, r"\n fields: {dt: !(!timestamp)? '%s'}" % re.escape(dt)) def test_naive_datetime(self): dt = datetime.datetime(2011, 9, 1, 13, 20, 30) @@ -1162,18 +1161,24 @@ class NewFormsTests(TestCase): with timezone.override(pytz.timezone('Europe/Paris')): form = EventForm({'dt': '2011-03-27 02:30:00'}) self.assertFalse(form.is_valid()) - self.assertEqual(form.errors['dt'], - ["2011-03-27 02:30:00 couldn't be interpreted in time zone " - "Europe/Paris; it may be ambiguous or it may not exist."]) + self.assertEqual( + form.errors['dt'], [ + "2011-03-27 02:30:00 couldn't be interpreted in time zone " + "Europe/Paris; it may be ambiguous or it may not exist." + ] + ) @requires_pytz def test_form_with_ambiguous_time(self): with timezone.override(pytz.timezone('Europe/Paris')): form = EventForm({'dt': '2011-10-30 02:30:00'}) self.assertFalse(form.is_valid()) - self.assertEqual(form.errors['dt'], - ["2011-10-30 02:30:00 couldn't be interpreted in time zone " - "Europe/Paris; it may be ambiguous or it may not exist."]) + self.assertEqual( + form.errors['dt'], [ + "2011-10-30 02:30:00 couldn't be interpreted in time zone " + "Europe/Paris; it may be ambiguous or it may not exist." + ] + ) @requires_tz_support def test_split_form(self): diff --git a/tests/transactions/tests.py b/tests/transactions/tests.py index b9faed1c62..5e947de65f 100644 --- a/tests/transactions/tests.py +++ b/tests/transactions/tests.py @@ -16,8 +16,7 @@ from django.test import ( from .models import Reporter -@skipUnless(connection.features.uses_savepoints, - "'atomic' requires transactions and savepoints.") +@skipUnless(connection.features.uses_savepoints, "'atomic' requires transactions and savepoints.") class AtomicTests(TransactionTestCase): """ Tests for the atomic decorator and context manager. @@ -81,8 +80,10 @@ class AtomicTests(TransactionTestCase): Reporter.objects.create(first_name="Tintin") with transaction.atomic(): Reporter.objects.create(first_name="Archibald", last_name="Haddock") - self.assertQuerysetEqual(Reporter.objects.all(), - ['', '']) + self.assertQuerysetEqual( + Reporter.objects.all(), + ['', ''] + ) def test_nested_commit_rollback(self): with transaction.atomic(): @@ -118,8 +119,10 @@ class AtomicTests(TransactionTestCase): Reporter.objects.create(first_name="Tintin") with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Archibald", last_name="Haddock") - self.assertQuerysetEqual(Reporter.objects.all(), - ['', '']) + self.assertQuerysetEqual( + Reporter.objects.all(), + ['', ''] + ) def test_merged_commit_rollback(self): with transaction.atomic(): @@ -157,8 +160,7 @@ class AtomicTests(TransactionTestCase): Reporter.objects.create(first_name="Tintin") with atomic: Reporter.objects.create(first_name="Archibald", last_name="Haddock") - self.assertQuerysetEqual(Reporter.objects.all(), - ['', '']) + self.assertQuerysetEqual(Reporter.objects.all(), ['', '']) def test_reuse_commit_rollback(self): atomic = transaction.atomic() @@ -228,8 +230,10 @@ class AtomicInsideTransactionTests(AtomicTests): self.atomic.__exit__(*sys.exc_info()) -@skipIf(connection.features.autocommits_when_autocommit_is_off, - "This test requires a non-autocommit mode that doesn't autocommit.") +@skipIf( + connection.features.autocommits_when_autocommit_is_off, + "This test requires a non-autocommit mode that doesn't autocommit." +) class AtomicWithoutAutocommitTests(AtomicTests): """All basic tests for atomic should also pass when autocommit is turned off.""" @@ -243,8 +247,7 @@ class AtomicWithoutAutocommitTests(AtomicTests): transaction.set_autocommit(True) -@skipUnless(connection.features.uses_savepoints, - "'atomic' requires transactions and savepoints.") +@skipUnless(connection.features.uses_savepoints, "'atomic' requires transactions and savepoints.") class AtomicMergeTests(TransactionTestCase): """Test merging transactions with savepoint=False.""" @@ -294,8 +297,7 @@ class AtomicMergeTests(TransactionTestCase): self.assertQuerysetEqual(Reporter.objects.all(), ['']) -@skipUnless(connection.features.uses_savepoints, - "'atomic' requires transactions and savepoints.") +@skipUnless(connection.features.uses_savepoints, "'atomic' requires transactions and savepoints.") class AtomicErrorsTests(TransactionTestCase): available_apps = ['transactions'] diff --git a/tests/update_only_fields/tests.py b/tests/update_only_fields/tests.py index c2ff8e1089..172cd64f5d 100644 --- a/tests/update_only_fields/tests.py +++ b/tests/update_only_fields/tests.py @@ -80,20 +80,17 @@ class UpdateOnlyFieldsTests(TestCase): def test_update_fields_inheritance_defer(self): profile_boss = Profile.objects.create(name='Boss', salary=3000) - e1 = Employee.objects.create(name='Sara', gender='F', - employee_num=1, profile=profile_boss) + e1 = Employee.objects.create(name='Sara', gender='F', employee_num=1, profile=profile_boss) e1 = Employee.objects.only('name').get(pk=e1.pk) e1.name = 'Linda' with self.assertNumQueries(1): e1.save() - self.assertEqual(Employee.objects.get(pk=e1.pk).name, - 'Linda') + self.assertEqual(Employee.objects.get(pk=e1.pk).name, 'Linda') def test_update_fields_fk_defer(self): profile_boss = Profile.objects.create(name='Boss', salary=3000) profile_receptionist = Profile.objects.create(name='Receptionist', salary=1000) - e1 = Employee.objects.create(name='Sara', gender='F', - employee_num=1, profile=profile_boss) + e1 = Employee.objects.create(name='Sara', gender='F', employee_num=1, profile=profile_boss) e1 = Employee.objects.only('profile').get(pk=e1.pk) e1.profile = profile_receptionist with self.assertNumQueries(1): @@ -106,8 +103,7 @@ class UpdateOnlyFieldsTests(TestCase): def test_select_related_only_interaction(self): profile_boss = Profile.objects.create(name='Boss', salary=3000) - e1 = Employee.objects.create(name='Sara', gender='F', - employee_num=1, profile=profile_boss) + e1 = Employee.objects.create(name='Sara', gender='F', employee_num=1, profile=profile_boss) e1 = Employee.objects.only('profile__salary').select_related('profile').get(pk=e1.pk) profile_boss.name = 'Clerk' profile_boss.salary = 1000 @@ -122,8 +118,7 @@ class UpdateOnlyFieldsTests(TestCase): def test_update_fields_m2m(self): profile_boss = Profile.objects.create(name='Boss', salary=3000) - e1 = Employee.objects.create(name='Sara', gender='F', - employee_num=1, profile=profile_boss) + e1 = Employee.objects.create(name='Sara', gender='F', employee_num=1, profile=profile_boss) a1 = Account.objects.create(num=1) a2 = Account.objects.create(num=2) e1.accounts.set([a1, a2]) @@ -134,9 +129,7 @@ class UpdateOnlyFieldsTests(TestCase): def test_update_fields_inheritance(self): profile_boss = Profile.objects.create(name='Boss', salary=3000) profile_receptionist = Profile.objects.create(name='Receptionist', salary=1000) - - e1 = Employee.objects.create(name='Sara', gender='F', - employee_num=1, profile=profile_boss) + e1 = Employee.objects.create(name='Sara', gender='F', employee_num=1, profile=profile_boss) e1.name = 'Ian' e1.gender = 'M' @@ -166,9 +159,7 @@ class UpdateOnlyFieldsTests(TestCase): def test_update_fields_inheritance_with_proxy_model(self): profile_boss = Profile.objects.create(name='Boss', salary=3000) profile_receptionist = Profile.objects.create(name='Receptionist', salary=1000) - - e1 = ProxyEmployee.objects.create(name='Sara', gender='F', - employee_num=1, profile=profile_boss) + e1 = ProxyEmployee.objects.create(name='Sara', gender='F', employee_num=1, profile=profile_boss) e1.name = 'Ian' e1.gender = 'M' diff --git a/tests/user_commands/management/commands/hal.py b/tests/user_commands/management/commands/hal.py index c7ea51c9e5..055f441ab4 100644 --- a/tests/user_commands/management/commands/hal.py +++ b/tests/user_commands/management/commands/hal.py @@ -5,10 +5,8 @@ class Command(BaseCommand): help = "Useless command." def add_arguments(self, parser): - parser.add_argument('args', metavar='app_label', nargs='*', - help='Specify the app label(s) to works on.') - parser.add_argument('--empty', action='store_true', dest='empty', default=False, - help="Do nothing.") + parser.add_argument('args', metavar='app_label', nargs='*', help='Specify the app label(s) to works on.') + parser.add_argument('--empty', action='store_true', dest='empty', default=False, help="Do nothing.") def handle(self, *app_labels, **options): app_labels = set(app_labels) diff --git a/tests/utils_tests/test_dateparse.py b/tests/utils_tests/test_dateparse.py index f0585187fc..bf740a9cc5 100644 --- a/tests/utils_tests/test_dateparse.py +++ b/tests/utils_tests/test_dateparse.py @@ -33,20 +33,34 @@ class DateParseTests(unittest.TestCase): def test_parse_datetime(self): # Valid inputs - self.assertEqual(parse_datetime('2012-04-23T09:15:00'), - datetime(2012, 4, 23, 9, 15)) - self.assertEqual(parse_datetime('2012-4-9 4:8:16'), - datetime(2012, 4, 9, 4, 8, 16)) - self.assertEqual(parse_datetime('2012-04-23T09:15:00Z'), - datetime(2012, 4, 23, 9, 15, 0, 0, get_fixed_timezone(0))) - self.assertEqual(parse_datetime('2012-4-9 4:8:16-0320'), - datetime(2012, 4, 9, 4, 8, 16, 0, get_fixed_timezone(-200))) - self.assertEqual(parse_datetime('2012-04-23T10:20:30.400+02:30'), - datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150))) - self.assertEqual(parse_datetime('2012-04-23T10:20:30.400+02'), - datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(120))) - self.assertEqual(parse_datetime('2012-04-23T10:20:30.400-02'), - datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120))) + self.assertEqual( + parse_datetime('2012-04-23T09:15:00'), + datetime(2012, 4, 23, 9, 15) + ) + self.assertEqual( + parse_datetime('2012-4-9 4:8:16'), + datetime(2012, 4, 9, 4, 8, 16) + ) + self.assertEqual( + parse_datetime('2012-04-23T09:15:00Z'), + datetime(2012, 4, 23, 9, 15, 0, 0, get_fixed_timezone(0)) + ) + self.assertEqual( + parse_datetime('2012-4-9 4:8:16-0320'), + datetime(2012, 4, 9, 4, 8, 16, 0, get_fixed_timezone(-200)) + ) + self.assertEqual( + parse_datetime('2012-04-23T10:20:30.400+02:30'), + datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(150)) + ) + self.assertEqual( + parse_datetime('2012-04-23T10:20:30.400+02'), + datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(120)) + ) + self.assertEqual( + parse_datetime('2012-04-23T10:20:30.400-02'), + datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)) + ) # Invalid inputs self.assertEqual(parse_datetime('20120423091500'), None) with self.assertRaises(ValueError): diff --git a/tests/utils_tests/test_encoding.py b/tests/utils_tests/test_encoding.py index 49fe33669f..5ddb18d069 100644 --- a/tests/utils_tests/test_encoding.py +++ b/tests/utils_tests/test_encoding.py @@ -80,10 +80,11 @@ class TestEncodingUtils(unittest.TestCase): class TestRFC3987IEncodingUtils(unittest.TestCase): def test_filepath_to_uri(self): - self.assertEqual(filepath_to_uri('upload\\чубака.mp4'), - 'upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4') - self.assertEqual(filepath_to_uri('upload\\чубака.mp4'.encode('utf-8')), - 'upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4') + self.assertEqual(filepath_to_uri('upload\\чубака.mp4'), 'upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4') + self.assertEqual( + filepath_to_uri('upload\\чубака.mp4'.encode('utf-8')), + 'upload/%D1%87%D1%83%D0%B1%D0%B0%D0%BA%D0%B0.mp4' + ) def test_iri_to_uri(self): cases = [ diff --git a/tests/utils_tests/test_http.py b/tests/utils_tests/test_http.py index 8f93c472a7..e22f76be2e 100644 --- a/tests/utils_tests/test_http.py +++ b/tests/utils_tests/test_http.py @@ -78,42 +78,49 @@ class TestUtilsHttp(unittest.TestCase): self.assertEqual(http.base36_to_int(b36), n) def test_is_safe_url(self): - for bad_url in ('http://example.com', - 'http:///example.com', - 'https://example.com', - 'ftp://example.com', - r'\\example.com', - r'\\\example.com', - r'/\\/example.com', - r'\\\example.com', - r'\\example.com', - r'\\//example.com', - r'/\/example.com', - r'\/example.com', - r'/\example.com', - 'http:///example.com', - 'http:/\//example.com', - 'http:\/example.com', - 'http:/\example.com', - 'javascript:alert("XSS")', - '\njavascript:alert(x)', - '\x08//example.com', - r'http://otherserver\@example.com', - r'http:\\testserver\@example.com', - r'http://testserver\me:pass@example.com', - r'http://testserver\@example.com', - r'http:\\testserver\confirm\me@example.com', - '\n'): + bad_urls = ( + 'http://example.com', + 'http:///example.com', + 'https://example.com', + 'ftp://example.com', + r'\\example.com', + r'\\\example.com', + r'/\\/example.com', + r'\\\example.com', + r'\\example.com', + r'\\//example.com', + r'/\/example.com', + r'\/example.com', + r'/\example.com', + 'http:///example.com', + 'http:/\//example.com', + 'http:\/example.com', + 'http:/\example.com', + 'javascript:alert("XSS")', + '\njavascript:alert(x)', + '\x08//example.com', + r'http://otherserver\@example.com', + r'http:\\testserver\@example.com', + r'http://testserver\me:pass@example.com', + r'http://testserver\@example.com', + r'http:\\testserver\confirm\me@example.com', + '\n', + ) + for bad_url in bad_urls: self.assertFalse(http.is_safe_url(bad_url, host='testserver'), "%s should be blocked" % bad_url) - for good_url in ('/view/?param=http://example.com', - '/view/?param=https://example.com', - '/view?param=ftp://example.com', - 'view/?param=//example.com', - 'https://testserver/', - 'HTTPS://testserver/', - '//testserver/', - 'http://testserver/confirm?email=me@example.com', - '/url%20with%20spaces/'): + + good_urls = ( + '/view/?param=http://example.com', + '/view/?param=https://example.com', + '/view?param=ftp://example.com', + 'view/?param=//example.com', + 'https://testserver/', + 'HTTPS://testserver/', + '//testserver/', + 'http://testserver/confirm?email=me@example.com', + '/url%20with%20spaces/', + ) + for good_url in good_urls: self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s should be allowed" % good_url) if six.PY2: @@ -140,26 +147,14 @@ class TestUtilsHttp(unittest.TestCase): self.assertEqual(bytestring, decoded) def test_urlquote(self): - self.assertEqual(http.urlquote('Paris & Orl\xe9ans'), - 'Paris%20%26%20Orl%C3%A9ans') - self.assertEqual(http.urlquote('Paris & Orl\xe9ans', safe="&"), - 'Paris%20&%20Orl%C3%A9ans') - self.assertEqual( - http.urlunquote('Paris%20%26%20Orl%C3%A9ans'), - 'Paris & Orl\xe9ans') - self.assertEqual( - http.urlunquote('Paris%20&%20Orl%C3%A9ans'), - 'Paris & Orl\xe9ans') - self.assertEqual(http.urlquote_plus('Paris & Orl\xe9ans'), - 'Paris+%26+Orl%C3%A9ans') - self.assertEqual(http.urlquote_plus('Paris & Orl\xe9ans', safe="&"), - 'Paris+&+Orl%C3%A9ans') - self.assertEqual( - http.urlunquote_plus('Paris+%26+Orl%C3%A9ans'), - 'Paris & Orl\xe9ans') - self.assertEqual( - http.urlunquote_plus('Paris+&+Orl%C3%A9ans'), - 'Paris & Orl\xe9ans') + self.assertEqual(http.urlquote('Paris & Orl\xe9ans'), 'Paris%20%26%20Orl%C3%A9ans') + self.assertEqual(http.urlquote('Paris & Orl\xe9ans', safe="&"), 'Paris%20&%20Orl%C3%A9ans') + self.assertEqual(http.urlunquote('Paris%20%26%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans') + self.assertEqual(http.urlunquote('Paris%20&%20Orl%C3%A9ans'), 'Paris & Orl\xe9ans') + self.assertEqual(http.urlquote_plus('Paris & Orl\xe9ans'), 'Paris+%26+Orl%C3%A9ans') + self.assertEqual(http.urlquote_plus('Paris & Orl\xe9ans', safe="&"), 'Paris+&+Orl%C3%A9ans') + self.assertEqual(http.urlunquote_plus('Paris+%26+Orl%C3%A9ans'), 'Paris & Orl\xe9ans') + self.assertEqual(http.urlunquote_plus('Paris+&+Orl%C3%A9ans'), 'Paris & Orl\xe9ans') def test_is_same_domain_good(self): for pair in ( @@ -204,15 +199,12 @@ class HttpDateProcessingTests(unittest.TestCase): def test_parsing_rfc1123(self): parsed = http.parse_http_date('Sun, 06 Nov 1994 08:49:37 GMT') - self.assertEqual(datetime.utcfromtimestamp(parsed), - datetime(1994, 11, 6, 8, 49, 37)) + self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) def test_parsing_rfc850(self): parsed = http.parse_http_date('Sunday, 06-Nov-94 08:49:37 GMT') - self.assertEqual(datetime.utcfromtimestamp(parsed), - datetime(1994, 11, 6, 8, 49, 37)) + self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) def test_parsing_asctime(self): parsed = http.parse_http_date('Sun Nov 6 08:49:37 1994') - self.assertEqual(datetime.utcfromtimestamp(parsed), - datetime(1994, 11, 6, 8, 49, 37)) + self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1994, 11, 6, 8, 49, 37)) diff --git a/tests/utils_tests/test_termcolors.py b/tests/utils_tests/test_termcolors.py index 6e1aa50124..08e4ae5f5a 100644 --- a/tests/utils_tests/test_termcolors.py +++ b/tests/utils_tests/test_termcolors.py @@ -17,45 +17,63 @@ class TermColorTests(unittest.TestCase): self.assertEqual(parse_color_setting('nocolor'), None) def test_fg(self): - self.assertEqual(parse_color_setting('error=green'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) + self.assertEqual( + parse_color_setting('error=green'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) def test_fg_bg(self): - self.assertEqual(parse_color_setting('error=green/blue'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'})) + self.assertEqual( + parse_color_setting('error=green/blue'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'}) + ) def test_fg_opts(self): - self.assertEqual(parse_color_setting('error=green,blink'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)})) - - self.assertEqual(parse_color_setting('error=green,bold,blink'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink', 'bold')})) + self.assertEqual( + parse_color_setting('error=green,blink'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)}) + ) + self.assertEqual( + parse_color_setting('error=green,bold,blink'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink', 'bold')}) + ) def test_fg_bg_opts(self): - self.assertEqual(parse_color_setting('error=green/blue,blink'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink',)})) - - self.assertEqual(parse_color_setting('error=green/blue,bold,blink'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink', 'bold')})) + self.assertEqual( + parse_color_setting('error=green/blue,blink'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink',)}) + ) + self.assertEqual( + parse_color_setting('error=green/blue,bold,blink'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink', 'bold')}) + ) def test_override_palette(self): - self.assertEqual(parse_color_setting('light;error=green'), - dict(PALETTES[LIGHT_PALETTE], ERROR={'fg': 'green'})) + self.assertEqual( + parse_color_setting('light;error=green'), + dict(PALETTES[LIGHT_PALETTE], ERROR={'fg': 'green'}) + ) def test_override_nocolor(self): - self.assertEqual(parse_color_setting('nocolor;error=green'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) + self.assertEqual( + parse_color_setting('nocolor;error=green'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) def test_reverse_override(self): self.assertEqual(parse_color_setting('error=green;light'), PALETTES[LIGHT_PALETTE]) def test_multiple_roles(self): - self.assertEqual(parse_color_setting('error=green;sql_field=blue'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}, SQL_FIELD={'fg': 'blue'})) + self.assertEqual( + parse_color_setting('error=green;sql_field=blue'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}, SQL_FIELD={'fg': 'blue'}) + ) def test_override_with_multiple_roles(self): - self.assertEqual(parse_color_setting('light;error=green;sql_field=blue'), - dict(PALETTES[LIGHT_PALETTE], ERROR={'fg': 'green'}, SQL_FIELD={'fg': 'blue'})) + self.assertEqual( + parse_color_setting('light;error=green;sql_field=blue'), + dict(PALETTES[LIGHT_PALETTE], ERROR={'fg': 'green'}, SQL_FIELD={'fg': 'blue'}) + ) def test_empty_definition(self): self.assertEqual(parse_color_setting(';'), None) @@ -63,14 +81,18 @@ class TermColorTests(unittest.TestCase): self.assertEqual(parse_color_setting(';;;'), None) def test_empty_options(self): - self.assertEqual(parse_color_setting('error=green,'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) - - self.assertEqual(parse_color_setting('error=green,,,'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) - - self.assertEqual(parse_color_setting('error=green,,blink,,'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)})) + self.assertEqual( + parse_color_setting('error=green,'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) + self.assertEqual( + parse_color_setting('error=green,,,'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) + self.assertEqual( + parse_color_setting('error=green,,blink,,'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)}) + ) def test_bad_palette(self): self.assertEqual(parse_color_setting('unknown'), None) @@ -78,60 +100,82 @@ class TermColorTests(unittest.TestCase): def test_bad_role(self): self.assertEqual(parse_color_setting('unknown='), None) self.assertEqual(parse_color_setting('unknown=green'), None) - self.assertEqual(parse_color_setting('unknown=green;sql_field=blue'), - dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'})) + self.assertEqual( + parse_color_setting('unknown=green;sql_field=blue'), + dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'}) + ) def test_bad_color(self): self.assertEqual(parse_color_setting('error='), None) - self.assertEqual(parse_color_setting('error=;sql_field=blue'), - dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'})) - + self.assertEqual( + parse_color_setting('error=;sql_field=blue'), + dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'}) + ) self.assertEqual(parse_color_setting('error=unknown'), None) - self.assertEqual(parse_color_setting('error=unknown;sql_field=blue'), - dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'})) - - self.assertEqual(parse_color_setting('error=green/unknown'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) - - self.assertEqual(parse_color_setting('error=green/blue/something'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'})) - - self.assertEqual(parse_color_setting('error=green/blue/something,blink'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink',)})) + self.assertEqual( + parse_color_setting('error=unknown;sql_field=blue'), + dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'}) + ) + self.assertEqual( + parse_color_setting('error=green/unknown'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) + self.assertEqual( + parse_color_setting('error=green/blue/something'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'}) + ) + self.assertEqual( + parse_color_setting('error=green/blue/something,blink'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink',)}) + ) def test_bad_option(self): - self.assertEqual(parse_color_setting('error=green,unknown'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) - - self.assertEqual(parse_color_setting('error=green,unknown,blink'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)})) + self.assertEqual( + parse_color_setting('error=green,unknown'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) + self.assertEqual( + parse_color_setting('error=green,unknown,blink'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)}) + ) def test_role_case(self): - self.assertEqual(parse_color_setting('ERROR=green'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) - - self.assertEqual(parse_color_setting('eRrOr=green'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) + self.assertEqual( + parse_color_setting('ERROR=green'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) + self.assertEqual( + parse_color_setting('eRrOr=green'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) def test_color_case(self): - self.assertEqual(parse_color_setting('error=GREEN'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) - - self.assertEqual(parse_color_setting('error=GREEN/BLUE'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'})) - - self.assertEqual(parse_color_setting('error=gReEn'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'})) - - self.assertEqual(parse_color_setting('error=gReEn/bLuE'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'})) + self.assertEqual( + parse_color_setting('error=GREEN'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) + self.assertEqual( + parse_color_setting('error=GREEN/BLUE'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'}) + ) + self.assertEqual( + parse_color_setting('error=gReEn'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green'}) + ) + self.assertEqual( + parse_color_setting('error=gReEn/bLuE'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'bg': 'blue'}) + ) def test_opts_case(self): - self.assertEqual(parse_color_setting('error=green,BLINK'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)})) - - self.assertEqual(parse_color_setting('error=green,bLiNk'), - dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)})) + self.assertEqual( + parse_color_setting('error=green,BLINK'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)}) + ) + self.assertEqual( + parse_color_setting('error=green,bLiNk'), + dict(PALETTES[NOCOLOR_PALETTE], ERROR={'fg': 'green', 'opts': ('blink',)}) + ) def test_colorize_empty_text(self): self.assertEqual(colorize(text=None), '\x1b[m\x1b[0m') diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py index 5d97844800..df4c055503 100644 --- a/tests/utils_tests/test_text.py +++ b/tests/utils_tests/test_text.py @@ -58,12 +58,9 @@ class TestUtilsText(SimpleTestCase): truncator = text.Truncator( 'The quick brown fox jumped over the lazy dog.' ) - self.assertEqual('The quick brown fox jumped over the lazy dog.', - truncator.chars(100)), - self.assertEqual('The quick brown fox ...', - truncator.chars(23)), - self.assertEqual('The quick brown fo.....', - truncator.chars(23, '.....')), + self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.chars(100)), + self.assertEqual('The quick brown fox ...', truncator.chars(23)), + self.assertEqual('The quick brown fo.....', truncator.chars(23, '.....')), # Ensure that we normalize our unicode data first nfc = text.Truncator('o\xfco\xfco\xfco\xfc') @@ -94,53 +91,55 @@ class TestUtilsText(SimpleTestCase): self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...') def test_truncate_words(self): - truncator = text.Truncator('The quick brown fox jumped over the lazy ' - 'dog.') - self.assertEqual('The quick brown fox jumped over the lazy dog.', - truncator.words(10)) + truncator = text.Truncator('The quick brown fox jumped over the lazy dog.') + self.assertEqual('The quick brown fox jumped over the lazy dog.', truncator.words(10)) self.assertEqual('The quick brown fox...', truncator.words(4)) - self.assertEqual('The quick brown fox[snip]', - truncator.words(4, '[snip]')) + self.assertEqual('The quick brown fox[snip]', truncator.words(4, '[snip]')) # Ensure that lazy strings are handled correctly truncator = text.Truncator(lazystr('The quick brown fox jumped over the lazy dog.')) self.assertEqual('The quick brown fox...', truncator.words(4)) def test_truncate_html_words(self): - truncator = text.Truncator('

    The quick brown fox' - ' jumped over the lazy dog.

    ') - self.assertEqual('

    The quick brown fox jumped over' - ' the lazy dog.

    ', truncator.words(10, html=True)) - self.assertEqual('

    The quick brown fox...' - '

    ', truncator.words(4, html=True)) - self.assertEqual('

    The quick brown fox....' - '

    ', truncator.words(4, '....', html=True)) - self.assertEqual('

    The quick brown fox' - '

    ', truncator.words(4, '', html=True)) + truncator = text.Truncator( + '

    The quick brown fox jumped over the lazy dog.

    ' + ) + self.assertEqual( + '

    The quick brown fox jumped over the lazy dog.

    ', + truncator.words(10, html=True) + ) + self.assertEqual( + '

    The quick brown fox...

    ', + truncator.words(4, html=True) + ) + self.assertEqual( + '

    The quick brown fox....

    ', + truncator.words(4, '....', html=True) + ) + self.assertEqual( + '

    The quick brown fox

    ', + truncator.words(4, '', html=True) + ) # Test with new line inside tag - truncator = text.Truncator('

    The quick brown fox jumped over the lazy dog.

    ') - self.assertEqual('

    The quick brown...

    ', truncator.words(3, '...', html=True)) + truncator = text.Truncator( + '

    The quick brown fox jumped over the lazy dog.

    ' + ) + self.assertEqual( + '

    The quick brown...

    ', + truncator.words(3, '...', html=True) + ) # Test self-closing tags - truncator = text.Truncator('
    The
    quick brown fox jumped over' - ' the lazy dog.') - self.assertEqual('
    The
    quick brown...', - truncator.words(3, '...', html=True)) - truncator = text.Truncator('
    The
    quick brown fox ' - 'jumped over the lazy dog.') - self.assertEqual('
    The
    quick brown...', - truncator.words(3, '...', html=True)) + truncator = text.Truncator('
    The
    quick brown fox jumped over the lazy dog.') + self.assertEqual('
    The
    quick brown...', truncator.words(3, '...', html=True)) + truncator = text.Truncator('
    The
    quick brown fox jumped over the lazy dog.') + self.assertEqual('
    The
    quick brown...', truncator.words(3, '...', html=True)) # Test html entities - truncator = text.Truncator('Buenos días!' - ' ¿Cómo está?') - self.assertEqual('Buenos días! ¿Cómo...', - truncator.words(3, '...', html=True)) + truncator = text.Truncator('Buenos días! ¿Cómo está?') + self.assertEqual('Buenos días! ¿Cómo...', truncator.words(3, '...', html=True)) truncator = text.Truncator('

    I <3 python, what about you?

    ') - self.assertEqual('

    I <3 python...

    ', - truncator.words(3, '...', html=True)) + self.assertEqual('

    I <3 python...

    ', truncator.words(3, '...', html=True)) def test_wrap(self): digits = '1234 67 9' @@ -148,21 +147,16 @@ class TestUtilsText(SimpleTestCase): self.assertEqual(text.wrap(digits, 9), '1234 67 9') self.assertEqual(text.wrap(digits, 8), '1234 67\n9') - self.assertEqual(text.wrap('short\na long line', 7), - 'short\na long\nline') - - self.assertEqual(text.wrap('do-not-break-long-words please? ok', 8), - 'do-not-break-long-words\nplease?\nok') + self.assertEqual(text.wrap('short\na long line', 7), 'short\na long\nline') + self.assertEqual(text.wrap('do-not-break-long-words please? ok', 8), 'do-not-break-long-words\nplease?\nok') long_word = 'l%sng' % ('o' * 20) self.assertEqual(text.wrap(long_word, 20), long_word) - self.assertEqual(text.wrap('a %s word' % long_word, 10), - 'a\n%s\nword' % long_word) + self.assertEqual(text.wrap('a %s word' % long_word, 10), 'a\n%s\nword' % long_word) self.assertEqual(text.wrap(lazystr(digits), 100), '1234 67 9') def test_normalize_newlines(self): - self.assertEqual(text.normalize_newlines("abc\ndef\rghi\r\n"), - "abc\ndef\nghi\n") + self.assertEqual(text.normalize_newlines("abc\ndef\rghi\r\n"), "abc\ndef\nghi\n") self.assertEqual(text.normalize_newlines("\n\r\r\n\r"), "\n\n\n\n") self.assertEqual(text.normalize_newlines("abcdefghi"), "abcdefghi") self.assertEqual(text.normalize_newlines(""), "") diff --git a/tests/utils_tests/test_timesince.py b/tests/utils_tests/test_timesince.py index ea1064f902..a410032acf 100644 --- a/tests/utils_tests/test_timesince.py +++ b/tests/utils_tests/test_timesince.py @@ -28,71 +28,53 @@ class TimesinceTests(unittest.TestCase): def test_ignore_microseconds_and_seconds(self): """ Microseconds and seconds are ignored. """ - self.assertEqual(timesince(self.t, self.t + self.onemicrosecond), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t + self.onesecond), - '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t + self.onemicrosecond), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t + self.onesecond), '0\xa0minutes') def test_other_units(self): """ Test other units. """ - self.assertEqual(timesince(self.t, self.t + self.oneminute), - '1\xa0minute') + self.assertEqual(timesince(self.t, self.t + self.oneminute), '1\xa0minute') self.assertEqual(timesince(self.t, self.t + self.onehour), '1\xa0hour') self.assertEqual(timesince(self.t, self.t + self.oneday), '1\xa0day') self.assertEqual(timesince(self.t, self.t + self.oneweek), '1\xa0week') - self.assertEqual(timesince(self.t, self.t + self.onemonth), - '1\xa0month') + self.assertEqual(timesince(self.t, self.t + self.onemonth), '1\xa0month') self.assertEqual(timesince(self.t, self.t + self.oneyear), '1\xa0year') def test_multiple_units(self): """ Test multiple units. """ - self.assertEqual(timesince(self.t, - self.t + 2 * self.oneday + 6 * self.onehour), '2\xa0days, 6\xa0hours') - self.assertEqual(timesince(self.t, - self.t + 2 * self.oneweek + 2 * self.oneday), '2\xa0weeks, 2\xa0days') + self.assertEqual(timesince(self.t, self.t + 2 * self.oneday + 6 * self.onehour), '2\xa0days, 6\xa0hours') + self.assertEqual(timesince(self.t, self.t + 2 * self.oneweek + 2 * self.oneday), '2\xa0weeks, 2\xa0days') def test_display_first_unit(self): """ If the two differing units aren't adjacent, only the first unit is displayed. """ - self.assertEqual(timesince(self.t, - self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute), - '2\xa0weeks') - - self.assertEqual(timesince(self.t, - self.t + 4 * self.oneday + 5 * self.oneminute), '4\xa0days') + self.assertEqual( + timesince(self.t, self.t + 2 * self.oneweek + 3 * self.onehour + 4 * self.oneminute), + '2\xa0weeks' + ) + self.assertEqual(timesince(self.t, self.t + 4 * self.oneday + 5 * self.oneminute), '4\xa0days') def test_display_second_before_first(self): """ When the second date occurs before the first, we should always get 0 minutes. """ - self.assertEqual(timesince(self.t, self.t - self.onemicrosecond), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t - self.onesecond), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t - self.oneminute), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t - self.onehour), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t - self.oneday), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t - self.oneweek), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t - self.onemonth), - '0\xa0minutes') - self.assertEqual(timesince(self.t, self.t - self.oneyear), - '0\xa0minutes') - self.assertEqual(timesince(self.t, - self.t - 2 * self.oneday - 6 * self.onehour), '0\xa0minutes') - self.assertEqual(timesince(self.t, - self.t - 2 * self.oneweek - 2 * self.oneday), '0\xa0minutes') - self.assertEqual(timesince(self.t, - self.t - 2 * self.oneweek - 3 * self.onehour - 4 * self.oneminute), - '0\xa0minutes') - self.assertEqual(timesince(self.t, - self.t - 4 * self.oneday - 5 * self.oneminute), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.onemicrosecond), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.onesecond), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.oneminute), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.onehour), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.oneday), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.oneweek), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.onemonth), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - self.oneyear), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - 2 * self.oneday - 6 * self.onehour), '0\xa0minutes') + self.assertEqual(timesince(self.t, self.t - 2 * self.oneweek - 2 * self.oneday), '0\xa0minutes') + self.assertEqual( + timesince(self.t, self.t - 2 * self.oneweek - 3 * self.onehour - 4 * self.oneminute), '0\xa0minutes' + ) + self.assertEqual(timesince(self.t, self.t - 4 * self.oneday - 5 * self.oneminute), '0\xa0minutes') @requires_tz_support def test_different_timezones(self): diff --git a/tests/validation/models.py b/tests/validation/models.py index 6b3d670000..83b998c38f 100644 --- a/tests/validation/models.py +++ b/tests/validation/models.py @@ -68,7 +68,8 @@ class UniqueForDateModel(models.Model): class CustomMessagesModel(models.Model): other = models.IntegerField(blank=True, null=True) - number = models.IntegerField(db_column='number_val', + number = models.IntegerField( + db_column='number_val', error_messages={'null': 'NULL', 'not42': 'AAARGH', 'not_equal': '%s != me'}, validators=[validate_answer_to_universe] ) @@ -115,8 +116,7 @@ class GenericIPAddressTestModel(models.Model): generic_ip = models.GenericIPAddressField(blank=True, null=True, unique=True) v4_ip = models.GenericIPAddressField(blank=True, null=True, protocol="ipv4") v6_ip = models.GenericIPAddressField(blank=True, null=True, protocol="ipv6") - ip_verbose_name = models.GenericIPAddressField("IP Address Verbose", - blank=True, null=True) + ip_verbose_name = models.GenericIPAddressField("IP Address Verbose", blank=True, null=True) class GenericIPAddrUnpackUniqueTest(models.Model): diff --git a/tests/validation/test_error_messages.py b/tests/validation/test_error_messages.py index 9b0bf701b1..c71b8cd60a 100644 --- a/tests/validation/test_error_messages.py +++ b/tests/validation/test_error_messages.py @@ -16,78 +16,75 @@ class ValidationMessagesTest(TestCase): def test_autofield_field_raises_error_message(self): f = models.AutoField(primary_key=True) - self._test_validation_messages(f, 'fõo', - ["'fõo' value must be an integer."]) + self._test_validation_messages(f, 'fõo', ["'fõo' value must be an integer."]) def test_integer_field_raises_error_message(self): f = models.IntegerField() - self._test_validation_messages(f, 'fõo', - ["'fõo' value must be an integer."]) + self._test_validation_messages(f, 'fõo', ["'fõo' value must be an integer."]) def test_boolean_field_raises_error_message(self): f = models.BooleanField() - self._test_validation_messages(f, 'fõo', - ["'fõo' value must be either True or False."]) + self._test_validation_messages(f, 'fõo', ["'fõo' value must be either True or False."]) def test_float_field_raises_error_message(self): f = models.FloatField() - self._test_validation_messages(f, 'fõo', - ["'fõo' value must be a float."]) + self._test_validation_messages(f, 'fõo', ["'fõo' value must be a float."]) def test_decimal_field_raises_error_message(self): f = models.DecimalField() - self._test_validation_messages(f, 'fõo', - ["'fõo' value must be a decimal number."]) + self._test_validation_messages(f, 'fõo', ["'fõo' value must be a decimal number."]) def test_null_boolean_field_raises_error_message(self): f = models.NullBooleanField() - self._test_validation_messages(f, 'fõo', - ["'fõo' value must be either None, True or False."]) + self._test_validation_messages(f, 'fõo', ["'fõo' value must be either None, True or False."]) def test_date_field_raises_error_message(self): f = models.DateField() - self._test_validation_messages(f, 'fõo', - ["'fõo' value has an invalid date format. " - "It must be in YYYY-MM-DD format."]) - - self._test_validation_messages(f, 'aaaa-10-10', - ["'aaaa-10-10' value has an invalid date format. " - "It must be in YYYY-MM-DD format."]) - - self._test_validation_messages(f, '2011-13-10', - ["'2011-13-10' value has the correct format (YYYY-MM-DD) " - "but it is an invalid date."]) - - self._test_validation_messages(f, '2011-10-32', - ["'2011-10-32' value has the correct format (YYYY-MM-DD) " - "but it is an invalid date."]) + self._test_validation_messages( + f, 'fõo', + ["'fõo' value has an invalid date format. It must be in YYYY-MM-DD format."] + ) + self._test_validation_messages( + f, 'aaaa-10-10', + ["'aaaa-10-10' value has an invalid date format. It must be in YYYY-MM-DD format."] + ) + self._test_validation_messages( + f, '2011-13-10', + ["'2011-13-10' value has the correct format (YYYY-MM-DD) but it is an invalid date."] + ) + self._test_validation_messages( + f, '2011-10-32', + ["'2011-10-32' value has the correct format (YYYY-MM-DD) but it is an invalid date."] + ) def test_datetime_field_raises_error_message(self): f = models.DateTimeField() # Wrong format - self._test_validation_messages(f, 'fõo', - ["'fõo' value has an invalid format. It must be " - "in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]) - + self._test_validation_messages( + f, 'fõo', + ["'fõo' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."] + ) # Correct format but invalid date - self._test_validation_messages(f, '2011-10-32', - ["'2011-10-32' value has the correct format " - "(YYYY-MM-DD) but it is an invalid date."]) - + self._test_validation_messages( + f, '2011-10-32', + ["'2011-10-32' value has the correct format (YYYY-MM-DD) but it is an invalid date."] + ) # Correct format but invalid date/time - self._test_validation_messages(f, '2011-10-32 10:10', - ["'2011-10-32 10:10' value has the correct format " - "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " - "but it is an invalid date/time."]) + self._test_validation_messages( + f, '2011-10-32 10:10', + ["'2011-10-32 10:10' value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " + "but it is an invalid date/time."] + ) def test_time_field_raises_error_message(self): f = models.TimeField() # Wrong format - self._test_validation_messages(f, 'fõo', - ["'fõo' value has an invalid format. It must be in " - "HH:MM[:ss[.uuuuuu]] format."]) - + self._test_validation_messages( + f, 'fõo', + ["'fõo' value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format."] + ) # Correct format but invalid time - self._test_validation_messages(f, '25:50', - ["'25:50' value has the correct format " - "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time."]) + self._test_validation_messages( + f, '25:50', + ["'25:50' value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an invalid time."] + ) diff --git a/tests/validation/test_unique.py b/tests/validation/test_unique.py index 2abe85c82c..8b79913d19 100644 --- a/tests/validation/test_unique.py +++ b/tests/validation/test_unique.py @@ -41,10 +41,8 @@ class GetUniqueCheckTests(unittest.TestCase): objects. """ data = { - '2-tuple': (('foo', 'bar'), - (('foo', 'bar'),)), - 'list': (['foo', 'bar'], - (('foo', 'bar'),)), + '2-tuple': (('foo', 'bar'), (('foo', 'bar'),)), + 'list': (['foo', 'bar'], (('foo', 'bar'),)), 'already normalized': ((('foo', 'bar'), ('bar', 'baz')), (('foo', 'bar'), ('bar', 'baz'))), 'set': ({('foo', 'bar'), ('bar', 'baz')}, # Ref #21469 @@ -113,9 +111,10 @@ class PerformUniqueChecksTest(TestCase): mtv.full_clean() def test_unique_for_date(self): - Post.objects.create(title="Django 1.0 is released", - slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) - + Post.objects.create( + title="Django 1.0 is released", slug="Django 1.0", + subtitle="Finally", posted=datetime.date(2008, 9, 3), + ) p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3)) with self.assertRaises(ValidationError) as cm: p.full_clean() @@ -145,9 +144,10 @@ class PerformUniqueChecksTest(TestCase): self.assertEqual(cm.exception.message_dict, {'posted': ['This field cannot be null.']}) def test_unique_for_date_with_nullable_date(self): - FlexibleDatePost.objects.create(title="Django 1.0 is released", - slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) - + FlexibleDatePost.objects.create( + title="Django 1.0 is released", slug="Django 1.0", + subtitle="Finally", posted=datetime.date(2008, 9, 3), + ) p = FlexibleDatePost(title="Django 1.0 is released") try: p.full_clean() diff --git a/tests/validation/tests.py b/tests/validation/tests.py index 653a6b1c4c..af8f195194 100644 --- a/tests/validation/tests.py +++ b/tests/validation/tests.py @@ -28,12 +28,15 @@ class BaseModelValidationTests(ValidationTestCase): def test_wrong_FK_value_raises_error(self): mtv = ModelToValidate(number=10, name='Some Name', parent_id=3) - self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'parent', - ['model to validate instance with id %r does not exist.' % mtv.parent_id]) - + self.assertFieldFailsValidationWithMessage( + mtv.full_clean, 'parent', + ['model to validate instance with id %r does not exist.' % mtv.parent_id] + ) mtv = ModelToValidate(number=10, name='Some Name', ufm_id='Some Name') - self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'ufm', - ["unique fields model instance with unique_charfield %r does not exist." % mtv.name]) + self.assertFieldFailsValidationWithMessage( + mtv.full_clean, 'ufm', + ["unique fields model instance with unique_charfield %r does not exist." % mtv.name] + ) def test_correct_FK_value_validates(self): parent = ModelToValidate.objects.create(number=10, name='Some Name') diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py index e4c99aefec..724613561a 100644 --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -140,8 +140,10 @@ class DebugViewTests(LoggingCaptureMixin, SimpleTestCase): match = re.search(b'
    ', response.content) self.assertIsNotNone(match) id_repr = match.group('id') - self.assertFalse(re.search(b'[^c0-9]', id_repr), - "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr) + self.assertFalse( + re.search(b'[^c0-9]', id_repr), + "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr + ) def test_template_exceptions(self): for n in range(len(except_args)): @@ -149,9 +151,11 @@ class DebugViewTests(LoggingCaptureMixin, SimpleTestCase): self.client.get(reverse('template_exception', args=(n,))) except Exception: raising_loc = inspect.trace()[-1][-2][0].strip() - self.assertNotEqual(raising_loc.find('raise BrokenException'), -1, - "Failed to find 'raise BrokenException' in last frame of traceback, instead found: %s" % - raising_loc) + self.assertNotEqual( + raising_loc.find('raise BrokenException'), -1, + "Failed to find 'raise BrokenException' in last frame of " + "traceback, instead found: %s" % raising_loc + ) def test_template_loader_postmortem(self): """Tests for not existing file""" @@ -939,12 +943,10 @@ class AjaxResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptu the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER. """ with self.settings(DEBUG=True): - self.verify_unsafe_response(custom_exception_reporter_filter_view, - check_for_vars=False) + self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) with self.settings(DEBUG=False): - self.verify_unsafe_response(custom_exception_reporter_filter_view, - check_for_vars=False) + self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False) class HelperFunctionTests(SimpleTestCase): diff --git a/tests/view_tests/tests/test_i18n.py b/tests/view_tests/tests/test_i18n.py index f1417003d2..1c934aaf8d 100644 --- a/tests/view_tests/tests/test_i18n.py +++ b/tests/view_tests/tests/test_i18n.py @@ -329,8 +329,7 @@ class JsI18NTestsMultiPackage(SimpleTestCase): with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths): with override('es-ar'): response = self.client.get('/jsi18n/') - self.assertContains(response, - 'este texto de app3 debe ser traducido') + self.assertContains(response, 'este texto de app3 debe ser traducido') @override_settings(ROOT_URLCONF='view_tests.urls') @@ -344,7 +343,7 @@ class JavascriptI18nTests(SeleniumTestCase): @override_settings(LANGUAGE_CODE='de') def test_javascript_gettext(self): - self.selenium.get('%s%s' % (self.live_server_url, '/jsi18n_template/')) + self.selenium.get(self.live_server_url + '/jsi18n_template/') elem = self.selenium.find_element_by_id("gettext") self.assertEqual(elem.text, "Entfernen") @@ -362,7 +361,7 @@ class JavascriptI18nTests(SeleniumTestCase): @modify_settings(INSTALLED_APPS={'append': ['view_tests.app1', 'view_tests.app2']}) @override_settings(LANGUAGE_CODE='fr') def test_multiple_catalogs(self): - self.selenium.get('%s%s' % (self.live_server_url, '/jsi18n_multi_catalogs/')) + self.selenium.get(self.live_server_url + '/jsi18n_multi_catalogs/') elem = self.selenium.find_element_by_id('app1string') self.assertEqual(elem.text, 'il faut traduire cette chaîne de caractères de app1') diff --git a/tests/view_tests/tests/test_static.py b/tests/view_tests/tests/test_static.py index f1b0bf5b75..f349c08c7c 100644 --- a/tests/view_tests/tests/test_static.py +++ b/tests/view_tests/tests/test_static.py @@ -56,8 +56,10 @@ class StaticTests(SimpleTestCase): def test_is_modified_since(self): file_name = 'file.txt' - response = self.client.get('/%s/%s' % (self.prefix, file_name), - HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT') + response = self.client.get( + '/%s/%s' % (self.prefix, file_name), + HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT' + ) response_content = b''.join(response) with open(path.join(media_dir, file_name), 'rb') as fp: self.assertEqual(fp.read(), response_content) diff --git a/tests/view_tests/views.py b/tests/view_tests/views.py index 9e53c14d5b..203cb6149c 100644 --- a/tests/view_tests/views.py +++ b/tests/view_tests/views.py @@ -113,12 +113,10 @@ def send_log(request, exc_info): orig_filters = admin_email_handler.filters admin_email_handler.filters = [] admin_email_handler.include_html = True - logger.error('Internal Server Error: %s', request.path, + logger.error( + 'Internal Server Error: %s', request.path, exc_info=exc_info, - extra={ - 'status_code': 500, - 'request': request - } + extra={'status_code': 500, 'request': request}, ) admin_email_handler.filters = orig_filters diff --git a/tests/wsgi/tests.py b/tests/wsgi/tests.py index 4056ffda84..f472d4fab9 100644 --- a/tests/wsgi/tests.py +++ b/tests/wsgi/tests.py @@ -1,19 +1,16 @@ from __future__ import unicode_literals -import unittest - from django.core.exceptions import ImproperlyConfigured from django.core.servers.basehttp import get_internal_wsgi_application from django.core.signals import request_started from django.core.wsgi import get_wsgi_application from django.db import close_old_connections -from django.test import TestCase, override_settings +from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory -from django.utils import six @override_settings(ROOT_URLCONF='wsgi.urls') -class WSGITest(TestCase): +class WSGITest(SimpleTestCase): def setUp(self): request_started.disconnect(close_old_connections) @@ -73,7 +70,7 @@ class WSGITest(TestCase): self.assertIsInstance(response, FileWrapper) -class GetInternalWSGIApplicationTest(unittest.TestCase): +class GetInternalWSGIApplicationTest(SimpleTestCase): @override_settings(WSGI_APPLICATION="wsgi.wsgi.application") def test_success(self): """ @@ -110,16 +107,12 @@ class GetInternalWSGIApplicationTest(unittest.TestCase): @override_settings(WSGI_APPLICATION="wsgi.noexist.app") def test_bad_module(self): - with six.assertRaisesRegex(self, - ImproperlyConfigured, - r"^WSGI application 'wsgi.noexist.app' could not be loaded; Error importing.*"): - + msg = "WSGI application 'wsgi.noexist.app' could not be loaded; Error importing" + with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application() @override_settings(WSGI_APPLICATION="wsgi.wsgi.noexist") def test_bad_name(self): - with six.assertRaisesRegex(self, - ImproperlyConfigured, - r"^WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing.*"): - + msg = "WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing" + with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application()