Merge pull request #1192 from mjtamlyn/assertIsInstance

Use assertIsInstance in test code.
This commit is contained in:
Marc Tamlyn 2013-05-21 02:51:14 -07:00
commit b632baac3c
31 changed files with 87 additions and 87 deletions

View File

@ -1995,7 +1995,7 @@ class AdminViewListEditable(TestCase):
} }
response = self.client.post('/test_admin/admin/admin_views/person/', data) response = self.client.post('/test_admin/admin/admin_views/person/', data)
non_form_errors = response.context['cl'].formset.non_form_errors() non_form_errors = response.context['cl'].formset.non_form_errors()
self.assertTrue(isinstance(non_form_errors, ErrorList)) self.assertIsInstance(non_form_errors, ErrorList)
self.assertEqual(str(non_form_errors), str(ErrorList(["Grace is not a Zombie"]))) self.assertEqual(str(non_form_errors), str(ErrorList(["Grace is not a Zombie"])))
def test_list_editable_ordering(self): def test_list_editable_ordering(self):

View File

@ -172,7 +172,7 @@ class LastExecutedQueryTest(TestCase):
sql, params = persons.query.sql_with_params() sql, params = persons.query.sql_with_params()
cursor = persons.query.get_compiler('default').execute_sql(None) cursor = persons.query.get_compiler('default').execute_sql(None)
last_sql = cursor.db.ops.last_executed_query(cursor, sql, params) last_sql = cursor.db.ops.last_executed_query(cursor, sql, params)
self.assertTrue(isinstance(last_sql, six.text_type)) self.assertIsInstance(last_sql, six.text_type)
@unittest.skipUnless(connection.vendor == 'sqlite', @unittest.skipUnless(connection.vendor == 'sqlite',
"This test is specific to SQLite.") "This test is specific to SQLite.")

View File

@ -432,7 +432,7 @@ class ModelTest(TestCase):
Article.objects.all()[0:-5] Article.objects.all()[0:-5]
except Exception as e: except Exception as e:
error = e error = e
self.assertTrue(isinstance(error, AssertionError)) self.assertIsInstance(error, AssertionError)
self.assertEqual(str(error), "Negative indexing is not supported.") self.assertEqual(str(error), "Negative indexing is not supported.")
# An Article instance doesn't have access to the "objects" attribute. # An Article instance doesn't have access to the "objects" attribute.
@ -637,15 +637,15 @@ class ModelTest(TestCase):
# Can't be instantiated # Can't be instantiated
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
EmptyQuerySet() EmptyQuerySet()
self.assertTrue(isinstance(Article.objects.none(), EmptyQuerySet)) self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
def test_emptyqs_values(self): def test_emptyqs_values(self):
# test for #15959 # test for #15959
Article.objects.create(headline='foo', pub_date=datetime.now()) Article.objects.create(headline='foo', pub_date=datetime.now())
with self.assertNumQueries(0): with self.assertNumQueries(0):
qs = Article.objects.none().values_list('pk') qs = Article.objects.none().values_list('pk')
self.assertTrue(isinstance(qs, EmptyQuerySet)) self.assertIsInstance(qs, EmptyQuerySet)
self.assertTrue(isinstance(qs, ValuesListQuerySet)) self.assertIsInstance(qs, ValuesListQuerySet)
self.assertEqual(len(qs), 0) self.assertEqual(len(qs), 0)
def test_emptyqs_customqs(self): def test_emptyqs_customqs(self):
@ -660,7 +660,7 @@ class ModelTest(TestCase):
qs = qs.none() qs = qs.none()
with self.assertNumQueries(0): with self.assertNumQueries(0):
self.assertEqual(len(qs), 0) self.assertEqual(len(qs), 0)
self.assertTrue(isinstance(qs, EmptyQuerySet)) self.assertIsInstance(qs, EmptyQuerySet)
self.assertEqual(qs.do_something(), 'did something') self.assertEqual(qs.do_something(), 'did something')
def test_emptyqs_values_order(self): def test_emptyqs_values_order(self):

View File

