Fixed #26747 -- Used more specific assertions in the Django test suite.

This commit is contained in:
Jon Dufresne 2016-06-16 11:19:18 -07:00 committed by Tim Graham
parent ea34426ae7
commit 4f336f6652
87 changed files with 406 additions and 406 deletions

View File

@ -180,7 +180,7 @@ Put the following in the ``tests.py`` file in the ``polls`` application:
""" """
time = timezone.now() + datetime.timedelta(days=30) time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time) future_question = Question(pub_date=time)
self.assertEqual(future_question.was_published_recently(), False) self.assertIs(future_question.was_published_recently(), False)
What we have done here is created a :class:`django.test.TestCase` subclass What we have done here is created a :class:`django.test.TestCase` subclass
with a method that creates a ``Question`` instance with a ``pub_date`` in the with a method that creates a ``Question`` instance with a ``pub_date`` in the
@ -203,8 +203,8 @@ and you'll see something like::
---------------------------------------------------------------------- ----------------------------------------------------------------------
Traceback (most recent call last): Traceback (most recent call last):
File "/path/to/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_question File "/path/to/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_question
self.assertEqual(future_question.was_published_recently(), False) self.assertIs(future_question.was_published_recently(), False)
AssertionError: True != False AssertionError: True is not False
---------------------------------------------------------------------- ----------------------------------------------------------------------
Ran 1 test in 0.001s Ran 1 test in 0.001s
@ -285,7 +285,7 @@ more comprehensively:
""" """
time = timezone.now() - datetime.timedelta(days=30) time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time) old_question = Question(pub_date=time)
self.assertEqual(old_question.was_published_recently(), False) self.assertIs(old_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self): def test_was_published_recently_with_recent_question(self):
""" """
@ -294,7 +294,7 @@ more comprehensively:
""" """
time = timezone.now() - datetime.timedelta(hours=1) time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time) recent_question = Question(pub_date=time)
self.assertEqual(recent_question.was_published_recently(), True) self.assertIs(recent_question.was_published_recently(), True)
And now we have three tests that confirm that ``Question.was_published_recently()`` And now we have three tests that confirm that ``Question.was_published_recently()``
returns sensible values for past, recent, and future questions. returns sensible values for past, recent, and future questions.

View File

@ -302,8 +302,8 @@ failed::
---------------------------------------------------------------------- ----------------------------------------------------------------------
Traceback (most recent call last): Traceback (most recent call last):
File "/dev/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_poll File "/dev/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_poll
self.assertEqual(future_poll.was_published_recently(), False) self.assertIs(future_poll.was_published_recently(), False)
AssertionError: True != False AssertionError: True is not False
---------------------------------------------------------------------- ----------------------------------------------------------------------
Ran 1 test in 0.003s Ran 1 test in 0.003s

View File

@ -95,7 +95,7 @@ class ChangeListTests(TestCase):
request, Child, request, Child,
*get_changelist_args(ia, list_select_related=ia.get_list_select_related(request)) *get_changelist_args(ia, list_select_related=ia.get_list_select_related(request))
) )
self.assertEqual(cl.queryset.query.select_related, False) self.assertIs(cl.queryset.query.select_related, False)
def test_get_select_related_custom_method(self): def test_get_select_related_custom_method(self):
class GetListSelectRelatedAdmin(admin.ModelAdmin): class GetListSelectRelatedAdmin(admin.ModelAdmin):

View File

@ -336,7 +336,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][4] filterspec = changelist.get_filters(request)[0][4]
self.assertEqual(force_text(filterspec.title), 'date registered') self.assertEqual(force_text(filterspec.title), 'date registered')
choice = select_by(filterspec.choices(changelist), "display", "Today") choice = select_by(filterspec.choices(changelist), "display", "Today")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual( self.assertEqual(
choice['query_string'], choice['query_string'],
'?date_registered__gte=%s&date_registered__lt=%s' % ( '?date_registered__gte=%s&date_registered__lt=%s' % (
@ -361,7 +361,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][4] filterspec = changelist.get_filters(request)[0][4]
self.assertEqual(force_text(filterspec.title), 'date registered') self.assertEqual(force_text(filterspec.title), 'date registered')
choice = select_by(filterspec.choices(changelist), "display", "This month") choice = select_by(filterspec.choices(changelist), "display", "This month")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual( self.assertEqual(
choice['query_string'], choice['query_string'],
'?date_registered__gte=%s&date_registered__lt=%s' % ( '?date_registered__gte=%s&date_registered__lt=%s' % (
@ -386,7 +386,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][4] filterspec = changelist.get_filters(request)[0][4]
self.assertEqual(force_text(filterspec.title), 'date registered') self.assertEqual(force_text(filterspec.title), 'date registered')
choice = select_by(filterspec.choices(changelist), "display", "This year") choice = select_by(filterspec.choices(changelist), "display", "This year")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual( self.assertEqual(
choice['query_string'], choice['query_string'],
'?date_registered__gte=%s&date_registered__lt=%s' % ( '?date_registered__gte=%s&date_registered__lt=%s' % (
@ -409,7 +409,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][4] filterspec = changelist.get_filters(request)[0][4]
self.assertEqual(force_text(filterspec.title), 'date registered') self.assertEqual(force_text(filterspec.title), 'date registered')
choice = select_by(filterspec.choices(changelist), "display", "Past 7 days") choice = select_by(filterspec.choices(changelist), "display", "Past 7 days")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual( self.assertEqual(
choice['query_string'], choice['query_string'],
'?date_registered__gte=%s&date_registered__lt=%s' % ( '?date_registered__gte=%s&date_registered__lt=%s' % (
@ -431,7 +431,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][4] filterspec = changelist.get_filters(request)[0][4]
self.assertEqual(force_text(filterspec.title), 'date registered') self.assertEqual(force_text(filterspec.title), 'date registered')
choice = select_by(filterspec.choices(changelist), 'display', 'No date') choice = select_by(filterspec.choices(changelist), 'display', 'No date')
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?date_registered__isnull=True') self.assertEqual(choice['query_string'], '?date_registered__isnull=True')
request = self.request_factory.get('/', {'date_registered__isnull': 'False'}) request = self.request_factory.get('/', {'date_registered__isnull': 'False'})
@ -446,7 +446,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][4] filterspec = changelist.get_filters(request)[0][4]
self.assertEqual(force_text(filterspec.title), 'date registered') self.assertEqual(force_text(filterspec.title), 'date registered')
choice = select_by(filterspec.choices(changelist), 'display', 'Has date') choice = select_by(filterspec.choices(changelist), 'display', 'Has date')
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?date_registered__isnull=False') self.assertEqual(choice['query_string'], '?date_registered__isnull=False')
@unittest.skipIf( @unittest.skipIf(
@ -473,7 +473,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][0] filterspec = changelist.get_filters(request)[0][0]
self.assertEqual(force_text(filterspec.title), 'year') self.assertEqual(force_text(filterspec.title), 'year')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[-1]['selected'], True) self.assertIs(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?year__isnull=True') self.assertEqual(choices[-1]['query_string'], '?year__isnull=True')
request = self.request_factory.get('/', {'year': '2002'}) request = self.request_factory.get('/', {'year': '2002'})
@ -483,7 +483,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][0] filterspec = changelist.get_filters(request)[0][0]
self.assertEqual(force_text(filterspec.title), 'year') self.assertEqual(force_text(filterspec.title), 'year')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[2]['selected'], True) self.assertIs(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?year=2002') self.assertEqual(choices[2]['query_string'], '?year=2002')
def test_allvaluesfieldlistfilter_custom_qs(self): def test_allvaluesfieldlistfilter_custom_qs(self):
@ -524,7 +524,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][1] filterspec = changelist.get_filters(request)[0][1]
self.assertEqual(force_text(filterspec.title), 'Verbose Author') self.assertEqual(force_text(filterspec.title), 'Verbose Author')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[-1]['selected'], True) self.assertIs(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?author__isnull=True') self.assertEqual(choices[-1]['query_string'], '?author__isnull=True')
request = self.request_factory.get('/', {'author__id__exact': self.alfred.pk}) request = self.request_factory.get('/', {'author__id__exact': self.alfred.pk})
@ -535,7 +535,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'Verbose Author') self.assertEqual(force_text(filterspec.title), 'Verbose Author')
# order of choices depends on User model, which has no order # order of choices depends on User model, which has no order
choice = select_by(filterspec.choices(changelist), "display", "alfred") choice = select_by(filterspec.choices(changelist), "display", "alfred")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?author__id__exact=%d' % self.alfred.pk) self.assertEqual(choice['query_string'], '?author__id__exact=%d' % self.alfred.pk)
def test_relatedfieldlistfilter_manytomany(self): def test_relatedfieldlistfilter_manytomany(self):
@ -560,7 +560,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][2] filterspec = changelist.get_filters(request)[0][2]
self.assertEqual(force_text(filterspec.title), 'Verbose Contributors') self.assertEqual(force_text(filterspec.title), 'Verbose Contributors')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[-1]['selected'], True) self.assertIs(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?contributors__isnull=True') self.assertEqual(choices[-1]['query_string'], '?contributors__isnull=True')
request = self.request_factory.get('/', {'contributors__id__exact': self.bob.pk}) request = self.request_factory.get('/', {'contributors__id__exact': self.bob.pk})
@ -570,7 +570,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][2] filterspec = changelist.get_filters(request)[0][2]
self.assertEqual(force_text(filterspec.title), 'Verbose Contributors') self.assertEqual(force_text(filterspec.title), 'Verbose Contributors')
choice = select_by(filterspec.choices(changelist), "display", "bob") choice = select_by(filterspec.choices(changelist), "display", "bob")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?contributors__id__exact=%d' % self.bob.pk) self.assertEqual(choice['query_string'], '?contributors__id__exact=%d' % self.bob.pk)
def test_relatedfieldlistfilter_reverse_relationships(self): def test_relatedfieldlistfilter_reverse_relationships(self):
@ -588,7 +588,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][0] filterspec = changelist.get_filters(request)[0][0]
self.assertEqual(force_text(filterspec.title), 'book') self.assertEqual(force_text(filterspec.title), 'book')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[-1]['selected'], True) self.assertIs(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?books_authored__isnull=True') self.assertEqual(choices[-1]['query_string'], '?books_authored__isnull=True')
request = self.request_factory.get('/', {'books_authored__id__exact': self.bio_book.pk}) request = self.request_factory.get('/', {'books_authored__id__exact': self.bio_book.pk})
@ -598,7 +598,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][0] filterspec = changelist.get_filters(request)[0][0]
self.assertEqual(force_text(filterspec.title), 'book') self.assertEqual(force_text(filterspec.title), 'book')
choice = select_by(filterspec.choices(changelist), "display", self.bio_book.title) choice = select_by(filterspec.choices(changelist), "display", self.bio_book.title)
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?books_authored__id__exact=%d' % self.bio_book.pk) self.assertEqual(choice['query_string'], '?books_authored__id__exact=%d' % self.bio_book.pk)
# M2M relationship ----- # M2M relationship -----
@ -613,7 +613,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][1] filterspec = changelist.get_filters(request)[0][1]
self.assertEqual(force_text(filterspec.title), 'book') self.assertEqual(force_text(filterspec.title), 'book')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[-1]['selected'], True) self.assertIs(choices[-1]['selected'], True)
self.assertEqual(choices[-1]['query_string'], '?books_contributed__isnull=True') self.assertEqual(choices[-1]['query_string'], '?books_contributed__isnull=True')
request = self.request_factory.get('/', {'books_contributed__id__exact': self.django_book.pk}) request = self.request_factory.get('/', {'books_contributed__id__exact': self.django_book.pk})
@ -623,7 +623,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][1] filterspec = changelist.get_filters(request)[0][1]
self.assertEqual(force_text(filterspec.title), 'book') self.assertEqual(force_text(filterspec.title), 'book')
choice = select_by(filterspec.choices(changelist), "display", self.django_book.title) choice = select_by(filterspec.choices(changelist), "display", self.django_book.title)
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?books_contributed__id__exact=%d' % self.django_book.pk) self.assertEqual(choice['query_string'], '?books_contributed__id__exact=%d' % self.django_book.pk)
# With one book, the list filter should appear because there is also a # With one book, the list filter should appear because there is also a
@ -719,7 +719,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][3] filterspec = changelist.get_filters(request)[0][3]
self.assertEqual(force_text(filterspec.title), 'is best seller') self.assertEqual(force_text(filterspec.title), 'is best seller')
choice = select_by(filterspec.choices(changelist), "display", "No") choice = select_by(filterspec.choices(changelist), "display", "No")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?is_best_seller__exact=0') self.assertEqual(choice['query_string'], '?is_best_seller__exact=0')
request = self.request_factory.get('/', {'is_best_seller__exact': 1}) request = self.request_factory.get('/', {'is_best_seller__exact': 1})
@ -733,7 +733,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][3] filterspec = changelist.get_filters(request)[0][3]
self.assertEqual(force_text(filterspec.title), 'is best seller') self.assertEqual(force_text(filterspec.title), 'is best seller')
choice = select_by(filterspec.choices(changelist), "display", "Yes") choice = select_by(filterspec.choices(changelist), "display", "Yes")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?is_best_seller__exact=1') self.assertEqual(choice['query_string'], '?is_best_seller__exact=1')
request = self.request_factory.get('/', {'is_best_seller__isnull': 'True'}) request = self.request_factory.get('/', {'is_best_seller__isnull': 'True'})
@ -747,7 +747,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][3] filterspec = changelist.get_filters(request)[0][3]
self.assertEqual(force_text(filterspec.title), 'is best seller') self.assertEqual(force_text(filterspec.title), 'is best seller')
choice = select_by(filterspec.choices(changelist), "display", "Unknown") choice = select_by(filterspec.choices(changelist), "display", "Unknown")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?is_best_seller__isnull=True') self.assertEqual(choice['query_string'], '?is_best_seller__isnull=True')
def test_fieldlistfilter_underscorelookup_tuple(self): def test_fieldlistfilter_underscorelookup_tuple(self):
@ -782,7 +782,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'publication decade') self.assertEqual(force_text(filterspec.title), 'publication decade')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['display'], 'All')
self.assertEqual(choices[0]['selected'], True) self.assertIs(choices[0]['selected'], True)
self.assertEqual(choices[0]['query_string'], '?') self.assertEqual(choices[0]['query_string'], '?')
# Look for books in the 1980s ---------------------------------------- # Look for books in the 1980s ----------------------------------------
@ -798,7 +798,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'publication decade') self.assertEqual(force_text(filterspec.title), 'publication decade')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[1]['display'], 'the 1980\'s') self.assertEqual(choices[1]['display'], 'the 1980\'s')
self.assertEqual(choices[1]['selected'], True) self.assertIs(choices[1]['selected'], True)
self.assertEqual(choices[1]['query_string'], '?publication-decade=the+80s') self.assertEqual(choices[1]['query_string'], '?publication-decade=the+80s')
# Look for books in the 1990s ---------------------------------------- # Look for books in the 1990s ----------------------------------------
@ -814,7 +814,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'publication decade') self.assertEqual(force_text(filterspec.title), 'publication decade')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[2]['display'], 'the 1990\'s') self.assertEqual(choices[2]['display'], 'the 1990\'s')
self.assertEqual(choices[2]['selected'], True) self.assertIs(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?publication-decade=the+90s') self.assertEqual(choices[2]['query_string'], '?publication-decade=the+90s')
# Look for books in the 2000s ---------------------------------------- # Look for books in the 2000s ----------------------------------------
@ -830,7 +830,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'publication decade') self.assertEqual(force_text(filterspec.title), 'publication decade')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[3]['display'], 'the 2000\'s') self.assertEqual(choices[3]['display'], 'the 2000\'s')
self.assertEqual(choices[3]['selected'], True) self.assertIs(choices[3]['selected'], True)
self.assertEqual(choices[3]['query_string'], '?publication-decade=the+00s') self.assertEqual(choices[3]['query_string'], '?publication-decade=the+00s')
# Combine multiple filters ------------------------------------------- # Combine multiple filters -------------------------------------------
@ -846,7 +846,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'publication decade') self.assertEqual(force_text(filterspec.title), 'publication decade')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[3]['display'], 'the 2000\'s') self.assertEqual(choices[3]['display'], 'the 2000\'s')
self.assertEqual(choices[3]['selected'], True) self.assertIs(choices[3]['selected'], True)
self.assertEqual( self.assertEqual(
choices[3]['query_string'], choices[3]['query_string'],
'?author__id__exact=%s&publication-decade=the+00s' % self.alfred.pk '?author__id__exact=%s&publication-decade=the+00s' % self.alfred.pk
@ -855,7 +855,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][0] filterspec = changelist.get_filters(request)[0][0]
self.assertEqual(force_text(filterspec.title), 'Verbose Author') self.assertEqual(force_text(filterspec.title), 'Verbose Author')
choice = select_by(filterspec.choices(changelist), "display", "alfred") choice = select_by(filterspec.choices(changelist), "display", "alfred")
self.assertEqual(choice['selected'], True) self.assertIs(choice['selected'], True)
self.assertEqual(choice['query_string'], '?author__id__exact=%s&publication-decade=the+00s' % self.alfred.pk) self.assertEqual(choice['query_string'], '?author__id__exact=%s&publication-decade=the+00s' % self.alfred.pk)
def test_listfilter_without_title(self): def test_listfilter_without_title(self):
@ -910,15 +910,15 @@ class ListFiltersTests(TestCase):
self.assertEqual(len(choices), 3) self.assertEqual(len(choices), 3)
self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['display'], 'All')
self.assertEqual(choices[0]['selected'], True) self.assertIs(choices[0]['selected'], True)
self.assertEqual(choices[0]['query_string'], '?') self.assertEqual(choices[0]['query_string'], '?')
self.assertEqual(choices[1]['display'], 'the 1990\'s') self.assertEqual(choices[1]['display'], 'the 1990\'s')
self.assertEqual(choices[1]['selected'], False) self.assertIs(choices[1]['selected'], False)
self.assertEqual(choices[1]['query_string'], '?publication-decade=the+90s') self.assertEqual(choices[1]['query_string'], '?publication-decade=the+90s')
self.assertEqual(choices[2]['display'], 'the 2000\'s') self.assertEqual(choices[2]['display'], 'the 2000\'s')
self.assertEqual(choices[2]['selected'], False) self.assertIs(choices[2]['selected'], False)
self.assertEqual(choices[2]['query_string'], '?publication-decade=the+00s') self.assertEqual(choices[2]['query_string'], '?publication-decade=the+00s')
def test_two_characters_long_field(self): def test_two_characters_long_field(self):
@ -936,7 +936,7 @@ class ListFiltersTests(TestCase):
filterspec = changelist.get_filters(request)[0][-1] filterspec = changelist.get_filters(request)[0][-1]
self.assertEqual(force_text(filterspec.title), 'number') self.assertEqual(force_text(filterspec.title), 'number')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[2]['selected'], True) self.assertIs(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?no=207') self.assertEqual(choices[2]['query_string'], '?no=207')
def test_parameter_ends_with__in__or__isnull(self): def test_parameter_ends_with__in__or__isnull(self):
@ -958,7 +958,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'publication decade') self.assertEqual(force_text(filterspec.title), 'publication decade')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[2]['display'], 'the 1990\'s') self.assertEqual(choices[2]['display'], 'the 1990\'s')
self.assertEqual(choices[2]['selected'], True) self.assertIs(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?decade__in=the+90s') self.assertEqual(choices[2]['query_string'], '?decade__in=the+90s')
# When it ends with '__isnull' --------------------------------------- # When it ends with '__isnull' ---------------------------------------
@ -975,7 +975,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'publication decade') self.assertEqual(force_text(filterspec.title), 'publication decade')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[2]['display'], 'the 1990\'s') self.assertEqual(choices[2]['display'], 'the 1990\'s')
self.assertEqual(choices[2]['selected'], True) self.assertIs(choices[2]['selected'], True)
self.assertEqual(choices[2]['query_string'], '?decade__isnull=the+90s') self.assertEqual(choices[2]['query_string'], '?decade__isnull=the+90s')
def test_lookup_with_non_string_value(self): def test_lookup_with_non_string_value(self):
@ -995,7 +995,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'department') self.assertEqual(force_text(filterspec.title), 'department')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[1]['display'], 'DEV') self.assertEqual(choices[1]['display'], 'DEV')
self.assertEqual(choices[1]['selected'], True) self.assertIs(choices[1]['selected'], True)
self.assertEqual(choices[1]['query_string'], '?department=%s' % self.john.department.pk) self.assertEqual(choices[1]['query_string'], '?department=%s' % self.john.department.pk)
def test_lookup_with_non_string_value_underscored(self): def test_lookup_with_non_string_value_underscored(self):
@ -1015,7 +1015,7 @@ class ListFiltersTests(TestCase):
self.assertEqual(force_text(filterspec.title), 'department') self.assertEqual(force_text(filterspec.title), 'department')
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[1]['display'], 'DEV') self.assertEqual(choices[1]['display'], 'DEV')
self.assertEqual(choices[1]['selected'], True) self.assertIs(choices[1]['selected'], True)
self.assertEqual(choices[1]['query_string'], '?department__whatever=%s' % self.john.department.pk) self.assertEqual(choices[1]['query_string'], '?department__whatever=%s' % self.john.department.pk)
def test_fk_with_to_field(self): def test_fk_with_to_field(self):
@ -1036,15 +1036,15 @@ class ListFiltersTests(TestCase):
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['display'], 'All')
self.assertEqual(choices[0]['selected'], True) self.assertIs(choices[0]['selected'], True)
self.assertEqual(choices[0]['query_string'], '?') self.assertEqual(choices[0]['query_string'], '?')
self.assertEqual(choices[1]['display'], 'Development') self.assertEqual(choices[1]['display'], 'Development')
self.assertEqual(choices[1]['selected'], False) self.assertIs(choices[1]['selected'], False)
self.assertEqual(choices[1]['query_string'], '?department__code__exact=DEV') self.assertEqual(choices[1]['query_string'], '?department__code__exact=DEV')
self.assertEqual(choices[2]['display'], 'Design') self.assertEqual(choices[2]['display'], 'Design')
self.assertEqual(choices[2]['selected'], False) self.assertIs(choices[2]['selected'], False)
self.assertEqual(choices[2]['query_string'], '?department__code__exact=DSN') self.assertEqual(choices[2]['query_string'], '?department__code__exact=DSN')
# Filter by Department=='Development' -------------------------------- # Filter by Department=='Development' --------------------------------
@ -1061,15 +1061,15 @@ class ListFiltersTests(TestCase):
choices = list(filterspec.choices(changelist)) choices = list(filterspec.choices(changelist))
self.assertEqual(choices[0]['display'], 'All') self.assertEqual(choices[0]['display'], 'All')
self.assertEqual(choices[0]['selected'], False) self.assertIs(choices[0]['selected'], False)
self.assertEqual(choices[0]['query_string'], '?') self.assertEqual(choices[0]['query_string'], '?')
self.assertEqual(choices[1]['display'], 'Development') self.assertEqual(choices[1]['display'], 'Development')
self.assertEqual(choices[1]['selected'], True) self.assertIs(choices[1]['selected'], True)
self.assertEqual(choices[1]['query_string'], '?department__code__exact=DEV') self.assertEqual(choices[1]['query_string'], '?department__code__exact=DEV')
self.assertEqual(choices[2]['display'], 'Design') self.assertEqual(choices[2]['display'], 'Design')
self.assertEqual(choices[2]['selected'], False) self.assertIs(choices[2]['selected'], False)
self.assertEqual(choices[2]['query_string'], '?department__code__exact=DSN') self.assertEqual(choices[2]['query_string'], '?department__code__exact=DSN')
def test_lookup_with_dynamic_value(self): def test_lookup_with_dynamic_value(self):

