Refs #26022 -- Replaced six.assertRaisesRegex with assertRaisesMessage as appropriate.

This commit is contained in:
Hasan 2016-01-18 12:15:45 +03:30 committed by Tim Graham
parent 253adc2b8a
commit 26ad01719d
23 changed files with 124 additions and 221 deletions

View File

@ -13,7 +13,6 @@ from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.test import RequestFactory, TestCase, override_settings from django.test import RequestFactory, TestCase, override_settings
from django.utils import six
from django.utils.encoding import force_text from django.utils.encoding import force_text
from .models import Book, Bookmark, Department, Employee, TaggedItem from .models import Book, Bookmark, Department, Employee, TaggedItem
@ -818,9 +817,9 @@ class ListFiltersTests(TestCase):
""" """
modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site) modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site)
request = self.request_factory.get('/', {}) request = self.request_factory.get('/', {})
six.assertRaisesRegex(self, ImproperlyConfigured, msg = "The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'."
"The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'.", with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.get_changelist, request, Book, modeladmin) self.get_changelist(request, Book, modeladmin)
def test_simplelistfilter_without_parameter(self): def test_simplelistfilter_without_parameter(self):
""" """
@ -828,9 +827,9 @@ class ListFiltersTests(TestCase):
""" """
modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site) modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site)
request = self.request_factory.get('/', {}) request = self.request_factory.get('/', {})
six.assertRaisesRegex(self, ImproperlyConfigured, msg = "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'."
"The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'.", with self.assertRaisesMessage(ImproperlyConfigured, msg):
self.get_changelist, request, Book, modeladmin) self.get_changelist(request, Book, modeladmin)
def test_simplelistfilter_with_none_returning_lookups(self): def test_simplelistfilter_with_none_returning_lookups(self):
""" """

View File

@ -12,7 +12,7 @@ from django.db.models import (
) )
from django.test import TestCase from django.test import TestCase
from django.test.utils import Approximate, CaptureQueriesContext from django.test.utils import Approximate, CaptureQueriesContext
from django.utils import six, timezone from django.utils import timezone
from .models import Author, Book, Publisher, Store from .models import Author, Book, Publisher, Store
@ -906,7 +906,7 @@ class AggregateTestCase(TestCase):
self.assertEqual(book['price_sum'], Decimal("99999.80")) self.assertEqual(book['price_sum'], Decimal("99999.80"))
def test_nonaggregate_aggregation_throws(self): def test_nonaggregate_aggregation_throws(self):
with six.assertRaisesRegex(self, TypeError, 'fail is not an aggregate expression'): with self.assertRaisesMessage(TypeError, 'fail is not an aggregate expression'):
Book.objects.aggregate(fail=F('price')) Book.objects.aggregate(fail=F('price'))
def test_nonfield_annotation(self): def test_nonfield_annotation(self):
@ -918,7 +918,7 @@ class AggregateTestCase(TestCase):
self.assertEqual(book.val, 2) self.assertEqual(book.val, 2)
def test_missing_output_field_raises_error(self): def test_missing_output_field_raises_error(self):
with six.assertRaisesRegex(self, FieldError, 'Cannot resolve expression type, unknown output_field'): with self.assertRaisesMessage(FieldError, 'Cannot resolve expression type, unknown output_field'):
Book.objects.annotate(val=Max(2)).first() Book.objects.annotate(val=Max(2)).first()
def test_annotation_expressions(self): def test_annotation_expressions(self):
@ -962,7 +962,7 @@ class AggregateTestCase(TestCase):
self.assertEqual(p2, {'avg_price': Approximate(53.39, places=2)}) self.assertEqual(p2, {'avg_price': Approximate(53.39, places=2)})
def test_combine_different_types(self): def test_combine_different_types(self):
with six.assertRaisesRegex(self, FieldError, 'Expression contains mixed types. You must set output_field'): with self.assertRaisesMessage(FieldError, 'Expression contains mixed types. You must set output_field'):
Book.objects.annotate(sums=Sum('rating') + Sum('pages') + Sum('price')).get(pk=self.b4.pk) Book.objects.annotate(sums=Sum('rating') + Sum('pages') + Sum('price')).get(pk=self.b4.pk)
b1 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'), b1 = Book.objects.annotate(sums=Sum(F('rating') + F('pages') + F('price'),
@ -978,11 +978,11 @@ class AggregateTestCase(TestCase):
self.assertEqual(b3.sums, Approximate(Decimal("383.69"), places=2)) self.assertEqual(b3.sums, Approximate(Decimal("383.69"), places=2))
def test_complex_aggregations_require_kwarg(self): def test_complex_aggregations_require_kwarg(self):
with six.assertRaisesRegex(self, TypeError, 'Complex annotations require an alias'): with self.assertRaisesMessage(TypeError, 'Complex annotations require an alias'):
Author.objects.annotate(Sum(F('age') + F('friends__age'))) Author.objects.annotate(Sum(F('age') + F('friends__age')))
with six.assertRaisesRegex(self, TypeError, 'Complex aggregates require an alias'): with self.assertRaisesMessage(TypeError, 'Complex aggregates require an alias'):
Author.objects.aggregate(Sum('age') / Count('age')) Author.objects.aggregate(Sum('age') / Count('age'))
with six.assertRaisesRegex(self, TypeError, 'Complex aggregates require an alias'): with self.assertRaisesMessage(TypeError, 'Complex aggregates require an alias'):
Author.objects.aggregate(Sum(1)) Author.objects.aggregate(Sum(1))
def test_aggregate_over_complex_annotation(self): def test_aggregate_over_complex_annotation(self):