@ -510,13 +510,13 @@ class BaseCacheTests(object):
# memcached does not allow whitespace or control characters in keys # memcached does not allow whitespace or control characters in keys
self.cache.set('key with spaces', 'value') self.cache.set('key with spaces', 'value')
self.assertEqual(len(w), 2) self.assertEqual(len(w), 2)
self.assertTrue(isinstance(w[0].message, CacheKeyWarning)) self.assertIsInstance(w[0].message, CacheKeyWarning)
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always") warnings.simplefilter("always")
# memcached limits key length to 250 # memcached limits key length to 250
self.cache.set('a' * 251, 'value') self.cache.set('a' * 251, 'value')
self.assertEqual(len(w), 1) self.assertEqual(len(w), 1)
self.assertTrue(isinstance(w[0].message, CacheKeyWarning)) self.assertIsInstance(w[0].message, CacheKeyWarning)
finally: finally:
self.cache.key_func = old_func self.cache.key_func = old_func
@ -1097,10 +1097,10 @@ class GetCacheTests(unittest.TestCase):
def test_simple(self): def test_simple(self):
cache = get_cache('locmem://') cache = get_cache('locmem://')
from django.core.cache.backends.locmem import LocMemCache from django.core.cache.backends.locmem import LocMemCache
self.assertTrue(isinstance(cache, LocMemCache)) self.assertIsInstance(cache, LocMemCache)
from django.core.cache import cache from django.core.cache import cache
self.assertTrue(isinstance(cache, get_cache('default').__class__)) self.assertIsInstance(cache, get_cache('default').__class__)
cache = get_cache( cache = get_cache(
'django.core.cache.backends.dummy.DummyCache', **{'TIMEOUT': 120}) 'django.core.cache.backends.dummy.DummyCache', **{'TIMEOUT': 120})

View File

@ -54,7 +54,7 @@ class CommentFormTests(CommentTestCase):
def testGetCommentObject(self): def testGetCommentObject(self):
f = self.testValidPost() f = self.testValidPost()
c = f.get_comment_object() c = f.get_comment_object()
self.assertTrue(isinstance(c, Comment)) self.assertIsInstance(c, Comment)
self.assertEqual(c.content_object, Article.objects.get(pk=1)) self.assertEqual(c.content_object, Article.objects.get(pk=1))
self.assertEqual(c.comment, "This is my comment") self.assertEqual(c.comment, "This is my comment")
c.save() c.save()

View File

@ -32,7 +32,7 @@ class CommentTemplateTagTests(CommentTestCase):
t = "{% load comments %}" + (tag or "{% get_comment_form for comment_tests.article a.id as form %}") t = "{% load comments %}" + (tag or "{% get_comment_form for comment_tests.article a.id as form %}")
ctx, out = self.render(t, a=Article.objects.get(pk=1)) ctx, out = self.render(t, a=Article.objects.get(pk=1))
self.assertEqual(out, "") self.assertEqual(out, "")
self.assertTrue(isinstance(ctx["form"], CommentForm)) self.assertIsInstance(ctx["form"], CommentForm)
def testGetCommentFormFromLiteral(self): def testGetCommentFormFromLiteral(self):
self.testGetCommentForm("{% get_comment_form for comment_tests.article 1 as form %}") self.testGetCommentForm("{% get_comment_form for comment_tests.article 1 as form %}")

View File