View File

@ -39,7 +39,7 @@ class SiteEachContextTest(TestCase):
self.assertEqual(ctx['site_header'], 'Django administration') self.assertEqual(ctx['site_header'], 'Django administration')
self.assertEqual(ctx['site_title'], 'Django site admin') self.assertEqual(ctx['site_title'], 'Django site admin')
self.assertEqual(ctx['site_url'], '/') self.assertEqual(ctx['site_url'], '/')
self.assertEqual(ctx['has_permission'], True) self.assertIs(ctx['has_permission'], True)
def test_each_context_site_url_with_script_name(self): def test_each_context_site_url_with_script_name(self):
request = RequestFactory().get(reverse('test_adminsite:index'), SCRIPT_NAME='/my-script-name/') request = RequestFactory().get(reverse('test_adminsite:index'), SCRIPT_NAME='/my-script-name/')
@ -66,12 +66,12 @@ class SiteEachContextTest(TestCase):
self.assertEqual(user['object_name'], 'User') self.assertEqual(user['object_name'], 'User')
self.assertEqual(auth['app_url'], '/test_admin/admin/auth/') self.assertEqual(auth['app_url'], '/test_admin/admin/auth/')
self.assertEqual(auth['has_module_perms'], True) self.assertIs(auth['has_module_perms'], True)
self.assertIn('perms', user) self.assertIn('perms', user)
self.assertEqual(user['perms']['add'], True) self.assertIs(user['perms']['add'], True)
self.assertEqual(user['perms']['change'], True) self.assertIs(user['perms']['change'], True)
self.assertEqual(user['perms']['delete'], True) self.assertIs(user['perms']['delete'], True)
self.assertEqual(user['admin_url'], '/test_admin/admin/auth/user/') self.assertEqual(user['admin_url'], '/test_admin/admin/auth/user/')
self.assertEqual(user['add_url'], '/test_admin/admin/auth/user/add/') self.assertEqual(user['add_url'], '/test_admin/admin/auth/user/add/')
self.assertEqual(user['name'], 'Users') self.assertEqual(user['name'], 'Users')

View File

@ -22,5 +22,5 @@ class AdminTemplateTagsTest(AdminViewBasicTestCase):
extra_context = {'extra': True} extra_context = {'extra': True}
response = admin.change_view(request, str(self.superuser.pk), extra_context=extra_context) response = admin.change_view(request, str(self.superuser.pk), extra_context=extra_context)
template_context = submit_row(response.context_data) template_context = submit_row(response.context_data)
self.assertEqual(template_context['extra'], True) self.assertIs(template_context['extra'], True)
self.assertEqual(template_context['show_save'], True) self.assertIs(template_context['show_save'], True)

View File

@ -545,10 +545,10 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
response = self.client.get(reverse('admin:admin_views_city_changelist'), {}) response = self.client.get(reverse('admin:admin_views_city_changelist'), {})
response.context['cl'].list_display = ['id', 'name', 'state'] response.context['cl'].list_display = ['id', 'name', 'state']
self.assertEqual(response.context['cl'].has_related_field_in_list_display(), True) self.assertIs(response.context['cl'].has_related_field_in_list_display(), True)
response.context['cl'].list_display = ['id', 'name', 'state_id'] response.context['cl'].list_display = ['id', 'name', 'state_id']
self.assertEqual(response.context['cl'].has_related_field_in_list_display(), False) self.assertIs(response.context['cl'].has_related_field_in_list_display(), False)
def test_limited_filter(self): def test_limited_filter(self):
"""Ensure admin changelist filters do not contain objects excluded via limit_choices_to. """Ensure admin changelist filters do not contain objects excluded via limit_choices_to.
@ -1569,7 +1569,7 @@ class AdminViewPermissionsTest(TestCase):
# Change User should not have access to add articles # Change User should not have access to add articles
self.client.force_login(self.changeuser) self.client.force_login(self.changeuser)
# make sure the view removes test cookie # make sure the view removes test cookie
self.assertEqual(self.client.session.test_cookie_worked(), False) self.assertIs(self.client.session.test_cookie_worked(), False)
response = self.client.get(reverse('admin:admin_views_article_add')) response = self.client.get(reverse('admin:admin_views_article_add'))
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
# Try POST just to make sure # Try POST just to make sure
@ -1622,7 +1622,7 @@ class AdminViewPermissionsTest(TestCase):
# Check and make sure that if user expires, data still persists # Check and make sure that if user expires, data still persists
self.client.force_login(self.superuser) self.client.force_login(self.superuser)
# make sure the view removes test cookie # make sure the view removes test cookie
self.assertEqual(self.client.session.test_cookie_worked(), False) self.assertIs(self.client.session.test_cookie_worked(), False)
def test_change_view(self): def test_change_view(self):
"""Change view should restrict access and allow users to edit items.""" """Change view should restrict access and allow users to edit items."""
@ -2602,7 +2602,7 @@ class AdminViewListEditable(TestCase):
} }
self.client.post(reverse('admin:admin_views_person_changelist'), data) self.client.post(reverse('admin:admin_views_person_changelist'), data)
self.assertEqual(Person.objects.get(name="John Mauchly").alive, False) self.assertIs(Person.objects.get(name="John Mauchly").alive, False)
self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2)
# test a filtered page # test a filtered page
@ -2623,7 +2623,7 @@ class AdminViewListEditable(TestCase):
} }
self.client.post(reverse('admin:admin_views_person_changelist') + '?gender__exact=1', data) self.client.post(reverse('admin:admin_views_person_changelist') + '?gender__exact=1', data)
self.assertEqual(Person.objects.get(name="John Mauchly").alive, True) self.assertIs(Person.objects.get(name="John Mauchly").alive, True)
# test a searched page # test a searched page
data = { data = {
@ -2638,7 +2638,7 @@ class AdminViewListEditable(TestCase):
} }
self.client.post(reverse('admin:admin_views_person_changelist') + '?q=john', data) self.client.post(reverse('admin:admin_views_person_changelist') + '?q=john', data)
self.assertEqual(Person.objects.get(name="John Mauchly").alive, False) self.assertIs(Person.objects.get(name="John Mauchly").alive, False)
def test_non_field_errors(self): def test_non_field_errors(self):
''' Ensure that non field errors are displayed for each of the ''' Ensure that non field errors are displayed for each of the
@ -2834,7 +2834,7 @@ class AdminViewListEditable(TestCase):
} }
self.client.post(reverse('admin:admin_views_person_changelist'), data) self.client.post(reverse('admin:admin_views_person_changelist'), data)
self.assertEqual(Person.objects.get(name="John Mauchly").alive, True) self.assertIs(Person.objects.get(name="John Mauchly").alive, True)
self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 1) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 1)
def test_list_editable_action_choices(self): def test_list_editable_action_choices(self):
@ -2861,7 +2861,7 @@ class AdminViewListEditable(TestCase):
} }
self.client.post(reverse('admin:admin_views_person_changelist'), data) self.client.post(reverse('admin:admin_views_person_changelist'), data)
self.assertEqual(Person.objects.get(name="John Mauchly").alive, False) self.assertIs(Person.objects.get(name="John Mauchly").alive, False)
self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2) self.assertEqual(Person.objects.get(name="Grace Hopper").gender, 2)
def test_list_editable_popup(self): def test_list_editable_popup(self):
@ -3333,7 +3333,7 @@ action)</option>
def test_model_without_action(self): def test_model_without_action(self):
"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.assertIsNone(response.context["action_form"])
self.assertNotContains( self.assertNotContains(
response, '<input type="checkbox" class="action-select"', response, '<input type="checkbox" class="action-select"',
msg_prefix="Found an unexpected action toggle checkboxbox in response" msg_prefix="Found an unexpected action toggle checkboxbox in response"
@ -3343,7 +3343,7 @@ action)</option>
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.assertIsNone(response.context["action_form"])
self.assertContains( self.assertContains(
response, 'jquery.min.js', response, 'jquery.min.js',
msg_prefix="jQuery missing from admin pages for model with no admin actions" msg_prefix="jQuery missing from admin pages for model with no admin actions"
@ -3352,7 +3352,7 @@ action)</option>
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"
response = self.client.get(reverse('admin:admin_views_subscriber_changelist')) response = self.client.get(reverse('admin:admin_views_subscriber_changelist'))
self.assertNotEqual(response.context["action_form"], None) self.assertIsNotNone(response.context["action_form"])
self.assertContains(response, 'action-checkbox-column') self.assertContains(response, 'action-checkbox-column')
def test_multiple_actions_form(self): def test_multiple_actions_form(self):
@ -3410,10 +3410,10 @@ action)</option>
def test_popup_actions(self): def test_popup_actions(self):
""" Actions should not be shown in popups. """ """ Actions should not be shown in popups. """
response = self.client.get(reverse('admin:admin_views_subscriber_changelist')) response = self.client.get(reverse('admin:admin_views_subscriber_changelist'))
self.assertNotEqual(response.context["action_form"], None) self.assertIsNotNone(response.context["action_form"])
response = self.client.get( response = self.client.get(
reverse('admin:admin_views_subscriber_changelist') + '?%s' % IS_POPUP_VAR) reverse('admin:admin_views_subscriber_changelist') + '?%s' % IS_POPUP_VAR)
self.assertEqual(response.context["action_form"], None) self.assertIsNone(response.context["action_form"])
def test_popup_template_response(self): def test_popup_template_response(self):
""" """
@ -4174,17 +4174,17 @@ class NeverCacheTests(TestCase):
"Check the never-cache status of the password change view" "Check the never-cache status of the password change view"
self.client.logout() self.client.logout()
response = self.client.get(reverse('admin:password_change')) response = self.client.get(reverse('admin:password_change'))
self.assertEqual(get_max_age(response), None) self.assertIsNone(get_max_age(response))
def test_password_change_done(self): def test_password_change_done(self):
"Check the never-cache status of the password change done view" "Check the never-cache status of the password change done view"
response = self.client.get(reverse('admin:password_change_done')) response = self.client.get(reverse('admin:password_change_done'))
self.assertEqual(get_max_age(response), None) self.assertIsNone(get_max_age(response))
def test_JS_i18n(self): def test_JS_i18n(self):
"Check the never-cache status of the JavaScript i18n view" "Check the never-cache status of the JavaScript i18n view"
response = self.client.get(reverse('admin:jsi18n')) response = self.client.get(reverse('admin:jsi18n'))
self.assertEqual(get_max_age(response), None) self.assertIsNone(get_max_age(response))
@override_settings(ROOT_URLCONF='admin_views.urls') @override_settings(ROOT_URLCONF='admin_views.urls')

View File

@ -116,7 +116,7 @@ class AdminFormfieldForDBFieldTests(SimpleTestCase):
def test_radio_fields_ForeignKey(self): def test_radio_fields_ForeignKey(self):
ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect, ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect,
radio_fields={'main_band': admin.VERTICAL}) radio_fields={'main_band': admin.VERTICAL})
self.assertEqual(ff.empty_label, None) self.assertIsNone(ff.empty_label)
def test_many_to_many(self): def test_many_to_many(self):
self.assertFormfield(models.Band, 'members', forms.SelectMultiple) self.assertFormfield(models.Band, 'members', forms.SelectMultiple)

View File

@ -56,21 +56,21 @@ class BaseModelBackendTest(object):
def test_has_perm(self): def test_has_perm(self):
user = self.UserModel._default_manager.get(pk=self.user.pk) user = self.UserModel._default_manager.get(pk=self.user.pk)
self.assertEqual(user.has_perm('auth.test'), False) self.assertIs(user.has_perm('auth.test'), False)
user.is_staff = True user.is_staff = True
user.save() user.save()
self.assertEqual(user.has_perm('auth.test'), False) self.assertIs(user.has_perm('auth.test'), False)
user.is_superuser = True user.is_superuser = True
user.save() user.save()
self.assertEqual(user.has_perm('auth.test'), True) self.assertIs(user.has_perm('auth.test'), True)
user.is_staff = True user.is_staff = True
user.is_superuser = True user.is_superuser = True
user.is_active = False user.is_active = False
user.save() user.save()
self.assertEqual(user.has_perm('auth.test'), False) self.assertIs(user.has_perm('auth.test'), False)
def test_custom_perms(self): def test_custom_perms(self):
user = self.UserModel._default_manager.get(pk=self.user.pk) user = self.UserModel._default_manager.get(pk=self.user.pk)
@ -80,10 +80,10 @@ class BaseModelBackendTest(object):
# reloading user to purge the _perm_cache # reloading user to purge the _perm_cache
user = self.UserModel._default_manager.get(pk=self.user.pk) user = self.UserModel._default_manager.get(pk=self.user.pk)
self.assertEqual(user.get_all_permissions() == {'auth.test'}, True) self.assertEqual(user.get_all_permissions(), {'auth.test'})
self.assertEqual(user.get_group_permissions(), set()) self.assertEqual(user.get_group_permissions(), set())
self.assertEqual(user.has_module_perms('Group'), False) self.assertIs(user.has_module_perms('Group'), False)
self.assertEqual(user.has_module_perms('auth'), True) self.assertIs(user.has_module_perms('auth'), True)
perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2')
user.user_permissions.add(perm) user.user_permissions.add(perm)
@ -91,9 +91,9 @@ class BaseModelBackendTest(object):
user.user_permissions.add(perm) user.user_permissions.add(perm)
user = self.UserModel._default_manager.get(pk=self.user.pk) user = self.UserModel._default_manager.get(pk=self.user.pk)
self.assertEqual(user.get_all_permissions(), {'auth.test2', 'auth.test', 'auth.test3'}) self.assertEqual(user.get_all_permissions(), {'auth.test2', 'auth.test', 'auth.test3'})
self.assertEqual(user.has_perm('test'), False) self.assertIs(user.has_perm('test'), False)
self.assertEqual(user.has_perm('auth.test'), True) self.assertIs(user.has_perm('auth.test'), True)
self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) self.assertIs(user.has_perms(['auth.test2', 'auth.test3']), True)
perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group') perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group')
group = Group.objects.create(name='test_group') group = Group.objects.create(name='test_group')
@ -103,11 +103,11 @@ class BaseModelBackendTest(object):
exp = {'auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'} exp = {'auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'}
self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_all_permissions(), exp)
self.assertEqual(user.get_group_permissions(), {'auth.test_group'}) self.assertEqual(user.get_group_permissions(), {'auth.test_group'})
self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) self.assertIs(user.has_perms(['auth.test3', 'auth.test_group']), True)
user = AnonymousUser() user = AnonymousUser()
self.assertEqual(user.has_perm('test'), False) self.assertIs(user.has_perm('test'), False)
self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False) self.assertIs(user.has_perms(['auth.test2', 'auth.test3']), False)
def test_has_no_object_perm(self): def test_has_no_object_perm(self):
"""Regressiontest for #12462""" """Regressiontest for #12462"""
@ -116,9 +116,9 @@ class BaseModelBackendTest(object):
perm = Permission.objects.create(name='test', content_type=content_type, codename='test') perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
user.user_permissions.add(perm) user.user_permissions.add(perm)
self.assertEqual(user.has_perm('auth.test', 'object'), False) self.assertIs(user.has_perm('auth.test', 'object'), False)
self.assertEqual(user.get_all_permissions('object'), set()) self.assertEqual(user.get_all_permissions('object'), set())
self.assertEqual(user.has_perm('auth.test'), True) self.assertIs(user.has_perm('auth.test'), True)
self.assertEqual(user.get_all_permissions(), {'auth.test'}) self.assertEqual(user.get_all_permissions(), {'auth.test'})
def test_anonymous_has_no_permissions(self): def test_anonymous_has_no_permissions(self):
@ -391,13 +391,13 @@ class RowlevelBackendTest(TestCase):
ContentType.objects.clear_cache() ContentType.objects.clear_cache()
def test_has_perm(self): def test_has_perm(self):
self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertIs(self.user1.has_perm('perm', TestObj()), False)
self.assertEqual(self.user2.has_perm('perm', TestObj()), True) self.assertIs(self.user2.has_perm('perm', TestObj()), True)
self.assertEqual(self.user2.has_perm('perm'), False) self.assertIs(self.user2.has_perm('perm'), False)
self.assertEqual(self.user2.has_perms(['simple', 'advanced'], TestObj()), True) self.assertIs(self.user2.has_perms(['simple', 'advanced'], TestObj()), True)
self.assertEqual(self.user3.has_perm('perm', TestObj()), False) self.assertIs(self.user3.has_perm('perm', TestObj()), False)
self.assertEqual(self.user3.has_perm('anon', TestObj()), False) self.assertIs(self.user3.has_perm('anon', TestObj()), False)
self.assertEqual(self.user3.has_perms(['simple', 'advanced'], TestObj()), False) self.assertIs(self.user3.has_perms(['simple', 'advanced'], TestObj()), False)
def test_get_all_permissions(self): def test_get_all_permissions(self):
self.assertEqual(self.user1.get_all_permissions(TestObj()), {'simple'}) self.assertEqual(self.user1.get_all_permissions(TestObj()), {'simple'})
@ -422,16 +422,16 @@ class AnonymousUserBackendTest(SimpleTestCase):
self.user1 = AnonymousUser() self.user1 = AnonymousUser()
def test_has_perm(self): def test_has_perm(self):
self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertIs(self.user1.has_perm('perm', TestObj()), False)
self.assertEqual(self.user1.has_perm('anon', TestObj()), True) self.assertIs(self.user1.has_perm('anon', TestObj()), True)
def test_has_perms(self): def test_has_perms(self):
self.assertEqual(self.user1.has_perms(['anon'], TestObj()), True) self.assertIs(self.user1.has_perms(['anon'], TestObj()), True)
self.assertEqual(self.user1.has_perms(['anon', 'perm'], TestObj()), False) self.assertIs(self.user1.has_perms(['anon', 'perm'], TestObj()), False)
def test_has_module_perms(self): def test_has_module_perms(self):
self.assertEqual(self.user1.has_module_perms("app1"), True) self.assertIs(self.user1.has_module_perms("app1"), True)
self.assertEqual(self.user1.has_module_perms("app2"), False) self.assertIs(self.user1.has_module_perms("app2"), False)
def test_get_all_permissions(self): def test_get_all_permissions(self):
self.assertEqual(self.user1.get_all_permissions(TestObj()), {'anon'}) self.assertEqual(self.user1.get_all_permissions(TestObj()), {'anon'})
@ -462,12 +462,12 @@ class InActiveUserBackendTest(TestCase):
self.user1.save() self.user1.save()
def test_has_perm(self): def test_has_perm(self):
self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertIs(self.user1.has_perm('perm', TestObj()), False)
self.assertEqual(self.user1.has_perm('inactive', TestObj()), True) self.assertIs(self.user1.has_perm('inactive', TestObj()), True)
def test_has_module_perms(self): def test_has_module_perms(self):
self.assertEqual(self.user1.has_module_perms("app1"), False) self.assertIs(self.user1.has_module_perms("app1"), False)
self.assertEqual(self.user1.has_module_perms("app2"), False) self.assertIs(self.user1.has_module_perms("app2"), False)
class PermissionDeniedBackend(object): class PermissionDeniedBackend(object):
@ -505,7 +505,7 @@ class PermissionDeniedBackendTest(TestCase):
@modify_settings(AUTHENTICATION_BACKENDS={'prepend': backend}) @modify_settings(AUTHENTICATION_BACKENDS={'prepend': backend})
def test_permission_denied(self): def test_permission_denied(self):
"user is not authenticated after a backend raises permission denied #2550" "user is not authenticated after a backend raises permission denied #2550"
self.assertEqual(authenticate(username='test', password='test'), None) self.assertIsNone(authenticate(username='test', password='test'))
# user_login_failed signal is sent. # user_login_failed signal is sent.
self.assertEqual(self.user_login_failed, [{'password': '********************', 'username': 'test'}]) self.assertEqual(self.user_login_failed, [{'password': '********************', 'username': 'test'}])

