Permalink
Browse files

Use assertIsInstance in tests.

Gives much nicer errors when it fails.
  • Loading branch information...
1 parent 18856f8 commit 09f865276554f35060ff939722ec4cefd578edf6 @mjtamlyn mjtamlyn committed May 21, 2013
@@ -1995,7 +1995,7 @@ def test_non_form_errors_is_errorlist(self):
}
response = self.client.post('/test_admin/admin/admin_views/person/', data)
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"])))
def test_list_editable_ordering(self):
@@ -172,7 +172,7 @@ def test_query_encoding(self):
sql, params = persons.query.sql_with_params()
cursor = persons.query.get_compiler('default').execute_sql(None)
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',
"This test is specific to SQLite.")
View
@@ -432,7 +432,7 @@ def test_object_creation(self):
Article.objects.all()[0:-5]
except Exception as e:
error = e
- self.assertTrue(isinstance(error, AssertionError))
+ self.assertIsInstance(error, AssertionError)
self.assertEqual(str(error), "Negative indexing is not supported.")
# An Article instance doesn't have access to the "objects" attribute.
@@ -637,15 +637,15 @@ def test_emptyqs(self):
# Can't be instantiated
with self.assertRaises(TypeError):
EmptyQuerySet()
- self.assertTrue(isinstance(Article.objects.none(), EmptyQuerySet))
+ self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
def test_emptyqs_values(self):
# test for #15959
Article.objects.create(headline='foo', pub_date=datetime.now())
with self.assertNumQueries(0):
qs = Article.objects.none().values_list('pk')
- self.assertTrue(isinstance(qs, EmptyQuerySet))
- self.assertTrue(isinstance(qs, ValuesListQuerySet))
+ self.assertIsInstance(qs, EmptyQuerySet)
+ self.assertIsInstance(qs, ValuesListQuerySet)
self.assertEqual(len(qs), 0)
def test_emptyqs_customqs(self):
@@ -660,7 +660,7 @@ def do_something(self):
qs = qs.none()
with self.assertNumQueries(0):
self.assertEqual(len(qs), 0)
- self.assertTrue(isinstance(qs, EmptyQuerySet))
+ self.assertIsInstance(qs, EmptyQuerySet)
self.assertEqual(qs.do_something(), 'did something')
def test_emptyqs_values_order(self):
@@ -510,13 +510,13 @@ def func(key, *args):
# memcached does not allow whitespace or control characters in keys
self.cache.set('key with spaces', 'value')
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:
warnings.simplefilter("always")
# memcached limits key length to 250
self.cache.set('a' * 251, 'value')
self.assertEqual(len(w), 1)
- self.assertTrue(isinstance(w[0].message, CacheKeyWarning))
+ self.assertIsInstance(w[0].message, CacheKeyWarning)
finally:
self.cache.key_func = old_func
@@ -1097,10 +1097,10 @@ class GetCacheTests(unittest.TestCase):
def test_simple(self):
cache = get_cache('locmem://')
from django.core.cache.backends.locmem import LocMemCache
- self.assertTrue(isinstance(cache, LocMemCache))
+ self.assertIsInstance(cache, LocMemCache)
from django.core.cache import cache
- self.assertTrue(isinstance(cache, get_cache('default').__class__))
+ self.assertIsInstance(cache, get_cache('default').__class__)
cache = get_cache(
'django.core.cache.backends.dummy.DummyCache', **{'TIMEOUT': 120})
@@ -54,7 +54,7 @@ def testSecurityErrors(self):
def testGetCommentObject(self):
f = self.testValidPost()
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.comment, "This is my comment")
c.save()
@@ -32,7 +32,7 @@ def testGetCommentForm(self, tag=None):
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))
self.assertEqual(out, "")
- self.assertTrue(isinstance(ctx["form"], CommentForm))
+ self.assertIsInstance(ctx["form"], CommentForm)
def testGetCommentFormFromLiteral(self):
self.testGetCommentForm("{% get_comment_form for comment_tests.article 1 as form %}")
@@ -19,7 +19,7 @@ def test_manager(self):
)
# The RelatedManager used on the 'books' descriptor extends the default
# manager
- self.assertTrue(isinstance(p2.books, PublishedBookManager))
+ self.assertIsInstance(p2.books, PublishedBookManager)
b1 = Book.published_objects.create(
title="How to program", author="Rodney Dangerfield", is_published=True
@@ -34,7 +34,7 @@ def test_manager(self):
# The RelatedManager used on the 'authors' descriptor extends the
# default manager
- self.assertTrue(isinstance(b2.authors, PersonManager))
+ self.assertIsInstance(b2.authors, PersonManager)
self.assertQuerysetEqual(
Book.published_objects.all(), [
@@ -74,7 +74,7 @@ def test_textfields_unicode(self):
database should be unicode."""
d = Donut.objects.create(name='Jelly Donut', review='Outstanding')
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')
def test_error_on_timezone(self):
@@ -90,7 +90,7 @@ def test_datefield_auto_now_add(self):
a Python datetime.date, not a datetime.datetime"""
b = RumBaba.objects.create()
# 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
# 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)
@@ -126,15 +126,15 @@ def my_view(request):
my_safe_view = require_safe(my_view)
request = HttpRequest()
request.method = 'GET'
- self.assertTrue(isinstance(my_safe_view(request), HttpResponse))
+ self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = 'HEAD'
- self.assertTrue(isinstance(my_safe_view(request), HttpResponse))
+ self.assertIsInstance(my_safe_view(request), HttpResponse)
request.method = 'POST'
- self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed))
+ self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
request.method = 'PUT'
- self.assertTrue(isinstance(my_safe_view(request), HttpResponseNotAllowed))
+ self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed)
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.
@@ -360,7 +360,7 @@ def test_force_escape(self):
escaped = force_escape('<some html & special characters > here')
self.assertEqual(
escaped, '&lt;some html &amp; special characters &gt; here')
- self.assertTrue(isinstance(escaped, SafeData))
+ self.assertIsInstance(escaped, SafeData)
self.assertEqual(
force_escape('<some html & special characters > here ĐÅ€£'),
'&lt;some html &amp; special characters &gt; here'\
@@ -108,7 +108,7 @@ def fails(val, **kwargs):
a_signal.connect(fails)
result = a_signal.send_robust(sender=self, val="test")
err = result[0][1]
- self.assertTrue(isinstance(err, ValueError))
+ self.assertIsInstance(err, ValueError)
self.assertEqual(err.args, ('this',))
a_signal.disconnect(fails)
self._testIsClean(a_signal)
@@ -14,6 +14,6 @@ def test_field_defaults(self):
now = datetime.now()
a.save()
- self.assertTrue(isinstance(a.id, six.integer_types))
+ self.assertIsInstance(a.id, six.integer_types)
self.assertEqual(a.headline, "Default headline")
self.assertTrue((now - a.pub_date).seconds < 5)
@@ -11,21 +11,21 @@ class CustomField(TestCase):
def test_defer(self):
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)
- self.assertTrue(isinstance(d.data, list))
+ self.assertIsInstance(d.data, list)
self.assertEqual(d.data, [1, 2, 3])
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])
# Refetch for save
d = DataModel.objects.defer("data").get(pk=d.pk)
d.save()
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])
def test_custom_field(self):
@@ -44,7 +44,7 @@ def test_custom_field(self):
# The data loads back from the database correctly and 'data' has the
# right type.
m1 = MyModel.objects.get(pk=m.pk)
- self.assertTrue(isinstance(m1.data, Small))
+ self.assertIsInstance(m1.data, Small)
self.assertEqual(str(m1.data), "12")
# We can do normal filtering on the custom field (and will get an error
@@ -588,11 +588,11 @@ def test_content_file_input_type(self):
Test that ContentFile can accept both bytes and unicode and that the
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:
- self.assertTrue(isinstance(ContentFile("español").read(), six.text_type))
+ self.assertIsInstance(ContentFile("español").read(), six.text_type)
else:
- self.assertTrue(isinstance(ContentFile("español").read(), bytes))
+ self.assertIsInstance(ContentFile("español").read(), bytes)
def test_content_saving(self):
"""
@@ -982,7 +982,7 @@ def clean(self):
ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet)
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()),
['This is a non-form error'])
@@ -52,9 +52,9 @@ def test_empty_queryset_return(self):
form = OptionalMultiChoiceModelForm({'multi_choice_optional': '', 'multi_choice': [option.pk]})
self.assertTrue(form.is_valid())
# 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.
- self.assertTrue(isinstance(form.cleaned_data['multi_choice'], models.query.QuerySet))
+ self.assertIsInstance(form.cleaned_data['multi_choice'], models.query.QuerySet)
class ModelFormCallableModelDefault(TestCase):
@@ -264,4 +264,4 @@ class GenericInlineFormsetTest(TestCase):
def test_generic_inlineformset_factory(self):
Formset = generic_inlineformset_factory(TaggedItem, TaggedItemForm)
form = Formset().forms[0]
- self.assertTrue(isinstance(form['tag'].field.widget, CustomWidget))
+ self.assertIsInstance(form['tag'].field.widget, CustomWidget)
@@ -278,7 +278,7 @@ def test_template_params(self):
response = self.client.get('/template/simple/bar/')
self.assertEqual(response.status_code, 200)
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):
"""
@@ -288,7 +288,7 @@ def test_extra_template_params(self):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['foo'], 'bar')
self.assertEqual(response.context['key'], 'value')
- self.assertTrue(isinstance(response.context['view'], View))
+ self.assertIsInstance(response.context['view'], View)
def test_cached_views(self):
"""
@@ -15,7 +15,7 @@ def test_simple_object(self):
res = self.client.get('/detail/obj/')
self.assertEqual(res.status_code, 200)
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')
def test_detail_by_pk(self):
@@ -43,8 +43,8 @@ class CreateViewTests(TestCase):
def test_create(self):
res = self.client.get('/edit/authors/create/')
self.assertEqual(res.status_code, 200)
- self.assertTrue(isinstance(res.context['form'], forms.ModelForm))
- self.assertTrue(isinstance(res.context['view'], View))
+ self.assertIsInstance(res.context['form'], forms.ModelForm)
+ self.assertIsInstance(res.context['view'], View)
self.assertFalse('object' in res.context)
self.assertFalse('author' in res.context)
self.assertTemplateUsed(res, 'generic_views/author_form.html')
@@ -89,7 +89,7 @@ def test_create_with_interpolated_redirect(self):
def test_create_with_special_properties(self):
res = self.client.get('/edit/authors/create/special/')
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('author' in res.context)
self.assertTemplateUsed(res, 'generic_views/form.html')
@@ -165,7 +165,7 @@ def test_update_post(self):
)
res = self.client.get('/edit/author/%d/update/' % a.pk)
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['author'], Author.objects.get(pk=a.pk))
self.assertTemplateUsed(res, 'generic_views/author_form.html')
@@ -247,7 +247,7 @@ def test_update_with_special_properties(self):
)
res = self.client.get('/edit/author/%d/update/special/' % a.pk)
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['thingy'], Author.objects.get(pk=a.pk))
self.assertFalse('author' in res.context)
@@ -279,8 +279,8 @@ def test_update_get_object(self):
)
res = self.client.get('/edit/author/update/')
self.assertEqual(res.status_code, 200)
- self.assertTrue(isinstance(res.context['form'], forms.ModelForm))
- self.assertTrue(isinstance(res.context['view'], View))
+ self.assertIsInstance(res.context['form'], forms.ModelForm)
+ self.assertIsInstance(res.context['view'], View)
self.assertEqual(res.context['object'], 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')
@@ -24,7 +24,7 @@ def test_queryset(self):
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_list.html')
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.assertIsNone(res.context['paginator'])
self.assertIsNone(res.context['page_obj'])
@@ -293,7 +293,7 @@ def test_uses_custom_email_backend(self):
def my_mail_admins(*args, **kwargs):
connection = kwargs['connection']
- self.assertTrue(isinstance(connection, MyEmailBackend))
+ self.assertIsInstance(connection, MyEmailBackend)
mail_admins_called['called'] = True
# Monkeypatches
View
@@ -251,16 +251,16 @@ def test_custom_backend(self):
def test_backend_arg(self):
"""Test backend argument of mail.get_connection()"""
- self.assertTrue(isinstance(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.assertTrue(isinstance(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.smtp.EmailBackend'), smtp.EmailBackend)
+ self.assertIsInstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)
+ self.assertIsInstance(mail.get_connection('django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)
+ self.assertIsInstance(mail.get_connection('django.core.mail.backends.console.EmailBackend'), console.EmailBackend)
tmp_dir = tempfile.mkdtemp()
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:
shutil.rmtree(tmp_dir)
- self.assertTrue(isinstance(mail.get_connection(), locmem.EmailBackend))
+ self.assertIsInstance(mail.get_connection(), locmem.EmailBackend)
@override_settings(
EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',
Oops, something went wrong.

0 comments on commit 09f8652

Please sign in to comment.