@ -19,7 +19,7 @@ class CustomManagerTests(TestCase):
) )
# The RelatedManager used on the 'books' descriptor extends the default # The RelatedManager used on the 'books' descriptor extends the default
# manager # manager
self.assertTrue(isinstance(p2.books, PublishedBookManager)) self.assertIsInstance(p2.books, PublishedBookManager)
b1 = Book.published_objects.create( b1 = Book.published_objects.create(
title="How to program", author="Rodney Dangerfield", is_published=True title="How to program", author="Rodney Dangerfield", is_published=True
@ -34,7 +34,7 @@ class CustomManagerTests(TestCase):
# The RelatedManager used on the 'authors' descriptor extends the # The RelatedManager used on the 'authors' descriptor extends the
# default manager # default manager
self.assertTrue(isinstance(b2.authors, PersonManager)) self.assertIsInstance(b2.authors, PersonManager)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Book.published_objects.all(), [ Book.published_objects.all(), [

View File

@ -74,7 +74,7 @@ class DataTypesTestCase(TestCase):
database should be unicode.""" database should be unicode."""
d = Donut.objects.create(name='Jelly Donut', review='Outstanding') d = Donut.objects.create(name='Jelly Donut', review='Outstanding')
newd = Donut.objects.get(id=d.id) newd = Donut.objects.get(id=d.id)
self.assertTrue(isinstance(newd.review, six.text_type)) self.assertIsInstance(newd.review, six.text_type)
@skipIfDBFeature('supports_timezones') @skipIfDBFeature('supports_timezones')
def test_error_on_timezone(self): def test_error_on_timezone(self):
@ -90,7 +90,7 @@ class DataTypesTestCase(TestCase):
a Python datetime.date, not a datetime.datetime""" a Python datetime.date, not a datetime.datetime"""
b = RumBaba.objects.create() b = RumBaba.objects.create()
# Verify we didn't break DateTimeField behavior # Verify we didn't break DateTimeField behavior
self.assertTrue(isinstance(b.baked_timestamp, datetime.datetime)) self.assertIsInstance(b.baked_timestamp, datetime.datetime)
# We need to test this this way because datetime.datetime inherits # We need to test this this way because datetime.datetime inherits
# from datetime.date: # from datetime.date:
self.assertTrue(isinstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime)) self.assertIsInstance(b.baked_date, datetime.date) and not isinstance(b.baked_date, datetime.datetime)

View File

@ -126,15 +126,15 @@ class DecoratorsTest(TestCase):
my_safe_view = require_safe(my_view) my_safe_view = require_safe(my_view)
request = HttpRequest() request = HttpRequest()
request.method = 'GET' request.method = 'GET'
self.assertTrue(isinstance(my_safe_view(request), HttpResponse)) self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = 'HEAD' request.method = 'HEAD'
self.assertTrue(isinstance(my_safe_view(request), HttpResponse)) self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = 'POST' request.method = 'POST'
self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed)) self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
request.method = 'PUT' request.method = 'PUT'
self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed)) self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
request.method = 'DELETE' request.method = 'DELETE'
self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed)) self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
# For testing method_decorator, a decorator that assumes a single argument. # For testing method_decorator, a decorator that assumes a single argument.

View File