View File

@ -89,7 +89,7 @@ class BasicTestCase(TestCase):
def test_anonymous_user(self): def test_anonymous_user(self):
"Check the properties of the anonymous user" "Check the properties of the anonymous user"
a = AnonymousUser() a = AnonymousUser()
self.assertEqual(a.pk, None) self.assertIsNone(a.pk)
self.assertEqual(a.username, '') self.assertEqual(a.username, '')
self.assertEqual(a.get_username(), '') self.assertEqual(a.get_username(), '')
self.assertTrue(a.is_anonymous) self.assertTrue(a.is_anonymous)

View File

@ -220,7 +220,7 @@ class IsActiveTestCase(TestCase):
def test_builtin_user_isactive(self): def test_builtin_user_isactive(self):
user = User.objects.create(username='foo', email='foo@bar.com') user = User.objects.create(username='foo', email='foo@bar.com')
# is_active is true by default # is_active is true by default
self.assertEqual(user.is_active, True) self.assertIs(user.is_active, True)
user.is_active = False user.is_active = False
user.save() user.save()
user_fetched = User.objects.get(pk=user.pk) user_fetched = User.objects.get(pk=user.pk)
@ -234,14 +234,14 @@ class IsActiveTestCase(TestCase):
""" """
UserModel = get_user_model() UserModel = get_user_model()
user = UserModel(username='foo') user = UserModel(username='foo')
self.assertEqual(user.is_active, True) self.assertIs(user.is_active, True)
# you can set the attribute - but it will not save # you can set the attribute - but it will not save
user.is_active = False user.is_active = False
# there should be no problem saving - but the attribute is not saved # there should be no problem saving - but the attribute is not saved
user.save() user.save()
user_fetched = UserModel._default_manager.get(pk=user.pk) user_fetched = UserModel._default_manager.get(pk=user.pk)
# the attribute is always true for newly retrieved instance # the attribute is always true for newly retrieved instance
self.assertEqual(user_fetched.is_active, True) self.assertIs(user_fetched.is_active, True)
class TestCreateSuperUserSignals(TestCase): class TestCreateSuperUserSignals(TestCase):

View File

@ -58,7 +58,7 @@ class SignalTestCase(TestCase):
# users. # users.
self.client.get('/logout/next_page/') self.client.get('/logout/next_page/')
self.assertEqual(len(self.logged_out), 1) self.assertEqual(len(self.logged_out), 1)
self.assertEqual(self.logged_out[0], None) self.assertIsNone(self.logged_out[0])
def test_logout(self): def test_logout(self):
self.client.login(username='testclient', password='password') self.client.login(username='testclient', password='password')

View File

@ -85,7 +85,7 @@ class ModelInstanceCreationTests(TestCase):
a = Article(headline='Article 5', pub_date=datetime(2005, 7, 31)) a = Article(headline='Article 5', pub_date=datetime(2005, 7, 31))
a.save() a.save()
self.assertEqual(a.headline, 'Article 5') self.assertEqual(a.headline, 'Article 5')
self.assertNotEqual(a.id, None) self.assertIsNotNone(a.id)
def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self): def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self):
a = Article(pub_date=datetime(2005, 7, 31)) a = Article(pub_date=datetime(2005, 7, 31))
@ -358,7 +358,7 @@ class ModelTest(TestCase):
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
EmptyQuerySet() EmptyQuerySet()
self.assertIsInstance(Article.objects.none(), EmptyQuerySet) self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
self.assertFalse(isinstance('', EmptyQuerySet)) self.assertNotIsInstance('', EmptyQuerySet)
def test_emptyqs_values(self): def test_emptyqs_values(self):
# test for #15959 # test for #15959

View File

@ -523,7 +523,7 @@ class BaseCacheTests(object):
cache.add('key2', 'ham', None) cache.add('key2', 'ham', None)
self.assertEqual(cache.get('key2'), 'ham') self.assertEqual(cache.get('key2'), 'ham')
added = cache.add('key1', 'new eggs', None) added = cache.add('key1', 'new eggs', None)
self.assertEqual(added, False) self.assertIs(added, False)
self.assertEqual(cache.get('key1'), 'eggs') self.assertEqual(cache.get('key1'), 'eggs')
cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, None) cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, None)

View File

@ -156,7 +156,7 @@ class CheckCommandTests(SimpleTestCase):
@override_system_checks([simple_system_check, tagged_system_check]) @override_system_checks([simple_system_check, tagged_system_check])
def test_given_tag(self): def test_given_tag(self):
call_command('check', tags=['simpletag']) call_command('check', tags=['simpletag'])
self.assertEqual(simple_system_check.kwargs, None) self.assertIsNone(simple_system_check.kwargs)
self.assertEqual(tagged_system_check.kwargs, {'app_configs': None}) self.assertEqual(tagged_system_check.kwargs, {'app_configs': None})
@override_system_checks([simple_system_check, tagged_system_check]) @override_system_checks([simple_system_check, tagged_system_check])

View File

@ -171,10 +171,10 @@ class CsrfViewMiddlewareTest(SimpleTestCase):
resp = token_view(req) resp = token_view(req)
resp2 = CsrfViewMiddleware().process_response(req, resp) resp2 = CsrfViewMiddleware().process_response(req, resp)
csrf_cookie = resp2.cookies.get('myname', False) csrf_cookie = resp2.cookies.get('myname', False)
self.assertNotEqual(csrf_cookie, False) self.assertIsNot(csrf_cookie, False)
self.assertEqual(csrf_cookie['domain'], '.example.com') self.assertEqual(csrf_cookie['domain'], '.example.com')
self.assertEqual(csrf_cookie['secure'], True) self.assertIs(csrf_cookie['secure'], True)
self.assertEqual(csrf_cookie['httponly'], True) self.assertIs(csrf_cookie['httponly'], True)
self.assertEqual(csrf_cookie['path'], '/test/') self.assertEqual(csrf_cookie['path'], '/test/')
self.assertIn('Cookie', resp2.get('Vary', '')) self.assertIn('Cookie', resp2.get('Vary', ''))
@ -196,7 +196,7 @@ class CsrfViewMiddlewareTest(SimpleTestCase):
resp2 = CsrfViewMiddleware().process_response(req, resp) resp2 = CsrfViewMiddleware().process_response(req, resp)
csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)
self.assertEqual(csrf_cookie, False) self.assertIs(csrf_cookie, False)
# Check the request processing # Check the request processing
def test_process_request_no_csrf_cookie(self): def test_process_request_no_csrf_cookie(self):

View File

@ -70,12 +70,12 @@ class CustomManagerTests(TestCase):
manager = getattr(Person, manager_name) manager = getattr(Person, manager_name)
queryset = manager.filter() queryset = manager.filter()
self.assertQuerysetEqual(queryset, ["Bugs Bunny"], six.text_type) self.assertQuerysetEqual(queryset, ["Bugs Bunny"], six.text_type)
self.assertEqual(queryset._filter_CustomQuerySet, True) self.assertIs(queryset._filter_CustomQuerySet, True)
# Test that specialized querysets inherit from our custom queryset. # Test that specialized querysets inherit from our custom queryset.
queryset = manager.values_list('first_name', flat=True).filter() queryset = manager.values_list('first_name', flat=True).filter()
self.assertEqual(list(queryset), [six.text_type("Bugs")]) self.assertEqual(list(queryset), [six.text_type("Bugs")])
self.assertEqual(queryset._filter_CustomQuerySet, True) self.assertIs(queryset._filter_CustomQuerySet, True)
self.assertIsInstance(queryset.values(), CustomQuerySet) self.assertIsInstance(queryset.values(), CustomQuerySet)
self.assertIsInstance(queryset.values().values(), CustomQuerySet) self.assertIsInstance(queryset.values().values(), CustomQuerySet)
@ -102,7 +102,7 @@ class CustomManagerTests(TestCase):
""" """
queryset = Person.custom_queryset_custom_manager.filter() queryset = Person.custom_queryset_custom_manager.filter()
self.assertQuerysetEqual(queryset, ["Bugs Bunny"], six.text_type) self.assertQuerysetEqual(queryset, ["Bugs Bunny"], six.text_type)
self.assertEqual(queryset._filter_CustomManager, True) self.assertIs(queryset._filter_CustomManager, True)
def test_related_manager(self): def test_related_manager(self):
""" """

View File

@ -227,8 +227,8 @@ class MethodDecoratorTests(SimpleTestCase):
def func(): def func():
pass pass
self.assertEqual(getattr(func, 'myattr', False), True) self.assertIs(getattr(func, 'myattr', False), True)
self.assertEqual(getattr(func, 'myattr2', False), True) self.assertIs(getattr(func, 'myattr2', False), True)
# Decorate using method_decorator() on the method. # Decorate using method_decorator() on the method.
class TestPlain(object): class TestPlain(object):
@ -258,11 +258,11 @@ class MethodDecoratorTests(SimpleTestCase):
pass pass
for Test in (TestPlain, TestMethodAndClass, TestIterable): for Test in (TestPlain, TestMethodAndClass, TestIterable):
self.assertEqual(getattr(Test().method, 'myattr', False), True) self.assertIs(getattr(Test().method, 'myattr', False), True)
self.assertEqual(getattr(Test().method, 'myattr2', False), True) self.assertIs(getattr(Test().method, 'myattr2', False), True)
self.assertEqual(getattr(Test.method, 'myattr', False), True) self.assertIs(getattr(Test.method, 'myattr', False), True)
self.assertEqual(getattr(Test.method, 'myattr2', False), True) self.assertIs(getattr(Test.method, 'myattr2', False), True)
self.assertEqual(Test.method.__doc__, 'A method') self.assertEqual(Test.method.__doc__, 'A method')
self.assertEqual(Test.method.__name__, 'method') self.assertEqual(Test.method.__name__, 'method')
@ -284,7 +284,7 @@ class MethodDecoratorTests(SimpleTestCase):
def method(self): def method(self):
return True return True
self.assertEqual(Test().method(), False) self.assertIs(Test().method(), False)
def test_descriptors(self): def test_descriptors(self):
@ -442,13 +442,13 @@ class XFrameOptionsDecoratorsTests(TestCase):
return HttpResponse() return HttpResponse()
req = HttpRequest() req = HttpRequest()
resp = a_view(req) resp = a_view(req)
self.assertEqual(resp.get('X-Frame-Options', None), None) self.assertIsNone(resp.get('X-Frame-Options', None))
self.assertTrue(resp.xframe_options_exempt) self.assertTrue(resp.xframe_options_exempt)
# Since the real purpose of the exempt decorator is to suppress # Since the real purpose of the exempt decorator is to suppress
# the middleware's functionality, let's make sure it actually works... # the middleware's functionality, let's make sure it actually works...
r = XFrameOptionsMiddleware().process_response(req, resp) r = XFrameOptionsMiddleware().process_response(req, resp)
self.assertEqual(r.get('X-Frame-Options', None), None) self.assertIsNone(r.get('X-Frame-Options', None))
class NeverCacheDecoratorTest(TestCase): class NeverCacheDecoratorTest(TestCase):

View File

@ -167,7 +167,7 @@ class NoNameFileTestCase(unittest.TestCase):
urllib.urlopen() urllib.urlopen()
""" """
def test_noname_file_default_name(self): def test_noname_file_default_name(self):
self.assertEqual(File(BytesIO(b'A file with no name')).name, None) self.assertIsNone(File(BytesIO(b'A file with no name')).name)
def test_noname_file_get_size(self): def test_noname_file_get_size(self):
self.assertEqual(File(BytesIO(b'A file with no name')).size, 19) self.assertEqual(File(BytesIO(b'A file with no name')).size, 19)
@ -175,7 +175,7 @@ class NoNameFileTestCase(unittest.TestCase):
class ContentFileTestCase(unittest.TestCase): class ContentFileTestCase(unittest.TestCase):
def test_content_file_default_name(self): def test_content_file_default_name(self):
self.assertEqual(ContentFile(b"content").name, None) self.assertIsNone(ContentFile(b"content").name)
def test_content_file_custom_name(self): def test_content_file_custom_name(self):
""" """

View File

@ -131,8 +131,8 @@ class TestFixtures(TestCase):
'pretty.xml', 'pretty.xml',
verbosity=0, verbosity=0,
) )
self.assertEqual(Stuff.objects.all()[0].name, None) self.assertIsNone(Stuff.objects.all()[0].name)
self.assertEqual(Stuff.objects.all()[0].owner, None) self.assertIsNone(Stuff.objects.all()[0].owner)
@skipUnlessDBFeature('interprets_empty_strings_as_nulls') @skipUnlessDBFeature('interprets_empty_strings_as_nulls')
def test_pretty_print_xml_empty_strings(self): def test_pretty_print_xml_empty_strings(self):
@ -147,7 +147,7 @@ class TestFixtures(TestCase):
verbosity=0, verbosity=0,
) )
self.assertEqual(Stuff.objects.all()[0].name, '') self.assertEqual(Stuff.objects.all()[0].name, '')
self.assertEqual(Stuff.objects.all()[0].owner, None) self.assertIsNone(Stuff.objects.all()[0].owner)
def test_absolute_path(self): def test_absolute_path(self):
""" """

View File

@ -27,18 +27,18 @@ class BooleanFieldTest(SimpleTestCase):
def test_booleanfield_clean_2(self): def test_booleanfield_clean_2(self):
f = BooleanField(required=False) f = BooleanField(required=False)
self.assertEqual(False, f.clean('')) self.assertIs(f.clean(''), False)
self.assertEqual(False, f.clean(None)) self.assertIs(f.clean(None), False)
self.assertEqual(True, f.clean(True)) self.assertIs(f.clean(True), True)
self.assertEqual(False, f.clean(False)) self.assertIs(f.clean(False), False)
self.assertEqual(True, f.clean(1)) self.assertIs(f.clean(1), True)
self.assertEqual(False, f.clean(0)) self.assertIs(f.clean(0), False)
self.assertEqual(True, f.clean('1')) self.assertIs(f.clean('1'), True)
self.assertEqual(False, f.clean('0')) self.assertIs(f.clean('0'), False)
self.assertEqual(True, f.clean('Django rocks')) self.assertIs(f.clean('Django rocks'), True)
self.assertEqual(False, f.clean('False')) self.assertIs(f.clean('False'), False)
self.assertEqual(False, f.clean('false')) self.assertIs(f.clean('false'), False)
self.assertEqual(False, f.clean('FaLsE')) self.assertIs(f.clean('FaLsE'), False)
def test_boolean_picklable(self): def test_boolean_picklable(self):
self.assertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField) self.assertIsInstance(pickle.loads(pickle.dumps(BooleanField())), BooleanField)

View File

@ -16,7 +16,7 @@ class UUIDFieldTest(SimpleTestCase):
def test_uuidfield_2(self): def test_uuidfield_2(self):
field = UUIDField(required=False) field = UUIDField(required=False)
value = field.clean('') value = field.clean('')
self.assertEqual(value, None) self.assertIsNone(value)
def test_uuidfield_3(self): def test_uuidfield_3(self):
field = UUIDField() field = UUIDField()

View File

@ -323,7 +323,7 @@ class FormsTestCase(SimpleTestCase):
data = {'first_name': 'John', 'last_name': 'Lennon'} data = {'first_name': 'John', 'last_name': 'Lennon'}
f = OptionalPersonForm(data) f = OptionalPersonForm(data)
self.assertTrue(f.is_valid()) self.assertTrue(f.is_valid())
self.assertEqual(f.cleaned_data['birth_date'], None) self.assertIsNone(f.cleaned_data['birth_date'])
self.assertEqual(f.cleaned_data['first_name'], 'John') self.assertEqual(f.cleaned_data['first_name'], 'John')
self.assertEqual(f.cleaned_data['last_name'], 'Lennon') self.assertEqual(f.cleaned_data['last_name'], 'Lennon')
@ -1926,10 +1926,10 @@ Password: <input type="password" name="password" required /></li>
unbound = UserRegistration() unbound = UserRegistration()
bound = UserRegistration({'password': 'foo'}) bound = UserRegistration({'password': 'foo'})
self.assertEqual(bound['username'].value(), None) self.assertIsNone(bound['username'].value())
self.assertEqual(unbound['username'].value(), 'djangonaut') self.assertEqual(unbound['username'].value(), 'djangonaut')
self.assertEqual(bound['password'].value(), 'foo') self.assertEqual(bound['password'].value(), 'foo')
self.assertEqual(unbound['password'].value(), None) self.assertIsNone(unbound['password'].value())
def test_boundfield_initial_called_once(self): def test_boundfield_initial_called_once(self):
""" """
@ -3089,7 +3089,7 @@ Good luck picking a username that doesn&#39;t already exist.</p>
raise ValidationError('Non-field error.', code='secret', params={'a': 1, 'b': 2}) raise ValidationError('Non-field error.', code='secret', params={'a': 1, 'b': 2})
form = MyForm({}) form = MyForm({})
self.assertEqual(form.is_valid(), False) self.assertIs(form.is_valid(), False)
errors = form.errors.as_text() errors = form.errors.as_text()
control = [ control = [

View File

@ -84,4 +84,4 @@ class CheckboxInputTest(WidgetTest):
def test_value_from_datadict_string_int(self): def test_value_from_datadict_string_int(self):
value = self.widget.value_from_datadict({'testing': '0'}, {}, 'testing') value = self.widget.value_from_datadict({'testing': '0'}, {}, 'testing')
self.assertEqual(value, True) self.assertIs(value, True)

View File

@ -87,7 +87,7 @@ class ClearableFileInputTest(WidgetTest):
files={}, files={},
name='myfile', name='myfile',
) )
self.assertEqual(value, False) self.assertIs(value, False)
def test_clear_input_checked_returns_false_only_if_not_required(self): def test_clear_input_checked_returns_false_only_if_not_required(self):
""" """

View File

@ -413,12 +413,12 @@ class GenericInlineModelAdminTest(SimpleTestCase):
# Create a formset with default arguments # Create a formset with default arguments
formset = media_inline.get_formset(request) formset = media_inline.get_formset(request)
self.assertEqual(formset.max_num, DEFAULT_MAX_NUM) self.assertEqual(formset.max_num, DEFAULT_MAX_NUM)
self.assertEqual(formset.can_order, False) self.assertIs(formset.can_order, False)
# Create a formset with custom keyword arguments # Create a formset with custom keyword arguments
formset = media_inline.get_formset(request, max_num=100, can_order=True) formset = media_inline.get_formset(request, max_num=100, can_order=True)
self.assertEqual(formset.max_num, 100) self.assertEqual(formset.max_num, 100)
self.assertEqual(formset.can_order, True) self.assertIs(formset.can_order, True)
def test_custom_form_meta_exclude_with_readonly(self): def test_custom_form_meta_exclude_with_readonly(self):
""" """

View File

