Refs #23919 -- Simplified assertRaisesRegex()'s that accounted for Python 2.

This commit is contained in:
Tim Graham 2017-01-19 21:10:33 -05:00 committed by Aymeric Augustin
parent dc8834cad4
commit 109b33f64c
12 changed files with 43 additions and 42 deletions

View File

@ -251,7 +251,7 @@ class TestUtilsHashPass(SimpleTestCase):
self.assertFalse(check_password('', encoded))
self.assertFalse(check_password('lètmein', encoded))
self.assertFalse(check_password('lètmeinz', encoded))
with self.assertRaises(ValueError):
with self.assertRaisesMessage(ValueError, 'Unknown password hashing algorith'):
identify_hasher(encoded)
# Assert that the unusable passwords actually contain a random part.
# This might fail one day due to a hash collision.
@ -265,9 +265,13 @@ class TestUtilsHashPass(SimpleTestCase):
self.assertFalse(check_password(None, make_password('lètmein')))
def test_bad_algorithm(self):
with self.assertRaises(ValueError):
msg = (
"Unknown password hashing algorithm '%s'. Did you specify it in "
"the PASSWORD_HASHERS setting?"
)
with self.assertRaisesMessage(ValueError, msg % 'lolcat'):
make_password('lètmein', hasher='lolcat')
with self.assertRaises(ValueError):
with self.assertRaisesMessage(ValueError, msg % 'lolcat'):
identify_hasher('lolcat$salt$hash')
def test_bad_encoded(self):
@ -424,15 +428,15 @@ class TestUtilsHashPass(SimpleTestCase):
self.assertEqual(hasher.harden_runtime.call_count, 1)
def test_load_library_no_algorithm(self):
with self.assertRaises(ValueError) as e:
msg = "Hasher 'BasePasswordHasher' doesn't specify a library attribute"
with self.assertRaisesMessage(ValueError, msg):
BasePasswordHasher()._load_library()
self.assertEqual("Hasher 'BasePasswordHasher' doesn't specify a library attribute", str(e.exception))
def test_load_library_importerror(self):
PlainHasher = type('PlainHasher', (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'})
# Python 3 adds quotes around module name
msg = "Couldn't load 'PlainHasher' algorithm library: No module named '?plain'?"
with self.assertRaisesRegex(ValueError, msg):
msg = "Couldn't load 'PlainHasher' algorithm library: No module named 'plain'"
with self.assertRaisesMessage(ValueError, msg):
PlainHasher()._load_library()

View File

@ -45,7 +45,7 @@ class GetStorageClassTests(SimpleTestCase):
"""
get_storage_class raises an error if the requested import don't exist.
"""
with self.assertRaisesRegex(ImportError, "No module named '?storage'?"):
with self.assertRaisesMessage(ImportError, "No module named 'storage'"):
get_storage_class('storage.NonExistingStorage')
def test_get_nonexisting_storage_class(self):
@ -59,8 +59,7 @@ class GetStorageClassTests(SimpleTestCase):
"""
get_storage_class raises an error if the requested module don't exist.
"""
# Error message may or may not be the fully qualified path.
with self.assertRaisesRegex(ImportError, "No module named '?(django.core.files.)?non_existing_storage'?"):
with self.assertRaisesMessage(ImportError, "No module named 'django.core.files.non_existing_storage'"):
get_storage_class('django.core.files.non_existing_storage.NonExistingStorage')

View File

@ -197,7 +197,7 @@ class TestFixtures(TestCase):
"""
Failing serializer import raises the proper error
"""
with self.assertRaisesRegex(ImportError, r"No module named.*unexistent"):
with self.assertRaisesMessage(ImportError, "No module named 'unexistent'"):
management.call_command(
'loaddata',
'bad_fixture1.unkn',

View File

@ -42,10 +42,10 @@ class RegexFieldTest(SimpleTestCase):
f = RegexField('^[0-9]+$', min_length=5, max_length=10)
with self.assertRaisesMessage(ValidationError, "'Ensure this value has at least 5 characters (it has 3).'"):
f.clean('123')
with self.assertRaisesRegex(
with self.assertRaisesMessage(
ValidationError,
r"'Ensure this value has at least 5 characters \(it has 3\)\.',"
r" u?'Enter a valid value\.'",
"'Ensure this value has at least 5 characters (it has 3).', "
"'Enter a valid value.'",
):
f.clean('abc')
self.assertEqual('12345', f.clean('12345'))

View File

@ -20,7 +20,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
f.clean('')
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello')
with self.assertRaisesRegex(ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.', 'Enter a valid time.'"):
f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there'])
@ -40,7 +40,7 @@ class SplitDateTimeFieldTest(SimpleTestCase):
self.assertIsNone(f.clean(['', '']))
with self.assertRaisesMessage(ValidationError, "'Enter a list of values.'"):
f.clean('hello')
with self.assertRaisesRegex(ValidationError, r"'Enter a valid date\.', u?'Enter a valid time\.'"):
with self.assertRaisesMessage(ValidationError, "'Enter a valid date.', 'Enter a valid time.'"):
f.clean(['hello', 'there'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid time.'"):
f.clean(['2006-01-10', 'there'])

View File

@ -2954,10 +2954,8 @@ Good luck picking a username that doesn&#39;t already exist.</p>
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
self.assertRaisesRegex(
ValidationError,
r"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']
)
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"):
f.clean(['', '', '', 'Home'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home'])
@ -2970,7 +2968,7 @@ Good luck picking a username that doesn&#39;t already exist.</p>
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
f.clean(['+61'])
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
with self.assertRaisesRegex(ValidationError, r"'Enter a complete value\.', u?'Enter an extension\.'"):
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.', 'Enter an extension.'"):
f.clean(['', '', '', 'Home'])
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
f.clean(['61', '287654321', '123', 'Home'])

View File

@ -450,7 +450,7 @@ class WriterTests(SimpleTestCase):
self.assertEqual(string, "migrations.test_writer.EmailValidator(message='hello')")
validator = deconstructible(path="custom.EmailValidator")(EmailValidator)(message="hello")
with self.assertRaisesRegex(ImportError, "No module named '?custom'?"):
with self.assertRaisesMessage(ImportError, "No module named 'custom'"):
MigrationWriter.serialize(validator)
validator = deconstructible(path="django.core.validators.EmailValidator2")(EmailValidator)(message="hello")

View File

@ -11,9 +11,9 @@ class TemplateUtilsTests(SimpleTestCase):
Failing to import a backend keeps raising the original import error
(#24265).
"""
with self.assertRaisesRegex(ImportError, "No module named '?raise"):
with self.assertRaisesMessage(ImportError, "No module named 'raise"):
engines.all()
with self.assertRaisesRegex(ImportError, "No module named '?raise"):
with self.assertRaisesMessage(ImportError, "No module named 'raise"):
engines.all()
@override_settings(TEMPLATES=[{

View File

@ -313,25 +313,21 @@ class TemplateTagLoadingTests(SimpleTestCase):
msg = (
"Invalid template library specified. ImportError raised when "
"trying to load 'template_tests.broken_tag': cannot import name "
"'?Xtemplate'?"
"'Xtemplate'"
)
with self.assertRaisesRegex(InvalidTemplateLibrary, msg):
Engine(libraries={
'broken_tag': 'template_tests.broken_tag',
})
with self.assertRaisesMessage(InvalidTemplateLibrary, msg):
Engine(libraries={'broken_tag': 'template_tests.broken_tag'})
def test_load_error_egg(self):
egg_name = '%s/tagsegg.egg' % self.egg_dir
msg = (
"Invalid template library specified. ImportError raised when "
"trying to load 'tagsegg.templatetags.broken_egg': cannot "
"import name '?Xtemplate'?"
"import name 'Xtemplate'"
)
with extend_sys_path(egg_name):
with self.assertRaisesRegex(InvalidTemplateLibrary, msg):
Engine(libraries={
'broken_egg': 'tagsegg.templatetags.broken_egg',
})
with self.assertRaisesMessage(InvalidTemplateLibrary, msg):
Engine(libraries={'broken_egg': 'tagsegg.templatetags.broken_egg'})
def test_load_working_egg(self):
ttext = "{% load working_egg %}"

View File

@ -68,7 +68,7 @@ class ParserTests(SimpleTestCase):
Variable("article._hidden")
# Variables should raise on non string type
with self.assertRaisesRegex(TypeError, "Variable must be a string or number, got <(class|type) 'dict'>"):
with self.assertRaisesMessage(TypeError, "Variable must be a string or number, got <class 'dict'>"):
Variable({})
def test_filter_args_count(self):

View File

@ -362,22 +362,26 @@ class AssertTemplateUsedContextManagerTests(SimpleTestCase):
pass
def test_error_message(self):
with self.assertRaisesRegex(AssertionError, r'^template_used/base\.html'):
msg = 'template_used/base.html was not rendered. No template was rendered.'
with self.assertRaisesMessage(AssertionError, msg):
with self.assertTemplateUsed('template_used/base.html'):
pass
with self.assertRaisesRegex(AssertionError, r'^template_used/base\.html'):
with self.assertRaisesMessage(AssertionError, msg):
with self.assertTemplateUsed(template_name='template_used/base.html'):
pass
with self.assertRaisesRegex(AssertionError, r'^template_used/base\.html.*template_used/alternative\.html$'):
msg2 = (
'template_used/base.html was not rendered. Following templates '
'were rendered: template_used/alternative.html'
)
with self.assertRaisesMessage(AssertionError, msg2):
with self.assertTemplateUsed('template_used/base.html'):
render_to_string('template_used/alternative.html')
with self.assertRaises(AssertionError) as cm:
with self.assertRaisesMessage(AssertionError, 'No templates used to render the response'):
response = self.client.get('/test_utils/no_template_used/')
self.assertTemplateUsed(response, 'template_used/base.html')
self.assertEqual(cm.exception.args[0], "No templates used to render the response")
def test_failure(self):
with self.assertRaises(TypeError):

View File

@ -146,11 +146,11 @@ class AutodiscoverModulesTestCase(SimpleTestCase):
autodiscover_modules('missing_module')
def test_autodiscover_modules_found_but_bad_module(self):
with self.assertRaisesRegex(ImportError, "No module named '?a_package_name_that_does_not_exist'?"):
with self.assertRaisesMessage(ImportError, "No module named 'a_package_name_that_does_not_exist'"):
autodiscover_modules('bad_module')
def test_autodiscover_modules_several_one_bad_module(self):
with self.assertRaisesRegex(ImportError, "No module named '?a_package_name_that_does_not_exist'?"):
with self.assertRaisesMessage(ImportError, "No module named 'a_package_name_that_does_not_exist'"):
autodiscover_modules('good_module', 'bad_module')
def test_autodiscover_modules_several_found(self):