@ -360,7 +360,7 @@ class DefaultFiltersTests(TestCase):
escaped = force_escape('<some html & special characters > here') escaped = force_escape('<some html & special characters > here')
self.assertEqual( self.assertEqual(
escaped, '&lt;some html &amp; special characters &gt; here') escaped, '&lt;some html &amp; special characters &gt; here')
self.assertTrue(isinstance(escaped, SafeData)) self.assertIsInstance(escaped, SafeData)
self.assertEqual( self.assertEqual(
force_escape('<some html & special characters > here ĐÅ€£'), force_escape('<some html & special characters > here ĐÅ€£'),
'&lt;some html &amp; special characters &gt; here'\ '&lt;some html &amp; special characters &gt; here'\

View File

@ -108,7 +108,7 @@ class DispatcherTests(unittest.TestCase):
a_signal.connect(fails) a_signal.connect(fails)
result = a_signal.send_robust(sender=self, val="test") result = a_signal.send_robust(sender=self, val="test")
err = result[0][1] err = result[0][1]
self.assertTrue(isinstance(err, ValueError)) self.assertIsInstance(err, ValueError)
self.assertEqual(err.args, ('this',)) self.assertEqual(err.args, ('this',))
a_signal.disconnect(fails) a_signal.disconnect(fails)
self._testIsClean(a_signal) self._testIsClean(a_signal)

View File

@ -14,6 +14,6 @@ class DefaultTests(TestCase):
now = datetime.now() now = datetime.now()
a.save() a.save()
self.assertTrue(isinstance(a.id, six.integer_types)) self.assertIsInstance(a.id, six.integer_types)
self.assertEqual(a.headline, "Default headline") self.assertEqual(a.headline, "Default headline")
self.assertTrue((now - a.pub_date).seconds < 5) self.assertTrue((now - a.pub_date).seconds < 5)

View File

@ -11,21 +11,21 @@ class CustomField(TestCase):
def test_defer(self): def test_defer(self):
d = DataModel.objects.create(data=[1, 2, 3]) d = DataModel.objects.create(data=[1, 2, 3])
self.assertTrue(isinstance(d.data, list)) self.assertIsInstance(d.data, list)
d = DataModel.objects.get(pk=d.pk) d = DataModel.objects.get(pk=d.pk)
self.assertTrue(isinstance(d.data, list)) self.assertIsInstance(d.data, list)
self.assertEqual(d.data, [1, 2, 3]) self.assertEqual(d.data, [1, 2, 3])
d = DataModel.objects.defer("data").get(pk=d.pk) d = DataModel.objects.defer("data").get(pk=d.pk)
self.assertTrue(isinstance(d.data, list)) self.assertIsInstance(d.data, list)
self.assertEqual(d.data, [1, 2, 3]) self.assertEqual(d.data, [1, 2, 3])
# Refetch for save # Refetch for save
d = DataModel.objects.defer("data").get(pk=d.pk) d = DataModel.objects.defer("data").get(pk=d.pk)
d.save() d.save()
d = DataModel.objects.get(pk=d.pk) d = DataModel.objects.get(pk=d.pk)
self.assertTrue(isinstance(d.data, list)) self.assertIsInstance(d.data, list)
self.assertEqual(d.data, [1, 2, 3]) self.assertEqual(d.data, [1, 2, 3])
def test_custom_field(self): def test_custom_field(self):
@ -44,7 +44,7 @@ class CustomField(TestCase):
# The data loads back from the database correctly and 'data' has the # The data loads back from the database correctly and 'data' has the
# right type. # right type.
m1 = MyModel.objects.get(pk=m.pk) m1 = MyModel.objects.get(pk=m.pk)
self.assertTrue(isinstance(m1.data, Small)) self.assertIsInstance(m1.data, Small)
self.assertEqual(str(m1.data), "12") self.assertEqual(str(m1.data), "12")
# We can do normal filtering on the custom field (and will get an error # We can do normal filtering on the custom field (and will get an error

View File

@ -588,11 +588,11 @@ class ContentFileTestCase(unittest.TestCase):
Test that ContentFile can accept both bytes and unicode and that the Test that ContentFile can accept both bytes and unicode and that the
retrieved content is of the same type. retrieved content is of the same type.
""" """
self.assertTrue(isinstance(ContentFile(b"content").read(), bytes)) self.assertIsInstance(ContentFile(b"content").read(), bytes)
if six.PY3: if six.PY3:
self.assertTrue(isinstance(ContentFile("español").read(), six.text_type)) self.assertIsInstance(ContentFile("español").read(), six.text_type)
else: else:
self.assertTrue(isinstance(ContentFile("español").read(), bytes)) self.assertIsInstance(ContentFile("español").read(), bytes)
def test_content_saving(self): def test_content_saving(self):
""" """

View File

@ -982,7 +982,7 @@ class FormsFormsetTestCase(TestCase):
ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet)
formset = ChoiceFormSet(data, auto_id=False, prefix='choices') formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertTrue(isinstance(formset.non_form_errors(), ErrorList)) self.assertIsInstance(formset.non_form_errors(), ErrorList)
self.assertEqual(list(formset.non_form_errors()), self.assertEqual(list(formset.non_form_errors()),
['This is a non-form error']) ['This is a non-form error'])

View File

@ -52,9 +52,9 @@ class TestTicket14567(TestCase):
form = OptionalMultiChoiceModelForm({'multi_choice_optional': '', 'multi_choice': [option.pk]}) form = OptionalMultiChoiceModelForm({'multi_choice_optional': '', 'multi_choice': [option.pk]})
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
# Check that the empty value is a QuerySet # Check that the empty value is a QuerySet
self.assertTrue(isinstance(form.cleaned_data['multi_choice_optional'], models.query.QuerySet)) self.assertIsInstance(form.cleaned_data['multi_choice_optional'], models.query.QuerySet)
# While we're at it, test whether a QuerySet is returned if there *is* a value. # While we're at it, test whether a QuerySet is returned if there *is* a value.
self.assertTrue(isinstance(form.cleaned_data['multi_choice'], models.query.QuerySet)) self.assertIsInstance(form.cleaned_data['multi_choice'], models.query.QuerySet)
class ModelFormCallableModelDefault(TestCase): class ModelFormCallableModelDefault(TestCase):

View File

@ -264,4 +264,4 @@ class GenericInlineFormsetTest(TestCase):
def test_generic_inlineformset_factory(self): def test_generic_inlineformset_factory(self):
Formset = generic_inlineformset_factory(TaggedItem, TaggedItemForm) Formset = generic_inlineformset_factory(TaggedItem, TaggedItemForm)
form = Formset().forms[0] form = Formset().forms[0]
self.assertTrue(isinstance(form['tag'].field.widget, CustomWidget)) self.assertIsInstance(form['tag'].field.widget, CustomWidget)

View File

@ -278,7 +278,7 @@ class TemplateViewTest(TestCase):
response = self.client.get('/template/simple/bar/') response = self.client.get('/template/simple/bar/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['foo'], 'bar') self.assertEqual(response.context['foo'], 'bar')
self.assertTrue(isinstance(response.context['view'], View)) self.assertIsInstance(response.context['view'], View)
def test_extra_template_params(self): def test_extra_template_params(self):
""" """
@ -288,7 +288,7 @@ class TemplateViewTest(TestCase):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['foo'], 'bar') self.assertEqual(response.context['foo'], 'bar')
self.assertEqual(response.context['key'], 'value') self.assertEqual(response.context['key'], 'value')
self.assertTrue(isinstance(response.context['view'], View)) self.assertIsInstance(response.context['view'], View)
def test_cached_views(self): def test_cached_views(self):
""" """

View File

@ -15,7 +15,7 @@ class DetailViewTest(TestCase):
res = self.client.get('/detail/obj/') res = self.client.get('/detail/obj/')
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], {'foo': 'bar'}) self.assertEqual(res.context['object'], {'foo': 'bar'})
self.assertTrue(isinstance(res.context['view'], View)) self.assertIsInstance(res.context['view'], View)
self.assertTemplateUsed(res, 'generic_views/detail.html') self.assertTemplateUsed(res, 'generic_views/detail.html')
def test_detail_by_pk(self): def test_detail_by_pk(self):

