Refs #26022 -- Used context manager version of assertRaisesMessage in tests.

This commit is contained in:
Hasan 2016-01-04 12:20:08 +03:30 committed by Tim Graham
parent 3d0dcd7f5a
commit 253adc2b8a
21 changed files with 584 additions and 566 deletions

View File

@ -127,12 +127,12 @@ class TestRegistrationDecorator(SimpleTestCase):
self.default_site.unregister(Place) self.default_site.unregister(Place)
def test_wrapped_class_not_a_model_admin(self): def test_wrapped_class_not_a_model_admin(self):
self.assertRaisesMessage(ValueError, 'Wrapped class must subclass ModelAdmin.', with self.assertRaisesMessage(ValueError, 'Wrapped class must subclass ModelAdmin.'):
register(Person), CustomSite) register(Person)(CustomSite)
def test_custom_site_not_an_admin_site(self): def test_custom_site_not_an_admin_site(self):
self.assertRaisesMessage(ValueError, 'site must subclass AdminSite', with self.assertRaisesMessage(ValueError, 'site must subclass AdminSite'):
register(Person, site=Traveler), NameAdmin) register(Person, site=Traveler)(NameAdmin)
def test_empty_models_list_registration_fails(self): def test_empty_models_list_registration_fails(self):
with self.assertRaisesMessage(ValueError, 'At least one model must be passed to register.'): with self.assertRaisesMessage(ValueError, 'At least one model must be passed to register.'):

View File

@ -161,11 +161,8 @@ class UserManagerTestCase(TestCase):
self.assertEqual(returned, 'email\ with_whitespace@d.com') self.assertEqual(returned, 'email\ with_whitespace@d.com')
def test_empty_username(self): def test_empty_username(self):
self.assertRaisesMessage( with self.assertRaisesMessage(ValueError, 'The given username must be set'):
ValueError, User.objects.create_user(username='')
'The given username must be set',
User.objects.create_user, username=''
)
def test_create_user_is_staff(self): def test_create_user_is_staff(self):
email = 'normal@normal.com' email = 'normal@normal.com'

View File

@ -91,31 +91,22 @@ class CustomColumnsTests(TestCase):
self.assertEqual(self.a1, Author.objects.get(first_name__exact='John')) self.assertEqual(self.a1, Author.objects.get(first_name__exact='John'))
def test_filter_on_nonexistent_field(self): def test_filter_on_nonexistent_field(self):
self.assertRaisesMessage( msg = (
FieldError,
"Cannot resolve keyword 'firstname' into field. Choices are: " "Cannot resolve keyword 'firstname' into field. Choices are: "
"Author_ID, article, first_name, last_name, primary_set", "Author_ID, article, first_name, last_name, primary_set"
Author.objects.filter,
firstname__exact='John'
) )
with self.assertRaisesMessage(FieldError, msg):
Author.objects.filter(firstname__exact='John')
def test_author_get_attributes(self): def test_author_get_attributes(self):
a = Author.objects.get(last_name__exact='Smith') a = Author.objects.get(last_name__exact='Smith')
self.assertEqual('John', a.first_name) self.assertEqual('John', a.first_name)
self.assertEqual('Smith', a.last_name) self.assertEqual('Smith', a.last_name)
self.assertRaisesMessage( with self.assertRaisesMessage(AttributeError, "'Author' object has no attribute 'firstname'"):
AttributeError, getattr(a, 'firstname')
"'Author' object has no attribute 'firstname'",
getattr,
a, 'firstname'
)
self.assertRaisesMessage( with self.assertRaisesMessage(AttributeError, "'Author' object has no attribute 'last'"):
AttributeError, getattr(a, 'last')
"'Author' object has no attribute 'last'",
getattr,
a, 'last'
)
def test_m2m_table(self): def test_m2m_table(self):
self.assertQuerysetEqual( self.assertQuerysetEqual(

View File

@ -90,11 +90,8 @@ class DistinctOnTests(TestCase):
# Combining queries with different distinct_fields is not allowed. # Combining queries with different distinct_fields is not allowed.
base_qs = Celebrity.objects.all() base_qs = Celebrity.objects.all()
self.assertRaisesMessage( with self.assertRaisesMessage(AssertionError, "Cannot combine queries with different distinct fields."):
AssertionError, base_qs.distinct('id') & base_qs.distinct('name')
"Cannot combine queries with different distinct fields.",
lambda: (base_qs.distinct('id') & base_qs.distinct('name'))
)
# Test join unreffing # Test join unreffing
c1 = Celebrity.objects.distinct('greatest_fan__id', 'greatest_fan__fan_of') c1 = Celebrity.objects.distinct('greatest_fan__id', 'greatest_fan__fan_of')

View File

@ -318,7 +318,8 @@ class BasicExpressionsTests(TestCase):
'expressions.Company.num_employees. F() expressions can only be ' 'expressions.Company.num_employees. F() expressions can only be '
'used to update, not to insert.' 'used to update, not to insert.'
) )
self.assertRaisesMessage(ValueError, msg, acme.save) with self.assertRaisesMessage(ValueError, msg):
acme.save()
acme.num_employees = 12 acme.num_employees = 12
acme.name = Lower(F('name')) acme.name = Lower(F('name'))
@ -327,7 +328,8 @@ class BasicExpressionsTests(TestCase):
'expressions.Company.name))" on expressions.Company.name. F() ' 'expressions.Company.name))" on expressions.Company.name. F() '
'expressions can only be used to update, not to insert.' '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): def test_ticket_11722_iexact_lookup(self):
Employee.objects.create(firstname="John", lastname="Doe") Employee.objects.create(firstname="John", lastname="Doe")