View File

@ -5,7 +5,6 @@ import os
from django.apps import apps from django.apps import apps
from django.test import SimpleTestCase from django.test import SimpleTestCase
from django.test.utils import extend_sys_path from django.test.utils import extend_sys_path
from django.utils import six
from django.utils._os import upath from django.utils._os import upath
@ -57,7 +56,7 @@ class EggLoadingTest(SimpleTestCase):
"""Loading an app from an egg that has an import error in its models module raises that error""" """Loading an app from an egg that has an import error in its models module raises that error"""
egg_name = '%s/brokenapp.egg' % self.egg_dir egg_name = '%s/brokenapp.egg' % self.egg_dir
with extend_sys_path(egg_name): with extend_sys_path(egg_name):
with six.assertRaisesRegex(self, ImportError, 'modelz'): with self.assertRaisesMessage(ImportError, 'modelz'):
with self.settings(INSTALLED_APPS=['broken_app']): with self.settings(INSTALLED_APPS=['broken_app']):
pass pass

View File

@ -159,12 +159,12 @@ class AppsTests(SimpleTestCase):
self.assertEqual(apps.get_app_config('relabeled').name, 'apps') self.assertEqual(apps.get_app_config('relabeled').name, 'apps')
def test_duplicate_labels(self): def test_duplicate_labels(self):
with six.assertRaisesRegex(self, ImproperlyConfigured, "Application labels aren't unique"): with self.assertRaisesMessage(ImproperlyConfigured, "Application labels aren't unique"):
with self.settings(INSTALLED_APPS=['apps.apps.PlainAppsConfig', 'apps']): with self.settings(INSTALLED_APPS=['apps.apps.PlainAppsConfig', 'apps']):
pass pass
def test_duplicate_names(self): def test_duplicate_names(self):
with six.assertRaisesRegex(self, ImproperlyConfigured, "Application names aren't unique"): with self.assertRaisesMessage(ImproperlyConfigured, "Application names aren't unique"):
with self.settings(INSTALLED_APPS=['apps.apps.RelabeledAppsConfig', 'apps']): with self.settings(INSTALLED_APPS=['apps.apps.RelabeledAppsConfig', 'apps']):
pass pass
@ -172,7 +172,7 @@ class AppsTests(SimpleTestCase):
""" """
App discovery should preserve stack traces. Regression test for #22920. App discovery should preserve stack traces. Regression test for #22920.
""" """
with six.assertRaisesRegex(self, ImportError, "Oops"): with self.assertRaisesMessage(ImportError, "Oops"):
with self.settings(INSTALLED_APPS=['import_error_package']): with self.settings(INSTALLED_APPS=['import_error_package']):
pass pass

View File

