Fixed E128 flake8 warnings in tests/.

This commit is contained in:
Tim Graham 2016-04-07 22:04:45 -04:00
parent df8d8d4292
commit 92053acbb9
148 changed files with 2073 additions and 2248 deletions

View File

@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh
[flake8] [flake8]
exclude = build,.git,./django/utils/lru_cache.py,./django/utils/six.py,./django/conf/app_template/*,./django/dispatch/weakref_backports.py,./tests/.env,./xmlrunner,tests/view_tests/tests/py3_test_debug.py,tests/template_tests/annotated_tag_function.py exclude = build,.git,./django/utils/lru_cache.py,./django/utils/six.py,./django/conf/app_template/*,./django/dispatch/weakref_backports.py,./tests/.env,./xmlrunner,tests/view_tests/tests/py3_test_debug.py,tests/template_tests/annotated_tag_function.py
ignore = E128,W601 ignore = W601
max-line-length = 119 max-line-length = 119
[isort] [isort]

View File

@ -12,8 +12,7 @@ site.register(User, UserAdmin)
class CustomPaginator(Paginator): class CustomPaginator(Paginator):
def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True): def __init__(self, queryset, page_size, orphans=0, allow_empty_first_page=True):
super(CustomPaginator, self).__init__(queryset, 5, orphans=2, super(CustomPaginator, self).__init__(queryset, 5, orphans=2, allow_empty_first_page=allow_empty_first_page)
allow_empty_first_page=allow_empty_first_page)
class EventAdmin(admin.ModelAdmin): class EventAdmin(admin.ModelAdmin):

View File

@ -130,8 +130,7 @@ class ChangeListTests(TestCase):
'<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>' '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
'<td class="field-parent nowrap">-</td></tr></tbody>' % link '<td class="field-parent nowrap">-</td></tr></tbody>' % link
) )
self.assertNotEqual(table_output.find(row_html), -1, self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)
'Failed to find expected row element: %s' % table_output)
def test_result_list_set_empty_value_display_on_admin_site(self): def test_result_list_set_empty_value_display_on_admin_site(self):
""" """
@ -152,8 +151,7 @@ class ChangeListTests(TestCase):
'<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>' '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
'<td class="field-parent nowrap">???</td></tr></tbody>' % link '<td class="field-parent nowrap">???</td></tr></tbody>' % link
) )
self.assertNotEqual(table_output.find(row_html), -1, self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)
'Failed to find expected row element: %s' % table_output)
def test_result_list_set_empty_value_display_in_model_admin(self): def test_result_list_set_empty_value_display_in_model_admin(self):
""" """
@ -172,8 +170,7 @@ class ChangeListTests(TestCase):
'<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>' '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
'<td class="field-age_display">&amp;dagger;</td><td class="field-age">-empty-</td></tr></tbody>' % link '<td class="field-age_display">&amp;dagger;</td><td class="field-age">-empty-</td></tr></tbody>' % link
) )
self.assertNotEqual(table_output.find(row_html), -1, self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)
'Failed to find expected row element: %s' % table_output)
def test_result_list_html(self): def test_result_list_html(self):
""" """
@ -194,8 +191,7 @@ class ChangeListTests(TestCase):
'<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>' '<tbody><tr class="row1"><th class="field-name"><a href="%s">name</a></th>'
'<td class="field-parent nowrap">Parent object</td></tr></tbody>' % link '<td class="field-parent nowrap">Parent object</td></tr></tbody>' % link
) )
self.assertNotEqual(table_output.find(row_html), -1, self.assertNotEqual(table_output.find(row_html), -1, 'Failed to find expected row element: %s' % table_output)
'Failed to find expected row element: %s' % table_output)
def test_result_list_editable_html(self): def test_result_list_editable_html(self):
""" """
@ -894,8 +890,7 @@ class SeleniumTests(AdminSeleniumTestCase):
Ensure that the status line for selected rows gets updated correctly (#22038) Ensure that the status line for selected rows gets updated correctly (#22038)
""" """
self.admin_login(username='super', password='secret') self.admin_login(username='super', password='secret')
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:auth_user_changelist'))
reverse('admin:auth_user_changelist')))
form_id = '#changelist-form' form_id = '#changelist-form'

View File

@ -73,15 +73,16 @@ class AdminCustomUrlsTest(TestCase):
""" """
# Should get the change_view for model instance with PK 'add', not show # Should get the change_view for model instance with PK 'add', not show
# the add_view # the add_view
url = reverse('admin_custom_urls:%s_action_change' % Action._meta.app_label, url = reverse('admin_custom_urls:%s_action_change' % Action._meta.app_label, args=(quote('add'),))
args=(quote('add'),))
response = self.client.get(url) response = self.client.get(url)
self.assertContains(response, 'Change action') self.assertContains(response, 'Change action')
# Should correctly get the change_view for the model instance with the # Should correctly get the change_view for the model instance with the
# funny-looking PK (the one with a 'path/to/html/document.html' value) # funny-looking PK (the one with a 'path/to/html/document.html' value)
url = reverse('admin_custom_urls:%s_action_change' % Action._meta.app_label, url = reverse(
args=(quote("path/to/html/document.html"),)) 'admin_custom_urls:%s_action_change' % Action._meta.app_label,
args=(quote("path/to/html/document.html"),)
)
response = self.client.get(url) response = self.client.get(url)
self.assertContains(response, 'Change action') self.assertContains(response, 'Change action')
self.assertContains(response, 'value="path/to/html/document.html"') self.assertContains(response, 'value="path/to/html/document.html"')
@ -95,12 +96,11 @@ class AdminCustomUrlsTest(TestCase):
""" """
post_data = {'name': 'John Doe'} post_data = {'name': 'John Doe'}
self.assertEqual(Person.objects.count(), 0) self.assertEqual(Person.objects.count(), 0)
response = self.client.post( response = self.client.post(reverse('admin_custom_urls:admin_custom_urls_person_add'), post_data)
reverse('admin_custom_urls:admin_custom_urls_person_add'), post_data)
persons = Person.objects.all() persons = Person.objects.all()
self.assertEqual(len(persons), 1) self.assertEqual(len(persons), 1)
self.assertRedirects( redirect_url = reverse('admin_custom_urls:admin_custom_urls_person_history', args=[persons[0].pk])
response, reverse('admin_custom_urls:admin_custom_urls_person_history', args=[persons[0].pk])) self.assertRedirects(response, redirect_url)
def test_post_save_change_redirect(self): def test_post_save_change_redirect(self):
""" """
@ -112,11 +112,9 @@ class AdminCustomUrlsTest(TestCase):
Person.objects.create(name='John Doe') Person.objects.create(name='John Doe')
self.assertEqual(Person.objects.count(), 1) self.assertEqual(Person.objects.count(), 1)
person = Person.objects.all()[0] person = Person.objects.all()[0]
post_data = {'name': 'Jack Doe'} post_url = reverse('admin_custom_urls:admin_custom_urls_person_change', args=[person.pk])
response = self.client.post( response = self.client.post(post_url, {'name': 'Jack Doe'})
reverse('admin_custom_urls:admin_custom_urls_person_change', args=[person.pk]), post_data) self.assertRedirects(response, reverse('admin_custom_urls:admin_custom_urls_person_delete', args=[person.pk]))
self.assertRedirects(
response, reverse('admin_custom_urls:admin_custom_urls_person_delete', args=[person.pk]))
def test_post_url_continue(self): def test_post_url_continue(self):
""" """
@ -125,9 +123,7 @@ class AdminCustomUrlsTest(TestCase):
""" """
post_data = {'name': 'SuperFast', '_continue': '1'} post_data = {'name': 'SuperFast', '_continue': '1'}
self.assertEqual(Car.objects.count(), 0) self.assertEqual(Car.objects.count(), 0)
response = self.client.post( response = self.client.post(reverse('admin_custom_urls:admin_custom_urls_car_add'), post_data)
reverse('admin_custom_urls:admin_custom_urls_car_add'), post_data)
cars = Car.objects.all() cars = Car.objects.all()
self.assertEqual(len(cars), 1) self.assertEqual(len(cars), 1)
self.assertRedirects( self.assertRedirects(response, reverse('admin_custom_urls:admin_custom_urls_car_history', args=[cars[0].pk]))
response, reverse('admin_custom_urls:admin_custom_urls_car_history', args=[cars[0].pk]))

View File

@ -54,14 +54,11 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
self.client.logout() self.client.logout()
response = self.client.get(reverse('django-admindocs-docroot'), follow=True) response = self.client.get(reverse('django-admindocs-docroot'), follow=True)
# Should display the login screen # Should display the login screen
self.assertContains(response, self.assertContains(response, '<input type="hidden" name="next" value="/admindocs/" />', html=True)
'<input type="hidden" name="next" value="/admindocs/" />', html=True)
self.client.force_login(self.superuser) self.client.force_login(self.superuser)
response = self.client.get(reverse('django-admindocs-docroot')) response = self.client.get(reverse('django-admindocs-docroot'))
self.assertContains(response, '<h1>Documentation</h1>', html=True) self.assertContains(response, '<h1>Documentation</h1>', html=True)
self.assertContains(response, self.assertContains(response, '<h1 id="site-name"><a href="/admin/">Django administration</a></h1>')
'<h1 id="site-name"><a href="/admin/">Django '
'administration</a></h1>')
def test_bookmarklets(self): def test_bookmarklets(self):
response = self.client.get(reverse('django-admindocs-bookmarklets')) response = self.client.get(reverse('django-admindocs-bookmarklets'))
@ -77,16 +74,17 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
def test_view_index(self): def test_view_index(self):
response = self.client.get(reverse('django-admindocs-views-index')) response = self.client.get(reverse('django-admindocs-views-index'))
self.assertContains(response, self.assertContains(
response,
'<h3><a href="/admindocs/views/django.contrib.admindocs.views.BaseAdminDocsView/">/admindocs/</a></h3>', '<h3><a href="/admindocs/views/django.contrib.admindocs.views.BaseAdminDocsView/">/admindocs/</a></h3>',
html=True) html=True
)
self.assertContains(response, 'Views by namespace test') self.assertContains(response, 'Views by namespace test')
self.assertContains(response, 'Name: <code>test:func</code>.') self.assertContains(response, 'Name: <code>test:func</code>.')
def test_view_detail(self): def test_view_detail(self):
response = self.client.get( url = reverse('django-admindocs-views-detail', args=['django.contrib.admindocs.views.BaseAdminDocsView'])
reverse('django-admindocs-views-detail', response = self.client.get(url)
args=['django.contrib.admindocs.views.BaseAdminDocsView']))
# View docstring # View docstring
self.assertContains(response, 'Base view for admindocs views.') self.assertContains(response, 'Base view for admindocs views.')
@ -94,9 +92,8 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
""" """
#23601 - Ensure the view exists in the URLconf. #23601 - Ensure the view exists in the URLconf.
""" """
response = self.client.get( url = reverse('django-admindocs-views-detail', args=['urlpatterns_reverse.nonimported_module.view'])
reverse('django-admindocs-views-detail', response = self.client.get(url)
args=['urlpatterns_reverse.nonimported_module.view']))
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules) self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules)
@ -109,22 +106,20 @@ class AdminDocViewTests(TestDataMixin, AdminDocsTestCase):
) )
def test_template_detail(self): def test_template_detail(self):
response = self.client.get(reverse('django-admindocs-templates', response = self.client.get(reverse('django-admindocs-templates', args=['admin_doc/template_detail.html']))
args=['admin_doc/template_detail.html'])) self.assertContains(response, '<h1>Template: "admin_doc/template_detail.html"</h1>', html=True)
self.assertContains(response,
'<h1>Template: "admin_doc/template_detail.html"</h1>', html=True)
def test_missing_docutils(self): def test_missing_docutils(self):
utils.docutils_is_available = False utils.docutils_is_available = False
try: try:
response = self.client.get(reverse('django-admindocs-docroot')) response = self.client.get(reverse('django-admindocs-docroot'))
self.assertContains(response, self.assertContains(
response,
'<h3>The admin documentation system requires Python\'s ' '<h3>The admin documentation system requires Python\'s '
'<a href="http://docutils.sf.net/">docutils</a> library.</h3>', '<a href="http://docutils.sf.net/">docutils</a> library.</h3>',
html=True) html=True
self.assertContains(response, )
'<h1 id="site-name"><a href="/admin/">Django ' self.assertContains(response, '<h1 id="site-name"><a href="/admin/">Django administration</a></h1>')
'administration</a></h1>')
finally: finally:
utils.docutils_is_available = True utils.docutils_is_available = True
@ -200,18 +195,12 @@ class DefaultRoleTest(AdminDocsTestCase):
``django.contrib.admindocs.utils.parse_rst`` should use ``django.contrib.admindocs.utils.parse_rst`` should use
``cmsreference`` as the default role. ``cmsreference`` as the default role.
""" """
markup = ('<p><a class="reference external" href="/admindocs/%s">' markup = '<p><a class="reference external" href="/admindocs/%s">title</a></p>\n'
'title</a></p>\n') self.assertEqual(utils.parse_rst('`title`', 'model'), markup % 'models/title/')
self.assertEqual(utils.parse_rst('`title`', 'model'), self.assertEqual(utils.parse_rst('`title`', 'view'), markup % 'views/title/')
markup % 'models/title/') self.assertEqual(utils.parse_rst('`title`', 'template'), markup % 'templates/title/')
self.assertEqual(utils.parse_rst('`title`', 'view'), self.assertEqual(utils.parse_rst('`title`', 'filter'), markup % 'filters/#title')
markup % 'views/title/') self.assertEqual(utils.parse_rst('`title`', 'tag'), markup % 'tags/#title')
self.assertEqual(utils.parse_rst('`title`', 'template'),
markup % 'templates/title/')
self.assertEqual(utils.parse_rst('`title`', 'filter'),
markup % 'filters/#title')
self.assertEqual(utils.parse_rst('`title`', 'tag'),
markup % 'tags/#title')
def test_publish_parts(self): def test_publish_parts(self):
""" """
@ -220,8 +209,7 @@ class DefaultRoleTest(AdminDocsTestCase):
``cmsreference``. See #6681. ``cmsreference``. See #6681.
""" """
import docutils import docutils
self.assertNotEqual(docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, self.assertNotEqual(docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, 'cmsreference')
'cmsreference')
source = 'reST, `interpreted text`, default role.' source = 'reST, `interpreted text`, default role.'
markup = '<p>reST, <cite>interpreted text</cite>, default role.</p>\n' markup = '<p>reST, <cite>interpreted text</cite>, default role.</p>\n'
parts = docutils.core.publish_parts(source=source, writer_name="html4css1") parts = docutils.core.publish_parts(source=source, writer_name="html4css1")
@ -286,21 +274,9 @@ class TestModelDetailView(TestDataMixin, AdminDocsTestCase):
by a method by a method
""" """
company = Company.objects.create(name="Django") company = Company.objects.create(name="Django")
person = Person.objects.create( person = Person.objects.create(first_name="Human", last_name="User", company=company)
first_name="Human", self.assertEqual(get_return_data_type(person.get_status_count.__name__), 'Integer')
last_name="User", self.assertEqual(get_return_data_type(person.get_groups_list.__name__), 'List')
company=company
)
self.assertEqual(
get_return_data_type(person.get_status_count.__name__),
'Integer'
)
self.assertEqual(
get_return_data_type(person.get_groups_list.__name__),
'List'
)
def test_descriptions_render_correctly(self): def test_descriptions_render_correctly(self):
""" """
@ -361,10 +337,7 @@ class TestModelDetailView(TestDataMixin, AdminDocsTestCase):
A model with ``related_name`` of `+` should not show backward relationship A model with ``related_name`` of `+` should not show backward relationship
links in admin docs links in admin docs
""" """
response = self.client.get( response = self.client.get(reverse('django-admindocs-models-detail', args=['admin_docs', 'family']))
reverse('django-admindocs-models-detail',
args=['admin_docs', 'family']))
fields = response.context_data.get('fields') fields = response.context_data.get('fields')
self.assertEqual(len(fields), 2) self.assertEqual(len(fields), 2)

View File

@ -37,9 +37,10 @@ class EditablePKBookStackedInline(admin.StackedInline):
class AuthorAdmin(admin.ModelAdmin): class AuthorAdmin(admin.ModelAdmin):
inlines = [BookInline, inlines = [
NonAutoPKBookTabularInline, NonAutoPKBookStackedInline, BookInline, NonAutoPKBookTabularInline, NonAutoPKBookStackedInline,
EditablePKBookTabularInline, EditablePKBookStackedInline] EditablePKBookTabularInline, EditablePKBookStackedInline,
]
class InnerInline(admin.StackedInline): class InnerInline(admin.StackedInline):

View File

@ -185,22 +185,28 @@ class TestInline(TestDataMixin, TestCase):
prefixes. Bug #16838. prefixes. Bug #16838.
""" """
response = self.client.get(reverse('admin:admin_inlines_capofamiglia_add')) response = self.client.get(reverse('admin:admin_inlines_capofamiglia_add'))
self.assertContains(response, '<input type="hidden" name="-1-0-id" id="id_-1-0-id" />', html=True)
self.assertContains(response, self.assertContains(
'<input type="hidden" name="-1-0-id" id="id_-1-0-id" />', html=True) response,
self.assertContains(response, '<input type="hidden" name="-1-0-capo_famiglia" id="id_-1-0-capo_famiglia" />',
'<input type="hidden" name="-1-0-capo_famiglia" id="id_-1-0-capo_famiglia" />', html=True) html=True
self.assertContains(response, )
'<input id="id_-1-0-name" type="text" class="vTextField" ' self.assertContains(
'name="-1-0-name" maxlength="100" />', html=True) response,
'<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" maxlength="100" />',
self.assertContains(response, html=True
'<input type="hidden" name="-2-0-id" id="id_-2-0-id" />', html=True) )
self.assertContains(response, self.assertContains(response, '<input type="hidden" name="-2-0-id" id="id_-2-0-id" />', html=True)
'<input type="hidden" name="-2-0-capo_famiglia" id="id_-2-0-capo_famiglia" />', html=True) self.assertContains(
self.assertContains(response, response,
'<input id="id_-2-0-name" type="text" class="vTextField" ' '<input type="hidden" name="-2-0-capo_famiglia" id="id_-2-0-capo_famiglia" />',
'name="-2-0-name" maxlength="100" />', html=True) html=True
)
self.assertContains(
response,
'<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" maxlength="100" />',
html=True
)
@override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True)
def test_localize_pk_shortcut(self): def test_localize_pk_shortcut(self):
@ -622,8 +628,11 @@ class TestInlinePermissions(TestCase):
'name="inner2_set-TOTAL_FORMS" />', 'name="inner2_set-TOTAL_FORMS" />',
html=True html=True
) )
self.assertNotContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' self.assertNotContains(
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) response,
'<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id" />' % self.inner2_id,
html=True
)
def test_inline_change_fk_change_perm(self): def test_inline_change_fk_change_perm(self):
permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct)
@ -632,13 +641,21 @@ class TestInlinePermissions(TestCase):
# Change permission on inner2s, so we can change existing but not add new # Change permission on inner2s, so we can change existing but not add new
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# Just the one form for existing instances # Just the one form for existing instances
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(
'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS" />',
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' html=True
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) )
self.assertContains(
response,
'<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id" />' % self.inner2_id,
html=True
)
# max-num 0 means we can't add new ones # max-num 0 means we can't add new ones
self.assertContains(response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" ' self.assertContains(
'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True) response,
'<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" name="inner2_set-MAX_NUM_FORMS" />',
html=True
)
def test_inline_change_fk_add_change_perm(self): def test_inline_change_fk_add_change_perm(self):
permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) 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 # Add/change perm, so we can add new and change existing
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance and three extra for new # One form for existing instance and three extra for new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(
'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS" />',
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' html=True
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) )
self.assertContains(
response,
'<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id" />' % self.inner2_id,
html=True
)
def test_inline_change_fk_change_del_perm(self): def test_inline_change_fk_change_del_perm(self):
permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) 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 # Change/delete perm on inner2s, so we can change/delete existing
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance only, no new # One form for existing instance only, no new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(
'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) response,
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS" />',
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) html=True
)
self.assertContains(
response,
'<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id" />' % self.inner2_id,
html=True
)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"') self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
def test_inline_change_fk_all_perms(self): 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 # All perms on inner2s, so we can add/change/delete
self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, '<h2>Inner2s</h2>')
# One form for existing instance only, three for new # One form for existing instance only, three for new
self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' self.assertContains(
'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) response,
self.assertContains(response, '<input type="hidden" id="id_inner2_set-0-id" ' '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS" />',
'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) html=True
)
self.assertContains(
response,
'<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id" />' % self.inner2_id,
html=True
)
self.assertContains(response, 'id="id_inner2_set-0-DELETE"') self.assertContains(response, 'id="id_inner2_set-0-DELETE"')
@ -701,8 +735,7 @@ class SeleniumTests(AdminSeleniumTestCase):
stacked formset. stacked formset.
""" """
self.admin_login(username='super', password='secret') self.admin_login(username='super', password='secret')
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_holder4_add'))
reverse('admin:admin_inlines_holder4_add')))
inline_id = '#inner4stacked_set-group' inline_id = '#inner4stacked_set-group'
@ -718,8 +751,7 @@ class SeleniumTests(AdminSeleniumTestCase):
def test_delete_stackeds(self): def test_delete_stackeds(self):
self.admin_login(username='super', password='secret') self.admin_login(username='super', password='secret')
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_holder4_add'))
reverse('admin:admin_inlines_holder4_add')))
inline_id = '#inner4stacked_set-group' inline_id = '#inner4stacked_set-group'
@ -733,8 +765,7 @@ class SeleniumTests(AdminSeleniumTestCase):
add_button.click() add_button.click()
self.assertEqual(rows_length(), 5, msg="sanity check") self.assertEqual(rows_length(), 5, msg="sanity check")
for delete_link in self.selenium.find_elements_by_css_selector( for delete_link in self.selenium.find_elements_by_css_selector('%s .inline-deletelink' % inline_id):
'%s .inline-deletelink' % inline_id):
delete_link.click() delete_link.click()
self.assertEqual(rows_length(), 3) self.assertEqual(rows_length(), 3)
@ -744,8 +775,7 @@ class SeleniumTests(AdminSeleniumTestCase):
inline form. inline form.
""" """
self.admin_login(username='super', password='secret') self.admin_login(username='super', password='secret')
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add'))
reverse('admin:admin_inlines_profilecollection_add')))
# Check that there's only one inline to start with and that it has the # Check that there's only one inline to start with and that it has the
# correct ID. # correct ID.
@ -764,8 +794,7 @@ class SeleniumTests(AdminSeleniumTestCase):
# Check that the inline has been added, that it has the right id, and # Check that the inline has been added, that it has the right id, and
# that it contains the right fields. # that it contains the right fields.
self.assertEqual(len(self.selenium.find_elements_by_css_selector( self.assertEqual(len(self.selenium.find_elements_by_css_selector('.dynamic-profile_set')), 2)
'.dynamic-profile_set')), 2)
self.assertEqual(self.selenium.find_elements_by_css_selector( self.assertEqual(self.selenium.find_elements_by_css_selector(
'.dynamic-profile_set')[1].get_attribute('id'), 'profile_set-1') '.dynamic-profile_set')[1].get_attribute('id'), 'profile_set-1')
self.assertEqual(len(self.selenium.find_elements_by_css_selector( 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 # Let's add another one to be sure
self.selenium.find_element_by_link_text('Add another Profile').click() self.selenium.find_element_by_link_text('Add another Profile').click()
self.assertEqual(len(self.selenium.find_elements_by_css_selector( self.assertEqual(len(self.selenium.find_elements_by_css_selector('.dynamic-profile_set')), 3)
'.dynamic-profile_set')), 3)
self.assertEqual(self.selenium.find_elements_by_css_selector( self.assertEqual(self.selenium.find_elements_by_css_selector(
'.dynamic-profile_set')[2].get_attribute('id'), 'profile_set-2') '.dynamic-profile_set')[2].get_attribute('id'), 'profile_set-2')
self.assertEqual(len(self.selenium.find_elements_by_css_selector( self.assertEqual(len(self.selenium.find_elements_by_css_selector(
@ -801,8 +829,7 @@ class SeleniumTests(AdminSeleniumTestCase):
def test_delete_inlines(self): def test_delete_inlines(self):
self.admin_login(username='super', password='secret') self.admin_login(username='super', password='secret')
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add'))
reverse('admin:admin_inlines_profilecollection_add')))
# Add a few inlines # Add a few inlines
self.selenium.find_element_by_link_text('Add another Profile').click() self.selenium.find_element_by_link_text('Add another Profile').click()
@ -839,8 +866,7 @@ class SeleniumTests(AdminSeleniumTestCase):
def test_alternating_rows(self): def test_alternating_rows(self):
self.admin_login(username='super', password='secret') self.admin_login(username='super', password='secret')
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add'))
reverse('admin:admin_inlines_profilecollection_add')))
# Add a few inlines # Add a few inlines
self.selenium.find_element_by_link_text('Add another Profile').click() self.selenium.find_element_by_link_text('Add another Profile').click()

View File

@ -4,5 +4,4 @@ from django.core.management.commands.startproject import Command as BaseCommand
class Command(BaseCommand): class Command(BaseCommand):
def add_arguments(self, parser): def add_arguments(self, parser):
super(Command, self).add_arguments(parser) super(Command, self).add_arguments(parser)
parser.add_argument('--extra', parser.add_argument('--extra', help='An arbitrary extra value passed to the context')
help='An arbitrary extra value passed to the context')

View File

@ -161,9 +161,11 @@ class AdminScriptTestCase(unittest.TestCase):
# Move to the test directory and run # Move to the test directory and run
os.chdir(self.test_dir) os.chdir(self.test_dir)
out, err = subprocess.Popen([sys.executable, script] + args, out, err = subprocess.Popen(
stdout=subprocess.PIPE, stderr=subprocess.PIPE, [sys.executable, script] + args,
env=test_environ, universal_newlines=True).communicate() stdout=subprocess.PIPE, stderr=subprocess.PIPE,
env=test_environ, universal_newlines=True,
).communicate()
# Move back to the old working directory # Move back to the old working directory
os.chdir(old_cwd) os.chdir(old_cwd)
@ -204,8 +206,10 @@ class AdminScriptTestCase(unittest.TestCase):
"Utility assertion: assert that the given message exists in the output" "Utility assertion: assert that the given message exists in the output"
stream = force_text(stream) stream = force_text(stream)
if regex: if regex:
self.assertIsNotNone(re.search(msg, stream), self.assertIsNotNone(
"'%s' does not match actual output text '%s'" % (msg, stream)) re.search(msg, stream),
"'%s' does not match actual output text '%s'" % (msg, stream)
)
else: else:
self.assertIn(msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream)) 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 """ manage.py check reports an error on a non-existent app in
INSTALLED_APPS """ INSTALLED_APPS """
self.write_settings('settings.py', self.write_settings(
'settings.py',
apps=['admin_scriptz.broken_app'], apps=['admin_scriptz.broken_app'],
sdict={'USE_I18N': False}) sdict={'USE_I18N': False},
)
args = ['check'] args = ['check']
out, err = self.run_manage(args) out, err = self.run_manage(args)
self.assertNoOutput(out) self.assertNoOutput(out)
@ -1192,12 +1198,16 @@ class ManageCheck(AdminScriptTestCase):
""" manage.py check does not raise errors when an app imports a base """ manage.py check does not raise errors when an app imports a base
class that itself has an abstract base. """ class that itself has an abstract base. """
self.write_settings('settings.py', self.write_settings(
apps=['admin_scripts.app_with_import', 'settings.py',
'django.contrib.auth', apps=[
'django.contrib.contenttypes', 'admin_scripts.app_with_import',
'django.contrib.sites'], 'django.contrib.auth',
sdict={'DEBUG': True}) 'django.contrib.contenttypes',
'django.contrib.sites',
],
sdict={'DEBUG': True},
)
args = ['check'] args = ['check']
out, err = self.run_manage(args) out, err = self.run_manage(args)
self.assertNoOutput(err) self.assertNoOutput(err)
@ -1206,11 +1216,15 @@ class ManageCheck(AdminScriptTestCase):
def test_output_format(self): def test_output_format(self):
""" All errors/warnings should be sorted by level and by message. """ """ All errors/warnings should be sorted by level and by message. """
self.write_settings('settings.py', self.write_settings(
apps=['admin_scripts.app_raising_messages', 'settings.py',
'django.contrib.auth', apps=[
'django.contrib.contenttypes'], 'admin_scripts.app_raising_messages',
sdict={'DEBUG': True}) 'django.contrib.auth',
'django.contrib.contenttypes',
],
sdict={'DEBUG': True},
)
args = ['check'] args = ['check']
out, err = self.run_manage(args) out, err = self.run_manage(args)
expected_err = ( expected_err = (
@ -1239,11 +1253,15 @@ class ManageCheck(AdminScriptTestCase):
In this test we also test output format. In this test we also test output format.
""" """
self.write_settings('settings.py', self.write_settings(
apps=['admin_scripts.app_raising_warning', 'settings.py',
'django.contrib.auth', apps=[
'django.contrib.contenttypes'], 'admin_scripts.app_raising_warning',
sdict={'DEBUG': True}) 'django.contrib.auth',
'django.contrib.contenttypes',
],
sdict={'DEBUG': True},
)
args = ['check'] args = ['check']
out, err = self.run_manage(args) out, err = self.run_manage(args)
expected_err = ( expected_err = (
@ -2049,8 +2067,7 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
for f in ('Procfile', 'additional_file.py', 'requirements.txt'): for f in ('Procfile', 'additional_file.py', 'requirements.txt'):
self.assertTrue(os.path.exists(os.path.join(base_path, f))) self.assertTrue(os.path.exists(os.path.join(base_path, f)))
with open(os.path.join(base_path, f)) as fh: with open(os.path.join(base_path, f)) as fh:
self.assertEqual(fh.read().strip(), self.assertEqual(fh.read().strip(), '# some file for customtestproject test project')
'# some file for customtestproject test project')
def test_custom_project_template_context_variables(self): def test_custom_project_template_context_variables(self):
"Make sure template context variables are rendered with proper values" "Make sure template context variables are rendered with proper values"

View File

@ -263,9 +263,7 @@ class UtilsTests(SimpleTestCase):
"not Really the Model" "not Really the Model"
) )
self.assertEqual( self.assertEqual(
label_for_field("test_from_model", Article, label_for_field("test_from_model", Article, model_admin=MockModelAdmin, return_attr=True),
model_admin=MockModelAdmin,
return_attr=True),
("not Really the Model", MockModelAdmin.test_from_model) ("not Really the Model", MockModelAdmin.test_from_model)
) )

View File

@ -208,8 +208,7 @@ class PersonAdmin(admin.ModelAdmin):
save_as = True save_as = True
def get_changelist_formset(self, request, **kwargs): def get_changelist_formset(self, request, **kwargs):
return super(PersonAdmin, self).get_changelist_formset(request, return super(PersonAdmin, self).get_changelist_formset(request, formset=BasePersonModelFormSet, **kwargs)
formset=BasePersonModelFormSet, **kwargs)
def get_queryset(self, request): def get_queryset(self, request):
# Order by a field that isn't in list display, to be able to test # Order by a field that isn't in list display, to be able to test

View File

@ -812,8 +812,10 @@ class Simple(models.Model):
class Choice(models.Model): class Choice(models.Model):
choice = models.IntegerField(blank=True, null=True, choice = models.IntegerField(
choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion'))) blank=True, null=True,
choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion')),
)
class ParentWithDependentChildren(models.Model): class ParentWithDependentChildren(models.Model):

View File

@ -230,8 +230,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
def test_add_with_GET_args(self): def test_add_with_GET_args(self):
response = self.client.get(reverse('admin:admin_views_section_add'), {'name': 'My Section'}) response = self.client.get(reverse('admin:admin_views_section_add'), {'name': 'My Section'})
self.assertContains(response, 'value="My Section"', self.assertContains(
msg_prefix="Couldn't find an input with the right value in the response") response, 'value="My Section"',
msg_prefix="Couldn't find an input with the right value in the response"
)
def test_basic_edit_GET(self): def test_basic_edit_GET(self):
""" """
@ -352,10 +354,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
(column 2 is callable_year in ArticleAdmin) (column 2 is callable_year in ArticleAdmin)
""" """
response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': 2}) response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': 2})
self.assertContentBefore(response, 'Oldest content', 'Middle content', self.assertContentBefore(
"Results of sorting on callable are out of order.") response, 'Oldest content', 'Middle content',
self.assertContentBefore(response, 'Middle content', 'Newest content', "Results of sorting on callable are out of order."
"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): def test_change_list_sorting_model(self):
""" """
@ -363,10 +369,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
(column 3 is 'model_year' in ArticleAdmin) (column 3 is 'model_year' in ArticleAdmin)
""" """
response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '-3'}) response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '-3'})
self.assertContentBefore(response, 'Newest content', 'Middle content', self.assertContentBefore(
"Results of sorting on Model method are out of order.") response, 'Newest content', 'Middle content',
self.assertContentBefore(response, 'Middle content', 'Oldest content', "Results of sorting on Model method are out of order."
"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): def test_change_list_sorting_model_admin(self):
""" """
@ -374,10 +384,14 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
(column 4 is 'modeladmin_year' in ArticleAdmin) (column 4 is 'modeladmin_year' in ArticleAdmin)
""" """
response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '4'}) response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '4'})
self.assertContentBefore(response, 'Oldest content', 'Middle content', self.assertContentBefore(
"Results of sorting on ModelAdmin method are out of order.") response, 'Oldest content', 'Middle content',
self.assertContentBefore(response, 'Middle content', 'Newest content', "Results of sorting on ModelAdmin method are out of order."
"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): def test_change_list_sorting_model_admin_reverse(self):
""" """
@ -386,17 +400,25 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
(column 6 is 'model_year_reverse' in ArticleAdmin) (column 6 is 'model_year_reverse' in ArticleAdmin)
""" """
response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '6'}) response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '6'})
self.assertContentBefore(response, '2009', '2008', self.assertContentBefore(
"Results of sorting on ModelAdmin method are out of order.") response, '2009', '2008',
self.assertContentBefore(response, '2008', '2000', "Results of sorting on ModelAdmin method are out of order."
"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 # Let's make sure the ordering is right and that we don't get a
# FieldError when we change to descending order # FieldError when we change to descending order
response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '-6'}) response = self.client.get(reverse('admin:admin_views_article_changelist'), {'o': '-6'})
self.assertContentBefore(response, '2000', '2008', self.assertContentBefore(
"Results of sorting on ModelAdmin method are out of order.") response, '2000', '2008',
self.assertContentBefore(response, '2008', '2009', "Results of sorting on ModelAdmin method are out of order."
"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): def test_change_list_sorting_multiple(self):
p1 = Person.objects.create(name="Chris", gender=1, alive=True) 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'). This also tests relation-spanning filters (e.g. 'color__value').
""" """
response = self.client.get(reverse('admin:admin_views_thing_changelist')) response = self.client.get(reverse('admin:admin_views_thing_changelist'))
self.assertContains(response, '<div id="changelist-filter">', self.assertContains(
msg_prefix="Expected filter not found in changelist view") response, '<div id="changelist-filter">',
self.assertNotContains(response, '<a href="?color__id__exact=3">Blue</a>', msg_prefix="Expected filter not found in changelist view"
msg_prefix="Changelist filter not correctly limited by limit_choices_to") )
self.assertNotContains(
response, '<a href="?color__id__exact=3">Blue</a>',
msg_prefix="Changelist filter not correctly limited by limit_choices_to"
)
def test_relation_spanning_filters(self): def test_relation_spanning_filters(self):
changelist_url = reverse('admin:admin_views_chapterxtra1_changelist') changelist_url = reverse('admin:admin_views_chapterxtra1_changelist')
@ -626,10 +652,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
"field 'choices' option named group." "field 'choices' option named group."
) )
self.assertContains(response, '<div id="changelist-filter">') self.assertContains(response, '<div id="changelist-filter">')
self.assertContains(response, self.assertContains(response, '<a href="?surface__exact=x">Horizontal</a>', msg_prefix=fail_msg, html=True)
'<a href="?surface__exact=x">Horizontal</a>', msg_prefix=fail_msg, html=True) self.assertContains(response, '<a href="?surface__exact=y">Vertical</a>', msg_prefix=fail_msg, html=True)
self.assertContains(response,
'<a href="?surface__exact=y">Vertical</a>', msg_prefix=fail_msg, html=True)
def test_change_list_null_boolean_display(self): def test_change_list_null_boolean_display(self):
Post.objects.create(public=None) Post.objects.create(public=None)
@ -789,8 +813,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
user.save() user.save()
self.client.force_login(user) self.client.force_login(user)
response = self.client.get(reverse('admin:index')) response = self.client.get(reverse('admin:index'))
self.assertNotContains(response, reverse('admin:password_change'), self.assertNotContains(
msg_prefix='The "change password" link should not be displayed if a user does not have a usable password.') 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): def test_change_view_with_show_delete_extra_context(self):
""" """
@ -1514,8 +1540,10 @@ class AdminViewPermissionsTest(TestCase):
self.client.force_login(self.adduser) self.client.force_login(self.adduser)
addpage = self.client.get(reverse('admin:admin_views_article_add')) addpage = self.client.get(reverse('admin:admin_views_article_add'))
change_list_link = '&rsaquo; <a href="%s">Articles</a>' % reverse('admin:admin_views_article_changelist') change_list_link = '&rsaquo; <a href="%s">Articles</a>' % reverse('admin:admin_views_article_changelist')
self.assertNotContains(addpage, change_list_link, self.assertNotContains(
msg_prefix='User restricted to add permission is given link to change list view in breadcrumbs.') 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) post = self.client.post(reverse('admin:admin_views_article_add'), add_dict)
self.assertRedirects(post, self.index_url) self.assertRedirects(post, self.index_url)
self.assertEqual(Article.objects.count(), 4) 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 # Super can add too, but is redirected to the change list view
self.client.force_login(self.superuser) self.client.force_login(self.superuser)
addpage = self.client.get(reverse('admin:admin_views_article_add')) addpage = self.client.get(reverse('admin:admin_views_article_add'))
self.assertContains(addpage, change_list_link, self.assertContains(
msg_prefix='Unrestricted user is not given link to change list view in breadcrumbs.') 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) post = self.client.post(reverse('admin:admin_views_article_add'), add_dict)
self.assertRedirects(post, reverse('admin:admin_views_article_changelist')) self.assertRedirects(post, reverse('admin:admin_views_article_changelist'))
self.assertEqual(Article.objects.count(), 5) 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 # one error in form should produce singular error message, multiple errors plural
change_dict['title'] = '' change_dict['title'] = ''
post = self.client.post(article_change_url, change_dict) post = self.client.post(article_change_url, change_dict)
self.assertContains(post, 'Please correct the error below.', self.assertContains(
msg_prefix='Singular error message not found in response to post with one error') post, 'Please correct the error below.',
msg_prefix='Singular error message not found in response to post with one error'
)
change_dict['content'] = '' change_dict['content'] = ''
post = self.client.post(article_change_url, change_dict) post = self.client.post(article_change_url, change_dict)
self.assertContains(post, 'Please correct the errors below.', self.assertContains(
msg_prefix='Plural error message not found in response to post with multiple errors') 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')) self.client.get(reverse('admin:logout'))
# Test redirection when using row-level change permissions. Refs #11513. # Test redirection when using row-level change permissions. Refs #11513.
@ -2292,14 +2326,16 @@ class AdminViewStringPrimaryKeyTest(TestCase):
def test_change_view_history_link(self): def test_change_view_history_link(self):
"""Object history button link should work and contain the pk value quoted.""" """Object history button link should work and contain the pk value quoted."""
url = reverse('admin:%s_modelwithstringprimarykey_change' % url = reverse(
ModelWithStringPrimaryKey._meta.app_label, 'admin:%s_modelwithstringprimarykey_change' % ModelWithStringPrimaryKey._meta.app_label,
args=(quote(self.pk),)) args=(quote(self.pk),)
)
response = self.client.get(url) response = self.client.get(url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
expected_link = reverse('admin:%s_modelwithstringprimarykey_history' % expected_link = reverse(
ModelWithStringPrimaryKey._meta.app_label, 'admin:%s_modelwithstringprimarykey_history' % ModelWithStringPrimaryKey._meta.app_label,
args=(quote(self.pk),)) args=(quote(self.pk),)
)
self.assertContains(response, '<a href="%s" class="historylink"' % escape(expected_link)) self.assertContains(response, '<a href="%s" class="historylink"' % escape(expected_link))
def test_redirect_on_add_view_continue_button(self): def test_redirect_on_add_view_continue_button(self):
@ -2443,8 +2479,7 @@ class AdminViewListEditable(TestCase):
self.client.force_login(self.superuser) self.client.force_login(self.superuser)
def test_inheritance(self): def test_inheritance(self):
Podcast.objects.create(name="This Week in Django", Podcast.objects.create(name="This Week in Django", release_date=datetime.date.today())
release_date=datetime.date.today())
response = self.client.get(reverse('admin:admin_views_podcast_changelist')) response = self.client.get(reverse('admin:admin_views_podcast_changelist'))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -2939,9 +2974,11 @@ class AdminSearchTest(TestCase):
# + 1 for total count # + 1 for total count
with self.assertNumQueries(5): with self.assertNumQueries(5):
response = self.client.get(reverse('admin:admin_views_person_changelist') + '?q=Gui') response = self.client.get(reverse('admin:admin_views_person_changelist') + '?q=Gui')
self.assertContains(response, self.assertContains(
response,
"""<span class="small quiet">1 result (<a href="?">3 total</a>)</span>""", """<span class="small quiet">1 result (<a href="?">3 total</a>)</span>""",
html=True) html=True
)
def test_no_total_count(self): def test_no_total_count(self):
""" """
@ -2952,9 +2989,11 @@ class AdminSearchTest(TestCase):
# + 1 for filtered result + 1 for filtered count # + 1 for filtered result + 1 for filtered count
with self.assertNumQueries(4): with self.assertNumQueries(4):
response = self.client.get(reverse('admin:admin_views_recommendation_changelist') + '?q=bar') response = self.client.get(reverse('admin:admin_views_recommendation_changelist') + '?q=bar')
self.assertContains(response, self.assertContains(
response,
"""<span class="small quiet">1 result (<a href="?">Show all</a>)</span>""", """<span class="small quiet">1 result (<a href="?">Show all</a>)</span>""",
html=True) html=True
)
self.assertTrue(response.context['cl'].show_admin_actions) self.assertTrue(response.context['cl'].show_admin_actions)
@ -3244,16 +3283,20 @@ action)</option>
"Tests a ModelAdmin without any action" "Tests a ModelAdmin without any action"
response = self.client.get(reverse('admin:admin_views_oldsubscriber_changelist')) response = self.client.get(reverse('admin:admin_views_oldsubscriber_changelist'))
self.assertEqual(response.context["action_form"], None) self.assertEqual(response.context["action_form"], None)
self.assertNotContains(response, '<input type="checkbox" class="action-select"', self.assertNotContains(
msg_prefix="Found an unexpected action toggle checkboxbox in response") response, '<input type="checkbox" class="action-select"',
msg_prefix="Found an unexpected action toggle checkboxbox in response"
)
self.assertNotContains(response, '<input type="checkbox" class="action-select"') self.assertNotContains(response, '<input type="checkbox" class="action-select"')
def test_model_without_action_still_has_jquery(self): def test_model_without_action_still_has_jquery(self):
"Tests that a ModelAdmin without any actions still gets jQuery included in page" "Tests that a ModelAdmin without any actions still gets jQuery included in page"
response = self.client.get(reverse('admin:admin_views_oldsubscriber_changelist')) response = self.client.get(reverse('admin:admin_views_oldsubscriber_changelist'))
self.assertEqual(response.context["action_form"], None) self.assertEqual(response.context["action_form"], None)
self.assertContains(response, 'jquery.min.js', self.assertContains(
msg_prefix="jQuery missing from admin pages for model with no admin actions") response, 'jquery.min.js',
msg_prefix="jQuery missing from admin pages for model with no admin actions"
)
def test_action_column_class(self): def test_action_column_class(self):
"Tests that the checkbox column class is present in the response" "Tests that the checkbox column class is present in the response"
@ -3467,8 +3510,7 @@ class AdminCustomQuerysetTest(TestCase):
"author": "Candidate, Best", "author": "Candidate, Best",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_coverletter_add'), response = self.client.post(reverse('admin:admin_views_coverletter_add'), post_data, follow=True)
post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(CoverLetter.objects.count(), 1) self.assertEqual(CoverLetter.objects.count(), 1)
# Message should contain non-ugly model verbose name # Message should contain non-ugly model verbose name
@ -3487,8 +3529,7 @@ class AdminCustomQuerysetTest(TestCase):
"content": "What's this SMS thing?", "content": "What's this SMS thing?",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_shortmessage_add'), response = self.client.post(reverse('admin:admin_views_shortmessage_add'), post_data, follow=True)
post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(ShortMessage.objects.count(), 1) self.assertEqual(ShortMessage.objects.count(), 1)
# Message should contain non-ugly model verbose name # Message should contain non-ugly model verbose name
@ -3510,8 +3551,7 @@ class AdminCustomQuerysetTest(TestCase):
"title": "Urgent telegram", "title": "Urgent telegram",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_telegram_add'), response = self.client.post(reverse('admin:admin_views_telegram_add'), post_data, follow=True)
post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(Telegram.objects.count(), 1) self.assertEqual(Telegram.objects.count(), 1)
# Message should contain non-ugly model verbose name # Message should contain non-ugly model verbose name
@ -3530,8 +3570,7 @@ class AdminCustomQuerysetTest(TestCase):
"title": "My Modified Paper Title", "title": "My Modified Paper Title",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_paper_add'), response = self.client.post(reverse('admin:admin_views_paper_add'), post_data, follow=True)
post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(Paper.objects.count(), 1) self.assertEqual(Paper.objects.count(), 1)
# Message should contain non-ugly model verbose name # Message should contain non-ugly model verbose name
@ -3556,8 +3595,8 @@ class AdminCustomQuerysetTest(TestCase):
"author": "John Doe II", "author": "John Doe II",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_coverletter_change', args=(cl.pk,)), url = reverse('admin:admin_views_coverletter_change', args=(cl.pk,))
post_data, follow=True) response = self.client.post(url, post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(CoverLetter.objects.count(), 1) self.assertEqual(CoverLetter.objects.count(), 1)
# Message should contain non-ugly model verbose name. Instance # Message should contain non-ugly model verbose name. Instance
@ -3579,8 +3618,8 @@ class AdminCustomQuerysetTest(TestCase):
"content": "Too expensive", "content": "Too expensive",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_shortmessage_change', args=(sm.pk,)), url = reverse('admin:admin_views_shortmessage_change', args=(sm.pk,))
post_data, follow=True) response = self.client.post(url, post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(ShortMessage.objects.count(), 1) self.assertEqual(ShortMessage.objects.count(), 1)
# Message should contain non-ugly model verbose name. The ugly(!) # Message should contain non-ugly model verbose name. The ugly(!)
@ -3605,8 +3644,7 @@ class AdminCustomQuerysetTest(TestCase):
"title": "Telegram without typo", "title": "Telegram without typo",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_telegram_change', args=(t.pk,)), response = self.client.post(reverse('admin:admin_views_telegram_change', args=(t.pk,)), post_data, follow=True)
post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(Telegram.objects.count(), 1) self.assertEqual(Telegram.objects.count(), 1)
# Message should contain non-ugly model verbose name. The instance # Message should contain non-ugly model verbose name. The instance
@ -3628,8 +3666,7 @@ class AdminCustomQuerysetTest(TestCase):
"title": "My Modified Paper Title", "title": "My Modified Paper Title",
"_save": "Save", "_save": "Save",
} }
response = self.client.post(reverse('admin:admin_views_paper_change', args=(p.pk,)), response = self.client.post(reverse('admin:admin_views_paper_change', args=(p.pk,)), post_data, follow=True)
post_data, follow=True)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(Paper.objects.count(), 1) self.assertEqual(Paper.objects.count(), 1)
# Message should contain non-ugly model verbose name. The ugly(!) # Message should contain non-ugly model verbose name. The ugly(!)
@ -4152,8 +4189,7 @@ class SeleniumTests(AdminSeleniumTestCase):
Refs #13068, #9264, #9983, #9784. Refs #13068, #9264, #9983, #9784.
""" """
self.admin_login(username='super', password='secret', login_url=reverse('admin:index')) self.admin_login(username='super', password='secret', login_url=reverse('admin:index'))
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_views_mainprepopulated_add'))
reverse('admin:admin_views_mainprepopulated_add')))
# Main form ---------------------------------------------------------- # Main form ----------------------------------------------------------
self.selenium.find_element_by_id('id_pubdate').send_keys('2012-02-18') self.selenium.find_element_by_id('id_pubdate').send_keys('2012-02-18')
@ -4273,13 +4309,9 @@ class SeleniumTests(AdminSeleniumTestCase):
slug1='', slug1='',
slug2='', slug2='',
) )
self.admin_login(username='super', self.admin_login(username='super', password='secret', login_url=reverse('admin:index'))
password='secret',
login_url=reverse('admin:index'))
object_url = '%s%s' % ( object_url = self.live_server_url + reverse('admin:admin_views_mainprepopulated_change', args=(item.id,))
self.live_server_url,
reverse('admin:admin_views_mainprepopulated_change', args=(item.id,)))
self.selenium.get(object_url) self.selenium.get(object_url)
self.selenium.find_element_by_id('id_name').send_keys(' the best') self.selenium.find_element_by_id('id_name').send_keys(' the best')
@ -4309,30 +4341,24 @@ class SeleniumTests(AdminSeleniumTestCase):
show/hide the appropriate field section. show/hide the appropriate field section.
""" """
self.admin_login(username='super', password='secret', login_url=reverse('admin:index')) self.admin_login(username='super', password='secret', login_url=reverse('admin:index'))
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_views_article_add'))
reverse('admin:admin_views_article_add')))
self.assertFalse(self.selenium.find_element_by_id('id_title').is_displayed()) self.assertFalse(self.selenium.find_element_by_id('id_title').is_displayed())
self.selenium.find_elements_by_link_text('Show')[0].click() self.selenium.find_elements_by_link_text('Show')[0].click()
self.assertTrue(self.selenium.find_element_by_id('id_title').is_displayed()) self.assertTrue(self.selenium.find_element_by_id('id_title').is_displayed())
self.assertEqual( self.assertEqual(self.selenium.find_element_by_id('fieldsetcollapser0').text, "Hide")
self.selenium.find_element_by_id('fieldsetcollapser0').text,
"Hide"
)
def test_first_field_focus(self): def test_first_field_focus(self):
"""JavaScript-assisted auto-focus on first usable form field.""" """JavaScript-assisted auto-focus on first usable form field."""
# First form field has a single widget # First form field has a single widget
self.admin_login(username='super', password='secret', login_url=reverse('admin:index')) self.admin_login(username='super', password='secret', login_url=reverse('admin:index'))
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_views_picture_add'))
reverse('admin:admin_views_picture_add')))
self.assertEqual( self.assertEqual(
self.selenium.switch_to.active_element, self.selenium.switch_to.active_element,
self.selenium.find_element_by_id('id_name') self.selenium.find_element_by_id('id_name')
) )
# First form field has a MultiWidget # First form field has a MultiWidget
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_views_reservation_add'))
reverse('admin:admin_views_reservation_add')))
self.assertEqual( self.assertEqual(
self.selenium.switch_to.active_element, self.selenium.switch_to.active_element,
self.selenium.find_element_by_id('id_start_date_0') self.selenium.find_element_by_id('id_start_date_0')
@ -4342,7 +4368,7 @@ class SeleniumTests(AdminSeleniumTestCase):
"Cancelling the deletion of an object takes the user back one page." "Cancelling the deletion of an object takes the user back one page."
pizza = Pizza.objects.create(name="Double Cheese") pizza = Pizza.objects.create(name="Double Cheese")
url = reverse('admin:admin_views_pizza_change', args=(pizza.id,)) url = reverse('admin:admin_views_pizza_change', args=(pizza.id,))
full_url = '%s%s' % (self.live_server_url, url) full_url = self.live_server_url + url
self.admin_login(username='super', password='secret', login_url=reverse('admin:index')) self.admin_login(username='super', password='secret', login_url=reverse('admin:index'))
self.selenium.get(full_url) self.selenium.get(full_url)
self.selenium.find_element_by_class_name('deletelink').click() self.selenium.find_element_by_class_name('deletelink').click()
@ -4363,7 +4389,7 @@ class SeleniumTests(AdminSeleniumTestCase):
topping2 = Topping.objects.create(name="Mozzarella") topping2 = Topping.objects.create(name="Mozzarella")
pizza.toppings.add(topping1, topping2) pizza.toppings.add(topping1, topping2)
url = reverse('admin:admin_views_pizza_change', args=(pizza.id,)) url = reverse('admin:admin_views_pizza_change', args=(pizza.id,))
full_url = '%s%s' % (self.live_server_url, url) full_url = self.live_server_url + url
self.admin_login(username='super', password='secret', login_url=reverse('admin:index')) self.admin_login(username='super', password='secret', login_url=reverse('admin:index'))
self.selenium.get(full_url) self.selenium.get(full_url)
self.selenium.find_element_by_class_name('deletelink').click() self.selenium.find_element_by_class_name('deletelink').click()
@ -4498,8 +4524,7 @@ class ReadonlyTest(AdminFieldExtractionMixin, TestCase):
# hidden fields for inlines + 1 field for the inline + 2 empty form # hidden fields for inlines + 1 field for the inline + 2 empty form
self.assertContains(response, "<input", count=15) self.assertContains(response, "<input", count=15)
self.assertContains(response, formats.localize(datetime.date.today())) self.assertContains(response, formats.localize(datetime.date.today()))
self.assertContains(response, self.assertContains(response, "<label>Awesomeness level:</label>")
"<label>Awesomeness level:</label>")
self.assertContains(response, "Very awesome.") self.assertContains(response, "Very awesome.")
self.assertContains(response, "Unknown coolness.") self.assertContains(response, "Unknown coolness.")
self.assertContains(response, "foo") self.assertContains(response, "foo")
@ -4511,8 +4536,7 @@ class ReadonlyTest(AdminFieldExtractionMixin, TestCase):
# Remove only this last line when the deprecation completes. # Remove only this last line when the deprecation completes.
self.assertContains(response, "<p>Multiline<br />html<br />content<br />with allow tags</p>", html=True) self.assertContains(response, "<p>Multiline<br />html<br />content<br />with allow tags</p>", html=True)
self.assertContains(response, self.assertContains(response, formats.localize(datetime.date.today() - datetime.timedelta(days=7)))
formats.localize(datetime.date.today() - datetime.timedelta(days=7)))
self.assertContains(response, '<div class="form-row field-coolness">') self.assertContains(response, '<div class="form-row field-coolness">')
self.assertContains(response, '<div class="form-row field-awesomeness_level">') self.assertContains(response, '<div class="form-row field-awesomeness_level">')
@ -4828,8 +4852,7 @@ class UserAdminTest(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
adminform = response.context['adminform'] adminform = response.context['adminform']
self.assertNotIn('password', adminform.form.errors) self.assertNotIn('password', adminform.form.errors)
self.assertEqual(adminform.form.errors['password2'], self.assertEqual(adminform.form.errors['password2'], ["The two password fields didn't match."])
["The two password fields didn't match."])
def test_user_fk_add_popup(self): def test_user_fk_add_popup(self):
"""User addition through a FK popup should return the appropriate JavaScript response.""" """User addition through a FK popup should return the appropriate JavaScript response."""
@ -5019,26 +5042,22 @@ class CSSTest(TestCase):
Ensure app and model tag are correctly read by change_form template Ensure app and model tag are correctly read by change_form template
""" """
response = self.client.get(reverse('admin:admin_views_section_add')) response = self.client.get(reverse('admin:admin_views_section_add'))
self.assertContains(response, self.assertContains(response, '<body class=" app-admin_views model-section ')
'<body class=" app-admin_views model-section ')
def test_app_model_in_list_body_class(self): def test_app_model_in_list_body_class(self):
""" """
Ensure app and model tag are correctly read by change_list template Ensure app and model tag are correctly read by change_list template
""" """
response = self.client.get(reverse('admin:admin_views_section_changelist')) response = self.client.get(reverse('admin:admin_views_section_changelist'))
self.assertContains(response, self.assertContains(response, '<body class=" app-admin_views model-section ')
'<body class=" app-admin_views model-section ')
def test_app_model_in_delete_confirmation_body_class(self): def test_app_model_in_delete_confirmation_body_class(self):
""" """
Ensure app and model tag are correctly read by delete_confirmation Ensure app and model tag are correctly read by delete_confirmation
template template
""" """
response = self.client.get( response = self.client.get(reverse('admin:admin_views_section_delete', args=(self.s1.pk,)))
reverse('admin:admin_views_section_delete', args=(self.s1.pk,))) self.assertContains(response, '<body class=" app-admin_views model-section ')
self.assertContains(response,
'<body class=" app-admin_views model-section ')
def test_app_model_in_app_index_body_class(self): def test_app_model_in_app_index_body_class(self):
""" """
@ -5057,25 +5076,19 @@ class CSSTest(TestCase):
'action': 'delete_selected', 'action': 'delete_selected',
'index': 0, 'index': 0,
} }
response = self.client.post(reverse('admin:admin_views_section_changelist'), response = self.client.post(reverse('admin:admin_views_section_changelist'), action_data)
action_data) self.assertContains(response, '<body class=" app-admin_views model-section ')
self.assertContains(response,
'<body class=" app-admin_views model-section ')
def test_changelist_field_classes(self): def test_changelist_field_classes(self):
""" """
Cells of the change list table should contain the field name in their class attribute Cells of the change list table should contain the field name in their class attribute
Refs #11195. Refs #11195.
""" """
Podcast.objects.create(name="Django Dose", Podcast.objects.create(name="Django Dose", release_date=datetime.date.today())
release_date=datetime.date.today())
response = self.client.get(reverse('admin:admin_views_podcast_changelist')) response = self.client.get(reverse('admin:admin_views_podcast_changelist'))
self.assertContains( self.assertContains(response, '<th class="field-name">')
response, '<th class="field-name">') self.assertContains(response, '<td class="field-release_date nowrap">')
self.assertContains( self.assertContains(response, '<td class="action-checkbox">')
response, '<td class="field-release_date nowrap">')
self.assertContains(
response, '<td class="action-checkbox">')
try: try:

View File

@ -215,18 +215,15 @@ class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase):
# Try posting with a non-existent pk in a raw id field: this # Try posting with a non-existent pk in a raw id field: this
# should result in an error message, not a server exception. # should result in an error message, not a server exception.
response = self.client.post(reverse('admin:admin_widgets_event_add'), post_data) response = self.client.post(reverse('admin:admin_widgets_event_add'), post_data)
self.assertContains(response, self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.')
'Select a valid choice. That choice is not one of the available choices.')
def test_invalid_target_id(self): def test_invalid_target_id(self):
for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): 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. # This should result in an error message, not a server exception.
response = self.client.post(reverse('admin:admin_widgets_event_add'), response = self.client.post(reverse('admin:admin_widgets_event_add'), {"main_band": test_str})
{"main_band": test_str})
self.assertContains(response, self.assertContains(response, 'Select a valid choice. That choice is not one of the available choices.')
'Select a valid choice. That choice is not one of the available choices.')
def test_url_params_from_lookup_dict_any_iterable(self): def test_url_params_from_lookup_dict_any_iterable(self):
lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')}) 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='/') self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets # Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add'))
reverse('admin:admin_widgets_member_add')))
# First, with the date picker widget --------------------------------- # First, with the date picker widget ---------------------------------
# Check that the date picker is hidden # Check that the date picker is hidden
self.assertEqual( self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none')
self.get_css_value('#calendarbox0', 'display'), 'none')
# Click the calendar icon # Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click() self.selenium.find_element_by_id('calendarlink0').click()
# Check that the date picker is visible # Check that the date picker is visible
self.assertEqual( self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'block')
self.get_css_value('#calendarbox0', 'display'), 'block')
# Press the ESC key # Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the date picker is hidden again # Check that the date picker is hidden again
self.assertEqual( self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none')
self.get_css_value('#calendarbox0', 'display'), 'none')
# Then, with the time picker widget ---------------------------------- # Then, with the time picker widget ----------------------------------
# Check that the time picker is hidden # Check that the time picker is hidden
self.assertEqual( self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'none')
self.get_css_value('#clockbox0', 'display'), 'none')
# Click the time icon # Click the time icon
self.selenium.find_element_by_id('clocklink0').click() self.selenium.find_element_by_id('clocklink0').click()
# Check that the time picker is visible # Check that the time picker is visible
self.assertEqual( self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'block')
self.get_css_value('#clockbox0', 'display'), 'block')
self.assertEqual( self.assertEqual(
[ [
x.text for x in x.text for x in
@ -671,8 +662,7 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase):
# Press the ESC key # Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE]) self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the time picker is hidden again # Check that the time picker is hidden again
self.assertEqual( self.assertEqual(self.get_css_value('#clockbox0', 'display'), 'none')
self.get_css_value('#clockbox0', 'display'), 'none')
def test_calendar_nonday_class(self): def test_calendar_nonday_class(self):
""" """
@ -681,8 +671,7 @@ class DateTimePickerSeleniumTests(AdminWidgetSeleniumTestCase):
""" """
self.admin_login(username='super', password='secret', login_url='/') self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets # Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add'))
reverse('admin:admin_widgets_member_add')))
# fill in the birth date. # fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01') 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='/') self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets # Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add'))
reverse('admin:admin_widgets_member_add')))
# fill in the birth date. # fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01') 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='/') self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets # Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add'))
reverse('admin:admin_widgets_member_add')))
# Click the calendar icon # Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click() 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): with override_settings(LANGUAGE_CODE=language_code, USE_L10N=True):
# Open a page that has a date picker widget # Open a page that has a date picker widget
self.selenium.get('{}{}'.format(self.live_server_url, url = reverse('admin:admin_widgets_member_change', args=(member.pk,))
reverse('admin:admin_widgets_member_change', args=(member.pk,)))) self.selenium.get(self.live_server_url + url)
# Click on the calendar icon # Click on the calendar icon
self.selenium.find_element_by_id('calendarlink0').click() self.selenium.find_element_by_id('calendarlink0').click()
# Make sure that the right month and year are displayed # Make sure that the right month and year are displayed
@ -813,14 +799,12 @@ class DateTimePickerShortcutsSeleniumTests(AdminWidgetSeleniumTestCase):
now = datetime.now() now = datetime.now()
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_member_add'))
reverse('admin:admin_widgets_member_add')))
self.selenium.find_element_by_id('id_name').send_keys('test') self.selenium.find_element_by_id('id_name').send_keys('test')
# Click on the "today" and "now" shortcuts. # Click on the "today" and "now" shortcuts.
shortcuts = self.selenium.find_elements_by_css_selector( shortcuts = self.selenium.find_elements_by_css_selector('.field-birthdate .datetimeshortcuts')
'.field-birthdate .datetimeshortcuts')
for shortcut in shortcuts: for shortcut in shortcuts:
shortcut.find_element_by_tag_name('a').click() 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 # Warning: This would effectively fail if the TIME_ZONE defined in the
# settings has the same UTC offset as "Asia/Singapore" because the # settings has the same UTC offset as "Asia/Singapore" because the
# mismatch warning would be rightfully missing from the page. # mismatch warning would be rightfully missing from the page.
self.selenium.find_elements_by_css_selector( self.selenium.find_elements_by_css_selector('.field-birthdate .timezonewarning')
'.field-birthdate .timezonewarning')
# Submit the form. # Submit the form.
self.selenium.find_element_by_tag_name('form').submit() 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.arthur = models.Student.objects.create(name='Arthur')
self.school = models.School.objects.create(name='School of Awesome') self.school = models.School.objects.create(name='School of Awesome')
def assertActiveButtons(self, mode, field_name, choose, remove, def assertActiveButtons(self, mode, field_name, choose, remove, choose_all=None, remove_all=None):
choose_all=None, remove_all=None):
choose_link = '#id_%s_add_link' % field_name choose_link = '#id_%s_add_link' % field_name
choose_all_link = '#id_%s_add_all_link' % field_name choose_all_link = '#id_%s_add_all_link' % field_name
remove_link = '#id_%s_remove_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 remove_all_link = 'id_%s_remove_all_link' % field_name
# Initial positions --------------------------------------------------- # Initial positions ---------------------------------------------------
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.arthur.id), str(self.bob.id), str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id), str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)]) str(self.jenny.id), str(self.john.id),
self.assertSelectOptions(to_box, ])
[str(self.lisa.id), str(self.peter.id)]) self.assertSelectOptions(to_box, [str(self.lisa.id), str(self.peter.id)])
self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertActiveButtons(mode, field_name, False, False, True, True)
# Click 'Choose all' -------------------------------------------------- # Click 'Choose all' --------------------------------------------------
@ -903,11 +885,12 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase):
option.click() option.click()
self.selenium.find_element_by_id(choose_link).click() self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box, []) self.assertSelectOptions(from_box, [])
self.assertSelectOptions(to_box, self.assertSelectOptions(to_box, [
[str(self.lisa.id), str(self.peter.id), str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id), str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id), str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)]) str(self.jenny.id), str(self.john.id),
])
self.assertActiveButtons(mode, field_name, False, False, False, True) self.assertActiveButtons(mode, field_name, False, False, False, True)
# Click 'Remove all' -------------------------------------------------- # Click 'Remove all' --------------------------------------------------
@ -919,11 +902,12 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase):
for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'): for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'):
option.click() option.click()
self.selenium.find_element_by_id(remove_link).click() self.selenium.find_element_by_id(remove_link).click()
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.lisa.id), str(self.peter.id), str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id), str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id), str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)]) str(self.jenny.id), str(self.john.id),
])
self.assertSelectOptions(to_box, []) self.assertSelectOptions(to_box, [])
self.assertActiveButtons(mode, field_name, False, False, True, False) 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.selenium.find_element_by_id(choose_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.peter.id), str(self.arthur.id), str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id)]) str(self.cliff.id), str(self.jenny.id),
self.assertSelectOptions(to_box, ])
[str(self.lisa.id), str(self.bob.id), self.assertSelectOptions(to_box, [
str(self.jason.id), str(self.john.id)]) 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 # Check the tooltip is still there after moving: ticket #20821
to_lisa_select_option = self.get_select_option(to_box, str(self.lisa.id)) 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.selenium.find_element_by_id(remove_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True) self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.peter.id), str(self.arthur.id), str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id), str(self.cliff.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)]) str(self.lisa.id), str(self.bob.id)
self.assertSelectOptions(to_box, ])
[str(self.jason.id), str(self.john.id)]) self.assertSelectOptions(to_box, [str(self.jason.id), str(self.john.id)])
# Choose some more options -------------------------------------------- # Choose some more options --------------------------------------------
self.get_select_option(from_box, str(self.arthur.id)).click() self.get_select_option(from_box, str(self.arthur.id)).click()
self.get_select_option(from_box, str(self.cliff.id)).click() self.get_select_option(from_box, str(self.cliff.id)).click()
self.selenium.find_element_by_id(choose_link).click() self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.peter.id), str(self.jenny.id), str(self.peter.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)]) str(self.lisa.id), str(self.bob.id),
self.assertSelectOptions(to_box, ])
[str(self.jason.id), str(self.john.id), self.assertSelectOptions(to_box, [
str(self.arthur.id), str(self.cliff.id)]) str(self.jason.id), str(self.john.id),
str(self.arthur.id), str(self.cliff.id),
])
def test_basic(self): def test_basic(self):
self.school.students.set([self.lisa, self.peter]) self.school.students.set([self.lisa, self.peter])
self.school.alumni.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter])
self.admin_login(username='super', password='secret', login_url='/') self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get('%s%s' % ( self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_school_change', args=(self.school.id,)))
self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,))))
self.wait_page_loaded() self.wait_page_loaded()
self.execute_basic_operations('vertical', 'students') self.execute_basic_operations('vertical', 'students')
@ -994,10 +981,8 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase):
self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded() self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()), self.assertEqual(list(self.school.students.all()), [self.arthur, self.cliff, self.jason, self.john])
[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.alumni.all()),
[self.arthur, self.cliff, self.jason, self.john])
def test_filter(self): def test_filter(self):
""" """
@ -1010,8 +995,7 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase):
self.school.alumni.set([self.lisa, self.peter]) self.school.alumni.set([self.lisa, self.peter])
self.admin_login(username='super', password='secret', login_url='/') self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get( self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_school_change', args=(self.school.id,)))
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,))))
for field_name in ['students', 'alumni']: for field_name in ['students', 'alumni']:
from_box = '#id_%s_from' % field_name 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) input = self.selenium.find_element_by_id('id_%s_input' % field_name)
# Initial values # Initial values
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.arthur.id), str(self.bob.id), str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id), str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)]) str(self.jenny.id), str(self.john.id),
])
# Typing in some characters filters out non-matching options # Typing in some characters filters out non-matching options
input.send_keys('a') input.send_keys('a')
@ -1036,10 +1021,11 @@ class HorizontalVerticalFilterSeleniumTests(AdminWidgetSeleniumTestCase):
input.send_keys([Keys.BACK_SPACE]) input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)]) self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE]) input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.arthur.id), str(self.bob.id), str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id), str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)]) str(self.jenny.id), str(self.john.id),
])
# ----------------------------------------------------------------- # -----------------------------------------------------------------
# Check that choosing a filtered option sends it properly to the # 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.get_select_option(from_box, str(self.jason.id)).click()
self.selenium.find_element_by_id(choose_link).click() self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box, [str(self.arthur.id)]) self.assertSelectOptions(from_box, [str(self.arthur.id)])
self.assertSelectOptions(to_box, self.assertSelectOptions(to_box, [
[str(self.lisa.id), str(self.peter.id), str(self.lisa.id), str(self.peter.id), str(self.jason.id),
str(self.jason.id)]) ])
self.get_select_option(to_box, str(self.lisa.id)).click() self.get_select_option(to_box, str(self.lisa.id)).click()
self.selenium.find_element_by_id(remove_link).click() self.selenium.find_element_by_id(remove_link).click()
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.lisa.id)])
[str(self.arthur.id), str(self.lisa.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)])
self.assertSelectOptions(to_box,
[str(self.peter.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE]) # Clear text box input.send_keys([Keys.BACK_SPACE]) # Clear text box
self.assertSelectOptions(from_box, self.assertSelectOptions(from_box, [
[str(self.arthur.id), str(self.bob.id), str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jenny.id), str(self.cliff.id), str(self.jenny.id),
str(self.john.id), str(self.lisa.id)]) str(self.john.id), str(self.lisa.id),
self.assertSelectOptions(to_box, ])
[str(self.peter.id), str(self.jason.id)]) self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)])
# ----------------------------------------------------------------- # -----------------------------------------------------------------
# Check that pressing enter on a filtered option sends it properly # 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.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded() self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()), self.assertEqual(list(self.school.students.all()), [self.jason, self.peter])
[self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter])
self.assertEqual(list(self.school.alumni.all()),
[self.jason, self.peter])
def test_back_button_bug(self): def test_back_button_bug(self):
""" """
@ -1147,14 +1129,11 @@ class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase):
def test_ForeignKey(self): def test_ForeignKey(self):
self.admin_login(username='super', password='secret', login_url='/') self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get( self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_event_add'))
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add')))
main_window = self.selenium.current_window_handle main_window = self.selenium.current_window_handle
# No value has been selected yet # No value has been selected yet
self.assertEqual( self.assertEqual(self.selenium.find_element_by_id('id_main_band').get_attribute('value'), '')
self.selenium.find_element_by_id('id_main_band').get_attribute('value'),
'')
# Open the popup window and click on a band # Open the popup window and click on a band
self.selenium.find_element_by_id('lookup_id_main_band').click() self.selenium.find_element_by_id('lookup_id_main_band').click()
@ -1182,14 +1161,11 @@ class AdminRawIdWidgetSeleniumTests(AdminWidgetSeleniumTestCase):
def test_many_to_many(self): def test_many_to_many(self):
self.admin_login(username='super', password='secret', login_url='/') self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get( self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_event_add'))
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add')))
main_window = self.selenium.current_window_handle main_window = self.selenium.current_window_handle
# No value has been selected yet # No value has been selected yet
self.assertEqual( self.assertEqual(self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '')
self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'),
'')
# Help text for the field is displayed # Help text for the field is displayed
self.assertEqual( self.assertEqual(
@ -1226,9 +1202,7 @@ class RelatedFieldWidgetSeleniumTests(AdminWidgetSeleniumTestCase):
def test_ForeignKey_using_to_field(self): def test_ForeignKey_using_to_field(self):
self.admin_login(username='super', password='secret', login_url='/') self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get('%s%s' % ( self.selenium.get(self.live_server_url + reverse('admin:admin_widgets_profile_add'))
self.live_server_url,
reverse('admin:admin_widgets_profile_add')))
main_window = self.selenium.current_window_handle main_window = self.selenium.current_window_handle
# Click the Add User button to add new # Click the Add User button to add new

View File

@ -1238,19 +1238,27 @@ class AggregationTests(TestCase):
tests aggregations with generic reverse relations tests aggregations with generic reverse relations
""" """
django_book = Book.objects.get(name='Practical Django Projects') django_book = Book.objects.get(name='Practical Django Projects')
ItemTag.objects.create(object_id=django_book.id, tag='intermediate', ItemTag.objects.create(
content_type=ContentType.objects.get_for_model(django_book)) object_id=django_book.id, tag='intermediate',
ItemTag.objects.create(object_id=django_book.id, tag='django', content_type=ContentType.objects.get_for_model(django_book),
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 # 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 # used in aggregation doesn't have content type as part of the
# condition the annotation will also count the 'hi mom' tag for b. # condition the annotation will also count the 'hi mom' tag for b.
wmpk = WithManualPK.objects.create(id=django_book.pk) wmpk = WithManualPK.objects.create(id=django_book.pk)
ItemTag.objects.create(object_id=wmpk.id, tag='hi mom', ItemTag.objects.create(
content_type=ContentType.objects.get_for_model(wmpk)) 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') ai_book = Book.objects.get(name__startswith='Paradigms of Artificial Intelligence')
ItemTag.objects.create(object_id=ai_book.id, tag='intermediate', ItemTag.objects.create(
content_type=ContentType.objects.get_for_model(ai_book)) 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}) self.assertEqual(Book.objects.aggregate(Count('tags')), {'tags__count': 3})
results = Book.objects.annotate(Count('tags')).order_by('-tags__count', 'name') results = Book.objects.annotate(Count('tags')).order_by('-tags__count', 'name')

View File

@ -81,8 +81,8 @@ class Company(models.Model):
description = models.CharField(max_length=200, null=True, blank=True) description = models.CharField(max_length=200, null=True, blank=True)
def __str__(self): def __str__(self):
return ('Company(name=%s, motto=%s, ticker_name=%s, description=%s)' return 'Company(name=%s, motto=%s, ticker_name=%s, description=%s)' % (
% (self.name, self.motto, self.ticker_name, self.description) self.name, self.motto, self.ticker_name, self.description,
) )

View File

@ -244,8 +244,7 @@ class AppsTests(SimpleTestCase):
body = {} body = {}
body['Meta'] = type(str("Meta"), tuple(), meta_contents) body['Meta'] = type(str("Meta"), tuple(), meta_contents)
body['__module__'] = TotallyNormal.__module__ + '.whatever' body['__module__'] = TotallyNormal.__module__ + '.whatever'
with six.assertRaisesRegex(self, RuntimeError, with self.assertRaisesMessage(RuntimeError, "Conflicting 'southponies' models in application 'apps':"):
"Conflicting 'southponies' models in application 'apps':.*"):
type(str("SouthPonies"), (models.Model,), body) type(str("SouthPonies"), (models.Model,), body)
def test_get_containing_app_config_apps_not_ready(self): def test_get_containing_app_config_apps_not_ready(self):

View File

@ -51,8 +51,7 @@ class LoginRequiredTestCase(AuthViewsTestCase):
Check that login_required works on a simple view wrapped in a Check that login_required works on a simple view wrapped in a
login_required decorator with a login_url set. login_required decorator with a login_url set.
""" """
self.testLoginRequired(view_url='/login_required_login_url/', self.testLoginRequired(view_url='/login_required_login_url/', login_url='/somewhere/')
login_url='/somewhere/')
class PermissionsRequiredDecoratorTest(TestCase): class PermissionsRequiredDecoratorTest(TestCase):

View File

@ -180,10 +180,13 @@ class AuthenticationFormTest(TestDataMixin, TestCase):
} }
form = AuthenticationForm(None, data) form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), self.assertEqual(
[force_text(form.error_messages['invalid_login'] % { form.non_field_errors(), [
force_text(form.error_messages['invalid_login'] % {
'username': User._meta.get_field('username').verbose_name 'username': User._meta.get_field('username').verbose_name
})]) })
]
)
def test_inactive_user(self): def test_inactive_user(self):
# The user is inactive. # The user is inactive.
@ -193,8 +196,7 @@ class AuthenticationFormTest(TestDataMixin, TestCase):
} }
form = AuthenticationForm(None, data) form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
[force_text(form.error_messages['inactive'])])
def test_inactive_user_i18n(self): def test_inactive_user_i18n(self):
with self.settings(USE_I18N=True), translation.override('pt-br', deactivate=True): with self.settings(USE_I18N=True), translation.override('pt-br', deactivate=True):
@ -205,8 +207,7 @@ class AuthenticationFormTest(TestDataMixin, TestCase):
} }
form = AuthenticationForm(None, data) form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), self.assertEqual(form.non_field_errors(), [force_text(form.error_messages['inactive'])])
[force_text(form.error_messages['inactive'])])
def test_custom_login_allowed_policy(self): def test_custom_login_allowed_policy(self):
# The user is inactive, but our custom form policy allows them to log in. # 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) form = SetPasswordForm(user, data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form["new_password2"].errors, self.assertEqual(
[force_text(form.error_messages['password_mismatch'])]) form["new_password2"].errors,
[force_text(form.error_messages['password_mismatch'])]
)
@mock.patch('django.contrib.auth.password_validation.password_changed') @mock.patch('django.contrib.auth.password_validation.password_changed')
def test_success(self, password_changed): def test_success(self, password_changed):
@ -359,8 +362,7 @@ class PasswordChangeFormTest(TestDataMixin, TestCase):
} }
form = PasswordChangeForm(user, data) form = PasswordChangeForm(user, data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form["old_password"].errors, self.assertEqual(form["old_password"].errors, [force_text(form.error_messages['password_incorrect'])])
[force_text(form.error_messages['password_incorrect'])])
def test_password_verification(self): def test_password_verification(self):
# The two new passwords do not match. # The two new passwords do not match.
@ -372,8 +374,7 @@ class PasswordChangeFormTest(TestDataMixin, TestCase):
} }
form = PasswordChangeForm(user, data) form = PasswordChangeForm(user, data)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form["new_password2"].errors, self.assertEqual(form["new_password2"].errors, [force_text(form.error_messages['password_mismatch'])])
[force_text(form.error_messages['password_mismatch'])])
@mock.patch('django.contrib.auth.password_validation.password_changed') @mock.patch('django.contrib.auth.password_validation.password_changed')
def test_success(self, password_changed): def test_success(self, password_changed):
@ -394,8 +395,7 @@ class PasswordChangeFormTest(TestDataMixin, TestCase):
def test_field_order(self): def test_field_order(self):
# Regression test - check the order of fields: # Regression test - check the order of fields:
user = User.objects.get(username='testclient') user = User.objects.get(username='testclient')
self.assertEqual(list(PasswordChangeForm(user, {}).fields), self.assertEqual(list(PasswordChangeForm(user, {}).fields), ['old_password', 'new_password1', 'new_password2'])
['old_password', 'new_password1', 'new_password2'])
def test_password_whitespace_not_stripped(self): def test_password_whitespace_not_stripped(self):
user = User.objects.get(username='testclient') user = User.objects.get(username='testclient')
@ -452,14 +452,12 @@ class UserChangeFormTest(TestDataMixin, TestCase):
def test_bug_17944_unmanageable_password(self): def test_bug_17944_unmanageable_password(self):
user = User.objects.get(username='unmanageable_password') user = User.objects.get(username='unmanageable_password')
form = UserChangeForm(instance=user) form = UserChangeForm(instance=user)
self.assertIn(_("Invalid password format or unknown hashing algorithm."), self.assertIn(_("Invalid password format or unknown hashing algorithm."), form.as_table())
form.as_table())
def test_bug_17944_unknown_password_algorithm(self): def test_bug_17944_unknown_password_algorithm(self):
user = User.objects.get(username='unknown_password') user = User.objects.get(username='unknown_password')
form = UserChangeForm(instance=user) form = UserChangeForm(instance=user)
self.assertIn(_("Invalid password format or unknown hashing algorithm."), self.assertIn(_("Invalid password format or unknown hashing algorithm."), form.as_table())
form.as_table())
def test_bug_19133(self): def test_bug_19133(self):
"The change form does not return the password value" "The change form does not return the password value"
@ -574,8 +572,10 @@ class PasswordResetFormTest(TestDataMixin, TestCase):
None, [to_email], None, [to_email],
['site_monitor@example.com'], ['site_monitor@example.com'],
headers={'Reply-To': 'webmaster@example.com'}, headers={'Reply-To': 'webmaster@example.com'},
alternatives=[("Really sorry to hear you forgot your password.", alternatives=[
"text/html")]).send() ("Really sorry to hear you forgot your password.", "text/html")
],
).send()
form = CustomEmailPasswordResetForm(data) form = CustomEmailPasswordResetForm(data)
self.assertTrue(form.is_valid()) 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_payload(1).get_content_type(), 'text/html')
self.assertEqual(message.get_all('to'), [email]) 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'^http://example.com/reset/[\w/-]+', message.get_payload(0).get_payload()))
self.assertTrue( self.assertTrue(re.match(
re.match(r'^<html><a href="http://example.com/reset/[\w/-]+/">Link</a></html>$', r'^<html><a href="http://example.com/reset/[\w/-]+/">Link</a></html>$',
message.get_payload(1).get_payload()) message.get_payload(1).get_payload()
) ))
class ReadOnlyPasswordHashTest(SimpleTestCase): class ReadOnlyPasswordHashTest(SimpleTestCase):

View File

@ -57,8 +57,7 @@ class TestUtilsHashPass(SimpleTestCase):
def test_pbkdf2(self): def test_pbkdf2(self):
encoded = make_password('lètmein', 'seasalt', 'pbkdf2_sha256') encoded = make_password('lètmein', 'seasalt', 'pbkdf2_sha256')
self.assertEqual(encoded, self.assertEqual(encoded, 'pbkdf2_sha256$30000$seasalt$VrX+V8drCGo68wlvy6rfu8i1d1pfkdeXA4LJkRGJodY=')
'pbkdf2_sha256$30000$seasalt$VrX+V8drCGo68wlvy6rfu8i1d1pfkdeXA4LJkRGJodY=')
self.assertTrue(is_password_usable(encoded)) self.assertTrue(is_password_usable(encoded))
self.assertTrue(check_password('lètmein', encoded)) self.assertTrue(check_password('lètmein', encoded))
self.assertFalse(check_password('lètmeinz', encoded)) self.assertFalse(check_password('lètmeinz', encoded))
@ -73,8 +72,7 @@ class TestUtilsHashPass(SimpleTestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher']) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'])
def test_sha1(self): def test_sha1(self):
encoded = make_password('lètmein', 'seasalt', 'sha1') encoded = make_password('lètmein', 'seasalt', 'sha1')
self.assertEqual(encoded, self.assertEqual(encoded, 'sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8')
'sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8')
self.assertTrue(is_password_usable(encoded)) self.assertTrue(is_password_usable(encoded))
self.assertTrue(check_password('lètmein', encoded)) self.assertTrue(check_password('lètmein', encoded))
self.assertFalse(check_password('lètmeinz', encoded)) self.assertFalse(check_password('lètmeinz', encoded))
@ -89,8 +87,7 @@ class TestUtilsHashPass(SimpleTestCase):
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.MD5PasswordHasher']) @override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.MD5PasswordHasher'])
def test_md5(self): def test_md5(self):
encoded = make_password('lètmein', 'seasalt', 'md5') encoded = make_password('lètmein', 'seasalt', 'md5')
self.assertEqual(encoded, self.assertEqual(encoded, 'md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3')
'md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3')
self.assertTrue(is_password_usable(encoded)) self.assertTrue(is_password_usable(encoded))
self.assertTrue(check_password('lètmein', encoded)) self.assertTrue(check_password('lètmein', encoded))
self.assertFalse(check_password('lètmeinz', encoded)) self.assertFalse(check_password('lètmeinz', encoded))
@ -165,8 +162,10 @@ class TestUtilsHashPass(SimpleTestCase):
self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256") self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256")
# Verify that password truncation no longer works # Verify that password truncation no longer works
password = ('VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5' password = (
'JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN') 'VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5'
'JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN'
)
encoded = make_password(password, hasher='bcrypt_sha256') encoded = make_password(password, hasher='bcrypt_sha256')
self.assertTrue(check_password(password, encoded)) self.assertTrue(check_password(password, encoded))
self.assertFalse(check_password(password[:72], encoded)) self.assertFalse(check_password(password[:72], encoded))
@ -282,15 +281,13 @@ class TestUtilsHashPass(SimpleTestCase):
def test_low_level_pbkdf2(self): def test_low_level_pbkdf2(self):
hasher = PBKDF2PasswordHasher() hasher = PBKDF2PasswordHasher()
encoded = hasher.encode('lètmein', 'seasalt2') encoded = hasher.encode('lètmein', 'seasalt2')
self.assertEqual(encoded, self.assertEqual(encoded, 'pbkdf2_sha256$30000$seasalt2$a75qzbogeVhNFeMqhdgyyoqGKpIzYUo651sq57RERew=')
'pbkdf2_sha256$30000$seasalt2$a75qzbogeVhNFeMqhdgyyoqGKpIzYUo651sq57RERew=')
self.assertTrue(hasher.verify('lètmein', encoded)) self.assertTrue(hasher.verify('lètmein', encoded))
def test_low_level_pbkdf2_sha1(self): def test_low_level_pbkdf2_sha1(self):
hasher = PBKDF2SHA1PasswordHasher() hasher = PBKDF2SHA1PasswordHasher()
encoded = hasher.encode('lètmein', 'seasalt2') encoded = hasher.encode('lètmein', 'seasalt2')
self.assertEqual(encoded, self.assertEqual(encoded, 'pbkdf2_sha1$30000$seasalt2$pMzU1zNPcydf6wjnJFbiVKwgULc=')
'pbkdf2_sha1$30000$seasalt2$pMzU1zNPcydf6wjnJFbiVKwgULc=')
self.assertTrue(hasher.verify('lètmein', encoded)) self.assertTrue(hasher.verify('lètmein', encoded))
@override_settings( @override_settings(
@ -433,15 +430,13 @@ class TestUtilsHashPass(SimpleTestCase):
def test_load_library_no_algorithm(self): def test_load_library_no_algorithm(self):
with self.assertRaises(ValueError) as e: with self.assertRaises(ValueError) as e:
BasePasswordHasher()._load_library() BasePasswordHasher()._load_library()
self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a " self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a library attribute", str(e.exception))
"library attribute", str(e.exception))
def test_load_library_importerror(self): def test_load_library_importerror(self):
PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), PlainHasher = type(str('PlainHasher'), (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'})
{'algorithm': 'plain', 'library': 'plain'})
# Python 3 adds quotes around module name # Python 3 adds quotes around module name
with six.assertRaisesRegex(self, ValueError, msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?"
"Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?"): with six.assertRaisesRegex(self, ValueError, msg):
PlainHasher()._load_library() PlainHasher()._load_library()

View File

@ -154,8 +154,12 @@ class AbstractUserTestCase(TestCase):
"html_message": None, "html_message": None,
} }
abstract_user = AbstractUser(email='foo@bar.com') abstract_user = AbstractUser(email='foo@bar.com')
abstract_user.email_user(subject="Subject here", abstract_user.email_user(
message="This is a message", from_email="from@domain.com", **kwargs) subject="Subject here",
message="This is a message",
from_email="from@domain.com",
**kwargs
)
# Test that one message has been sent. # Test that one message has been sent.
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
# Verify that test email contains the correct attributes: # Verify that test email contains the correct attributes:

View File

@ -255,8 +255,7 @@ class PasswordResetTest(AuthViewsTestCase):
def test_confirm_complete(self): def test_confirm_complete(self):
url, path = self._test_confirm_start() url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword', response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
'new_password2': 'anewpassword'})
# Check the password has been changed # Check the password has been changed
u = User.objects.get(email='staffmember@example.com') u = User.objects.get(email='staffmember@example.com')
self.assertTrue(u.check_password("anewpassword")) self.assertTrue(u.check_password("anewpassword"))
@ -267,48 +266,41 @@ class PasswordResetTest(AuthViewsTestCase):
def test_confirm_different_passwords(self): def test_confirm_different_passwords(self):
url, path = self._test_confirm_start() url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword', response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'x'})
'new_password2': 'x'})
self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch']) self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch'])
def test_reset_redirect_default(self): def test_reset_redirect_default(self):
response = self.client.post('/password_reset/', response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
{'email': 'staffmember@example.com'})
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertURLEqual(response.url, '/password_reset/done/') self.assertURLEqual(response.url, '/password_reset/done/')
def test_reset_custom_redirect(self): def test_reset_custom_redirect(self):
response = self.client.post('/password_reset/custom_redirect/', response = self.client.post('/password_reset/custom_redirect/', {'email': 'staffmember@example.com'})
{'email': 'staffmember@example.com'})
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertURLEqual(response.url, '/custom/') self.assertURLEqual(response.url, '/custom/')
def test_reset_custom_redirect_named(self): def test_reset_custom_redirect_named(self):
response = self.client.post('/password_reset/custom_redirect/named/', response = self.client.post('/password_reset/custom_redirect/named/', {'email': 'staffmember@example.com'})
{'email': 'staffmember@example.com'})
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertURLEqual(response.url, '/password_reset/') self.assertURLEqual(response.url, '/password_reset/')
def test_confirm_redirect_default(self): def test_confirm_redirect_default(self):
url, path = self._test_confirm_start() url, path = self._test_confirm_start()
response = self.client.post(path, {'new_password1': 'anewpassword', response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
'new_password2': 'anewpassword'})
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertURLEqual(response.url, '/reset/done/') self.assertURLEqual(response.url, '/reset/done/')
def test_confirm_redirect_custom(self): def test_confirm_redirect_custom(self):
url, path = self._test_confirm_start() url, path = self._test_confirm_start()
path = path.replace('/reset/', '/reset/custom/') path = path.replace('/reset/', '/reset/custom/')
response = self.client.post(path, {'new_password1': 'anewpassword', response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
'new_password2': 'anewpassword'})
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertURLEqual(response.url, '/custom/') self.assertURLEqual(response.url, '/custom/')
def test_confirm_redirect_custom_named(self): def test_confirm_redirect_custom_named(self):
url, path = self._test_confirm_start() url, path = self._test_confirm_start()
path = path.replace('/reset/', '/reset/custom/named/') path = path.replace('/reset/', '/reset/custom/named/')
response = self.client.post(path, {'new_password1': 'anewpassword', response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
'new_password2': 'anewpassword'})
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertURLEqual(response.url, '/password_reset/') self.assertURLEqual(response.url, '/password_reset/')

View File

@ -40,8 +40,7 @@ class DummyBackendTest(SimpleTestCase):
""" """
DATABASES = {} DATABASES = {}
conns = ConnectionHandler(DATABASES) conns = ConnectionHandler(DATABASES)
self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'], self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'], 'django.db.backends.dummy')
'django.db.backends.dummy')
with self.assertRaises(ImproperlyConfigured): with self.assertRaises(ImproperlyConfigured):
conns[DEFAULT_DB_ALIAS].ensure_connection() conns[DEFAULT_DB_ALIAS].ensure_connection()
@ -119,9 +118,11 @@ class SQLiteTests(TestCase):
statements = editor.collected_sql statements = editor.collected_sql
match = re.search('"id" ([^,]+),', statements[0]) match = re.search('"id" ([^,]+),', statements[0])
self.assertIsNotNone(match) self.assertIsNotNone(match)
self.assertEqual('integer NOT NULL PRIMARY KEY AUTOINCREMENT', self.assertEqual(
match.group(1), "Wrong SQL used to create an auto-increment " 'integer NOT NULL PRIMARY KEY AUTOINCREMENT',
"column on SQLite") match.group(1),
"Wrong SQL used to create an auto-increment column on SQLite"
)
def test_aggregation(self): def test_aggregation(self):
""" """
@ -672,11 +673,15 @@ class BackendTestCase(TransactionTestCase):
models.Person(first_name="Clark", last_name="Kent").save() models.Person(first_name="Clark", last_name="Kent").save()
opts2 = models.Person._meta opts2 = models.Person._meta
f3, f4 = opts2.get_field('first_name'), opts2.get_field('last_name') 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 = 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(cursor.fetchone(), ('Clark', 'Kent'))
self.assertEqual(list(cursor.fetchmany(2)), [('Jane', 'Doe'), ('John', 'Doe')]) self.assertEqual(list(cursor.fetchmany(2)), [('Jane', 'Doe'), ('John', 'Doe')])
self.assertEqual(list(cursor.fetchall()), [('Mary', 'Agnelline'), ('Peter', 'Parker')]) self.assertEqual(list(cursor.fetchall()), [('Mary', 'Agnelline'), ('Peter', 'Parker')])
@ -818,9 +823,10 @@ class BackendTestCase(TransactionTestCase):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
self.assertEqual(3, len(new_connection.queries)) self.assertEqual(3, len(new_connection.queries))
self.assertEqual(1, len(w)) self.assertEqual(1, len(w))
self.assertEqual(str(w[0].message), "Limit for query logging " self.assertEqual(
"exceeded, only the last 3 queries will be returned.") str(w[0].message),
"Limit for query logging exceeded, only the last 3 queries will be returned."
)
finally: finally:
BaseDatabaseWrapper.queries_limit = old_queries_limit BaseDatabaseWrapper.queries_limit = old_queries_limit
new_connection.close() new_connection.close()

View File

@ -3,8 +3,7 @@ from django.core.management.base import BaseCommand
class Command(BaseCommand): class Command(BaseCommand):
def add_arguments(self, parser): def add_arguments(self, parser):
parser.add_argument("--list", action="store_true", dest="list", parser.add_argument("--list", action="store_true", dest="list", help="Print all options")
help="Print all options")
def handle(self, *args, **options): def handle(self, *args, **options):
pass pass

View File

@ -97,7 +97,8 @@ class BashCompletionTests(unittest.TestCase):
"Application names will be autocompleted for an AppCommand" "Application names will be autocompleted for an AppCommand"
self._user_input('django-admin sqlmigrate a') self._user_input('django-admin sqlmigrate a')
output = self._run_autocomplete() output = self._run_autocomplete()
a_labels = sorted(app_config.label a_labels = sorted(
for app_config in apps.get_app_configs() app_config.label for app_config in apps.get_app_configs()
if app_config.label.startswith('a')) if app_config.label.startswith('a')
)
self.assertEqual(output, a_labels) self.assertEqual(output, a_labels)

View File

@ -99,16 +99,14 @@ class ModelInstanceCreationTests(TestCase):
pub_date=datetime(2005, 7, 31, 12, 30), pub_date=datetime(2005, 7, 31, 12, 30),
) )
a1.save() a1.save()
self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30))
datetime(2005, 7, 31, 12, 30))
a2 = Article( a2 = Article(
headline='Article 8', headline='Article 8',
pub_date=datetime(2005, 7, 31, 12, 30, 45), pub_date=datetime(2005, 7, 31, 12, 30, 45),
) )
a2.save() a2.save()
self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45))
datetime(2005, 7, 31, 12, 30, 45))
def test_saving_an_object_again_does_not_create_a_new_object(self): def test_saving_an_object_again_does_not_create_a_new_object(self):
a = Article(headline='original', pub_date=datetime(2014, 5, 16)) 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) some_pub_date = datetime(2014, 5, 16, 12, 1)
for headline in headlines: for headline in headlines:
Article(headline=headline, pub_date=some_pub_date).save() 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: Amazing article>", ["<Article: Amazing article>",
"<Article: An article>", "<Article: An article>",
"<Article: Article One>", "<Article: Article One>",
"<Article: Boring article>"]) "<Article: Boring article>"]
)
Article.objects.filter(headline__startswith='A').delete() Article.objects.filter(headline__startswith='A').delete()
self.assertQuerysetEqual(Article.objects.all().order_by('headline'), self.assertQuerysetEqual(Article.objects.all().order_by('headline'), ["<Article: Boring article>"])
["<Article: Boring article>"])
def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self): def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self):
some_pub_date = datetime(2014, 5, 16, 12, 1) 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), pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
) )
a9.save() a9.save()
self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180))
datetime(2005, 7, 31, 12, 30, 45, 180))
@skipIfDBFeature('supports_microsecond_precision') @skipIfDBFeature('supports_microsecond_precision')
def test_microsecond_precision_not_supported(self): def test_microsecond_precision_not_supported(self):
@ -236,8 +234,10 @@ class ModelTest(TestCase):
headline='Article 12', headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999), pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
) )
self.assertQuerysetEqual(Article.objects.filter(pub_date__year=2008), self.assertQuerysetEqual(
["<Article: Article 11>", "<Article: Article 12>"]) Article.objects.filter(pub_date__year=2008),
["<Article: Article 11>", "<Article: Article 12>"]
)
def test_unicode_data(self): def test_unicode_data(self):
# Unicode data works, too. # Unicode data works, too.
@ -246,8 +246,7 @@ class ModelTest(TestCase):
pub_date=datetime(2005, 7, 28), pub_date=datetime(2005, 7, 28),
) )
a.save() a.save()
self.assertEqual(Article.objects.get(pk=a.id).headline, self.assertEqual(Article.objects.get(pk=a.id).headline, '\u6797\u539f \u3081\u3050\u307f')
'\u6797\u539f \u3081\u3050\u307f')
def test_hash_function(self): def test_hash_function(self):
# Model instances have a hash function, so they can be used in sets # Model instances have a hash function, so they can be used in sets
@ -304,8 +303,10 @@ class ModelTest(TestCase):
dicts = Article.objects.filter( dicts = Article.objects.filter(
pub_date__year=2008).extra( pub_date__year=2008).extra(
select={'dashed-value': '1'}).values('headline', 'dashed-value') select={'dashed-value': '1'}).values('headline', 'dashed-value')
self.assertEqual([sorted(d.items()) for d in dicts], self.assertEqual(
[[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]]) [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): def test_extra_method_select_argument_with_dashes(self):
# If you use 'select' with extra() and names containing dashes on a # If you use 'select' with extra() and names containing dashes on a
@ -438,8 +439,7 @@ class ModelLookupTest(TestCase):
self.a.save() self.a.save()
# Article.objects.all() returns all the articles in the database. # Article.objects.all() returns all the articles in the database.
self.assertQuerysetEqual(Article.objects.all(), self.assertQuerysetEqual(Article.objects.all(), ['<Article: Parrot programs in Python>'])
['<Article: Parrot programs in Python>'])
def test_rich_lookup(self): def test_rich_lookup(self):
# Django provides a rich database lookup API. # 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) 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. # 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]), ["<Article: Swallow programs in Python>"])
["<Article: Swallow programs in Python>"])
# Model instances of the same type and same ID are considered equal. # Model instances of the same type and same ID are considered equal.
a = Article.objects.get(pk=self.a.id) a = Article.objects.get(pk=self.a.id)

63
tests/cache/tests.py vendored
View File

@ -772,54 +772,42 @@ class BaseCacheTests(object):
def test_cache_versioning_get_set_many(self): def test_cache_versioning_get_set_many(self):
# set, using default version = 1 # set, using default version = 1
cache.set_many({'ford1': 37, 'arthur1': 42}) cache.set_many({'ford1': 37, 'arthur1': 42})
self.assertDictEqual(cache.get_many(['ford1', 'arthur1']), self.assertDictEqual(cache.get_many(['ford1', 'arthur1']), {'ford1': 37, 'arthur1': 42})
{'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=1),
{'ford1': 37, 'arthur1': 42})
self.assertDictEqual(cache.get_many(['ford1', 'arthur1'], version=2), {}) 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']), {})
self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=1), self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=1), {'ford1': 37, 'arthur1': 42})
{'ford1': 37, 'arthur1': 42})
self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=2), {}) self.assertDictEqual(caches['v2'].get_many(['ford1', 'arthur1'], version=2), {})
# set, default version = 1, but manually override version = 2 # set, default version = 1, but manually override version = 2
cache.set_many({'ford2': 37, 'arthur2': 42}, 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']), {})
self.assertDictEqual(cache.get_many(['ford2', 'arthur2'], version=1), {}) self.assertDictEqual(cache.get_many(['ford2', 'arthur2'], version=1), {})
self.assertDictEqual(cache.get_many(['ford2', 'arthur2'], version=2), self.assertDictEqual(cache.get_many(['ford2', 'arthur2'], version=2), {'ford2': 37, 'arthur2': 42})
{'ford2': 37, 'arthur2': 42})
self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2']), self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2']), {'ford2': 37, 'arthur2': 42})
{'ford2': 37, 'arthur2': 42})
self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=1), {}) self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=1), {})
self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=2), self.assertDictEqual(caches['v2'].get_many(['ford2', 'arthur2'], version=2), {'ford2': 37, 'arthur2': 42})
{'ford2': 37, 'arthur2': 42})
# v2 set, using default version = 2 # v2 set, using default version = 2
caches['v2'].set_many({'ford3': 37, 'arthur3': 42}) caches['v2'].set_many({'ford3': 37, 'arthur3': 42})
self.assertDictEqual(cache.get_many(['ford3', 'arthur3']), {}) self.assertDictEqual(cache.get_many(['ford3', 'arthur3']), {})
self.assertDictEqual(cache.get_many(['ford3', 'arthur3'], version=1), {}) self.assertDictEqual(cache.get_many(['ford3', 'arthur3'], version=1), {})
self.assertDictEqual(cache.get_many(['ford3', 'arthur3'], version=2), self.assertDictEqual(cache.get_many(['ford3', 'arthur3'], version=2), {'ford3': 37, 'arthur3': 42})
{'ford3': 37, 'arthur3': 42})
self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3']), self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3']), {'ford3': 37, 'arthur3': 42})
{'ford3': 37, 'arthur3': 42})
self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=1), {}) self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=1), {})
self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=2), self.assertDictEqual(caches['v2'].get_many(['ford3', 'arthur3'], version=2), {'ford3': 37, 'arthur3': 42})
{'ford3': 37, 'arthur3': 42})
# v2 set, default version = 2, but manually override version = 1 # v2 set, default version = 2, but manually override version = 1
caches['v2'].set_many({'ford4': 37, 'arthur4': 42}, version=1) caches['v2'].set_many({'ford4': 37, 'arthur4': 42}, version=1)
self.assertDictEqual(cache.get_many(['ford4', 'arthur4']), self.assertDictEqual(cache.get_many(['ford4', 'arthur4']), {'ford4': 37, 'arthur4': 42})
{'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=1),
{'ford4': 37, 'arthur4': 42})
self.assertDictEqual(cache.get_many(['ford4', 'arthur4'], version=2), {}) 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']), {})
self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=1), self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=1), {'ford4': 37, 'arthur4': 42})
{'ford4': 37, 'arthur4': 42})
self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=2), {}) self.assertDictEqual(caches['v2'].get_many(['ford4', 'arthur4'], version=2), {})
def test_incr_version(self): def test_incr_version(self):
@ -988,8 +976,7 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase):
def test_second_call_doesnt_crash(self): def test_second_call_doesnt_crash(self):
out = six.StringIO() out = six.StringIO()
management.call_command('createcachetable', stdout=out) management.call_command('createcachetable', stdout=out)
self.assertEqual(out.getvalue(), self.assertEqual(out.getvalue(), "Cache table 'test cache table' already exists.\n" * len(settings.CACHES))
"Cache table 'test cache table' already exists.\n" * len(settings.CACHES))
@override_settings(CACHES=caches_setting_for_tests( @override_settings(CACHES=caches_setting_for_tests(
BACKEND='django.core.cache.backends.db.DatabaseCache', BACKEND='django.core.cache.backends.db.DatabaseCache',
@ -1015,8 +1002,7 @@ class DBCacheTests(BaseCacheTests, TransactionTestCase):
verbosity=2, verbosity=2,
stdout=out, stdout=out,
) )
self.assertEqual(out.getvalue(), self.assertEqual(out.getvalue(), "Cache table 'test cache table' created.\n")
"Cache table 'test cache table' created.\n")
@override_settings(USE_TZ=True) @override_settings(USE_TZ=True)
@ -1732,13 +1718,17 @@ class CacheI18nTest(TestCase):
with timezone.override(CustomTzName()): with timezone.override(CustomTzName()):
CustomTzName.name = 'Hora estándar de Argentina'.encode('UTF-8') # UTF-8 string CustomTzName.name = 'Hora estándar de Argentina'.encode('UTF-8') # UTF-8 string
sanitized_name = 'Hora_estndar_de_Argentina' sanitized_name = 'Hora_estndar_de_Argentina'
self.assertIn(sanitized_name, learn_cache_key(request, response), self.assertIn(
"Cache keys should include the time zone name when time zones are active") 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 CustomTzName.name = 'Hora estándar de Argentina' # unicode
sanitized_name = 'Hora_estndar_de_Argentina' sanitized_name = 'Hora_estndar_de_Argentina'
self.assertIn(sanitized_name, learn_cache_key(request, response), self.assertIn(
"Cache keys should include the time zone name when time zones are active") sanitized_name, learn_cache_key(request, response),
"Cache keys should include the time zone name when time zones are active"
)
@override_settings( @override_settings(
CACHE_MIDDLEWARE_KEY_PREFIX="test", CACHE_MIDDLEWARE_KEY_PREFIX="test",
@ -2151,18 +2141,15 @@ class TestMakeTemplateFragmentKey(SimpleTestCase):
def test_with_one_vary_on(self): def test_with_one_vary_on(self):
key = make_template_fragment_key('foo', ['abc']) key = make_template_fragment_key('foo', ['abc'])
self.assertEqual(key, self.assertEqual(key, 'template.cache.foo.900150983cd24fb0d6963f7d28e17f72')
'template.cache.foo.900150983cd24fb0d6963f7d28e17f72')
def test_with_many_vary_on(self): def test_with_many_vary_on(self):
key = make_template_fragment_key('bar', ['abc', 'def']) key = make_template_fragment_key('bar', ['abc', 'def'])
self.assertEqual(key, self.assertEqual(key, 'template.cache.bar.4b35f12ab03cec09beec4c21b2d2fa88')
'template.cache.bar.4b35f12ab03cec09beec4c21b2d2fa88')
def test_proper_escaping(self): def test_proper_escaping(self):
key = make_template_fragment_key('spam', ['abc:def%']) key = make_template_fragment_key('spam', ['abc:def%'])
self.assertEqual(key, self.assertEqual(key, 'template.cache.spam.f27688177baec990cdf3fbd9d9c3f469')
'template.cache.spam.f27688177baec990cdf3fbd9d9c3f469')
class CacheHandlerTest(SimpleTestCase): class CacheHandlerTest(SimpleTestCase):

View File

@ -40,8 +40,7 @@ class ContentTypesTests(TestCase):
with self.assertNumQueries(0): with self.assertNumQueries(0):
ContentType.objects.get_for_id(ct.id) ContentType.objects.get_for_id(ct.id)
with self.assertNumQueries(0): with self.assertNumQueries(0):
ContentType.objects.get_by_natural_key('contenttypes', ContentType.objects.get_by_natural_key('contenttypes', 'contenttype')
'contenttype')
# Once we clear the cache, another lookup will again hit the DB # Once we clear the cache, another lookup will again hit the DB
ContentType.objects.clear_cache() ContentType.objects.clear_cache()
@ -51,12 +50,10 @@ class ContentTypesTests(TestCase):
# The same should happen with a lookup by natural key # The same should happen with a lookup by natural key
ContentType.objects.clear_cache() ContentType.objects.clear_cache()
with self.assertNumQueries(1): with self.assertNumQueries(1):
ContentType.objects.get_by_natural_key('contenttypes', ContentType.objects.get_by_natural_key('contenttypes', 'contenttype')
'contenttype')
# And a second hit shouldn't hit the DB # And a second hit shouldn't hit the DB
with self.assertNumQueries(0): with self.assertNumQueries(0):
ContentType.objects.get_by_natural_key('contenttypes', ContentType.objects.get_by_natural_key('contenttypes', 'contenttype')
'contenttype')
def test_get_for_models_empty_cache(self): def test_get_for_models_empty_cache(self):
# Empty cache. # Empty cache.
@ -94,17 +91,10 @@ class ContentTypesTests(TestCase):
with concrete, proxy and deferred models with concrete, proxy and deferred models
""" """
concrete_model_ct = ContentType.objects.get_for_model(ConcreteModel) 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, proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, for_concrete_model=False)
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)
self.assertNotEqual(concrete_model_ct, proxy_model_ct) self.assertNotEqual(concrete_model_ct, proxy_model_ct)
# Make sure deferred model are correctly handled # Make sure deferred model are correctly handled
@ -112,19 +102,16 @@ class ContentTypesTests(TestCase):
DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__ DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__
DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__ DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__
self.assertEqual(concrete_model_ct, self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredConcreteModel))
ContentType.objects.get_for_model(DeferredConcreteModel)) self.assertEqual(
concrete_model_ct,
self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredConcreteModel, for_concrete_model=False)
ContentType.objects.get_for_model(DeferredConcreteModel, )
for_concrete_model=False)) self.assertEqual(concrete_model_ct, ContentType.objects.get_for_model(DeferredProxyModel))
self.assertEqual(
self.assertEqual(concrete_model_ct, proxy_model_ct,
ContentType.objects.get_for_model(DeferredProxyModel)) ContentType.objects.get_for_model(DeferredProxyModel, for_concrete_model=False)
)
self.assertEqual(proxy_model_ct,
ContentType.objects.get_for_model(DeferredProxyModel,
for_concrete_model=False))
def test_get_for_concrete_models(self): def test_get_for_concrete_models(self):
""" """
@ -139,10 +126,8 @@ class ContentTypesTests(TestCase):
ProxyModel: concrete_model_ct, ProxyModel: concrete_model_ct,
}) })
proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, proxy_model_ct = ContentType.objects.get_for_model(ProxyModel, for_concrete_model=False)
for_concrete_model=False) cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel, for_concrete_models=False)
cts = ContentType.objects.get_for_models(ConcreteModel, ProxyModel,
for_concrete_models=False)
self.assertEqual(cts, { self.assertEqual(cts, {
ConcreteModel: concrete_model_ct, ConcreteModel: concrete_model_ct,
ProxyModel: proxy_model_ct, ProxyModel: proxy_model_ct,
@ -153,16 +138,15 @@ class ContentTypesTests(TestCase):
DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__ DeferredConcreteModel = ConcreteModel.objects.only('pk').get().__class__
DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__ DeferredProxyModel = ProxyModel.objects.only('pk').get().__class__
cts = ContentType.objects.get_for_models(DeferredConcreteModel, cts = ContentType.objects.get_for_models(DeferredConcreteModel, DeferredProxyModel)
DeferredProxyModel)
self.assertEqual(cts, { self.assertEqual(cts, {
DeferredConcreteModel: concrete_model_ct, DeferredConcreteModel: concrete_model_ct,
DeferredProxyModel: concrete_model_ct, DeferredProxyModel: concrete_model_ct,
}) })
cts = ContentType.objects.get_for_models(DeferredConcreteModel, cts = ContentType.objects.get_for_models(
DeferredProxyModel, DeferredConcreteModel, DeferredProxyModel, for_concrete_models=False
for_concrete_models=False) )
self.assertEqual(cts, { self.assertEqual(cts, {
DeferredConcreteModel: concrete_model_ct, DeferredConcreteModel: concrete_model_ct,
DeferredProxyModel: proxy_model_ct, DeferredProxyModel: proxy_model_ct,
@ -198,13 +182,14 @@ class ContentTypesTests(TestCase):
with self.modify_settings(INSTALLED_APPS={'append': 'django.contrib.sites'}): with self.modify_settings(INSTALLED_APPS={'append': 'django.contrib.sites'}):
response = shortcut(request, user_ct.id, obj.id) response = shortcut(request, user_ct.id, obj.id)
self.assertEqual("http://%s/users/john/" % get_current_site(request).domain, self.assertEqual(
response._headers.get("location")[1]) "http://%s/users/john/" % get_current_site(request).domain,
response._headers.get("location")[1]
)
with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}): with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}):
response = shortcut(request, user_ct.id, obj.id) response = shortcut(request, user_ct.id, obj.id)
self.assertEqual("http://Example.com/users/john/", self.assertEqual("http://Example.com/users/john/", response._headers.get("location")[1])
response._headers.get("location")[1])
def test_shortcut_view_without_get_absolute_url(self): def test_shortcut_view_without_get_absolute_url(self):
""" """

View File

@ -252,9 +252,11 @@ class GenericRelationshipTests(SimpleTestCase):
'custom_content_type', 'custom_object_id') 'custom_content_type', 'custom_object_id')
class Bookmark(models.Model): class Bookmark(models.Model):
tags = GenericRelation('TaggedItem', tags = GenericRelation(
'TaggedItem',
content_type_field='custom_content_type', content_type_field='custom_content_type',
object_id_field='custom_object_id') object_id_field='custom_object_id',
)
errors = Bookmark.tags.field.check() errors = Bookmark.tags.field.check()
self.assertEqual(errors, []) self.assertEqual(errors, [])

View File

@ -116,7 +116,6 @@ class FunPerson(models.Model):
first_name = models.CharField(max_length=30) first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30)
fun = models.BooleanField(default=True) fun = models.BooleanField(default=True)
favorite_book = models.ForeignKey( favorite_book = models.ForeignKey(
'Book', 'Book',
models.SET_NULL, models.SET_NULL,
@ -141,12 +140,16 @@ class Book(models.Model):
published_objects = PublishedBookManager() published_objects = PublishedBookManager()
authors = models.ManyToManyField(Person, related_name='books') authors = models.ManyToManyField(Person, related_name='books')
fun_authors = models.ManyToManyField(FunPerson, related_name='books') fun_authors = models.ManyToManyField(FunPerson, related_name='books')
favorite_things = GenericRelation(
favorite_things = GenericRelation(Person, Person,
content_type_field='favorite_thing_type', object_id_field='favorite_thing_id') 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') fun_people_favorite_things = GenericRelation(
FunPerson,
content_type_field='favorite_thing_type',
object_id_field='favorite_thing_id',
)
def __str__(self): def __str__(self):
return self.title return self.title

View File

@ -47,25 +47,28 @@ class DataTypesTestCase(TestCase):
def test_year_boundaries(self): def test_year_boundaries(self):
"""Year boundary tests (ticket #3689)""" """Year boundary tests (ticket #3689)"""
Donut.objects.create(name='Date Test 2007', Donut.objects.create(
baked_date=datetime.datetime(year=2007, month=12, day=31), name='Date Test 2007',
consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) baked_date=datetime.datetime(year=2007, month=12, day=31),
Donut.objects.create(name='Date Test 2006', 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), 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.create(
Donut.objects.filter(baked_date__year=2007)[0].name) name='Apple Fritter',
consumed_at=datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59),
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)))
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=2005).count())
self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count()) self.assertEqual(0, Donut.objects.filter(consumed_at__year=2008).count())

View File

@ -286,12 +286,18 @@ class DeferAnnotateSelectRelatedTest(TestCase):
def test_defer_annotate_select_related(self): def test_defer_annotate_select_related(self):
location = Location.objects.create() location = Location.objects.create()
Request.objects.create(location=location) Request.objects.create(location=location)
self.assertIsInstance(list(Request.objects self.assertIsInstance(
.annotate(Count('items')).select_related('profile', 'location') list(Request.objects.annotate(Count('items')).select_related('profile', 'location')
.only('profile', 'location')), list) .only('profile', 'location')),
self.assertIsInstance(list(Request.objects list
.annotate(Count('items')).select_related('profile', 'location') )
.only('profile__profile1', 'location__location1')), list) self.assertIsInstance(
self.assertIsInstance(list(Request.objects list(Request.objects.annotate(Count('items')).select_related('profile', 'location')
.annotate(Count('items')).select_related('profile', 'location') .only('profile__profile1', 'location__location1')),
.defer('request1', 'request2', 'request3', 'request4')), list) list
)
self.assertIsInstance(
list(Request.objects.annotate(Count('items')).select_related('profile', 'location')
.defer('request1', 'request2', 'request3', 'request4')),
list
)

View File

@ -36,32 +36,25 @@ class A(models.Model):
name = models.CharField(max_length=30) name = models.CharField(max_length=30)
auto = models.ForeignKey(R, models.CASCADE, related_name="auto_set") auto = models.ForeignKey(R, models.CASCADE, related_name="auto_set")
auto_nullable = models.ForeignKey(R, models.CASCADE, null=True, auto_nullable = models.ForeignKey(R, models.CASCADE, null=True, related_name='auto_nullable_set')
related_name='auto_nullable_set') setvalue = models.ForeignKey(R, models.SET(get_default_r), related_name='setvalue')
setvalue = models.ForeignKey(R, models.SET(get_default_r), setnull = models.ForeignKey(R, models.SET_NULL, null=True, related_name='setnull_set')
related_name='setvalue') setdefault = models.ForeignKey(R, models.SET_DEFAULT, default=get_default_r, related_name='setdefault_set')
setnull = models.ForeignKey(R, models.SET_NULL, null=True, setdefault_none = models.ForeignKey(
related_name='setnull_set') R, models.SET_DEFAULT,
setdefault = models.ForeignKey(R, models.SET_DEFAULT, default=None, null=True, related_name='setnull_nullable_set',
default=get_default_r, related_name='setdefault_set') )
setdefault_none = models.ForeignKey(R, models.SET_DEFAULT, cascade = models.ForeignKey(R, models.CASCADE, related_name='cascade_set')
default=None, null=True, related_name='setnull_nullable_set') cascade_nullable = models.ForeignKey(R, models.CASCADE, null=True, related_name='cascade_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) protect = models.ForeignKey(R, models.PROTECT, null=True)
donothing = models.ForeignKey(R, models.DO_NOTHING, null=True, donothing = models.ForeignKey(R, models.DO_NOTHING, null=True, related_name='donothing_set')
related_name='donothing_set')
child = models.ForeignKey(RChild, models.CASCADE, related_name="child") child = models.ForeignKey(RChild, models.CASCADE, related_name="child")
child_setnull = models.ForeignKey(RChild, models.SET_NULL, null=True, child_setnull = models.ForeignKey(RChild, models.SET_NULL, null=True, related_name="child_setnull")
related_name="child_setnull")
# A OneToOneField is just a ForeignKey unique=True, so we don't duplicate # 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 # all the tests; just one smoke test to ensure on_delete works for it as
# well. # well.
o2o_setnull = models.ForeignKey(R, models.SET_NULL, null=True, o2o_setnull = models.ForeignKey(R, models.SET_NULL, null=True, related_name="o2o_nullable_set")
related_name="o2o_nullable_set")
def create_a(name): def create_a(name):
@ -79,10 +72,8 @@ def create_a(name):
class M(models.Model): class M(models.Model):
m2m = models.ManyToManyField(R, related_name="m_set") m2m = models.ManyToManyField(R, related_name="m_set")
m2m_through = models.ManyToManyField(R, through="MR", m2m_through = models.ManyToManyField(R, through="MR", related_name="m_through_set")
related_name="m_through_set") m2m_through_null = models.ManyToManyField(R, through="MRNull", related_name="m_through_null_set")
m2m_through_null = models.ManyToManyField(R, through="MRNull",
related_name="m_through_null_set")
class MR(models.Model): class MR(models.Model):

View File

@ -36,8 +36,7 @@ class RenameMethodsTests(SimpleTestCase):
pass pass
self.assertEqual(len(recorded), 1) self.assertEqual(len(recorded), 1)
msg = str(recorded[0].message) msg = str(recorded[0].message)
self.assertEqual(msg, self.assertEqual(msg, '`Manager.old` method should be renamed `new`.')
'`Manager.old` method should be renamed `new`.')
def test_get_new_defined(self): def test_get_new_defined(self):
""" """
@ -56,8 +55,7 @@ class RenameMethodsTests(SimpleTestCase):
manager.old() manager.old()
self.assertEqual(len(recorded), 1) self.assertEqual(len(recorded), 1)
msg = str(recorded.pop().message) msg = str(recorded.pop().message)
self.assertEqual(msg, self.assertEqual(msg, '`Manager.old` is deprecated, use `new` instead.')
'`Manager.old` is deprecated, use `new` instead.')
def test_get_old_defined(self): def test_get_old_defined(self):
""" """
@ -76,8 +74,7 @@ class RenameMethodsTests(SimpleTestCase):
manager.old() manager.old()
self.assertEqual(len(recorded), 1) self.assertEqual(len(recorded), 1)
msg = str(recorded.pop().message) msg = str(recorded.pop().message)
self.assertEqual(msg, self.assertEqual(msg, '`Manager.old` is deprecated, use `new` instead.')
'`Manager.old` is deprecated, use `new` instead.')
def test_deprecated_subclass_renamed(self): def test_deprecated_subclass_renamed(self):
""" """
@ -99,8 +96,7 @@ class RenameMethodsTests(SimpleTestCase):
deprecated.new() deprecated.new()
self.assertEqual(len(recorded), 1) self.assertEqual(len(recorded), 1)
msg = str(recorded.pop().message) msg = str(recorded.pop().message)
self.assertEqual(msg, self.assertEqual(msg, '`Renamed.old` is deprecated, use `new` instead.')
'`Renamed.old` is deprecated, use `new` instead.')
recorded[:] = [] recorded[:] = []
deprecated.old() deprecated.old()
self.assertEqual(len(recorded), 2) self.assertEqual(len(recorded), 2)
@ -132,8 +128,7 @@ class RenameMethodsTests(SimpleTestCase):
renamed.old() renamed.old()
self.assertEqual(len(recorded), 1) self.assertEqual(len(recorded), 1)
msg = str(recorded.pop().message) msg = str(recorded.pop().message)
self.assertEqual(msg, self.assertEqual(msg, '`Renamed.old` is deprecated, use `new` instead.')
'`Renamed.old` is deprecated, use `new` instead.')
def test_deprecated_subclass_renamed_and_mixins(self): def test_deprecated_subclass_renamed_and_mixins(self):
""" """
@ -163,8 +158,7 @@ class RenameMethodsTests(SimpleTestCase):
deprecated.new() deprecated.new()
self.assertEqual(len(recorded), 1) self.assertEqual(len(recorded), 1)
msg = str(recorded.pop().message) msg = str(recorded.pop().message)
self.assertEqual(msg, self.assertEqual(msg, '`RenamedMixin.old` is deprecated, use `new` instead.')
'`RenamedMixin.old` is deprecated, use `new` instead.')
deprecated.old() deprecated.old()
self.assertEqual(len(recorded), 2) self.assertEqual(len(recorded), 2)
msgs = [str(warning.message) for warning in recorded] msgs = [str(warning.message) for warning in recorded]

View File

@ -52,8 +52,10 @@ class BasicExpressionsTests(TestCase):
companies = Company.objects.annotate( companies = Company.objects.annotate(
salaries=F('ceo__salary'), salaries=F('ceo__salary'),
).values('num_employees', 'salaries').aggregate( ).values('num_employees', 'salaries').aggregate(
result=Sum(F('salaries') + F('num_employees'), result=Sum(
output_field=models.IntegerField()), F('salaries') + F('num_employees'),
output_field=models.IntegerField()
),
) )
self.assertEqual(companies['result'], 2395) self.assertEqual(companies['result'], 2395)
@ -572,24 +574,21 @@ class ExpressionOperatorTests(TestCase):
def test_lefthand_subtraction(self): def test_lefthand_subtraction(self):
# LH Subtraction of floats and integers # LH Subtraction of floats and integers
Number.objects.filter(pk=self.n.pk).update(integer=F('integer') - 15, Number.objects.filter(pk=self.n.pk).update(integer=F('integer') - 15, float=F('float') - 42.7)
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).integer, 27)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(-27.200, places=3)) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(-27.200, places=3))
def test_lefthand_multiplication(self): def test_lefthand_multiplication(self):
# Multiplication of floats and integers # Multiplication of floats and integers
Number.objects.filter(pk=self.n.pk).update(integer=F('integer') * 15, Number.objects.filter(pk=self.n.pk).update(integer=F('integer') * 15, float=F('float') * 42.7)
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).integer, 630)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3))
def test_lefthand_division(self): def test_lefthand_division(self):
# LH Division of floats and integers # LH Division of floats and integers
Number.objects.filter(pk=self.n.pk).update(integer=F('integer') / 2, Number.objects.filter(pk=self.n.pk).update(integer=F('integer') / 2, float=F('float') / 42.7)
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).integer, 21)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(0.363, places=3)) 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): def test_lefthand_power(self):
# LH Powert arithmetic operation on floats and integers # LH Powert arithmetic operation on floats and integers
Number.objects.filter(pk=self.n.pk).update(integer=F('integer') ** 2, Number.objects.filter(pk=self.n.pk).update(integer=F('integer') ** 2, float=F('float') ** 1.5)
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).integer, 1764)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(61.02, places=2)) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(61.02, places=2))
def test_right_hand_addition(self): def test_right_hand_addition(self):
# Right hand operators # Right hand operators
Number.objects.filter(pk=self.n.pk).update(integer=15 + F('integer'), Number.objects.filter(pk=self.n.pk).update(integer=15 + F('integer'), float=42.7 + F('float'))
float=42.7 + F('float'))
# RH Addition of floats and integers # 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).integer, 57)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3)) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(58.200, places=3))
def test_right_hand_subtraction(self): def test_right_hand_subtraction(self):
Number.objects.filter(pk=self.n.pk).update(integer=15 - F('integer'), Number.objects.filter(pk=self.n.pk).update(integer=15 - F('integer'), float=42.7 - F('float'))
float=42.7 - F('float'))
# RH Subtraction of floats and integers # RH Subtraction of floats and integers
self.assertEqual(Number.objects.get(pk=self.n.pk).integer, -27) self.assertEqual(Number.objects.get(pk=self.n.pk).integer, -27)
@ -642,16 +638,14 @@ class ExpressionOperatorTests(TestCase):
def test_right_hand_multiplication(self): def test_right_hand_multiplication(self):
# RH Multiplication of floats and integers # RH Multiplication of floats and integers
Number.objects.filter(pk=self.n.pk).update(integer=15 * F('integer'), Number.objects.filter(pk=self.n.pk).update(integer=15 * F('integer'), float=42.7 * F('float'))
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).integer, 630)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3)) self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(661.850, places=3))
def test_right_hand_division(self): def test_right_hand_division(self):
# RH Division of floats and integers # RH Division of floats and integers
Number.objects.filter(pk=self.n.pk).update(integer=640 / F('integer'), Number.objects.filter(pk=self.n.pk).update(integer=640 / F('integer'), float=42.7 / F('float'))
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).integer, 15)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(2.755, places=3)) 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): def test_righthand_power(self):
# RH Powert arithmetic operation on floats and integers # RH Powert arithmetic operation on floats and integers
Number.objects.filter(pk=self.n.pk).update(integer=2 ** F('integer'), Number.objects.filter(pk=self.n.pk).update(integer=2 ** F('integer'), float=1.5 ** F('float'))
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).integer, 4398046511104)
self.assertEqual(Number.objects.get(pk=self.n.pk).float, Approximate(536.308, places=3)) 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 # e0: started same day as assigned, zero duration
end = stime + delta0 end = stime + delta0
e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime, e0 = Experiment.objects.create(
end=end, completed=end.date(), estimated_time=delta0) name='e0', assigned=sday, start=stime, end=end,
completed=end.date(), estimated_time=delta0,
)
cls.deltas.append(delta0) cls.deltas.append(delta0)
cls.delays.append(e0.start - cls.delays.append(e0.start - datetime.datetime.combine(e0.assigned, midnight))
datetime.datetime.combine(e0.assigned, midnight))
cls.days_long.append(e0.completed - e0.assigned) cls.days_long.append(e0.completed - e0.assigned)
# e1: started one day after assigned, tiny duration, data # e1: started one day after assigned, tiny duration, data
@ -708,41 +702,43 @@ class FTimeDeltaTests(TestCase):
if connection.features.supports_microsecond_precision: if connection.features.supports_microsecond_precision:
delay = datetime.timedelta(1) delay = datetime.timedelta(1)
end = stime + delay + delta1 end = stime + delay + delta1
e1 = Experiment.objects.create(name='e1', assigned=sday, e1 = Experiment.objects.create(
start=stime + delay, end=end, completed=end.date(), estimated_time=delta1) name='e1', assigned=sday, start=stime + delay, end=end,
completed=end.date(), estimated_time=delta1,
)
cls.deltas.append(delta1) cls.deltas.append(delta1)
cls.delays.append(e1.start - cls.delays.append(e1.start - datetime.datetime.combine(e1.assigned, midnight))
datetime.datetime.combine(e1.assigned, midnight))
cls.days_long.append(e1.completed - e1.assigned) cls.days_long.append(e1.completed - e1.assigned)
# e2: started three days after assigned, small duration # e2: started three days after assigned, small duration
end = stime + delta2 end = stime + delta2
e2 = Experiment.objects.create(name='e2', e2 = Experiment.objects.create(
assigned=sday - datetime.timedelta(3), start=stime, end=end, name='e2', assigned=sday - datetime.timedelta(3), start=stime,
completed=end.date(), estimated_time=datetime.timedelta(hours=1)) end=end, completed=end.date(), estimated_time=datetime.timedelta(hours=1),
)
cls.deltas.append(delta2) cls.deltas.append(delta2)
cls.delays.append(e2.start - cls.delays.append(e2.start - datetime.datetime.combine(e2.assigned, midnight))
datetime.datetime.combine(e2.assigned, midnight))
cls.days_long.append(e2.completed - e2.assigned) cls.days_long.append(e2.completed - e2.assigned)
# e3: started four days after assigned, medium duration # e3: started four days after assigned, medium duration
delay = datetime.timedelta(4) delay = datetime.timedelta(4)
end = stime + delay + delta3 end = stime + delay + delta3
e3 = Experiment.objects.create(name='e3', e3 = Experiment.objects.create(
assigned=sday, start=stime + delay, end=end, completed=end.date(), estimated_time=delta3) name='e3', assigned=sday, start=stime + delay, end=end,
completed=end.date(), estimated_time=delta3,
)
cls.deltas.append(delta3) cls.deltas.append(delta3)
cls.delays.append(e3.start - cls.delays.append(e3.start - datetime.datetime.combine(e3.assigned, midnight))
datetime.datetime.combine(e3.assigned, midnight))
cls.days_long.append(e3.completed - e3.assigned) cls.days_long.append(e3.completed - e3.assigned)
# e4: started 10 days after assignment, long duration # e4: started 10 days after assignment, long duration
end = stime + delta4 end = stime + delta4
e4 = Experiment.objects.create(name='e4', e4 = Experiment.objects.create(
assigned=sday - datetime.timedelta(10), start=stime, end=end, name='e4', assigned=sday - datetime.timedelta(10), start=stime,
completed=end.date(), estimated_time=delta4 - datetime.timedelta(1)) end=end, completed=end.date(), estimated_time=delta4 - datetime.timedelta(1),
)
cls.deltas.append(delta4) cls.deltas.append(delta4)
cls.delays.append(e4.start - cls.delays.append(e4.start - datetime.datetime.combine(e4.assigned, midnight))
datetime.datetime.combine(e4.assigned, midnight))
cls.days_long.append(e4.completed - e4.assigned) cls.days_long.append(e4.completed - e4.assigned)
cls.expnames = [e.name for e in Experiment.objects.all()] cls.expnames = [e.name for e in Experiment.objects.all()]
@ -764,49 +760,40 @@ class FTimeDeltaTests(TestCase):
def test_delta_add(self): def test_delta_add(self):
for i in range(len(self.deltas)): for i in range(len(self.deltas)):
delta = self.deltas[i] delta = self.deltas[i]
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(end__lt=F('start') + delta)]
Experiment.objects.filter(end__lt=F('start') + delta)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(end__lt=delta + F('start'))]
Experiment.objects.filter(end__lt=delta + F('start'))]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(end__lte=F('start') + delta)]
Experiment.objects.filter(end__lte=F('start') + delta)]
self.assertEqual(test_set, self.expnames[:i + 1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_delta_subtract(self): def test_delta_subtract(self):
for i in range(len(self.deltas)): for i in range(len(self.deltas)):
delta = self.deltas[i] delta = self.deltas[i]
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(start__gt=F('end') - delta)]
Experiment.objects.filter(start__gt=F('end') - delta)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(start__gte=F('end') - delta)]
Experiment.objects.filter(start__gte=F('end') - delta)]
self.assertEqual(test_set, self.expnames[:i + 1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_exclude(self): def test_exclude(self):
for i in range(len(self.deltas)): for i in range(len(self.deltas)):
delta = self.deltas[i] delta = self.deltas[i]
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.exclude(end__lt=F('start') + delta)]
Experiment.objects.exclude(end__lt=F('start') + delta)]
self.assertEqual(test_set, self.expnames[i:]) self.assertEqual(test_set, self.expnames[i:])
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.exclude(end__lte=F('start') + delta)]
Experiment.objects.exclude(end__lte=F('start') + delta)]
self.assertEqual(test_set, self.expnames[i + 1:]) self.assertEqual(test_set, self.expnames[i + 1:])
def test_date_comparison(self): def test_date_comparison(self):
for i in range(len(self.days_long)): for i in range(len(self.days_long)):
days = self.days_long[i] days = self.days_long[i]
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(completed__lt=F('assigned') + days)]
Experiment.objects.filter(completed__lt=F('assigned') + days)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(completed__lte=F('assigned') + days)]
Experiment.objects.filter(completed__lte=F('assigned') + days)]
self.assertEqual(test_set, self.expnames[:i + 1]) self.assertEqual(test_set, self.expnames[:i + 1])
@skipUnlessDBFeature("supports_mixed_date_datetime_comparisons") @skipUnlessDBFeature("supports_mixed_date_datetime_comparisons")
@ -815,25 +802,22 @@ class FTimeDeltaTests(TestCase):
delay = self.delays[i] delay = self.delays[i]
if not connection.features.supports_microsecond_precision: if not connection.features.supports_microsecond_precision:
delay = datetime.timedelta(delay.days, delay.seconds) delay = datetime.timedelta(delay.days, delay.seconds)
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(assigned__gt=F('start') - delay)]
Experiment.objects.filter(assigned__gt=F('start') - delay)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(assigned__gte=F('start') - delay)]
Experiment.objects.filter(assigned__gte=F('start') - delay)]
self.assertEqual(test_set, self.expnames[:i + 1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_mixed_comparisons2(self): def test_mixed_comparisons2(self):
delays = [datetime.timedelta(delay.days) for delay in self.delays] delays = [datetime.timedelta(delay.days) for delay in self.delays]
for i in range(len(delays)): for i in range(len(delays)):
delay = delays[i] delay = delays[i]
test_set = [e.name for e in test_set = [e.name for e in Experiment.objects.filter(start__lt=F('assigned') + delay)]
Experiment.objects.filter(start__lt=F('assigned') + delay)]
self.assertEqual(test_set, self.expnames[:i]) self.assertEqual(test_set, self.expnames[:i])
test_set = [e.name for e in test_set = [
Experiment.objects.filter(start__lte=F('assigned') + delay + e.name for e in Experiment.objects.filter(start__lte=F('assigned') + delay + datetime.timedelta(1))
datetime.timedelta(1))] ]
self.assertEqual(test_set, self.expnames[:i + 1]) self.assertEqual(test_set, self.expnames[:i + 1])
def test_delta_update(self): def test_delta_update(self):
@ -858,16 +842,16 @@ class FTimeDeltaTests(TestCase):
list(Experiment.objects.filter(start=F('start') * datetime.timedelta(0))) list(Experiment.objects.filter(start=F('start') * datetime.timedelta(0)))
def test_durationfield_add(self): def test_durationfield_add(self):
zeros = [e.name for e in zeros = [e.name for e in Experiment.objects.filter(start=F('start') + F('estimated_time'))]
Experiment.objects.filter(start=F('start') + F('estimated_time'))]
self.assertEqual(zeros, ['e0']) self.assertEqual(zeros, ['e0'])
end_less = [e.name for e in end_less = [e.name for e in Experiment.objects.filter(end__lt=F('start') + F('estimated_time'))]
Experiment.objects.filter(end__lt=F('start') + F('estimated_time'))]
self.assertEqual(end_less, ['e2']) self.assertEqual(end_less, ['e2'])
delta_math = [e.name for e in delta_math = [
Experiment.objects.filter(end__gte=F('start') + F('estimated_time') + datetime.timedelta(hours=1))] e.name for e in
Experiment.objects.filter(end__gte=F('start') + F('estimated_time') + datetime.timedelta(hours=1))
]
self.assertEqual(delta_math, ['e4']) self.assertEqual(delta_math, ['e4'])
@skipUnlessDBFeature('supports_temporal_subtraction') @skipUnlessDBFeature('supports_temporal_subtraction')
@ -906,12 +890,14 @@ class FTimeDeltaTests(TestCase):
@skipUnlessDBFeature('supports_temporal_subtraction') @skipUnlessDBFeature('supports_temporal_subtraction')
def test_datetime_subtraction(self): def test_datetime_subtraction(self):
under_estimate = [e.name for e in under_estimate = [
Experiment.objects.filter(estimated_time__gt=F('end') - F('start'))] e.name for e in Experiment.objects.filter(estimated_time__gt=F('end') - F('start'))
]
self.assertEqual(under_estimate, ['e2']) self.assertEqual(under_estimate, ['e2'])
over_estimate = [e.name for e in over_estimate = [
Experiment.objects.filter(estimated_time__lt=F('end') - F('start'))] e.name for e in Experiment.objects.filter(estimated_time__lt=F('end') - F('start'))
]
self.assertEqual(over_estimate, ['e4']) self.assertEqual(over_estimate, ['e4'])
def test_duration_with_datetime(self): def test_duration_with_datetime(self):

View File

@ -46,15 +46,15 @@ class ExtraRegressTests(TestCase):
}] }]
) )
self.assertQuerysetEqual(qs, self.assertQuerysetEqual(
[('Second Revision', 'First Revision')], qs, [('Second Revision', 'First Revision')],
transform=lambda r: (r.title, r.base.title) transform=lambda r: (r.title, r.base.title)
) )
# Queryset to search for string in title: # Queryset to search for string in title:
qs2 = RevisionableModel.objects.filter(title__contains="Revision") qs2 = RevisionableModel.objects.filter(title__contains="Revision")
self.assertQuerysetEqual(qs2, self.assertQuerysetEqual(
[ qs2, [
('First Revision', 'First Revision'), ('First Revision', 'First Revision'),
('Second Revision', 'First Revision'), ('Second Revision', 'First Revision'),
], ],
@ -63,7 +63,8 @@ class ExtraRegressTests(TestCase):
) )
# Following queryset should return the most recent revision: # Following queryset should return the most recent revision:
self.assertQuerysetEqual(qs & qs2, self.assertQuerysetEqual(
qs & qs2,
[('Second Revision', 'First Revision')], [('Second Revision', 'First Revision')],
transform=lambda r: (r.title, r.base.title), transform=lambda r: (r.title, r.base.title),
ordered=False ordered=False
@ -111,10 +112,8 @@ class ExtraRegressTests(TestCase):
query as well. query as well.
""" """
self.assertEqual( self.assertEqual(
list(User.objects list(User.objects.extra(select={"alpha": "%s"}, select_params=(-6,))
.extra(select={"alpha": "%s"}, select_params=(-6,)) .filter(id=self.u.id).values_list('id', flat=True)),
.filter(id=self.u.id)
.values_list('id', flat=True)),
[self.u.id] [self.u.id]
) )

View File

@ -69,10 +69,8 @@ class GetStorageClassTests(SimpleTestCase):
get_storage_class raises an error if the requested module don't exist. get_storage_class raises an error if the requested module don't exist.
""" """
# Error message may or may not be the fully qualified path. # Error message may or may not be the fully qualified path.
with six.assertRaisesRegex(self, ImportError, with six.assertRaisesRegex(self, ImportError, "No module named '?(django.core.files.)?non_existing_storage'?"):
"No module named '?(django.core.files.)?non_existing_storage'?"): get_storage_class('django.core.files.non_existing_storage.NonExistingStorage')
get_storage_class(
'django.core.files.non_existing_storage.NonExistingStorage')
class FileStorageDeconstructionTests(unittest.TestCase): class FileStorageDeconstructionTests(unittest.TestCase):
@ -103,8 +101,7 @@ class FileStorageTests(TestCase):
def setUp(self): def setUp(self):
self.temp_dir = tempfile.mkdtemp() self.temp_dir = tempfile.mkdtemp()
self.storage = self.storage_class(location=self.temp_dir, self.storage = self.storage_class(location=self.temp_dir, base_url='/test_media_url/')
base_url='/test_media_url/')
# Set up a second temporary directory which is ensured to have a mixed # Set up a second temporary directory which is ensured to have a mixed
# case name. # case name.
self.temp_dir2 = tempfile.mkdtemp(suffix='aBc') self.temp_dir2 = tempfile.mkdtemp(suffix='aBc')
@ -345,8 +342,7 @@ class FileStorageTests(TestCase):
Saving a pathname should create intermediate directories as necessary. Saving a pathname should create intermediate directories as necessary.
""" """
self.assertFalse(self.storage.exists('path/to')) self.assertFalse(self.storage.exists('path/to'))
self.storage.save('path/to/test.file', self.storage.save('path/to/test.file', ContentFile('file saved with path'))
ContentFile('file saved with path'))
self.assertTrue(self.storage.exists('path/to')) self.assertTrue(self.storage.exists('path/to'))
with self.storage.open('path/to/test.file') as f: with self.storage.open('path/to/test.file') as f:
@ -366,8 +362,7 @@ class FileStorageTests(TestCase):
self.assertFalse(file.closed) self.assertFalse(file.closed)
self.assertFalse(file.file.closed) self.assertFalse(file.file.closed)
file = InMemoryUploadedFile(six.StringIO('1'), '', 'test', file = InMemoryUploadedFile(six.StringIO('1'), '', 'test', 'text/plain', 1, 'utf8')
'text/plain', 1, 'utf8')
with file: with file:
self.assertFalse(file.closed) self.assertFalse(file.closed)
self.storage.save('path/to/test.file', file) self.storage.save('path/to/test.file', file)
@ -383,8 +378,7 @@ class FileStorageTests(TestCase):
f = ContentFile('custom contents') f = ContentFile('custom contents')
f_name = self.storage.save('test.file', f) f_name = self.storage.save('test.file', f)
self.assertEqual(self.storage.path(f_name), self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name))
os.path.join(self.temp_dir, f_name))
self.storage.delete(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. File storage returns a url to access a given file from the Web.
""" """
self.assertEqual(self.storage.url('test.file'), self.assertEqual(self.storage.url('test.file'), self.storage.base_url + 'test.file')
'%s%s' % (self.storage.base_url, 'test.file'))
# should encode special chars except ~!*()' # should encode special chars except ~!*()'
# like encodeURIComponent() JavaScript function do # like encodeURIComponent() JavaScript function do
self.assertEqual(self.storage.url(r"""~!*()'@#$%^&*abc`+ =.file"""), self.assertEqual(
"""/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file""") self.storage.url(r"~!*()'@#$%^&*abc`+ =.file"),
self.assertEqual(self.storage.url("""ab\0c"""), """/test_media_url/ab%00c""") "/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 # should translate os path separator(s) to the url path separator
self.assertEqual(self.storage.url("""a/b\\c.file"""), self.assertEqual(self.storage.url("""a/b\\c.file"""), "/test_media_url/a/b/c.file")
"""/test_media_url/a/b/c.file""")
# #25905: remove leading slashes from file names to prevent unsafe url output # #25905: remove leading slashes from file names to prevent unsafe url output
self.assertEqual(self.storage.url("/evil.com"), "/test_media_url/evil.com") self.assertEqual(self.storage.url("/evil.com"), "/test_media_url/evil.com")
@ -422,8 +416,7 @@ class FileStorageTests(TestCase):
self.storage.url('test.file') self.storage.url('test.file')
# #22717: missing ending slash in base_url should be auto-corrected # #22717: missing ending slash in base_url should be auto-corrected
storage = self.storage_class(location=self.temp_dir, storage = self.storage_class(location=self.temp_dir, base_url='/no_ending_slash')
base_url='/no_ending_slash')
self.assertEqual( self.assertEqual(
storage.url('test.file'), storage.url('test.file'),
'%s%s' % (storage.base_url, 'test.file') '%s%s' % (storage.base_url, 'test.file')
@ -443,8 +436,7 @@ class FileStorageTests(TestCase):
dirs, files = self.storage.listdir('') dirs, files = self.storage.listdir('')
self.assertEqual(set(dirs), {'storage_dir_1'}) self.assertEqual(set(dirs), {'storage_dir_1'})
self.assertEqual(set(files), self.assertEqual(set(files), {'storage_test_1', 'storage_test_2'})
{'storage_test_1', 'storage_test_2'})
self.storage.delete('storage_test_1') self.storage.delete('storage_test_1')
self.storage.delete('storage_test_2') self.storage.delete('storage_test_2')
@ -470,8 +462,7 @@ class FileStorageTests(TestCase):
file = other_temp_storage.open(mixed_case, 'w') file = other_temp_storage.open(mixed_case, 'w')
file.write('storage contents') file.write('storage contents')
file.close() file.close()
self.assertEqual(os.path.join(self.temp_dir2, mixed_case), self.assertEqual(os.path.join(self.temp_dir2, mixed_case), other_temp_storage.path(mixed_case))
other_temp_storage.path(mixed_case))
other_temp_storage.delete(mixed_case) other_temp_storage.delete(mixed_case)
def test_makedirs_race_handling(self): def test_makedirs_race_handling(self):
@ -496,13 +487,11 @@ class FileStorageTests(TestCase):
try: try:
os.makedirs = fake_makedirs os.makedirs = fake_makedirs
self.storage.save('normal/test.file', self.storage.save('normal/test.file', ContentFile('saved normally'))
ContentFile('saved normally'))
with self.storage.open('normal/test.file') as f: with self.storage.open('normal/test.file') as f:
self.assertEqual(f.read(), b'saved normally') self.assertEqual(f.read(), b'saved normally')
self.storage.save('raced/test.file', self.storage.save('raced/test.file', ContentFile('saved with race'))
ContentFile('saved with race'))
with self.storage.open('raced/test.file') as f: with self.storage.open('raced/test.file') as f:
self.assertEqual(f.read(), b'saved with race') self.assertEqual(f.read(), b'saved with race')

View File

@ -585,8 +585,7 @@ class DirectoryCreationTests(SimpleTestCase):
self.obj.testfile.save('foo.txt', file, save=False) self.obj.testfile.save('foo.txt', file, save=False)
# The test needs to be done on a specific string as IOError # The test needs to be done on a specific string as IOError
# is raised even without the patch (just not early enough) # is raised even without the patch (just not early enough)
self.assertEqual(exc_info.exception.args[0], self.assertEqual(exc_info.exception.args[0], "%s exists and is not a directory." % UPLOAD_TO)
"%s exists and is not a directory." % UPLOAD_TO)
class MultiParserTests(unittest.TestCase): class MultiParserTests(unittest.TestCase):

View File

@ -664,8 +664,8 @@ class NonExistentFixtureTests(TestCase):
@mock.patch('django.db.connection.enable_constraint_checking') @mock.patch('django.db.connection.enable_constraint_checking')
@mock.patch('django.db.connection.disable_constraint_checking') @mock.patch('django.db.connection.disable_constraint_checking')
def test_nonexistent_fixture_no_constraint_checking(self, def test_nonexistent_fixture_no_constraint_checking(
disable_constraint_checking, enable_constraint_checking): self, disable_constraint_checking, enable_constraint_checking):
""" """
If no fixtures match the loaddata command, constraints checks on the If no fixtures match the loaddata command, constraints checks on the
database shouldn't be disabled. This is performance critical on MSSQL. database shouldn't be disabled. This is performance critical on MSSQL.

View File

@ -215,8 +215,7 @@ class TestFixtures(TestCase):
""" """
Test that failing serializer import raises the proper error Test that failing serializer import raises the proper error
""" """
with six.assertRaisesRegex(self, ImportError, with six.assertRaisesRegex(self, ImportError, r"No module named.*unexistent"):
r"No module named.*unexistent"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
'bad_fixture1.unkn', 'bad_fixture1.unkn',
@ -277,8 +276,7 @@ class TestFixtures(TestCase):
) )
warning = warning_list.pop() warning = warning_list.pop()
self.assertEqual(warning.category, RuntimeWarning) self.assertEqual(warning.category, RuntimeWarning)
self.assertEqual(str(warning.message), self.assertEqual(str(warning.message), "No fixture data found for 'empty'. (File format may be invalid.)")
"No fixture data found for 'empty'. (File format may be invalid.)")
def test_error_message(self): def test_error_message(self):
""" """

View File

@ -47,16 +47,14 @@ class FlatpageAdminFormTests(TestCase):
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.errors['url'], ["URL is missing a leading slash."]) self.assertEqual(form.errors['url'], ["URL is missing a leading slash."])
@override_settings(APPEND_SLASH=True, @override_settings(APPEND_SLASH=True, MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'])
MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'])
def test_flatpage_requires_trailing_slash_with_append_slash(self): def test_flatpage_requires_trailing_slash_with_append_slash(self):
form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))
with translation.override('en'): with translation.override('en'):
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."]) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."])
@override_settings(APPEND_SLASH=False, @override_settings(APPEND_SLASH=False, MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'])
MIDDLEWARE_CLASSES=['django.middleware.common.CommonMiddleware'])
def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self): def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self):
form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data))
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())

View File

@ -850,8 +850,10 @@ class FieldsTests(SimpleTestCase):
self.assertEqual('person@example.com', f.clean('person@example.com')) self.assertEqual('person@example.com', f.clean('person@example.com'))
with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid email address.'"):
f.clean('foo') f.clean('foo')
self.assertEqual('local@domain.with.idn.xyz\xe4\xf6\xfc\xdfabc.part.com', self.assertEqual(
f.clean('local@domain.with.idn.xyzäöüßabc.part.com')) '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): def test_email_regexp_for_performance(self):
f = EmailField() f = EmailField()
@ -1259,9 +1261,11 @@ class FieldsTests(SimpleTestCase):
def test_choicefield_disabled(self): def test_choicefield_disabled(self):
f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True) f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')], disabled=True)
self.assertWidgetRendersTo(f, self.assertWidgetRendersTo(
f,
'<select id="id_f" name="f" disabled><option value="J">John</option>' '<select id="id_f" name="f" disabled><option value="J">John</option>'
'<option value="P">Paul</option></select>') '<option value="P">Paul</option></select>'
)
# TypedChoiceField ############################################################ # TypedChoiceField ############################################################
# TypedChoiceField is just like ChoiceField, except that coerced types will # TypedChoiceField is just like ChoiceField, except that coerced types will
@ -1434,8 +1438,8 @@ class FieldsTests(SimpleTestCase):
f.clean('hello') f.clean('hello')
self.assertEqual([], f.clean([])) self.assertEqual([], f.clean([]))
self.assertEqual([], f.clean(())) self.assertEqual([], f.clean(()))
with self.assertRaisesMessage(ValidationError, msg = "'Select a valid choice. 3 is not one of the available choices.'"
"'Select a valid choice. 3 is not one of the available choices.'"): with self.assertRaisesMessage(ValidationError, msg):
f.clean(['3']) f.clean(['3'])
def test_multiplechoicefield_3(self): def test_multiplechoicefield_3(self):

View File

@ -1493,11 +1493,13 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/
address = CharField() # no max_length defined here address = CharField() # no max_length defined here
p = UserRegistration(auto_id=False) p = UserRegistration(auto_id=False)
self.assertHTMLEqual(p.as_ul(), self.assertHTMLEqual(
"""<li>Username: <input type="text" name="username" maxlength="10" /></li> p.as_ul(),
"""<li>Username: <input type="text" name="username" maxlength="10" /></li>
<li>Password: <input type="password" name="password" maxlength="10" /></li> <li>Password: <input type="password" name="password" maxlength="10" /></li>
<li>Realname: <input type="text" name="realname" maxlength="10" /></li> <li>Realname: <input type="text" name="realname" maxlength="10" /></li>
<li>Address: <input type="text" name="address" /></li>""") <li>Address: <input type="text" name="address" /></li>"""
)
# If you specify a custom "attrs" that includes the "maxlength" attribute, # If you specify a custom "attrs" that includes the "maxlength" attribute,
# the Field's max_length attribute will override whatever "maxlength" you specify # the Field's max_length attribute will override whatever "maxlength" you specify
@ -1507,9 +1509,11 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/
password = CharField(max_length=10, widget=PasswordInput) password = CharField(max_length=10, widget=PasswordInput)
p = UserRegistration(auto_id=False) p = UserRegistration(auto_id=False)
self.assertHTMLEqual(p.as_ul(), self.assertHTMLEqual(
"""<li>Username: <input type="text" name="username" maxlength="10" /></li> p.as_ul(),
<li>Password: <input type="password" name="password" maxlength="10" /></li>""") """<li>Username: <input type="text" name="username" maxlength="10" /></li>
<li>Password: <input type="password" name="password" maxlength="10" /></li>"""
)
def test_specifying_labels(self): def test_specifying_labels(self):
# You can specify the label for a field by using the 'label' argument to a Field # You can specify the label for a field by using the 'label' argument to a Field
@ -1521,10 +1525,12 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/
password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)') password2 = CharField(widget=PasswordInput, label='Contraseña (de nuevo)')
p = UserRegistration(auto_id=False) p = UserRegistration(auto_id=False)
self.assertHTMLEqual(p.as_ul(), self.assertHTMLEqual(
"""<li>Your username: <input type="text" name="username" maxlength="10" /></li> p.as_ul(),
"""<li>Your username: <input type="text" name="username" maxlength="10" /></li>
<li>Password1: <input type="password" name="password1" /></li> <li>Password1: <input type="password" name="password1" /></li>
<li>Contraseña (de nuevo): <input type="password" name="password2" /></li>""") <li>Contraseña (de nuevo): <input type="password" name="password2" /></li>"""
)
# Labels for as_* methods will only end in a colon if they don't end in other # Labels for as_* methods will only end in a colon if they don't end in other
# punctuation already. # punctuation already.
@ -1574,9 +1580,11 @@ value="Should escape &lt; &amp; &gt; and &lt;script&gt;alert(&#39;xss&#39;)&lt;/
password = CharField(widget=PasswordInput) password = CharField(widget=PasswordInput)
p = UserRegistration(auto_id=False) p = UserRegistration(auto_id=False)
self.assertHTMLEqual(p.as_ul(), self.assertHTMLEqual(
"""<li>Username: <input type="text" name="username" maxlength="10" /></li> p.as_ul(),
<li>Password: <input type="password" name="password" /></li>""") """<li>Username: <input type="text" name="username" maxlength="10" /></li>
<li>Password: <input type="password" name="password" /></li>"""
)
p = UserRegistration(auto_id='id_%s') p = UserRegistration(auto_id='id_%s')
self.assertHTMLEqual( self.assertHTMLEqual(
p.as_ul(), p.as_ul(),
@ -1861,8 +1869,7 @@ Password: <input type="password" name="password" /></li>
last_name = CharField(initial='Greatel') last_name = CharField(initial='Greatel')
birthday = DateField(initial=datetime.date(1974, 8, 16)) birthday = DateField(initial=datetime.date(1974, 8, 16))
p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', p = Person(data={'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16'})
'birthday': '1974-08-16'})
self.assertTrue(p.is_valid()) self.assertTrue(p.is_valid())
self.assertNotIn('first_name', p.changed_data) self.assertNotIn('first_name', p.changed_data)
self.assertIn('last_name', p.changed_data) self.assertIn('last_name', p.changed_data)
@ -1876,8 +1883,10 @@ Password: <input type="password" name="password" /></li>
class Person2(Person): class Person2(Person):
pedantic = PedanticField(initial='whatever', show_hidden_initial=True) pedantic = PedanticField(initial='whatever', show_hidden_initial=True)
p = Person2(data={'first_name': 'Hans', 'last_name': 'Scrmbl', p = Person2(data={
'birthday': '1974-08-16', 'initial-pedantic': 'whatever'}) 'first_name': 'Hans', 'last_name': 'Scrmbl', 'birthday': '1974-08-16',
'initial-pedantic': 'whatever',
})
self.assertFalse(p.is_valid()) self.assertFalse(p.is_valid())
self.assertIn('pedantic', p.changed_data) self.assertIn('pedantic', p.changed_data)
@ -2700,9 +2709,10 @@ Good luck picking a username that doesn&#39;t already exist.</p>
""" """
class ChoicesField(MultiValueField): class ChoicesField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs): def __init__(self, fields=(), *args, **kwargs):
fields = (ChoiceField(label='Rank', fields = (
choices=((1, 1), (2, 2))), ChoiceField(label='Rank', choices=((1, 1), (2, 2))),
CharField(label='Name', max_length=10)) CharField(label='Name', max_length=10),
)
super(ChoicesField, self).__init__(fields=fields, *args, **kwargs) super(ChoicesField, self).__init__(fields=fields, *args, **kwargs)
field = ChoicesField() field = ChoicesField()
@ -2787,8 +2797,10 @@ Good luck picking a username that doesn&#39;t already exist.</p>
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61']) f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex(self, ValidationError, six.assertRaisesRegex(
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) self, ValidationError,
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])
@ -2801,8 +2813,10 @@ Good luck picking a username that doesn&#39;t already exist.</p>
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61']) f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex(self, ValidationError, six.assertRaisesRegex(
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) self, ValidationError,
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
)
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])

View File

@ -46,8 +46,7 @@ class EmptyFsetWontValidate(BaseFormSet):
# Let's define a FormSet that takes a list of favorite drinks, but raises an # 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``, # error if there are any duplicates. Used in ``test_clean_hook``,
# ``test_regression_6926`` & ``test_regression_12878``. # ``test_regression_6926`` & ``test_regression_12878``.
FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, FavoriteDrinksFormSet = formset_factory(FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3)
formset=BaseFavoriteDrinksFormSet, extra=3)
# Used in ``test_formset_splitdatetimefield``. # Used in ``test_formset_splitdatetimefield``.
@ -65,7 +64,8 @@ class CustomKwargForm(Form):
class FormsFormsetTestCase(SimpleTestCase): 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): total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs):
""" """
Make a ChoiceFormset from the given formset_data. Make a ChoiceFormset from the given formset_data.
@ -1162,8 +1162,7 @@ class FormsFormsetTestCase(SimpleTestCase):
ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet)
formset = ChoiceFormSet(data, auto_id=False, prefix='choices') formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertIsInstance(formset.non_form_errors(), ErrorList) self.assertIsInstance(formset.non_form_errors(), ErrorList)
self.assertEqual(list(formset.non_form_errors()), self.assertEqual(list(formset.non_form_errors()), ['This is a non-form error'])
['This is a non-form error'])
def test_validate_max_ignores_forms_marked_for_deletion(self): def test_validate_max_ignores_forms_marked_for_deletion(self):
class CheckForm(Form): class CheckForm(Form):

View File

@ -59,27 +59,30 @@ class FormsUtilsTestCase(SimpleTestCase):
################### ###################
# Can take a string. # Can take a string.
self.assertHTMLEqual(str(ErrorList(ValidationError("There was an error.").messages)), self.assertHTMLEqual(
'<ul class="errorlist"><li>There was an error.</li></ul>') str(ErrorList(ValidationError("There was an error.").messages)),
'<ul class="errorlist"><li>There was an error.</li></ul>'
)
# Can take a unicode string. # Can take a unicode string.
self.assertHTMLEqual(six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)), self.assertHTMLEqual(
'<ul class="errorlist"><li>Not π.</li></ul>') six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)),
'<ul class="errorlist"><li>Not π.</li></ul>'
)
# Can take a lazy string. # Can take a lazy string.
self.assertHTMLEqual(str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)), self.assertHTMLEqual(
'<ul class="errorlist"><li>Error.</li></ul>') str(ErrorList(ValidationError(ugettext_lazy("Error.")).messages)),
'<ul class="errorlist"><li>Error.</li></ul>'
)
# Can take a list. # Can take a list.
self.assertHTMLEqual(str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)), self.assertHTMLEqual(
'<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>') str(ErrorList(ValidationError(["Error one.", "Error two."]).messages)),
'<ul class="errorlist"><li>Error one.</li><li>Error two.</li></ul>'
)
# Can take a dict. # Can take a dict.
self.assertHTMLEqual( self.assertHTMLEqual(
str(ErrorList(sorted(ValidationError({'error_1': "1. Error one.", 'error_2': "2. Error two."}).messages))), str(ErrorList(sorted(ValidationError({'error_1': "1. Error one.", 'error_2': "2. Error two."}).messages))),
'<ul class="errorlist"><li>1. Error one.</li><li>2. Error two.</li></ul>' '<ul class="errorlist"><li>1. Error one.</li><li>2. Error two.</li></ul>'
) )
# Can take a mixture in a list. # Can take a mixture in a list.
self.assertHTMLEqual( self.assertHTMLEqual(
str(ErrorList(sorted(ValidationError([ str(ErrorList(sorted(ValidationError([

View File

@ -170,8 +170,7 @@ class LiveWidgetTests(AdminSeleniumTestCase):
Test that a roundtrip on a ModelForm doesn't alter the TextField value Test that a roundtrip on a ModelForm doesn't alter the TextField value
""" """
article = Article.objects.create(content="\nTst\n") article = Article.objects.create(content="\nTst\n")
self.selenium.get('%s%s' % (self.live_server_url, self.selenium.get(self.live_server_url + reverse('article_form', args=[article.pk]))
reverse('article_form', args=[article.pk])))
self.selenium.find_element_by_id('submit').submit() self.selenium.find_element_by_id('submit').submit()
article = Article.objects.get(pk=article.pk) article = Article.objects.get(pk=article.pk)
# Should be "\nTst\n" after #19251 is fixed # Should be "\nTst\n" after #19251 is fixed

View File

@ -191,8 +191,7 @@ class GenericAdminViewTest(TestDataMixin, TestCase):
def test_generic_inline_formset_factory(self): def test_generic_inline_formset_factory(self):
# Regression test for #10522. # Regression test for #10522.
inline_formset = generic_inlineformset_factory(Media, inline_formset = generic_inlineformset_factory(Media, exclude=('url',))
exclude=('url',))
# Regression test for #12340. # Regression test for #12340.
e = Episode.objects.get(name='This Week in Django') e = Episode.objects.get(name='This Week in Django')

View File

@ -524,8 +524,7 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id" /></p>""" % tag
def test_get_or_create(self): def test_get_or_create(self):
# get_or_create should work with virtual fields (content_object) # get_or_create should work with virtual fields (content_object)
quartz = Mineral.objects.create(name="Quartz", hardness=7) quartz = Mineral.objects.create(name="Quartz", hardness=7)
tag, created = TaggedItem.objects.get_or_create(tag="shiny", tag, created = TaggedItem.objects.get_or_create(tag="shiny", defaults={'content_object': quartz})
defaults={'content_object': quartz})
self.assertTrue(created) self.assertTrue(created)
self.assertEqual(tag.tag, "shiny") self.assertEqual(tag.tag, "shiny")
self.assertEqual(tag.content_object.id, quartz.id) self.assertEqual(tag.content_object.id, quartz.id)
@ -534,13 +533,11 @@ id="id_generic_relations-taggeditem-content_type-object_id-1-id" /></p>""" % tag
# update_or_create should work with virtual fields (content_object) # update_or_create should work with virtual fields (content_object)
quartz = Mineral.objects.create(name="Quartz", hardness=7) quartz = Mineral.objects.create(name="Quartz", hardness=7)
diamond = Mineral.objects.create(name="Diamond", hardness=7) diamond = Mineral.objects.create(name="Diamond", hardness=7)
tag, created = TaggedItem.objects.update_or_create(tag="shiny", tag, created = TaggedItem.objects.update_or_create(tag="shiny", defaults={'content_object': quartz})
defaults={'content_object': quartz})
self.assertTrue(created) self.assertTrue(created)
self.assertEqual(tag.content_object.id, quartz.id) self.assertEqual(tag.content_object.id, quartz.id)
tag, created = TaggedItem.objects.update_or_create(tag="shiny", tag, created = TaggedItem.objects.update_or_create(tag="shiny", defaults={'content_object': diamond})
defaults={'content_object': diamond})
self.assertFalse(created) self.assertFalse(created)
self.assertEqual(tag.content_object.id, diamond.id) self.assertEqual(tag.content_object.id, diamond.id)
@ -589,8 +586,7 @@ class GenericInlineFormsetTest(TestCase):
self.instance.saved_by = "custom method" self.instance.saved_by = "custom method"
return super(SaveTestForm, self).save(*args, **kwargs) return super(SaveTestForm, self).save(*args, **kwargs)
Formset = generic_inlineformset_factory( Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', form=SaveTestForm)
ForProxyModelModel, fields='__all__', form=SaveTestForm)
instance = ProxyRelatedModel.objects.create() instance = ProxyRelatedModel.objects.create()
@ -607,8 +603,7 @@ class GenericInlineFormsetTest(TestCase):
self.assertEqual(new_obj.saved_by, "custom method") self.assertEqual(new_obj.saved_by, "custom method")
def test_save_new_for_proxy(self): def test_save_new_for_proxy(self):
Formset = generic_inlineformset_factory(ForProxyModelModel, Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', for_concrete_model=False)
fields='__all__', for_concrete_model=False)
instance = ProxyRelatedModel.objects.create() instance = ProxyRelatedModel.objects.create()
@ -626,8 +621,7 @@ class GenericInlineFormsetTest(TestCase):
self.assertEqual(new_obj.obj, instance) self.assertEqual(new_obj.obj, instance)
def test_save_new_for_concrete(self): def test_save_new_for_concrete(self):
Formset = generic_inlineformset_factory(ForProxyModelModel, Formset = generic_inlineformset_factory(ForProxyModelModel, fields='__all__', for_concrete_model=True)
fields='__all__', for_concrete_model=True)
instance = ProxyRelatedModel.objects.create() instance = ProxyRelatedModel.objects.create()

View File

@ -103,31 +103,27 @@ class CreateViewTests(TestCase):
self.assertNotIn('author', res.context) self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertTemplateUsed(res, 'generic_views/author_form.html')
res = self.client.post('/edit/authors/create/', res = self.client.post('/edit/authors/create/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/list/authors/') self.assertRedirects(res, '/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
def test_create_invalid(self): def test_create_invalid(self):
res = self.client.post('/edit/authors/create/', res = self.client.post('/edit/authors/create/', {'name': 'A' * 101, 'slug': 'randall-munroe'})
{'name': 'A' * 101, 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertTemplateUsed(res, 'generic_views/author_form.html')
self.assertEqual(len(res.context['form'].errors), 1) self.assertEqual(len(res.context['form'].errors), 1)
self.assertEqual(Author.objects.count(), 0) self.assertEqual(Author.objects.count(), 0)
def test_create_with_object_url(self): def test_create_with_object_url(self):
res = self.client.post('/edit/artists/create/', res = self.client.post('/edit/artists/create/', {'name': 'Rene Magritte'})
{'name': 'Rene Magritte'})
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
artist = Artist.objects.get(name='Rene Magritte') artist = Artist.objects.get(name='Rene Magritte')
self.assertRedirects(res, '/detail/artist/%d/' % artist.pk) self.assertRedirects(res, '/detail/artist/%d/' % artist.pk)
self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>']) self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
def test_create_with_redirect(self): def test_create_with_redirect(self):
res = self.client.post('/edit/authors/create/redirect/', res = self.client.post('/edit/authors/create/redirect/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/edit/authors/create/') self.assertRedirects(res, '/edit/authors/create/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
@ -158,24 +154,21 @@ class CreateViewTests(TestCase):
self.assertNotIn('author', res.context) self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html') self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/authors/create/special/', res = self.client.post('/edit/authors/create/special/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
obj = Author.objects.get(slug='randall-munroe') obj = Author.objects.get(slug='randall-munroe')
self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk})) self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk}))
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
def test_create_without_redirect(self): def test_create_without_redirect(self):
try: with self.assertRaises(ImproperlyConfigured):
self.client.post('/edit/authors/create/naive/', self.client.post('/edit/authors/create/naive/', {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
except ImproperlyConfigured:
pass
def test_create_restricted(self): def test_create_restricted(self):
res = self.client.post('/edit/authors/create/restricted/', res = self.client.post(
{'name': 'Randall Munroe', 'slug': 'randall-munroe'}) '/edit/authors/create/restricted/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'}
)
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/accounts/login/?next=/edit/authors/create/restricted/') self.assertRedirects(res, '/accounts/login/?next=/edit/authors/create/restricted/')
@ -185,16 +178,14 @@ class CreateViewTests(TestCase):
model = Author model = Author
fields = ['name'] fields = ['name']
self.assertEqual(list(MyCreateView().get_form_class().base_fields), self.assertEqual(list(MyCreateView().get_form_class().base_fields), ['name'])
['name'])
def test_create_view_all_fields(self): def test_create_view_all_fields(self):
class MyCreateView(CreateView): class MyCreateView(CreateView):
model = Author model = Author
fields = '__all__' fields = '__all__'
self.assertEqual(list(MyCreateView().get_form_class().base_fields), self.assertEqual(list(MyCreateView().get_form_class().base_fields), ['name', 'slug'])
['name', 'slug'])
def test_create_view_without_explicit_fields(self): def test_create_view_without_explicit_fields(self):
class MyCreateView(CreateView): class MyCreateView(CreateView):
@ -235,8 +226,10 @@ class UpdateViewTests(TestCase):
self.assertEqual(res.context['view'].get_form_called_count, 1) self.assertEqual(res.context['view'].get_form_called_count, 1)
# Modification with both POST and PUT (browser compatible) # Modification with both POST and PUT (browser compatible)
res = self.client.post('/edit/author/%d/update/' % a.pk, res = self.client.post(
{'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}) '/edit/author/%d/update/' % a.pk,
{'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'}
)
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/list/authors/') self.assertRedirects(res, '/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])
@ -246,8 +239,7 @@ class UpdateViewTests(TestCase):
name='Randall Munroe', name='Randall Munroe',
slug='randall-munroe', slug='randall-munroe',
) )
res = self.client.post('/edit/author/%d/update/' % a.pk, res = self.client.post('/edit/author/%d/update/' % a.pk, {'name': 'A' * 101, 'slug': 'randall-munroe'})
{'name': 'A' * 101, 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertTemplateUsed(res, 'generic_views/author_form.html')
self.assertEqual(len(res.context['form'].errors), 1) self.assertEqual(len(res.context['form'].errors), 1)
@ -256,8 +248,7 @@ class UpdateViewTests(TestCase):
def test_update_with_object_url(self): def test_update_with_object_url(self):
a = Artist.objects.create(name='Rene Magritte') a = Artist.objects.create(name='Rene Magritte')
res = self.client.post('/edit/artists/%d/update/' % a.pk, res = self.client.post('/edit/artists/%d/update/' % a.pk, {'name': 'Rene Magritte'})
{'name': 'Rene Magritte'})
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/detail/artist/%d/' % a.pk) self.assertRedirects(res, '/detail/artist/%d/' % a.pk)
self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>']) self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
@ -267,8 +258,10 @@ class UpdateViewTests(TestCase):
name='Randall Munroe', name='Randall Munroe',
slug='randall-munroe', slug='randall-munroe',
) )
res = self.client.post('/edit/author/%d/update/redirect/' % a.pk, res = self.client.post(
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) '/edit/author/%d/update/redirect/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}
)
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/edit/authors/create/') self.assertRedirects(res, '/edit/authors/create/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
@ -308,8 +301,10 @@ class UpdateViewTests(TestCase):
self.assertNotIn('author', res.context) self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html') self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/author/%d/update/special/' % a.pk, res = self.client.post(
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) '/edit/author/%d/update/special/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}
)
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/detail/author/%d/' % a.pk) self.assertRedirects(res, '/detail/author/%d/' % a.pk)
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
@ -322,8 +317,10 @@ class UpdateViewTests(TestCase):
# Should raise exception -- No redirect URL provided, and no # Should raise exception -- No redirect URL provided, and no
# get_absolute_url provided # get_absolute_url provided
with self.assertRaises(ImproperlyConfigured): with self.assertRaises(ImproperlyConfigured):
self.client.post('/edit/author/%d/update/naive/' % a.pk, self.client.post(
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) '/edit/author/%d/update/naive/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}
)
def test_update_get_object(self): def test_update_get_object(self):
a = Author.objects.create( a = Author.objects.create(
@ -340,8 +337,7 @@ class UpdateViewTests(TestCase):
self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertTemplateUsed(res, 'generic_views/author_form.html')
# Modification with both POST and PUT (browser compatible) # Modification with both POST and PUT (browser compatible)
res = self.client.post('/edit/author/update/', res = self.client.post('/edit/author/update/', {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
{'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, '/list/authors/') self.assertRedirects(res, '/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])

View File

@ -238,8 +238,7 @@ class ListViewTests(TestCase):
self._make_authors(1) self._make_authors(1)
res = self.client.get('/list/authors/paginated/2/') res = self.client.get('/list/authors/paginated/2/')
self.assertEqual(res.status_code, 404) self.assertEqual(res.status_code, 404)
self.assertEqual(force_str(res.context.get('reason')), self.assertEqual(force_str(res.context.get('reason')), "Invalid page (2): That page contains no results")
"Invalid page (2): That page contains no results")
def _make_authors(self, n): def _make_authors(self, n):
Author.objects.all().delete() Author.objects.all().delete()

View File

@ -12,7 +12,8 @@ if HAS_GDAL:
# List of acceptable data sources. # List of acceptable data sources.
ds_list = ( ds_list = (
TestDS('test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile', TestDS(
'test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile',
fields={'dbl': OFTReal, 'int': OFTInteger, 'str': OFTString}, fields={'dbl': OFTReal, 'int': OFTInteger, 'str': OFTString},
extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS
srs_wkt=( srs_wkt=(
@ -27,7 +28,8 @@ if HAS_GDAL:
}, },
fids=range(5) fids=range(5)
), ),
TestDS('test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', TestDS(
'test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D',
driver='OGR_VRT' if GDAL_VERSION >= (2, 0) else 'VRT', driver='OGR_VRT' if GDAL_VERSION >= (2, 0) else 'VRT',
fields={ fields={
'POINT_X': OFTString, 'POINT_X': OFTString,
@ -42,7 +44,8 @@ if HAS_GDAL:
}, },
fids=range(1, 4) fids=range(1, 4)
), ),
TestDS('test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3, TestDS(
'test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3,
driver='ESRI Shapefile', driver='ESRI Shapefile',
fields={'float': OFTReal, 'int': OFTInteger, 'str': OFTString}, fields={'float': OFTReal, 'int': OFTInteger, 'str': OFTString},
extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS

View File

@ -15,9 +15,10 @@ except ImportError:
if HAS_GDAL: if HAS_GDAL:
from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType, from django.contrib.gis.gdal import (
GDALException, OGRIndexError, SpatialReference, CoordTransform, OGRGeometry, OGRGeomType, GDALException, OGRIndexError,
GDAL_VERSION) SpatialReference, CoordTransform, GDAL_VERSION,
)
@skipUnless(HAS_GDAL, "GDAL is required") @skipUnless(HAS_GDAL, "GDAL is required")

View File

@ -96,8 +96,10 @@ class GDALRasterTests(unittest.TestCase):
def test_geotransform_and_friends(self): def test_geotransform_and_friends(self):
# Assert correct values for file based raster # Assert correct values for file based raster
self.assertEqual(self.rs.geotransform, self.assertEqual(
[511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0]) self.rs.geotransform,
[511700.4680706557, 100.0, 0.0, 435103.3771231986, 0.0, -100.0]
)
self.assertEqual(self.rs.origin, [511700.4680706557, 435103.3771231986]) self.assertEqual(self.rs.origin, [511700.4680706557, 435103.3771231986])
self.assertEqual(self.rs.origin.x, 511700.4680706557) self.assertEqual(self.rs.origin.x, 511700.4680706557)
self.assertEqual(self.rs.origin.y, 435103.3771231986) self.assertEqual(self.rs.origin.y, 435103.3771231986)
@ -124,9 +126,10 @@ class GDALRasterTests(unittest.TestCase):
self.assertEqual(rsmem.height, 5) self.assertEqual(rsmem.height, 5)
def test_rs_extent(self): def test_rs_extent(self):
self.assertEqual(self.rs.extent, self.assertEqual(
(511700.4680706557, 417703.3771231986, self.rs.extent,
528000.4680706557, 435103.3771231986)) (511700.4680706557, 417703.3771231986, 528000.4680706557, 435103.3771231986)
)
def test_rs_bands(self): def test_rs_bands(self):
self.assertEqual(len(self.rs.bands), 1) self.assertEqual(len(self.rs.bands), 1)
@ -305,8 +308,7 @@ class GDALRasterTests(unittest.TestCase):
@unittest.skipUnless(HAS_GDAL, "GDAL is required") @unittest.skipUnless(HAS_GDAL, "GDAL is required")
class GDALBandTests(SimpleTestCase): class GDALBandTests(SimpleTestCase):
def setUp(self): def setUp(self):
self.rs_path = os.path.join(os.path.dirname(upath(__file__)), self.rs_path = os.path.join(os.path.dirname(upath(__file__)), '../data/rasters/raster.tif')
'../data/rasters/raster.tif')
rs = GDALRaster(self.rs_path) rs = GDALRaster(self.rs_path)
self.band = rs.bands[0] self.band = rs.bands[0]

View File

@ -73,8 +73,9 @@ class GeoJSONSerializerTests(TestCase):
the 'properties' of the generated output. the 'properties' of the generated output.
""" """
PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)') PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)')
geojson = serializers.serialize('geojson', PennsylvaniaCity.objects.all(), geojson = serializers.serialize(
fields=('county', 'point')) 'geojson', PennsylvaniaCity.objects.all(), fields=('county', 'point'),
)
geodata = json.loads(geojson) geodata = json.loads(geojson)
self.assertIn('county', geodata['features'][0]['properties']) self.assertIn('county', geodata['features'][0]['properties'])
self.assertNotIn('founded', geodata['features'][0]['properties']) self.assertNotIn('founded', geodata['features'][0]['properties'])
@ -85,7 +86,8 @@ class GeoJSONSerializerTests(TestCase):
geodata = json.loads(geojson) geodata = json.loads(geojson)
self.assertEqual( self.assertEqual(
[int(c) for c in geodata['features'][0]['geometry']['coordinates']], [int(c) for c in geodata['features'][0]['geometry']['coordinates']],
[1564802, 5613214]) [1564802, 5613214]
)
@mock.patch('django.contrib.gis.serializers.geojson.HAS_GDAL', False) @mock.patch('django.contrib.gis.serializers.geojson.HAS_GDAL', False)
def test_without_gdal(self): def test_without_gdal(self):

View File

@ -147,8 +147,7 @@ class GEOSMutationTest(unittest.TestCase):
'Polygon _get_single_external(1)') 'Polygon _get_single_external(1)')
# _set_list # _set_list
pg._set_list(2, (((1, 2), (10, 0), (12, 9), (-1, 15), (1, 2)), pg._set_list(2, (((1, 2), (10, 0), (12, 9), (-1, 15), (1, 2)), ((4, 2), (5, 2), (5, 3), (4, 2))))
((4, 2), (5, 2), (5, 3), (4, 2))))
self.assertEqual( self.assertEqual(
pg.coords, pg.coords,
(((1.0, 2.0), (10.0, 0.0), (12.0, 9.0), (-1.0, 15.0), (1.0, 2.0)), (((1.0, 2.0), (10.0, 0.0), (12.0, 9.0), (-1.0, 15.0), (1.0, 2.0)),
@ -161,8 +160,11 @@ class GEOSMutationTest(unittest.TestCase):
def test06_Collection(self): def test06_Collection(self):
'Testing Collection mutations' 'Testing Collection mutations'
for mp in (MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))), points = (
fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)')): MultiPoint(*map(Point, ((3, 4), (-1, 2), (5, -4), (2, 8)))),
fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)'),
)
for mp in points:
self.assertEqual(mp._get_single_external(2), Point(5, -4), 'Collection _get_single_external') self.assertEqual(mp._get_single_external(2), Point(5, -4), 'Collection _get_single_external')
mp._set_list(3, map(Point, ((5, 5), (3, -2), (8, 1)))) mp._set_list(3, map(Point, ((5, 5), (3, -2), (8, 1))))

View File

@ -73,7 +73,7 @@ class OperationTests(TransactionTestCase):
self.assertIn(column, indexes) self.assertIn(column, indexes)
def alter_gis_model(self, migration_class, model_name, field_name, def alter_gis_model(self, migration_class, model_name, field_name,
blank=False, field_class=None): blank=False, field_class=None):
project_state = self.set_up_test_model() project_state = self.set_up_test_model()
self.current_state = project_state self.current_state = project_state
args = [model_name, field_name] args = [model_name, field_name]
@ -90,8 +90,7 @@ class OperationTests(TransactionTestCase):
""" """
Test the AddField operation with a geometry-enabled column. Test the AddField operation with a geometry-enabled column.
""" """
self.alter_gis_model(migrations.AddField, 'Neighborhood', self.alter_gis_model(migrations.AddField, 'Neighborhood', 'path', False, fields.LineStringField)
'path', False, fields.LineStringField)
self.assertColumnExists('gis_neighborhood', 'path') self.assertColumnExists('gis_neighborhood', 'path')
# Test GeometryColumns when available # Test GeometryColumns when available
@ -107,8 +106,7 @@ class OperationTests(TransactionTestCase):
""" """
Test the AddField operation with a raster-enabled column. Test the AddField operation with a raster-enabled column.
""" """
self.alter_gis_model(migrations.AddField, 'Neighborhood', self.alter_gis_model(migrations.AddField, 'Neighborhood', 'heatmap', False, fields.RasterField)
'heatmap', False, fields.RasterField)
self.assertColumnExists('gis_neighborhood', 'heatmap') self.assertColumnExists('gis_neighborhood', 'heatmap')
# Test spatial indices when available # Test spatial indices when available
@ -140,8 +138,7 @@ class OperationTests(TransactionTestCase):
""" """
Should be able to add a GeometryField with blank=True. Should be able to add a GeometryField with blank=True.
""" """
self.alter_gis_model(migrations.AddField, 'Neighborhood', self.alter_gis_model(migrations.AddField, 'Neighborhood', 'path', True, fields.LineStringField)
'path', True, fields.LineStringField)
self.assertColumnExists('gis_neighborhood', 'path') self.assertColumnExists('gis_neighborhood', 'path')
# Test GeometryColumns when available # Test GeometryColumns when available
@ -157,8 +154,7 @@ class OperationTests(TransactionTestCase):
""" """
Should be able to add a RasterField with blank=True. Should be able to add a RasterField with blank=True.
""" """
self.alter_gis_model(migrations.AddField, 'Neighborhood', self.alter_gis_model(migrations.AddField, 'Neighborhood', 'heatmap', True, fields.RasterField)
'heatmap', True, fields.RasterField)
self.assertColumnExists('gis_neighborhood', 'heatmap') self.assertColumnExists('gis_neighborhood', 'heatmap')
# Test spatial indices when available # Test spatial indices when available

View File

@ -15,13 +15,16 @@ from django.test import TestCase, override_settings, skipUnlessDBFeature
from django.utils._os import upath from django.utils._os import upath
if HAS_GEOS and HAS_GDAL: if HAS_GEOS and HAS_GDAL:
from django.contrib.gis.utils.layermapping import (LayerMapping, from django.contrib.gis.utils.layermapping import (
LayerMapError, InvalidDecimal, InvalidString, MissingForeignKey) LayerMapping, LayerMapError, InvalidDecimal, InvalidString,
MissingForeignKey,
)
from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal import DataSource
from .models import ( from .models import (
City, County, CountyFeat, Interstate, ICity1, ICity2, Invalid, State, City, County, CountyFeat, Interstate, ICity1, ICity2, Invalid, State,
city_mapping, co_mapping, cofeat_mapping, inter_mapping) city_mapping, co_mapping, cofeat_mapping, inter_mapping,
)
shp_path = os.path.realpath(os.path.join(os.path.dirname(upath(__file__)), os.pardir, 'data')) shp_path = os.path.realpath(os.path.join(os.path.dirname(upath(__file__)), os.pardir, 'data'))

View File

@ -26,8 +26,10 @@ if HAS_GEOIP:
# 'GeoLiteCity.dat'. # 'GeoLiteCity.dat'.
@skipUnless(HAS_GEOIP and getattr(settings, "GEOIP_PATH", None), @skipUnless(
"GeoIP is required along with the GEOIP_PATH setting.") HAS_GEOIP and getattr(settings, "GEOIP_PATH", None),
"GeoIP is required along with the GEOIP_PATH setting."
)
@ignore_warnings(category=RemovedInDjango20Warning) @ignore_warnings(category=RemovedInDjango20Warning)
class GeoIPTest(unittest.TestCase): class GeoIPTest(unittest.TestCase):
addr = '128.249.1.1' addr = '128.249.1.1'

View File

@ -19,8 +19,10 @@ if HAS_GEOIP2:
# The GEOIP_DATA path should be the only setting set (the directory # The GEOIP_DATA path should be the only setting set (the directory
# should contain links or the actual database files 'GeoLite2-City.mmdb' and # should contain links or the actual database files 'GeoLite2-City.mmdb' and
# 'GeoLite2-City.mmdb'. # 'GeoLite2-City.mmdb'.
@skipUnless(HAS_GEOIP2 and getattr(settings, "GEOIP_PATH", None), @skipUnless(
"GeoIP is required along with the GEOIP_PATH setting.") HAS_GEOIP2 and getattr(settings, "GEOIP_PATH", None),
"GeoIP is required along with the GEOIP_PATH setting."
)
class GeoIPTest(unittest.TestCase): class GeoIPTest(unittest.TestCase):
addr = '128.249.1.1' addr = '128.249.1.1'
fqdn = 'tmc.edu' fqdn = 'tmc.edu'

View File

@ -461,9 +461,11 @@ class HttpResponseSubclassesTests(SimpleTestCase):
response = HttpResponseRedirect('/redirected/') response = HttpResponseRedirect('/redirected/')
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
# Test that standard HttpResponse init args can be used # Test that standard HttpResponse init args can be used
response = HttpResponseRedirect('/redirected/', response = HttpResponseRedirect(
'/redirected/',
content='The resource has temporarily moved', content='The resource has temporarily moved',
content_type='text/html') content_type='text/html',
)
self.assertContains(response, 'The resource has temporarily moved', status_code=302) self.assertContains(response, 'The resource has temporarily moved', status_code=302)
# Test that url attribute is right # Test that url attribute is right
self.assertEqual(response.url, response['Location']) self.assertEqual(response.url, response['Location'])
@ -490,9 +492,7 @@ class HttpResponseSubclassesTests(SimpleTestCase):
response = HttpResponseNotAllowed(['GET']) response = HttpResponseNotAllowed(['GET'])
self.assertEqual(response.status_code, 405) self.assertEqual(response.status_code, 405)
# Test that standard HttpResponse init args can be used # Test that standard HttpResponse init args can be used
response = HttpResponseNotAllowed(['GET'], response = HttpResponseNotAllowed(['GET'], content='Only the GET method is allowed', content_type='text/html')
content='Only the GET method is allowed',
content_type='text/html')
self.assertContains(response, 'Only the GET method is allowed', status_code=405) self.assertContains(response, 'Only the GET method is allowed', status_code=405)
def test_not_allowed_repr(self): def test_not_allowed_repr(self):

View File

@ -70,24 +70,30 @@ class HumanizeTests(TestCase):
self.humanize_tester(test_list, result_list, 'ordinal', lambda x: x) self.humanize_tester(test_list, result_list, 'ordinal', lambda x: x)
def test_intcomma(self): def test_intcomma(self):
test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25, test_list = (
'100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'), 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000',
None) '10123', '10311', '1000000', '1234567.1234567',
result_list = ('100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', Decimal('1234567.1234567'), None,
'100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567', )
None) result_list = (
'100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
'100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567',
'1,234,567.1234567', None,
)
with translation.override('en'): with translation.override('en'):
self.humanize_tester(test_list, result_list, 'intcomma') self.humanize_tester(test_list, result_list, 'intcomma')
def test_l10n_intcomma(self): def test_l10n_intcomma(self):
test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25, test_list = (
'100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'), 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000',
None) '10123', '10311', '1000000', '1234567.1234567',
result_list = ('100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', Decimal('1234567.1234567'), None,
'100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567', )
None) result_list = (
'100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25',
'100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567',
'1,234,567.1234567', None,
)
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False): with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False):
with translation.override('en'): with translation.override('en'):
self.humanize_tester(test_list, result_list, 'intcomma') self.humanize_tester(test_list, result_list, 'intcomma')
@ -98,14 +104,16 @@ class HumanizeTests(TestCase):
self.humanize_tester([100], ['100'], 'intcomma') self.humanize_tester([100], ['100'], 'intcomma')
def test_intword(self): def test_intword(self):
test_list = ('100', '1000000', '1200000', '1290000', test_list = (
'1000000000', '2000000000', '6000000000000', '100', '1000000', '1200000', '1290000', '1000000000', '2000000000',
'1300000000000000', '3500000000000000000000', '6000000000000', '1300000000000000', '3500000000000000000000',
'8100000000000000000000000000000000', None) '8100000000000000000000000000000000', None,
result_list = ('100', '1.0 million', '1.2 million', '1.3 million', )
'1.0 billion', '2.0 billion', '6.0 trillion', result_list = (
'1.3 quadrillion', '3.5 sextillion', '100', '1.0 million', '1.2 million', '1.3 million', '1.0 billion',
'8.1 decillion', None) '2.0 billion', '6.0 trillion', '1.3 quadrillion', '3.5 sextillion',
'8.1 decillion', None,
)
with translation.override('en'): with translation.override('en'):
self.humanize_tester(test_list, result_list, 'intword') self.humanize_tester(test_list, result_list, 'intword')
@ -119,10 +127,14 @@ class HumanizeTests(TestCase):
self.humanize_tester(test_list, result_list, 'intcomma') self.humanize_tester(test_list, result_list, 'intcomma')
def test_i18n_intword(self): def test_i18n_intword(self):
test_list = ('100', '1000000', '1200000', '1290000', test_list = (
'1000000000', '2000000000', '6000000000000') '100', '1000000', '1200000', '1290000', '1000000000', '2000000000',
result_list = ('100', '1,0 Million', '1,2 Millionen', '1,3 Millionen', '6000000000000',
'1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen') )
result_list = (
'100', '1,0 Million', '1,2 Millionen', '1,3 Millionen',
'1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen',
)
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True):
with translation.override('de'): with translation.override('de'):
self.humanize_tester(test_list, result_list, 'intword') self.humanize_tester(test_list, result_list, 'intword')
@ -130,8 +142,7 @@ class HumanizeTests(TestCase):
def test_apnumber(self): def test_apnumber(self):
test_list = [str(x) for x in range(1, 11)] test_list = [str(x) for x in range(1, 11)]
test_list.append(None) test_list.append(None)
result_list = ('one', 'two', 'three', 'four', 'five', 'six', result_list = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', '10', None)
'seven', 'eight', 'nine', '10', None)
with translation.override('en'): with translation.override('en'):
self.humanize_tester(test_list, result_list, 'apnumber') self.humanize_tester(test_list, result_list, 'apnumber')

View File

@ -172,8 +172,7 @@ class CompilationErrorHandling(MessageCompilationTests):
# Make sure the output of msgfmt is unaffected by the current locale. # Make sure the output of msgfmt is unaffected by the current locale.
env = os.environ.copy() env = os.environ.copy()
env.update({'LANG': 'C'}) env.update({'LANG': 'C'})
with mock.patch('django.core.management.utils.Popen', with mock.patch('django.core.management.utils.Popen', lambda *args, **kwargs: Popen(*args, env=env, **kwargs)):
lambda *args, **kwargs: Popen(*args, env=env, **kwargs)):
if six.PY2: if six.PY2:
# Various assertRaises on PY2 don't support unicode error messages. # Various assertRaises on PY2 don't support unicode error messages.
try: try:

View File

@ -66,8 +66,7 @@ class ExtractorTests(SerializeMixin, SimpleTestCase):
def _run_makemessages(self, **options): def _run_makemessages(self, **options):
os.chdir(self.test_dir) os.chdir(self.test_dir)
out = StringIO() out = StringIO()
management.call_command('makemessages', locale=[LOCALE], verbosity=2, management.call_command('makemessages', locale=[LOCALE], verbosity=2, stdout=out, **options)
stdout=out, **options)
output = out.getvalue() output = out.getvalue()
self.assertTrue(os.path.exists(self.PO_FILE)) self.assertTrue(os.path.exists(self.PO_FILE))
with open(self.PO_FILE, 'r') as fp: with open(self.PO_FILE, 'r') as fp:
@ -776,10 +775,8 @@ class CustomLayoutExtractionTests(ExtractorTests):
* translations outside of that app are in LOCALE_PATHS[0] * translations outside of that app are in LOCALE_PATHS[0]
""" """
os.chdir(self.test_dir) os.chdir(self.test_dir)
self.addCleanup(shutil.rmtree, self.addCleanup(shutil.rmtree, os.path.join(settings.LOCALE_PATHS[0], LOCALE), True)
os.path.join(settings.LOCALE_PATHS[0], LOCALE), True) self.addCleanup(shutil.rmtree, os.path.join(self.test_dir, 'app_with_locale', 'locale', LOCALE), True)
self.addCleanup(shutil.rmtree,
os.path.join(self.test_dir, 'app_with_locale', 'locale', LOCALE), True)
management.call_command('makemessages', locale=[LOCALE], verbosity=0) management.call_command('makemessages', locale=[LOCALE], verbosity=0)
project_de_locale = os.path.join( project_de_locale = os.path.join(

View File

@ -708,8 +708,7 @@ class FormattingTests(SimpleTestCase):
# thousand separator and grouping when USE_L10N is False even # thousand separator and grouping when USE_L10N is False even
# if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and # if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and
# THOUSAND_SEPARATOR settings are specified # THOUSAND_SEPARATOR settings are specified
with self.settings(USE_THOUSAND_SEPARATOR=True, with self.settings(USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'):
NUMBER_GROUPING=1, THOUSAND_SEPARATOR='!'):
self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt)) self.assertEqual('66666.67', Template('{{ n|floatformat:2 }}').render(self.ctxt))
self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt)) self.assertEqual('100000.0', Template('{{ f|floatformat }}').render(self.ctxt))
@ -1527,8 +1526,11 @@ class ResolutionOrderI18NTests(SimpleTestCase):
def assertUgettext(self, msgid, msgstr): def assertUgettext(self, msgid, msgstr):
result = ugettext(msgid) result = ugettext(msgid)
self.assertIn(msgstr, result, ("The string '%s' isn't in the " self.assertIn(
"translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result))) msgstr, result,
"The string '%s' isn't in the translation of '%s'; the actual result is '%s'."
% (msgstr, msgid, result)
)
class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): class AppResolutionOrderI18NTests(ResolutionOrderI18NTests):

View File

@ -40,8 +40,7 @@ class SchemaIndexesTests(TestCase):
index_sql = connection.schema_editor()._model_indexes_sql(IndexTogetherSingleList) index_sql = connection.schema_editor()._model_indexes_sql(IndexTogetherSingleList)
self.assertEqual(len(index_sql), 1) self.assertEqual(len(index_sql), 1)
@skipUnless(connection.vendor == 'postgresql', @skipUnless(connection.vendor == 'postgresql', "This is a postgresql-specific issue")
"This is a postgresql-specific issue")
def test_postgresql_text_indexes(self): def test_postgresql_text_indexes(self):
"""Test creation of PostgreSQL-specific text indexes (#12234)""" """Test creation of PostgreSQL-specific text indexes (#12234)"""
from .models import IndexedArticle from .models import IndexedArticle
@ -53,8 +52,7 @@ class SchemaIndexesTests(TestCase):
# index (#19441). # index (#19441).
self.assertIn('("slug" varchar_pattern_ops)', index_sql[4]) self.assertIn('("slug" varchar_pattern_ops)', index_sql[4])
@skipUnless(connection.vendor == 'postgresql', @skipUnless(connection.vendor == 'postgresql', "This is a postgresql-specific issue")
"This is a postgresql-specific issue")
def test_postgresql_virtual_relation_indexes(self): def test_postgresql_virtual_relation_indexes(self):
"""Test indexes are not created for related objects""" """Test indexes are not created for related objects"""
index_sql = connection.schema_editor()._model_indexes_sql(Article) index_sql = connection.schema_editor()._model_indexes_sql(Article)

View File

@ -16,10 +16,8 @@ class IntrospectionTests(TransactionTestCase):
def test_table_names(self): def test_table_names(self):
tl = connection.introspection.table_names() tl = connection.introspection.table_names()
self.assertEqual(tl, sorted(tl)) self.assertEqual(tl, sorted(tl))
self.assertIn(Reporter._meta.db_table, tl, self.assertIn(Reporter._meta.db_table, tl, "'%s' isn't in table_list()." % Reporter._meta.db_table)
"'%s' isn't in table_list()." % Reporter._meta.db_table) self.assertIn(Article._meta.db_table, tl, "'%s' isn't in table_list()." % Article._meta.db_table)
self.assertIn(Article._meta.db_table, tl,
"'%s' isn't in table_list()." % Article._meta.db_table)
def test_django_table_names(self): def test_django_table_names(self):
with connection.cursor() as cursor: with connection.cursor() as cursor:
@ -48,10 +46,8 @@ class IntrospectionTests(TransactionTestCase):
else: else:
raise raise
self.assertIn('introspection_article_view', self.assertIn('introspection_article_view', connection.introspection.table_names(include_views=True))
connection.introspection.table_names(include_views=True)) self.assertNotIn('introspection_article_view', connection.introspection.table_names())
self.assertNotIn('introspection_article_view',
connection.introspection.table_names())
def test_unmanaged_through_model(self): def test_unmanaged_through_model(self):
tables = connection.introspection.django_table_names() tables = connection.introspection.django_table_names()
@ -65,8 +61,7 @@ class IntrospectionTests(TransactionTestCase):
def test_sequence_list(self): def test_sequence_list(self):
sequences = connection.introspection.sequence_list() sequences = connection.introspection.sequence_list()
expected = {'table': Reporter._meta.db_table, 'column': 'id'} expected = {'table': Reporter._meta.db_table, 'column': 'id'}
self.assertIn(expected, sequences, self.assertIn(expected, sequences, 'Reporter sequence not found in sequence_list()')
'Reporter sequence not found in sequence_list()')
def test_get_table_description_names(self): def test_get_table_description_names(self):
with connection.cursor() as cursor: with connection.cursor() as cursor:

View File

@ -267,8 +267,7 @@ class FieldNamesTests(SimpleTestCase):
max_column_name_length, column_limit_db_alias = get_max_column_name_length() max_column_name_length, column_limit_db_alias = get_max_column_name_length()
@unittest.skipIf(max_column_name_length is None, @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.")
"The database doesn't have a column name length limit.")
def test_M2M_long_column_name(self): def test_M2M_long_column_name(self):
""" """
#13711 -- Model check for long M2M column names when database has #13711 -- Model check for long M2M column names when database has
@ -333,8 +332,8 @@ class FieldNamesTests(SimpleTestCase):
'Autogenerated column name too long for M2M field "%s". ' 'Autogenerated column name too long for M2M field "%s". '
'Maximum length is "%s" for database "%s".' 'Maximum length is "%s" for database "%s".'
% (m2m_long_name, self.max_column_name_length, self.column_limit_db_alias), % (m2m_long_name, self.max_column_name_length, self.column_limit_db_alias),
hint=("Use 'through' to create a separate model for " hint="Use 'through' to create a separate model for "
"M2M and then set column_name using 'db_column'."), "M2M and then set column_name using 'db_column'.",
obj=ModelWithLongField, obj=ModelWithLongField,
id='models.E019', id='models.E019',
) )
@ -350,8 +349,8 @@ class FieldNamesTests(SimpleTestCase):
'Autogenerated column name too long for M2M field "%s_id". ' 'Autogenerated column name too long for M2M field "%s_id". '
'Maximum length is "%s" for database "%s".' 'Maximum length is "%s" for database "%s".'
% (long_field_name, self.max_column_name_length, self.column_limit_db_alias), % (long_field_name, self.max_column_name_length, self.column_limit_db_alias),
hint=("Use 'through' to create a separate model for " hint="Use 'through' to create a separate model for "
"M2M and then set column_name using 'db_column'."), "M2M and then set column_name using 'db_column'.",
obj=ModelWithLongField, obj=ModelWithLongField,
id='models.E019', id='models.E019',
) )
@ -359,8 +358,7 @@ class FieldNamesTests(SimpleTestCase):
self.assertEqual(errors, expected) self.assertEqual(errors, expected)
@unittest.skipIf(max_column_name_length is None, @unittest.skipIf(max_column_name_length is None, "The database doesn't have a column name length limit.")
"The database doesn't have a column name length limit.")
def test_local_field_long_column_name(self): def test_local_field_long_column_name(self):
""" """
#13711 -- Model check for long column names #13711 -- Model check for long column names
@ -724,10 +722,8 @@ class OtherModelTests(SimpleTestCase):
pass pass
class Group(models.Model): class Group(models.Model):
primary = models.ManyToManyField(Person, primary = models.ManyToManyField(Person, through="Membership", related_name="primary")
through="Membership", related_name="primary") secondary = models.ManyToManyField(Person, through="Membership", related_name="secondary")
secondary = models.ManyToManyField(Person, through="Membership",
related_name="secondary")
class Membership(models.Model): class Membership(models.Model):
person = models.ForeignKey(Person, models.CASCADE) person = models.ForeignKey(Person, models.CASCADE)

View File

@ -858,8 +858,7 @@ class AccessorClashTests(SimpleTestCase):
pass pass
class Model(models.Model): class Model(models.Model):
children = models.ManyToManyField('Child', children = models.ManyToManyField('Child', related_name="m2m_clash", related_query_name="no_clash")
related_name="m2m_clash", related_query_name="no_clash")
class Parent(models.Model): class Parent(models.Model):
m2m_clash = models.ManyToManyField('Target') m2m_clash = models.ManyToManyField('Target')
@ -1013,10 +1012,13 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase):
def test_fk_to_integer(self, related_name=None): def test_fk_to_integer(self, related_name=None):
self._test_explicit_related_query_name_clash( self._test_explicit_related_query_name_clash(
target=models.IntegerField(), target=models.IntegerField(),
relative=models.ForeignKey('Target', relative=models.ForeignKey(
'Target',
models.CASCADE, models.CASCADE,
related_name=related_name, related_name=related_name,
related_query_name='clash')) related_query_name='clash',
)
)
def test_hidden_fk_to_integer(self, related_name=None): def test_hidden_fk_to_integer(self, related_name=None):
self.test_fk_to_integer(related_name='+') self.test_fk_to_integer(related_name='+')
@ -1024,10 +1026,13 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase):
def test_fk_to_fk(self, related_name=None): def test_fk_to_fk(self, related_name=None):
self._test_explicit_related_query_name_clash( self._test_explicit_related_query_name_clash(
target=models.ForeignKey('Another', models.CASCADE), target=models.ForeignKey('Another', models.CASCADE),
relative=models.ForeignKey('Target', relative=models.ForeignKey(
'Target',
models.CASCADE, models.CASCADE,
related_name=related_name, related_name=related_name,
related_query_name='clash')) related_query_name='clash',
)
)
def test_hidden_fk_to_fk(self): def test_hidden_fk_to_fk(self):
self.test_fk_to_fk(related_name='+') self.test_fk_to_fk(related_name='+')
@ -1035,10 +1040,13 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase):
def test_fk_to_m2m(self, related_name=None): def test_fk_to_m2m(self, related_name=None):
self._test_explicit_related_query_name_clash( self._test_explicit_related_query_name_clash(
target=models.ManyToManyField('Another'), target=models.ManyToManyField('Another'),
relative=models.ForeignKey('Target', relative=models.ForeignKey(
'Target',
models.CASCADE, models.CASCADE,
related_name=related_name, related_name=related_name,
related_query_name='clash')) related_query_name='clash',
)
)
def test_hidden_fk_to_m2m(self): def test_hidden_fk_to_m2m(self):
self.test_fk_to_m2m(related_name='+') self.test_fk_to_m2m(related_name='+')
@ -1046,9 +1054,7 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase):
def test_m2m_to_integer(self, related_name=None): def test_m2m_to_integer(self, related_name=None):
self._test_explicit_related_query_name_clash( self._test_explicit_related_query_name_clash(
target=models.IntegerField(), target=models.IntegerField(),
relative=models.ManyToManyField('Target', relative=models.ManyToManyField('Target', related_name=related_name, related_query_name='clash'))
related_name=related_name,
related_query_name='clash'))
def test_hidden_m2m_to_integer(self): def test_hidden_m2m_to_integer(self):
self.test_m2m_to_integer(related_name='+') self.test_m2m_to_integer(related_name='+')
@ -1056,9 +1062,7 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase):
def test_m2m_to_fk(self, related_name=None): def test_m2m_to_fk(self, related_name=None):
self._test_explicit_related_query_name_clash( self._test_explicit_related_query_name_clash(
target=models.ForeignKey('Another', models.CASCADE), target=models.ForeignKey('Another', models.CASCADE),
relative=models.ManyToManyField('Target', relative=models.ManyToManyField('Target', related_name=related_name, related_query_name='clash'))
related_name=related_name,
related_query_name='clash'))
def test_hidden_m2m_to_fk(self): def test_hidden_m2m_to_fk(self):
self.test_m2m_to_fk(related_name='+') self.test_m2m_to_fk(related_name='+')
@ -1066,9 +1070,12 @@ class ExplicitRelatedQueryNameClashTests(SimpleTestCase):
def test_m2m_to_m2m(self, related_name=None): def test_m2m_to_m2m(self, related_name=None):
self._test_explicit_related_query_name_clash( self._test_explicit_related_query_name_clash(
target=models.ManyToManyField('Another'), target=models.ManyToManyField('Another'),
relative=models.ManyToManyField('Target', relative=models.ManyToManyField(
'Target',
related_name=related_name, related_name=related_name,
related_query_name='clash')) related_query_name='clash',
)
)
def test_hidden_m2m_to_m2m(self): def test_hidden_m2m_to_m2m(self):
self.test_m2m_to_m2m(related_name='+') self.test_m2m_to_m2m(related_name='+')

View File

@ -223,7 +223,8 @@ class AdminEmailHandlerTest(SimpleTestCase):
admin_email_handler.filters = [] admin_email_handler.filters = []
rf = RequestFactory() rf = RequestFactory()
request = rf.get('/') request = rf.get('/')
self.logger.error(message, token1, token2, self.logger.error(
message, token1, token2,
extra={ extra={
'status_code': 403, 'status_code': 403,
'request': request, 'request': request,

View File

@ -128,8 +128,7 @@ class M2MThroughSerializationTestCase(TestCase):
) )
out = StringIO() out = StringIO()
management.call_command("dumpdata", "m2m_through_regress", format="xml", management.call_command("dumpdata", "m2m_through_regress", format="xml", indent=2, stdout=out)
indent=2, stdout=out)
self.assertXMLEqual(out.getvalue().strip(), """ self.assertXMLEqual(out.getvalue().strip(), """
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0"> <django-objects version="1.0">

View File

@ -31,8 +31,10 @@ if PY3:
from email import message_from_bytes, message_from_binary_file from email import message_from_bytes, message_from_binary_file
else: else:
from email.Utils import parseaddr from email.Utils import parseaddr
from email import (message_from_string as message_from_bytes, from email import (
message_from_file as message_from_binary_file) message_from_string as message_from_bytes,
message_from_file as message_from_binary_file,
)
class HeadersCheckMixin(object): class HeadersCheckMixin(object):
@ -613,9 +615,10 @@ class BaseEmailBackendTests(HeadersCheckMixin, object):
def get_the_message(self): def get_the_message(self):
mailbox = self.get_mailbox_content() mailbox = self.get_mailbox_content()
self.assertEqual(len(mailbox), 1, self.assertEqual(
"Expected exactly one message, got %d.\n%r" % (len(mailbox), [ len(mailbox), 1,
m.as_string() for m in mailbox])) "Expected exactly one message, got %d.\n%r" % (len(mailbox), [m.as_string() for m in mailbox])
)
return mailbox[0] return mailbox[0]
def test_send(self): def test_send(self):
@ -769,8 +772,7 @@ class BaseEmailBackendTests(HeadersCheckMixin, object):
self.assertEqual(message.get('to'), 'to@xn--4ca9at.com') self.assertEqual(message.get('to'), 'to@xn--4ca9at.com')
self.flush_mailbox() self.flush_mailbox()
m = EmailMessage('Subject', 'Content', 'from@öäü.com', m = EmailMessage('Subject', 'Content', 'from@öäü.com', ['to@öäü.com'], cc=['cc@öäü.com'])
['to@öäü.com'], cc=['cc@öäü.com'])
m.send() m.send()
message = self.get_the_message() message = self.get_the_message()
self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('subject'), 'Subject')

View File

@ -34,10 +34,8 @@ class ManyToOneNullTests(TestCase):
def test_related_set(self): def test_related_set(self):
# Reporter objects have access to their related Article objects. # Reporter objects have access to their related Article objects.
self.assertQuerysetEqual(self.r.article_set.all(), self.assertQuerysetEqual(self.r.article_set.all(), ['<Article: First>', '<Article: Second>'])
['<Article: First>', '<Article: Second>']) self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='Fir'), ['<Article: First>'])
self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='Fir'),
['<Article: First>'])
self.assertEqual(self.r.article_set.count(), 2) self.assertEqual(self.r.article_set.count(), 2)
def test_created_without_related(self): def test_created_without_related(self):
@ -50,24 +48,21 @@ class ManyToOneNullTests(TestCase):
# if the reporter is set to None. # if the reporter is set to None.
self.assertEqual(a3.reporter, None) self.assertEqual(a3.reporter, None)
# To retrieve the articles with no reporters set, use "reporter__isnull=True". # To retrieve the articles with no reporters set, use "reporter__isnull=True".
self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['<Article: Third>'])
['<Article: Third>'])
# We can achieve the same thing by filtering for the case where the # We can achieve the same thing by filtering for the case where the
# reporter is None. # reporter is None.
self.assertQuerysetEqual(Article.objects.filter(reporter=None), self.assertQuerysetEqual(Article.objects.filter(reporter=None), ['<Article: Third>'])
['<Article: Third>'])
# Set the reporter for the Third article # Set the reporter for the Third article
self.assertQuerysetEqual(self.r.article_set.all(), self.assertQuerysetEqual(self.r.article_set.all(), ['<Article: First>', '<Article: Second>'])
['<Article: First>', '<Article: Second>'])
self.r.article_set.add(a3) self.r.article_set.add(a3)
self.assertQuerysetEqual(self.r.article_set.all(), self.assertQuerysetEqual(
['<Article: First>', '<Article: Second>', '<Article: Third>']) self.r.article_set.all(),
['<Article: First>', '<Article: Second>', '<Article: Third>']
)
# Remove an article from the set, and check that it was removed. # Remove an article from the set, and check that it was removed.
self.r.article_set.remove(a3) self.r.article_set.remove(a3)
self.assertQuerysetEqual(self.r.article_set.all(), self.assertQuerysetEqual(self.r.article_set.all(), ['<Article: First>', '<Article: Second>'])
['<Article: First>', '<Article: Second>']) self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['<Article: Third>'])
self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True),
['<Article: Third>'])
def test_remove_from_wrong_set(self): def test_remove_from_wrong_set(self):
self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>']) self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>'])
@ -80,30 +75,31 @@ class ManyToOneNullTests(TestCase):
# Use manager.set() to allocate ForeignKey. Null is legal, so existing # Use manager.set() to allocate ForeignKey. Null is legal, so existing
# members of the set that are not in the assignment set are set to null. # members of the set that are not in the assignment set are set to null.
self.r2.article_set.set([self.a2, self.a3]) self.r2.article_set.set([self.a2, self.a3])
self.assertQuerysetEqual(self.r2.article_set.all(), self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Second>', '<Article: Third>'])
['<Article: Second>', '<Article: Third>'])
# Use manager.set(clear=True) # Use manager.set(clear=True)
self.r2.article_set.set([self.a3, self.a4], clear=True) self.r2.article_set.set([self.a3, self.a4], clear=True)
self.assertQuerysetEqual(self.r2.article_set.all(), self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>', '<Article: Third>'])
['<Article: Fourth>', '<Article: Third>'])
# Clear the rest of the set # Clear the rest of the set
self.r2.article_set.set([]) self.r2.article_set.set([])
self.assertQuerysetEqual(self.r2.article_set.all(), []) self.assertQuerysetEqual(self.r2.article_set.all(), [])
self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), self.assertQuerysetEqual(
['<Article: Fourth>', '<Article: Second>', '<Article: Third>']) Article.objects.filter(reporter__isnull=True),
['<Article: Fourth>', '<Article: Second>', '<Article: Third>']
)
def test_assign_clear_related_set(self): def test_assign_clear_related_set(self):
# Use descriptor assignment to allocate ForeignKey. Null is legal, so # Use descriptor assignment to allocate ForeignKey. Null is legal, so
# existing members of the set that are not in the assignment set are # existing members of the set that are not in the assignment set are
# set to null. # set to null.
self.r2.article_set.set([self.a2, self.a3]) self.r2.article_set.set([self.a2, self.a3])
self.assertQuerysetEqual(self.r2.article_set.all(), self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Second>', '<Article: Third>'])
['<Article: Second>', '<Article: Third>'])
# Clear the rest of the set # Clear the rest of the set
self.r.article_set.clear() self.r.article_set.clear()
self.assertQuerysetEqual(self.r.article_set.all(), []) self.assertQuerysetEqual(self.r.article_set.all(), [])
self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), self.assertQuerysetEqual(
['<Article: First>', '<Article: Fourth>']) Article.objects.filter(reporter__isnull=True),
['<Article: First>', '<Article: Fourth>']
)
def test_assign_with_queryset(self): def test_assign_with_queryset(self):
# Ensure that querysets used in reverse FK assignments are pre-evaluated # Ensure that querysets used in reverse FK assignments are pre-evaluated

View File

@ -353,18 +353,14 @@ class BaseTests(object):
storage.level = 0 storage.level = 0
add_level_messages(storage) add_level_messages(storage)
tags = [msg.tags for msg in storage] tags = [msg.tags for msg in storage]
self.assertEqual(tags, self.assertEqual(tags, ['info', '', 'extra-tag debug', 'warning', 'error', 'success'])
['info', '', 'extra-tag debug', 'warning', 'error',
'success'])
def test_level_tag(self): def test_level_tag(self):
storage = self.get_storage() storage = self.get_storage()
storage.level = 0 storage.level = 0
add_level_messages(storage) add_level_messages(storage)
tags = [msg.level_tag for msg in storage] tags = [msg.level_tag for msg in storage]
self.assertEqual(tags, self.assertEqual(tags, ['info', '', 'debug', 'warning', 'error', 'success'])
['info', '', 'debug', 'warning', 'error',
'success'])
@override_settings_tags(MESSAGE_TAGS={ @override_settings_tags(MESSAGE_TAGS={
constants.INFO: 'info', constants.INFO: 'info',
@ -379,5 +375,4 @@ class BaseTests(object):
storage.level = 0 storage.level = 0
add_level_messages(storage) add_level_messages(storage)
tags = [msg.tags for msg in storage] tags = [msg.tags for msg in storage]
self.assertEqual(tags, self.assertEqual(tags, ['info', 'custom', 'extra-tag', '', 'bad', 'success'])
['info', 'custom', 'extra-tag', '', 'bad', 'success'])

View File

@ -127,9 +127,9 @@ class CookieTest(BaseTests, SimpleTestCase):
messages = [ messages = [
{ {
'message': Message(constants.INFO, 'Test message'), 'message': Message(constants.INFO, 'Test message'),
'message_list': [Message(constants.INFO, 'message %s') 'message_list': [
for x in range(5)] + [{'another-message': Message(constants.INFO, 'message %s') for x in range(5)
Message(constants.ERROR, 'error')}], ] + [{'another-message': Message(constants.ERROR, 'error')}],
}, },
Message(constants.INFO, 'message %s'), Message(constants.INFO, 'message %s'),
] ]

View File

@ -776,13 +776,17 @@ class ETagGZipMiddlewareTest(SimpleTestCase):
ETag is changed after gzip compression is performed. ETag is changed after gzip compression is performed.
""" """
request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate') request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate')
response = GZipMiddleware().process_response(request, response = GZipMiddleware().process_response(
CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))) request,
CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))
)
gzip_etag = response.get('ETag') gzip_etag = response.get('ETag')
request = self.rf.get('/', HTTP_ACCEPT_ENCODING='') request = self.rf.get('/', HTTP_ACCEPT_ENCODING='')
response = GZipMiddleware().process_response(request, response = GZipMiddleware().process_response(
CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))) request,
CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))
)
nogzip_etag = response.get('ETag') nogzip_etag = response.get('ETag')
self.assertNotEqual(gzip_etag, nogzip_etag) self.assertNotEqual(gzip_etag, nogzip_etag)

View File

@ -63,9 +63,10 @@ class MigrateSignalTests(TestCase):
def test_pre_migrate_args(self): def test_pre_migrate_args(self):
r = PreMigrateReceiver() r = PreMigrateReceiver()
signals.pre_migrate.connect(r, sender=APP_CONFIG) signals.pre_migrate.connect(r, sender=APP_CONFIG)
management.call_command('migrate', database=MIGRATE_DATABASE, management.call_command(
verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, 'migrate', database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY,
stdout=six.StringIO()) interactive=MIGRATE_INTERACTIVE, stdout=six.StringIO(),
)
args = r.call_args args = r.call_args
self.assertEqual(r.call_counter, 1) self.assertEqual(r.call_counter, 1)
@ -83,9 +84,10 @@ class MigrateSignalTests(TestCase):
r = PreMigrateReceiver() r = PreMigrateReceiver()
signals.pre_migrate.connect(r, sender=APP_CONFIG) signals.pre_migrate.connect(r, sender=APP_CONFIG)
stdout = six.StringIO() stdout = six.StringIO()
management.call_command('migrate', database=MIGRATE_DATABASE, management.call_command(
verbosity=MIGRATE_VERBOSITY, interactive=MIGRATE_INTERACTIVE, 'migrate', database=MIGRATE_DATABASE, verbosity=MIGRATE_VERBOSITY,
stdout=stdout) interactive=MIGRATE_INTERACTIVE, stdout=stdout,
)
args = r.call_args args = r.call_args
self.assertEqual(r.call_counter, 1) self.assertEqual(r.call_counter, 1)
self.assertEqual(set(args), set(PRE_MIGRATE_ARGS)) self.assertEqual(set(args), set(PRE_MIGRATE_ARGS))

View File

@ -1290,8 +1290,7 @@ class AutodetectorTests(TestCase):
# Right number/type of migrations? # Right number/type of migrations?
self.assertNumberMigrations(changes, 'testapp', 1) self.assertNumberMigrations(changes, 'testapp', 1)
self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"]) self.assertOperationTypes(changes, 'testapp', 0, ["CreateModel"])
self.assertOperationAttributes(changes, 'testapp', 0, 0, self.assertOperationAttributes(changes, 'testapp', 0, 0, name="AuthorUnmanaged", options={"managed": False})
name="AuthorUnmanaged", options={"managed": False})
def test_unmanaged_to_managed(self): def test_unmanaged_to_managed(self):
# Now, we test turning an unmanaged model into a managed model # Now, we test turning an unmanaged model into a managed model
@ -1302,8 +1301,7 @@ class AutodetectorTests(TestCase):
# Right number/type of migrations? # Right number/type of migrations?
self.assertNumberMigrations(changes, 'testapp', 1) self.assertNumberMigrations(changes, 'testapp', 1)
self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelOptions"]) self.assertOperationTypes(changes, 'testapp', 0, ["AlterModelOptions"])
self.assertOperationAttributes(changes, 'testapp', 0, 0, self.assertOperationAttributes(changes, 'testapp', 0, 0, name="authorunmanaged", options={})
name="authorunmanaged", options={})
def test_managed_to_unmanaged(self): def test_managed_to_unmanaged(self):
# Now, we turn managed to unmanaged. # Now, we turn managed to unmanaged.
@ -1314,8 +1312,7 @@ class AutodetectorTests(TestCase):
# Right number/type of migrations? # Right number/type of migrations?
self.assertNumberMigrations(changes, 'testapp', 1) self.assertNumberMigrations(changes, 'testapp', 1)
self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"])
self.assertOperationAttributes(changes, "testapp", 0, 0, self.assertOperationAttributes(changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False})
name="authorunmanaged", options={"managed": False})
def test_unmanaged_custom_pk(self): def test_unmanaged_custom_pk(self):
""" """

View File

@ -338,16 +338,26 @@ class MigrateTests(MigrationTestBase):
index_tx_end = output.find(connection.ops.end_transaction_sql().lower()) index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
self.assertGreater(index_tx_start, -1, "Transaction start not found") self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(index_op_desc_author, index_tx_start, self.assertGreater(
"Operation description (author) not found or found before transaction start") index_op_desc_author, index_tx_start,
self.assertGreater(index_create_table, index_op_desc_author, "Operation description (author) not found or found before transaction start"
"CREATE TABLE not found or found before operation description (author)") )
self.assertGreater(index_op_desc_tribble, index_create_table, self.assertGreater(
"Operation description (tribble) not found or found before CREATE TABLE (author)") index_create_table, index_op_desc_author,
self.assertGreater(index_op_desc_unique_together, index_op_desc_tribble, "CREATE TABLE not found or found before operation description (author)"
"Operation description (unique_together) not found or found before operation description (tribble)") )
self.assertGreater(index_tx_end, index_op_desc_unique_together, self.assertGreater(
"Transaction end not found or found before operation description (unique_together)") index_op_desc_tribble, index_create_table,
"Operation description (tribble) not found or found before CREATE TABLE (author)"
)
self.assertGreater(
index_op_desc_unique_together, index_op_desc_tribble,
"Operation description (unique_together) not found or found before operation description (tribble)"
)
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before operation description (unique_together)"
)
@override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
def test_sqlmigrate_backwards(self): def test_sqlmigrate_backwards(self):
@ -369,17 +379,27 @@ class MigrateTests(MigrationTestBase):
index_tx_end = output.find(connection.ops.end_transaction_sql().lower()) index_tx_end = output.find(connection.ops.end_transaction_sql().lower())
self.assertGreater(index_tx_start, -1, "Transaction start not found") self.assertGreater(index_tx_start, -1, "Transaction start not found")
self.assertGreater(index_op_desc_unique_together, index_tx_start, self.assertGreater(
"Operation description (unique_together) not found or found before transaction start") index_op_desc_unique_together, index_tx_start,
self.assertGreater(index_op_desc_tribble, index_op_desc_unique_together, "Operation description (unique_together) not found or found before transaction start"
"Operation description (tribble) not found or found before operation description (unique_together)") )
self.assertGreater(index_op_desc_author, index_op_desc_tribble, self.assertGreater(
"Operation description (author) not found or found before operation description (tribble)") index_op_desc_tribble, index_op_desc_unique_together,
"Operation description (tribble) not found or found before operation description (unique_together)"
)
self.assertGreater(
index_op_desc_author, index_op_desc_tribble,
"Operation description (author) not found or found before operation description (tribble)"
)
self.assertGreater(index_drop_table, index_op_desc_author, self.assertGreater(
"DROP TABLE not found or found before operation description (author)") index_drop_table, index_op_desc_author,
self.assertGreater(index_tx_end, index_op_desc_unique_together, "DROP TABLE not found or found before operation description (author)"
"Transaction end not found or found before DROP TABLE") )
self.assertGreater(
index_tx_end, index_op_desc_unique_together,
"Transaction end not found or found before DROP TABLE"
)
# Cleanup by unmigrating everything # Cleanup by unmigrating everything
call_command("migrate", "migrations", "zero", verbosity=0) call_command("migrate", "migrations", "zero", verbosity=0)

View File

@ -46,7 +46,8 @@ class OperationTestBase(MigrationTestBase):
operation.state_forwards(app_label, new_state) operation.state_forwards(app_label, new_state)
return project_state, new_state return project_state, new_state
def set_up_test_model(self, app_label, second_model=False, third_model=False, def set_up_test_model(
self, app_label, second_model=False, third_model=False,
related_model=False, mti_model=False, proxy_model=False, manager_model=False, related_model=False, mti_model=False, proxy_model=False, manager_model=False,
unique_together=False, options=False, db_table=None, index_together=False): unique_together=False, options=False, db_table=None, index_together=False):
""" """

View File

@ -817,23 +817,26 @@ class ModelStateTests(SimpleTestCase):
def test_bound_field_sanity_check(self): def test_bound_field_sanity_check(self):
field = models.CharField(max_length=1) field = models.CharField(max_length=1)
field.model = models.Model field.model = models.Model
with self.assertRaisesMessage(ValueError, with self.assertRaisesMessage(ValueError, 'ModelState.fields cannot be bound to a model - "field" is.'):
'ModelState.fields cannot be bound to a model - "field" is.'):
ModelState('app', 'Model', [('field', field)]) ModelState('app', 'Model', [('field', field)])
def test_sanity_check_to(self): def test_sanity_check_to(self):
field = models.ForeignKey(UnicodeModel, models.CASCADE) field = models.ForeignKey(UnicodeModel, models.CASCADE)
with self.assertRaisesMessage(ValueError, with self.assertRaisesMessage(
'ModelState.fields cannot refer to a model class - "field.to" does. ' ValueError,
'Use a string reference instead.'): 'ModelState.fields cannot refer to a model class - "field.to" does. '
'Use a string reference instead.'
):
ModelState('app', 'Model', [('field', field)]) ModelState('app', 'Model', [('field', field)])
def test_sanity_check_through(self): def test_sanity_check_through(self):
field = models.ManyToManyField('UnicodeModel') field = models.ManyToManyField('UnicodeModel')
field.remote_field.through = UnicodeModel field.remote_field.through = UnicodeModel
with self.assertRaisesMessage(ValueError, with self.assertRaisesMessage(
'ModelState.fields cannot refer to a model class - "field.through" does. ' ValueError,
'Use a string reference instead.'): 'ModelState.fields cannot refer to a model class - "field.through" does. '
'Use a string reference instead.'
):
ModelState('app', 'Model', [('field', field)]) ModelState('app', 'Model', [('field', field)])
def test_fields_immutability(self): def test_fields_immutability(self):

View File

@ -103,8 +103,7 @@ class FieldFlagsTests(test.SimpleTestCase):
def test_each_object_should_have_auto_created(self): def test_each_object_should_have_auto_created(self):
self.assertTrue( self.assertTrue(
all(f.auto_created.__class__ == bool all(f.auto_created.__class__ == bool for f in self.fields_and_reverse_objects)
for f in self.fields_and_reverse_objects)
) )
def test_non_concrete_fields(self): def test_non_concrete_fields(self):

View File

@ -17,8 +17,10 @@ except ImproperlyConfigured:
Image = None Image = None
if Image: if Image:
from .models import (Person, PersonWithHeight, PersonWithHeightAndWidth, from .models import (
PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile) Person, PersonWithHeight, PersonWithHeightAndWidth,
PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile,
)
from .models import temp_storage_dir from .models import temp_storage_dir
else: else:
# Pillow not available, create dummy classes (tests will be skipped anyway) # Pillow not available, create dummy classes (tests will be skipped anyway)

View File

@ -388,13 +388,16 @@ class ColourfulItem(models.Model):
class CustomErrorMessage(models.Model): class CustomErrorMessage(models.Model):
name1 = models.CharField(max_length=50, name1 = models.CharField(
max_length=50,
validators=[validators.validate_slug], validators=[validators.validate_slug],
error_messages={'invalid': 'Model custom error message.'}) error_messages={'invalid': 'Model custom error message.'},
)
name2 = models.CharField(max_length=50, name2 = models.CharField(
max_length=50,
validators=[validators.validate_slug], validators=[validators.validate_slug],
error_messages={'invalid': 'Model custom error message.'}) error_messages={'invalid': 'Model custom error message.'},
)
def clean(self): def clean(self):
if self.name1 == 'FORBIDDEN_VALUE': if self.name1 == 'FORBIDDEN_VALUE':

View File

@ -328,8 +328,7 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
fields = '__all__' fields = '__all__'
self.assertIsInstance(ReplaceField.base_fields['url'], self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField)
forms.fields.BooleanField)
def test_replace_field_variant_2(self): def test_replace_field_variant_2(self):
# Should have the same result as before, # Should have the same result as before,
@ -341,8 +340,7 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
fields = ['url'] fields = ['url']
self.assertIsInstance(ReplaceField.base_fields['url'], self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField)
forms.fields.BooleanField)
def test_replace_field_variant_3(self): def test_replace_field_variant_3(self):
# Should have the same result as before, # Should have the same result as before,
@ -354,8 +352,7 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
fields = [] # url will still appear, since it is explicit above fields = [] # url will still appear, since it is explicit above
self.assertIsInstance(ReplaceField.base_fields['url'], self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField)
forms.fields.BooleanField)
def test_override_field(self): def test_override_field(self):
class WriterForm(forms.ModelForm): class WriterForm(forms.ModelForm):
@ -390,8 +387,7 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
exclude = ['url'] exclude = ['url']
self.assertEqual(list(ExcludeFields.base_fields), self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug'])
['name', 'slug'])
def test_exclude_nonexistent_field(self): def test_exclude_nonexistent_field(self):
class ExcludeFields(forms.ModelForm): class ExcludeFields(forms.ModelForm):
@ -399,8 +395,7 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
exclude = ['nonexistent'] exclude = ['nonexistent']
self.assertEqual(list(ExcludeFields.base_fields), self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug', 'url'])
['name', 'slug', 'url'])
def test_exclude_fields_with_string(self): def test_exclude_fields_with_string(self):
expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?" expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?"
@ -811,8 +806,10 @@ class UniqueTest(TestCase):
self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.'])
def test_unique_for_date(self): def test_unique_for_date(self):
p = Post.objects.create(title="Django 1.0 is released", p = Post.objects.create(
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) title="Django 1.0 is released", slug="Django 1.0",
subtitle="Finally", posted=datetime.date(2008, 9, 3),
)
form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1) self.assertEqual(len(form.errors), 1)
@ -828,8 +825,8 @@ class UniqueTest(TestCase):
form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.'])
form = PostForm({'subtitle': "Finally", "title": "Django 1.0 is released", data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'}
"slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) form = PostForm(data, instance=p)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form = PostForm({'title': "Django 1.0 is released"}) form = PostForm({'title': "Django 1.0 is released"})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
@ -847,9 +844,10 @@ class UniqueTest(TestCase):
model = DateTimePost model = DateTimePost
fields = '__all__' fields = '__all__'
DateTimePost.objects.create(title="Django 1.0 is released", DateTimePost.objects.create(
slug="Django 1.0", subtitle="Finally", title="Django 1.0 is released", slug="Django 1.0",
posted=datetime.datetime(2008, 9, 3, 10, 10, 1)) subtitle="Finally", posted=datetime.datetime(2008, 9, 3, 10, 10, 1),
)
# 'title' has unique_for_date='posted' # 'title' has unique_for_date='posted'
form = DateTimePostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) form = DateTimePostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
@ -861,8 +859,10 @@ class UniqueTest(TestCase):
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
def test_inherited_unique_for_date(self): def test_inherited_unique_for_date(self):
p = Post.objects.create(title="Django 1.0 is released", p = Post.objects.create(
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) title="Django 1.0 is released", slug="Django 1.0",
subtitle="Finally", posted=datetime.date(2008, 9, 3),
)
form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1) self.assertEqual(len(form.errors), 1)
@ -878,8 +878,8 @@ class UniqueTest(TestCase):
form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.'])
form = DerivedPostForm({'subtitle': "Finally", "title": "Django 1.0 is released", data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'}
"slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p) form = DerivedPostForm(data, instance=p)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
def test_unique_for_date_with_nullable_date(self): def test_unique_for_date_with_nullable_date(self):
@ -888,8 +888,10 @@ class UniqueTest(TestCase):
model = FlexibleDatePost model = FlexibleDatePost
fields = '__all__' fields = '__all__'
p = FlexibleDatePost.objects.create(title="Django 1.0 is released", p = FlexibleDatePost.objects.create(
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) title="Django 1.0 is released", slug="Django 1.0",
subtitle="Finally", posted=datetime.date(2008, 9, 3),
)
form = FlexDatePostForm({'title': "Django 1.0 is released"}) form = FlexDatePostForm({'title': "Django 1.0 is released"})
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
@ -897,8 +899,8 @@ class UniqueTest(TestCase):
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form = FlexDatePostForm({'subtitle': "Finally"}) form = FlexDatePostForm({'subtitle': "Finally"})
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
form = FlexDatePostForm({'subtitle': "Finally", "title": "Django 1.0 is released", data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0"}
"slug": "Django 1.0"}, instance=p) form = FlexDatePostForm(data, instance=p)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
def test_override_unique_message(self): def test_override_unique_message(self):
@ -941,8 +943,10 @@ class UniqueTest(TestCase):
} }
} }
Post.objects.create(title="Django 1.0 is released", Post.objects.create(
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) title="Django 1.0 is released", slug="Django 1.0",
subtitle="Finally", posted=datetime.date(2008, 9, 3),
)
form = CustomPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) form = CustomPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
self.assertEqual(len(form.errors), 1) self.assertEqual(len(form.errors), 1)
self.assertEqual(form.errors['title'], ["Post's Title not unique for Posted date."]) self.assertEqual(form.errors['title'], ["Post's Title not unique for Posted date."])
@ -1343,8 +1347,7 @@ class ModelFormBasicTests(TestCase):
new_art = f.save() new_art = f.save()
new_art = Article.objects.get(id=new_art.id) new_art = Article.objects.get(id=new_art.id)
art_id_1 = new_art.id art_id_1 = new_art.id
self.assertQuerysetEqual(new_art.categories.order_by('name'), self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"])
["Entertainment", "It's a test"])
# Now, submit form data with no categories. This deletes the existing categories. # Now, submit form data with no categories. This deletes the existing categories.
form_data['categories'] = [] form_data['categories'] = []
@ -1379,8 +1382,7 @@ class ModelFormBasicTests(TestCase):
# Save the m2m data on the form # Save the m2m data on the form
f.save_m2m() f.save_m2m()
self.assertQuerysetEqual(new_art.categories.order_by('name'), self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"])
["Entertainment", "It's a test"])
def test_custom_form_fields(self): def test_custom_form_fields(self):
# Here, we define a custom ModelForm. Because it happens to have the same fields as # Here, we define a custom ModelForm. Because it happens to have the same fields as
@ -1594,12 +1596,18 @@ class ModelMultipleChoiceFieldTests(TestCase):
self.assertQuerysetEqual(f.clean([self.c1.id]), ["Entertainment"]) self.assertQuerysetEqual(f.clean([self.c1.id]), ["Entertainment"])
self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"])
self.assertQuerysetEqual(f.clean([str(self.c1.id)]), ["Entertainment"]) self.assertQuerysetEqual(f.clean([str(self.c1.id)]), ["Entertainment"])
self.assertQuerysetEqual(f.clean([str(self.c1.id), str(self.c2.id)]), self.assertQuerysetEqual(
["Entertainment", "It's a test"], ordered=False) f.clean([str(self.c1.id), str(self.c2.id)]),
self.assertQuerysetEqual(f.clean([self.c1.id, str(self.c2.id)]), ["Entertainment", "It's a test"], ordered=False
["Entertainment", "It's a test"], ordered=False) )
self.assertQuerysetEqual(f.clean((self.c1.id, str(self.c2.id))), self.assertQuerysetEqual(
["Entertainment", "It's a test"], ordered=False) f.clean([self.c1.id, str(self.c2.id)]),
["Entertainment", "It's a test"], ordered=False
)
self.assertQuerysetEqual(
f.clean((self.c1.id, str(self.c2.id))),
["Entertainment", "It's a test"], ordered=False
)
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
f.clean(['100']) f.clean(['100'])
with self.assertRaises(ValidationError): with self.assertRaises(ValidationError):
@ -1827,8 +1835,7 @@ class ModelOneToOneFieldTests(TestCase):
model = Author model = Author
fields = ['publication', 'full_name'] fields = ['publication', 'full_name']
publication = Publication.objects.create(title="Pravda", publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22))
date_published=datetime.date(1991, 8, 22))
author = Author.objects.create(publication=publication, full_name='John Doe') author = Author.objects.create(publication=publication, full_name='John Doe')
form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
@ -1845,8 +1852,7 @@ class ModelOneToOneFieldTests(TestCase):
model = Author1 model = Author1
fields = ['publication', 'full_name'] fields = ['publication', 'full_name']
publication = Publication.objects.create(title="Pravda", publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22))
date_published=datetime.date(1991, 8, 22))
author = Author1.objects.create(publication=publication, full_name='John Doe') author = Author1.objects.create(publication=publication, full_name='John Doe')
form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author)
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())

View File

@ -1506,8 +1506,7 @@ class ModelFormsetTest(TestCase):
} }
formset = FormSet(data) formset = FormSet(data)
self.assertFalse(formset.is_valid()) self.assertFalse(formset.is_valid())
self.assertEqual(formset._non_form_errors, self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for slug.'])
['Please correct the duplicate data for slug.'])
FormSet = modelformset_factory(Price, fields="__all__", extra=2) FormSet = modelformset_factory(Price, fields="__all__", extra=2)
data = { data = {
@ -1521,8 +1520,10 @@ class ModelFormsetTest(TestCase):
} }
formset = FormSet(data) formset = FormSet(data)
self.assertFalse(formset.is_valid()) self.assertFalse(formset.is_valid())
self.assertEqual(formset._non_form_errors, self.assertEqual(
['Please correct the duplicate data for price and quantity, which must be unique.']) formset._non_form_errors,
['Please correct the duplicate data for price and quantity, which must be unique.']
)
# Only the price field is specified, this should skip any unique checks since # Only the price field is specified, this should skip any unique checks since
# the unique_together is not fulfilled. This will fail with a KeyError if broken. # the unique_together is not fulfilled. This will fail with a KeyError if broken.
@ -1559,10 +1560,8 @@ class ModelFormsetTest(TestCase):
} }
formset = FormSet(data=data, instance=author) formset = FormSet(data=data, instance=author)
self.assertFalse(formset.is_valid()) self.assertFalse(formset.is_valid())
self.assertEqual(formset._non_form_errors, self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for title.'])
['Please correct the duplicate data for title.']) self.assertEqual(formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}])
self.assertEqual(formset.errors,
[{}, {'__all__': ['Please correct the duplicate values below.']}])
FormSet = modelformset_factory(Post, fields="__all__", extra=2) FormSet = modelformset_factory(Post, fields="__all__", extra=2)
data = { data = {
@ -1581,10 +1580,14 @@ class ModelFormsetTest(TestCase):
} }
formset = FormSet(data) formset = FormSet(data)
self.assertFalse(formset.is_valid()) self.assertFalse(formset.is_valid())
self.assertEqual(formset._non_form_errors, self.assertEqual(
['Please correct the duplicate data for title which must be unique for the date in posted.']) formset._non_form_errors,
self.assertEqual(formset.errors, ['Please correct the duplicate data for title which must be unique for the date in posted.']
[{}, {'__all__': ['Please correct the duplicate values below.']}]) )
self.assertEqual(
formset.errors,
[{}, {'__all__': ['Please correct the duplicate values below.']}]
)
data = { data = {
'form-TOTAL_FORMS': '2', 'form-TOTAL_FORMS': '2',
@ -1602,8 +1605,10 @@ class ModelFormsetTest(TestCase):
} }
formset = FormSet(data) formset = FormSet(data)
self.assertFalse(formset.is_valid()) self.assertFalse(formset.is_valid())
self.assertEqual(formset._non_form_errors, self.assertEqual(
['Please correct the duplicate data for slug which must be unique for the year in posted.']) formset._non_form_errors,
['Please correct the duplicate data for slug which must be unique for the year in posted.']
)
data = { data = {
'form-TOTAL_FORMS': '2', 'form-TOTAL_FORMS': '2',
@ -1621,8 +1626,10 @@ class ModelFormsetTest(TestCase):
} }
formset = FormSet(data) formset = FormSet(data)
self.assertFalse(formset.is_valid()) self.assertFalse(formset.is_valid())
self.assertEqual(formset._non_form_errors, self.assertEqual(
['Please correct the duplicate data for subtitle which must be unique for the month in posted.']) formset._non_form_errors,
['Please correct the duplicate data for subtitle which must be unique for the month in posted.']
)
class TestModelFormsetOverridesTroughFormMeta(TestCase): class TestModelFormsetOverridesTroughFormMeta(TestCase):

View File

@ -336,10 +336,8 @@ class ModelInheritanceDataTests(TestCase):
#23370 - Should be able to defer child fields when using #23370 - Should be able to defer child fields when using
select_related() from parent to child. select_related() from parent to child.
""" """
qs = (Restaurant.objects qs = (Restaurant.objects.select_related("italianrestaurant")
.select_related("italianrestaurant") .defer("italianrestaurant__serves_gnocchi").order_by("rating"))
.defer("italianrestaurant__serves_gnocchi")
.order_by("rating"))
# Test that the field was actually deferred # Test that the field was actually deferred
with self.assertNumQueries(2): with self.assertNumQueries(2):

View File

@ -43,8 +43,7 @@ class TablespacesTests(TestCase):
def assertNumContains(self, haystack, needle, count): def assertNumContains(self, haystack, needle, count):
real_count = haystack.count(needle) real_count = haystack.count(needle)
self.assertEqual(real_count, count, "Found %d instances of '%s', " self.assertEqual(real_count, count, "Found %d instances of '%s', expected %d" % (real_count, needle, count))
"expected %d" % (real_count, needle, count))
@skipUnlessDBFeature('supports_tablespaces') @skipUnlessDBFeature('supports_tablespaces')
def test_tablespace_for_model(self): def test_tablespace_for_model(self):

View File

@ -19,8 +19,7 @@ class Band(models.Model):
class Concert(models.Model): class Concert(models.Model):
main_band = models.ForeignKey(Band, models.CASCADE, related_name='main_concerts') main_band = models.ForeignKey(Band, models.CASCADE, related_name='main_concerts')
opening_band = models.ForeignKey(Band, models.CASCADE, related_name='opening_concerts', opening_band = models.ForeignKey(Band, models.CASCADE, related_name='opening_concerts', blank=True)
blank=True)
day = models.CharField(max_length=3, choices=((1, 'Fri'), (2, 'Sat'))) day = models.CharField(max_length=3, choices=((1, 'Fri'), (2, 'Sat')))
transport = models.CharField(max_length=100, choices=( transport = models.CharField(max_length=100, choices=(
(1, 'Plane'), (1, 'Plane'),

View File

@ -47,14 +47,9 @@ class ModelAdminTests(TestCase):
def test_default_fields(self): def test_default_fields(self):
ma = ModelAdmin(Band, self.site) ma = ModelAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date'])
['name', 'bio', 'sign_date']) self.assertEqual(list(ma.get_fields(request)), ['name', 'bio', 'sign_date'])
self.assertEqual(list(ma.get_fields(request, self.band)), ['name', 'bio', 'sign_date'])
self.assertEqual(list(ma.get_fields(request)),
['name', 'bio', 'sign_date'])
self.assertEqual(list(ma.get_fields(request, self.band)),
['name', 'bio', 'sign_date'])
def test_default_fieldsets(self): def test_default_fieldsets(self):
# fieldsets_add and fieldsets_change should return a special data structure that # fieldsets_add and fieldsets_change should return a special data structure that
@ -64,11 +59,9 @@ class ModelAdminTests(TestCase):
# Here's the default case. There are no custom form_add/form_change methods, # Here's the default case. There are no custom form_add/form_change methods,
# no fields argument, and no fieldsets argument. # no fields argument, and no fieldsets argument.
ma = ModelAdmin(Band, self.site) ma = ModelAdmin(Band, self.site)
self.assertEqual(ma.get_fieldsets(request), self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name', 'bio', 'sign_date']})])
[(None, {'fields': ['name', 'bio', 'sign_date']})])
self.assertEqual(ma.get_fieldsets(request, self.band), self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name', 'bio', 'sign_date']})])
[(None, {'fields': ['name', 'bio', 'sign_date']})])
def test_get_fieldsets(self): def test_get_fieldsets(self):
# Test that get_fieldsets is called when figuring out form fields. # Test that get_fieldsets is called when figuring out form fields.
@ -115,14 +108,9 @@ class ModelAdminTests(TestCase):
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_fields(request)), ['name']) self.assertEqual(list(ma.get_fields(request)), ['name'])
self.assertEqual(list(ma.get_fields(request, self.band)), ['name']) self.assertEqual(list(ma.get_fields(request, self.band)), ['name'])
self.assertEqual(ma.get_fieldsets(request), [(None, {'fields': ['name']})])
self.assertEqual(ma.get_fieldsets(request), self.assertEqual(ma.get_fieldsets(request, self.band), [(None, {'fields': ['name']})])
[(None, {'fields': ['name']})])
self.assertEqual(ma.get_fieldsets(request, self.band),
[(None, {'fields': ['name']})])
def test_field_arguments_restricted_on_form(self): def test_field_arguments_restricted_on_form(self):
# If we specify fields or fieldsets, it should exclude fields on the Form class # If we specify fields or fieldsets, it should exclude fields on the Form class
@ -137,8 +125,7 @@ class ModelAdminTests(TestCase):
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), ['name']) self.assertEqual(list(ma.get_form(request).base_fields), ['name'])
self.assertEqual(list(ma.get_form(request, self.band).base_fields), self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name'])
['name'])
# Using `fieldsets`. # Using `fieldsets`.
class BandAdmin(ModelAdmin): class BandAdmin(ModelAdmin):
@ -146,24 +133,21 @@ class ModelAdminTests(TestCase):
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), ['name']) self.assertEqual(list(ma.get_form(request).base_fields), ['name'])
self.assertEqual(list(ma.get_form(request, self.band).base_fields), self.assertEqual(list(ma.get_form(request, self.band).base_fields), ['name'])
['name'])
# Using `exclude`. # Using `exclude`.
class BandAdmin(ModelAdmin): class BandAdmin(ModelAdmin):
exclude = ['bio'] exclude = ['bio']
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date'])
['name', 'sign_date'])
# You can also pass a tuple to `exclude`. # You can also pass a tuple to `exclude`.
class BandAdmin(ModelAdmin): class BandAdmin(ModelAdmin):
exclude = ('bio',) exclude = ('bio',)
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date'])
['name', 'sign_date'])
# Using `fields` and `exclude`. # Using `fields` and `exclude`.
class BandAdmin(ModelAdmin): class BandAdmin(ModelAdmin):
@ -171,8 +155,7 @@ class ModelAdminTests(TestCase):
exclude = ['bio'] exclude = ['bio']
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['name'])
['name'])
def test_custom_form_meta_exclude_with_readonly(self): def test_custom_form_meta_exclude_with_readonly(self):
""" """
@ -184,7 +167,6 @@ class ModelAdminTests(TestCase):
# First, with `ModelAdmin` ----------------------- # First, with `ModelAdmin` -----------------------
class AdminBandForm(forms.ModelForm): class AdminBandForm(forms.ModelForm):
class Meta: class Meta:
model = Band model = Band
exclude = ['bio'] exclude = ['bio']
@ -194,13 +176,11 @@ class ModelAdminTests(TestCase):
form = AdminBandForm form = AdminBandForm
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['sign_date'])
['sign_date'])
# Then, with `InlineModelAdmin` ----------------- # Then, with `InlineModelAdmin` -----------------
class AdminConcertForm(forms.ModelForm): class AdminConcertForm(forms.ModelForm):
class Meta: class Meta:
model = Concert model = Concert
exclude = ['day'] exclude = ['day']
@ -261,7 +241,6 @@ class ModelAdminTests(TestCase):
# First, with `ModelAdmin` ----------------------- # First, with `ModelAdmin` -----------------------
class AdminBandForm(forms.ModelForm): class AdminBandForm(forms.ModelForm):
class Meta: class Meta:
model = Band model = Band
exclude = ['bio'] exclude = ['bio']
@ -271,8 +250,7 @@ class ModelAdminTests(TestCase):
form = AdminBandForm form = AdminBandForm
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['bio', 'sign_date'])
['bio', 'sign_date'])
# Then, with `InlineModelAdmin` ----------------- # Then, with `InlineModelAdmin` -----------------
@ -296,7 +274,8 @@ class ModelAdminTests(TestCase):
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual( self.assertEqual(
list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
['main_band', 'opening_band', 'day', 'id', 'DELETE']) ['main_band', 'opening_band', 'day', 'id', 'DELETE']
)
def test_custom_form_validation(self): def test_custom_form_validation(self):
# If we specify a form, it should use it allowing custom validation to work # If we specify a form, it should use it allowing custom validation to work
@ -309,12 +288,8 @@ class ModelAdminTests(TestCase):
form = AdminBandForm form = AdminBandForm
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'bio', 'sign_date', 'delete'])
['name', 'bio', 'sign_date', 'delete']) self.assertEqual(type(ma.get_form(request).base_fields['sign_date'].widget), AdminDateWidget)
self.assertEqual(
type(ma.get_form(request).base_fields['sign_date'].widget),
AdminDateWidget)
def test_form_exclude_kwarg_override(self): def test_form_exclude_kwarg_override(self):
""" """
@ -323,7 +298,6 @@ class ModelAdminTests(TestCase):
""" """
class AdminBandForm(forms.ModelForm): class AdminBandForm(forms.ModelForm):
class Meta: class Meta:
model = Band model = Band
exclude = ['name'] exclude = ['name']
@ -337,8 +311,7 @@ class ModelAdminTests(TestCase):
return super(BandAdmin, self).get_form(request, obj, **kwargs) return super(BandAdmin, self).get_form(request, obj, **kwargs)
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['name', 'sign_date'])
['name', 'sign_date'])
def test_formset_exclude_kwarg_override(self): def test_formset_exclude_kwarg_override(self):
""" """
@ -347,7 +320,6 @@ class ModelAdminTests(TestCase):
""" """
class AdminConcertForm(forms.ModelForm): class AdminConcertForm(forms.ModelForm):
class Meta: class Meta:
model = Concert model = Concert
exclude = ['day'] exclude = ['day']
@ -384,13 +356,15 @@ class ModelAdminTests(TestCase):
ma = ConcertAdmin(Concert, self.site) ma = ConcertAdmin(Concert, self.site)
form = ma.get_form(request)() form = ma.get_form(request)()
self.assertHTMLEqual(str(form["main_band"]), self.assertHTMLEqual(
str(form["main_band"]),
'<div class="related-widget-wrapper">' '<div class="related-widget-wrapper">'
'<select name="main_band" id="id_main_band">' '<select name="main_band" id="id_main_band">'
'<option value="" selected="selected">---------</option>' '<option value="" selected="selected">---------</option>'
'<option value="%d">The Beatles</option>' '<option value="%d">The Beatles</option>'
'<option value="%d">The Doors</option>' '<option value="%d">The Doors</option>'
'</select></div>' % (band2.id, self.band.id)) '</select></div>' % (band2.id, self.band.id)
)
class AdminConcertForm(forms.ModelForm): class AdminConcertForm(forms.ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -403,12 +377,14 @@ class ModelAdminTests(TestCase):
ma = ConcertAdminWithForm(Concert, self.site) ma = ConcertAdminWithForm(Concert, self.site)
form = ma.get_form(request)() form = ma.get_form(request)()
self.assertHTMLEqual(str(form["main_band"]), self.assertHTMLEqual(
str(form["main_band"]),
'<div class="related-widget-wrapper">' '<div class="related-widget-wrapper">'
'<select name="main_band" id="id_main_band">' '<select name="main_band" id="id_main_band">'
'<option value="" selected="selected">---------</option>' '<option value="" selected="selected">---------</option>'
'<option value="%d">The Doors</option>' '<option value="%d">The Doors</option>'
'</select></div>' % self.band.id) '</select></div>' % self.band.id
)
def test_regression_for_ticket_15820(self): def test_regression_for_ticket_15820(self):
""" """
@ -455,24 +431,22 @@ class ModelAdminTests(TestCase):
cma = ModelAdmin(Concert, self.site) cma = ModelAdmin(Concert, self.site)
cmafa = cma.get_form(request) cmafa = cma.get_form(request)
self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), Select)
Select)
self.assertEqual( self.assertEqual(
list(cmafa.base_fields['main_band'].widget.choices), list(cmafa.base_fields['main_band'].widget.choices),
[('', '---------'), (self.band.id, 'The Doors')]) [('', '---------'), (self.band.id, 'The Doors')])
self.assertEqual( self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), Select)
type(cmafa.base_fields['opening_band'].widget.widget), Select)
self.assertEqual( self.assertEqual(
list(cmafa.base_fields['opening_band'].widget.choices), list(cmafa.base_fields['opening_band'].widget.choices),
[('', '---------'), (self.band.id, 'The Doors')]) [('', '---------'), (self.band.id, 'The Doors')]
)
self.assertEqual(type(cmafa.base_fields['day'].widget), Select) self.assertEqual(type(cmafa.base_fields['day'].widget), Select)
self.assertEqual(list(cmafa.base_fields['day'].widget.choices), self.assertEqual(
[('', '---------'), (1, 'Fri'), (2, 'Sat')]) list(cmafa.base_fields['day'].widget.choices),
[('', '---------'), (1, 'Fri'), (2, 'Sat')]
self.assertEqual(type(cmafa.base_fields['transport'].widget), )
Select) self.assertEqual(type(cmafa.base_fields['transport'].widget), Select)
self.assertEqual( self.assertEqual(
list(cmafa.base_fields['transport'].widget.choices), list(cmafa.base_fields['transport'].widget.choices),
[('', '---------'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]) [('', '---------'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')])
@ -494,35 +468,29 @@ class ModelAdminTests(TestCase):
cma = ConcertAdmin(Concert, self.site) cma = ConcertAdmin(Concert, self.site)
cmafa = cma.get_form(request) cmafa = cma.get_form(request)
self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget), AdminRadioSelect)
AdminRadioSelect) self.assertEqual(cmafa.base_fields['main_band'].widget.attrs, {'class': 'radiolist inline'})
self.assertEqual(cmafa.base_fields['main_band'].widget.attrs,
{'class': 'radiolist inline'})
self.assertEqual(list(cmafa.base_fields['main_band'].widget.choices),
[(self.band.id, 'The Doors')])
self.assertEqual( self.assertEqual(
type(cmafa.base_fields['opening_band'].widget.widget), list(cmafa.base_fields['main_band'].widget.choices),
AdminRadioSelect) [(self.band.id, 'The Doors')]
self.assertEqual(cmafa.base_fields['opening_band'].widget.attrs, )
{'class': 'radiolist'})
self.assertEqual(type(cmafa.base_fields['opening_band'].widget.widget), AdminRadioSelect)
self.assertEqual(cmafa.base_fields['opening_band'].widget.attrs, {'class': 'radiolist'})
self.assertEqual( self.assertEqual(
list(cmafa.base_fields['opening_band'].widget.choices), list(cmafa.base_fields['opening_band'].widget.choices),
[('', 'None'), (self.band.id, 'The Doors')]) [('', 'None'), (self.band.id, 'The Doors')]
)
self.assertEqual(type(cmafa.base_fields['day'].widget), AdminRadioSelect)
self.assertEqual(cmafa.base_fields['day'].widget.attrs, {'class': 'radiolist'})
self.assertEqual(list(cmafa.base_fields['day'].widget.choices), [(1, 'Fri'), (2, 'Sat')])
self.assertEqual(type(cmafa.base_fields['day'].widget), self.assertEqual(type(cmafa.base_fields['transport'].widget), AdminRadioSelect)
AdminRadioSelect) self.assertEqual(cmafa.base_fields['transport'].widget.attrs, {'class': 'radiolist inline'})
self.assertEqual(cmafa.base_fields['day'].widget.attrs, self.assertEqual(
{'class': 'radiolist'}) list(cmafa.base_fields['transport'].widget.choices),
self.assertEqual(list(cmafa.base_fields['day'].widget.choices), [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')]
[(1, 'Fri'), (2, 'Sat')]) )
self.assertEqual(type(cmafa.base_fields['transport'].widget),
AdminRadioSelect)
self.assertEqual(cmafa.base_fields['transport'].widget.attrs,
{'class': 'radiolist inline'})
self.assertEqual(list(cmafa.base_fields['transport'].widget.choices),
[('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')])
class AdminConcertForm(forms.ModelForm): class AdminConcertForm(forms.ModelForm):
class Meta: class Meta:
@ -533,8 +501,7 @@ class ModelAdminTests(TestCase):
form = AdminConcertForm form = AdminConcertForm
ma = ConcertAdmin(Concert, self.site) ma = ConcertAdmin(Concert, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['main_band', 'opening_band', 'day'])
['main_band', 'opening_band', 'day'])
class AdminConcertForm(forms.ModelForm): class AdminConcertForm(forms.ModelForm):
extra = forms.CharField() extra = forms.CharField()
@ -547,8 +514,7 @@ class ModelAdminTests(TestCase):
form = AdminConcertForm form = AdminConcertForm
ma = ConcertAdmin(Concert, self.site) ma = ConcertAdmin(Concert, self.site)
self.assertEqual(list(ma.get_form(request).base_fields), self.assertEqual(list(ma.get_form(request).base_fields), ['extra', 'transport'])
['extra', 'transport'])
class ConcertInline(TabularInline): class ConcertInline(TabularInline):
form = AdminConcertForm form = AdminConcertForm
@ -564,13 +530,13 @@ class ModelAdminTests(TestCase):
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
self.assertEqual( self.assertEqual(
list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields), list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
['extra', 'transport', 'id', 'DELETE', 'main_band']) ['extra', 'transport', 'id', 'DELETE', 'main_band']
)
class CheckTestCase(SimpleTestCase): class CheckTestCase(SimpleTestCase):
def assertIsInvalid(self, model_admin, model, msg, def assertIsInvalid(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None):
id=None, hint=None, invalid_obj=None):
invalid_obj = invalid_obj or model_admin invalid_obj = invalid_obj or model_admin
admin_obj = model_admin(model, AdminSite()) admin_obj = model_admin(model, AdminSite())
errors = admin_obj.check() errors = admin_obj.check()
@ -584,8 +550,7 @@ class CheckTestCase(SimpleTestCase):
] ]
self.assertEqual(errors, expected) self.assertEqual(errors, expected)
def assertIsInvalidRegexp(self, model_admin, model, msg, def assertIsInvalidRegexp(self, model_admin, model, msg, id=None, hint=None, invalid_obj=None):
id=None, hint=None, invalid_obj=None):
""" """
Same as assertIsInvalid but treats the given msg as a regexp. Same as assertIsInvalid but treats the given msg as a regexp.
""" """

View File

@ -33,8 +33,7 @@ class QueryTestCase(TestCase):
def test_default_creation(self): def test_default_creation(self):
"Objects created on the default database don't leak onto other databases" "Objects created on the default database don't leak onto other databases"
# Create a book on the default database using create() # Create a book on the default database using create()
Book.objects.create(title="Pro Django", Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
published=datetime.date(2008, 12, 16))
# Create a book on the default database using a save # Create a book on the default database using a save
dive = Book() dive = Book()
@ -114,8 +113,7 @@ class QueryTestCase(TestCase):
def test_basic_queries(self): def test_basic_queries(self):
"Queries are constrained to a single database" "Queries are constrained to a single database"
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4)) dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4))
self.assertEqual(dive.title, "Dive into Python") self.assertEqual(dive.title, "Dive into Python")
@ -157,8 +155,7 @@ class QueryTestCase(TestCase):
marty = Person.objects.create(name="Marty Alchin") marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
@ -195,18 +192,14 @@ class QueryTestCase(TestCase):
mark = Person.objects.using('other').get(name="Mark Pilgrim") mark = Person.objects.using('other').get(name="Mark Pilgrim")
# Retrieve related object by descriptor. Related objects should be database-bound # Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(dive.authors.all().values_list('name', flat=True)), self.assertEqual(list(dive.authors.all().values_list('name', flat=True)), ['Mark Pilgrim'])
['Mark Pilgrim'])
self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)), self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)), ['Dive into Python'])
['Dive into Python'])
def test_m2m_forward_operations(self): def test_m2m_forward_operations(self):
"M2M forward manipulations are all constrained to a single DB" "M2M forward manipulations are all constrained to a single DB"
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations # Save the author relations
@ -265,17 +258,14 @@ class QueryTestCase(TestCase):
def test_m2m_reverse_operations(self): def test_m2m_reverse_operations(self):
"M2M reverse manipulations are all constrained to a single DB" "M2M reverse manipulations are all constrained to a single DB"
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Save the author relations # Save the author relations
dive.authors.set([mark]) dive.authors.set([mark])
# Create a second book on the other database # Create a second book on the other database
grease = Book.objects.using('other').create(title="Greasemonkey Hacks", grease = Book.objects.using('other').create(title="Greasemonkey Hacks", published=datetime.date(2005, 11, 1))
published=datetime.date(2005, 11, 1))
# Add a books to the m2m # Add a books to the m2m
mark.book_set.add(grease) mark.book_set.add(grease)
@ -330,14 +320,12 @@ class QueryTestCase(TestCase):
def test_m2m_cross_database_protection(self): def test_m2m_cross_database_protection(self):
"Operations that involve sharing M2M objects across databases raise an error" "Operations that involve sharing M2M objects across databases raise an error"
# Create a book and author on the default database # Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin") marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
# Set a foreign key set with an object from a different database # Set a foreign key set with an object from a different database
@ -368,9 +356,7 @@ class QueryTestCase(TestCase):
def test_m2m_deletion(self): def test_m2m_deletion(self):
"Cascaded deletions of m2m relations issue queries on the right database" "Cascaded deletions of m2m relations issue queries on the right database"
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
dive.authors.set([mark]) dive.authors.set([mark])
@ -398,8 +384,7 @@ class QueryTestCase(TestCase):
self.assertEqual(Book.authors.through.objects.using('other').count(), 0) self.assertEqual(Book.authors.through.objects.using('other').count(), 0)
# Now try deletion in the reverse direction. Set up the relation again # Now try deletion in the reverse direction. Set up the relation again
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
dive.authors.set([mark]) dive.authors.set([mark])
# Check the initial state # Check the initial state
@ -428,15 +413,12 @@ class QueryTestCase(TestCase):
def test_foreign_key_separation(self): def test_foreign_key_separation(self):
"FK fields are constrained to a single database" "FK fields are constrained to a single database"
# Create a book and author on the default database # Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
published=datetime.date(2008, 12, 16))
george = Person.objects.create(name="George Vilches") george = Person.objects.create(name="George Vilches")
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
chris = Person.objects.using('other').create(name="Chris Mills") chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author's favorite books # Save the author's favorite books
@ -480,14 +462,11 @@ class QueryTestCase(TestCase):
dive = Book.objects.using('other').get(title="Dive into Python") dive = Book.objects.using('other').get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be database-bound # Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(chris.edited.values_list('title', flat=True)), self.assertEqual(list(chris.edited.values_list('title', flat=True)), ['Dive into Python'])
['Dive into Python'])
def test_foreign_key_reverse_operations(self): def test_foreign_key_reverse_operations(self):
"FK reverse manipulations are all constrained to a single DB" "FK reverse manipulations are all constrained to a single DB"
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
chris = Person.objects.using('other').create(name="Chris Mills") chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author relations # Save the author relations
@ -559,14 +538,11 @@ class QueryTestCase(TestCase):
def test_foreign_key_cross_database_protection(self): def test_foreign_key_cross_database_protection(self):
"Operations that involve sharing FK objects across databases raise an error" "Operations that involve sharing FK objects across databases raise an error"
# Create a book and author on the default database # Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin") marty = Person.objects.create(name="Marty Alchin")
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
# Set a foreign key with an object from a different database # Set a foreign key with an object from a different database
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@ -701,23 +677,20 @@ class QueryTestCase(TestCase):
self.assertEqual(charlie._state.db, 'other') self.assertEqual(charlie._state.db, 'other')
# ... but it isn't saved yet # ... but it isn't saved yet
self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), ['bob'])
['bob']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), ['crunchy frog'])
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog'])
# When saved (no using required), new objects goes to 'other' # When saved (no using required), new objects goes to 'other'
charlie.save() charlie.save()
bob_profile.save() bob_profile.save()
new_bob_profile.save() new_bob_profile.save()
self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)), self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)), ['alice'])
['alice']) self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), ['bob', 'charlie'])
self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate'])
['bob', 'charlie']) self.assertEqual(
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['chocolate']) ['crunchy frog', 'spring surprise']
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), )
['crunchy frog', 'spring surprise'])
# This also works if you assign the O2O relation in the constructor # This also works if you assign the O2O relation in the constructor
denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com') denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com')
@ -725,29 +698,28 @@ class QueryTestCase(TestCase):
self.assertEqual(denise_profile._state.db, 'other') self.assertEqual(denise_profile._state.db, 'other')
# ... but it isn't saved yet # ... but it isn't saved yet
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate'])
['chocolate']) self.assertEqual(
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise']) ['crunchy frog', 'spring surprise']
)
# When saved, the new profile goes to 'other' # When saved, the new profile goes to 'other'
denise_profile.save() denise_profile.save()
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), ['chocolate'])
['chocolate']) self.assertEqual(
self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), list(UserProfile.objects.using('other').values_list('flavor', flat=True)),
['crunchy frog', 'spring surprise', 'tofu']) ['crunchy frog', 'spring surprise', 'tofu']
)
def test_generic_key_separation(self): def test_generic_key_separation(self):
"Generic fields are constrained to a single database" "Generic fields are constrained to a single database"
# Create a book and author on the default database # Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source="Python Monthly", content_object=pro) review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
@ -761,17 +733,12 @@ class QueryTestCase(TestCase):
dive = Book.objects.using('other').get(title="Dive into Python") dive = Book.objects.using('other').get(title="Dive into Python")
# Retrieve related object by descriptor. Related objects should be database-bound # Retrieve related object by descriptor. Related objects should be database-bound
self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)), self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)), ['Python Weekly'])
['Python Weekly'])
def test_generic_key_reverse_operations(self): def test_generic_key_reverse_operations(self):
"Generic reverse manipulations are all constrained to a single DB" "Generic reverse manipulations are all constrained to a single DB"
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4)) temp = Book.objects.using('other').create(title="Temp", published=datetime.date(2009, 5, 4))
temp = Book.objects.using('other').create(title="Temp",
published=datetime.date(2009, 5, 4))
review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) review1 = Review.objects.using('other').create(source="Python Weekly", content_object=dive)
review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp) review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp)
@ -831,14 +798,11 @@ class QueryTestCase(TestCase):
def test_generic_key_cross_database_protection(self): def test_generic_key_cross_database_protection(self):
"Operations that involve sharing generic key objects across databases raise an error" "Operations that involve sharing generic key objects across databases raise an error"
# Create a book and author on the default database # Create a book and author on the default database
pro = Book.objects.create(title="Pro Django", pro = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
published=datetime.date(2008, 12, 16))
review1 = Review.objects.create(source="Python Monthly", content_object=pro) review1 = Review.objects.create(source="Python Monthly", content_object=pro)
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source="Python Weekly", content_object=dive) Review.objects.using('other').create(source="Python Weekly", content_object=dive)
@ -884,8 +848,7 @@ class QueryTestCase(TestCase):
def test_generic_key_deletion(self): def test_generic_key_deletion(self):
"Cascaded deletions of Generic Key relations issue queries on the right database" "Cascaded deletions of Generic Key relations issue queries on the right database"
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
Review.objects.using('other').create(source="Python Weekly", content_object=dive) Review.objects.using('other').create(source="Python Weekly", content_object=dive)
# Check the initial state # Check the initial state
@ -907,22 +870,16 @@ class QueryTestCase(TestCase):
def test_ordering(self): def test_ordering(self):
"get_next_by_XXX commands stick to a single database" "get_next_by_XXX commands stick to a single database"
Book.objects.create(title="Pro Django", Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16))
published=datetime.date(2008, 12, 16)) dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
learn = Book.objects.using('other').create(title="Learning Python", published=datetime.date(2008, 7, 16))
dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4))
learn = Book.objects.using('other').create(title="Learning Python",
published=datetime.date(2008, 7, 16))
self.assertEqual(learn.get_next_by_published().title, "Dive into Python") self.assertEqual(learn.get_next_by_published().title, "Dive into Python")
self.assertEqual(dive.get_previous_by_published().title, "Learning Python") self.assertEqual(dive.get_previous_by_published().title, "Learning Python")
def test_raw(self): def test_raw(self):
"test the raw() method across databases" "test the raw() method across databases"
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book') val = Book.objects.db_manager("other").raw('SELECT id FROM multiple_database_book')
self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk")) self.assertQuerysetEqual(val, [dive.pk], attrgetter("pk"))
@ -933,9 +890,11 @@ class QueryTestCase(TestCase):
"Database assignment is retained if an object is retrieved with select_related()" "Database assignment is retained if an object is retrieved with select_related()"
# Create a book and author on the other database # Create a book and author on the other database
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
Book.objects.using('other').create(title="Dive into Python", Book.objects.using('other').create(
published=datetime.date(2009, 5, 4), title="Dive into Python",
editor=mark) published=datetime.date(2009, 5, 4),
editor=mark,
)
# Retrieve the Person using select_related() # Retrieve the Person using select_related()
book = Book.objects.using('other').select_related('editor').get(title="Dive into Python") book = Book.objects.using('other').select_related('editor').get(title="Dive into Python")
@ -966,21 +925,10 @@ class QueryTestCase(TestCase):
# extra_arg is removed by the BookManager's implementation of # extra_arg is removed by the BookManager's implementation of
# create(); but the BookManager's implementation won't get called # create(); but the BookManager's implementation won't get called
# unless edited returns a Manager, not a queryset # unless edited returns a Manager, not a queryset
mark.book_set.create(title="Dive into Python", mark.book_set.create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True)
published=datetime.date(2009, 5, 4), mark.book_set.get_or_create(title="Dive into Python", published=datetime.date(2009, 5, 4), extra_arg=True)
extra_arg=True) mark.edited.create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True)
mark.edited.get_or_create(title="Dive into Water", published=datetime.date(2009, 5, 4), extra_arg=True)
mark.book_set.get_or_create(title="Dive into Python",
published=datetime.date(2009, 5, 4),
extra_arg=True)
mark.edited.create(title="Dive into Water",
published=datetime.date(2009, 5, 4),
extra_arg=True)
mark.edited.get_or_create(title="Dive into Water",
published=datetime.date(2009, 5, 4),
extra_arg=True)
class ConnectionRouterTestCase(SimpleTestCase): class ConnectionRouterTestCase(SimpleTestCase):
@ -989,21 +937,18 @@ class ConnectionRouterTestCase(SimpleTestCase):
'multiple_database.tests.WriteRouter']) 'multiple_database.tests.WriteRouter'])
def test_router_init_default(self): def test_router_init_default(self):
connection_router = ConnectionRouter() connection_router = ConnectionRouter()
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter'])
['TestRouter', 'WriteRouter'])
def test_router_init_arg(self): def test_router_init_arg(self):
connection_router = ConnectionRouter([ connection_router = ConnectionRouter([
'multiple_database.tests.TestRouter', 'multiple_database.tests.TestRouter',
'multiple_database.tests.WriteRouter' 'multiple_database.tests.WriteRouter'
]) ])
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter'])
['TestRouter', 'WriteRouter'])
# Init with instances instead of strings # Init with instances instead of strings
connection_router = ConnectionRouter([TestRouter(), WriteRouter()]) connection_router = ConnectionRouter([TestRouter(), WriteRouter()])
self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], self.assertListEqual([r.__class__.__name__ for r in connection_router.routers], ['TestRouter', 'WriteRouter'])
['TestRouter', 'WriteRouter'])
# Make the 'other' database appear to be a replica of the 'default' # Make the 'other' database appear to be a replica of the 'default'
@ -1085,8 +1030,7 @@ class RouterTestCase(TestCase):
pro.authors.set([marty]) pro.authors.set([marty])
# Create a book and author on the other database # Create a book and author on the other database
Book.objects.using('other').create(title="Dive into Python", Book.objects.using('other').create(title="Dive into Python", published=datetime.date(2009, 5, 4))
published=datetime.date(2009, 5, 4))
# An update query will be routed to the default database # An update query will be routed to the default database
Book.objects.filter(title='Pro Django').update(pages=200) Book.objects.filter(title='Pro Django').update(pages=200)

View File

@ -37,9 +37,11 @@ class PaginationTests(unittest.TestCase):
got = getattr(paginator, name) got = getattr(paginator, name)
if coerce is not None: if coerce is not None:
got = coerce(got) got = coerce(got)
self.assertEqual(expected, got, self.assertEqual(
expected, got,
"For '%s', expected %s but got %s. Paginator parameters were: %s" "For '%s', expected %s but got %s. Paginator parameters were: %s"
% (name, expected, got, params)) % (name, expected, got, params)
)
def test_paginator(self): def test_paginator(self):
""" """
@ -156,12 +158,9 @@ class PaginationTests(unittest.TestCase):
page_num = paginator.num_pages page_num = paginator.num_pages
page = paginator.page(page_num) page = paginator.page(page_num)
start, end = indexes start, end = indexes
msg = ("For %s of page %s, expected %s but got %s." msg = ("For %s of page %s, expected %s but got %s. Paginator parameters were: %s")
" Paginator parameters were: %s") self.assertEqual(start, page.start_index(), msg % ('start index', page_num, start, page.start_index(), params))
self.assertEqual(start, page.start_index(), self.assertEqual(end, page.end_index(), msg % ('end index', page_num, end, page.end_index(), params))
msg % ('start index', page_num, start, page.start_index(), params))
self.assertEqual(end, page.end_index(),
msg % ('end index', page_num, end, page.end_index(), params))
def test_page_indexes(self): def test_page_indexes(self):
""" """

View File

@ -295,9 +295,11 @@ class TestSerialization(PostgreSQLTestCase):
upper_dt = datetime.datetime(2014, 2, 2, 12, 12, 12, tzinfo=timezone.utc) upper_dt = datetime.datetime(2014, 2, 2, 12, 12, 12, tzinfo=timezone.utc)
def test_dumping(self): def test_dumping(self):
instance = RangesModel(ints=NumericRange(0, 10), floats=NumericRange(empty=True), instance = RangesModel(
ints=NumericRange(0, 10), floats=NumericRange(empty=True),
timestamps=DateTimeTZRange(self.lower_dt, self.upper_dt), timestamps=DateTimeTZRange(self.lower_dt, self.upper_dt),
dates=DateRange(self.lower_date, self.upper_date)) dates=DateRange(self.lower_date, self.upper_date),
)
data = serializers.serialize('json', [instance]) data = serializers.serialize('json', [instance])
dumped = json.loads(data) dumped = json.loads(data)
for field in ('ints', 'dates', 'timestamps'): for field in ('ints', 'dates', 'timestamps'):

View File

@ -135,8 +135,7 @@ class PrefetchRelatedTests(TestCase):
lists = [[[six.text_type(r) for r in b.read_by.all()] lists = [[[six.text_type(r) for r in b.read_by.all()]
for b in a.books.all()] for b in a.books.all()]
for a in qs] for a in qs]
self.assertEqual(lists, self.assertEqual(lists, [
[
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems [["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy"], []], # Emily - Poems, Wuthering Heights
@ -149,8 +148,7 @@ class PrefetchRelatedTests(TestCase):
lists = [[[six.text_type(r) for r in b.read_by.all()] lists = [[[six.text_type(r) for r in b.read_by.all()]
for b in a.books.all()] for b in a.books.all()]
for a in qs] for a in qs]
self.assertEqual(lists, self.assertEqual(lists, [
[
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems [["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy"], []], # Emily - Poems, Wuthering Heights
@ -161,8 +159,7 @@ class PrefetchRelatedTests(TestCase):
lists = [[[six.text_type(r) for r in b.read_by.all()] lists = [[[six.text_type(r) for r in b.read_by.all()]
for b in a.books.all()] for b in a.books.all()]
for a in qs] for a in qs]
self.assertEqual(lists, self.assertEqual(lists, [
[
[["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre [["Amy"], ["Belinda"]], # Charlotte - Poems, Jane Eyre
[["Amy"]], # Anne - Poems [["Amy"]], # Anne - Poems
[["Amy"], []], # Emily - Poems, Wuthering Heights [["Amy"], []], # Emily - Poems, Wuthering Heights
@ -176,8 +173,7 @@ class PrefetchRelatedTests(TestCase):
# Need a double # Need a double
with self.assertNumQueries(3): with self.assertNumQueries(3):
author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte") author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte")
lists = [[six.text_type(r) for r in b.read_by.all()] lists = [[six.text_type(r) for r in b.read_by.all()] for b in author.books.all()]
for b in author.books.all()]
self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre
def test_foreign_key_then_m2m(self): def test_foreign_key_then_m2m(self):
@ -189,10 +185,7 @@ class PrefetchRelatedTests(TestCase):
qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by') qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by')
lists = [[six.text_type(r) for r in a.first_book.read_by.all()] lists = [[six.text_type(r) for r in a.first_book.read_by.all()]
for a in qs] for a in qs]
self.assertEqual(lists, [["Amy"], self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]])
["Amy"],
["Amy"],
["Amy", "Belinda"]])
def test_reverse_one_to_one_then_m2m(self): def test_reverse_one_to_one_then_m2m(self):
""" """
@ -907,8 +900,7 @@ class MultiTableInheritanceTest(TestCase):
def test_foreignkey(self): def test_foreignkey(self):
with self.assertNumQueries(2): with self.assertNumQueries(2):
qs = AuthorWithAge.objects.prefetch_related('addresses') qs = AuthorWithAge.objects.prefetch_related('addresses')
addresses = [[six.text_type(address) for address in obj.addresses.all()] addresses = [[six.text_type(address) for address in obj.addresses.all()] for obj in qs]
for obj in qs]
self.assertEqual(addresses, [[six.text_type(self.author_address)], [], []]) self.assertEqual(addresses, [[six.text_type(self.author_address)], [], []])
def test_foreignkey_to_inherited(self): def test_foreignkey_to_inherited(self):
@ -920,20 +912,16 @@ class MultiTableInheritanceTest(TestCase):
def test_m2m_to_inheriting_model(self): def test_m2m_to_inheriting_model(self):
qs = AuthorWithAge.objects.prefetch_related('books_with_year') qs = AuthorWithAge.objects.prefetch_related('books_with_year')
with self.assertNumQueries(2): with self.assertNumQueries(2):
lst = [[six.text_type(book) for book in author.books_with_year.all()] lst = [[six.text_type(book) for book in author.books_with_year.all()] for author in qs]
for author in qs]
qs = AuthorWithAge.objects.all() qs = AuthorWithAge.objects.all()
lst2 = [[six.text_type(book) for book in author.books_with_year.all()] lst2 = [[six.text_type(book) for book in author.books_with_year.all()] for author in qs]
for author in qs]
self.assertEqual(lst, lst2) self.assertEqual(lst, lst2)
qs = BookWithYear.objects.prefetch_related('aged_authors') qs = BookWithYear.objects.prefetch_related('aged_authors')
with self.assertNumQueries(2): with self.assertNumQueries(2):
lst = [[six.text_type(author) for author in book.aged_authors.all()] lst = [[six.text_type(author) for author in book.aged_authors.all()] for book in qs]
for book in qs]
qs = BookWithYear.objects.all() qs = BookWithYear.objects.all()
lst2 = [[six.text_type(author) for author in book.aged_authors.all()] lst2 = [[six.text_type(author) for author in book.aged_authors.all()] for book in qs]
for book in qs]
self.assertEqual(lst, lst2) self.assertEqual(lst, lst2)
def test_parent_link_prefetch(self): def test_parent_link_prefetch(self):
@ -1248,14 +1236,10 @@ class Ticket21410Tests(TestCase):
self.book3 = Book.objects.create(title="Wuthering Heights") self.book3 = Book.objects.create(title="Wuthering Heights")
self.book4 = Book.objects.create(title="Sense and Sensibility") self.book4 = Book.objects.create(title="Sense and Sensibility")
self.author1 = Author2.objects.create(name="Charlotte", self.author1 = Author2.objects.create(name="Charlotte", first_book=self.book1)
first_book=self.book1) self.author2 = Author2.objects.create(name="Anne", first_book=self.book1)
self.author2 = Author2.objects.create(name="Anne", self.author3 = Author2.objects.create(name="Emily", first_book=self.book1)
first_book=self.book1) self.author4 = Author2.objects.create(name="Jane", first_book=self.book4)
self.author3 = Author2.objects.create(name="Emily",
first_book=self.book1)
self.author4 = Author2.objects.create(name="Jane",
first_book=self.book4)
self.author1.favorite_books.add(self.book1, self.book2, self.book3) self.author1.favorite_books.add(self.book1, self.book2, self.book3)
self.author2.favorite_books.add(self.book1) self.author2.favorite_books.add(self.book1)

View File

@ -8,9 +8,11 @@ from django.utils import six
from django.utils._os import upath from django.utils._os import upath
@unittest.skipIf(six.PY2, @unittest.skipIf(
six.PY2,
'Python 2 cannot import the project template because ' 'Python 2 cannot import the project template because '
'django/conf/project_template doesn\'t have an __init__.py file.') 'django/conf/project_template doesn\'t have an __init__.py file.'
)
class TestStartProjectSettings(TestCase): class TestStartProjectSettings(TestCase):
def setUp(self): def setUp(self):
# Ensure settings.py exists # Ensure settings.py exists

View File

@ -295,8 +295,7 @@ class ProxyModelTests(TestCase):
resp = [s.name for s in StateProxy.objects.select_related()] resp = [s.name for s in StateProxy.objects.select_related()]
self.assertEqual(resp, ['New South Wales']) self.assertEqual(resp, ['New South Wales'])
self.assertEqual(StateProxy.objects.get(name='New South Wales').name, self.assertEqual(StateProxy.objects.get(name='New South Wales').name, 'New South Wales')
'New South Wales')
resp = StateProxy.objects.select_related().get(name='New South Wales') resp = StateProxy.objects.select_related().get(name='New South Wales')
self.assertEqual(resp.name, 'New South Wales') self.assertEqual(resp.name, 'New South Wales')
@ -317,16 +316,15 @@ class ProxyModelTests(TestCase):
) )
def test_proxy_bug(self): def test_proxy_bug(self):
contributor = ProxyTrackerUser.objects.create(name='Contributor', contributor = ProxyTrackerUser.objects.create(name='Contributor', status='contrib')
status='contrib')
someone = BaseUser.objects.create(name='Someone') someone = BaseUser.objects.create(name='Someone')
Bug.objects.create(summary='fix this', version='1.1beta', Bug.objects.create(summary='fix this', version='1.1beta', assignee=contributor, reporter=someone)
assignee=contributor, reporter=someone) pcontributor = ProxyTrackerUser.objects.create(name='OtherContributor', status='proxy')
pcontributor = ProxyTrackerUser.objects.create(name='OtherContributor', Improvement.objects.create(
status='proxy') summary='improve that', version='1.1beta',
Improvement.objects.create(summary='improve that', version='1.1beta',
assignee=contributor, reporter=pcontributor, assignee=contributor, reporter=pcontributor,
associated_bug=ProxyProxyBug.objects.all()[0]) associated_bug=ProxyProxyBug.objects.all()[0],
)
# Related field filter on proxy # Related field filter on proxy
resp = ProxyBug.objects.get(version__icontains='beta') resp = ProxyBug.objects.get(version__icontains='beta')

View File

@ -1474,10 +1474,8 @@ class Queries4Tests(BaseQuerysetTest):
def test_ticket15316_filter_false(self): def test_ticket15316_filter_false(self):
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = SpecialCategory.objects.create(name="named category1", c2 = SpecialCategory.objects.create(name="named category1", special_name="special1")
special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2")
c3 = SpecialCategory.objects.create(name="named category2",
special_name="special2")
CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c1)
ci2 = CategoryItem.objects.create(category=c2) ci2 = CategoryItem.objects.create(category=c2)
@ -1489,10 +1487,8 @@ class Queries4Tests(BaseQuerysetTest):
def test_ticket15316_exclude_false(self): def test_ticket15316_exclude_false(self):
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = SpecialCategory.objects.create(name="named category1", c2 = SpecialCategory.objects.create(name="named category1", special_name="special1")
special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2")
c3 = SpecialCategory.objects.create(name="named category2",
special_name="special2")
ci1 = CategoryItem.objects.create(category=c1) ci1 = CategoryItem.objects.create(category=c1)
CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c2)
@ -1504,10 +1500,8 @@ class Queries4Tests(BaseQuerysetTest):
def test_ticket15316_filter_true(self): def test_ticket15316_filter_true(self):
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = SpecialCategory.objects.create(name="named category1", c2 = SpecialCategory.objects.create(name="named category1", special_name="special1")
special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2")
c3 = SpecialCategory.objects.create(name="named category2",
special_name="special2")
ci1 = CategoryItem.objects.create(category=c1) ci1 = CategoryItem.objects.create(category=c1)
CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c2)
@ -1519,10 +1513,8 @@ class Queries4Tests(BaseQuerysetTest):
def test_ticket15316_exclude_true(self): def test_ticket15316_exclude_true(self):
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = SpecialCategory.objects.create(name="named category1", c2 = SpecialCategory.objects.create(name="named category1", special_name="special1")
special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2")
c3 = SpecialCategory.objects.create(name="named category2",
special_name="special2")
CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c1)
ci2 = CategoryItem.objects.create(category=c2) ci2 = CategoryItem.objects.create(category=c2)
@ -2260,15 +2252,20 @@ class QuerySetSupportsPythonIdioms(TestCase):
def test_can_get_items_using_index_and_slice_notation(self): def test_can_get_items_using_index_and_slice_notation(self):
self.assertEqual(self.get_ordered_articles()[0].name, 'Article 1') self.assertEqual(self.get_ordered_articles()[0].name, 'Article 1')
self.assertQuerysetEqual(self.get_ordered_articles()[1:3], self.assertQuerysetEqual(
["<Article: Article 2>", "<Article: Article 3>"]) self.get_ordered_articles()[1:3],
["<Article: Article 2>", "<Article: Article 3>"]
)
def test_slicing_with_steps_can_be_used(self): def test_slicing_with_steps_can_be_used(self):
self.assertQuerysetEqual(self.get_ordered_articles()[::2], self.assertQuerysetEqual(
["<Article: Article 1>", self.get_ordered_articles()[::2], [
"<Article: Article 3>", "<Article: Article 1>",
"<Article: Article 5>", "<Article: Article 3>",
"<Article: Article 7>"]) "<Article: Article 5>",
"<Article: Article 7>"
]
)
@unittest.skipUnless(six.PY2, "Python 2 only -- Python 3 doesn't have longs.") @unittest.skipUnless(six.PY2, "Python 2 only -- Python 3 doesn't have longs.")
def test_slicing_works_with_longs(self): def test_slicing_works_with_longs(self):
@ -2276,11 +2273,14 @@ class QuerySetSupportsPythonIdioms(TestCase):
self.assertEqual(self.get_ordered_articles()[long(0)].name, 'Article 1') # NOQA self.assertEqual(self.get_ordered_articles()[long(0)].name, 'Article 1') # NOQA
self.assertQuerysetEqual(self.get_ordered_articles()[long(1):long(3)], # NOQA self.assertQuerysetEqual(self.get_ordered_articles()[long(1):long(3)], # NOQA
["<Article: Article 2>", "<Article: Article 3>"]) ["<Article: Article 2>", "<Article: Article 3>"])
self.assertQuerysetEqual(self.get_ordered_articles()[::long(2)], # NOQA self.assertQuerysetEqual(
["<Article: Article 1>", self.get_ordered_articles()[::long(2)], [ # NOQA
"<Article: Article 3>", "<Article: Article 1>",
"<Article: Article 5>", "<Article: Article 3>",
"<Article: Article 7>"]) "<Article: Article 5>",
"<Article: Article 7>"
]
)
# And can be mixed with ints. # And can be mixed with ints.
self.assertQuerysetEqual(self.get_ordered_articles()[1:long(3)], # NOQA self.assertQuerysetEqual(self.get_ordered_articles()[1:long(3)], # NOQA
@ -2295,25 +2295,29 @@ class QuerySetSupportsPythonIdioms(TestCase):
self.get_ordered_articles()[0:5:3] self.get_ordered_articles()[0:5:3]
def test_slicing_can_slice_again_after_slicing(self): def test_slicing_can_slice_again_after_slicing(self):
self.assertQuerysetEqual(self.get_ordered_articles()[0:5][0:2], self.assertQuerysetEqual(
["<Article: Article 1>", self.get_ordered_articles()[0:5][0:2],
"<Article: Article 2>"]) ["<Article: Article 1>", "<Article: Article 2>"]
self.assertQuerysetEqual(self.get_ordered_articles()[0:5][4:], )
["<Article: Article 5>"]) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][4:], ["<Article: Article 5>"])
self.assertQuerysetEqual(self.get_ordered_articles()[0:5][5:], []) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][5:], [])
# Some more tests! # Some more tests!
self.assertQuerysetEqual(self.get_ordered_articles()[2:][0:2], self.assertQuerysetEqual(
["<Article: Article 3>", "<Article: Article 4>"]) self.get_ordered_articles()[2:][0:2],
self.assertQuerysetEqual(self.get_ordered_articles()[2:][:2], ["<Article: Article 3>", "<Article: Article 4>"]
["<Article: Article 3>", "<Article: Article 4>"]) )
self.assertQuerysetEqual(self.get_ordered_articles()[2:][2:3], self.assertQuerysetEqual(
["<Article: Article 5>"]) self.get_ordered_articles()[2:][:2],
["<Article: Article 3>", "<Article: Article 4>"]
)
self.assertQuerysetEqual(self.get_ordered_articles()[2:][2:3], ["<Article: Article 5>"])
# Using an offset without a limit is also possible. # Using an offset without a limit is also possible.
self.assertQuerysetEqual(self.get_ordered_articles()[5:], self.assertQuerysetEqual(
["<Article: Article 6>", self.get_ordered_articles()[5:],
"<Article: Article 7>"]) ["<Article: Article 6>", "<Article: Article 7>"]
)
def test_slicing_cannot_filter_queryset_once_sliced(self): def test_slicing_cannot_filter_queryset_once_sliced(self):
with self.assertRaisesMessage(AssertionError, "Cannot filter a query once a slice has been taken."): with self.assertRaisesMessage(AssertionError, "Cannot filter a query once a slice has been taken."):
@ -2343,9 +2347,10 @@ class QuerySetSupportsPythonIdioms(TestCase):
def test_can_combine_queries_using_and_and_or_operators(self): def test_can_combine_queries_using_and_and_or_operators(self):
s1 = Article.objects.filter(name__exact='Article 1') s1 = Article.objects.filter(name__exact='Article 1')
s2 = Article.objects.filter(name__exact='Article 2') s2 = Article.objects.filter(name__exact='Article 2')
self.assertQuerysetEqual((s1 | s2).order_by('name'), self.assertQuerysetEqual(
["<Article: Article 1>", (s1 | s2).order_by('name'),
"<Article: Article 2>"]) ["<Article: Article 1>", "<Article: Article 2>"]
)
self.assertQuerysetEqual(s1 & s2, []) self.assertQuerysetEqual(s1 & s2, [])
@ -3488,8 +3493,7 @@ class RelatedLookupTypeTests(TestCase):
with self.assertRaisesMessage(ValueError, self.error % (self.ob, ObjectA._meta.object_name)): with self.assertRaisesMessage(ValueError, self.error % (self.ob, ObjectA._meta.object_name)):
ObjectB.objects.filter(objecta__in=[self.poa, self.ob]) ObjectB.objects.filter(objecta__in=[self.poa, self.ob])
with self.assertRaisesMessage(ValueError, with self.assertRaisesMessage(ValueError, self.error % (self.ob, ChildObjectA._meta.object_name)):
self.error % (self.ob, ChildObjectA._meta.object_name)):
ObjectC.objects.exclude(childobjecta__in=[self.coa, self.ob]) ObjectC.objects.exclude(childobjecta__in=[self.coa, self.ob])
def test_wrong_backward_lookup(self): def test_wrong_backward_lookup(self):

View File

@ -44,7 +44,7 @@ class RawQueryTests(TestCase):
cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4) cls.r1.reviewed.add(cls.b2, cls.b3, cls.b4)
def assertSuccessfulRawQuery(self, model, query, expected_results, def assertSuccessfulRawQuery(self, model, query, expected_results,
expected_annotations=(), params=[], translations=None): expected_annotations=(), params=[], translations=None):
""" """
Execute the passed query against the passed model and check the output Execute the passed query against the passed model and check the output
""" """
@ -280,10 +280,7 @@ class RawQueryTests(TestCase):
Author.objects.raw(query)['test'] Author.objects.raw(query)['test']
def test_inheritance(self): def test_inheritance(self):
# date is the end of the Cuban Missile Crisis, I have no idea when f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun", dob=date(1962, 10, 28))
# Wesley was born
f = FriendlyAuthor.objects.create(first_name="Wesley", last_name="Chun",
dob=date(1962, 10, 28))
query = "SELECT * FROM raw_query_friendlyauthor" query = "SELECT * FROM raw_query_friendlyauthor"
self.assertEqual( self.assertEqual(
[o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk] [o.pk for o in FriendlyAuthor.objects.raw(query)], [f.pk]

View File

@ -8,8 +8,7 @@ from django.test import TestCase, modify_settings, override_settings
from django.utils import six from django.utils import six
@modify_settings(MIDDLEWARE_CLASSES={'append': @modify_settings(MIDDLEWARE_CLASSES={'append': 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'})
'django.contrib.redirects.middleware.RedirectFallbackMiddleware'})
@override_settings(APPEND_SLASH=False, SITE_ID=1) @override_settings(APPEND_SLASH=False, SITE_ID=1)
class RedirectTests(TestCase): class RedirectTests(TestCase):
@ -17,37 +16,29 @@ class RedirectTests(TestCase):
self.site = Site.objects.get(pk=settings.SITE_ID) self.site = Site.objects.get(pk=settings.SITE_ID)
def test_model(self): def test_model(self):
r1 = Redirect.objects.create( r1 = Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target')
site=self.site, old_path='/initial', new_path='/new_target')
self.assertEqual(six.text_type(r1), "/initial ---> /new_target") self.assertEqual(six.text_type(r1), "/initial ---> /new_target")
def test_redirect(self): def test_redirect(self):
Redirect.objects.create( Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target')
site=self.site, old_path='/initial', new_path='/new_target')
response = self.client.get('/initial') response = self.client.get('/initial')
self.assertRedirects(response, self.assertRedirects(response, '/new_target', status_code=301, target_status_code=404)
'/new_target', status_code=301, target_status_code=404)
@override_settings(APPEND_SLASH=True) @override_settings(APPEND_SLASH=True)
def test_redirect_with_append_slash(self): def test_redirect_with_append_slash(self):
Redirect.objects.create( Redirect.objects.create(site=self.site, old_path='/initial/', new_path='/new_target/')
site=self.site, old_path='/initial/', new_path='/new_target/')
response = self.client.get('/initial') response = self.client.get('/initial')
self.assertRedirects(response, self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404)
'/new_target/', status_code=301, target_status_code=404)
@override_settings(APPEND_SLASH=True) @override_settings(APPEND_SLASH=True)
def test_redirect_with_append_slash_and_query_string(self): def test_redirect_with_append_slash_and_query_string(self):
Redirect.objects.create( Redirect.objects.create(site=self.site, old_path='/initial/?foo', new_path='/new_target/')
site=self.site, old_path='/initial/?foo', new_path='/new_target/')
response = self.client.get('/initial?foo') response = self.client.get('/initial?foo')
self.assertRedirects(response, self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404)
'/new_target/', status_code=301, target_status_code=404)
def test_response_gone(self): def test_response_gone(self):
"""When the redirect target is '', return a 410""" """When the redirect target is '', return a 410"""
Redirect.objects.create( Redirect.objects.create(site=self.site, old_path='/initial', new_path='')
site=self.site, old_path='/initial', new_path='')
response = self.client.get('/initial') response = self.client.get('/initial')
self.assertEqual(response.status_code, 410) self.assertEqual(response.status_code, 410)
@ -63,8 +54,7 @@ class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware):
response_redirect_class = http.HttpResponseRedirect response_redirect_class = http.HttpResponseRedirect
@modify_settings(MIDDLEWARE_CLASSES={'append': @modify_settings(MIDDLEWARE_CLASSES={'append': 'redirects_tests.tests.OverriddenRedirectFallbackMiddleware'})
'redirects_tests.tests.OverriddenRedirectFallbackMiddleware'})
@override_settings(SITE_ID=1) @override_settings(SITE_ID=1)
class OverriddenRedirectMiddlewareTests(TestCase): class OverriddenRedirectMiddlewareTests(TestCase):
@ -72,13 +62,11 @@ class OverriddenRedirectMiddlewareTests(TestCase):
self.site = Site.objects.get(pk=settings.SITE_ID) self.site = Site.objects.get(pk=settings.SITE_ID)
def test_response_gone_class(self): def test_response_gone_class(self):
Redirect.objects.create( Redirect.objects.create(site=self.site, old_path='/initial/', new_path='')
site=self.site, old_path='/initial/', new_path='')
response = self.client.get('/initial/') response = self.client.get('/initial/')
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_response_redirect_class(self): def test_response_redirect_class(self):
Redirect.objects.create( Redirect.objects.create(site=self.site, old_path='/initial/', new_path='/new_target/')
site=self.site, old_path='/initial/', new_path='/new_target/')
response = self.client.get('/initial/') response = self.client.get('/initial/')
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)

View File

@ -184,13 +184,17 @@ class RequestsTests(SimpleTestCase):
def test_httprequest_location(self): def test_httprequest_location(self):
request = HttpRequest() request = HttpRequest()
self.assertEqual(request.build_absolute_uri(location="https://www.example.com/asdf"), self.assertEqual(
'https://www.example.com/asdf') request.build_absolute_uri(location="https://www.example.com/asdf"),
'https://www.example.com/asdf'
)
request.get_host = lambda: 'www.example.com' request.get_host = lambda: 'www.example.com'
request.path = '' request.path = ''
self.assertEqual(request.build_absolute_uri(location="/path/with:colons"), self.assertEqual(
'http://www.example.com/path/with:colons') request.build_absolute_uri(location="/path/with:colons"),
'http://www.example.com/path/with:colons'
)
def test_near_expiration(self): def test_near_expiration(self):
"Cookie will expire when an near expiration time is provided" "Cookie will expire when an near expiration time is provided"

View File

@ -10,21 +10,29 @@ from .models import Thing
class ReservedNameTests(TestCase): class ReservedNameTests(TestCase):
def generate(self): def generate(self):
day1 = datetime.date(2005, 1, 1) day1 = datetime.date(2005, 1, 1)
Thing.objects.create(when='a', join='b', like='c', drop='d', Thing.objects.create(
alter='e', having='f', where=day1, has_hyphen='h') when='a', join='b', like='c', drop='d', alter='e', having='f',
where=day1, has_hyphen='h',
)
day2 = datetime.date(2006, 2, 2) day2 = datetime.date(2006, 2, 2)
Thing.objects.create(when='h', join='i', like='j', drop='k', Thing.objects.create(
alter='l', having='m', where=day2) when='h', join='i', like='j', drop='k', alter='l', having='m',
where=day2,
)
def test_simple(self): def test_simple(self):
day1 = datetime.date(2005, 1, 1) day1 = datetime.date(2005, 1, 1)
t = Thing.objects.create(when='a', join='b', like='c', drop='d', t = Thing.objects.create(
alter='e', having='f', where=day1, has_hyphen='h') when='a', join='b', like='c', drop='d',
alter='e', having='f', where=day1, has_hyphen='h',
)
self.assertEqual(t.when, 'a') self.assertEqual(t.when, 'a')
day2 = datetime.date(2006, 2, 2) day2 = datetime.date(2006, 2, 2)
u = Thing.objects.create(when='h', join='i', like='j', drop='k', u = Thing.objects.create(
alter='l', having='m', where=day2) when='h', join='i', like='j', drop='k', alter='l', having='m',
where=day2,
)
self.assertEqual(u.when, 'h') self.assertEqual(u.when, 'h')
def test_order_by(self): def test_order_by(self):

Some files were not shown because too many files have changed in this diff Show More