View File

@ -574,10 +574,8 @@ class FileFieldStorageTests(TestCase):
# Testing exception is raised when filename is too short to truncate. # Testing exception is raised when filename is too short to truncate.
filename = 'short.longext' filename = 'short.longext'
objs[0].limited_length.save(filename, ContentFile('Same Content')) objs[0].limited_length.save(filename, ContentFile('Same Content'))
self.assertRaisesMessage( with self.assertRaisesMessage(SuspiciousFileOperation, 'Storage can not find an available filename'):
SuspiciousFileOperation, 'Storage can not find an available filename', objs[1].limited_length.save(*(filename, ContentFile('Same Content')))
objs[1].limited_length.save, *(filename, ContentFile('Same Content'))
)
finally: finally:
for o in objs: for o in objs:
o.delete() o.delete()

View File

@ -537,14 +537,8 @@ class TestFixtures(TestCase):
settings.FIXTURE_DIRS cannot contain duplicates in order to avoid settings.FIXTURE_DIRS cannot contain duplicates in order to avoid
repeated fixture loading. repeated fixture loading.
""" """
self.assertRaisesMessage( with self.assertRaisesMessage(ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."):
ImproperlyConfigured, management.call_command('loaddata', 'absolute.json', verbosity=0)
"settings.FIXTURE_DIRS contains duplicates.",
management.call_command,
'loaddata',
'absolute.json',
verbosity=0,
)
@skipIfNonASCIIPath @skipIfNonASCIIPath
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures')]) @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 settings.FIXTURE_DIRS cannot contain a default fixtures directory
for application (app/fixtures) in order to avoid repeated fixture loading. for application (app/fixtures) in order to avoid repeated fixture loading.
""" """
self.assertRaisesMessage( msg = (
ImproperlyConfigured,
"'%s' is a default fixture directory for the '%s' app " "'%s' is a default fixture directory for the '%s' app "
"and cannot be listed in settings.FIXTURE_DIRS." "and cannot be listed in settings.FIXTURE_DIRS."
% (os.path.join(_cur_dir, 'fixtures'), 'fixtures_regress'), % (os.path.join(_cur_dir, 'fixtures'), 'fixtures_regress')
management.call_command,
'loaddata',
'absolute.json',
verbosity=0,
) )
with self.assertRaisesMessage(ImproperlyConfigured, msg):
management.call_command('loaddata', 'absolute.json', verbosity=0)
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'), @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'),
os.path.join(_cur_dir, 'fixtures_2')]) os.path.join(_cur_dir, 'fixtures_2')])
@ -734,41 +725,37 @@ class NaturalKeyFixtureTests(TestCase):
) )
def test_dependency_sorting_tight_circular(self): def test_dependency_sorting_tight_circular(self):
self.assertRaisesMessage( with self.assertRaisesMessage(
RuntimeError, RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, " "Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list.", "fixtures_regress.Circle2 in serialized app list."
serializers.sort_dependencies, ):
[('fixtures_regress', [Person, Circle2, Circle1, Store, Book])], serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Store, Book])])
)
def test_dependency_sorting_tight_circular_2(self): def test_dependency_sorting_tight_circular_2(self):
self.assertRaisesMessage( with self.assertRaisesMessage(
RuntimeError, RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, " "Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2 in serialized app list.", "fixtures_regress.Circle2 in serialized app list."
serializers.sort_dependencies, ):
[('fixtures_regress', [Circle1, Book, Circle2])], serializers.sort_dependencies([('fixtures_regress', [Circle1, Book, Circle2])])
)
def test_dependency_self_referential(self): def test_dependency_self_referential(self):
self.assertRaisesMessage( with self.assertRaisesMessage(
RuntimeError, RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle3 in " "Can't resolve dependencies for fixtures_regress.Circle3 in "
"serialized app list.", "serialized app list."
serializers.sort_dependencies, ):
[('fixtures_regress', [Book, Circle3])], serializers.sort_dependencies([('fixtures_regress', [Book, Circle3])])
)
def test_dependency_sorting_long(self): def test_dependency_sorting_long(self):
self.assertRaisesMessage( with self.assertRaisesMessage(
RuntimeError, RuntimeError,
"Can't resolve dependencies for fixtures_regress.Circle1, " "Can't resolve dependencies for fixtures_regress.Circle1, "
"fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized " "fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized "
"app list.", "app list."
serializers.sort_dependencies, ):
[('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])], serializers.sort_dependencies([('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])])
)
def test_dependency_sorting_normal(self): def test_dependency_sorting_normal(self):
sorted_deps = serializers.sort_dependencies( sorted_deps = serializers.sort_dependencies(
@ -830,13 +817,12 @@ class M2MNaturalKeyFixtureTests(TestCase):
Resolving circular M2M relations without explicit through models should Resolving circular M2M relations without explicit through models should
fail loudly fail loudly
""" """
self.assertRaisesMessage( with self.assertRaisesMessage(
RuntimeError, RuntimeError,
"Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, " "Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, "
"fixtures_regress.M2MSimpleCircularB in serialized app list.", "fixtures_regress.M2MSimpleCircularB in serialized app list."
serializers.sort_dependencies, ):
[('fixtures_regress', [M2MSimpleCircularA, M2MSimpleCircularB])] serializers.sort_dependencies([('fixtures_regress', [M2MSimpleCircularA, M2MSimpleCircularB])])
)
def test_dependency_sorting_m2m_complex(self): def test_dependency_sorting_m2m_complex(self):
""" """

File diff suppressed because it is too large Load Diff

View File

@ -2733,14 +2733,19 @@ Good luck picking a username that doesn&#39;t already exist.</p>
# An empty value for any field will raise a `required` error on a # An empty value for any field will raise a `required` error on a
# required `MultiValueField`. # required `MultiValueField`.
f = PhoneField() f = PhoneField()
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) f.clean('')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, ['+61']) f.clean(None)
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(['+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.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
self.assertRaisesMessage(ValidationError, with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])
# Empty values for fields will NOT raise a `required` error on an # Empty values for fields will NOT raise a `required` error on an
# optional `MultiValueField` # optional `MultiValueField`
@ -2751,23 +2756,27 @@ Good luck picking a username that doesn&#39;t already exist.</p>
self.assertEqual('+61. ext. (label: )', f.clean(['+61'])) 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: )', f.clean(['+61', '287654321', '123']))
self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home'])) self.assertEqual('+61.287654321 ext. 123 (label: Home)', f.clean(['+61', '287654321', '123', 'Home']))
self.assertRaisesMessage(ValidationError, with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])
# For a required `MultiValueField` with `require_all_fields=False`, a # For a required `MultiValueField` with `require_all_fields=False`, a
# `required` error will only be raised if all fields are empty. Fields # `required` error will only be raised if all fields are empty. Fields
# can individually be required or optional. An empty value for any # can individually be required or optional. An empty value for any
# required field will raise an `incomplete` error. # required field will raise an `incomplete` error.
f = PhoneField(require_all_fields=False) f = PhoneField(require_all_fields=False)
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, '') with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, None) f.clean('')
self.assertRaisesMessage(ValidationError, "'This field is required.'", f.clean, []) with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
self.assertRaisesMessage(ValidationError, "'Enter a complete value.'", f.clean, ['+61']) 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'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex(self, ValidationError, six.assertRaisesRegex(self, ValidationError,
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'])
self.assertRaisesMessage(ValidationError, with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])
# For an optional `MultiValueField` with `require_all_fields=False`, we # For an optional `MultiValueField` with `require_all_fields=False`, we
# don't get any `required` error but we still get `incomplete` errors. # don't get any `required` error but we still get `incomplete` errors.
@ -2775,12 +2784,13 @@ Good luck picking a username that doesn&#39;t already exist.</p>
self.assertIsNone(f.clean('')) self.assertIsNone(f.clean(''))
self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean(None))
self.assertIsNone(f.clean([])) 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'])) self.assertEqual('+61.287654321 ext. 123 (label: )', f.clean(['+61', '287654321', '123']))
six.assertRaisesRegex(self, ValidationError, six.assertRaisesRegex(self, ValidationError,
"'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home']) "'Enter a complete value\.', u?'Enter an extension\.'", f.clean, ['', '', '', 'Home'])
self.assertRaisesMessage(ValidationError, with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"):
"'Enter a valid country code.'", f.clean, ['61', '287654321', '123', 'Home']) f.clean(['61', '287654321', '123', 'Home'])
def test_custom_empty_values(self): def test_custom_empty_values(self):
""" """

View File

@ -384,8 +384,8 @@ class SelectDateWidgetTest(WidgetTest):
""", """,
) )
self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.', with self.assertRaisesMessage(ValueError, 'empty_label list/tuple must have 3 elements.'):
SelectDateWidget, years=('2014',), empty_label=('not enough', 'values')) SelectDateWidget(years=('2014',), empty_label=('not enough', 'values'))
@override_settings(USE_L10N=True) @override_settings(USE_L10N=True)
@translation.override('nl') @translation.override('nl')