@ -427,8 +427,8 @@ class CreatesuperuserManagementCommandTestCase(TestCase):
self.assertEqual(u.group, group) self.assertEqual(u.group, group)
non_existent_email = 'mymail2@gmail.com' non_existent_email = 'mymail2@gmail.com'
with self.assertRaisesMessage(CommandError, msg = 'email instance with email %r does not exist.' % non_existent_email
'email instance with email %r does not exist.' % non_existent_email): with self.assertRaisesMessage(CommandError, msg):
call_command( call_command(
'createsuperuser', 'createsuperuser',
interactive=False, interactive=False,
@ -670,10 +670,12 @@ class PermissionTestCase(TestCase):
# check duplicated default permission # check duplicated default permission
Permission._meta.permissions = [ Permission._meta.permissions = [
('change_permission', 'Can edit permission (duplicate)')] ('change_permission', 'Can edit permission (duplicate)')]
six.assertRaisesRegex(self, CommandError, msg = (
"The permission codename 'change_permission' clashes with a " "The permission codename 'change_permission' clashes with a "
"builtin permission for model 'auth.Permission'.", "builtin permission for model 'auth.Permission'."
create_permissions, auth_app_config, verbosity=0) )
with self.assertRaisesMessage(CommandError, msg):
create_permissions(auth_app_config, verbosity=0)
# check duplicated custom permissions # check duplicated custom permissions
Permission._meta.permissions = [ Permission._meta.permissions = [
@ -681,10 +683,9 @@ class PermissionTestCase(TestCase):
('other_one', 'Some other permission'), ('other_one', 'Some other permission'),
('my_custom_permission', 'Some permission with duplicate permission code'), ('my_custom_permission', 'Some permission with duplicate permission code'),
] ]
six.assertRaisesRegex(self, CommandError, msg = "The permission codename 'my_custom_permission' is duplicated for model 'auth.Permission'."
"The permission codename 'my_custom_permission' is duplicated for model " with self.assertRaisesMessage(CommandError, msg):
"'auth.Permission'.", create_permissions(auth_app_config, verbosity=0)
create_permissions, auth_app_config, verbosity=0)
# should not raise anything # should not raise anything
Permission._meta.permissions = [ Permission._meta.permissions = [
@ -723,9 +724,9 @@ class PermissionTestCase(TestCase):
Permission.objects.filter(content_type=permission_content_type).delete() Permission.objects.filter(content_type=permission_content_type).delete()
Permission._meta.verbose_name = "some ridiculously long verbose name that is out of control" * 5 Permission._meta.verbose_name = "some ridiculously long verbose name that is out of control" * 5
six.assertRaisesRegex(self, exceptions.ValidationError, msg = "The verbose_name of auth.permission is longer than 244 characters"
"The verbose_name of auth.permission is longer than 244 characters", with self.assertRaisesMessage(exceptions.ValidationError, msg):
create_permissions, auth_app_config, verbosity=0) create_permissions(auth_app_config, verbosity=0)
def test_custom_permission_name_length(self): def test_custom_permission_name_length(self):
auth_app_config = apps.get_app_config('auth') auth_app_config = apps.get_app_config('auth')

View File

@ -12,7 +12,6 @@ from django.test import (
SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature,
skipUnlessDBFeature, skipUnlessDBFeature,
) )
from django.utils import six
from django.utils.translation import ugettext_lazy from django.utils.translation import ugettext_lazy
from .models import Article, ArticleSelectOnSave, SelfRef from .models import Article, ArticleSelectOnSave, SelfRef
@ -70,11 +69,8 @@ class ModelInstanceCreationTests(TestCase):
self.assertEqual(a.headline, 'Fourth article') self.assertEqual(a.headline, 'Fourth article')
def test_cannot_create_instance_with_invalid_kwargs(self): def test_cannot_create_instance_with_invalid_kwargs(self):
six.assertRaisesRegex( with self.assertRaisesMessage(TypeError, "'foo' is an invalid keyword argument for this function"):
self, Article(
TypeError,
"'foo' is an invalid keyword argument for this function",
Article,
id=None, id=None,
headline='Some headline', headline='Some headline',
pub_date=datetime(2005, 7, 31), pub_date=datetime(2005, 7, 31),
@ -143,14 +139,8 @@ class ModelInstanceCreationTests(TestCase):
class ModelTest(TestCase): class ModelTest(TestCase):
def test_objects_attribute_is_only_available_on_the_class_itself(self): def test_objects_attribute_is_only_available_on_the_class_itself(self):
six.assertRaisesRegex( with self.assertRaisesMessage(AttributeError, "Manager isn't accessible via Article instances"):
self, getattr(Article(), "objects",)
AttributeError,
"Manager isn't accessible via Article instances",
getattr,
Article(),
"objects",
)
self.assertFalse(hasattr(Article(), 'objects')) self.assertFalse(hasattr(Article(), 'objects'))
self.assertTrue(hasattr(Article, 'objects')) self.assertTrue(hasattr(Article, 'objects'))
@ -490,24 +480,14 @@ class ModelLookupTest(TestCase):
def test_does_not_exist(self): def test_does_not_exist(self):
# Django raises an Article.DoesNotExist exception for get() if the # Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object. # parameters don't match any object.
six.assertRaisesRegex( with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."):
self, Article.objects.get(id__exact=2000,)
ObjectDoesNotExist,
"Article matching query does not exist.",
Article.objects.get,
id__exact=2000,
)
# To avoid dict-ordering related errors check only one lookup # To avoid dict-ordering related errors check only one lookup
# in single assert. # in single assert.
with self.assertRaises(ObjectDoesNotExist): with self.assertRaises(ObjectDoesNotExist):
Article.objects.get(pub_date__year=2005, pub_date__month=8) Article.objects.get(pub_date__year=2005, pub_date__month=8)
six.assertRaisesRegex( with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."):
self, Article.objects.get(pub_date__week_day=6,)
ObjectDoesNotExist,
"Article matching query does not exist.",
Article.objects.get,
pub_date__week_day=6,
)
def test_lookup_by_primary_key(self): def test_lookup_by_primary_key(self):
# Lookup by a primary key is the most common case, so Django # Lookup by a primary key is the most common case, so Django
@ -537,28 +517,13 @@ class ModelLookupTest(TestCase):
# Django raises an Article.MultipleObjectsReturned exception if the # Django raises an Article.MultipleObjectsReturned exception if the
# lookup matches more than one object # lookup matches more than one object
six.assertRaisesRegex( msg = "get() returned more than one Article -- it returned 2!"
self, with self.assertRaisesMessage(MultipleObjectsReturned, msg):
MultipleObjectsReturned, Article.objects.get(headline__startswith='Swallow',)
"get\(\) returned more than one Article -- it returned 2!", with self.assertRaisesMessage(MultipleObjectsReturned, msg):
Article.objects.get, Article.objects.get(pub_date__year=2005,)
headline__startswith='Swallow', with self.assertRaisesMessage(MultipleObjectsReturned, msg):
) Article.objects.get(pub_date__year=2005, pub_date__month=7)
six.assertRaisesRegex(
self,
MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!",
Article.objects.get,
pub_date__year=2005,
)
six.assertRaisesRegex(
self,
MultipleObjectsReturned,
"get\(\) returned more than one Article -- it returned 2!",
Article.objects.get,
pub_date__year=2005,
pub_date__month=7,
)
class ConcurrentSaveTests(TransactionTestCase): class ConcurrentSaveTests(TransactionTestCase):

View File

@ -102,25 +102,12 @@ class DatesTests(TestCase):
) )
def test_dates_fails_when_given_invalid_kind_argument(self): def test_dates_fails_when_given_invalid_kind_argument(self):
six.assertRaisesRegex( with self.assertRaisesMessage(AssertionError, "'kind' must be one of 'year', 'month' or 'day'."):
self, Article.objects.dates("pub_date", "bad_kind")
AssertionError,
"'kind' must be one of 'year', 'month' or 'day'.",
Article.objects.dates,
"pub_date",
"bad_kind",
)
def test_dates_fails_when_given_invalid_order_argument(self): def test_dates_fails_when_given_invalid_order_argument(self):
six.assertRaisesRegex( with self.assertRaisesMessage(AssertionError, "'order' must be either 'ASC' or 'DESC'."):
self, Article.objects.dates("pub_date", "year", order="bad order")
AssertionError,
"'order' must be either 'ASC' or 'DESC'.",
Article.objects.dates,
"pub_date",
"year",
order="bad order",
)
@override_settings(USE_TZ=False) @override_settings(USE_TZ=False)
def test_dates_trunc_datetime_fields(self): def test_dates_trunc_datetime_fields(self):

View File

@ -11,7 +11,7 @@ from django.db.models.functions import (
Upper, Upper,
) )
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils import six, timezone from django.utils import timezone
from .models import Article, Author, Fan from .models import Article, Author, Fan
@ -491,7 +491,7 @@ class FunctionTests(TestCase):
self.assertEqual(a.name_part_1[1:], a.name_part_2) self.assertEqual(a.name_part_1[1:], a.name_part_2)
with six.assertRaisesRegex(self, ValueError, "'pos' must be greater than 0"): with self.assertRaisesMessage(ValueError, "'pos' must be greater than 0"):
Author.objects.annotate(raises=Substr('name', 0)) Author.objects.annotate(raises=Substr('name', 0))
def test_substr_with_expressions(self): def test_substr_with_expressions(self):

View File

@ -364,13 +364,11 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
) )
# Excluding a bogus app should throw an error # Excluding a bogus app should throw an error
with six.assertRaisesRegex(self, management.CommandError, with self.assertRaisesMessage(management.CommandError, "No installed app with label 'foo_app'."):
"No installed app with label 'foo_app'."):
self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app']) self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app'])
# Excluding a bogus model should throw an error # Excluding a bogus model should throw an error
with six.assertRaisesRegex(self, management.CommandError, with self.assertRaisesMessage(management.CommandError, "Unknown model in excludes: fixtures.FooModel"):
"Unknown model in excludes: fixtures.FooModel"):
self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel']) self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel'])
@unittest.skipIf(sys.platform.startswith('win'), "Windows doesn't support '?' in filenames.") @unittest.skipIf(sys.platform.startswith('win'), "Windows doesn't support '?' in filenames.")
@ -415,8 +413,7 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
primary_keys='2' primary_keys='2'
) )
with six.assertRaisesRegex(self, management.CommandError, with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"):
"You can only use --pks option with one model"):
self._dumpdata_assert( self._dumpdata_assert(
['fixtures'], ['fixtures'],
'[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
@ -425,8 +422,7 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
primary_keys='2,3' primary_keys='2,3'
) )
with six.assertRaisesRegex(self, management.CommandError, with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"):
"You can only use --pks option with one model"):
self._dumpdata_assert( self._dumpdata_assert(
'', '',
'[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
@ -435,8 +431,7 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
primary_keys='2,3' primary_keys='2,3'
) )
with six.assertRaisesRegex(self, management.CommandError, with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"):
"You can only use --pks option with one model"):
self._dumpdata_assert( self._dumpdata_assert(
['fixtures.Article', 'fixtures.category'], ['fixtures.Article', 'fixtures.category'],
'[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '

View File

@ -201,9 +201,8 @@ class TestFixtures(TestCase):
Test for ticket #4371 -- Loading data of an unknown format should fail Test for ticket #4371 -- Loading data of an unknown format should fail
Validate that error conditions are caught correctly Validate that error conditions are caught correctly
""" """
with six.assertRaisesRegex(self, management.CommandError, msg = "Problem installing fixture 'bad_fixture1': unkn is not a known serialization format."
"Problem installing fixture 'bad_fixture1': " with self.assertRaisesMessage(management.CommandError, msg):
"unkn is not a known serialization format."):
management.call_command( management.call_command(
'loaddata', 'loaddata',
'bad_fixture1.unkn', 'bad_fixture1.unkn',
@ -460,8 +459,7 @@ class TestFixtures(TestCase):
""" """
Regression for #3615 - Ensure data with nonexistent child key references raises error Regression for #3615 - Ensure data with nonexistent child key references raises error
""" """
with six.assertRaisesRegex(self, IntegrityError, with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"):
"Problem installing fixture"):
management.call_command( management.call_command(
'loaddata', 'loaddata',
'forward_ref_bad_data.json', 'forward_ref_bad_data.json',
@ -489,9 +487,8 @@ class TestFixtures(TestCase):
""" """
Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line. Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line.
""" """
with six.assertRaisesRegex(self, management.CommandError, msg = "No database fixture specified. Please provide the path of at least one fixture in the command line."
"No database fixture specified. Please provide the path of " with self.assertRaisesMessage(management.CommandError, msg):
"at least one fixture in the command line."):
management.call_command( management.call_command(
'loaddata', 'loaddata',
verbosity=0, verbosity=0,

View File

@ -7,7 +7,6 @@ from django.core.exceptions import FieldError
from django.db import IntegrityError from django.db import IntegrityError
from django.db.models import Q from django.db.models import Q
from django.test import SimpleTestCase, TestCase from django.test import SimpleTestCase, TestCase
from django.utils import six
from .models import ( from .models import (
AllowsNullGFK, Animal, Carrot, Comparison, ConcreteRelatedModel, AllowsNullGFK, Animal, Carrot, Comparison, ConcreteRelatedModel,
@ -721,8 +720,8 @@ class TestInitWithNoneArgument(SimpleTestCase):
def test_none_not_allowed(self): def test_none_not_allowed(self):
# TaggedItem requires a content_type, initializing with None should # TaggedItem requires a content_type, initializing with None should
# raise a ValueError. # raise a ValueError.
with six.assertRaisesRegex(self, ValueError, msg = 'Cannot assign None: "TaggedItem.content_type" does not allow null values'
'Cannot assign None: "TaggedItem.content_type" does not allow null values'): with self.assertRaisesMessage(ValueError, msg):
TaggedItem(content_object=None) TaggedItem(content_object=None)
def test_none_allowed(self): def test_none_allowed(self):

View File

@ -5,7 +5,6 @@ from django.contrib.gis.gdal import HAS_GDAL
from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis.geos import GEOSGeometry
from django.forms import ValidationError from django.forms import ValidationError
from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature
from django.utils import six
from django.utils.html import escape from django.utils.html import escape
@ -40,8 +39,7 @@ class GeometryFieldTest(SimpleTestCase):
"Testing GeometryField's handling of null (None) geometries." "Testing GeometryField's handling of null (None) geometries."
# Form fields, by default, are required (`required=True`) # Form fields, by default, are required (`required=True`)
fld = forms.GeometryField() fld = forms.GeometryField()
with six.assertRaisesRegex(self, forms.ValidationError, with self.assertRaisesMessage(forms.ValidationError, "No geometry value provided."):
"No geometry value provided."):
fld.clean(None) fld.clean(None)
# This will clean None as a geometry (See #10660). # This will clean None as a geometry (See #10660).

View File

@ -762,8 +762,8 @@ class CustomLayoutExtractionTests(ExtractorTests):
def test_no_locale_raises(self): def test_no_locale_raises(self):
os.chdir(self.test_dir) os.chdir(self.test_dir)
with six.assertRaisesRegex(self, management.CommandError, msg = "Unable to find a locale path to store translations for file"
"Unable to find a locale path to store translations for file"): with self.assertRaisesMessage(management.CommandError, msg):
management.call_command('makemessages', locale=LOCALE, verbosity=0) management.call_command('makemessages', locale=LOCALE, verbosity=0)
@override_settings( @override_settings(

View File

@ -123,12 +123,9 @@ class InlineFormsetFactoryTest(TestCase):
Child has two ForeignKeys to Parent, so if we don't specify which one Child has two ForeignKeys to Parent, so if we don't specify which one
to use for the inline formset, we should get an exception. to use for the inline formset, we should get an exception.
""" """
six.assertRaisesRegex( msg = "'inline_formsets.Child' has more than one ForeignKey to 'inline_formsets.Parent'."
self, with self.assertRaisesMessage(ValueError, msg):
ValueError, inlineformset_factory(Parent, Child)
"'inline_formsets.Child' has more than one ForeignKey to 'inline_formsets.Parent'.",
inlineformset_factory, Parent, Child
)
def test_fk_name_not_foreign_key_field_from_child(self): def test_fk_name_not_foreign_key_field_from_child(self):
""" """
@ -144,11 +141,8 @@ class InlineFormsetFactoryTest(TestCase):
If the field specified in fk_name is not a ForeignKey, we should get an If the field specified in fk_name is not a ForeignKey, we should get an
exception. exception.
""" """
six.assertRaisesRegex( with self.assertRaisesMessage(ValueError, "'inline_formsets.Child' has no field named 'test'."):
self, ValueError, inlineformset_factory(Parent, Child, fk_name='test')
"'inline_formsets.Child' has no field named 'test'.",
inlineformset_factory, Parent, Child, fk_name='test'
)
def test_any_iterable_allowed_as_argument_to_exclude(self): def test_any_iterable_allowed_as_argument_to_exclude(self):
# Regression test for #9171. # Regression test for #9171.

View File

@ -499,7 +499,7 @@ class MakeMigrationsTests(MigrationTestBase):
apps.register_model('migrations', UnserializableModel) apps.register_model('migrations', UnserializableModel)
with self.temporary_migration_module() as migration_dir: with self.temporary_migration_module() as migration_dir:
with six.assertRaisesRegex(self, ValueError, r'Cannot serialize'): with self.assertRaisesMessage(ValueError, 'Cannot serialize'):
call_command("makemigrations", "migrations", verbosity=0) call_command("makemigrations", "migrations", verbosity=0)
initial_file = os.path.join(migration_dir, "0001_initial.py") initial_file = os.path.join(migration_dir, "0001_initial.py")

View File

@ -9,7 +9,6 @@ from django.db.models.fields import NOT_PROVIDED
from django.db.transaction import atomic from django.db.transaction import atomic
from django.db.utils import IntegrityError from django.db.utils import IntegrityError
from django.test import override_settings, skipUnlessDBFeature from django.test import override_settings, skipUnlessDBFeature
from django.utils import six
from .models import FoodManager, FoodQuerySet from .models import FoodManager, FoodQuerySet
from .test_base import MigrationTestBase from .test_base import MigrationTestBase
@ -1607,16 +1606,12 @@ class OperationTests(OperationTestBase):
) )
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
six.assertRaisesRegex(self, ValueError, with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"):
"Expected a 2-tuple but got 1", operation.database_forwards("test_runsql", editor, project_state, new_state)
operation.database_forwards,
"test_runsql", editor, project_state, new_state)
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
six.assertRaisesRegex(self, ValueError, with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"):
"Expected a 2-tuple but got 3", operation.database_backwards("test_runsql", editor, new_state, project_state)
operation.database_backwards,
"test_runsql", editor, new_state, project_state)
def test_run_sql_noop(self): def test_run_sql_noop(self):
""" """

View File

@ -296,7 +296,7 @@ class WriterTests(SimpleTestCase):
) )
def test_serialize_functions(self): def test_serialize_functions(self):
with six.assertRaisesRegex(self, ValueError, 'Cannot serialize function: lambda'): with self.assertRaisesMessage(ValueError, 'Cannot serialize function: lambda'):
self.assertSerializedEqual(lambda x: 42) self.assertSerializedEqual(lambda x: 42)
self.assertSerializedEqual(models.SET_NULL) self.assertSerializedEqual(models.SET_NULL)
string, imports = MigrationWriter.serialize(models.SET(42)) string, imports = MigrationWriter.serialize(models.SET(42))
@ -463,8 +463,7 @@ class WriterTests(SimpleTestCase):
return "somewhere dynamic" return "somewhere dynamic"
thing = models.FileField(upload_to=upload_to) thing = models.FileField(upload_to=upload_to)
with six.assertRaisesRegex(self, ValueError, with self.assertRaisesMessage(ValueError, 'Could not find function upload_to in migrations.test_writer'):
'^Could not find function upload_to in migrations.test_writer'):
self.serialize_round_trip(TestModel2.thing) self.serialize_round_trip(TestModel2.thing)
def test_serialize_managers(self): def test_serialize_managers(self):

View File

@ -1362,9 +1362,8 @@ class Queries4Tests(BaseQuerysetTest):
def test_ticket11811(self): def test_ticket11811(self):
unsaved_category = NamedCategory(name="Other") unsaved_category = NamedCategory(name="Other")
with six.assertRaisesRegex(self, ValueError, msg = 'Unsaved model instance <NamedCategory: Other> cannot be used in an ORM query.'
'Unsaved model instance <NamedCategory: Other> ' with self.assertRaisesMessage(ValueError, msg):
'cannot be used in an ORM query.'):
Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category) Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category)
def test_ticket14876(self): def test_ticket14876(self):
@ -2321,48 +2320,26 @@ class QuerySetSupportsPythonIdioms(TestCase):
"<Article: Article 7>"]) "<Article: Article 7>"])
def test_slicing_cannot_filter_queryset_once_sliced(self): def test_slicing_cannot_filter_queryset_once_sliced(self):
six.assertRaisesRegex( with self.assertRaisesMessage(AssertionError, "Cannot filter a query once a slice has been taken."):
self, Article.objects.all()[0:5].filter(id=1, )
AssertionError,
"Cannot filter a query once a slice has been taken.",
Article.objects.all()[0:5].filter,
id=1,
)
def test_slicing_cannot_reorder_queryset_once_sliced(self): def test_slicing_cannot_reorder_queryset_once_sliced(self):
six.assertRaisesRegex( with self.assertRaisesMessage(AssertionError, "Cannot reorder a query once a slice has been taken."):
self, Article.objects.all()[0:5].order_by('id', )
AssertionError,
"Cannot reorder a query once a slice has been taken.",
Article.objects.all()[0:5].order_by,
'id',
)
def test_slicing_cannot_combine_queries_once_sliced(self): def test_slicing_cannot_combine_queries_once_sliced(self):
six.assertRaisesRegex( with self.assertRaisesMessage(AssertionError, "Cannot combine queries once a slice has been taken."):
self, Article.objects.all()[0:1] & Article.objects.all()[4:5]
AssertionError,
"Cannot combine queries once a slice has been taken.",
lambda: Article.objects.all()[0:1] & Article.objects.all()[4:5]
)
def test_slicing_negative_indexing_not_supported_for_single_element(self): def test_slicing_negative_indexing_not_supported_for_single_element(self):
"""hint: inverting your ordering might do what you need""" """hint: inverting your ordering might do what you need"""
six.assertRaisesRegex( with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."):
self, Article.objects.all()[-1]
AssertionError,
"Negative indexing is not supported.",
lambda: Article.objects.all()[-1]
)
def test_slicing_negative_indexing_not_supported_for_range(self): def test_slicing_negative_indexing_not_supported_for_range(self):
"""hint: inverting your ordering might do what you need""" """hint: inverting your ordering might do what you need"""
six.assertRaisesRegex( with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."):
self, Article.objects.all()[0:-5]
AssertionError,
"Negative indexing is not supported.",
lambda: Article.objects.all()[0:-5]
)
def test_can_get_number_of_items_in_queryset_using_standard_len(self): def test_can_get_number_of_items_in_queryset_using_standard_len(self):
self.assertEqual(len(Article.objects.filter(name__exact='Article 1')), 1) self.assertEqual(len(Article.objects.filter(name__exact='Article 1')), 1)

View File

@ -82,7 +82,7 @@ class NoYamlSerializerTestCase(SimpleTestCase):
def test_dumpdata_pyyaml_error_message(self): def test_dumpdata_pyyaml_error_message(self):
"""Calling dumpdata produces an error when yaml package missing""" """Calling dumpdata produces an error when yaml package missing"""
with six.assertRaisesRegex(self, management.CommandError, YAML_IMPORT_ERROR_MESSAGE): with self.assertRaisesMessage(management.CommandError, YAML_IMPORT_ERROR_MESSAGE):
management.call_command('dumpdata', format='yaml') management.call_command('dumpdata', format='yaml')

View File

@ -98,12 +98,11 @@ class TestFindStatic(CollectionTestCase, TestDefaults):
class TestConfiguration(StaticFilesTestCase): class TestConfiguration(StaticFilesTestCase):
def test_location_empty(self): def test_location_empty(self):
msg = 'without having set the STATIC_ROOT setting to a filesystem path'
err = six.StringIO() err = six.StringIO()
for root in ['', None]: for root in ['', None]:
with override_settings(STATIC_ROOT=root): with override_settings(STATIC_ROOT=root):
with six.assertRaisesRegex( with self.assertRaisesMessage(ImproperlyConfigured, msg):
self, ImproperlyConfigured,
'without having set the STATIC_ROOT setting to a filesystem path'):
call_command('collectstatic', interactive=False, verbosity=0, stderr=err) call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
def test_local_storage_detection_helper(self): def test_local_storage_detection_helper(self):

View File

@ -12,7 +12,6 @@ from django.db import (
from django.test import ( from django.test import (
TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature,
) )
from django.utils import six
from .models import Reporter from .models import Reporter
@ -45,7 +44,7 @@ class AtomicTests(TransactionTestCase):
def make_reporter(): def make_reporter():
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
make_reporter() make_reporter()
self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Reporter.objects.all(), [])
@ -61,7 +60,7 @@ class AtomicTests(TransactionTestCase):
def make_reporter(): def make_reporter():
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
make_reporter() make_reporter()
self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Reporter.objects.all(), [])
@ -71,7 +70,7 @@ class AtomicTests(TransactionTestCase):
self.assertQuerysetEqual(Reporter.objects.all(), ['<Reporter: Tintin>']) self.assertQuerysetEqual(Reporter.objects.all(), ['<Reporter: Tintin>'])
def test_rollback(self): def test_rollback(self):
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -88,14 +87,14 @@ class AtomicTests(TransactionTestCase):
def test_nested_commit_rollback(self): def test_nested_commit_rollback(self):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(first_name="Tintin") Reporter.objects.create(first_name="Tintin")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
self.assertQuerysetEqual(Reporter.objects.all(), ['<Reporter: Tintin>']) self.assertQuerysetEqual(Reporter.objects.all(), ['<Reporter: Tintin>'])
def test_nested_rollback_commit(self): def test_nested_rollback_commit(self):
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(last_name="Tintin") Reporter.objects.create(last_name="Tintin")
with transaction.atomic(): with transaction.atomic():
@ -104,10 +103,10 @@ class AtomicTests(TransactionTestCase):
self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Reporter.objects.all(), [])
def test_nested_rollback_rollback(self): def test_nested_rollback_rollback(self):
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(last_name="Tintin") Reporter.objects.create(last_name="Tintin")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -125,7 +124,7 @@ class AtomicTests(TransactionTestCase):
def test_merged_commit_rollback(self): def test_merged_commit_rollback(self):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(first_name="Tintin") Reporter.objects.create(first_name="Tintin")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False): with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -133,7 +132,7 @@ class AtomicTests(TransactionTestCase):
self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Reporter.objects.all(), [])
def test_merged_rollback_commit(self): def test_merged_rollback_commit(self):
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(last_name="Tintin") Reporter.objects.create(last_name="Tintin")
with transaction.atomic(savepoint=False): with transaction.atomic(savepoint=False):
@ -142,10 +141,10 @@ class AtomicTests(TransactionTestCase):
self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Reporter.objects.all(), [])
def test_merged_rollback_rollback(self): def test_merged_rollback_rollback(self):
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(last_name="Tintin") Reporter.objects.create(last_name="Tintin")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False): with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -165,7 +164,7 @@ class AtomicTests(TransactionTestCase):
atomic = transaction.atomic() atomic = transaction.atomic()
with atomic: with atomic:
Reporter.objects.create(first_name="Tintin") Reporter.objects.create(first_name="Tintin")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with atomic: with atomic:
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -173,7 +172,7 @@ class AtomicTests(TransactionTestCase):
def test_reuse_rollback_commit(self): def test_reuse_rollback_commit(self):
atomic = transaction.atomic() atomic = transaction.atomic()
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with atomic: with atomic:
Reporter.objects.create(last_name="Tintin") Reporter.objects.create(last_name="Tintin")
with atomic: with atomic:
@ -183,10 +182,10 @@ class AtomicTests(TransactionTestCase):
def test_reuse_rollback_rollback(self): def test_reuse_rollback_rollback(self):
atomic = transaction.atomic() atomic = transaction.atomic()
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with atomic: with atomic:
Reporter.objects.create(last_name="Tintin") Reporter.objects.create(last_name="Tintin")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with atomic: with atomic:
Reporter.objects.create(first_name="Haddock") Reporter.objects.create(first_name="Haddock")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -256,7 +255,7 @@ class AtomicMergeTests(TransactionTestCase):
Reporter.objects.create(first_name="Tintin") Reporter.objects.create(first_name="Tintin")
with transaction.atomic(savepoint=False): with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Archibald", last_name="Haddock") Reporter.objects.create(first_name="Archibald", last_name="Haddock")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False): with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Calculus") Reporter.objects.create(first_name="Calculus")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -280,7 +279,7 @@ class AtomicMergeTests(TransactionTestCase):
Reporter.objects.create(first_name="Tintin") Reporter.objects.create(first_name="Tintin")
with transaction.atomic(): with transaction.atomic():
Reporter.objects.create(first_name="Archibald", last_name="Haddock") Reporter.objects.create(first_name="Archibald", last_name="Haddock")
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
with transaction.atomic(savepoint=False): with transaction.atomic(savepoint=False):
Reporter.objects.create(first_name="Calculus") Reporter.objects.create(first_name="Calculus")
raise Exception("Oops, that's his last name") raise Exception("Oops, that's his last name")
@ -383,7 +382,7 @@ class AtomicMySQLTests(TransactionTestCase):
other_thread.start() other_thread.start()
other_thread_ready.wait() other_thread_ready.wait()
with six.assertRaisesRegex(self, OperationalError, 'Deadlock found'): with self.assertRaisesMessage(OperationalError, 'Deadlock found'):
# Double atomic to enter a transaction and create a savepoint. # Double atomic to enter a transaction and create a savepoint.
with transaction.atomic(): with transaction.atomic():
with transaction.atomic(): with transaction.atomic():
@ -419,7 +418,7 @@ class AtomicMiscTests(TransactionTestCase):
with transaction.atomic(): with transaction.atomic():
# Swallow the intentional error raised in the sub-transaction. # Swallow the intentional error raised in the sub-transaction.
with six.assertRaisesRegex(self, Exception, "Oops"): with self.assertRaisesMessage(Exception, "Oops"):
# Start a sub-transaction with a savepoint. # Start a sub-transaction with a savepoint.
with transaction.atomic(): with transaction.atomic():

