Used assertRaisesMessage() in various tests.

This commit is contained in:
Hasan Ramezani 2020-02-04 21:58:07 +01:00 committed by Mariusz Felisiak
parent 71756bdfed
commit fc4f45ebdc
8 changed files with 59 additions and 101 deletions

View File

@ -1,21 +1,17 @@
from unittest import TestCase
from django.contrib import admin from django.contrib import admin
from django.test import SimpleTestCase
class AdminAutoDiscoverTests(TestCase): class AdminAutoDiscoverTests(SimpleTestCase):
""" """
Test for bug #8245 - don't raise an AlreadyRegistered exception when using Test for bug #8245 - don't raise an AlreadyRegistered exception when using
autodiscover() and an admin.py module contains an error. autodiscover() and an admin.py module contains an error.
""" """
def test_double_call_autodiscover(self): def test_double_call_autodiscover(self):
# The first time autodiscover is called, we should get our real error. # The first time autodiscover is called, we should get our real error.
with self.assertRaises(Exception) as cm: with self.assertRaisesMessage(Exception, 'Bad admin module'):
admin.autodiscover() admin.autodiscover()
self.assertEqual(str(cm.exception), "Bad admin module")
# Calling autodiscover again should raise the very same error it did # Calling autodiscover again should raise the very same error it did
# the first time, not an AlreadyRegistered error. # the first time, not an AlreadyRegistered error.
with self.assertRaises(Exception) as cm: with self.assertRaisesMessage(Exception, 'Bad admin module'):
admin.autodiscover() admin.autodiscover()
self.assertEqual(str(cm.exception), "Bad admin module")

View File

@ -164,9 +164,8 @@ class UserPassesTestTests(SimpleTestCase):
request = self.factory.get('/rand') request = self.factory.get('/rand')
request.user = AnonymousUser() request.user = AnonymousUser()
view = AView.as_view() view = AView.as_view()
with self.assertRaises(PermissionDenied) as cm: with self.assertRaisesMessage(PermissionDenied, msg):
view(request) view(request)
self.assertEqual(cm.exception.args[0], msg)
def test_raise_exception_custom_message_function(self): def test_raise_exception_custom_message_function(self):
msg = "You don't have access here" msg = "You don't have access here"
@ -180,9 +179,8 @@ class UserPassesTestTests(SimpleTestCase):
request = self.factory.get('/rand') request = self.factory.get('/rand')
request.user = AnonymousUser() request.user = AnonymousUser()
view = AView.as_view() view = AView.as_view()
with self.assertRaises(PermissionDenied) as cm: with self.assertRaisesMessage(PermissionDenied, msg):
view(request) view(request)
self.assertEqual(cm.exception.args[0], msg)
def test_user_passes(self): def test_user_passes(self):
view = AlwaysTrueView.as_view() view = AlwaysTrueView.as_view()

View File