View File

@ -58,12 +58,12 @@ class EarliestOrLatestTests(TestCase):
# Ensure that error is raised if the user forgot to add a get_latest_by # Ensure that error is raised if the user forgot to add a get_latest_by
# in the Model.Meta # in the Model.Meta
Article.objects.model._meta.get_latest_by = None Article.objects.model._meta.get_latest_by = None
self.assertRaisesMessage( with self.assertRaisesMessage(
AssertionError, AssertionError,
"earliest() and latest() require either a field_name parameter or " "earliest() and latest() require either a field_name parameter or "
"'get_latest_by' in the model", "'get_latest_by' in the model"
lambda: Article.objects.earliest(), ):
) Article.objects.earliest()
def test_latest(self): def test_latest(self):
# Because no Articles exist yet, latest() raises ArticleDoesNotExist. # 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 # Ensure that error is raised if the user forgot to add a get_latest_by
# in the Model.Meta # in the Model.Meta
Article.objects.model._meta.get_latest_by = None Article.objects.model._meta.get_latest_by = None
self.assertRaisesMessage( with self.assertRaisesMessage(
AssertionError, AssertionError,
"earliest() and latest() require either a field_name parameter or " "earliest() and latest() require either a field_name parameter or "
"'get_latest_by' in the model", "'get_latest_by' in the model"):
lambda: Article.objects.latest(), Article.objects.latest()
)
def test_latest_manual(self): def test_latest_manual(self):
# You can still use latest() with a model that doesn't have # You can still use latest() with a model that doesn't have

