summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorHasan Ramezani <hasan.r67@gmail.com>2020-02-04 21:58:07 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2020-02-07 12:46:23 +0100
commitfc4f45ebdccd87f140f39bebed897053c7f345c5 (patch)
tree0080670fe0c04124b7b2e15766fac2d73a00f164
parent71756bdfed5029bd14dce8cb3c5629efc4be55ac (diff)
Used assertRaisesMessage() in various tests.
-rw-r--r--tests/admin_autodiscover/tests.py12
-rw-r--r--tests/auth_tests/test_mixins.py6
-rw-r--r--tests/fixtures/tests.py14
-rw-r--r--tests/serializers/tests.py3
-rw-r--r--tests/template_tests/syntax_tests/test_include.py12
-rw-r--r--tests/test_client_regress/tests.py100
-rw-r--r--tests/test_utils/tests.py10
-rw-r--r--tests/utils_tests/test_datastructures.py3
8 files changed, 59 insertions, 101 deletions
diff --git a/tests/admin_autodiscover/tests.py b/tests/admin_autodiscover/tests.py
index af5aebcd7f..b15060ade8 100644
--- a/tests/admin_autodiscover/tests.py
+++ b/tests/admin_autodiscover/tests.py
@@ -1,21 +1,17 @@
-from unittest import TestCase
-
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
autodiscover() and an admin.py module contains an error.
"""
def test_double_call_autodiscover(self):
# 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()
- self.assertEqual(str(cm.exception), "Bad admin module")
-
# Calling autodiscover again should raise the very same error it did
# the first time, not an AlreadyRegistered error.
- with self.assertRaises(Exception) as cm:
+ with self.assertRaisesMessage(Exception, 'Bad admin module'):
admin.autodiscover()
- self.assertEqual(str(cm.exception), "Bad admin module")
diff --git a/tests/auth_tests/test_mixins.py b/tests/auth_tests/test_mixins.py
index 5f0379bcd0..ca3a249d75 100644
--- a/tests/auth_tests/test_mixins.py
+++ b/tests/auth_tests/test_mixins.py
@@ -164,9 +164,8 @@ class UserPassesTestTests(SimpleTestCase):
request = self.factory.get('/rand')
request.user = AnonymousUser()
view = AView.as_view()
- with self.assertRaises(PermissionDenied) as cm:
+ with self.assertRaisesMessage(PermissionDenied, msg):
view(request)
- self.assertEqual(cm.exception.args[0], msg)
def test_raise_exception_custom_message_function(self):
msg = "You don't have access here"
@@ -180,9 +179,8 @@ class UserPassesTestTests(SimpleTestCase):
request = self.factory.get('/rand')
request.user = AnonymousUser()
view = AView.as_view()
- with self.assertRaises(PermissionDenied) as cm:
+ with self.assertRaisesMessage(PermissionDenied, msg):
view(request)
- self.assertEqual(cm.exception.args[0], msg)
def test_user_passes(self):
view = AlwaysTrueView.as_view()
diff --git a/tests/fixtures/tests.py b/tests/fixtures/tests.py
index 16e90dea38..0027c62c20 100644
--- a/tests/fixtures/tests.py
+++ b/tests/fixtures/tests.py
@@ -541,10 +541,10 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
])
def test_ambiguous_compressed_fixture(self):
- # The name "fixture5" is ambiguous, so loading it will raise an error
- with self.assertRaises(management.CommandError) as cm:
+ # The name "fixture5" is ambiguous, so loading raises an error.
+ msg = "Multiple fixtures named 'fixture5'"
+ with self.assertRaisesMessage(management.CommandError, msg):
management.call_command('loaddata', 'fixture5', verbosity=0)
- self.assertIn("Multiple fixtures named 'fixture5'", cm.exception.args[0])
def test_db_loading(self):
# 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':
with connection.cursor() as cursor:
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)
- self.assertIn("Could not load fixtures.Article(pk=1):", cm.exception.args[0])
@unittest.skipUnless(connection.vendor == 'postgresql', 'psycopg2 prohibits null characters in data.')
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
# 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)
- self.assertIn("Multiple fixtures named 'fixture2'", cm.exception.args[0])
# object list is unaffected
self.assertQuerysetEqual(Article.objects.all(), [
diff --git a/tests/serializers/tests.py b/tests/serializers/tests.py
index 4bee157ace..863ee00e89 100644
--- a/tests/serializers/tests.py
+++ b/tests/serializers/tests.py
@@ -79,9 +79,8 @@ class SerializerRegistrationTests(SimpleTestCase):
serializers.get_serializer("nonsense")
# SerializerDoesNotExist is instantiated with the nonexistent format
- with self.assertRaises(SerializerDoesNotExist) as cm:
+ with self.assertRaisesMessage(SerializerDoesNotExist, 'nonsense'):
serializers.get_serializer("nonsense")
- self.assertEqual(cm.exception.args, ("nonsense",))
def test_get_unknown_deserializer(self):
with self.assertRaises(SerializerDoesNotExist):
diff --git a/tests/template_tests/syntax_tests/test_include.py b/tests/template_tests/syntax_tests/test_include.py
index 8587639674..b840c676f7 100644
--- a/tests/template_tests/syntax_tests/test_include.py
+++ b/tests/template_tests/syntax_tests/test_include.py
@@ -201,9 +201,8 @@ class IncludeTests(SimpleTestCase):
"""
engine = Engine(app_dirs=True, debug=True)
template = engine.get_template('test_include_error.html')
- with self.assertRaises(TemplateDoesNotExist) as e:
+ with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context())
- self.assertEqual(e.exception.args[0], 'missing.html')
def test_extends_include_missing_baseloader(self):
"""
@@ -213,9 +212,8 @@ class IncludeTests(SimpleTestCase):
"""
engine = Engine(app_dirs=True, debug=True)
template = engine.get_template('test_extends_error.html')
- with self.assertRaises(TemplateDoesNotExist) as e:
+ with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context())
- self.assertEqual(e.exception.args[0], 'missing.html')
def test_extends_include_missing_cachedloader(self):
engine = Engine(debug=True, loaders=[
@@ -225,15 +223,13 @@ class IncludeTests(SimpleTestCase):
])
template = engine.get_template('test_extends_error.html')
- with self.assertRaises(TemplateDoesNotExist) as e:
+ with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context())
- self.assertEqual(e.exception.args[0], 'missing.html')
# Repeat to ensure it still works when loading from the cache
template = engine.get_template('test_extends_error.html')
- with self.assertRaises(TemplateDoesNotExist) as e:
+ with self.assertRaisesMessage(TemplateDoesNotExist, 'missing.html'):
template.render(Context())
- self.assertEqual(e.exception.args[0], 'missing.html')
def test_include_template_argument(self):
"""
diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py
index 1a8d069ea1..cb6cb4a8ac 100644
--- a/tests/test_client_regress/tests.py
+++ b/tests/test_client_regress/tests.py
@@ -213,58 +213,37 @@ class AssertTemplateUsedTests(TestDataMixin, TestCase):
except AssertionError as 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.assertIn(
- "No templates used to render the response",
- str(context.exception))
def test_single_context(self):
"Template assertions work when there is a single context"
response = self.client.get('/post_view/', {})
-
- try:
+ msg = (
+ ": Template 'Empty GET Template' was used unexpectedly in "
+ "rendering the response"
+ )
+ with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateNotUsed(response, 'Empty GET Template')
- except AssertionError as e:
- self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
-
- try:
+ with self.assertRaisesMessage(AssertionError, 'abc' + msg):
self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc')
- except AssertionError as e:
- self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
-
- try:
+ msg = (
+ ": Template 'Empty POST Template' was not a template used to "
+ "render the response. Actual template(s) used: Empty GET Template"
+ )
+ with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, 'Empty POST Template')
- except AssertionError as e:
- 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:
+ with self.assertRaisesMessage(AssertionError, 'abc' + msg):
self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc')
- except AssertionError as e:
- self.assertIn(
- "abc: Template 'Empty POST Template' was not a template used "
- "to render the response. Actual template(s) used: Empty GET Template",
- str(e)
- )
-
- with self.assertRaises(AssertionError) as context:
+ msg = (
+ ": Template 'Empty GET Template' was expected to be rendered 2 "
+ "time(s) but was actually rendered 1 time(s)."
+ )
+ with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, 'Empty GET Template', count=2)
- self.assertIn(
- "Template 'Empty GET Template' was expected to be rendered 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))
+ with self.assertRaisesMessage(AssertionError, 'abc' + msg):
+ self.assertTemplateUsed(response, 'Empty GET Template', msg_prefix='abc', count=2)
def test_multiple_context(self):
"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)
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")
- except AssertionError as e:
- self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e))
-
- try:
+ with self.assertRaisesMessage(AssertionError, msg % 'base.html'):
self.assertTemplateNotUsed(response, 'base.html')
- except AssertionError as e:
- self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e))
-
- try:
+ msg = (
+ "Template 'Valid POST Template' was not a template used to render "
+ "the response. Actual template(s) used: form_view.html, base.html"
+ )
+ with self.assertRaisesMessage(AssertionError, msg):
self.assertTemplateUsed(response, "Valid POST Template")
- except AssertionError as e:
- self.assertIn(
- "Template 'Valid POST Template' was not a template used to "
- "render the response. Actual template(s) used: form_view.html, base.html",
- str(e)
- )
-
- with self.assertRaises(AssertionError) as context:
+ msg = (
+ "Template 'base.html' was expected to be rendered 2 time(s) but "
+ "was actually rendered 1 time(s)."
+ )
+ with self.assertRaisesMessage(AssertionError, msg):
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):
"""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['data'], 'bacon')
- with self.assertRaises(KeyError) as cm:
+ with self.assertRaisesMessage(KeyError, 'does-not-exist'):
response.context['does-not-exist']
- self.assertEqual(cm.exception.args[0], 'does-not-exist')
def test_contextlist_keys(self):
c1 = Context()
diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py
index c61358f4c8..8d7e6e4889 100644
--- a/tests/test_utils/tests.py
+++ b/tests/test_utils/tests.py
@@ -374,13 +374,13 @@ class AssertNumQueriesContextManagerTests(TestCase):
Person.objects.count()
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):
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.assertNumQueries(4000):
diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py
index 3400b1d65a..3e6f903be2 100644
--- a/tests/utils_tests/test_datastructures.py
+++ b/tests/utils_tests/test_datastructures.py
@@ -44,9 +44,8 @@ class MultiValueDictTests(SimpleTestCase):
sorted(d.lists()),
[('name', ['Adrian', 'Simon']), ('position', ['Developer'])]
)
- with self.assertRaises(MultiValueDictKeyError) as cm:
+ with self.assertRaisesMessage(MultiValueDictKeyError, "'lastname'"):
d.__getitem__('lastname')
- self.assertEqual(str(cm.exception), "'lastname'")
self.assertIsNone(d.get('lastname'))
self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent')
self.assertEqual(d.getlist('lastname'), [])