@ -166,7 +166,7 @@ class YearArchiveViewTests(TestDataMixin, TestCase):
self.assertTemplateUsed(res, 'generic_views/book_archive_year.html') self.assertTemplateUsed(res, 'generic_views/book_archive_year.html')
# Since allow_empty=False, next/prev years must be valid (#7164) # Since allow_empty=False, next/prev years must be valid (#7164)
self.assertEqual(res.context['next_year'], None) self.assertIsNone(res.context['next_year'])
self.assertEqual(res.context['previous_year'], datetime.date(2006, 1, 1)) self.assertEqual(res.context['previous_year'], datetime.date(2006, 1, 1))
def test_year_view_make_object_list(self): def test_year_view_make_object_list(self):
@ -287,7 +287,7 @@ class MonthArchiveViewTests(TestDataMixin, TestCase):
self.assertEqual(res.context['month'], datetime.date(2008, 10, 1)) self.assertEqual(res.context['month'], datetime.date(2008, 10, 1))
# Since allow_empty=False, next/prev months must be valid (#7164) # Since allow_empty=False, next/prev months must be valid (#7164)
self.assertEqual(res.context['next_month'], None) self.assertIsNone(res.context['next_month'])
self.assertEqual(res.context['previous_month'], datetime.date(2006, 5, 1)) self.assertEqual(res.context['previous_month'], datetime.date(2006, 5, 1))
def test_month_view_allow_empty(self): def test_month_view_allow_empty(self):
@ -310,7 +310,7 @@ class MonthArchiveViewTests(TestDataMixin, TestCase):
url = datetime.date.today().strftime('/dates/books/%Y/%b/allow_empty/').lower() url = datetime.date.today().strftime('/dates/books/%Y/%b/allow_empty/').lower()
res = self.client.get(url) res = self.client.get(url)
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['next_month'], None) self.assertIsNone(res.context['next_month'])
def test_month_view_allow_future(self): def test_month_view_allow_future(self):
future = (datetime.date.today() + datetime.timedelta(days=60)).replace(day=1) future = (datetime.date.today() + datetime.timedelta(days=60)).replace(day=1)
@ -330,7 +330,7 @@ class MonthArchiveViewTests(TestDataMixin, TestCase):
# Since allow_future = True but not allow_empty, next/prev are not # Since allow_future = True but not allow_empty, next/prev are not
# allowed to be empty months (#7164) # allowed to be empty months (#7164)
self.assertEqual(res.context['next_month'], None) self.assertIsNone(res.context['next_month'])
self.assertEqual(res.context['previous_month'], datetime.date(2008, 10, 1)) self.assertEqual(res.context['previous_month'], datetime.date(2008, 10, 1))
# allow_future, but not allow_empty, with a current month. So next # allow_future, but not allow_empty, with a current month. So next
@ -417,7 +417,7 @@ class WeekArchiveViewTests(TestDataMixin, TestCase):
self.assertEqual(res.context['week'], datetime.date(2008, 9, 28)) self.assertEqual(res.context['week'], datetime.date(2008, 9, 28))
# Since allow_empty=False, next/prev weeks must be valid # Since allow_empty=False, next/prev weeks must be valid
self.assertEqual(res.context['next_week'], None) self.assertIsNone(res.context['next_week'])
self.assertEqual(res.context['previous_week'], datetime.date(2006, 4, 30)) self.assertEqual(res.context['previous_week'], datetime.date(2006, 4, 30))
def test_week_view_allow_empty(self): def test_week_view_allow_empty(self):
@ -439,7 +439,7 @@ class WeekArchiveViewTests(TestDataMixin, TestCase):
url = datetime.date.today().strftime('/dates/books/%Y/week/%U/allow_empty/').lower() url = datetime.date.today().strftime('/dates/books/%Y/week/%U/allow_empty/').lower()
res = self.client.get(url) res = self.client.get(url)
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['next_week'], None) self.assertIsNone(res.context['next_week'])
def test_week_view_allow_future(self): def test_week_view_allow_future(self):
# January 7th always falls in week 1, given Python's definition of week numbers # January 7th always falls in week 1, given Python's definition of week numbers
@ -457,7 +457,7 @@ class WeekArchiveViewTests(TestDataMixin, TestCase):
# Since allow_future = True but not allow_empty, next/prev are not # Since allow_future = True but not allow_empty, next/prev are not
# allowed to be empty weeks # allowed to be empty weeks
self.assertEqual(res.context['next_week'], None) self.assertIsNone(res.context['next_week'])
self.assertEqual(res.context['previous_week'], datetime.date(2008, 9, 28)) self.assertEqual(res.context['previous_week'], datetime.date(2008, 9, 28))
# allow_future, but not allow_empty, with a current week. So next # allow_future, but not allow_empty, with a current week. So next
@ -520,7 +520,7 @@ class DayArchiveViewTests(TestDataMixin, TestCase):
self.assertEqual(res.context['day'], datetime.date(2008, 10, 1)) self.assertEqual(res.context['day'], datetime.date(2008, 10, 1))
# Since allow_empty=False, next/prev days must be valid. # Since allow_empty=False, next/prev days must be valid.
self.assertEqual(res.context['next_day'], None) self.assertIsNone(res.context['next_day'])
self.assertEqual(res.context['previous_day'], datetime.date(2006, 5, 1)) self.assertEqual(res.context['previous_day'], datetime.date(2006, 5, 1))
def test_day_view_allow_empty(self): def test_day_view_allow_empty(self):
@ -542,7 +542,7 @@ class DayArchiveViewTests(TestDataMixin, TestCase):
url = datetime.date.today().strftime('/dates/books/%Y/%b/%d/allow_empty/').lower() url = datetime.date.today().strftime('/dates/books/%Y/%b/%d/allow_empty/').lower()
res = self.client.get(url) res = self.client.get(url)
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['next_day'], None) self.assertIsNone(res.context['next_day'])
def test_day_view_allow_future(self): def test_day_view_allow_future(self):
future = (datetime.date.today() + datetime.timedelta(days=60)) future = (datetime.date.today() + datetime.timedelta(days=60))
@ -560,7 +560,7 @@ class DayArchiveViewTests(TestDataMixin, TestCase):
self.assertEqual(res.context['day'], future) self.assertEqual(res.context['day'], future)
# allow_future but not allow_empty, next/prev must be valid # allow_future but not allow_empty, next/prev must be valid
self.assertEqual(res.context['next_day'], None) self.assertIsNone(res.context['next_day'])
self.assertEqual(res.context['previous_day'], datetime.date(2008, 10, 1)) self.assertEqual(res.context['previous_day'], datetime.date(2008, 10, 1))
# allow_future, but not allow_empty, with a current month. # allow_future, but not allow_empty, with a current month.

View File

@ -241,8 +241,8 @@ class GISFunctionsTests(TestCase):
State.objects.create(name='invalid', poly=invalid_geom) State.objects.create(name='invalid', poly=invalid_geom)
valid = State.objects.filter(name='valid').annotate(isvalid=functions.IsValid('poly')).first() valid = State.objects.filter(name='valid').annotate(isvalid=functions.IsValid('poly')).first()
invalid = State.objects.filter(name='invalid').annotate(isvalid=functions.IsValid('poly')).first() invalid = State.objects.filter(name='invalid').annotate(isvalid=functions.IsValid('poly')).first()
self.assertEqual(valid.isvalid, True) self.assertIs(valid.isvalid, True)
self.assertEqual(invalid.isvalid, False) self.assertIs(invalid.isvalid, False)
@skipUnlessDBFeature("has_Area_function") @skipUnlessDBFeature("has_Area_function")
def test_area_with_regular_aggregate(self): def test_area_with_regular_aggregate(self):
@ -265,7 +265,7 @@ class GISFunctionsTests(TestCase):
invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))') invalid_geom = fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))')
State.objects.create(name='invalid', poly=invalid_geom) State.objects.create(name='invalid', poly=invalid_geom)
invalid = State.objects.filter(name='invalid').annotate(repaired=functions.MakeValid('poly')).first() invalid = State.objects.filter(name='invalid').annotate(repaired=functions.MakeValid('poly')).first()
self.assertEqual(invalid.repaired.valid, True) self.assertIs(invalid.repaired.valid, True)
self.assertEqual(invalid.repaired, fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))')) self.assertEqual(invalid.repaired, fromstr('POLYGON((0 0, 0 1, 1 1, 1 0, 0 0))'))
@skipUnlessDBFeature("has_MemSize_function") @skipUnlessDBFeature("has_MemSize_function")

View File

@ -85,5 +85,5 @@ class GeoRegressionTests(TestCase):
self.assertIsInstance(val1, bool) self.assertIsInstance(val1, bool)
self.assertIsInstance(val2, bool) self.assertIsInstance(val2, bool)
# verify values # verify values
self.assertEqual(val1, True) self.assertIs(val1, True)
self.assertEqual(val2, False) self.assertIs(val2, False)

View File

@ -151,7 +151,7 @@ class GeoModelTest(TestCase):
def test_createnull(self): def test_createnull(self):
"Testing creating a model instance and the geometry being None" "Testing creating a model instance and the geometry being None"
c = City() c = City()
self.assertEqual(c.point, None) self.assertIsNone(c.point)
def test_geometryfield(self): def test_geometryfield(self):
"Testing the general GeometryField." "Testing the general GeometryField."
@ -387,7 +387,7 @@ class GeoLookupTest(TestCase):
# Saving another commonwealth w/a NULL geometry. # Saving another commonwealth w/a NULL geometry.
nmi = State.objects.create(name='Northern Mariana Islands', poly=None) nmi = State.objects.create(name='Northern Mariana Islands', poly=None)
self.assertEqual(nmi.poly, None) self.assertIsNone(nmi.poly)
# Assigning a geometry and saving -- then UPDATE back to NULL. # Assigning a geometry and saving -- then UPDATE back to NULL.
nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))' nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))'

View File

@ -112,7 +112,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
# garbage into 3D coordinate if there is none. # garbage into 3D coordinate if there is none.
self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)
self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)
self.assertEqual(True, GEOSGeometry(hexewkb_3d).hasz) self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True)
# Same for EWKB. # Same for EWKB.
self.assertEqual(six.memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) self.assertEqual(six.memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
@ -247,14 +247,14 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
# Testing the third dimension, and getting the tuple arguments # Testing the third dimension, and getting the tuple arguments
if hasattr(p, 'z'): if hasattr(p, 'z'):
self.assertEqual(True, pnt.hasz) self.assertIs(pnt.hasz, True)
self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.z)
self.assertEqual(p.z, pnt.tuple[2], 9) self.assertEqual(p.z, pnt.tuple[2], 9)
tup_args = (p.x, p.y, p.z) tup_args = (p.x, p.y, p.z)
set_tup1 = (2.71, 3.14, 5.23) set_tup1 = (2.71, 3.14, 5.23)
set_tup2 = (5.23, 2.71, 3.14) set_tup2 = (5.23, 2.71, 3.14)
else: else:
self.assertEqual(False, pnt.hasz) self.assertIs(pnt.hasz, False)
self.assertIsNone(pnt.z) self.assertIsNone(pnt.z)
tup_args = (p.x, p.y) tup_args = (p.x, p.y)
set_tup1 = (2.71, 3.14) set_tup1 = (2.71, 3.14)
@ -301,8 +301,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
for p in mpnt: for p in mpnt:
self.assertEqual(p.geom_type, 'Point') self.assertEqual(p.geom_type, 'Point')
self.assertEqual(p.geom_typeid, 0) self.assertEqual(p.geom_typeid, 0)
self.assertEqual(p.empty, False) self.assertIs(p.empty, False)
self.assertEqual(p.valid, True) self.assertIs(p.valid, True)
def test_linestring(self): def test_linestring(self):
"Testing LineString objects." "Testing LineString objects."
@ -312,8 +312,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(ls.geom_type, 'LineString') self.assertEqual(ls.geom_type, 'LineString')
self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.geom_typeid, 1)
self.assertEqual(ls.dims, 1) self.assertEqual(ls.dims, 1)
self.assertEqual(ls.empty, False) self.assertIs(ls.empty, False)
self.assertEqual(ls.ring, False) self.assertIs(ls.ring, False)
if hasattr(l, 'centroid'): if hasattr(l, 'centroid'):
self.assertEqual(l.centroid, ls.centroid.tuple) self.assertEqual(l.centroid, ls.centroid.tuple)
if hasattr(l, 'tup'): if hasattr(l, 'tup'):
@ -367,7 +367,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
for ls in ml: for ls in ml:
self.assertEqual(ls.geom_type, 'LineString') self.assertEqual(ls.geom_type, 'LineString')
self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.geom_typeid, 1)
self.assertEqual(ls.empty, False) self.assertIs(ls.empty, False)
with self.assertRaises(IndexError): with self.assertRaises(IndexError):
ml.__getitem__(len(ml)) ml.__getitem__(len(ml))
@ -382,8 +382,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(lr.geom_typeid, 2) self.assertEqual(lr.geom_typeid, 2)
self.assertEqual(lr.dims, 1) self.assertEqual(lr.dims, 1)
self.assertEqual(rr.n_p, len(lr)) self.assertEqual(rr.n_p, len(lr))
self.assertEqual(True, lr.valid) self.assertIs(lr.valid, True)
self.assertEqual(False, lr.empty) self.assertIs(lr.empty, False)
# Creating a LinearRing from a tuple, list, and numpy array # Creating a LinearRing from a tuple, list, and numpy array
self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(lr.tuple))
@ -425,8 +425,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(poly.geom_type, 'Polygon') self.assertEqual(poly.geom_type, 'Polygon')
self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.geom_typeid, 3)
self.assertEqual(poly.dims, 2) self.assertEqual(poly.dims, 2)
self.assertEqual(poly.empty, False) self.assertIs(poly.empty, False)
self.assertEqual(poly.ring, False) self.assertIs(poly.ring, False)
self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual(p.n_i, poly.num_interior_rings)
self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
self.assertEqual(p.n_p, poly.num_points) self.assertEqual(p.n_p, poly.num_points)
@ -519,7 +519,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
for p in mpoly: for p in mpoly:
self.assertEqual(p.geom_type, 'Polygon') self.assertEqual(p.geom_type, 'Polygon')
self.assertEqual(p.geom_typeid, 3) self.assertEqual(p.geom_typeid, 3)
self.assertEqual(p.valid, True) self.assertIs(p.valid, True)
self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt) self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
def test_memory_hijinks(self): def test_memory_hijinks(self):
@ -592,7 +592,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
a = fromstr(self.geometries.topology_geoms[i].wkt_a) a = fromstr(self.geometries.topology_geoms[i].wkt_a)
b = fromstr(self.geometries.topology_geoms[i].wkt_b) b = fromstr(self.geometries.topology_geoms[i].wkt_b)
i1 = fromstr(self.geometries.intersect_geoms[i].wkt) i1 = fromstr(self.geometries.intersect_geoms[i].wkt)
self.assertEqual(True, a.intersects(b)) self.assertIs(a.intersects(b), True)
i2 = a.intersection(b) i2 = a.intersection(b)
self.assertEqual(i1, i2) self.assertEqual(i1, i2)
self.assertEqual(i1, a & b) # __and__ is intersection operator self.assertEqual(i1, a & b) # __and__ is intersection operator
@ -957,7 +957,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
geoms.append(LineString(numpy.array([]))) geoms.append(LineString(numpy.array([])))
for g in geoms: for g in geoms:
self.assertEqual(True, g.empty) self.assertIs(g.empty, True)
# Testing len() and num_geom. # Testing len() and num_geom.
if isinstance(g, Polygon): if isinstance(g, Polygon):
@ -979,7 +979,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
lr = g.shell lr = g.shell
self.assertEqual('LINEARRING EMPTY', lr.wkt) self.assertEqual('LINEARRING EMPTY', lr.wkt)
self.assertEqual(0, len(lr)) self.assertEqual(0, len(lr))
self.assertEqual(True, lr.empty) self.assertIs(lr.empty, True)
with self.assertRaises(IndexError): with self.assertRaises(IndexError):
lr.__getitem__(0) lr.__getitem__(0)
else: else:

View File

@ -138,7 +138,7 @@ class GEOSIOTest(SimpleTestCase):
def test_wkt_writer_precision(self): def test_wkt_writer_precision(self):
wkt_w = WKTWriter() wkt_w = WKTWriter()
self.assertEqual(wkt_w.precision, None) self.assertIsNone(wkt_w.precision)
self.assertEqual(wkt_w.write(Point(1. / 3, 2. / 3)), b'POINT (0.3333333333333333 0.6666666666666666)') self.assertEqual(wkt_w.write(Point(1. / 3, 2. / 3)), b'POINT (0.3333333333333333 0.6666666666666666)')
wkt_w.precision = 1 wkt_w.precision = 1
@ -150,7 +150,7 @@ class GEOSIOTest(SimpleTestCase):
self.assertEqual(wkt_w.write(Point(1. / 3, 2. / 3)), b'POINT (0 1)') self.assertEqual(wkt_w.write(Point(1. / 3, 2. / 3)), b'POINT (0 1)')
wkt_w.precision = None wkt_w.precision = None
self.assertEqual(wkt_w.precision, None) self.assertIsNone(wkt_w.precision)
self.assertEqual(wkt_w.write(Point(1. / 3, 2. / 3)), b'POINT (0.3333333333333333 0.6666666666666666)') self.assertEqual(wkt_w.write(Point(1. / 3, 2. / 3)), b'POINT (0.3333333333333333 0.6666666666666666)')
with self.assertRaisesMessage(AttributeError, 'WKT output rounding precision must be '): with self.assertRaisesMessage(AttributeError, 'WKT output rounding precision must be '):

View File

@ -185,11 +185,11 @@ class RasterFieldTest(TransactionTestCase):
qs = RasterModel.objects.filter(**combo) qs = RasterModel.objects.filter(**combo)
# Evaluate normal filter qs. # Evaluate normal filter qs.
self.assertTrue(qs.count() in [0, 1]) self.assertIn(qs.count(), [0, 1])
# Evaluate on conditional Q expressions. # Evaluate on conditional Q expressions.
qs = RasterModel.objects.filter(Q(**combos[0]) & Q(**combos[1])) qs = RasterModel.objects.filter(Q(**combos[0]) & Q(**combos[1]))
self.assertTrue(qs.count() in [0, 1]) self.assertIn(qs.count(), [0, 1])
def test_dwithin_gis_lookup_ouptut_with_rasters(self): def test_dwithin_gis_lookup_ouptut_with_rasters(self):
""" """

View File

@ -59,8 +59,8 @@ class QueryDictTests(SimpleTestCase):
q = QueryDict() q = QueryDict()
self.assertEqual(q.getlist('foo'), []) self.assertEqual(q.getlist('foo'), [])
if six.PY2: if six.PY2:
self.assertEqual(q.has_key('foo'), False) self.assertIs(q.has_key('foo'), False)
self.assertEqual('foo' in q, False) self.assertNotIn('foo', q)
self.assertEqual(list(six.iteritems(q)), []) self.assertEqual(list(six.iteritems(q)), [])
self.assertEqual(list(six.iterlists(q)), []) self.assertEqual(list(six.iterlists(q)), [])
self.assertEqual(list(six.iterkeys(q)), []) self.assertEqual(list(six.iterkeys(q)), [])
@ -203,11 +203,11 @@ class QueryDictTests(SimpleTestCase):
q.appendlist('foo', ['bar']) q.appendlist('foo', ['bar'])
if six.PY2: if six.PY2:
self.assertEqual(q.has_key('vote'), True) self.assertIs(q.has_key('vote'), True)
self.assertEqual('vote' in q, True) self.assertIn('vote', q)
if six.PY2: if six.PY2:
self.assertEqual(q.has_key('foo'), False) self.assertIs(q.has_key('foo'), False)
self.assertEqual('foo' in q, False) self.assertNotIn('foo', q)
self.assertEqual(list(six.iteritems(q)), [('vote', 'no')]) self.assertEqual(list(six.iteritems(q)), [('vote', 'no')])
self.assertEqual(list(six.iterlists(q)), [('vote', ['yes', 'no'])]) self.assertEqual(list(six.iterlists(q)), [('vote', ['yes', 'no'])])
self.assertEqual(list(six.iterkeys(q)), ['vote']) self.assertEqual(list(six.iterkeys(q)), ['vote'])
@ -243,13 +243,13 @@ class QueryDictTests(SimpleTestCase):
def test_pickle(self): def test_pickle(self):
q = QueryDict() q = QueryDict()
q1 = pickle.loads(pickle.dumps(q, 2)) q1 = pickle.loads(pickle.dumps(q, 2))
self.assertEqual(q == q1, True) self.assertEqual(q, q1)
q = QueryDict(str('a=b&c=d')) q = QueryDict(str('a=b&c=d'))
q1 = pickle.loads(pickle.dumps(q, 2)) q1 = pickle.loads(pickle.dumps(q, 2))
self.assertEqual(q == q1, True) self.assertEqual(q, q1)
q = QueryDict(str('a=b&c=d&a=1')) q = QueryDict(str('a=b&c=d&a=1'))
q1 = pickle.loads(pickle.dumps(q, 2)) q1 = pickle.loads(pickle.dumps(q, 2))
self.assertEqual(q == q1, True) self.assertEqual(q, q1)
def test_update_from_querydict(self): def test_update_from_querydict(self):
"""Regression test for #8278: QueryDict.update(QueryDict)""" """Regression test for #8278: QueryDict.update(QueryDict)"""
@ -390,7 +390,7 @@ class HttpResponseTests(unittest.TestCase):
Test for bug #14020: Make HttpResponse.get work like dict.get Test for bug #14020: Make HttpResponse.get work like dict.get
""" """
r = HttpResponse() r = HttpResponse()
self.assertEqual(r.get('test'), None) self.assertIsNone(r.get('test'))
def test_non_string_content(self): def test_non_string_content(self):
# Bug 16494: HttpResponse should behave consistently with non-strings # Bug 16494: HttpResponse should behave consistently with non-strings
@ -477,7 +477,7 @@ class HttpResponseTests(unittest.TestCase):
self.assertEqual(r.getvalue(), b'asdf') self.assertEqual(r.getvalue(), b'asdf')
r = HttpResponse() r = HttpResponse()
self.assertEqual(r.writable(), True) self.assertIs(r.writable(), True)
r.writelines(['foo\n', 'bar\n', 'baz\n']) r.writelines(['foo\n', 'bar\n', 'baz\n'])
self.assertEqual(r.content, b'foo\nbar\nbaz\n') self.assertEqual(r.content, b'foo\nbar\nbaz\n')