View File

@ -81,27 +81,18 @@ class GetObjectOr404Tests(TestCase):
def test_bad_class(self): def test_bad_class(self):
# Given an argument klass that is not a Model, Manager, or Queryset # Given an argument klass that is not a Model, Manager, or Queryset
# raises a helpful ValueError message # raises a helpful ValueError message
self.assertRaisesMessage( msg = "Object is of type 'str', but must be a Django Model, Manager, or QuerySet"
ValueError, with self.assertRaisesMessage(ValueError, msg):
"Object is of type 'str', but must be a Django Model, Manager, " get_object_or_404(str("Article"), title__icontains="Run")
"or QuerySet",
get_object_or_404, str("Article"), title__icontains="Run"
)
class CustomClass(object): class CustomClass(object):
pass pass
self.assertRaisesMessage( msg = "Object is of type 'CustomClass', but must be a Django Model, Manager, or QuerySet"
ValueError, with self.assertRaisesMessage(ValueError, msg):
"Object is of type 'CustomClass', but must be a Django Model, " get_object_or_404(CustomClass, title__icontains="Run")
"Manager, or QuerySet",
get_object_or_404, CustomClass, title__icontains="Run"
)
# Works for lists too # Works for lists too
self.assertRaisesMessage( msg = "Object is of type 'list', but must be a Django Model, Manager, or QuerySet"
ValueError, with self.assertRaisesMessage(ValueError, msg):
"Object is of type 'list', but must be a Django Model, Manager, " get_list_or_404([Article], title__icontains="Run")
"or QuerySet",
get_list_or_404, [Article], title__icontains="Run"
)