View File

@ -49,8 +49,8 @@ class MultiValueDictTests(SimpleTestCase):
[('name', ['Adrian', 'Simon']), ('position', ['Developer'])] [('name', ['Adrian', 'Simon']), ('position', ['Developer'])]
) )
six.assertRaisesRegex(self, MultiValueDictKeyError, 'lastname', with self.assertRaisesMessage(MultiValueDictKeyError, 'lastname'):
d.__getitem__, 'lastname') d.__getitem__('lastname')
self.assertEqual(d.get('lastname'), None) self.assertEqual(d.get('lastname'), None)
self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent') self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent')

View File

@ -5,7 +5,7 @@ import unittest
from importlib import import_module from importlib import import_module
from zipimport import zipimporter from zipimport import zipimporter
from django.test import SimpleTestCase, modify_settings from django.test import SimpleTestCase, TestCase, modify_settings
from django.test.utils import extend_sys_path from django.test.utils import extend_sys_path
from django.utils import six from django.utils import six
from django.utils._os import upath from django.utils._os import upath
@ -115,7 +115,7 @@ class EggLoader(unittest.TestCase):
import_module('egg_module.sub1.sub2.no_such_module') import_module('egg_module.sub1.sub2.no_such_module')
class ModuleImportTestCase(unittest.TestCase): class ModuleImportTestCase(TestCase):
def test_import_string(self): def test_import_string(self):
cls = import_string('django.utils.module_loading.import_string') cls = import_string('django.utils.module_loading.import_string')
self.assertEqual(cls, import_string) self.assertEqual(cls, import_string)
@ -124,7 +124,7 @@ class ModuleImportTestCase(unittest.TestCase):
with self.assertRaises(ImportError): with self.assertRaises(ImportError):
import_string('no_dots_in_path') import_string('no_dots_in_path')
msg = 'Module "utils_tests" does not define a "unexistent" attribute' msg = 'Module "utils_tests" does not define a "unexistent" attribute'
with six.assertRaisesRegex(self, ImportError, msg): with self.assertRaisesMessage(ImportError, msg):
import_string('utils_tests.unexistent') import_string('utils_tests.unexistent')
@ -164,13 +164,13 @@ class AutodiscoverModulesTestCase(SimpleTestCase):
def test_validate_registry_keeps_intact(self): def test_validate_registry_keeps_intact(self):
from .test_module import site from .test_module import site
with six.assertRaisesRegex(self, Exception, "Some random exception."): with self.assertRaisesMessage(Exception, "Some random exception."):
autodiscover_modules('another_bad_module', register_to=site) autodiscover_modules('another_bad_module', register_to=site)
self.assertEqual(site._registry, {}) self.assertEqual(site._registry, {})
def test_validate_registry_resets_after_erroneous_module(self): def test_validate_registry_resets_after_erroneous_module(self):
from .test_module import site from .test_module import site
with six.assertRaisesRegex(self, Exception, "Some random exception."): with self.assertRaisesMessage(Exception, "Some random exception."):
autodiscover_modules('another_good_module', 'another_bad_module', register_to=site) autodiscover_modules('another_good_module', 'another_bad_module', register_to=site)
self.assertEqual(site._registry, {'lorem': 'ipsum'}) self.assertEqual(site._registry, {'lorem': 'ipsum'})