View File

@ -76,10 +76,10 @@ class TranslationTests(SimpleTestCase):
self.assertEqual(get_language(), 'pl') self.assertEqual(get_language(), 'pl')
self.assertEqual(get_language(), 'de') self.assertEqual(get_language(), 'de')
with translation.override(None): with translation.override(None):
self.assertEqual(get_language(), None) self.assertIsNone(get_language())
with translation.override('pl'): with translation.override('pl'):
pass pass
self.assertEqual(get_language(), None) self.assertIsNone(get_language())
self.assertEqual(get_language(), 'de') self.assertEqual(get_language(), 'de')
finally: finally:
deactivate() deactivate()
@ -92,7 +92,7 @@ class TranslationTests(SimpleTestCase):
@translation.override(None) @translation.override(None)
def func_none(): def func_none():
self.assertEqual(get_language(), None) self.assertIsNone(get_language())
try: try:
activate('de') activate('de')
@ -475,9 +475,9 @@ class TranslationTests(SimpleTestCase):
self.assertEqual(trans_real.to_language('sr_Lat'), 'sr-lat') self.assertEqual(trans_real.to_language('sr_Lat'), 'sr-lat')
def test_language_bidi(self): def test_language_bidi(self):
self.assertEqual(get_language_bidi(), False) self.assertIs(get_language_bidi(), False)
with translation.override(None): with translation.override(None):
self.assertEqual(get_language_bidi(), False) self.assertIs(get_language_bidi(), False)
@override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')]) @override_settings(LOCALE_PATHS=[os.path.join(here, 'other', 'locale')])
def test_bad_placeholder_1(self): def test_bad_placeholder_1(self):
@ -1464,13 +1464,13 @@ class MiscTests(SimpleTestCase):
g = trans_real.get_language_from_path g = trans_real.get_language_from_path
self.assertEqual(g('/pl/'), 'pl') self.assertEqual(g('/pl/'), 'pl')
self.assertEqual(g('/pl'), 'pl') self.assertEqual(g('/pl'), 'pl')
self.assertEqual(g('/xyz/'), None) self.assertIsNone(g('/xyz/'))
def test_get_language_from_path_null(self): def test_get_language_from_path_null(self):
from django.utils.translation.trans_null import get_language_from_path as g from django.utils.translation.trans_null import get_language_from_path as g
self.assertEqual(g('/pl/'), None) self.assertIsNone(g('/pl/'))
self.assertEqual(g('/pl'), None) self.assertIsNone(g('/pl'))
self.assertEqual(g('/xyz/'), None) self.assertIsNone(g('/xyz/'))
@override_settings(LOCALE_PATHS=extended_locale_paths) @override_settings(LOCALE_PATHS=extended_locale_paths)
def test_percent_in_translatable_block(self): def test_percent_in_translatable_block(self):
@ -1595,7 +1595,7 @@ class TestLanguageInfo(SimpleTestCase):
self.assertEqual(li['code'], 'de') self.assertEqual(li['code'], 'de')
self.assertEqual(li['name_local'], 'Deutsch') self.assertEqual(li['name_local'], 'Deutsch')
self.assertEqual(li['name'], 'German') self.assertEqual(li['name'], 'German')
self.assertEqual(li['bidi'], False) self.assertIs(li['bidi'], False)
def test_unknown_language_code(self): def test_unknown_language_code(self):
six.assertRaisesRegex(self, KeyError, r"Unknown language code xx\.", get_language_info, 'xx') six.assertRaisesRegex(self, KeyError, r"Unknown language code xx\.", get_language_info, 'xx')
@ -1609,7 +1609,7 @@ class TestLanguageInfo(SimpleTestCase):
self.assertEqual(li['code'], 'de') self.assertEqual(li['code'], 'de')
self.assertEqual(li['name_local'], 'Deutsch') self.assertEqual(li['name_local'], 'Deutsch')
self.assertEqual(li['name'], 'German') self.assertEqual(li['name'], 'German')
self.assertEqual(li['bidi'], False) self.assertIs(li['bidi'], False)
def test_unknown_language_code_and_country_code(self): def test_unknown_language_code_and_country_code(self):
six.assertRaisesRegex(self, KeyError, r"Unknown language code xx-xx and xx\.", get_language_info, 'xx-xx') six.assertRaisesRegex(self, KeyError, r"Unknown language code xx-xx and xx\.", get_language_info, 'xx-xx')

View File

@ -44,14 +44,14 @@ class DeletionTests(TestCase):
} }
formset = PoemFormSet(data, instance=poet) formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation. # Make sure this form doesn't pass validation.
self.assertEqual(formset.is_valid(), False) self.assertIs(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 0) self.assertEqual(Poem.objects.count(), 0)
# Then make sure that it *does* pass validation and delete the object, # Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actually valid. # even though the data isn't actually valid.
data['poem_set-0-DELETE'] = 'on' data['poem_set-0-DELETE'] = 'on'
formset = PoemFormSet(data, instance=poet) formset = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), True) self.assertIs(formset.is_valid(), True)
formset.save() formset.save()
self.assertEqual(Poem.objects.count(), 0) self.assertEqual(Poem.objects.count(), 0)
@ -73,14 +73,14 @@ class DeletionTests(TestCase):
} }
formset = PoemFormSet(data, instance=poet) formset = PoemFormSet(data, instance=poet)
# Make sure this form doesn't pass validation. # Make sure this form doesn't pass validation.
self.assertEqual(formset.is_valid(), False) self.assertIs(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 1) self.assertEqual(Poem.objects.count(), 1)
# Then make sure that it *does* pass validation and delete the object, # Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actually valid. # even though the data isn't actually valid.
data['poem_set-0-DELETE'] = 'on' data['poem_set-0-DELETE'] = 'on'
formset = PoemFormSet(data, instance=poet) formset = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), True) self.assertIs(formset.is_valid(), True)
formset.save() formset.save()
self.assertEqual(Poem.objects.count(), 0) self.assertEqual(Poem.objects.count(), 0)
@ -101,7 +101,7 @@ class DeletionTests(TestCase):
'child_set-0-name': 'child', 'child_set-0-name': 'child',
} }
formset = ChildFormSet(data, instance=school) formset = ChildFormSet(data, instance=school)
self.assertEqual(formset.is_valid(), True) self.assertIs(formset.is_valid(), True)
objects = formset.save(commit=False) objects = formset.save(commit=False)
for obj in objects: for obj in objects:
obj.mother = mother obj.mother = mother

View File

@ -48,10 +48,10 @@ class LoggingFiltersTest(SimpleTestCase):
filter_ = RequireDebugFalse() filter_ = RequireDebugFalse()
with self.settings(DEBUG=True): with self.settings(DEBUG=True):
self.assertEqual(filter_.filter("record is not used"), False) self.assertIs(filter_.filter("record is not used"), False)
with self.settings(DEBUG=False): with self.settings(DEBUG=False):
self.assertEqual(filter_.filter("record is not used"), True) self.assertIs(filter_.filter("record is not used"), True)
def test_require_debug_true_filter(self): def test_require_debug_true_filter(self):
""" """
@ -60,10 +60,10 @@ class LoggingFiltersTest(SimpleTestCase):
filter_ = RequireDebugTrue() filter_ = RequireDebugTrue()
with self.settings(DEBUG=True): with self.settings(DEBUG=True):
self.assertEqual(filter_.filter("record is not used"), True) self.assertIs(filter_.filter("record is not used"), True)
with self.settings(DEBUG=False): with self.settings(DEBUG=False):
self.assertEqual(filter_.filter("record is not used"), False) self.assertIs(filter_.filter("record is not used"), False)
class SetupDefaultLoggingMixin(object): class SetupDefaultLoggingMixin(object):

View File

@ -17,7 +17,7 @@ class ManyToOneRecursiveTests(TestCase):
self.assertQuerysetEqual(self.r.child_set.all(), self.assertQuerysetEqual(self.r.child_set.all(),
['<Category: Child category>']) ['<Category: Child category>'])
self.assertEqual(self.r.child_set.get(name__startswith='Child').id, self.c.id) self.assertEqual(self.r.child_set.get(name__startswith='Child').id, self.c.id)
self.assertEqual(self.r.parent, None) self.assertIsNone(self.r.parent)
self.assertQuerysetEqual(self.c.child_set.all(), []) self.assertQuerysetEqual(self.c.child_set.all(), [])
self.assertEqual(self.c.parent.id, self.r.id) self.assertEqual(self.c.parent.id, self.r.id)

View File

@ -1249,7 +1249,7 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
def test_email_ssl_certfile_default_disabled(self): def test_email_ssl_certfile_default_disabled(self):
backend = smtp.EmailBackend() backend = smtp.EmailBackend()
self.assertEqual(backend.ssl_certfile, None) self.assertIsNone(backend.ssl_certfile)
@override_settings(EMAIL_SSL_KEYFILE='foo') @override_settings(EMAIL_SSL_KEYFILE='foo')
def test_email_ssl_keyfile_use_settings(self): def test_email_ssl_keyfile_use_settings(self):
@ -1263,7 +1263,7 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
def test_email_ssl_keyfile_default_disabled(self): def test_email_ssl_keyfile_default_disabled(self):
backend = smtp.EmailBackend() backend = smtp.EmailBackend()
self.assertEqual(backend.ssl_keyfile, None) self.assertIsNone(backend.ssl_keyfile)
@override_settings(EMAIL_USE_TLS=True) @override_settings(EMAIL_USE_TLS=True)
def test_email_tls_attempts_starttls(self): def test_email_tls_attempts_starttls(self):
@ -1288,7 +1288,7 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
def test_connection_timeout_default(self): def test_connection_timeout_default(self):
"""Test that the connection's timeout value is None by default.""" """Test that the connection's timeout value is None by default."""
connection = mail.get_connection('django.core.mail.backends.smtp.EmailBackend') connection = mail.get_connection('django.core.mail.backends.smtp.EmailBackend')
self.assertEqual(connection.timeout, None) self.assertIsNone(connection.timeout)
def test_connection_timeout_custom(self): def test_connection_timeout_custom(self):
"""Test that the timeout parameter can be customized.""" """Test that the timeout parameter can be customized."""

View File

@ -39,14 +39,14 @@ class ManyToOneNullTests(TestCase):
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):
self.assertEqual(self.a3.reporter, None) self.assertIsNone(self.a3.reporter)
# Need to reget a3 to refresh the cache # Need to reget a3 to refresh the cache
a3 = Article.objects.get(pk=self.a3.pk) a3 = Article.objects.get(pk=self.a3.pk)
with self.assertRaises(AttributeError): with self.assertRaises(AttributeError):
getattr(a3.reporter, 'id') getattr(a3.reporter, 'id')
# Accessing an article's 'reporter' attribute returns None # Accessing an article's 'reporter' attribute returns None
# if the reporter is set to None. # if the reporter is set to None.
self.assertEqual(a3.reporter, None) self.assertIsNone(a3.reporter)
# 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), ['<Article: Third>']) self.assertQuerysetEqual(Article.objects.filter(reporter__isnull=True), ['<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

View File

@ -70,8 +70,8 @@ class CookieTest(BaseTests, SimpleTestCase):
self.assertIn('test', response.cookies['messages'].value) self.assertIn('test', response.cookies['messages'].value)
self.assertEqual(response.cookies['messages']['domain'], '.example.com') self.assertEqual(response.cookies['messages']['domain'], '.example.com')
self.assertEqual(response.cookies['messages']['expires'], '') self.assertEqual(response.cookies['messages']['expires'], '')
self.assertEqual(response.cookies['messages']['secure'], True) self.assertIs(response.cookies['messages']['secure'], True)
self.assertEqual(response.cookies['messages']['httponly'], True) self.assertIs(response.cookies['messages']['httponly'], True)
# Test deletion of the cookie (storing with an empty value) after the messages have been consumed # Test deletion of the cookie (storing with an empty value) after the messages have been consumed
storage = self.get_storage() storage = self.get_storage()

View File

@ -168,7 +168,7 @@ class SecurityMiddlewareTest(SimpleTestCase):
The middleware does not redirect secure requests. The middleware does not redirect secure requests.
""" """
ret = self.process_request("get", "/some/url", secure=True) ret = self.process_request("get", "/some/url", secure=True)
self.assertEqual(ret, None) self.assertIsNone(ret)
@override_settings( @override_settings(
SECURE_SSL_REDIRECT=True, SECURE_REDIRECT_EXEMPT=["^insecure/"]) SECURE_SSL_REDIRECT=True, SECURE_REDIRECT_EXEMPT=["^insecure/"])
@ -178,7 +178,7 @@ class SecurityMiddlewareTest(SimpleTestCase):
exempt pattern. exempt pattern.
""" """
ret = self.process_request("get", "/insecure/page") ret = self.process_request("get", "/insecure/page")
self.assertEqual(ret, None) self.assertIsNone(ret)
@override_settings( @override_settings(
SECURE_SSL_REDIRECT=True, SECURE_SSL_HOST="secure.example.com") SECURE_SSL_REDIRECT=True, SECURE_SSL_HOST="secure.example.com")
@ -196,4 +196,4 @@ class SecurityMiddlewareTest(SimpleTestCase):
With SSL_REDIRECT False, the middleware does no redirect. With SSL_REDIRECT False, the middleware does no redirect.
""" """
ret = self.process_request("get", "/some/url") ret = self.process_request("get", "/some/url")
self.assertEqual(ret, None) self.assertIsNone(ret)

View File

@ -38,7 +38,7 @@ class CommonMiddlewareTest(SimpleTestCase):
URLs with slashes should go unmolested. URLs with slashes should go unmolested.
""" """
request = self.rf.get('/slash/') request = self.rf.get('/slash/')
self.assertEqual(CommonMiddleware().process_request(request), None) self.assertIsNone(CommonMiddleware().process_request(request))
response = HttpResponseNotFound() response = HttpResponseNotFound()
self.assertEqual(CommonMiddleware().process_response(request, response), response) self.assertEqual(CommonMiddleware().process_response(request, response), response)
@ -48,7 +48,7 @@ class CommonMiddlewareTest(SimpleTestCase):
Matches to explicit slashless URLs should go unmolested. Matches to explicit slashless URLs should go unmolested.
""" """
request = self.rf.get('/noslash') request = self.rf.get('/noslash')
self.assertEqual(CommonMiddleware().process_request(request), None) self.assertIsNone(CommonMiddleware().process_request(request))
response = HttpResponse("Here's the text of the Web page.") response = HttpResponse("Here's the text of the Web page.")
self.assertEqual(CommonMiddleware().process_response(request, response), response) self.assertEqual(CommonMiddleware().process_response(request, response), response)
@ -153,7 +153,7 @@ class CommonMiddlewareTest(SimpleTestCase):
""" """
request = self.rf.get('/customurlconf/slash/') request = self.rf.get('/customurlconf/slash/')
request.urlconf = 'middleware.extra_urls' request.urlconf = 'middleware.extra_urls'
self.assertEqual(CommonMiddleware().process_request(request), None) self.assertIsNone(CommonMiddleware().process_request(request))
response = HttpResponseNotFound() response = HttpResponseNotFound()
self.assertEqual(CommonMiddleware().process_response(request, response), response) self.assertEqual(CommonMiddleware().process_response(request, response), response)
@ -164,7 +164,7 @@ class CommonMiddlewareTest(SimpleTestCase):
""" """
request = self.rf.get('/customurlconf/noslash') request = self.rf.get('/customurlconf/noslash')
request.urlconf = 'middleware.extra_urls' request.urlconf = 'middleware.extra_urls'
self.assertEqual(CommonMiddleware().process_request(request), None) self.assertIsNone(CommonMiddleware().process_request(request))
response = HttpResponse("Here's the text of the Web page.") response = HttpResponse("Here's the text of the Web page.")
self.assertEqual(CommonMiddleware().process_response(request, response), response) self.assertEqual(CommonMiddleware().process_response(request, response), response)
@ -175,7 +175,7 @@ class CommonMiddlewareTest(SimpleTestCase):
""" """
request = self.rf.get('/customurlconf/unknown') request = self.rf.get('/customurlconf/unknown')
request.urlconf = 'middleware.extra_urls' request.urlconf = 'middleware.extra_urls'
self.assertEqual(CommonMiddleware().process_request(request), None) self.assertIsNone(CommonMiddleware().process_request(request))
response = HttpResponseNotFound() response = HttpResponseNotFound()
self.assertEqual(CommonMiddleware().process_response(request, response), response) self.assertEqual(CommonMiddleware().process_response(request, response), response)
@ -213,7 +213,7 @@ class CommonMiddlewareTest(SimpleTestCase):
""" """
request = self.rf.get('/customurlconf/slash') request = self.rf.get('/customurlconf/slash')
request.urlconf = 'middleware.extra_urls' request.urlconf = 'middleware.extra_urls'
self.assertEqual(CommonMiddleware().process_request(request), None) self.assertIsNone(CommonMiddleware().process_request(request))
response = HttpResponseNotFound() response = HttpResponseNotFound()
self.assertEqual(CommonMiddleware().process_response(request, response), response) self.assertEqual(CommonMiddleware().process_response(request, response), response)

View File