View File

@ -1355,9 +1355,8 @@ class M2mThroughFieldsTests(SimpleTestCase):
class Fan(models.Model): class Fan(models.Model):
pass pass
self.assertRaisesMessage( with self.assertRaisesMessage(ValueError, 'Cannot specify through_fields without a through model'):
ValueError, 'Cannot specify through_fields without a through model', models.ManyToManyField(Fan, through_fields=('f1', 'f2'))
models.ManyToManyField, Fan, through_fields=('f1', 'f2'))
def test_invalid_order(self): def test_invalid_order(self):
""" """

View File

@ -1109,8 +1109,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
backend = smtp.EmailBackend( backend = smtp.EmailBackend(
username='not empty username', password='not empty password') username='not empty username', password='not empty password')
try: try:
self.assertRaisesMessage(SMTPException, with self.assertRaisesMessage(SMTPException, 'SMTP AUTH extension not supported by server.'):
'SMTP AUTH extension not supported by server.', backend.open) backend.open()
finally: finally:
backend.close() backend.close()
@ -1185,8 +1185,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
backend = smtp.EmailBackend() backend = smtp.EmailBackend()
self.assertTrue(backend.use_tls) self.assertTrue(backend.use_tls)
try: try:
self.assertRaisesMessage(SMTPException, with self.assertRaisesMessage(SMTPException, 'STARTTLS extension not supported by server.'):
'STARTTLS extension not supported by server.', backend.open) backend.open()
finally: finally:
backend.close() backend.close()

View File

@ -490,17 +490,12 @@ class ManyToOneTests(TestCase):
def test_values_list_exception(self): def test_values_list_exception(self):
expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s" expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s"
reporter_fields = ', '.join(sorted(f.name for f in Reporter._meta.get_fields()))
self.assertRaisesMessage(FieldError, with self.assertRaisesMessage(FieldError, expected_message % reporter_fields):
expected_message % ', '.join(sorted(f.name for f in Reporter._meta.get_fields())), Article.objects.values_list('reporter__notafield')
Article.objects.values_list, article_fields = ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields()))
'reporter__notafield') with self.assertRaisesMessage(FieldError, expected_message % article_fields):
self.assertRaisesMessage( Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list('notafield')
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'
)
def test_fk_assignment_and_related_object_cache(self): def test_fk_assignment_and_related_object_cache(self):
# Tests of ForeignKey assignment and the related-object cache (see #6886). # Tests of ForeignKey assignment and the related-object cache (see #6886).

View File

@ -47,13 +47,11 @@ class TestSaveLoad(TestCase):
PrimaryKeyUUIDModel.objects.get(pk=[]) PrimaryKeyUUIDModel.objects.get(pk=[])
def test_wrong_value(self): def test_wrong_value(self):
self.assertRaisesMessage( with self.assertRaisesMessage(ValueError, 'badly formed hexadecimal UUID string'):
ValueError, 'badly formed hexadecimal UUID string', UUIDModel.objects.get(field='not-a-uuid')
UUIDModel.objects.get, field='not-a-uuid')
self.assertRaisesMessage( with self.assertRaisesMessage(ValueError, 'badly formed hexadecimal UUID string'):
ValueError, 'badly formed hexadecimal UUID string', UUIDModel.objects.create(field='not-a-uuid')
UUIDModel.objects.create, field='not-a-uuid')
class TestMigrations(SimpleTestCase): class TestMigrations(SimpleTestCase):

View File

