Refs #26022 -- Used context manager version of assertRaisesMessage in tests.
This commit is contained in:
parent
3d0dcd7f5a
commit
253adc2b8a
|
@ -127,12 +127,12 @@ class TestRegistrationDecorator(SimpleTestCase):
|
|||
self.default_site.unregister(Place)
|
||||
|
||||
def test_wrapped_class_not_a_model_admin(self):
|
||||
self.assertRaisesMessage(ValueError, 'Wrapped class must subclass ModelAdmin.',
|
||||
register(Person), CustomSite)
|
||||
with self.assertRaisesMessage(ValueError, 'Wrapped class must subclass ModelAdmin.'):
|
||||
register(Person)(CustomSite)
|
||||
|
||||
def test_custom_site_not_an_admin_site(self):
|
||||
self.assertRaisesMessage(ValueError, 'site must subclass AdminSite',
|
||||
register(Person, site=Traveler), NameAdmin)
|
||||
with self.assertRaisesMessage(ValueError, 'site must subclass AdminSite'):
|
||||
register(Person, site=Traveler)(NameAdmin)
|
||||
|
||||
def test_empty_models_list_registration_fails(self):
|
||||
with self.assertRaisesMessage(ValueError, 'At least one model must be passed to register.'):
|
||||
|
|
|
@ -161,11 +161,8 @@ class UserManagerTestCase(TestCase):
|
|||
self.assertEqual(returned, 'email\ with_whitespace@d.com')
|
||||
|
||||
def test_empty_username(self):
|
||||
self.assertRaisesMessage(
|
||||
ValueError,
|
||||
'The given username must be set',
|
||||
User.objects.create_user, username=''
|
||||
)
|
||||
with self.assertRaisesMessage(ValueError, 'The given username must be set'):
|
||||
User.objects.create_user(username='')
|
||||
|
||||
def test_create_user_is_staff(self):
|
||||
email = 'normal@normal.com'
|
||||
|
|
|
@ -91,31 +91,22 @@ class CustomColumnsTests(TestCase):
|
|||
self.assertEqual(self.a1, Author.objects.get(first_name__exact='John'))
|
||||
|
||||
def test_filter_on_nonexistent_field(self):
|
||||
self.assertRaisesMessage(
|
||||
FieldError,
|
||||
msg = (
|
||||
"Cannot resolve keyword 'firstname' into field. Choices are: "
|
||||
"Author_ID, article, first_name, last_name, primary_set",
|
||||
Author.objects.filter,
|
||||
firstname__exact='John'
|
||||
"Author_ID, article, first_name, last_name, primary_set"
|
||||
)
|
||||
with self.assertRaisesMessage(FieldError, msg):
|
||||
Author.objects.filter(firstname__exact='John')
|
||||
|
||||
def test_author_get_attributes(self):
|
||||
a = Author.objects.get(last_name__exact='Smith')
|
||||
self.assertEqual('John', a.first_name)
|
||||
self.assertEqual('Smith', a.last_name)
|
||||
self.assertRaisesMessage(
|
||||
AttributeError,
|
||||
"'Author' object has no attribute 'firstname'",
|
||||
getattr,
|
||||
a, 'firstname'
|
||||
)
|
||||
with self.assertRaisesMessage(AttributeError, "'Author' object has no attribute 'firstname'"):
|
||||
getattr(a, 'firstname')
|
||||
|
||||
self.assertRaisesMessage(
|
||||
AttributeError,
|
||||
"'Author' object has no attribute 'last'",
|
||||
getattr,
|
||||
a, 'last'
|
||||
)
|
||||
with self.assertRaisesMessage(AttributeError, "'Author' object has no attribute 'last'"):
|
||||
getattr(a, 'last')
|
||||
|
||||
def test_m2m_table(self):
|
||||
self.assertQuerysetEqual(
|
||||
|
|
|
@ -90,11 +90,8 @@ class DistinctOnTests(TestCase):
|
|||
|
||||
# Combining queries with different distinct_fields is not allowed.
|
||||
base_qs = Celebrity.objects.all()
|
||||
self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
"Cannot combine queries with different distinct fields.",
|
||||
lambda: (base_qs.distinct('id') & base_qs.distinct('name'))
|
||||
)
|
||||
with self.assertRaisesMessage(AssertionError, "Cannot combine queries with different distinct fields."):
|
||||
base_qs.distinct('id') & base_qs.distinct('name')
|
||||
|
||||
# Test join unreffing
|
||||
c1 = Celebrity.objects.distinct('greatest_fan__id', 'greatest_fan__fan_of')
|
||||
|
|
|
@ -318,7 +318,8 @@ class BasicExpressionsTests(TestCase):
|
|||
'expressions.Company.num_employees. F() expressions can only be '
|
||||
'used to update, not to insert.'
|
||||
)
|
||||
self.assertRaisesMessage(ValueError, msg, acme.save)
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
acme.save()
|
||||
|
||||
acme.num_employees = 12
|
||||
acme.name = Lower(F('name'))
|
||||
|
@ -327,7 +328,8 @@ class BasicExpressionsTests(TestCase):
|
|||
'expressions.Company.name))" on expressions.Company.name. F() '
|
||||
'expressions can only be used to update, not to insert.'
|
||||
)
|
||||
self.assertRaisesMessage(ValueError, msg, acme.save)
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
acme.save()
|
||||
|
||||
def test_ticket_11722_iexact_lookup(self):
|
||||
Employee.objects.create(firstname="John", lastname="Doe")
|
||||
|
|
|
@ -574,10 +574,8 @@ class FileFieldStorageTests(TestCase):
|
|||
# Testing exception is raised when filename is too short to truncate.
|
||||
filename = 'short.longext'
|
||||
objs[0].limited_length.save(filename, ContentFile('Same Content'))
|
||||
self.assertRaisesMessage(
|
||||
SuspiciousFileOperation, 'Storage can not find an available filename',
|
||||
objs[1].limited_length.save, *(filename, ContentFile('Same Content'))
|
||||
)
|
||||
with self.assertRaisesMessage(SuspiciousFileOperation, 'Storage can not find an available filename'):
|
||||
objs[1].limited_length.save(*(filename, ContentFile('Same Content')))
|
||||
finally:
|
||||
for o in objs:
|
||||
o.delete()
|
||||
|
|
|
@ -537,14 +537,8 @@ class TestFixtures(TestCase):
|
|||
settings.FIXTURE_DIRS cannot contain duplicates in order to avoid
|
||||
repeated fixture loading.
|
||||
"""
|
||||
self.assertRaisesMessage(
|
||||
ImproperlyConfigured,
|
||||
"settings.FIXTURE_DIRS contains duplicates.",
|
||||
management.call_command,
|
||||
'loaddata',
|
||||
'absolute.json',
|
||||
verbosity=0,
|
||||
)
|
||||
with self.assertRaisesMessage(ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."):
|
||||
management.call_command('loaddata', 'absolute.json', verbosity=0)
|
||||
|
||||
@skipIfNonASCIIPath
|
||||
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures')])
|
||||
|
@ -553,16 +547,13 @@ class TestFixtures(TestCase):
|
|||
settings.FIXTURE_DIRS cannot contain a default fixtures directory
|
||||
for application (app/fixtures) in order to avoid repeated fixture loading.
|
||||
"""
|
||||
self.assertRaisesMessage(
|
||||
ImproperlyConfigured,
|
||||
msg = (
|
||||
"'%s' is a default fixture directory for the '%s' app "
|
||||
"and cannot be listed in settings.FIXTURE_DIRS."
|
||||
% (os.path.join(_cur_dir, 'fixtures'), 'fixtures_regress'),
|
||||
management.call_command,
|
||||
'loaddata',
|
||||
'absolute.json',
|
||||
verbosity=0,
|
||||
% (os.path.join(_cur_dir, 'fixtures'), 'fixtures_regress')
|
||||
)
|
||||
with self.assertRaisesMessage(ImproperlyConfigured, msg):
|
||||
management.call_command('loaddata', 'absolute.json', verbosity=0)
|
||||
|
||||
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'),
|
||||
os.path.join(_cur_dir, 'fixtures_2')])
|
||||
|
@ -734,41 +725,37 @@ class NaturalKeyFixtureTests(TestCase):
|
|||
)
|
||||
|
||||
def test_dependency_sorting_tight_circular(self):
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
RuntimeError,
|
||||
"Can't resolve dependencies for fixtures_regress.Circle1, "
|
||||
"fixtures_regress.Circle2 in serialized app list.",
|
||||
serializers.sort_dependencies,
|
||||
[('fixtures_regress', [Person, Circle2, Circle1, Store, Book])],
|
||||
)
|
||||
"fixtures_regress.Circle2 in serialized app list."
|
||||
):
|
||||
serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Store, Book])])
|
||||
|
||||
def test_dependency_sorting_tight_circular_2(self):
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
RuntimeError,
|
||||
"Can't resolve dependencies for fixtures_regress.Circle1, "
|
||||
"fixtures_regress.Circle2 in serialized app list.",
|
||||
serializers.sort_dependencies,
|
||||
[('fixtures_regress', [Circle1, Book, Circle2])],
|
||||
)
|
||||
"fixtures_regress.Circle2 in serialized app list."
|
||||
):
|
||||
serializers.sort_dependencies([('fixtures_regress', [Circle1, Book, Circle2])])
|
||||
|
||||
def test_dependency_self_referential(self):
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
RuntimeError,
|
||||
"Can't resolve dependencies for fixtures_regress.Circle3 in "
|
||||
"serialized app list.",
|
||||
serializers.sort_dependencies,
|
||||
[('fixtures_regress', [Book, Circle3])],
|
||||
)
|
||||
"serialized app list."
|
||||
):
|
||||
serializers.sort_dependencies([('fixtures_regress', [Book, Circle3])])
|
||||
|
||||
def test_dependency_sorting_long(self):
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
RuntimeError,
|
||||
"Can't resolve dependencies for fixtures_regress.Circle1, "
|
||||
"fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized "
|
||||
"app list.",
|
||||
serializers.sort_dependencies,
|
||||
[('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])],
|
||||
)
|
||||
"app list."
|
||||
):
|
||||
serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])])
|
||||
|
||||
def test_dependency_sorting_normal(self):
|
||||
sorted_deps = serializers.sort_dependencies(
|
||||
|
@ -830,13 +817,12 @@ class M2MNaturalKeyFixtureTests(TestCase):
|
|||
Resolving circular M2M relations without explicit through models should
|
||||
fail loudly
|
||||
"""
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
RuntimeError,
|
||||
"Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, "
|
||||
"fixtures_regress.M2MSimpleCircularB in serialized app list.",
|
||||
serializers.sort_dependencies,
|
||||
[('fixtures_regress', [M2MSimpleCircularA, M2MSimpleCircularB])]
|
||||
)
|
||||
"fixtures_regress.M2MSimpleCircularB in serialized app list."
|
||||
):
|
||||
serializers.sort_dependencies([('fixtures_regress', [M2MSimpleCircularA, M2MSimpleCircularB])])
|
||||
|
||||
def test_dependency_sorting_m2m_complex(self):
|
||||
"""
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -2733,14 +2733,19 @@ Good luck picking a username that doesn't already exist.</p>
|
|||
# An empty value for any field will raise a `required` error on a
|
||||
# required `MultiValueField`.
|
||||
f = PhoneField()
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ['+61'])
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ['+61', '287654321', '123'])
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean('')
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean(None)
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean([])
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean(['+61'])
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean(['+61', '287654321', '123'])
|
||||
self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
|
||||
self.assertRaisesMessage(ValidationError,
|
||||
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home'])
|
||||
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
|
||||
f.clean(['61', '287654321', '123', 'Home'])
|
||||
|
||||
# Empty values for fields will NOT raise a `required` error on an
|
||||
# optional `MultiValueField`
|
||||
|
@ -2751,23 +2756,27 @@ Good luck picking a username that doesn't already exist.</p>
|
|||
self.assertEqual('+61. ext. (label: )', f.clean(['+61']))
|
||||
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
|
||||
self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
|
||||
self.assertRaisesMessage(ValidationError,
|
||||
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home'])
|
||||
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
|
||||
f.clean(['61', '287654321', '123', 'Home'])
|
||||
|
||||
# For a required `MultiValueField` with `require_all_fields=False`, a
|
||||
# `required` error will only be raised if all fields are empty. Fields
|
||||
# can individually be required or optional. An empty value for any
|
||||
# required field will raise an `incomplete` error.
|
||||
f = PhoneField(require_all_fields=False)
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '')
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None)
|
||||
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, [])
|
||||
self.assertRaisesMessage(ValidationError, "'Enter a complete value.'", f.clean, ['+61'])
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean('')
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean(None)
|
||||
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
|
||||
f.clean([])
|
||||
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
|
||||
f.clean(['+61'])
|
||||
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
|
||||
six.assertRaisesRegex(self, ValidationError,
|
||||
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'])
|
||||
self.assertRaisesMessage(ValidationError,
|
||||
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home'])
|
||||
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
|
||||
f.clean(['61', '287654321', '123', 'Home'])
|
||||
|
||||
# For an optional `MultiValueField` with `require_all_fields=False`, we
|
||||
# don't get any `required` error but we still get `incomplete` errors.
|
||||
|
@ -2775,12 +2784,13 @@ Good luck picking a username that doesn't already exist.</p>
|
|||
self.assertIsNone(f.clean(''))
|
||||
self.assertIsNone(f.clean(None))
|
||||
self.assertIsNone(f.clean([]))
|
||||
self.assertRaisesMessage(ValidationError, "'Enter a complete value.'", f.clean, ['+61'])
|
||||
with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"):
|
||||
f.clean(['+61'])
|
||||
self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
|
||||
six.assertRaisesRegex(self, ValidationError,
|
||||
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'])
|
||||
self.assertRaisesMessage(ValidationError,
|
||||
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home'])
|
||||
with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
|
||||
f.clean(['61', '287654321', '123', 'Home'])
|
||||
|
||||
def test_custom_empty_values(self):
|
||||
"""
|
||||
|
|
|
@ -384,8 +384,8 @@ class SelectDateWidgetTest(WidgetTest):
|
|||
""",
|
||||
)
|
||||
|
||||
self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.',
|
||||
SelectDateWidget, years=('2014',), empty_label=('not enough', 'values'))
|
||||
with self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.'):
|
||||
SelectDateWidget(years=('2014',), empty_label=('not enough', 'values'))
|
||||
|
||||
@override_settings(USE_L10N=True)
|
||||
@translation.override('nl')
|
||||
|
|
|
@ -58,12 +58,12 @@ class EarliestOrLatestTests(TestCase):
|
|||
# Ensure that error is raised if the user forgot to add a get_latest_by
|
||||
# in the Model.Meta
|
||||
Article.objects.model._meta.get_latest_by = None
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
"earliest() and latest() require either a field_name parameter or "
|
||||
"'get_latest_by' in the model",
|
||||
lambda: Article.objects.earliest(),
|
||||
)
|
||||
"'get_latest_by' in the model"
|
||||
):
|
||||
Article.objects.earliest()
|
||||
|
||||
def test_latest(self):
|
||||
# Because no Articles exist yet, latest() raises ArticleDoesNotExist.
|
||||
|
@ -109,12 +109,11 @@ class EarliestOrLatestTests(TestCase):
|
|||
# Ensure that error is raised if the user forgot to add a get_latest_by
|
||||
# in the Model.Meta
|
||||
Article.objects.model._meta.get_latest_by = None
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
"earliest() and latest() require either a field_name parameter or "
|
||||
"'get_latest_by' in the model",
|
||||
lambda: Article.objects.latest(),
|
||||
)
|
||||
"earliest() and latest() require either a field_name parameter or "
|
||||
"'get_latest_by' in the model"):
|
||||
Article.objects.latest()
|
||||
|
||||
def test_latest_manual(self):
|
||||
# You can still use latest() with a model that doesn't have
|
||||
|
|
|
@ -81,27 +81,18 @@ class GetObjectOr404Tests(TestCase):
|
|||
def test_bad_class(self):
|
||||
# Given an argument klass that is not a Model, Manager, or Queryset
|
||||
# raises a helpful ValueError message
|
||||
self.assertRaisesMessage(
|
||||
ValueError,
|
||||
"Object is of type 'str', but must be a Django Model, Manager, "
|
||||
"or QuerySet",
|
||||
get_object_or_404, str("Article"), title__icontains="Run"
|
||||
)
|
||||
msg = "Object is of type 'str', but must be a Django Model, Manager, or QuerySet"
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
get_object_or_404(str("Article"), title__icontains="Run")
|
||||
|
||||
class CustomClass(object):
|
||||
pass
|
||||
|
||||
self.assertRaisesMessage(
|
||||
ValueError,
|
||||
"Object is of type 'CustomClass', but must be a Django Model, "
|
||||
"Manager, or QuerySet",
|
||||
get_object_or_404, CustomClass, title__icontains="Run"
|
||||
)
|
||||
msg = "Object is of type 'CustomClass', but must be a Django Model, Manager, or QuerySet"
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
get_object_or_404(CustomClass, title__icontains="Run")
|
||||
|
||||
# Works for lists too
|
||||
self.assertRaisesMessage(
|
||||
ValueError,
|
||||
"Object is of type 'list', but must be a Django Model, Manager, "
|
||||
"or QuerySet",
|
||||
get_list_or_404, [Article], title__icontains="Run"
|
||||
)
|
||||
msg = "Object is of type 'list', but must be a Django Model, Manager, or QuerySet"
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
get_list_or_404([Article], title__icontains="Run")
|
||||
|
|
|
@ -1355,9 +1355,8 @@ class M2mThroughFieldsTests(SimpleTestCase):
|
|||
class Fan(models.Model):
|
||||
pass
|
||||
|
||||
self.assertRaisesMessage(
|
||||
ValueError, 'Cannot specify through_fields without a through model',
|
||||
models.ManyToManyField, Fan, through_fields=('f1', 'f2'))
|
||||
with self.assertRaisesMessage(ValueError, 'Cannot specify through_fields without a through model'):
|
||||
models.ManyToManyField(Fan, through_fields=('f1', 'f2'))
|
||||
|
||||
def test_invalid_order(self):
|
||||
"""
|
||||
|
|
|
@ -1109,8 +1109,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
|
|||
backend = smtp.EmailBackend(
|
||||
username='not empty username', password='not empty password')
|
||||
try:
|
||||
self.assertRaisesMessage(SMTPException,
|
||||
'SMTP AUTH extension not supported by server.', backend.open)
|
||||
with self.assertRaisesMessage(SMTPException, 'SMTP AUTH extension not supported by server.'):
|
||||
backend.open()
|
||||
finally:
|
||||
backend.close()
|
||||
|
||||
|
@ -1185,8 +1185,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
|
|||
backend = smtp.EmailBackend()
|
||||
self.assertTrue(backend.use_tls)
|
||||
try:
|
||||
self.assertRaisesMessage(SMTPException,
|
||||
'STARTTLS extension not supported by server.', backend.open)
|
||||
with self.assertRaisesMessage(SMTPException, 'STARTTLS extension not supported by server.'):
|
||||
backend.open()
|
||||
finally:
|
||||
backend.close()
|
||||
|
||||
|
|
|
@ -490,17 +490,12 @@ class ManyToOneTests(TestCase):
|
|||
|
||||
def test_values_list_exception(self):
|
||||
expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s"
|
||||
|
||||
self.assertRaisesMessage(FieldError,
|
||||
expected_message % ', '.join(sorted(f.name for f in Reporter._meta.get_fields())),
|
||||
Article.objects.values_list,
|
||||
'reporter__notafield')
|
||||
self.assertRaisesMessage(
|
||||
FieldError,
|
||||
expected_message % ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields())),
|
||||
Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list,
|
||||
'notafield'
|
||||
)
|
||||
reporter_fields = ', '.join(sorted(f.name for f in Reporter._meta.get_fields()))
|
||||
with self.assertRaisesMessage(FieldError, expected_message % reporter_fields):
|
||||
Article.objects.values_list('reporter__notafield')
|
||||
article_fields = ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields()))
|
||||
with self.assertRaisesMessage(FieldError, expected_message % article_fields):
|
||||
Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list('notafield')
|
||||
|
||||
def test_fk_assignment_and_related_object_cache(self):
|
||||
# Tests of ForeignKey assignment and the related-object cache (see #6886).
|
||||
|
|
|
@ -47,13 +47,11 @@ class TestSaveLoad(TestCase):
|
|||
PrimaryKeyUUIDModel.objects.get(pk=[])
|
||||
|
||||
def test_wrong_value(self):
|
||||
self.assertRaisesMessage(
|
||||
ValueError, 'badly formed hexadecimal UUID string',
|
||||
UUIDModel.objects.get, field='not-a-uuid')
|
||||
with self.assertRaisesMessage(ValueError, 'badly formed hexadecimal UUID string'):
|
||||
UUIDModel.objects.get(field='not-a-uuid')
|
||||
|
||||
self.assertRaisesMessage(
|
||||
ValueError, 'badly formed hexadecimal UUID string',
|
||||
UUIDModel.objects.create, field='not-a-uuid')
|
||||
with self.assertRaisesMessage(ValueError, 'badly formed hexadecimal UUID string'):
|
||||
UUIDModel.objects.create(field='not-a-uuid')
|
||||
|
||||
|
||||
class TestMigrations(SimpleTestCase):
|
||||
|
|
|
@ -431,16 +431,10 @@ class Queries1Tests(BaseQuerysetTest):
|
|||
def test_heterogeneous_qs_combination(self):
|
||||
# Combining querysets built on different models should behave in a well-defined
|
||||
# fashion. We raise an error.
|
||||
self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
'Cannot combine queries on two different base models.',
|
||||
lambda: Author.objects.all() & Tag.objects.all()
|
||||
)
|
||||
self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
'Cannot combine queries on two different base models.',
|
||||
lambda: Author.objects.all() | Tag.objects.all()
|
||||
)
|
||||
with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'):
|
||||
Author.objects.all() & Tag.objects.all()
|
||||
with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'):
|
||||
Author.objects.all() | Tag.objects.all()
|
||||
|
||||
def test_ticket3141(self):
|
||||
self.assertEqual(Author.objects.extra(select={'foo': '1'}).count(), 4)
|
||||
|
@ -759,11 +753,8 @@ class Queries1Tests(BaseQuerysetTest):
|
|||
[]
|
||||
)
|
||||
q.query.low_mark = 1
|
||||
self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
'Cannot change a query once a slice has been taken',
|
||||
q.extra, select={'foo': "1"}
|
||||
)
|
||||
with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken'):
|
||||
q.extra(select={'foo': "1"})
|
||||
self.assertQuerysetEqual(q.reverse(), [])
|
||||
self.assertQuerysetEqual(q.defer('meal'), [])
|
||||
self.assertQuerysetEqual(q.only('meal'), [])
|
||||
|
@ -790,16 +781,10 @@ class Queries1Tests(BaseQuerysetTest):
|
|||
)
|
||||
|
||||
# Multi-valued values() and values_list() querysets should raise errors.
|
||||
self.assertRaisesMessage(
|
||||
TypeError,
|
||||
'Cannot use multi-field values as a filter value.',
|
||||
lambda: Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id'))
|
||||
)
|
||||
self.assertRaisesMessage(
|
||||
TypeError,
|
||||
'Cannot use multi-field values as a filter value.',
|
||||
lambda: Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('name', 'id'))
|
||||
)
|
||||
with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'):
|
||||
Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id'))
|
||||
with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'):
|
||||
Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('name', 'id'))
|
||||
|
||||
def test_ticket9985(self):
|
||||
# qs.values_list(...).values(...) combinations should work.
|
||||
|
@ -1329,11 +1314,8 @@ class Queries3Tests(BaseQuerysetTest):
|
|||
def test_ticket8683(self):
|
||||
# An error should be raised when QuerySet.datetimes() is passed the
|
||||
# wrong type of field.
|
||||
self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
"'name' isn't a DateTimeField.",
|
||||
Item.objects.datetimes, 'name', 'month'
|
||||
)
|
||||
with self.assertRaisesMessage(AssertionError, "'name' isn't a DateTimeField."):
|
||||
Item.objects.datetimes('name', 'month')
|
||||
|
||||
def test_ticket22023(self):
|
||||
with self.assertRaisesMessage(TypeError,
|
||||
|
@ -2413,11 +2395,8 @@ class WeirdQuerysetSlicingTests(BaseQuerysetTest):
|
|||
self.assertQuerysetEqual(Article.objects.all()[0:0], [])
|
||||
self.assertQuerysetEqual(Article.objects.all()[0:0][:10], [])
|
||||
self.assertEqual(Article.objects.all()[:0].count(), 0)
|
||||
self.assertRaisesMessage(
|
||||
AssertionError,
|
||||
'Cannot change a query once a slice has been taken.',
|
||||
Article.objects.all()[:0].latest, 'created'
|
||||
)
|
||||
with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken.'):
|
||||
Article.objects.all()[:0].latest('created')
|
||||
|
||||
def test_empty_resultset_sql(self):
|
||||
# ticket #12192
|
||||
|
@ -2528,16 +2507,10 @@ class ConditionalTests(BaseQuerysetTest):
|
|||
def test_infinite_loop(self):
|
||||
# If you're not careful, it's possible to introduce infinite loops via
|
||||
# default ordering on foreign keys in a cycle. We detect that.
|
||||
self.assertRaisesMessage(
|
||||
FieldError,
|
||||
'Infinite loop caused by ordering.',
|
||||
lambda: list(LoopX.objects.all()) # Force queryset evaluation with list()
|
||||
)
|
||||
self.assertRaisesMessage(
|
||||
FieldError,
|
||||
'Infinite loop caused by ordering.',
|
||||
lambda: list(LoopZ.objects.all()) # Force queryset evaluation with list()
|
||||
)
|
||||
with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'):
|
||||
list(LoopX.objects.all()) # Force queryset evaluation with list()
|
||||
with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'):
|
||||
list(LoopZ.objects.all()) # Force queryset evaluation with list()
|
||||
|
||||
# Note that this doesn't cause an infinite loop, since the default
|
||||
# ordering on the Tag model is empty (and thus defaults to using "id"
|
||||
|
|
|
@ -772,11 +772,8 @@ class HostValidationTests(SimpleTestCase):
|
|||
]:
|
||||
request = HttpRequest()
|
||||
request.META = {'HTTP_HOST': host}
|
||||
self.assertRaisesMessage(
|
||||
SuspiciousOperation,
|
||||
msg_suggestion % (host, host),
|
||||
request.get_host
|
||||
)
|
||||
with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion % (host, host)):
|
||||
request.get_host()
|
||||
|
||||
for domain, port in [ # Valid-looking hosts with a port number
|
||||
('example.com', 80),
|
||||
|
@ -786,28 +783,19 @@ class HostValidationTests(SimpleTestCase):
|
|||
host = '%s:%s' % (domain, port)
|
||||
request = HttpRequest()
|
||||
request.META = {'HTTP_HOST': host}
|
||||
self.assertRaisesMessage(
|
||||
SuspiciousOperation,
|
||||
msg_suggestion % (host, domain),
|
||||
request.get_host
|
||||
)
|
||||
with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion % (host, domain)):
|
||||
request.get_host()
|
||||
|
||||
for host in self.poisoned_hosts:
|
||||
request = HttpRequest()
|
||||
request.META = {'HTTP_HOST': host}
|
||||
self.assertRaisesMessage(
|
||||
SuspiciousOperation,
|
||||
msg_invalid_host % host,
|
||||
request.get_host
|
||||
)
|
||||
with self.assertRaisesMessage(SuspiciousOperation, msg_invalid_host % host):
|
||||
request.get_host()
|
||||
|
||||
request = HttpRequest()
|
||||
request.META = {'HTTP_HOST': "invalid_hostname.com"}
|
||||
self.assertRaisesMessage(
|
||||
SuspiciousOperation,
|
||||
msg_suggestion2 % "invalid_hostname.com",
|
||||
request.get_host
|
||||
)
|
||||
with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion2 % "invalid_hostname.com"):
|
||||
request.get_host()
|
||||
|
||||
|
||||
class BuildAbsoluteURITestCase(SimpleTestCase):
|
||||
|
|
|
@ -801,7 +801,8 @@ class AssertRaisesMsgTest(SimpleTestCase):
|
|||
"""assertRaisesMessage shouldn't interpret RE special chars."""
|
||||
def func1():
|
||||
raise ValueError("[.*x+]y?")
|
||||
self.assertRaisesMessage(ValueError, "[.*x+]y?", func1)
|
||||
with self.assertRaisesMessage(ValueError, "[.*x+]y?"):
|
||||
func1()
|
||||
|
||||
@ignore_warnings(category=RemovedInDjango20Warning)
|
||||
def test_callable_obj_param(self):
|
||||
|
|
|
@ -252,13 +252,13 @@ class NoURLPatternsTests(SimpleTestCase):
|
|||
"""
|
||||
resolver = RegexURLResolver(r'^$', settings.ROOT_URLCONF)
|
||||
|
||||
self.assertRaisesMessage(
|
||||
with self.assertRaisesMessage(
|
||||
ImproperlyConfigured,
|
||||
"The included URLconf 'urlpatterns_reverse.no_urls' does not "
|
||||
"appear to have any patterns in it. If you see valid patterns in "
|
||||
"the file then the issue is probably caused by a circular import.",
|
||||
getattr, resolver, 'url_patterns'
|
||||
)
|
||||
"the file then the issue is probably caused by a circular import."
|
||||
):
|
||||
getattr(resolver, 'url_patterns')
|
||||
|
||||
|
||||
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls')
|
||||
|
|
|
@ -108,8 +108,8 @@ class ImmutableListTests(SimpleTestCase):
|
|||
d = ImmutableList(range(10))
|
||||
|
||||
# AttributeError: ImmutableList object is immutable.
|
||||
self.assertRaisesMessage(AttributeError,
|
||||
'ImmutableList object is immutable.', d.sort)
|
||||
with self.assertRaisesMessage(AttributeError, 'ImmutableList object is immutable.'):
|
||||
d.sort()
|
||||
|
||||
self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)')
|
||||
|
||||
|
@ -119,8 +119,8 @@ class ImmutableListTests(SimpleTestCase):
|
|||
self.assertEqual(d[1], 1)
|
||||
|
||||
# AttributeError: Object is immutable!
|
||||
self.assertRaisesMessage(AttributeError,
|
||||
'Object is immutable!', d.__setitem__, 1, 'test')
|
||||
with self.assertRaisesMessage(AttributeError, 'Object is immutable!'):
|
||||
d.__setitem__(1, 'test')
|
||||
|
||||
|
||||
class DictWrapperTests(SimpleTestCase):
|
||||
|
|
Loading…
Reference in New Issue