@ -256,7 +256,7 @@ class ExecutorTests(MigrationTestBase):
self.assertTableExists("migrations_author") self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble") self.assertTableExists("migrations_tribble")
# We shouldn't have faked that one # We shouldn't have faked that one
self.assertEqual(state["faked"], False) self.assertIs(state["faked"], False)
# Rebuild the graph to reflect the new DB state # Rebuild the graph to reflect the new DB state
executor.loader.build_graph() executor.loader.build_graph()
# Fake-reverse that # Fake-reverse that
@ -265,7 +265,7 @@ class ExecutorTests(MigrationTestBase):
self.assertTableExists("migrations_author") self.assertTableExists("migrations_author")
self.assertTableExists("migrations_tribble") self.assertTableExists("migrations_tribble")
# Make sure that was faked # Make sure that was faked
self.assertEqual(state["faked"], True) self.assertIs(state["faked"], True)
# Finally, migrate forwards; this should fake-apply our initial migration # Finally, migrate forwards; this should fake-apply our initial migration
executor.loader.build_graph() executor.loader.build_graph()
self.assertEqual( self.assertEqual(
@ -282,7 +282,7 @@ class ExecutorTests(MigrationTestBase):
state = {"faked": None} state = {"faked": None}
# Allow faking of initial CreateModel operations # Allow faking of initial CreateModel operations
executor.migrate([("migrations", "0001_initial")], fake_initial=True) executor.migrate([("migrations", "0001_initial")], fake_initial=True)
self.assertEqual(state["faked"], True) self.assertIs(state["faked"], True)
# And migrate back to clean up the database # And migrate back to clean up the database
executor.loader.build_graph() executor.loader.build_graph()
executor.migrate([("migrations", None)]) executor.migrate([("migrations", None)])
@ -318,7 +318,7 @@ class ExecutorTests(MigrationTestBase):
global_apps.get_app_config("migrations").models["author"] = migrations_apps.get_model("migrations", "author") global_apps.get_app_config("migrations").models["author"] = migrations_apps.get_model("migrations", "author")
try: try:
migration = executor.loader.get_migration("auth", "0001_initial") migration = executor.loader.get_migration("auth", "0001_initial")
self.assertEqual(executor.detect_soft_applied(None, migration)[0], True) self.assertIs(executor.detect_soft_applied(None, migration)[0], True)
finally: finally:
connection.introspection.table_names = old_table_names connection.introspection.table_names = old_table_names
del global_apps.get_app_config("migrations").models["author"] del global_apps.get_app_config("migrations").models["author"]
@ -357,9 +357,9 @@ class ExecutorTests(MigrationTestBase):
self.assertTableExists(table) self.assertTableExists(table)
# Table detection sees 0001 is applied but not 0002. # Table detection sees 0001 is applied but not 0002.
migration = executor.loader.get_migration("migrations", "0001_initial") migration = executor.loader.get_migration("migrations", "0001_initial")
self.assertEqual(executor.detect_soft_applied(None, migration)[0], True) self.assertIs(executor.detect_soft_applied(None, migration)[0], True)
migration = executor.loader.get_migration("migrations", "0002_initial") migration = executor.loader.get_migration("migrations", "0002_initial")
self.assertEqual(executor.detect_soft_applied(None, migration)[0], False) self.assertIs(executor.detect_soft_applied(None, migration)[0], False)
# Create the tables for both migrations but make it look like neither # Create the tables for both migrations but make it look like neither
# has been applied. # has been applied.
@ -370,7 +370,7 @@ class ExecutorTests(MigrationTestBase):
executor.migrate([("migrations", None)], fake=True) executor.migrate([("migrations", None)], fake=True)
# Table detection sees 0002 is applied. # Table detection sees 0002 is applied.
migration = executor.loader.get_migration("migrations", "0002_initial") migration = executor.loader.get_migration("migrations", "0002_initial")
self.assertEqual(executor.detect_soft_applied(None, migration)[0], True) self.assertIs(executor.detect_soft_applied(None, migration)[0], True)
# Leave the tables for 0001 except the many-to-many table. That missing # Leave the tables for 0001 except the many-to-many table. That missing
# table should cause detect_soft_applied() to return False. # table should cause detect_soft_applied() to return False.
@ -378,7 +378,7 @@ class ExecutorTests(MigrationTestBase):
for table in tables[2:]: for table in tables[2:]:
editor.execute(editor.sql_delete_table % {"table": table}) editor.execute(editor.sql_delete_table % {"table": table})
migration = executor.loader.get_migration("migrations", "0001_initial") migration = executor.loader.get_migration("migrations", "0001_initial")
self.assertEqual(executor.detect_soft_applied(None, migration)[0], False) self.assertIs(executor.detect_soft_applied(None, migration)[0], False)
# Cleanup by removing the remaining tables. # Cleanup by removing the remaining tables.
with connection.schema_editor() as editor: with connection.schema_editor() as editor:

View File

@ -1210,8 +1210,8 @@ class OperationTests(OperationTestBase):
self.assertEqual(operation.describe(), "Alter field pink on Pony") self.assertEqual(operation.describe(), "Alter field pink on Pony")
new_state = project_state.clone() new_state = project_state.clone()
operation.state_forwards("test_alfl", new_state) operation.state_forwards("test_alfl", new_state)
self.assertEqual(project_state.models["test_alfl", "pony"].get_field_by_name("pink").null, False) self.assertIs(project_state.models["test_alfl", "pony"].get_field_by_name("pink").null, False)
self.assertEqual(new_state.models["test_alfl", "pony"].get_field_by_name("pink").null, True) self.assertIs(new_state.models["test_alfl", "pony"].get_field_by_name("pink").null, True)
# Test the database alteration # Test the database alteration
self.assertColumnNotNull("test_alfl_pony", "pink") self.assertColumnNotNull("test_alfl_pony", "pink")
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
@ -2063,7 +2063,7 @@ class OperationTests(OperationTestBase):
state = new_state.clone() state = new_state.clone()
blog = state.apps.get_model("test_blog.Blog") blog = state.apps.get_model("test_blog.Blog")
self.assertTrue(isinstance(blog._meta.pk, models.BigAutoField)) self.assertIsInstance(blog._meta.pk, models.BigAutoField)
project_state = new_state project_state = new_state
new_state = new_state.clone() new_state = new_state.clone()

View File

@ -121,8 +121,8 @@ class StateTests(SimpleTestCase):
self.assertEqual(author_state.name, "Author") self.assertEqual(author_state.name, "Author")
self.assertEqual([x for x, y in author_state.fields], ["id", "name", "bio", "age"]) self.assertEqual([x for x, y in author_state.fields], ["id", "name", "bio", "age"])
self.assertEqual(author_state.fields[1][1].max_length, 255) self.assertEqual(author_state.fields[1][1].max_length, 255)
self.assertEqual(author_state.fields[2][1].null, False) self.assertIs(author_state.fields[2][1].null, False)
self.assertEqual(author_state.fields[3][1].null, True) self.assertIs(author_state.fields[3][1].null, True)
self.assertEqual( self.assertEqual(
author_state.options, author_state.options,
{"unique_together": {("name", "bio")}, "index_together": {("bio", "age")}} {"unique_together": {("name", "bio")}, "index_together": {("bio", "age")}}
@ -133,7 +133,7 @@ class StateTests(SimpleTestCase):
self.assertEqual(book_state.name, "Book") self.assertEqual(book_state.name, "Book")
self.assertEqual([x for x, y in book_state.fields], ["id", "title", "author", "contributors"]) self.assertEqual([x for x, y in book_state.fields], ["id", "title", "author", "contributors"])
self.assertEqual(book_state.fields[1][1].max_length, 1000) self.assertEqual(book_state.fields[1][1].max_length, 1000)
self.assertEqual(book_state.fields[2][1].null, False) self.assertIs(book_state.fields[2][1].null, False)
self.assertEqual(book_state.fields[3][1].__class__.__name__, "ManyToManyField") self.assertEqual(book_state.fields[3][1].__class__.__name__, "ManyToManyField")
self.assertEqual(book_state.options, {"verbose_name": "tome", "db_table": "test_tome"}) self.assertEqual(book_state.options, {"verbose_name": "tome", "db_table": "test_tome"})
self.assertEqual(book_state.bases, (models.Model, )) self.assertEqual(book_state.bases, (models.Model, ))
@ -257,7 +257,7 @@ class StateTests(SimpleTestCase):
new_apps = project_state.apps new_apps = project_state.apps
self.assertEqual(new_apps.get_model("migrations", "Tag")._meta.get_field("name").max_length, 100) self.assertEqual(new_apps.get_model("migrations", "Tag")._meta.get_field("name").max_length, 100)
self.assertEqual(new_apps.get_model("migrations", "Tag")._meta.get_field("hidden").null, False) self.assertIs(new_apps.get_model("migrations", "Tag")._meta.get_field("hidden").null, False)
self.assertEqual(len(new_apps.get_model("migrations", "SubTag")._meta.local_fields), 2) self.assertEqual(len(new_apps.get_model("migrations", "SubTag")._meta.local_fields), 2)
@ -597,8 +597,8 @@ class StateTests(SimpleTestCase):
other_state = project_state.clone() other_state = project_state.clone()
self.assertEqual(project_state, project_state) self.assertEqual(project_state, project_state)
self.assertEqual(project_state, other_state) self.assertEqual(project_state, other_state)
self.assertEqual(project_state != project_state, False) self.assertIs(project_state != project_state, False)
self.assertEqual(project_state != other_state, False) self.assertIs(project_state != other_state, False)
self.assertNotEqual(project_state.apps, other_state.apps) self.assertNotEqual(project_state.apps, other_state.apps)
# Make a very small change (max_len 99) and see if that affects it # Make a very small change (max_len 99) and see if that affects it
@ -615,7 +615,7 @@ class StateTests(SimpleTestCase):
None, None,
)) ))
self.assertNotEqual(project_state, other_state) self.assertNotEqual(project_state, other_state)
self.assertEqual(project_state == other_state, False) self.assertIs(project_state == other_state, False)
def test_dangling_references_throw_error(self): def test_dangling_references_throw_error(self):
new_apps = Apps() new_apps = Apps()
@ -886,8 +886,8 @@ class ModelStateTests(SimpleTestCase):
self.assertEqual(author_state.name, 'Author') self.assertEqual(author_state.name, 'Author')
self.assertEqual([x for x, y in author_state.fields], ['id', 'name', 'bio', 'age']) self.assertEqual([x for x, y in author_state.fields], ['id', 'name', 'bio', 'age'])
self.assertEqual(author_state.fields[1][1].max_length, 255) self.assertEqual(author_state.fields[1][1].max_length, 255)
self.assertEqual(author_state.fields[2][1].null, False) self.assertIs(author_state.fields[2][1].null, False)
self.assertEqual(author_state.fields[3][1].null, True) self.assertIs(author_state.fields[3][1].null, True)
self.assertEqual(author_state.options, {'swappable': 'TEST_SWAPPABLE_MODEL'}) self.assertEqual(author_state.options, {'swappable': 'TEST_SWAPPABLE_MODEL'})
self.assertEqual(author_state.bases, (models.Model, )) self.assertEqual(author_state.bases, (models.Model, ))
self.assertEqual(author_state.managers, []) self.assertEqual(author_state.managers, [])

View File

@ -7,13 +7,13 @@ from .models import BooleanModel, FksToBooleans, NullBooleanModel
class BooleanFieldTests(TestCase): class BooleanFieldTests(TestCase):
def _test_get_prep_value(self, f): def _test_get_prep_value(self, f):
self.assertEqual(f.get_prep_value(True), True) self.assertIs(f.get_prep_value(True), True)
self.assertEqual(f.get_prep_value('1'), True) self.assertIs(f.get_prep_value('1'), True)
self.assertEqual(f.get_prep_value(1), True) self.assertIs(f.get_prep_value(1), True)
self.assertEqual(f.get_prep_value(False), False) self.assertIs(f.get_prep_value(False), False)
self.assertEqual(f.get_prep_value('0'), False) self.assertIs(f.get_prep_value('0'), False)
self.assertEqual(f.get_prep_value(0), False) self.assertIs(f.get_prep_value(0), False)
self.assertEqual(f.get_prep_value(None), None) self.assertIsNone(f.get_prep_value(None))
def _test_to_python(self, f): def _test_to_python(self, f):
self.assertIs(f.to_python(1), True) self.assertIs(f.to_python(1), True)
@ -43,19 +43,19 @@ class BooleanFieldTests(TestCase):
def test_return_type(self): def test_return_type(self):
b = BooleanModel.objects.create(bfield=True) b = BooleanModel.objects.create(bfield=True)
b.refresh_from_db() b.refresh_from_db()
self.assertEqual(b.bfield, True) self.assertIs(b.bfield, True)
b2 = BooleanModel.objects.create(bfield=False) b2 = BooleanModel.objects.create(bfield=False)
b2.refresh_from_db() b2.refresh_from_db()
self.assertEqual(b2.bfield, False) self.assertIs(b2.bfield, False)
b3 = NullBooleanModel.objects.create(nbfield=True) b3 = NullBooleanModel.objects.create(nbfield=True)
b3.refresh_from_db() b3.refresh_from_db()
self.assertEqual(b3.nbfield, True) self.assertIs(b3.nbfield, True)
b4 = NullBooleanModel.objects.create(nbfield=False) b4 = NullBooleanModel.objects.create(nbfield=False)
b4.refresh_from_db() b4.refresh_from_db()
self.assertEqual(b4.nbfield, False) self.assertIs(b4.nbfield, False)
# When an extra clause exists, the boolean conversions are applied with # When an extra clause exists, the boolean conversions are applied with
# an offset (#13293). # an offset (#13293).
@ -75,16 +75,16 @@ class BooleanFieldTests(TestCase):
# select_related('fk_field_name') # select_related('fk_field_name')
ma = FksToBooleans.objects.select_related('bf').get(pk=m1.id) ma = FksToBooleans.objects.select_related('bf').get(pk=m1.id)
self.assertEqual(ma.bf.bfield, True) self.assertIs(ma.bf.bfield, True)
self.assertEqual(ma.nbf.nbfield, True) self.assertIs(ma.nbf.nbfield, True)
# select_related() # select_related()
mb = FksToBooleans.objects.select_related().get(pk=m1.id) mb = FksToBooleans.objects.select_related().get(pk=m1.id)
mc = FksToBooleans.objects.select_related().get(pk=m2.id) mc = FksToBooleans.objects.select_related().get(pk=m2.id)
self.assertEqual(mb.bf.bfield, True) self.assertIs(mb.bf.bfield, True)
self.assertEqual(mb.nbf.nbfield, True) self.assertIs(mb.nbf.nbfield, True)
self.assertEqual(mc.bf.bfield, False) self.assertIs(mc.bf.bfield, False)
self.assertEqual(mc.nbf.nbfield, False) self.assertIs(mc.nbf.nbfield, False)
def test_null_default(self): def test_null_default(self):
""" """

View File

@ -25,11 +25,11 @@ class DecimalFieldTests(TestCase):
f = models.DecimalField(max_digits=5, decimal_places=1) f = models.DecimalField(max_digits=5, decimal_places=1)
self.assertEqual(f._format(f.to_python(2)), '2.0') self.assertEqual(f._format(f.to_python(2)), '2.0')
self.assertEqual(f._format(f.to_python('2.6')), '2.6') self.assertEqual(f._format(f.to_python('2.6')), '2.6')
self.assertEqual(f._format(None), None) self.assertIsNone(f._format(None))
def test_get_prep_value(self): def test_get_prep_value(self):
f = models.DecimalField(max_digits=5, decimal_places=1) f = models.DecimalField(max_digits=5, decimal_places=1)
self.assertEqual(f.get_prep_value(None), None) self.assertIsNone(f.get_prep_value(None))
self.assertEqual(f.get_prep_value('2.4'), Decimal('2.4')) self.assertEqual(f.get_prep_value('2.4'), Decimal('2.4'))
def test_filter_with_strings(self): def test_filter_with_strings(self):

View File

@ -20,7 +20,7 @@ class TestSaveLoad(TestCase):
def test_create_empty(self): def test_create_empty(self):
NullDurationModel.objects.create() NullDurationModel.objects.create()
loaded = NullDurationModel.objects.get() loaded = NullDurationModel.objects.get()
self.assertEqual(loaded.field, None) self.assertIsNone(loaded.field)
def test_fractional_seconds(self): def test_fractional_seconds(self):
value = datetime.timedelta(seconds=2.05) value = datetime.timedelta(seconds=2.05)

View File

@ -120,18 +120,18 @@ class ImageFieldTests(ImageFieldTestMixin, TestCase):
p1.mugshot.save("mug", self.file1) p1.mugshot.save("mug", self.file1)
p2 = self.PersonModel(name="Bob") p2 = self.PersonModel(name="Bob")
p2.mugshot.save("mug", self.file2) p2.mugshot.save("mug", self.file2)
self.assertEqual(p1.mugshot == p2.mugshot, False) self.assertIs(p1.mugshot == p2.mugshot, False)
self.assertEqual(p1.mugshot != p2.mugshot, True) self.assertIs(p1.mugshot != p2.mugshot, True)
# Test again with an instance fetched from the db. # Test again with an instance fetched from the db.
p1_db = self.PersonModel.objects.get(name="Joe") p1_db = self.PersonModel.objects.get(name="Joe")
self.assertEqual(p1_db.mugshot == p2.mugshot, False) self.assertIs(p1_db.mugshot == p2.mugshot, False)
self.assertEqual(p1_db.mugshot != p2.mugshot, True) self.assertIs(p1_db.mugshot != p2.mugshot, True)
# Instance from db should match the local instance. # Instance from db should match the local instance.
self.assertEqual(p1_db.mugshot == p1.mugshot, True) self.assertIs(p1_db.mugshot == p1.mugshot, True)
self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot)) self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot))
self.assertEqual(p1_db.mugshot != p1.mugshot, False) self.assertIs(p1_db.mugshot != p1.mugshot, False)
def test_instantiate_missing(self): def test_instantiate_missing(self):
""" """
@ -165,11 +165,11 @@ class ImageFieldTests(ImageFieldTestMixin, TestCase):
# Get a "clean" model instance # Get a "clean" model instance
p = self.PersonModel.objects.get(name="Joan") p = self.PersonModel.objects.get(name="Joan")
# It won't have an opened file. # It won't have an opened file.
self.assertEqual(p.mugshot.closed, True) self.assertIs(p.mugshot.closed, True)
# After asking for the size, the file should still be closed. # After asking for the size, the file should still be closed.
p.mugshot.size p.mugshot.size
self.assertEqual(p.mugshot.closed, True) self.assertIs(p.mugshot.closed, True)
def test_pickle(self): def test_pickle(self):
""" """
@ -213,7 +213,7 @@ class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase):
# attr_class, a TestImageFieldFile, with name == None, which will # attr_class, a TestImageFieldFile, with name == None, which will
# cause it to evaluate as False. # cause it to evaluate as False.
self.assertIsInstance(p.mugshot, TestImageFieldFile) self.assertIsInstance(p.mugshot, TestImageFieldFile)
self.assertEqual(bool(p.mugshot), False) self.assertFalse(p.mugshot)
# Test setting a fresh created model instance. # Test setting a fresh created model instance.
p = self.PersonModel(name='Joe') p = self.PersonModel(name='Joe')
@ -235,7 +235,7 @@ class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase):
""" """
p = self.PersonModel() p = self.PersonModel()
self.assertIsInstance(p.mugshot, TestImageFieldFile) self.assertIsInstance(p.mugshot, TestImageFieldFile)
self.assertEqual(bool(p.mugshot), False) self.assertFalse(p.mugshot)
def test_assignment_to_None(self): def test_assignment_to_None(self):
""" """
@ -284,23 +284,23 @@ class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase):
# Bug 11084: Dimensions should not get recalculated if file is # Bug 11084: Dimensions should not get recalculated if file is
# coming from the database. We test this by checking if the file # coming from the database. We test this by checking if the file
# was opened. # was opened.
self.assertEqual(p.mugshot.was_opened, False) self.assertIs(p.mugshot.was_opened, False)
self.check_dimensions(p, 4, 8) self.check_dimensions(p, 4, 8)
# After checking dimensions on the image field, the file will have # After checking dimensions on the image field, the file will have
# opened. # opened.
self.assertEqual(p.mugshot.was_opened, True) self.assertIs(p.mugshot.was_opened, True)
# Dimensions should now be cached, and if we reset was_opened and # Dimensions should now be cached, and if we reset was_opened and
# check dimensions again, the file should not have opened. # check dimensions again, the file should not have opened.
p.mugshot.was_opened = False p.mugshot.was_opened = False
self.check_dimensions(p, 4, 8) self.check_dimensions(p, 4, 8)
self.assertEqual(p.mugshot.was_opened, False) self.assertIs(p.mugshot.was_opened, False)
# If we assign a new image to the instance, the dimensions should # If we assign a new image to the instance, the dimensions should
# update. # update.
p.mugshot = self.file2 p.mugshot = self.file2
self.check_dimensions(p, 8, 4) self.check_dimensions(p, 8, 4)
# Dimensions were recalculated, and hence file should have opened. # Dimensions were recalculated, and hence file should have opened.
self.assertEqual(p.mugshot.was_opened, True) self.assertIs(p.mugshot.was_opened, True)
@skipIf(Image is None, "Pillow is required to test ImageField") @skipIf(Image is None, "Pillow is required to test ImageField")
@ -419,22 +419,22 @@ class TwoImageFieldTests(ImageFieldTestMixin, TestCase):
# Bug 11084: Dimensions should not get recalculated if file is # Bug 11084: Dimensions should not get recalculated if file is
# coming from the database. We test this by checking if the file # coming from the database. We test this by checking if the file
# was opened. # was opened.
self.assertEqual(p.mugshot.was_opened, False) self.assertIs(p.mugshot.was_opened, False)
self.assertEqual(p.headshot.was_opened, False) self.assertIs(p.headshot.was_opened, False)
self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 4, 8, 'mugshot')
self.check_dimensions(p, 8, 4, 'headshot') self.check_dimensions(p, 8, 4, 'headshot')
# After checking dimensions on the image fields, the files will # After checking dimensions on the image fields, the files will
# have been opened. # have been opened.
self.assertEqual(p.mugshot.was_opened, True) self.assertIs(p.mugshot.was_opened, True)
self.assertEqual(p.headshot.was_opened, True) self.assertIs(p.headshot.was_opened, True)
# Dimensions should now be cached, and if we reset was_opened and # Dimensions should now be cached, and if we reset was_opened and
# check dimensions again, the file should not have opened. # check dimensions again, the file should not have opened.
p.mugshot.was_opened = False p.mugshot.was_opened = False
p.headshot.was_opened = False p.headshot.was_opened = False
self.check_dimensions(p, 4, 8, 'mugshot') self.check_dimensions(p, 4, 8, 'mugshot')
self.check_dimensions(p, 8, 4, 'headshot') self.check_dimensions(p, 8, 4, 'headshot')
self.assertEqual(p.mugshot.was_opened, False) self.assertIs(p.mugshot.was_opened, False)
self.assertEqual(p.headshot.was_opened, False) self.assertIs(p.headshot.was_opened, False)
# If we assign a new image to the instance, the dimensions should # If we assign a new image to the instance, the dimensions should
# update. # update.
@ -443,5 +443,5 @@ class TwoImageFieldTests(ImageFieldTestMixin, TestCase):
self.check_dimensions(p, 8, 4, 'mugshot') self.check_dimensions(p, 8, 4, 'mugshot')
self.check_dimensions(p, 4, 8, 'headshot') self.check_dimensions(p, 4, 8, 'headshot')
# Dimensions were recalculated, and hence file should have opened. # Dimensions were recalculated, and hence file should have opened.
self.assertEqual(p.mugshot.was_opened, True) self.assertIs(p.mugshot.was_opened, True)
self.assertEqual(p.headshot.was_opened, True) self.assertIs(p.headshot.was_opened, True)