View File

@ -43,8 +43,8 @@ class CreateViewTests(TestCase):
def test_create(self): def test_create(self):
res = self.client.get('/edit/authors/create/') res = self.client.get('/edit/authors/create/')
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTrue(isinstance(res.context['form'], forms.ModelForm)) self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertTrue(isinstance(res.context['view'], View)) self.assertIsInstance(res.context['view'], View)
self.assertFalse('object' in res.context) self.assertFalse('object' in res.context)
self.assertFalse('author' in res.context) self.assertFalse('author' in res.context)
self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertTemplateUsed(res, 'generic_views/author_form.html')
@ -89,7 +89,7 @@ class CreateViewTests(TestCase):
def test_create_with_special_properties(self): def test_create_with_special_properties(self):
res = self.client.get('/edit/authors/create/special/') res = self.client.get('/edit/authors/create/special/')
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTrue(isinstance(res.context['form'], views.AuthorForm)) self.assertIsInstance(res.context['form'], views.AuthorForm)
self.assertFalse('object' in res.context) self.assertFalse('object' in res.context)
self.assertFalse('author' in res.context) self.assertFalse('author' in res.context)
self.assertTemplateUsed(res, 'generic_views/form.html') self.assertTemplateUsed(res, 'generic_views/form.html')
@ -165,7 +165,7 @@ class UpdateViewTests(TestCase):
) )
res = self.client.get('/edit/author/%d/update/' % a.pk) res = self.client.get('/edit/author/%d/update/' % a.pk)
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTrue(isinstance(res.context['form'], forms.ModelForm)) self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertTemplateUsed(res, 'generic_views/author_form.html')
@ -247,7 +247,7 @@ class UpdateViewTests(TestCase):
) )
res = self.client.get('/edit/author/%d/update/special/' % a.pk) res = self.client.get('/edit/author/%d/update/special/' % a.pk)
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTrue(isinstance(res.context['form'], views.AuthorForm)) self.assertIsInstance(res.context['form'], views.AuthorForm)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
self.assertFalse('author' in res.context) self.assertFalse('author' in res.context)
@ -279,8 +279,8 @@ class UpdateViewTests(TestCase):
) )
res = self.client.get('/edit/author/update/') res = self.client.get('/edit/author/update/')
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTrue(isinstance(res.context['form'], forms.ModelForm)) self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertTrue(isinstance(res.context['view'], View)) self.assertIsInstance(res.context['view'], View)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk)) self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
self.assertTemplateUsed(res, 'generic_views/author_form.html') self.assertTemplateUsed(res, 'generic_views/author_form.html')

View File

@ -24,7 +24,7 @@ class ListViewTests(TestCase):
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html') self.assertTemplateUsed(res, 'generic_views/author_list.html')
self.assertEqual(list(res.context['object_list']), list(Author.objects.all())) self.assertEqual(list(res.context['object_list']), list(Author.objects.all()))
self.assertTrue(isinstance(res.context['view'], View)) self.assertIsInstance(res.context['view'], View)
self.assertIs(res.context['author_list'], res.context['object_list']) self.assertIs(res.context['author_list'], res.context['object_list'])
self.assertIsNone(res.context['paginator']) self.assertIsNone(res.context['paginator'])
self.assertIsNone(res.context['page_obj']) self.assertIsNone(res.context['page_obj'])

View File