@ -431,16 +431,10 @@ class Queries1Tests(BaseQuerysetTest):
def test_heterogeneous_qs_combination(self): def test_heterogeneous_qs_combination(self):
# Combining querysets built on different models should behave in a well-defined # Combining querysets built on different models should behave in a well-defined
# fashion. We raise an error. # fashion. We raise an error.
self.assertRaisesMessage( with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'):
AssertionError, Author.objects.all() & Tag.objects.all()
'Cannot combine queries on two different base models.', with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'):
lambda: Author.objects.all() & Tag.objects.all() Author.objects.all() | Tag.objects.all()
)
self.assertRaisesMessage(
AssertionError,
'Cannot combine queries on two different base models.',
lambda: Author.objects.all() | Tag.objects.all()
)
def test_ticket3141(self): def test_ticket3141(self):
self.assertEqual(Author.objects.extra(select={'foo': '1'}).count(), 4) self.assertEqual(Author.objects.extra(select={'foo': '1'}).count(), 4)
@ -759,11 +753,8 @@ class Queries1Tests(BaseQuerysetTest):
[] []
) )
q.query.low_mark = 1 q.query.low_mark = 1
self.assertRaisesMessage( with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken'):
AssertionError, q.extra(select={'foo': "1"})
'Cannot change a query once a slice has been taken',
q.extra, select={'foo': "1"}
)
self.assertQuerysetEqual(q.reverse(), []) self.assertQuerysetEqual(q.reverse(), [])
self.assertQuerysetEqual(q.defer('meal'), []) self.assertQuerysetEqual(q.defer('meal'), [])
self.assertQuerysetEqual(q.only('meal'), []) self.assertQuerysetEqual(q.only('meal'), [])
@ -790,16 +781,10 @@ class Queries1Tests(BaseQuerysetTest):
) )
# Multi-valued values() and values_list() querysets should raise errors. # Multi-valued values() and values_list() querysets should raise errors.
self.assertRaisesMessage( with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'):
TypeError, Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id'))
'Cannot use multi-field values as a filter value.', with 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')) Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('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'))
)
def test_ticket9985(self): def test_ticket9985(self):
# qs.values_list(...).values(...) combinations should work. # qs.values_list(...).values(...) combinations should work.
@ -1329,11 +1314,8 @@ class Queries3Tests(BaseQuerysetTest):
def test_ticket8683(self): def test_ticket8683(self):
# An error should be raised when QuerySet.datetimes() is passed the # An error should be raised when QuerySet.datetimes() is passed the
# wrong type of field. # wrong type of field.
self.assertRaisesMessage( with self.assertRaisesMessage(AssertionError, "'name' isn't a DateTimeField."):
AssertionError, Item.objects.datetimes('name', 'month')
"'name' isn't a DateTimeField.",
Item.objects.datetimes, 'name', 'month'
)
def test_ticket22023(self): def test_ticket22023(self):
with self.assertRaisesMessage(TypeError, 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], [])
self.assertQuerysetEqual(Article.objects.all()[0:0][:10], []) self.assertQuerysetEqual(Article.objects.all()[0:0][:10], [])
self.assertEqual(Article.objects.all()[:0].count(), 0) self.assertEqual(Article.objects.all()[:0].count(), 0)
self.assertRaisesMessage( with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken.'):
AssertionError, Article.objects.all()[:0].latest('created')
'Cannot change a query once a slice has been taken.',
Article.objects.all()[:0].latest, 'created'
)
def test_empty_resultset_sql(self): def test_empty_resultset_sql(self):
# ticket #12192 # ticket #12192
@ -2528,16 +2507,10 @@ class ConditionalTests(BaseQuerysetTest):
def test_infinite_loop(self): def test_infinite_loop(self):
# If you're not careful, it's possible to introduce infinite loops via # If you're not careful, it's possible to introduce infinite loops via
# default ordering on foreign keys in a cycle. We detect that. # default ordering on foreign keys in a cycle. We detect that.
self.assertRaisesMessage( with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'):
FieldError, list(LoopX.objects.all()) # Force queryset evaluation with list()
'Infinite loop caused by ordering.', with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'):
lambda: list(LoopX.objects.all()) # Force queryset evaluation with list() list(LoopZ.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()
)
# Note that this doesn't cause an infinite loop, since the default # 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" # ordering on the Tag model is empty (and thus defaults to using "id"

View File