View File

@ -37,7 +37,7 @@ class TestSaveLoad(TestCase):
def test_null_handling(self): def test_null_handling(self):
NullableUUIDModel.objects.create(field=None) NullableUUIDModel.objects.create(field=None)
loaded = NullableUUIDModel.objects.get() loaded = NullableUUIDModel.objects.get()
self.assertEqual(loaded.field, None) self.assertIsNone(loaded.field)
def test_pk_validated(self): def test_pk_validated(self):
with self.assertRaisesMessage(TypeError, 'is not a valid UUID'): with self.assertRaisesMessage(TypeError, 'is not a valid UUID'):

View File

@ -70,7 +70,7 @@ class ChoicesTests(SimpleTestCase):
self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value self.assertEqual(Whiz(c=1).get_c_display(), 'First') # A nested value
self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value self.assertEqual(Whiz(c=0).get_c_display(), 'Other') # A top level value
self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value
self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value self.assertIsNone(Whiz(c=None).get_c_display()) # Blank value
self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value
def test_iterator_choices(self): def test_iterator_choices(self):
@ -79,7 +79,7 @@ class ChoicesTests(SimpleTestCase):
""" """
self.assertEqual(WhizIter(c=1).c, 1) # A nested value self.assertEqual(WhizIter(c=1).c, 1) # A nested value
self.assertEqual(WhizIter(c=9).c, 9) # Invalid value self.assertEqual(WhizIter(c=9).c, 9) # Invalid value
self.assertEqual(WhizIter(c=None).c, None) # Blank value self.assertIsNone(WhizIter(c=None).c) # Blank value
self.assertEqual(WhizIter(c='').c, '') # Empty value self.assertEqual(WhizIter(c='').c, '') # Empty value
def test_empty_iterator_choices(self): def test_empty_iterator_choices(self):
@ -88,5 +88,5 @@ class ChoicesTests(SimpleTestCase):
""" """
self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value
self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value
self.assertEqual(WhizIterEmpty(c=None).c, None) # Blank value self.assertIsNone(WhizIterEmpty(c=None).c) # Blank value
self.assertEqual(WhizIterEmpty(c='').c, '') # Empty value self.assertEqual(WhizIterEmpty(c='').c, '') # Empty value

View File

@ -1877,12 +1877,12 @@ class ModelOneToOneFieldTests(TestCase):
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())
self.assertEqual(form.cleaned_data['publication'], None) self.assertIsNone(form.cleaned_data['publication'])
author = form.save() author = form.save()
# author object returned from form still retains original publication object # author object returned from form still retains original publication object
# that's why we need to retrieve it from database again # that's why we need to retrieve it from database again
new_author = Author.objects.get(pk=author.pk) new_author = Author.objects.get(pk=author.pk)
self.assertEqual(new_author.publication, None) self.assertIsNone(new_author.publication)
def test_assignment_of_none_null_false(self): def test_assignment_of_none_null_false(self):
class AuthorForm(forms.ModelForm): class AuthorForm(forms.ModelForm):
@ -1904,8 +1904,8 @@ class FileAndImageFieldTests(TestCase):
of the value of ``initial``. of the value of ``initial``.
""" """
f = forms.FileField(required=False) f = forms.FileField(required=False)
self.assertEqual(f.clean(False), False) self.assertIs(f.clean(False), False)
self.assertEqual(f.clean(False, 'initial'), False) self.assertIs(f.clean(False, 'initial'), False)
def test_clean_false_required(self): def test_clean_false_required(self):
""" """
@ -1939,7 +1939,7 @@ class FileAndImageFieldTests(TestCase):
self.assertIn('myfile-clear', six.text_type(form)) self.assertIn('myfile-clear', six.text_type(form))
form = DocumentForm(instance=doc, data={'myfile-clear': 'true'}) form = DocumentForm(instance=doc, data={'myfile-clear': 'true'})
doc = form.save(commit=False) doc = form.save(commit=False)
self.assertEqual(bool(doc.myfile), False) self.assertFalse(doc.myfile)
def test_clear_and_file_contradiction(self): def test_clear_and_file_contradiction(self):
""" """
@ -2212,8 +2212,8 @@ class FileAndImageFieldTests(TestCase):
self.assertTrue(f.is_valid()) self.assertTrue(f.is_valid())
instance = f.save() instance = f.save()
self.assertEqual(instance.image.name, expected_null_imagefield_repr) self.assertEqual(instance.image.name, expected_null_imagefield_repr)
self.assertEqual(instance.width, None) self.assertIsNone(instance.width)
self.assertEqual(instance.height, None) self.assertIsNone(instance.height)
f = OptionalImageFileForm( f = OptionalImageFileForm(
data={'description': 'And a final one'}, data={'description': 'And a final one'},

View File

@ -65,7 +65,7 @@ class DeletionTests(TestCase):
} }
formset = PoetFormSet(data, queryset=Poet.objects.all()) formset = PoetFormSet(data, queryset=Poet.objects.all())
# Make sure this form doesn't pass validation. # Make sure this form doesn't pass validation.
self.assertEqual(formset.is_valid(), False) self.assertIs(formset.is_valid(), False)
self.assertEqual(Poet.objects.count(), 1) self.assertEqual(Poet.objects.count(), 1)
# Then make sure that it *does* pass validation and delete the object, # Then make sure that it *does* pass validation and delete the object,
@ -74,7 +74,7 @@ class DeletionTests(TestCase):
data['form-1-DELETE'] = 'on' data['form-1-DELETE'] = 'on'
data['form-2-DELETE'] = 'on' data['form-2-DELETE'] = 'on'
formset = PoetFormSet(data, queryset=Poet.objects.all()) formset = PoetFormSet(data, queryset=Poet.objects.all())
self.assertEqual(formset.is_valid(), True) self.assertIs(formset.is_valid(), True)
formset.save() formset.save()
self.assertEqual(Poet.objects.count(), 0) self.assertEqual(Poet.objects.count(), 0)
@ -94,14 +94,14 @@ class DeletionTests(TestCase):
} }
formset = PoetFormSet(data, queryset=Poet.objects.all()) formset = PoetFormSet(data, queryset=Poet.objects.all())
# Make sure this form doesn't pass validation. # Make sure this form doesn't pass validation.
self.assertEqual(formset.is_valid(), False) self.assertIs(formset.is_valid(), False)
self.assertEqual(Poet.objects.count(), 1) self.assertEqual(Poet.objects.count(), 1)
# Then make sure that it *does* pass validation and delete the object, # Then make sure that it *does* pass validation and delete the object,
# even though the data isn't actually valid. # even though the data isn't actually valid.
data['form-0-DELETE'] = 'on' data['form-0-DELETE'] = 'on'
formset = PoetFormSet(data, queryset=Poet.objects.all()) formset = PoetFormSet(data, queryset=Poet.objects.all())
self.assertEqual(formset.is_valid(), True) self.assertIs(formset.is_valid(), True)
formset.save() formset.save()
self.assertEqual(Poet.objects.count(), 0) self.assertEqual(Poet.objects.count(), 0)

View File

@ -667,8 +667,8 @@ class QueryTestCase(TestCase):
charlie.set_unusable_password() charlie.set_unusable_password()
# initially, no db assigned # initially, no db assigned
self.assertEqual(new_bob_profile._state.db, None) self.assertIsNone(new_bob_profile._state.db)
self.assertEqual(charlie._state.db, None) self.assertIsNone(charlie._state.db)
# old object comes from 'other', so the new object is set to use 'other'... # old object comes from 'other', so the new object is set to use 'other'...
new_bob_profile.user = bob new_bob_profile.user = bob
@ -820,7 +820,7 @@ class QueryTestCase(TestCase):
# base object. # base object.
review3 = Review(source="Python Daily") review3 = Review(source="Python Daily")
# initially, no db assigned # initially, no db assigned
self.assertEqual(review3._state.db, None) self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use 'other'... # Dive comes from 'other', so review3 is set to use 'other'...
review3.content_object = dive review3.content_object = dive
@ -1178,8 +1178,8 @@ class RouterTestCase(TestCase):
chris = Person(name="Chris Mills") chris = Person(name="Chris Mills")
html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) html5 = Book(title="Dive into HTML5", published=datetime.date(2010, 3, 15))
# initially, no db assigned # initially, no db assigned
self.assertEqual(chris._state.db, None) self.assertIsNone(chris._state.db)
self.assertEqual(html5._state.db, None) self.assertIsNone(html5._state.db)
# old object comes from 'other', so the new object is set to use the # old object comes from 'other', so the new object is set to use the
# source of 'other'... # source of 'other'...
@ -1432,7 +1432,7 @@ class RouterTestCase(TestCase):
# base object. # base object.
review3 = Review(source="Python Daily") review3 = Review(source="Python Daily")
# initially, no db assigned # initially, no db assigned
self.assertEqual(review3._state.db, None) self.assertIsNone(review3._state.db)
# Dive comes from 'other', so review3 is set to use the source of 'other'... # Dive comes from 'other', so review3 is set to use the source of 'other'...
review3.content_object = dive review3.content_object = dive

View File

@ -24,7 +24,7 @@ class NullFkTests(TestCase):
# test for #7369. # test for #7369.
c = Comment.objects.select_related().get(id=c1.id) c = Comment.objects.select_related().get(id=c1.id)
self.assertEqual(c.post, p) self.assertEqual(c.post, p)
self.assertEqual(Comment.objects.select_related().get(id=c2.id).post, None) self.assertIsNone(Comment.objects.select_related().get(id=c2.id).post)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info').all(), Comment.objects.select_related('post__forum__system_info').all(),

View File

@ -68,7 +68,7 @@ class TestSaveLoad(PostgreSQLTestCase):
instance = NullableIntegerArrayModel() instance = NullableIntegerArrayModel()
instance.save() instance.save()
loaded = NullableIntegerArrayModel.objects.get(pk=instance.pk) loaded = NullableIntegerArrayModel.objects.get(pk=instance.pk)
self.assertEqual(loaded.field, None) self.assertIsNone(loaded.field)
self.assertEqual(instance.field, loaded.field) self.assertEqual(instance.field, loaded.field)
def test_null_handling(self): def test_null_handling(self):

View File

@ -31,7 +31,7 @@ class SimpleTests(PostgreSQLTestCase):
instance = HStoreModel(field=None) instance = HStoreModel(field=None)
instance.save() instance.save()
reloaded = HStoreModel.objects.get() reloaded = HStoreModel.objects.get()
self.assertEqual(reloaded.field, None) self.assertIsNone(reloaded.field)
def test_value_null(self): def test_value_null(self):
value = {'a': None} value = {'a': None}

View File

@ -33,7 +33,7 @@ class TestSaveLoad(TestCase):
instance = JSONModel() instance = JSONModel()
instance.save() instance.save()
loaded = JSONModel.objects.get() loaded = JSONModel.objects.get()
self.assertEqual(loaded.field, None) self.assertIsNone(loaded.field)
def test_empty_object(self): def test_empty_object(self):
instance = JSONModel(field={}) instance = JSONModel(field={})
@ -51,7 +51,7 @@ class TestSaveLoad(TestCase):
instance = JSONModel(field=True) instance = JSONModel(field=True)
instance.save() instance.save()
loaded = JSONModel.objects.get() loaded = JSONModel.objects.get()
self.assertEqual(loaded.field, True) self.assertIs(loaded.field, True)
def test_string(self): def test_string(self):
instance = JSONModel(field='why?') instance = JSONModel(field='why?')
@ -247,7 +247,7 @@ class TestFormField(PostgreSQLTestCase):
def test_valid_empty(self): def test_valid_empty(self):
field = forms.JSONField(required=False) field = forms.JSONField(required=False)
value = field.clean('') value = field.clean('')
self.assertEqual(value, None) self.assertIsNone(value)
def test_invalid(self): def test_invalid(self):
field = forms.JSONField() field = forms.JSONField()

View File

@ -58,7 +58,7 @@ class TestSaveLoad(PostgreSQLTestCase):
instance.save() instance.save()
loaded = RangesModel.objects.get() loaded = RangesModel.objects.get()
self.assertEqual(r, loaded.floats) self.assertEqual(r, loaded.floats)
self.assertTrue(10 in loaded.floats) self.assertIn(10, loaded.floats)
def test_unbounded(self): def test_unbounded(self):
r = NumericRange(None, None, '()') r = NumericRange(None, None, '()')
@ -313,7 +313,7 @@ class TestSerialization(PostgreSQLTestCase):
instance = list(serializers.deserialize('json', self.test_data))[0].object instance = list(serializers.deserialize('json', self.test_data))[0].object
self.assertEqual(instance.ints, NumericRange(0, 10)) self.assertEqual(instance.ints, NumericRange(0, 10))
self.assertEqual(instance.floats, NumericRange(empty=True)) self.assertEqual(instance.floats, NumericRange(empty=True))
self.assertEqual(instance.bigints, None) self.assertIsNone(instance.bigints)
self.assertEqual(instance.dates, DateRange(self.lower_date, self.upper_date)) self.assertEqual(instance.dates, DateRange(self.lower_date, self.upper_date))
self.assertEqual(instance.timestamps, DateTimeTZRange(self.lower_dt, self.upper_dt)) self.assertEqual(instance.timestamps, DateTimeTZRange(self.lower_dt, self.upper_dt))
@ -409,7 +409,7 @@ class TestFormField(PostgreSQLTestCase):
def test_none(self): def test_none(self):
field = pg_forms.IntegerRangeField(required=False) field = pg_forms.IntegerRangeField(required=False)
value = field.clean(['', '']) value = field.clean(['', ''])
self.assertEqual(value, None) self.assertIsNone(value)
def test_rendering(self): def test_rendering(self):
class RangeForm(forms.Form): class RangeForm(forms.Form):

View File

@ -1838,8 +1838,8 @@ class Queries6Tests(TestCase):
self.assertEqual(repr(next(i1)), '<Tag: t3>') self.assertEqual(repr(next(i1)), '<Tag: t3>')
qs = X.objects.all() qs = X.objects.all()
self.assertEqual(bool(qs), False) self.assertFalse(qs)
self.assertEqual(bool(qs), False) self.assertFalse(qs)
def test_nested_queries_sql(self): def test_nested_queries_sql(self):
# Nested queries should not evaluate the inner query as part of constructing the # Nested queries should not evaluate the inner query as part of constructing the
@ -1992,22 +1992,22 @@ class QuerysetOrderedTests(unittest.TestCase):
""" """
def test_no_default_or_explicit_ordering(self): def test_no_default_or_explicit_ordering(self):
self.assertEqual(Annotation.objects.all().ordered, False) self.assertIs(Annotation.objects.all().ordered, False)
def test_cleared_default_ordering(self): def test_cleared_default_ordering(self):
self.assertEqual(Tag.objects.all().ordered, True) self.assertIs(Tag.objects.all().ordered, True)
self.assertEqual(Tag.objects.all().order_by().ordered, False) self.assertIs(Tag.objects.all().order_by().ordered, False)
def test_explicit_ordering(self): def test_explicit_ordering(self):
self.assertEqual(Annotation.objects.all().order_by('id').ordered, True) self.assertIs(Annotation.objects.all().order_by('id').ordered, True)
def test_order_by_extra(self): def test_order_by_extra(self):
self.assertEqual(Annotation.objects.all().extra(order_by=['id']).ordered, True) self.assertIs(Annotation.objects.all().extra(order_by=['id']).ordered, True)
def test_annotated_ordering(self): def test_annotated_ordering(self):
qs = Annotation.objects.annotate(num_notes=Count('notes')) qs = Annotation.objects.annotate(num_notes=Count('notes'))
self.assertEqual(qs.ordered, False) self.assertIs(qs.ordered, False)
self.assertEqual(qs.order_by('num_notes').ordered, True) self.assertIs(qs.order_by('num_notes').ordered, True)
@skipUnlessDBFeature('allow_sliced_subqueries') @skipUnlessDBFeature('allow_sliced_subqueries')

View File

@ -215,9 +215,9 @@ class RawQueryTests(TestCase):
def test_missing_fields(self): def test_missing_fields(self):
query = "SELECT id, first_name, dob FROM raw_query_author" query = "SELECT id, first_name, dob FROM raw_query_author"
for author in Author.objects.raw(query): for author in Author.objects.raw(query):
self.assertNotEqual(author.first_name, None) self.assertIsNotNone(author.first_name)
# last_name isn't given, but it will be retrieved on demand # last_name isn't given, but it will be retrieved on demand
self.assertNotEqual(author.last_name, None) self.assertIsNotNone(author.last_name)
def test_missing_fields_without_PK(self): def test_missing_fields_without_PK(self):
query = "SELECT first_name, dob FROM raw_query_author" query = "SELECT first_name, dob FROM raw_query_author"

View File

@ -1700,7 +1700,7 @@ class SchemaTests(TransactionTestCase):
editor.create_model(Author) editor.create_model(Author)
# Create a row # Create a row
Author.objects.create(name='Anonymous1') Author.objects.create(name='Anonymous1')
self.assertEqual(Author.objects.get().height, None) self.assertIsNone(Author.objects.get().height)
old_field = Author._meta.get_field('height') old_field = Author._meta.get_field('height')
# The default from the new field is used in updating existing rows. # The default from the new field is used in updating existing rows.
new_field = IntegerField(blank=True, default=42) new_field = IntegerField(blank=True, default=42)

View File

@ -145,7 +145,7 @@ class SelectRelatedTests(TestCase):
def test_none_clears_list(self): def test_none_clears_list(self):
queryset = Species.objects.select_related('genus').select_related(None) queryset = Species.objects.select_related('genus').select_related(None)
self.assertEqual(queryset.query.select_related, False) self.assertIs(queryset.query.select_related, False)
def test_chaining(self): def test_chaining(self):
parent_1, parent_2 = Species.objects.all()[:2] parent_1, parent_2 = Species.objects.all()[:2]

View File

@ -66,7 +66,7 @@ def natural_key_test(format, self):
self.assertEqual(books[0].object.title, book1['title']) self.assertEqual(books[0].object.title, book1['title'])
self.assertEqual(books[0].object.pk, adrian.pk) self.assertEqual(books[0].object.pk, adrian.pk)
self.assertEqual(books[1].object.title, book2['title']) self.assertEqual(books[1].object.title, book2['title'])
self.assertEqual(books[1].object.pk, None) self.assertIsNone(books[1].object.pk)
# Dynamically register tests for each serializer # Dynamically register tests for each serializer

View File

@ -262,7 +262,7 @@ class SerializersTestBase(object):
self.assertFalse(pk_value) self.assertFalse(pk_value)
cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0].object cat_obj = list(serializers.deserialize(self.serializer_name, serial_str))[0].object
self.assertEqual(cat_obj.id, None) self.assertIsNone(cat_obj.id)
def test_float_serialization(self): def test_float_serialization(self):
"""Tests that float values serialize and deserialize intact""" """Tests that float values serialize and deserialize intact"""

View File