@ -293,7 +293,7 @@ class AdminEmailHandlerTest(TestCase):
def my_mail_admins(*args, **kwargs): def my_mail_admins(*args, **kwargs):
connection = kwargs['connection'] connection = kwargs['connection']
self.assertTrue(isinstance(connection, MyEmailBackend)) self.assertIsInstance(connection, MyEmailBackend)
mail_admins_called['called'] = True mail_admins_called['called'] = True
# Monkeypatches # Monkeypatches

View File

@ -251,16 +251,16 @@ class MailTests(TestCase):
def test_backend_arg(self): def test_backend_arg(self):
"""Test backend argument of mail.get_connection()""" """Test backend argument of mail.get_connection()"""
self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend)) self.assertIsInstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend)
self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)) self.assertIsInstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)
self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)) self.assertIsInstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)
self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend)) self.assertIsInstance(mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend)
tmp_dir = tempfile.mkdtemp() tmp_dir = tempfile.mkdtemp()
try: try:
self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend)) self.assertIsInstance(mail.get_connection('django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend)
finally: finally:
shutil.rmtree(tmp_dir) shutil.rmtree(tmp_dir)
self.assertTrue(isinstance(mail.get_connection(), locmem.EmailBackend)) self.assertIsInstance(mail.get_connection(), locmem.EmailBackend)
@override_settings( @override_settings(
EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',

View File

@ -193,28 +193,28 @@ class BooleanFieldTests(unittest.TestCase):
b.bfield = True b.bfield = True
b.save() b.save()
b2 = BooleanModel.objects.get(pk=b.pk) b2 = BooleanModel.objects.get(pk=b.pk)
self.assertTrue(isinstance(b2.bfield, bool)) self.assertIsInstance(b2.bfield, bool)
self.assertEqual(b2.bfield, True) self.assertEqual(b2.bfield, True)
b3 = BooleanModel() b3 = BooleanModel()
b3.bfield = False b3.bfield = False
b3.save() b3.save()
b4 = BooleanModel.objects.get(pk=b3.pk) b4 = BooleanModel.objects.get(pk=b3.pk)
self.assertTrue(isinstance(b4.bfield, bool)) self.assertIsInstance(b4.bfield, bool)
self.assertEqual(b4.bfield, False) self.assertEqual(b4.bfield, False)
b = NullBooleanModel() b = NullBooleanModel()
b.nbfield = True b.nbfield = True
b.save() b.save()
b2 = NullBooleanModel.objects.get(pk=b.pk) b2 = NullBooleanModel.objects.get(pk=b.pk)
self.assertTrue(isinstance(b2.nbfield, bool)) self.assertIsInstance(b2.nbfield, bool)
self.assertEqual(b2.nbfield, True) self.assertEqual(b2.nbfield, True)
b3 = NullBooleanModel() b3 = NullBooleanModel()
b3.nbfield = False b3.nbfield = False
b3.save() b3.save()
b4 = NullBooleanModel.objects.get(pk=b3.pk) b4 = NullBooleanModel.objects.get(pk=b3.pk)
self.assertTrue(isinstance(b4.nbfield, bool)) self.assertIsInstance(b4.nbfield, bool)
self.assertEqual(b4.nbfield, False) self.assertEqual(b4.nbfield, False)
# http://code.djangoproject.com/ticket/13293 # http://code.djangoproject.com/ticket/13293
@ -371,11 +371,11 @@ class BigIntegerFieldTests(test.TestCase):
def test_types(self): def test_types(self):
b = BigInt(value = 0) b = BigInt(value = 0)
self.assertTrue(isinstance(b.value, six.integer_types)) self.assertIsInstance(b.value, six.integer_types)
b.save() b.save()
self.assertTrue(isinstance(b.value, six.integer_types)) self.assertIsInstance(b.value, six.integer_types)
b = BigInt.objects.all()[0] b = BigInt.objects.all()[0]
self.assertTrue(isinstance(b.value, six.integer_types)) self.assertIsInstance(b.value, six.integer_types)
def test_coercing(self): def test_coercing(self):
BigInt.objects.create(value ='10') BigInt.objects.create(value ='10')

View File

@ -274,8 +274,8 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
fields = '__all__' fields = '__all__'
self.assertTrue(isinstance(ReplaceField.base_fields['url'], self.assertIsInstance(ReplaceField.base_fields['url'],
forms.fields.BooleanField)) forms.fields.BooleanField)
def test_replace_field_variant_2(self): def test_replace_field_variant_2(self):
# Should have the same result as before, # Should have the same result as before,
@ -287,8 +287,8 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
fields = ['url'] fields = ['url']
self.assertTrue(isinstance(ReplaceField.base_fields['url'], self.assertIsInstance(ReplaceField.base_fields['url'],
forms.fields.BooleanField)) forms.fields.BooleanField)
def test_replace_field_variant_3(self): def test_replace_field_variant_3(self):
# Should have the same result as before, # Should have the same result as before,
@ -300,8 +300,8 @@ class ModelFormBaseTest(TestCase):
model = Category model = Category
fields = [] # url will still appear, since it is explicit above fields = [] # url will still appear, since it is explicit above
self.assertTrue(isinstance(ReplaceField.base_fields['url'], self.assertIsInstance(ReplaceField.base_fields['url'],
forms.fields.BooleanField)) forms.fields.BooleanField)
def test_override_field(self): def test_override_field(self):
class AuthorForm(forms.ModelForm): class AuthorForm(forms.ModelForm):

View File

@ -236,11 +236,11 @@ class FormsetTests(TestCase):
formset = Formset(data) formset = Formset(data)
# check if the returned error classes are correct # check if the returned error classes are correct
# note: formset.errors returns a list as documented # note: formset.errors returns a list as documented
self.assertTrue(isinstance(formset.errors, list)) self.assertIsInstance(formset.errors, list)
self.assertTrue(isinstance(formset.non_form_errors(), ErrorList)) self.assertIsInstance(formset.non_form_errors(), ErrorList)
for form in formset.forms: for form in formset.forms:
self.assertTrue(isinstance(form.errors, ErrorDict)) self.assertIsInstance(form.errors, ErrorDict)
self.assertTrue(isinstance(form.non_field_errors(), ErrorList)) self.assertIsInstance(form.non_field_errors(), ErrorList)
def test_initial_data(self): def test_initial_data(self):
User.objects.create(username="bibi", serial=1) User.objects.create(username="bibi", serial=1)
@ -296,16 +296,16 @@ class FormfieldCallbackTests(TestCase):
def test_inlineformset_factory_default(self): def test_inlineformset_factory_default(self):
Formset = inlineformset_factory(User, UserSite, form=UserSiteForm, fields="__all__") Formset = inlineformset_factory(User, UserSite, form=UserSiteForm, fields="__all__")
form = Formset().forms[0] form = Formset().forms[0]
self.assertTrue(isinstance(form['id'].field.widget, CustomWidget)) self.assertIsInstance(form['id'].field.widget, CustomWidget)
self.assertTrue(isinstance(form['data'].field.widget, CustomWidget)) self.assertIsInstance(form['data'].field.widget, CustomWidget)
self.assertFalse(form.fields['id'].localize) self.assertFalse(form.fields['id'].localize)
self.assertTrue(form.fields['data'].localize) self.assertTrue(form.fields['data'].localize)
def test_modelformset_factory_default(self): def test_modelformset_factory_default(self):
Formset = modelformset_factory(UserSite, form=UserSiteForm) Formset = modelformset_factory(UserSite, form=UserSiteForm)
form = Formset().forms[0] form = Formset().forms[0]
self.assertTrue(isinstance(form['id'].field.widget, CustomWidget)) self.assertIsInstance(form['id'].field.widget, CustomWidget)
self.assertTrue(isinstance(form['data'].field.widget, CustomWidget)) self.assertIsInstance(form['data'].field.widget, CustomWidget)
self.assertFalse(form.fields['id'].localize) self.assertFalse(form.fields['id'].localize)
self.assertTrue(form.fields['data'].localize) self.assertTrue(form.fields['data'].localize)

View File

@ -23,14 +23,14 @@ class SimpleTests(TestCase):
# ... and pull it out via the other set. # ... and pull it out via the other set.
a2 = A02.objects.all()[0] a2 = A02.objects.all()[0]
self.assertTrue(isinstance(a2, A02)) self.assertIsInstance(a2, A02)
self.assertEqual(a2.f_a, "foo") self.assertEqual(a2.f_a, "foo")
b2 = B02.objects.all()[0] b2 = B02.objects.all()[0]
self.assertTrue(isinstance(b2, B02)) self.assertIsInstance(b2, B02)
self.assertEqual(b2.f_a, "fred") self.assertEqual(b2.f_a, "fred")
self.assertTrue(isinstance(b2.fk_a, A02)) self.assertIsInstance(b2.fk_a, A02)
self.assertEqual(b2.fk_a.f_a, "foo") self.assertEqual(b2.fk_a.f_a, "foo")
self.assertEqual(list(C02.objects.filter(f_a=None)), []) self.assertEqual(list(C02.objects.filter(f_a=None)), [])
@ -38,7 +38,7 @@ class SimpleTests(TestCase):
resp = list(C02.objects.filter(mm_a=a.id)) resp = list(C02.objects.filter(mm_a=a.id))
self.assertEqual(len(resp), 1) self.assertEqual(len(resp), 1)
self.assertTrue(isinstance(resp[0], C02)) self.assertIsInstance(resp[0], C02)
self.assertEqual(resp[0].f_a, 'barney') self.assertEqual(resp[0].f_a, 'barney')

View File

@ -246,7 +246,7 @@ class ResolverTests(unittest.TestCase):
self.assertEqual(len(e.args[0]['tried']), len(url_types_names), 'Wrong number of tried URLs returned. Expected %s, got %s.' % (len(url_types_names), len(e.args[0]['tried']))) self.assertEqual(len(e.args[0]['tried']), len(url_types_names), 'Wrong number of tried URLs returned. Expected %s, got %s.' % (len(url_types_names), len(e.args[0]['tried'])))
for tried, expected in zip(e.args[0]['tried'], url_types_names): for tried, expected in zip(e.args[0]['tried'], url_types_names):
for t, e in zip(tried, expected): for t, e in zip(tried, expected):
self.assertTrue(isinstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type'])) self.assertIsInstance(t, e['type']), str('%s is not an instance of %s') % (t, e['type'])
if 'name' in e: if 'name' in e:
if not e['name']: if not e['name']:
self.assertTrue(t.name is None, 'Expected no URL name but found %s.' % t.name) self.assertTrue(t.name is None, 'Expected no URL name but found %s.' % t.name)
@ -278,11 +278,11 @@ class ReverseShortcutTests(TestCase):
return "/hi-there/" return "/hi-there/"
res = redirect(FakeObj()) res = redirect(FakeObj())
self.assertTrue(isinstance(res, HttpResponseRedirect)) self.assertIsInstance(res, HttpResponseRedirect)
self.assertEqual(res.url, '/hi-there/') self.assertEqual(res.url, '/hi-there/')
res = redirect(FakeObj(), permanent=True) res = redirect(FakeObj(), permanent=True)
self.assertTrue(isinstance(res, HttpResponsePermanentRedirect)) self.assertIsInstance(res, HttpResponsePermanentRedirect)
self.assertEqual(res.url, '/hi-there/') self.assertEqual(res.url, '/hi-there/')
def test_redirect_to_view_name(self): def test_redirect_to_view_name(self):

View File

@ -39,4 +39,4 @@ class TestBaseConv(TestCase):
def test_exception(self): def test_exception(self):
self.assertRaises(ValueError, BaseConverter, 'abc', sign='a') self.assertRaises(ValueError, BaseConverter, 'abc', sign='a')
self.assertTrue(isinstance(BaseConverter('abc', sign='d'), BaseConverter)) self.assertIsInstance(BaseConverter('abc', sign='d'), BaseConverter)

View File

@ -68,7 +68,7 @@ class TestUtilsSimpleLazyObject(TestCase):
# Second, for an evaluated SimpleLazyObject # Second, for an evaluated SimpleLazyObject
name = x.name # evaluate name = x.name # evaluate
self.assertTrue(isinstance(x._wrapped, _ComplexObject)) self.assertIsInstance(x._wrapped, _ComplexObject)
# __repr__ contains __repr__ of wrapped object # __repr__ contains __repr__ of wrapped object
self.assertEqual("<SimpleLazyObject: %r>" % x._wrapped, repr(x)) self.assertEqual("<SimpleLazyObject: %r>" % x._wrapped, repr(x))

View File

@ -60,7 +60,7 @@ class StaticTests(TestCase):
# This is 24h before max Unix time. Remember to fix Django and # This is 24h before max Unix time. Remember to fix Django and
# update this test well before 2038 :) # update this test well before 2038 :)
) )
self.assertTrue(isinstance(response, HttpResponseNotModified)) self.assertIsInstance(response, HttpResponseNotModified)
def test_invalid_if_modified_since(self): def test_invalid_if_modified_since(self):
"""Handle bogus If-Modified-Since values gracefully """Handle bogus If-Modified-Since values gracefully