@ -541,10 +541,10 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
]) ])
def test_ambiguous_compressed_fixture(self): def test_ambiguous_compressed_fixture(self):
# The name "fixture5" is ambiguous, so loading it will raise an error # The name "fixture5" is ambiguous, so loading raises an error.
with self.assertRaises(management.CommandError) as cm: msg = "Multiple fixtures named 'fixture5'"
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command('loaddata', 'fixture5', verbosity=0) management.call_command('loaddata', 'fixture5', verbosity=0)
self.assertIn("Multiple fixtures named 'fixture5'", cm.exception.args[0])
def test_db_loading(self): def test_db_loading(self):
# Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly
@ -566,9 +566,9 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
if connection.vendor == 'mysql': if connection.vendor == 'mysql':
with connection.cursor() as cursor: with connection.cursor() as cursor:
cursor.execute("SET sql_mode = 'TRADITIONAL'") cursor.execute("SET sql_mode = 'TRADITIONAL'")
with self.assertRaises(IntegrityError) as cm: msg = 'Could not load fixtures.Article(pk=1):'
with self.assertRaisesMessage(IntegrityError, msg):
management.call_command('loaddata', 'invalid.json', verbosity=0) management.call_command('loaddata', 'invalid.json', verbosity=0)
self.assertIn("Could not load fixtures.Article(pk=1):", cm.exception.args[0])
@unittest.skipUnless(connection.vendor == 'postgresql', 'psycopg2 prohibits null characters in data.') @unittest.skipUnless(connection.vendor == 'postgresql', 'psycopg2 prohibits null characters in data.')
def test_loaddata_null_characters_on_postgresql(self): def test_loaddata_null_characters_on_postgresql(self):
@ -760,9 +760,9 @@ class FixtureTransactionTests(DumpDataAssertMixin, TransactionTestCase):
# Try to load fixture 2 using format discovery; this will fail # Try to load fixture 2 using format discovery; this will fail
# because there are two fixture2's in the fixtures directory # because there are two fixture2's in the fixtures directory
with self.assertRaises(management.CommandError) as cm: msg = "Multiple fixtures named 'fixture2'"
with self.assertRaisesMessage(management.CommandError, msg):
management.call_command('loaddata', 'fixture2', verbosity=0) management.call_command('loaddata', 'fixture2', verbosity=0)
self.assertIn("Multiple fixtures named 'fixture2'", cm.exception.args[0])
# object list is unaffected # object list is unaffected
self.assertQuerysetEqual(Article.objects.all(), [ self.assertQuerysetEqual(Article.objects.all(), [

View File

@ -79,9 +79,8 @@ class SerializerRegistrationTests(SimpleTestCase):
serializers.get_serializer("nonsense") serializers.get_serializer("nonsense")
# SerializerDoesNotExist is instantiated with the nonexistent format # SerializerDoesNotExist is instantiated with the nonexistent format
with self.assertRaises(SerializerDoesNotExist) as cm: with self.assertRaisesMessage(SerializerDoesNotExist, 'nonsense'):
serializers.get_serializer("nonsense") serializers.get_serializer("nonsense")
self.assertEqual(cm.exception.args, ("nonsense",))
def test_get_unknown_deserializer(self): def test_get_unknown_deserializer(self):
with self.assertRaises(SerializerDoesNotExist): with self.assertRaises(SerializerDoesNotExist):

View File

@ -201,9 +201,8 @@ class IncludeTests(SimpleTestCase):
""" """
engine = Engine(app_dirs=True, debug=True) engine = Engine(app_dirs=True, debug=True)
template = engine.get_template('test_include_error.html') template = engine.get_template('test_include_error.html')
with self.assertRaises(TemplateDoesNotExist) as e: with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context()) template.render(Context())
self.assertEqual(e.exception.args[0], 'missing.html')
def test_extends_include_missing_baseloader(self): def test_extends_include_missing_baseloader(self):
""" """
@ -213,9 +212,8 @@ class IncludeTests(SimpleTestCase):
""" """
engine = Engine(app_dirs=True, debug=True) engine = Engine(app_dirs=True, debug=True)
template = engine.get_template('test_extends_error.html') template = engine.get_template('test_extends_error.html')
with self.assertRaises(TemplateDoesNotExist) as e: with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context()) template.render(Context())
self.assertEqual(e.exception.args[0], 'missing.html')
def test_extends_include_missing_cachedloader(self): def test_extends_include_missing_cachedloader(self):
engine = Engine(debug=True, loaders=[ engine = Engine(debug=True, loaders=[
@ -225,15 +223,13 @@ class IncludeTests(SimpleTestCase):
]) ])
template = engine.get_template('test_extends_error.html') template = engine.get_template('test_extends_error.html')
with self.assertRaises(TemplateDoesNotExist) as e: with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context()) template.render(Context())
self.assertEqual(e.exception.args[0], 'missing.html')
# Repeat to ensure it still works when loading from the cache # Repeat to ensure it still works when loading from the cache
template = engine.get_template('test_extends_error.html') template = engine.get_template('test_extends_error.html')
with self.assertRaises(TemplateDoesNotExist) as e: with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context()) template.render(Context())
self.assertEqual(e.exception.args[0], 'missing.html')
def test_include_template_argument(self): def test_include_template_argument(self):
""" """

View File