@ -59,7 +59,7 @@ class SessionTestsMixin(object):
self.assertFalse(self.session.accessed) self.assertFalse(self.session.accessed)
def test_get_empty(self): def test_get_empty(self):
self.assertEqual(self.session.get('cat'), None) self.assertIsNone(self.session.get('cat'))
def test_store(self): def test_store(self):
self.session['cat'] = "dog" self.session['cat'] = "dog"
@ -75,7 +75,7 @@ class SessionTestsMixin(object):
self.assertEqual(self.session.pop('some key'), 'exists') self.assertEqual(self.session.pop('some key'), 'exists')
self.assertTrue(self.session.accessed) self.assertTrue(self.session.accessed)
self.assertTrue(self.session.modified) self.assertTrue(self.session.modified)
self.assertEqual(self.session.get('some key'), None) self.assertIsNone(self.session.get('some key'))
def test_pop_default(self): def test_pop_default(self):
self.assertEqual(self.session.pop('some key', 'does not exist'), self.assertEqual(self.session.pop('some key', 'does not exist'),
@ -206,7 +206,7 @@ class SessionTestsMixin(object):
"Middleware may be saving cache items without namespaces." "Middleware may be saving cache items without namespaces."
) )
self.assertNotEqual(session.session_key, '1') self.assertNotEqual(session.session_key, '1')
self.assertEqual(session.get('cat'), None) self.assertIsNone(session.get('cat'))
session.delete() session.delete()
finally: finally:
# Some backends leave a stale cache entry for the invalid # Some backends leave a stale cache entry for the invalid
@ -479,7 +479,7 @@ class CustomDatabaseSessionTests(DatabaseSessionTests):
# Make sure that save() on an existing session did the right job. # Make sure that save() on an existing session did the right job.
s = self.model.objects.get(session_key=self.session.session_key) s = self.model.objects.get(session_key=self.session.session_key)
self.assertEqual(s.account_id, None) self.assertIsNone(s.account_id)
class CacheDBSessionTests(SessionTestsMixin, TestCase): class CacheDBSessionTests(SessionTestsMixin, TestCase):
@ -605,7 +605,7 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
def test_default_cache(self): def test_default_cache(self):
self.session.save() self.session.save()
self.assertNotEqual(caches['default'].get(self.session.cache_key), None) self.assertIsNotNone(caches['default'].get(self.session.cache_key))
@override_settings(CACHES={ @override_settings(CACHES={
'default': { 'default': {
@ -621,8 +621,8 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase):
self.session = self.backend() self.session = self.backend()
self.session.save() self.session.save()
self.assertEqual(caches['default'].get(self.session.cache_key), None) self.assertIsNone(caches['default'].get(self.session.cache_key))
self.assertNotEqual(caches['sessions'].get(self.session.cache_key), None) self.assertIsNotNone(caches['sessions'].get(self.session.cache_key))
def test_create_and_save(self): def test_create_and_save(self):
self.session = self.backend() self.session = self.backend()

View File

@ -221,7 +221,7 @@ class SettingsTests(SimpleTestCase):
getattr(settings, 'TEST') getattr(settings, 'TEST')
with self.settings(TEST='override'): with self.settings(TEST='override'):
self.assertEqual(self.testvalue, 'override') self.assertEqual(self.testvalue, 'override')
self.assertEqual(self.testvalue, None) self.assertIsNone(self.testvalue)
@override_settings(TEST='override') @override_settings(TEST='override')
def test_signal_callback_decorator(self): def test_signal_callback_decorator(self):
@ -403,24 +403,24 @@ class SecureProxySslHeaderTest(SimpleTestCase):
def test_none(self): def test_none(self):
self.settings_module.SECURE_PROXY_SSL_HEADER = None self.settings_module.SECURE_PROXY_SSL_HEADER = None
req = HttpRequest() req = HttpRequest()
self.assertEqual(req.is_secure(), False) self.assertIs(req.is_secure(), False)
def test_set_without_xheader(self): def test_set_without_xheader(self):
self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
req = HttpRequest() req = HttpRequest()
self.assertEqual(req.is_secure(), False) self.assertIs(req.is_secure(), False)
def test_set_with_xheader_wrong(self): def test_set_with_xheader_wrong(self):
self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
req = HttpRequest() req = HttpRequest()
req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'wrongvalue' req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'wrongvalue'
self.assertEqual(req.is_secure(), False) self.assertIs(req.is_secure(), False)
def test_set_with_xheader_right(self): def test_set_with_xheader_right(self):
self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https') self.settings_module.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')
req = HttpRequest() req = HttpRequest()
req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https' req.META['HTTP_X_FORWARDED_PROTOCOL'] = 'https'
self.assertEqual(req.is_secure(), True) self.assertIs(req.is_secure(), True)
class IsOverriddenTest(SimpleTestCase): class IsOverriddenTest(SimpleTestCase):

View File

@ -41,7 +41,7 @@ class SignedCookieTest(SimpleTestCase):
response.set_signed_cookie('c', 'hello') response.set_signed_cookie('c', 'hello')
request = HttpRequest() request = HttpRequest()
request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$' request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$'
self.assertEqual(request.get_signed_cookie('c', default=None), None) self.assertIsNone(request.get_signed_cookie('c', default=None))
def test_max_age_argument(self): def test_max_age_argument(self):
value = 'hello' value = 'hello'

View File

@ -214,7 +214,7 @@ class TestCollectionCachedStorage(TestHashedFiles, CollectionTestCase):
# clearing the cache to make sure we re-set it correctly in the url method # clearing the cache to make sure we re-set it correctly in the url method
storage.staticfiles_storage.hashed_files.clear() storage.staticfiles_storage.hashed_files.clear()
cached_name = storage.staticfiles_storage.hashed_files.get(cache_key) cached_name = storage.staticfiles_storage.hashed_files.get(cache_key)
self.assertEqual(cached_name, None) self.assertIsNone(cached_name)
self.assertEqual(self.hashed_file_path(name), hashed_name) self.assertEqual(self.hashed_file_path(name), hashed_name)
cached_name = storage.staticfiles_storage.hashed_files.get(cache_key) cached_name = storage.staticfiles_storage.hashed_files.get(cache_key)
self.assertEqual(cached_name, hashed_name) self.assertEqual(cached_name, hashed_name)

View File

@ -32,7 +32,7 @@ class Jinja2Tests(TemplateStringsTests):
def test_origin_from_string(self): def test_origin_from_string(self):
template = self.engine.from_string('Hello!\n') template = self.engine.from_string('Hello!\n')
self.assertEqual(template.origin.name, '<template>') self.assertEqual(template.origin.name, '<template>')
self.assertEqual(template.origin.template_name, None) self.assertIsNone(template.origin.template_name)
def test_self_context(self): def test_self_context(self):
""" """
@ -58,7 +58,7 @@ class Jinja2Tests(TemplateStringsTests):
self.assertEqual(debug['total'], 1) self.assertEqual(debug['total'], 1)
self.assertEqual(len(debug['source_lines']), 1) self.assertEqual(len(debug['source_lines']), 1)
self.assertTrue(debug['name'].endswith('syntax_error.html')) self.assertTrue(debug['name'].endswith('syntax_error.html'))
self.assertTrue('message' in debug) self.assertIn('message', debug)
def test_exception_debug_info_max_context(self): def test_exception_debug_info_max_context(self):
with self.assertRaises(TemplateSyntaxError) as e: with self.assertRaises(TemplateSyntaxError) as e:
@ -73,4 +73,4 @@ class Jinja2Tests(TemplateStringsTests):
self.assertEqual(debug['total'], 31) self.assertEqual(debug['total'], 31)
self.assertEqual(len(debug['source_lines']), 21) self.assertEqual(len(debug['source_lines']), 21)
self.assertTrue(debug['name'].endswith('syntax_error2.html')) self.assertTrue(debug['name'].endswith('syntax_error2.html'))
self.assertTrue('message' in debug) self.assertIn('message', debug)

View File

@ -5,7 +5,7 @@ from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase): class FunctionTests(SimpleTestCase):
def test_true(self): def test_true(self):
self.assertEqual(divisibleby(4, 2), True) self.assertIs(divisibleby(4, 2), True)
def test_false(self): def test_false(self):
self.assertEqual(divisibleby(4, 3), False) self.assertIs(divisibleby(4, 3), False)

View File

@ -67,9 +67,9 @@ class LengthIsTests(SimpleTestCase):
class FunctionTests(SimpleTestCase): class FunctionTests(SimpleTestCase):
def test_empty_list(self): def test_empty_list(self):
self.assertEqual(length_is([], 0), True) self.assertIs(length_is([], 0), True)
self.assertEqual(length_is([], 1), False) self.assertIs(length_is([], 1), False)
def test_string(self): def test_string(self):
self.assertEqual(length_is('a', 1), True) self.assertIs(length_is('a', 1), True)
self.assertEqual(length_is('a', 10), False) self.assertIs(length_is('a', 10), False)

View File

@ -193,10 +193,10 @@ class ContextTests(SimpleTestCase):
with warnings.catch_warnings(record=True) as warns: with warnings.catch_warnings(record=True) as warns:
warnings.simplefilter('always') warnings.simplefilter('always')
self.assertEqual(a.has_key('a'), True) self.assertIs(a.has_key('a'), True)
self.assertEqual(a.has_key('b'), False) self.assertIs(a.has_key('b'), False)
self.assertEqual(b.has_key('a'), True) self.assertIs(b.has_key('a'), True)
self.assertEqual(b.has_key('b'), False) self.assertIs(b.has_key('b'), False)
self.assertEqual(len(warns), 4) self.assertEqual(len(warns), 4)
self.assertEqual(str(warns[0].message), msg) self.assertEqual(str(warns[0].message), msg)

View File

@ -162,8 +162,8 @@ class NonRecursiveLoaderExtendsTests(SimpleTestCase):
self.assertEqual(output, 'base') self.assertEqual(output, 'base')
cache = engine.template_loaders[0].template_cache cache = engine.template_loaders[0].template_cache
self.assertTrue('base.html' in cache) self.assertIn('base.html', cache)
self.assertTrue('index.html' in cache) self.assertIn('index.html', cache)
# Render a second time from cache # Render a second time from cache
output = engine.render_to_string('index.html') output = engine.render_to_string('index.html')

View File

@ -112,7 +112,7 @@ class CachedLoaderTests(SimpleTestCase):
""" """
loader = self.engine.template_loaders[0] loader = self.engine.template_loaders[0]
self.assertFalse('missing.html' in loader.template_cache) self.assertNotIn('missing.html', loader.template_cache)
with self.assertRaises(TemplateDoesNotExist): with self.assertRaises(TemplateDoesNotExist):
loader.load_template("missing.html") loader.load_template("missing.html")

View File

@ -16,7 +16,7 @@ class TemplateTests(SimpleTestCase):
def test_string_origin(self): def test_string_origin(self):
template = Engine().from_string('string template') template = Engine().from_string('string template')
self.assertEqual(template.origin.name, UNKNOWN_SOURCE) self.assertEqual(template.origin.name, UNKNOWN_SOURCE)
self.assertEqual(template.origin.loader_name, None) self.assertIsNone(template.origin.loader_name)
self.assertEqual(template.source, 'string template') self.assertEqual(template.source, 'string template')
@override_settings(SETTINGS_MODULE=None) @override_settings(SETTINGS_MODULE=None)

View File

@ -730,7 +730,7 @@ class CustomTestClientTest(SimpleTestCase):
def test_custom_test_client(self): def test_custom_test_client(self):
"""A test case can specify a custom class for self.client.""" """A test case can specify a custom class for self.client."""
self.assertEqual(hasattr(self.client, "i_am_customized"), True) self.assertIs(hasattr(self.client, "i_am_customized"), True)
def _generic_view(request): def _generic_view(request):

View File

@ -1244,19 +1244,19 @@ class QueryStringTests(SimpleTestCase):
self.assertEqual(response.context['get-foo'], 'bang') self.assertEqual(response.context['get-foo'], 'bang')
response = method("/request_data/?foo=whiz", data={'bar': 'bang'}) response = method("/request_data/?foo=whiz", data={'bar': 'bang'})
self.assertEqual(response.context['get-foo'], None) self.assertIsNone(response.context['get-foo'])
self.assertEqual(response.context['get-bar'], 'bang') self.assertEqual(response.context['get-bar'], 'bang')
def test_post_like_requests(self): def test_post_like_requests(self):
# A POST-like request can pass a query string as data # A POST-like request can pass a query string as data
response = self.client.post("/request_data/", data={'foo': 'whiz'}) response = self.client.post("/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context['get-foo'], None) self.assertIsNone(response.context['get-foo'])
self.assertEqual(response.context['post-foo'], 'whiz') self.assertEqual(response.context['post-foo'], 'whiz')
# A POST-like request can pass a query string as part of the URL # A POST-like request can pass a query string as part of the URL
response = self.client.post("/request_data/?foo=whiz") response = self.client.post("/request_data/?foo=whiz")
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['post-foo'], None) self.assertIsNone(response.context['post-foo'])
# POST data provided in the URL augments actual form data # POST data provided in the URL augments actual form data
response = self.client.post("/request_data/?foo=whiz", data={'foo': 'bang'}) response = self.client.post("/request_data/?foo=whiz", data={'foo': 'bang'})
@ -1265,8 +1265,8 @@ class QueryStringTests(SimpleTestCase):
response = self.client.post("/request_data/?foo=whiz", data={'bar': 'bang'}) response = self.client.post("/request_data/?foo=whiz", data={'bar': 'bang'})
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['get-bar'], None) self.assertIsNone(response.context['get-bar'])
self.assertEqual(response.context['post-foo'], None) self.assertIsNone(response.context['post-foo'])
self.assertEqual(response.context['post-bar'], 'bang') self.assertEqual(response.context['post-bar'], 'bang')

View File

@ -588,7 +588,7 @@ class NewDatabaseTests(TestCase):
def test_null_datetime(self): def test_null_datetime(self):
# Regression test for #17294 # Regression test for #17294
e = MaybeEvent.objects.create() e = MaybeEvent.objects.create()
self.assertEqual(e.dt, None) self.assertIsNone(e.dt)
@override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True) @override_settings(TIME_ZONE='Africa/Nairobi', USE_TZ=True)

View File

@ -160,7 +160,7 @@ class CommandTests(SimpleTestCase):
def test_check_migrations(self): def test_check_migrations(self):
requires_migrations_checks = dance.Command.requires_migrations_checks requires_migrations_checks = dance.Command.requires_migrations_checks
self.assertEqual(requires_migrations_checks, False) self.assertIs(requires_migrations_checks, False)
try: try:
with mock.patch.object(BaseCommand, 'check_migrations') as check_migrations: with mock.patch.object(BaseCommand, 'check_migrations') as check_migrations:
management.call_command('dance', verbosity=0) management.call_command('dance', verbosity=0)

View File

@ -52,7 +52,7 @@ class MultiValueDictTests(SimpleTestCase):
with self.assertRaisesMessage(MultiValueDictKeyError, 'lastname'): with self.assertRaisesMessage(MultiValueDictKeyError, 'lastname'):
d.__getitem__('lastname') d.__getitem__('lastname')
self.assertEqual(d.get('lastname'), None) self.assertIsNone(d.get('lastname'))
self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent') self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent')
self.assertEqual(d.getlist('lastname'), []) self.assertEqual(d.getlist('lastname'), [])
self.assertEqual(d.getlist('doesnotexist', ['Adrian', 'Simon']), self.assertEqual(d.getlist('doesnotexist', ['Adrian', 'Simon']),

View File

@ -16,7 +16,7 @@ class DateParseTests(unittest.TestCase):
self.assertEqual(parse_date('2012-04-23'), date(2012, 4, 23)) self.assertEqual(parse_date('2012-04-23'), date(2012, 4, 23))
self.assertEqual(parse_date('2012-4-9'), date(2012, 4, 9)) self.assertEqual(parse_date('2012-4-9'), date(2012, 4, 9))
# Invalid inputs # Invalid inputs
self.assertEqual(parse_date('20120423'), None) self.assertIsNone(parse_date('20120423'))
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
parse_date('2012-04-56') parse_date('2012-04-56')
@ -27,7 +27,7 @@ class DateParseTests(unittest.TestCase):
self.assertEqual(parse_time('10:20:30.400'), time(10, 20, 30, 400000)) self.assertEqual(parse_time('10:20:30.400'), time(10, 20, 30, 400000))
self.assertEqual(parse_time('4:8:16'), time(4, 8, 16)) self.assertEqual(parse_time('4:8:16'), time(4, 8, 16))
# Invalid inputs # Invalid inputs
self.assertEqual(parse_time('091500'), None) self.assertIsNone(parse_time('091500'))
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
parse_time('09:15:90') parse_time('09:15:90')
@ -62,7 +62,7 @@ class DateParseTests(unittest.TestCase):
datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120)) datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120))
) )
# Invalid inputs # Invalid inputs
self.assertEqual(parse_datetime('20120423091500'), None) self.assertIsNone(parse_datetime('20120423091500'))
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
parse_datetime('2012-04-56T09:15:90') parse_datetime('2012-04-56T09:15:90')
@ -110,9 +110,9 @@ class DurationParseTests(unittest.TestCase):
self.assertEqual(parse_duration('-4 15:30'), timedelta(days=-4, minutes=15, seconds=30)) self.assertEqual(parse_duration('-4 15:30'), timedelta(days=-4, minutes=15, seconds=30))
def test_iso_8601(self): def test_iso_8601(self):
self.assertEqual(parse_duration('P4Y'), None) self.assertIsNone(parse_duration('P4Y'))
self.assertEqual(parse_duration('P4M'), None) self.assertIsNone(parse_duration('P4M'))
self.assertEqual(parse_duration('P4W'), None) self.assertIsNone(parse_duration('P4W'))
self.assertEqual(parse_duration('P4D'), timedelta(days=4)) self.assertEqual(parse_duration('P4D'), timedelta(days=4))
self.assertEqual(parse_duration('P0.5D'), timedelta(hours=12)) self.assertEqual(parse_duration('P0.5D'), timedelta(hours=12))
self.assertEqual(parse_duration('PT5H'), timedelta(hours=5)) self.assertEqual(parse_duration('PT5H'), timedelta(hours=5))

View File

@ -109,7 +109,7 @@ class FeedgeneratorTest(unittest.TestCase):
def test_feed_without_feed_url_gets_rendered_without_atom_link(self): def test_feed_without_feed_url_gets_rendered_without_atom_link(self):
feed = feedgenerator.Rss201rev2Feed('title', '/link/', 'descr') feed = feedgenerator.Rss201rev2Feed('title', '/link/', 'descr')
self.assertEqual(feed.feed['feed_url'], None) self.assertIsNone(feed.feed['feed_url'])
feed_content = feed.writeString('utf-8') feed_content = feed.writeString('utf-8')
self.assertNotIn('<atom:link', feed_content) self.assertNotIn('<atom:link', feed_content)
self.assertNotIn('href="/feed/"', feed_content) self.assertNotIn('href="/feed/"', feed_content)

View File

@ -29,7 +29,7 @@ class TestInspectMethods(unittest.TestCase):
self.assertEqual(inspect.get_func_full_args(Person.all_kinds), arguments) self.assertEqual(inspect.get_func_full_args(Person.all_kinds), arguments)
def test_func_accepts_var_args_has_var_args(self): def test_func_accepts_var_args_has_var_args(self):
self.assertEqual(inspect.func_accepts_var_args(Person.just_args), True) self.assertIs(inspect.func_accepts_var_args(Person.just_args), True)
def test_func_accepts_var_args_no_var_args(self): def test_func_accepts_var_args_no_var_args(self):
self.assertEqual(inspect.func_accepts_var_args(Person.one_argument), False) self.assertIs(inspect.func_accepts_var_args(Person.one_argument), False)

View File

@ -14,7 +14,7 @@ class TermColorTests(unittest.TestCase):
def test_simple_palette(self): def test_simple_palette(self):
self.assertEqual(parse_color_setting('light'), PALETTES[LIGHT_PALETTE]) self.assertEqual(parse_color_setting('light'), PALETTES[LIGHT_PALETTE])
self.assertEqual(parse_color_setting('dark'), PALETTES[DARK_PALETTE]) self.assertEqual(parse_color_setting('dark'), PALETTES[DARK_PALETTE])
self.assertEqual(parse_color_setting('nocolor'), None) self.assertIsNone(parse_color_setting('nocolor'))
def test_fg(self): def test_fg(self):
self.assertEqual( self.assertEqual(
@ -76,9 +76,9 @@ class TermColorTests(unittest.TestCase):
) )
def test_empty_definition(self): def test_empty_definition(self):
self.assertEqual(parse_color_setting(';'), None) self.assertIsNone(parse_color_setting(';'))
self.assertEqual(parse_color_setting('light;'), PALETTES[LIGHT_PALETTE]) self.assertEqual(parse_color_setting('light;'), PALETTES[LIGHT_PALETTE])
self.assertEqual(parse_color_setting(';;;'), None) self.assertIsNone(parse_color_setting(';;;'))
def test_empty_options(self): def test_empty_options(self):
self.assertEqual( self.assertEqual(
@ -95,23 +95,23 @@ class TermColorTests(unittest.TestCase):
) )
def test_bad_palette(self): def test_bad_palette(self):
self.assertEqual(parse_color_setting('unknown'), None) self.assertIsNone(parse_color_setting('unknown'))
def test_bad_role(self): def test_bad_role(self):
self.assertEqual(parse_color_setting('unknown='), None) self.assertIsNone(parse_color_setting('unknown='))
self.assertEqual(parse_color_setting('unknown=green'), None) self.assertIsNone(parse_color_setting('unknown=green'))
self.assertEqual( self.assertEqual(
parse_color_setting('unknown=green;sql_field=blue'), parse_color_setting('unknown=green;sql_field=blue'),
dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'}) dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'})
) )
def test_bad_color(self): def test_bad_color(self):
self.assertEqual(parse_color_setting('error='), None) self.assertIsNone(parse_color_setting('error='))
self.assertEqual( self.assertEqual(
parse_color_setting('error=;sql_field=blue'), parse_color_setting('error=;sql_field=blue'),
dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'}) dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'})
) )
self.assertEqual(parse_color_setting('error=unknown'), None) self.assertIsNone(parse_color_setting('error=unknown'))
self.assertEqual( self.assertEqual(
parse_color_setting('error=unknown;sql_field=blue'), parse_color_setting('error=unknown;sql_field=blue'),
dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'}) dict(PALETTES[NOCOLOR_PALETTE], SQL_FIELD={'fg': 'blue'})

View File

@ -113,7 +113,7 @@ class ModelFormsTests(TestCase):
article = Article(author_id=self.author.id) article = Article(author_id=self.author.id)
form = ArticleForm(data, instance=article) form = ArticleForm(data, instance=article)
self.assertEqual(list(form.errors), []) self.assertEqual(list(form.errors), [])
self.assertNotEqual(form.instance.pub_date, None) self.assertIsNotNone(form.instance.pub_date)
article = form.save() article = form.save()
def test_validation_with_invalid_blank_field(self): def test_validation_with_invalid_blank_field(self):