')
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 = ('
')
# 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, "
')
@@ -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)),
- '