@ -213,58 +213,37 @@ class AssertTemplateUsedTests(TestDataMixin, TestCase):
except AssertionError as e: except AssertionError as e:
self.assertIn("abc: No templates used to render the response", str(e)) self.assertIn("abc: No templates used to render the response", str(e))
with self.assertRaises(AssertionError) as context: msg = 'No templates used to render the response'
with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, 'GET Template', count=2) self.assertTemplateUsed(response, 'GET Template', count=2)
self.assertIn(
"No templates used to render the response",
str(context.exception))
def test_single_context(self): def test_single_context(self):
"Template assertions work when there is a single context" "Template assertions work when there is a single context"
response = self.client.get('/post_view/', {}) response = self.client.get('/post_view/', {})
msg = (
try: ": Template 'Empty GET Template' was used unexpectedly in "
"rendering the response"
)
with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateNotUsed(response, 'Empty GET Template') self.assertTemplateNotUsed(response, 'Empty GET Template')
except AssertionError as e: with self.assertRaisesMessage(AssertionError, 'abc' + msg):
self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
try:
self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc') self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc')
except AssertionError as e: msg = (
self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e)) ": Template 'Empty POST Template' was not a template used to "
"render the response. Actual template(s) used: Empty GET Template"
try: )
with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, 'Empty POST Template') self.assertTemplateUsed(response, 'Empty POST Template')
except AssertionError as e: with self.assertRaisesMessage(AssertionError, 'abc' + msg):
self.assertIn(
"Template 'Empty POST Template' was not a template used to "
"render the response. Actual template(s) used: Empty GET Template",
str(e)
)
try:
self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc') self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc')
except AssertionError as e: msg = (
self.assertIn( ": Template 'Empty GET Template' was expected to be rendered 2 "
"abc: Template 'Empty POST Template' was not a template used " "time(s) but was actually rendered 1 time(s)."
"to render the response. Actual template(s) used: Empty GET Template", )
str(e) with self.assertRaisesMessage(AssertionError, msg):
)
with self.assertRaises(AssertionError) as context:
self.assertTemplateUsed(response, 'Empty GET Template', count=2) self.assertTemplateUsed(response, 'Empty GET Template', count=2)
self.assertIn( with self.assertRaisesMessage(AssertionError, 'abc' + msg):
"Template 'Empty GET Template' was expected to be rendered 2 " self.assertTemplateUsed(response, 'Empty GET Template', msg_prefix='abc', count=2)
"time(s) but was actually rendered 1 time(s).",
str(context.exception))
with self.assertRaises(AssertionError) as context:
self.assertTemplateUsed(
response, 'Empty GET Template', msg_prefix='abc', count=2)
self.assertIn(
"abc: Template 'Empty GET Template' was expected to be rendered 2 "
"time(s) but was actually rendered 1 time(s).",
str(context.exception))
def test_multiple_context(self): def test_multiple_context(self):
"Template assertions work when there are multiple contexts" "Template assertions work when there are multiple contexts"
@ -277,31 +256,23 @@ class AssertTemplateUsedTests(TestDataMixin, TestCase):
} }
response = self.client.post('/form_view_with_template/', post_data) response = self.client.post('/form_view_with_template/', post_data)
self.assertContains(response, 'POST data OK') self.assertContains(response, 'POST data OK')
try: msg = "Template '%s' was used unexpectedly in rendering the response"
with self.assertRaisesMessage(AssertionError, msg % 'form_view.html'):
self.assertTemplateNotUsed(response, "form_view.html") self.assertTemplateNotUsed(response, "form_view.html")
except AssertionError as e: with self.assertRaisesMessage(AssertionError, msg % 'base.html'):
self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e))
try:
self.assertTemplateNotUsed(response, 'base.html') self.assertTemplateNotUsed(response, 'base.html')
except AssertionError as e: msg = (
self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e)) "Template 'Valid POST Template' was not a template used to render "
"the response. Actual template(s) used: form_view.html, base.html"
try: )
with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, "Valid POST Template") self.assertTemplateUsed(response, "Valid POST Template")
except AssertionError as e: msg = (
self.assertIn( "Template 'base.html' was expected to be rendered 2 time(s) but "
"Template 'Valid POST Template' was not a template used to " "was actually rendered 1 time(s)."
"render the response. Actual template(s) used: form_view.html, base.html", )
str(e) with self.assertRaisesMessage(AssertionError, msg):
)
with self.assertRaises(AssertionError) as context:
self.assertTemplateUsed(response, 'base.html', count=2) self.assertTemplateUsed(response, 'base.html', count=2)
self.assertIn(
"Template 'base.html' was expected to be rendered 2 "
"time(s) but was actually rendered 1 time(s).",
str(context.exception))
def test_template_rendered_multiple_times(self): def test_template_rendered_multiple_times(self):
"""Template assertions work when a template is rendered multiple times.""" """Template assertions work when a template is rendered multiple times."""
@ -947,9 +918,8 @@ class ContextTests(TestDataMixin, TestCase):
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['data'], 'bacon') self.assertEqual(response.context['data'], 'bacon')
with self.assertRaises(KeyError) as cm: with self.assertRaisesMessage(KeyError, 'does-not-exist'):
response.context['does-not-exist'] response.context['does-not-exist']
self.assertEqual(cm.exception.args[0], 'does-not-exist')
def test_contextlist_keys(self): def test_contextlist_keys(self):
c1 = Context() c1 = Context()

View File

@ -374,13 +374,13 @@ class AssertNumQueriesContextManagerTests(TestCase):
Person.objects.count() Person.objects.count()
def test_failure(self): def test_failure(self):
with self.assertRaises(AssertionError) as exc_info: msg = (
'1 != 2 : 1 queries executed, 2 expected\nCaptured queries were:\n'
'1.'
)
with self.assertRaisesMessage(AssertionError, msg):
with self.assertNumQueries(2): with self.assertNumQueries(2):
Person.objects.count() Person.objects.count()
exc_lines = str(exc_info.exception).split('\n')
self.assertEqual(exc_lines[0], '1 != 2 : 1 queries executed, 2 expected')
self.assertEqual(exc_lines[1], 'Captured queries were:')
self.assertTrue(exc_lines[2].startswith('1.')) # queries are numbered
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
with self.assertNumQueries(4000): with self.assertNumQueries(4000):

View File

@ -44,9 +44,8 @@ class MultiValueDictTests(SimpleTestCase):
sorted(d.lists()), sorted(d.lists()),
[('name', ['Adrian', 'Simon']), ('position', ['Developer'])] [('name', ['Adrian', 'Simon']), ('position', ['Developer'])]
) )
with self.assertRaises(MultiValueDictKeyError) as cm: with self.assertRaisesMessage(MultiValueDictKeyError, "'lastname'"):
d.__getitem__('lastname') d.__getitem__('lastname')
self.assertEqual(str(cm.exception), "'lastname'")
self.assertIsNone(d.get('lastname')) 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'), [])