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.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):
"""

View File

@ -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):

View File

@ -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

View File

@ -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

View File

@ -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')

View File

@ -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):

View File

@ -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):

View File

@ -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):

View File

@ -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", '

View File

@ -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,

View File

@ -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):

View File

@ -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).

View File

@ -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(

View File

@ -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.

View File

@ -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")

View File

@ -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):
"""

View File

@ -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):

View File

@ -1362,9 +1362,8 @@ class Queries4Tests(BaseQuerysetTest):
def test_ticket11811(self):
unsaved_category = NamedCategory(name="Other")
with six.assertRaisesRegex(self, ValueError,
'Unsaved model instance <NamedCategory: Other> '
'cannot be used in an ORM query.'):
msg = 'Unsaved model instance <NamedCategory: Other> 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):
"<Article: Article 7>"])
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)

View File

@ -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')

View File

@ -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):

View File

@ -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(), ['<Reporter: Tintin>'])
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(), ['<Reporter: Tintin>'])
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():

View File

@ -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')

View File

@ -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'})