From 26ad01719d73823e65c0358a2ee9941e0a888a63 Mon Sep 17 00:00:00 2001 From: Hasan Date: Mon, 18 Jan 2016 12:15:45 +0330 Subject: [PATCH] Refs #26022 -- Replaced six.assertRaisesRegex with assertRaisesMessage as appropriate. --- tests/admin_filters/tests.py | 13 ++-- tests/aggregation/tests.py | 14 ++-- tests/app_loading/tests.py | 3 +- tests/apps/tests.py | 6 +- tests/auth_tests/test_management.py | 25 ++++---- tests/basic/tests.py | 75 ++++++---------------- tests/dates/tests.py | 21 ++---- tests/db_functions/tests.py | 4 +- tests/fixtures/tests.py | 15 ++--- tests/fixtures_regress/tests.py | 13 ++-- tests/generic_relations/tests.py | 5 +- tests/gis_tests/test_geoforms.py | 4 +- tests/i18n/test_extraction.py | 4 +- tests/inline_formsets/tests.py | 16 ++--- tests/migrations/test_commands.py | 2 +- tests/migrations/test_operations.py | 13 ++-- tests/migrations/test_writer.py | 5 +- tests/queries/tests.py | 47 ++++---------- tests/serializers/test_yaml.py | 2 +- tests/staticfiles_tests/test_management.py | 5 +- tests/transactions/tests.py | 39 ++++++----- tests/utils_tests/test_datastructures.py | 4 +- tests/utils_tests/test_module_loading.py | 10 +-- 23 files changed, 124 insertions(+), 221 deletions(-) diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index 97b9100f5d..570353430d 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -13,7 +13,6 @@ from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured from django.test import RequestFactory, TestCase, override_settings -from django.utils import six from django.utils.encoding import force_text from .models import Book, Bookmark, Department, Employee, TaggedItem @@ -818,9 +817,9 @@ class ListFiltersTests(TestCase): """ modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site) request = self.request_factory.get('/', {}) - six.assertRaisesRegex(self, ImproperlyConfigured, - "The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'.", - self.get_changelist, request, Book, modeladmin) + msg = "The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'." + with self.assertRaisesMessage(ImproperlyConfigured, msg): + self.get_changelist(request, Book, modeladmin) def test_simplelistfilter_without_parameter(self): """ @@ -828,9 +827,9 @@ class ListFiltersTests(TestCase): """ modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site) request = self.request_factory.get('/', {}) - six.assertRaisesRegex(self, ImproperlyConfigured, - "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'.", - self.get_changelist, request, Book, modeladmin) + msg = "The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'." + with self.assertRaisesMessage(ImproperlyConfigured, msg): + self.get_changelist(request, Book, modeladmin) def test_simplelistfilter_with_none_returning_lookups(self): """ diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py index f310b1e5c9..f6054a1b73 100644 --- a/tests/aggregation/tests.py +++ b/tests/aggregation/tests.py @@ -12,7 +12,7 @@ from django.db.models import ( ) from django.test import TestCase 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 @@ -906,7 +906,7 @@ class AggregateTestCase(TestCase): self.assertEqual(book['price_sum'], Decimal("99999.80")) 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')) def test_nonfield_annotation(self): @@ -918,7 +918,7 @@ class AggregateTestCase(TestCase): self.assertEqual(book.val, 2) 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() def test_annotation_expressions(self): @@ -962,7 +962,7 @@ class AggregateTestCase(TestCase): self.assertEqual(p2, {'avg_price': Approximate(53.39, places=2)}) 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) 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)) 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'))) - 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')) - with six.assertRaisesRegex(self, TypeError, 'Complex aggregates require an alias'): + with self.assertRaisesMessage(TypeError, 'Complex aggregates require an alias'): Author.objects.aggregate(Sum(1)) def test_aggregate_over_complex_annotation(self): diff --git a/tests/app_loading/tests.py b/tests/app_loading/tests.py index e068508e6c..a79bdaec04 100644 --- a/tests/app_loading/tests.py +++ b/tests/app_loading/tests.py @@ -5,7 +5,6 @@ import os from django.apps import apps from django.test import SimpleTestCase from django.test.utils import extend_sys_path -from django.utils import six 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""" egg_name = '%s/brokenapp.egg' % self.egg_dir with extend_sys_path(egg_name): - with six.assertRaisesRegex(self, ImportError, 'modelz'): + with self.assertRaisesMessage(ImportError, 'modelz'): with self.settings(INSTALLED_APPS=['broken_app']): pass diff --git a/tests/apps/tests.py b/tests/apps/tests.py index af9ba0c6b9..701be50803 100644 --- a/tests/apps/tests.py +++ b/tests/apps/tests.py @@ -159,12 +159,12 @@ class AppsTests(SimpleTestCase): self.assertEqual(apps.get_app_config('relabeled').name, 'apps') 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']): pass 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']): pass @@ -172,7 +172,7 @@ class AppsTests(SimpleTestCase): """ 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']): pass diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index a941847474..ab8e8a60e0 100644 --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -427,8 +427,8 @@ class CreatesuperuserManagementCommandTestCase(TestCase): self.assertEqual(u.group, group) non_existent_email = 'mymail2@gmail.com' - with self.assertRaisesMessage(CommandError, - 'email instance with email %r does not exist.' % non_existent_email): + msg = 'email instance with email %r does not exist.' % non_existent_email + with self.assertRaisesMessage(CommandError, msg): call_command( 'createsuperuser', interactive=False, @@ -670,10 +670,12 @@ class PermissionTestCase(TestCase): # check duplicated default permission Permission._meta.permissions = [ ('change_permission', 'Can edit permission (duplicate)')] - six.assertRaisesRegex(self, CommandError, + msg = ( "The permission codename 'change_permission' clashes with a " - "builtin permission for model 'auth.Permission'.", - create_permissions, auth_app_config, verbosity=0) + "builtin permission for model 'auth.Permission'." + ) + with self.assertRaisesMessage(CommandError, msg): + create_permissions(auth_app_config, verbosity=0) # check duplicated custom permissions Permission._meta.permissions = [ @@ -681,10 +683,9 @@ class PermissionTestCase(TestCase): ('other_one', 'Some other permission'), ('my_custom_permission', 'Some permission with duplicate permission code'), ] - six.assertRaisesRegex(self, CommandError, - "The permission codename 'my_custom_permission' is duplicated for model " - "'auth.Permission'.", - create_permissions, auth_app_config, verbosity=0) + msg = "The permission codename 'my_custom_permission' is duplicated for model 'auth.Permission'." + with self.assertRaisesMessage(CommandError, msg): + create_permissions(auth_app_config, verbosity=0) # should not raise anything Permission._meta.permissions = [ @@ -723,9 +724,9 @@ class PermissionTestCase(TestCase): Permission.objects.filter(content_type=permission_content_type).delete() Permission._meta.verbose_name = "some ridiculously long verbose name that is out of control" * 5 - six.assertRaisesRegex(self, exceptions.ValidationError, - "The verbose_name of auth.permission is longer than 244 characters", - create_permissions, auth_app_config, verbosity=0) + msg = "The verbose_name of auth.permission is longer than 244 characters" + with self.assertRaisesMessage(exceptions.ValidationError, msg): + create_permissions(auth_app_config, verbosity=0) def test_custom_permission_name_length(self): auth_app_config = apps.get_app_config('auth') diff --git a/tests/basic/tests.py b/tests/basic/tests.py index 95ed7ad897..a69a43a0f4 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -12,7 +12,6 @@ from django.test import ( SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) -from django.utils import six from django.utils.translation import ugettext_lazy from .models import Article, ArticleSelectOnSave, SelfRef @@ -70,16 +69,13 @@ class ModelInstanceCreationTests(TestCase): self.assertEqual(a.headline, 'Fourth article') def test_cannot_create_instance_with_invalid_kwargs(self): - six.assertRaisesRegex( - self, - TypeError, - "'foo' is an invalid keyword argument for this function", - Article, - id=None, - headline='Some headline', - pub_date=datetime(2005, 7, 31), - foo='bar', - ) + with self.assertRaisesMessage(TypeError, "'foo' is an invalid keyword argument for this function"): + Article( + id=None, + headline='Some headline', + pub_date=datetime(2005, 7, 31), + foo='bar', + ) def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self): """ @@ -143,14 +139,8 @@ class ModelInstanceCreationTests(TestCase): class ModelTest(TestCase): def test_objects_attribute_is_only_available_on_the_class_itself(self): - six.assertRaisesRegex( - self, - AttributeError, - "Manager isn't accessible via Article instances", - getattr, - Article(), - "objects", - ) + with self.assertRaisesMessage(AttributeError, "Manager isn't accessible via Article instances"): + getattr(Article(), "objects",) self.assertFalse(hasattr(Article(), 'objects')) self.assertTrue(hasattr(Article, 'objects')) @@ -490,24 +480,14 @@ class ModelLookupTest(TestCase): def test_does_not_exist(self): # Django raises an Article.DoesNotExist exception for get() if the # parameters don't match any object. - six.assertRaisesRegex( - self, - ObjectDoesNotExist, - "Article matching query does not exist.", - Article.objects.get, - id__exact=2000, - ) + with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."): + Article.objects.get(id__exact=2000,) # To avoid dict-ordering related errors check only one lookup # in single assert. with self.assertRaises(ObjectDoesNotExist): Article.objects.get(pub_date__year=2005, pub_date__month=8) - six.assertRaisesRegex( - self, - ObjectDoesNotExist, - "Article matching query does not exist.", - Article.objects.get, - pub_date__week_day=6, - ) + with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."): + Article.objects.get(pub_date__week_day=6,) def test_lookup_by_primary_key(self): # 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 # lookup matches more than one object - six.assertRaisesRegex( - self, - MultipleObjectsReturned, - "get\(\) returned more than one Article -- it returned 2!", - Article.objects.get, - headline__startswith='Swallow', - ) - 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, - ) + msg = "get() returned more than one Article -- it returned 2!" + with self.assertRaisesMessage(MultipleObjectsReturned, msg): + Article.objects.get(headline__startswith='Swallow',) + with self.assertRaisesMessage(MultipleObjectsReturned, msg): + Article.objects.get(pub_date__year=2005,) + with self.assertRaisesMessage(MultipleObjectsReturned, msg): + Article.objects.get(pub_date__year=2005, pub_date__month=7) class ConcurrentSaveTests(TransactionTestCase): diff --git a/tests/dates/tests.py b/tests/dates/tests.py index 97c4face6e..5d7bd0fb97 100644 --- a/tests/dates/tests.py +++ b/tests/dates/tests.py @@ -102,25 +102,12 @@ class DatesTests(TestCase): ) def test_dates_fails_when_given_invalid_kind_argument(self): - six.assertRaisesRegex( - self, - AssertionError, - "'kind' must be one of 'year', 'month' or 'day'.", - Article.objects.dates, - "pub_date", - "bad_kind", - ) + with self.assertRaisesMessage(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): - six.assertRaisesRegex( - self, - AssertionError, - "'order' must be either 'ASC' or 'DESC'.", - Article.objects.dates, - "pub_date", - "year", - order="bad order", - ) + with self.assertRaisesMessage(AssertionError, "'order' must be either 'ASC' or 'DESC'."): + Article.objects.dates("pub_date", "year", order="bad order") @override_settings(USE_TZ=False) def test_dates_trunc_datetime_fields(self): diff --git a/tests/db_functions/tests.py b/tests/db_functions/tests.py index b6ab915d4d..26acc687ea 100644 --- a/tests/db_functions/tests.py +++ b/tests/db_functions/tests.py @@ -11,7 +11,7 @@ from django.db.models.functions import ( Upper, ) from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature -from django.utils import six, timezone +from django.utils import timezone from .models import Article, Author, Fan @@ -491,7 +491,7 @@ class FunctionTests(TestCase): 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)) def test_substr_with_expressions(self): diff --git a/tests/fixtures/tests.py b/tests/fixtures/tests.py index b151797c98..e7a105532a 100644 --- a/tests/fixtures/tests.py +++ b/tests/fixtures/tests.py @@ -364,13 +364,11 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): ) # Excluding a bogus app should throw an error - with six.assertRaisesRegex(self, management.CommandError, - "No installed app with label 'foo_app'."): + with self.assertRaisesMessage(management.CommandError, "No installed app with label 'foo_app'."): self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app']) # Excluding a bogus model should throw an error - with six.assertRaisesRegex(self, management.CommandError, - "Unknown model in excludes: fixtures.FooModel"): + with self.assertRaisesMessage(management.CommandError, "Unknown model in excludes: fixtures.FooModel"): self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel']) @unittest.skipIf(sys.platform.startswith('win'), "Windows doesn't support '?' in filenames.") @@ -415,8 +413,7 @@ class FixtureLoadingTests(DumpDataAssertMixin, TestCase): primary_keys='2' ) - with six.assertRaisesRegex(self, management.CommandError, - "You can only use --pks option with one model"): + with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"): self._dumpdata_assert( ['fixtures'], '[{"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' ) - with six.assertRaisesRegex(self, management.CommandError, - "You can only use --pks option with one model"): + with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"): self._dumpdata_assert( '', '[{"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' ) - with six.assertRaisesRegex(self, management.CommandError, - "You can only use --pks option with one model"): + with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"): self._dumpdata_assert( ['fixtures.Article', 'fixtures.category'], '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", ' diff --git a/tests/fixtures_regress/tests.py b/tests/fixtures_regress/tests.py index 6b4a3f7673..3a47d2617f 100644 --- a/tests/fixtures_regress/tests.py +++ b/tests/fixtures_regress/tests.py @@ -201,9 +201,8 @@ class TestFixtures(TestCase): Test for ticket #4371 -- Loading data of an unknown format should fail Validate that error conditions are caught correctly """ - with six.assertRaisesRegex(self, management.CommandError, - "Problem installing fixture 'bad_fixture1': " - "unkn is not a known serialization format."): + msg = "Problem installing fixture 'bad_fixture1': unkn is not a known serialization format." + with self.assertRaisesMessage(management.CommandError, msg): management.call_command( 'loaddata', 'bad_fixture1.unkn', @@ -460,8 +459,7 @@ class TestFixtures(TestCase): """ Regression for #3615 - Ensure data with nonexistent child key references raises error """ - with six.assertRaisesRegex(self, IntegrityError, - "Problem installing fixture"): + with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"): management.call_command( 'loaddata', '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. """ - with six.assertRaisesRegex(self, management.CommandError, - "No database fixture specified. Please provide the path of " - "at least one fixture in the command line."): + msg = "No database fixture specified. Please provide the path of at least one fixture in the command line." + with self.assertRaisesMessage(management.CommandError, msg): management.call_command( 'loaddata', verbosity=0, diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py index 1d3d3d373b..436bb92222 100644 --- a/tests/generic_relations/tests.py +++ b/tests/generic_relations/tests.py @@ -7,7 +7,6 @@ from django.core.exceptions import FieldError from django.db import IntegrityError from django.db.models import Q from django.test import SimpleTestCase, TestCase -from django.utils import six from .models import ( AllowsNullGFK, Animal, Carrot, Comparison, ConcreteRelatedModel, @@ -721,8 +720,8 @@ class TestInitWithNoneArgument(SimpleTestCase): def test_none_not_allowed(self): # TaggedItem requires a content_type, initializing with None should # raise a ValueError. - with six.assertRaisesRegex(self, ValueError, - 'Cannot assign None: "TaggedItem.content_type" does not allow null values'): + msg = 'Cannot assign None: "TaggedItem.content_type" does not allow null values' + with self.assertRaisesMessage(ValueError, msg): TaggedItem(content_object=None) def test_none_allowed(self): diff --git a/tests/gis_tests/test_geoforms.py b/tests/gis_tests/test_geoforms.py index df2aa08066..e07153df51 100644 --- a/tests/gis_tests/test_geoforms.py +++ b/tests/gis_tests/test_geoforms.py @@ -5,7 +5,6 @@ from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.geos import GEOSGeometry from django.forms import ValidationError from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature -from django.utils import six from django.utils.html import escape @@ -40,8 +39,7 @@ class GeometryFieldTest(SimpleTestCase): "Testing GeometryField's handling of null (None) geometries." # Form fields, by default, are required (`required=True`) fld = forms.GeometryField() - with six.assertRaisesRegex(self, forms.ValidationError, - "No geometry value provided."): + with self.assertRaisesMessage(forms.ValidationError, "No geometry value provided."): fld.clean(None) # This will clean None as a geometry (See #10660). diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index dd28a76c4f..2f8056560d 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -762,8 +762,8 @@ class CustomLayoutExtractionTests(ExtractorTests): def test_no_locale_raises(self): os.chdir(self.test_dir) - with six.assertRaisesRegex(self, management.CommandError, - "Unable to find a locale path to store translations for file"): + msg = "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) @override_settings( diff --git a/tests/inline_formsets/tests.py b/tests/inline_formsets/tests.py index 3bb7586575..c298f9430e 100644 --- a/tests/inline_formsets/tests.py +++ b/tests/inline_formsets/tests.py @@ -123,12 +123,9 @@ class InlineFormsetFactoryTest(TestCase): 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. """ - six.assertRaisesRegex( - self, - ValueError, - "'inline_formsets.Child' has more than one ForeignKey to 'inline_formsets.Parent'.", - inlineformset_factory, Parent, Child - ) + msg = "'inline_formsets.Child' has more than one ForeignKey to 'inline_formsets.Parent'." + with self.assertRaisesMessage(ValueError, msg): + inlineformset_factory(Parent, Child) 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 exception. """ - six.assertRaisesRegex( - self, ValueError, - "'inline_formsets.Child' has no field named 'test'.", - inlineformset_factory, Parent, Child, fk_name='test' - ) + with self.assertRaisesMessage(ValueError, "'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): # Regression test for #9171. diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 1ef749e0b3..4eb96de2e9 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -499,7 +499,7 @@ class MakeMigrationsTests(MigrationTestBase): apps.register_model('migrations', UnserializableModel) 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) initial_file = os.path.join(migration_dir, "0001_initial.py") diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py index 22d2df2754..81e7ec1dd8 100644 --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -9,7 +9,6 @@ from django.db.models.fields import NOT_PROVIDED from django.db.transaction import atomic from django.db.utils import IntegrityError from django.test import override_settings, skipUnlessDBFeature -from django.utils import six from .models import FoodManager, FoodQuerySet from .test_base import MigrationTestBase @@ -1607,16 +1606,12 @@ class OperationTests(OperationTestBase): ) with connection.schema_editor() as editor: - six.assertRaisesRegex(self, ValueError, - "Expected a 2-tuple but got 1", - operation.database_forwards, - "test_runsql", editor, project_state, new_state) + with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"): + operation.database_forwards("test_runsql", editor, project_state, new_state) with connection.schema_editor() as editor: - six.assertRaisesRegex(self, ValueError, - "Expected a 2-tuple but got 3", - operation.database_backwards, - "test_runsql", editor, new_state, project_state) + with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"): + operation.database_backwards("test_runsql", editor, new_state, project_state) def test_run_sql_noop(self): """ diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py index 7d0e457d40..03dd5f7ed3 100644 --- a/tests/migrations/test_writer.py +++ b/tests/migrations/test_writer.py @@ -296,7 +296,7 @@ class WriterTests(SimpleTestCase): ) 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(models.SET_NULL) string, imports = MigrationWriter.serialize(models.SET(42)) @@ -463,8 +463,7 @@ class WriterTests(SimpleTestCase): return "somewhere dynamic" thing = models.FileField(upload_to=upload_to) - with six.assertRaisesRegex(self, ValueError, - '^Could not find function upload_to in migrations.test_writer'): + with self.assertRaisesMessage(ValueError, 'Could not find function upload_to in migrations.test_writer'): self.serialize_round_trip(TestModel2.thing) def test_serialize_managers(self): diff --git a/tests/queries/tests.py b/tests/queries/tests.py index 376208c62d..f1acd69067 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -1362,9 +1362,8 @@ class Queries4Tests(BaseQuerysetTest): def test_ticket11811(self): unsaved_category = NamedCategory(name="Other") - with six.assertRaisesRegex(self, ValueError, - 'Unsaved model instance ' - 'cannot be used in an ORM query.'): + msg = 'Unsaved model instance cannot be used in an ORM query.' + with self.assertRaisesMessage(ValueError, msg): Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category) def test_ticket14876(self): @@ -2321,48 +2320,26 @@ class QuerySetSupportsPythonIdioms(TestCase): ""]) def test_slicing_cannot_filter_queryset_once_sliced(self): - six.assertRaisesRegex( - self, - AssertionError, - "Cannot filter a query once a slice has been taken.", - Article.objects.all()[0:5].filter, - id=1, - ) + with self.assertRaisesMessage(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): - six.assertRaisesRegex( - self, - AssertionError, - "Cannot reorder a query once a slice has been taken.", - Article.objects.all()[0:5].order_by, - 'id', - ) + with self.assertRaisesMessage(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): - six.assertRaisesRegex( - self, - AssertionError, - "Cannot combine queries once a slice has been taken.", - lambda: Article.objects.all()[0:1] & Article.objects.all()[4:5] - ) + with self.assertRaisesMessage(AssertionError, "Cannot combine queries once a slice has been taken."): + Article.objects.all()[0:1] & Article.objects.all()[4:5] def test_slicing_negative_indexing_not_supported_for_single_element(self): """hint: inverting your ordering might do what you need""" - six.assertRaisesRegex( - self, - AssertionError, - "Negative indexing is not supported.", - lambda: Article.objects.all()[-1] - ) + with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): + Article.objects.all()[-1] def test_slicing_negative_indexing_not_supported_for_range(self): """hint: inverting your ordering might do what you need""" - six.assertRaisesRegex( - self, - AssertionError, - "Negative indexing is not supported.", - lambda: Article.objects.all()[0:-5] - ) + with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): + Article.objects.all()[0:-5] def test_can_get_number_of_items_in_queryset_using_standard_len(self): self.assertEqual(len(Article.objects.filter(name__exact='Article 1')), 1) diff --git a/tests/serializers/test_yaml.py b/tests/serializers/test_yaml.py index 2b5933d698..0b4b9b00d1 100644 --- a/tests/serializers/test_yaml.py +++ b/tests/serializers/test_yaml.py @@ -82,7 +82,7 @@ class NoYamlSerializerTestCase(SimpleTestCase): def test_dumpdata_pyyaml_error_message(self): """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') diff --git a/tests/staticfiles_tests/test_management.py b/tests/staticfiles_tests/test_management.py index 7c1c4223d0..ed6749b217 100644 --- a/tests/staticfiles_tests/test_management.py +++ b/tests/staticfiles_tests/test_management.py @@ -98,12 +98,11 @@ class TestFindStatic(CollectionTestCase, TestDefaults): class TestConfiguration(StaticFilesTestCase): def test_location_empty(self): + msg = 'without having set the STATIC_ROOT setting to a filesystem path' err = six.StringIO() for root in ['', None]: with override_settings(STATIC_ROOT=root): - with six.assertRaisesRegex( - self, ImproperlyConfigured, - 'without having set the STATIC_ROOT setting to a filesystem path'): + with self.assertRaisesMessage(ImproperlyConfigured, msg): call_command('collectstatic', interactive=False, verbosity=0, stderr=err) def test_local_storage_detection_helper(self): diff --git a/tests/transactions/tests.py b/tests/transactions/tests.py index 5d7851032f..b9faed1c62 100644 --- a/tests/transactions/tests.py +++ b/tests/transactions/tests.py @@ -12,7 +12,6 @@ from django.db import ( from django.test import ( TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) -from django.utils import six from .models import Reporter @@ -45,7 +44,7 @@ class AtomicTests(TransactionTestCase): def make_reporter(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): make_reporter() self.assertQuerysetEqual(Reporter.objects.all(), []) @@ -61,7 +60,7 @@ class AtomicTests(TransactionTestCase): def make_reporter(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): make_reporter() self.assertQuerysetEqual(Reporter.objects.all(), []) @@ -71,7 +70,7 @@ class AtomicTests(TransactionTestCase): self.assertQuerysetEqual(Reporter.objects.all(), ['']) def test_rollback(self): - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") @@ -88,14 +87,14 @@ class AtomicTests(TransactionTestCase): def test_nested_commit_rollback(self): with transaction.atomic(): Reporter.objects.create(first_name="Tintin") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") self.assertQuerysetEqual(Reporter.objects.all(), ['']) def test_nested_rollback_commit(self): - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") with transaction.atomic(): @@ -104,10 +103,10 @@ class AtomicTests(TransactionTestCase): self.assertQuerysetEqual(Reporter.objects.all(), []) def test_nested_rollback_rollback(self): - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") @@ -125,7 +124,7 @@ class AtomicTests(TransactionTestCase): def test_merged_commit_rollback(self): with transaction.atomic(): Reporter.objects.create(first_name="Tintin") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") @@ -133,7 +132,7 @@ class AtomicTests(TransactionTestCase): self.assertQuerysetEqual(Reporter.objects.all(), []) def test_merged_rollback_commit(self): - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") with transaction.atomic(savepoint=False): @@ -142,10 +141,10 @@ class AtomicTests(TransactionTestCase): self.assertQuerysetEqual(Reporter.objects.all(), []) def test_merged_rollback_rollback(self): - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(): Reporter.objects.create(last_name="Tintin") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with transaction.atomic(savepoint=False): Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") @@ -165,7 +164,7 @@ class AtomicTests(TransactionTestCase): atomic = transaction.atomic() with atomic: Reporter.objects.create(first_name="Tintin") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") @@ -173,7 +172,7 @@ class AtomicTests(TransactionTestCase): def test_reuse_rollback_commit(self): atomic = transaction.atomic() - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(last_name="Tintin") with atomic: @@ -183,10 +182,10 @@ class AtomicTests(TransactionTestCase): def test_reuse_rollback_rollback(self): atomic = transaction.atomic() - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(last_name="Tintin") - with six.assertRaisesRegex(self, Exception, "Oops"): + with self.assertRaisesMessage(Exception, "Oops"): with atomic: Reporter.objects.create(first_name="Haddock") raise Exception("Oops, that's his last name") @@ -256,7 +255,7 @@ class AtomicMergeTests(TransactionTestCase): Reporter.objects.create(first_name="Tintin") with transaction.atomic(savepoint=False): 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): Reporter.objects.create(first_name="Calculus") raise Exception("Oops, that's his last name") @@ -280,7 +279,7 @@ class AtomicMergeTests(TransactionTestCase): Reporter.objects.create(first_name="Tintin") with transaction.atomic(): 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): Reporter.objects.create(first_name="Calculus") raise Exception("Oops, that's his last name") @@ -383,7 +382,7 @@ class AtomicMySQLTests(TransactionTestCase): other_thread.start() 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. with transaction.atomic(): with transaction.atomic(): @@ -419,7 +418,7 @@ class AtomicMiscTests(TransactionTestCase): with transaction.atomic(): # 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. with transaction.atomic(): diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py index c90ef470bb..2d30e18915 100644 --- a/tests/utils_tests/test_datastructures.py +++ b/tests/utils_tests/test_datastructures.py @@ -49,8 +49,8 @@ class MultiValueDictTests(SimpleTestCase): [('name', ['Adrian', 'Simon']), ('position', ['Developer'])] ) - six.assertRaisesRegex(self, MultiValueDictKeyError, 'lastname', - d.__getitem__, 'lastname') + with self.assertRaisesMessage(MultiValueDictKeyError, 'lastname'): + d.__getitem__('lastname') self.assertEqual(d.get('lastname'), None) self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent') diff --git a/tests/utils_tests/test_module_loading.py b/tests/utils_tests/test_module_loading.py index 7140515cb9..738d3c7d04 100644 --- a/tests/utils_tests/test_module_loading.py +++ b/tests/utils_tests/test_module_loading.py @@ -5,7 +5,7 @@ import unittest from importlib import import_module 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.utils import six from django.utils._os import upath @@ -115,7 +115,7 @@ class EggLoader(unittest.TestCase): import_module('egg_module.sub1.sub2.no_such_module') -class ModuleImportTestCase(unittest.TestCase): +class ModuleImportTestCase(TestCase): def test_import_string(self): cls = import_string('django.utils.module_loading.import_string') self.assertEqual(cls, import_string) @@ -124,7 +124,7 @@ class ModuleImportTestCase(unittest.TestCase): with self.assertRaises(ImportError): import_string('no_dots_in_path') 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') @@ -164,13 +164,13 @@ class AutodiscoverModulesTestCase(SimpleTestCase): def test_validate_registry_keeps_intact(self): 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) self.assertEqual(site._registry, {}) def test_validate_registry_resets_after_erroneous_module(self): 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) self.assertEqual(site._registry, {'lorem': 'ipsum'})