@ -772,11 +772,8 @@ class HostValidationTests(SimpleTestCase):
]: ]:
request = HttpRequest() request = HttpRequest()
request.META = {'HTTP_HOST': host} request.META = {'HTTP_HOST': host}
self.assertRaisesMessage( with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion % (host, host)):
SuspiciousOperation, request.get_host()
msg_suggestion % (host, host),
request.get_host
)
for domain, port in [ # Valid-looking hosts with a port number for domain, port in [ # Valid-looking hosts with a port number
('example.com', 80), ('example.com', 80),
@ -786,28 +783,19 @@ class HostValidationTests(SimpleTestCase):
host = '%s:%s' % (domain, port) host = '%s:%s' % (domain, port)
request = HttpRequest() request = HttpRequest()
request.META = {'HTTP_HOST': host} request.META = {'HTTP_HOST': host}
self.assertRaisesMessage( with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion % (host, domain)):
SuspiciousOperation, request.get_host()
msg_suggestion % (host, domain),
request.get_host
)
for host in self.poisoned_hosts: for host in self.poisoned_hosts:
request = HttpRequest() request = HttpRequest()
request.META = {'HTTP_HOST': host} request.META = {'HTTP_HOST': host}
self.assertRaisesMessage( with self.assertRaisesMessage(SuspiciousOperation, msg_invalid_host % host):
SuspiciousOperation, request.get_host()
msg_invalid_host % host,
request.get_host
)
request = HttpRequest() request = HttpRequest()
request.META = {'HTTP_HOST': "invalid_hostname.com"} request.META = {'HTTP_HOST': "invalid_hostname.com"}
self.assertRaisesMessage( with self.assertRaisesMessage(SuspiciousOperation, msg_suggestion2 % "invalid_hostname.com"):
SuspiciousOperation, request.get_host()
msg_suggestion2 % "invalid_hostname.com",
request.get_host
)
class BuildAbsoluteURITestCase(SimpleTestCase): class BuildAbsoluteURITestCase(SimpleTestCase):

View File

@ -801,7 +801,8 @@ class AssertRaisesMsgTest(SimpleTestCase):
"""assertRaisesMessage shouldn't interpret RE special chars.""" """assertRaisesMessage shouldn't interpret RE special chars."""
def func1(): def func1():
raise ValueError("[.*x+]y?") raise ValueError("[.*x+]y?")
self.assertRaisesMessage(ValueError, "[.*x+]y?", func1) with self.assertRaisesMessage(ValueError, "[.*x+]y?"):
func1()
@ignore_warnings(category=RemovedInDjango20Warning) @ignore_warnings(category=RemovedInDjango20Warning)
def test_callable_obj_param(self): def test_callable_obj_param(self):

View File

@ -252,13 +252,13 @@ class NoURLPatternsTests(SimpleTestCase):
""" """
resolver = RegexURLResolver(r'^$', settings.ROOT_URLCONF) resolver = RegexURLResolver(r'^$', settings.ROOT_URLCONF)
self.assertRaisesMessage( with self.assertRaisesMessage(
ImproperlyConfigured, ImproperlyConfigured,
"The included URLconf 'urlpatterns_reverse.no_urls' does not " "The included URLconf 'urlpatterns_reverse.no_urls' does not "
"appear to have any patterns in it. If you see valid patterns in " "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.", "the file then the issue is probably caused by a circular import."
getattr, resolver, 'url_patterns' ):
) getattr(resolver, 'url_patterns')
@override_settings(ROOT_URLCONF='urlpatterns_reverse.urls') @override_settings(ROOT_URLCONF='urlpatterns_reverse.urls')

View File

@ -108,8 +108,8 @@ class ImmutableListTests(SimpleTestCase):
d = ImmutableList(range(10)) d = ImmutableList(range(10))
# AttributeError: ImmutableList object is immutable. # AttributeError: ImmutableList object is immutable.
self.assertRaisesMessage(AttributeError, with self.assertRaisesMessage(AttributeError, 'ImmutableList object is immutable.'):
'ImmutableList object is immutable.', d.sort) d.sort()
self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)') 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) self.assertEqual(d[1], 1)
# AttributeError: Object is immutable! # AttributeError: Object is immutable!
self.assertRaisesMessage(AttributeError, with self.assertRaisesMessage(AttributeError, 'Object is immutable!'):
'Object is immutable!', d.__setitem__, 1, 'test') d.__setitem__(1, 'test')
class DictWrapperTests(SimpleTestCase): class DictWrapperTests(SimpleTestCase):