1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

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

This commit is contained in:
Hasan 2016-01-17 14:56:39 +03:30 committed by Tim Graham
parent 575706331b
commit 3d0dcd7f5a
118 changed files with 1086 additions and 760 deletions

View File

@ -850,7 +850,8 @@ class ListFiltersTests(TestCase):
""" """
modeladmin = DecadeFilterBookAdminWithFailingQueryset(Book, site) modeladmin = DecadeFilterBookAdminWithFailingQueryset(Book, site)
request = self.request_factory.get('/', {}) request = self.request_factory.get('/', {})
self.assertRaises(ZeroDivisionError, self.get_changelist, request, Book, modeladmin) with self.assertRaises(ZeroDivisionError):
self.get_changelist(request, Book, modeladmin)
def test_simplelistfilter_with_queryset_based_lookups(self): def test_simplelistfilter_with_queryset_based_lookups(self):
modeladmin = DecadeFilterBookAdminWithQuerysetBasedLookups(Book, site) modeladmin = DecadeFilterBookAdminWithQuerysetBasedLookups(Book, site)

View File

@ -36,9 +36,8 @@ class TestRegistration(SimpleTestCase):
def test_prevent_double_registration(self): def test_prevent_double_registration(self):
self.site.register(Person) self.site.register(Person)
self.assertRaises(admin.sites.AlreadyRegistered, with self.assertRaises(admin.sites.AlreadyRegistered):
self.site.register, self.site.register(Person)
Person)
def test_registration_with_star_star_options(self): def test_registration_with_star_star_options(self):
self.site.register(Person, search_fields=['name']) self.site.register(Person, search_fields=['name'])
@ -68,7 +67,8 @@ class TestRegistration(SimpleTestCase):
Exception is raised when trying to register an abstract model. Exception is raised when trying to register an abstract model.
Refs #12004. Refs #12004.
""" """
self.assertRaises(ImproperlyConfigured, self.site.register, Location) with self.assertRaises(ImproperlyConfigured):
self.site.register(Location)
def test_is_registered_model(self): def test_is_registered_model(self):
"Checks for registered models should return true." "Checks for registered models should return true."

View File

@ -221,10 +221,8 @@ class UtilsTests(SimpleTestCase):
str("article") str("article")
) )
self.assertRaises( with self.assertRaises(AttributeError):
AttributeError, label_for_field("unknown", Article)
lambda: label_for_field("unknown", Article)
)
def test_callable(obj): def test_callable(obj):
return "nothing" return "nothing"

View File

@ -376,20 +376,14 @@ class AggregationTests(TestCase):
def test_field_error(self): def test_field_error(self):
# Bad field requests in aggregates are caught and reported # Bad field requests in aggregates are caught and reported
self.assertRaises( with self.assertRaises(FieldError):
FieldError, Book.objects.all().aggregate(num_authors=Count('foo'))
lambda: Book.objects.all().aggregate(num_authors=Count('foo'))
)
self.assertRaises( with self.assertRaises(FieldError):
FieldError, Book.objects.all().annotate(num_authors=Count('foo'))
lambda: Book.objects.all().annotate(num_authors=Count('foo'))
)
self.assertRaises( with self.assertRaises(FieldError):
FieldError, Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
lambda: Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
)
def test_more(self): def test_more(self):
# Old-style count aggregations can be mixed with new-style # Old-style count aggregations can be mixed with new-style
@ -698,21 +692,20 @@ class AggregationTests(TestCase):
def test_duplicate_alias(self): def test_duplicate_alias(self):
# Regression for #11256 - duplicating a default alias raises ValueError. # Regression for #11256 - duplicating a default alias raises ValueError.
self.assertRaises( with self.assertRaises(ValueError):
ValueError, Book.objects.all().annotate(Avg('authors__age'), authors__age__avg=Avg('authors__age'))
Book.objects.all().annotate,
Avg('authors__age'), authors__age__avg=Avg('authors__age')
)
def test_field_name_conflict(self): def test_field_name_conflict(self):
# Regression for #11256 - providing an aggregate name # Regression for #11256 - providing an aggregate name
# that conflicts with a field name on the model raises ValueError # that conflicts with a field name on the model raises ValueError
self.assertRaises(ValueError, Author.objects.annotate, age=Avg('friends__age')) with self.assertRaises(ValueError):
Author.objects.annotate(age=Avg('friends__age'))
def test_m2m_name_conflict(self): def test_m2m_name_conflict(self):
# Regression for #11256 - providing an aggregate name # Regression for #11256 - providing an aggregate name
# that conflicts with an m2m name on the model raises ValueError # that conflicts with an m2m name on the model raises ValueError
self.assertRaises(ValueError, Author.objects.annotate, friends=Count('friends')) with self.assertRaises(ValueError):
Author.objects.annotate(friends=Count('friends'))
def test_values_queryset_non_conflict(self): def test_values_queryset_non_conflict(self):
# Regression for #14707 -- If you're using a values query set, some potential conflicts are avoided. # Regression for #14707 -- If you're using a values query set, some potential conflicts are avoided.
@ -739,7 +732,8 @@ class AggregationTests(TestCase):
def test_reverse_relation_name_conflict(self): def test_reverse_relation_name_conflict(self):
# Regression for #11256 - providing an aggregate name # Regression for #11256 - providing an aggregate name
# that conflicts with a reverse-related name on the model raises ValueError # that conflicts with a reverse-related name on the model raises ValueError
self.assertRaises(ValueError, Author.objects.annotate, book_contact_set=Avg('friends__age')) with self.assertRaises(ValueError):
Author.objects.annotate(book_contact_set=Avg('friends__age'))
def test_pickle(self): def test_pickle(self):
# Regression for #10197 -- Queries with aggregates can be pickled. # Regression for #10197 -- Queries with aggregates can be pickled.
@ -900,10 +894,8 @@ class AggregationTests(TestCase):
# Regression for #10766 - Shouldn't be able to reference an aggregate # Regression for #10766 - Shouldn't be able to reference an aggregate
# fields in an aggregate() call. # fields in an aggregate() call.
self.assertRaises( with self.assertRaises(FieldError):
FieldError, Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age'))
lambda: Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age'))
)
def test_empty_filter_count(self): def test_empty_filter_count(self):
self.assertEqual( self.assertEqual(

View File

@ -429,7 +429,8 @@ class NoBackendsTest(TestCase):
self.user = User.objects.create_user('test', 'test@example.com', 'test') self.user = User.objects.create_user('test', 'test@example.com', 'test')
def test_raises_exception(self): def test_raises_exception(self):
self.assertRaises(ImproperlyConfigured, self.user.has_perm, ('perm', TestObj(),)) with self.assertRaises(ImproperlyConfigured):
self.user.has_perm(('perm', TestObj()))
@override_settings(AUTHENTICATION_BACKENDS=['auth_tests.test_auth_backends.SimpleRowlevelBackend']) @override_settings(AUTHENTICATION_BACKENDS=['auth_tests.test_auth_backends.SimpleRowlevelBackend'])
@ -575,7 +576,8 @@ class TypeErrorBackendTest(TestCase):
@override_settings(AUTHENTICATION_BACKENDS=[backend]) @override_settings(AUTHENTICATION_BACKENDS=[backend])
def test_type_error_raised(self): def test_type_error_raised(self):
self.assertRaises(TypeError, authenticate, username='test', password='test') with self.assertRaises(TypeError):
authenticate(username='test', password='test')
class ImproperlyConfiguredUserModelTest(TestCase): class ImproperlyConfiguredUserModelTest(TestCase):
@ -598,7 +600,8 @@ class ImproperlyConfiguredUserModelTest(TestCase):
request = HttpRequest() request = HttpRequest()
request.session = self.client.session request.session = self.client.session
self.assertRaises(ImproperlyConfigured, get_user, request) with self.assertRaises(ImproperlyConfigured):
get_user(request)
class ImportedModelBackend(ModelBackend): class ImportedModelBackend(ModelBackend):

View File

@ -115,4 +115,5 @@ class PermissionsRequiredDecoratorTest(TestCase):
return HttpResponse() return HttpResponse()
request = self.factory.get('/rand') request = self.factory.get('/rand')
request.user = self.user request.user = self.user
self.assertRaises(PermissionDenied, a_view, request) with self.assertRaises(PermissionDenied):
a_view(request)

View File

@ -219,7 +219,8 @@ class TestUtilsHashPass(SimpleTestCase):
self.assertFalse(check_password('', encoded)) self.assertFalse(check_password('', encoded))
self.assertFalse(check_password('lètmein', encoded)) self.assertFalse(check_password('lètmein', encoded))
self.assertFalse(check_password('lètmeinz', encoded)) self.assertFalse(check_password('lètmeinz', encoded))
self.assertRaises(ValueError, identify_hasher, encoded) with self.assertRaises(ValueError):
identify_hasher(encoded)
# Assert that the unusable passwords actually contain a random part. # Assert that the unusable passwords actually contain a random part.
# This might fail one day due to a hash collision. # This might fail one day due to a hash collision.
self.assertNotEqual(encoded, make_password(None), "Random password collision?") self.assertNotEqual(encoded, make_password(None), "Random password collision?")
@ -234,7 +235,8 @@ class TestUtilsHashPass(SimpleTestCase):
def test_bad_algorithm(self): def test_bad_algorithm(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
make_password('lètmein', hasher='lolcat') make_password('lètmein', hasher='lolcat')
self.assertRaises(ValueError, identify_hasher, "lolcat$salt$hash") with self.assertRaises(ValueError):
identify_hasher('lolcat$salt$hash')
def test_bad_encoded(self): def test_bad_encoded(self):
self.assertFalse(is_password_usable('lètmein_badencoded')) self.assertFalse(is_password_usable('lètmein_badencoded'))

View File

@ -135,7 +135,8 @@ class UserPassesTestTests(TestCase):
request = self.factory.get('/rand') request = self.factory.get('/rand')
request.user = AnonymousUser() request.user = AnonymousUser()
self.assertRaises(PermissionDenied, AView.as_view(), request) with self.assertRaises(PermissionDenied):
AView.as_view()(request)
def test_raise_exception_custom_message(self): def test_raise_exception_custom_message(self):
msg = "You don't have access here" msg = "You don't have access here"
@ -248,4 +249,5 @@ class PermissionsRequiredMixinTests(TestCase):
request = self.factory.get('/rand') request = self.factory.get('/rand')
request.user = self.user request.user = self.user
self.assertRaises(PermissionDenied, AView.as_view(), request) with self.assertRaises(PermissionDenied):
AView.as_view()(request)

View File

@ -63,6 +63,5 @@ class TokenGeneratorTest(TestCase):
p0 = PasswordResetTokenGenerator() p0 = PasswordResetTokenGenerator()
# This will put a 14-digit base36 timestamp into the token, which is too large. # This will put a 14-digit base36 timestamp into the token, which is too large.
self.assertRaises(ValueError, with self.assertRaises(ValueError):
p0._make_token_with_timestamp, p0._make_token_with_timestamp(user, 175455491841851871349)
user, 175455491841851871349)

View File

@ -128,19 +128,16 @@ class SQLiteTests(TestCase):
#19360: Raise NotImplementedError when aggregating on date/time fields. #19360: Raise NotImplementedError when aggregating on date/time fields.
""" """
for aggregate in (Sum, Avg, Variance, StdDev): for aggregate in (Sum, Avg, Variance, StdDev):
self.assertRaises( with self.assertRaises(NotImplementedError):
NotImplementedError, models.Item.objects.all().aggregate(aggregate('time'))
models.Item.objects.all().aggregate, aggregate('time')) with self.assertRaises(NotImplementedError):
self.assertRaises( models.Item.objects.all().aggregate(aggregate('date'))
NotImplementedError, with self.assertRaises(NotImplementedError):
models.Item.objects.all().aggregate, aggregate('date')) models.Item.objects.all().aggregate(aggregate('last_modified'))
self.assertRaises( with self.assertRaises(NotImplementedError):
NotImplementedError, models.Item.objects.all().aggregate(
models.Item.objects.all().aggregate, aggregate('last_modified')) **{'complex': aggregate('last_modified') + aggregate('last_modified')}
self.assertRaises( )
NotImplementedError,
models.Item.objects.all().aggregate,
**{'complex': aggregate('last_modified') + aggregate('last_modified')})
def test_memory_db_test_name(self): def test_memory_db_test_name(self):
""" """
@ -449,8 +446,10 @@ class ParameterHandlingTest(TestCase):
connection.ops.quote_name('root'), connection.ops.quote_name('root'),
connection.ops.quote_name('square') connection.ops.quote_name('square')
)) ))
self.assertRaises(Exception, cursor.executemany, query, [(1, 2, 3)]) with self.assertRaises(Exception):
self.assertRaises(Exception, cursor.executemany, query, [(1,)]) cursor.executemany(query, [(1, 2, 3)])
with self.assertRaises(Exception):
cursor.executemany(query, [(1,)])
# Unfortunately, the following tests would be a good test to run on all # Unfortunately, the following tests would be a good test to run on all
@ -859,7 +858,8 @@ class FkConstraintsTests(TransactionTestCase):
a2 = models.Article(headline='This is another test', reporter=self.r, a2 = models.Article(headline='This is another test', reporter=self.r,
pub_date=datetime.datetime(2012, 8, 3), pub_date=datetime.datetime(2012, 8, 3),
reporter_proxy_id=30) reporter_proxy_id=30)
self.assertRaises(IntegrityError, a2.save) with self.assertRaises(IntegrityError):
a2.save()
def test_integrity_checks_on_update(self): def test_integrity_checks_on_update(self):
""" """
@ -887,7 +887,8 @@ class FkConstraintsTests(TransactionTestCase):
# Retrieve the second article from the DB # Retrieve the second article from the DB
a2 = models.Article.objects.get(headline='Another article') a2 = models.Article.objects.get(headline='Another article')
a2.reporter_proxy_id = 30 a2.reporter_proxy_id = 30
self.assertRaises(IntegrityError, a2.save) with self.assertRaises(IntegrityError):
a2.save()
def test_disable_constraint_checks_manually(self): def test_disable_constraint_checks_manually(self):
""" """

View File

@ -499,12 +499,8 @@ class ModelLookupTest(TestCase):
) )
# To avoid dict-ordering related errors check only one lookup # To avoid dict-ordering related errors check only one lookup
# in single assert. # in single assert.
self.assertRaises( with self.assertRaises(ObjectDoesNotExist):
ObjectDoesNotExist, Article.objects.get(pub_date__year=2005, pub_date__month=8)
Article.objects.get,
pub_date__year=2005,
pub_date__month=8,
)
six.assertRaisesRegex( six.assertRaisesRegex(
self, self,
ObjectDoesNotExist, ObjectDoesNotExist,

42
tests/cache/tests.py vendored
View File

@ -129,14 +129,18 @@ class DummyCacheTests(SimpleTestCase):
def test_incr(self): def test_incr(self):
"Dummy cache values can't be incremented" "Dummy cache values can't be incremented"
cache.set('answer', 42) cache.set('answer', 42)
self.assertRaises(ValueError, cache.incr, 'answer') with self.assertRaises(ValueError):
self.assertRaises(ValueError, cache.incr, 'does_not_exist') cache.incr('answer')
with self.assertRaises(ValueError):
cache.incr('does_not_exist')
def test_decr(self): def test_decr(self):
"Dummy cache values can't be decremented" "Dummy cache values can't be decremented"
cache.set('answer', 42) cache.set('answer', 42)
self.assertRaises(ValueError, cache.decr, 'answer') with self.assertRaises(ValueError):
self.assertRaises(ValueError, cache.decr, 'does_not_exist') cache.decr('answer')
with self.assertRaises(ValueError):
cache.decr('does_not_exist')
def test_data_types(self): def test_data_types(self):
"All data types are ignored equally by the dummy cache" "All data types are ignored equally by the dummy cache"
@ -193,14 +197,18 @@ class DummyCacheTests(SimpleTestCase):
def test_incr_version(self): def test_incr_version(self):
"Dummy cache versions can't be incremented" "Dummy cache versions can't be incremented"
cache.set('answer', 42) cache.set('answer', 42)
self.assertRaises(ValueError, cache.incr_version, 'answer') with self.assertRaises(ValueError):
self.assertRaises(ValueError, cache.incr_version, 'does_not_exist') cache.incr_version('answer')
with self.assertRaises(ValueError):
cache.incr_version('does_not_exist')
def test_decr_version(self): def test_decr_version(self):
"Dummy cache versions can't be decremented" "Dummy cache versions can't be decremented"
cache.set('answer', 42) cache.set('answer', 42)
self.assertRaises(ValueError, cache.decr_version, 'answer') with self.assertRaises(ValueError):
self.assertRaises(ValueError, cache.decr_version, 'does_not_exist') cache.decr_version('answer')
with self.assertRaises(ValueError):
cache.decr_version('does_not_exist')
def test_get_or_set(self): def test_get_or_set(self):
self.assertEqual(cache.get_or_set('mykey', 'default'), 'default') self.assertEqual(cache.get_or_set('mykey', 'default'), 'default')
@ -321,7 +329,8 @@ class BaseCacheTests(object):
self.assertEqual(cache.incr('answer', 10), 52) self.assertEqual(cache.incr('answer', 10), 52)
self.assertEqual(cache.get('answer'), 52) self.assertEqual(cache.get('answer'), 52)
self.assertEqual(cache.incr('answer', -10), 42) self.assertEqual(cache.incr('answer', -10), 42)
self.assertRaises(ValueError, cache.incr, 'does_not_exist') with self.assertRaises(ValueError):
cache.incr('does_not_exist')
def test_decr(self): def test_decr(self):
# Cache values can be decremented # Cache values can be decremented
@ -331,7 +340,8 @@ class BaseCacheTests(object):
self.assertEqual(cache.decr('answer', 10), 32) self.assertEqual(cache.decr('answer', 10), 32)
self.assertEqual(cache.get('answer'), 32) self.assertEqual(cache.get('answer'), 32)
self.assertEqual(cache.decr('answer', -10), 42) self.assertEqual(cache.decr('answer', -10), 42)
self.assertRaises(ValueError, cache.decr, 'does_not_exist') with self.assertRaises(ValueError):
cache.decr('does_not_exist')
def test_close(self): def test_close(self):
self.assertTrue(hasattr(cache, 'close')) self.assertTrue(hasattr(cache, 'close'))
@ -821,7 +831,8 @@ class BaseCacheTests(object):
self.assertIsNone(caches['v2'].get('answer2', version=2)) self.assertIsNone(caches['v2'].get('answer2', version=2))
self.assertEqual(caches['v2'].get('answer2', version=3), 42) self.assertEqual(caches['v2'].get('answer2', version=3), 42)
self.assertRaises(ValueError, cache.incr_version, 'does_not_exist') with self.assertRaises(ValueError):
cache.incr_version('does_not_exist')
def test_decr_version(self): def test_decr_version(self):
cache.set('answer', 42, version=2) cache.set('answer', 42, version=2)
@ -844,7 +855,8 @@ class BaseCacheTests(object):
self.assertEqual(caches['v2'].get('answer2', version=1), 42) self.assertEqual(caches['v2'].get('answer2', version=1), 42)
self.assertIsNone(caches['v2'].get('answer2', version=2)) self.assertIsNone(caches['v2'].get('answer2', version=2))
self.assertRaises(ValueError, cache.decr_version, 'does_not_exist', version=2) with self.assertRaises(ValueError):
cache.decr_version('does_not_exist', version=2)
def test_custom_key_func(self): def test_custom_key_func(self):
# Two caches with different key functions aren't visible to each other # Two caches with different key functions aren't visible to each other
@ -1138,9 +1150,11 @@ class MemcachedCacheTests(BaseCacheTests, TestCase):
that a generic exception of some kind is raised. that a generic exception of some kind is raised.
""" """
# memcached does not allow whitespace or control characters in keys # memcached does not allow whitespace or control characters in keys
self.assertRaises(Exception, cache.set, 'key with spaces', 'value') with self.assertRaises(Exception):
cache.set('key with spaces', 'value')
# memcached limits key length to 250 # memcached limits key length to 250
self.assertRaises(Exception, cache.set, 'a' * 251, 'value') with self.assertRaises(Exception):
cache.set('a' * 251, 'value')
# Explicitly display a skipped test if no configured cache uses MemcachedCache # Explicitly display a skipped test if no configured cache uses MemcachedCache
@unittest.skipUnless( @unittest.skipUnless(

View File

@ -161,7 +161,8 @@ class CheckCommandTests(SimpleTestCase):
@override_system_checks([simple_system_check, tagged_system_check]) @override_system_checks([simple_system_check, tagged_system_check])
def test_invalid_tag(self): def test_invalid_tag(self):
self.assertRaises(CommandError, call_command, 'check', tags=['missingtag']) with self.assertRaises(CommandError):
call_command('check', tags=['missingtag'])
@override_system_checks([simple_system_check]) @override_system_checks([simple_system_check])
def test_list_tags_empty(self): def test_list_tags_empty(self):

View File

@ -208,7 +208,8 @@ class ContentTypesTests(TestCase):
user_ct = ContentType.objects.get_for_model(FooWithoutUrl) user_ct = ContentType.objects.get_for_model(FooWithoutUrl)
obj = FooWithoutUrl.objects.create(name="john") obj = FooWithoutUrl.objects.create(name="john")
self.assertRaises(Http404, shortcut, request, user_ct.id, obj.id) with self.assertRaises(Http404):
shortcut(request, user_ct.id, obj.id)
def test_shortcut_view_with_broken_get_absolute_url(self): def test_shortcut_view_with_broken_get_absolute_url(self):
""" """
@ -224,7 +225,8 @@ class ContentTypesTests(TestCase):
user_ct = ContentType.objects.get_for_model(FooWithBrokenAbsoluteUrl) user_ct = ContentType.objects.get_for_model(FooWithBrokenAbsoluteUrl)
obj = FooWithBrokenAbsoluteUrl.objects.create(name="john") obj = FooWithBrokenAbsoluteUrl.objects.create(name="john")
self.assertRaises(AttributeError, shortcut, request, user_ct.id, obj.id) with self.assertRaises(AttributeError):
shortcut(request, user_ct.id, obj.id)
def test_missing_model(self): def test_missing_model(self):
""" """

View File

@ -40,10 +40,8 @@ class CustomColumnsTests(TestCase):
) )
def test_field_error(self): def test_field_error(self):
self.assertRaises( with self.assertRaises(FieldError):
FieldError, Author.objects.filter(firstname__exact="John")
lambda: Author.objects.filter(firstname__exact="John")
)
def test_attribute_error(self): def test_attribute_error(self):
with self.assertRaises(AttributeError): with self.assertRaises(AttributeError):

View File

@ -115,7 +115,8 @@ class CustomManagerTests(TestCase):
The default manager, "objects", doesn't exist, because a custom one The default manager, "objects", doesn't exist, because a custom one
was provided. was provided.
""" """
self.assertRaises(AttributeError, lambda: Book.objects) with self.assertRaises(AttributeError):
Book.objects
def test_filtering(self): def test_filtering(self):
""" """

View File

@ -131,10 +131,8 @@ class BasicCustomPKTests(TestCase):
self.assertEqual(Employee.objects.get(pk=123), self.dan) self.assertEqual(Employee.objects.get(pk=123), self.dan)
self.assertEqual(Employee.objects.get(pk=456), self.fran) self.assertEqual(Employee.objects.get(pk=456), self.fran)
self.assertRaises( with self.assertRaises(Employee.DoesNotExist):
Employee.DoesNotExist, Employee.objects.get(pk=42)
lambda: Employee.objects.get(pk=42)
)
# Use the name of the primary key, rather than pk. # Use the name of the primary key, rather than pk.
self.assertEqual(Employee.objects.get(employee_code=123), self.dan) self.assertEqual(Employee.objects.get(employee_code=123), self.dan)
@ -151,7 +149,8 @@ class BasicCustomPKTests(TestCase):
# Or we can use the real attribute name for the primary key: # Or we can use the real attribute name for the primary key:
self.assertEqual(e.employee_code, 123) self.assertEqual(e.employee_code, 123)
self.assertRaises(AttributeError, lambda: e.id) with self.assertRaises(AttributeError):
e.id
def test_in_bulk(self): def test_in_bulk(self):
""" """

View File

@ -82,8 +82,9 @@ class DataTypesTestCase(TestCase):
an error if given a timezone-aware datetime object.""" an error if given a timezone-aware datetime object."""
dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=utc) dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=utc)
d = Donut(name='Bear claw', consumed_at=dt) d = Donut(name='Bear claw', consumed_at=dt)
self.assertRaises(ValueError, d.save) # MySQL backend does not support timezone-aware datetimes.
# ValueError: MySQL backend does not support timezone-aware datetimes. with self.assertRaises(ValueError):
d.save()
def test_datefield_auto_now_add(self): def test_datefield_auto_now_add(self):
"""Regression test for #10970, auto_now_add for DateField should store """Regression test for #10970, auto_now_add for DateField should store

View File

@ -87,10 +87,8 @@ class DatesTests(TestCase):
) )
def test_dates_fails_when_no_arguments_are_provided(self): def test_dates_fails_when_no_arguments_are_provided(self):
self.assertRaises( with self.assertRaises(TypeError):
TypeError, Article.objects.dates()
Article.objects.dates,
)
def test_dates_fails_when_given_invalid_field_argument(self): def test_dates_fails_when_given_invalid_field_argument(self):
six.assertRaisesRegex( six.assertRaisesRegex(

View File

@ -63,7 +63,8 @@ class OnDeleteTests(TestCase):
def test_protect(self): def test_protect(self):
a = create_a('protect') a = create_a('protect')
self.assertRaises(IntegrityError, a.protect.delete) with self.assertRaises(IntegrityError):
a.protect.delete()
def test_do_nothing(self): def test_do_nothing(self):
# Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model, # Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model,

View File

@ -294,12 +294,14 @@ class BasicExpressionsTests(TestCase):
def test(): def test():
test_gmbh.point_of_contact = F("ceo") test_gmbh.point_of_contact = F("ceo")
self.assertRaises(ValueError, test) with self.assertRaises(ValueError):
test()
test_gmbh.point_of_contact = test_gmbh.ceo test_gmbh.point_of_contact = test_gmbh.ceo
test_gmbh.save() test_gmbh.save()
test_gmbh.name = F("ceo__last_name") test_gmbh.name = F("ceo__last_name")
self.assertRaises(FieldError, test_gmbh.save) with self.assertRaises(FieldError):
test_gmbh.save()
def test_object_update_unsaved_objects(self): def test_object_update_unsaved_objects(self):
# F expressions cannot be used to update attributes on objects which do # F expressions cannot be used to update attributes on objects which do

View File

@ -52,8 +52,8 @@ class GetStorageClassTests(SimpleTestCase):
""" """
get_storage_class raises an error if the requested class don't exist. get_storage_class raises an error if the requested class don't exist.
""" """
self.assertRaises(ImportError, get_storage_class, with self.assertRaises(ImportError):
'django.core.files.storage.NonExistingStorage') get_storage_class('django.core.files.storage.NonExistingStorage')
def test_get_nonexisting_storage_module(self): def test_get_nonexisting_storage_module(self):
""" """
@ -256,7 +256,8 @@ class FileStorageTests(SimpleTestCase):
"""/test_media_url/a/b/c.file""") """/test_media_url/a/b/c.file""")
self.storage.base_url = None self.storage.base_url = None
self.assertRaises(ValueError, self.storage.url, 'test.file') with self.assertRaises(ValueError):
self.storage.url('test.file')
# #22717: missing ending slash in base_url should be auto-corrected # #22717: missing ending slash in base_url should be auto-corrected
storage = self.storage_class(location=self.temp_dir, storage = self.storage_class(location=self.temp_dir,
@ -292,8 +293,10 @@ class FileStorageTests(SimpleTestCase):
File storage prevents directory traversal (files can only be accessed if File storage prevents directory traversal (files can only be accessed if
they're below the storage location). they're below the storage location).
""" """
self.assertRaises(SuspiciousOperation, self.storage.exists, '..') with self.assertRaises(SuspiciousOperation):
self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd') self.storage.exists('..')
with self.assertRaises(SuspiciousOperation):
self.storage.exists('/etc/passwd')
def test_file_storage_preserves_filename_case(self): def test_file_storage_preserves_filename_case(self):
"""The storage backend should preserve case of filenames.""" """The storage backend should preserve case of filenames."""
@ -342,8 +345,8 @@ class FileStorageTests(SimpleTestCase):
self.assertEqual(f.read(), b'saved with race') self.assertEqual(f.read(), b'saved with race')
# Check that OSErrors aside from EEXIST are still raised. # Check that OSErrors aside from EEXIST are still raised.
self.assertRaises(OSError, with self.assertRaises(OSError):
self.storage.save, 'error/test.file', ContentFile('not saved')) self.storage.save('error/test.file', ContentFile('not saved'))
finally: finally:
os.makedirs = real_makedirs os.makedirs = real_makedirs
@ -379,7 +382,8 @@ class FileStorageTests(SimpleTestCase):
# Check that OSErrors aside from ENOENT are still raised. # Check that OSErrors aside from ENOENT are still raised.
self.storage.save('error.file', ContentFile('delete with error')) self.storage.save('error.file', ContentFile('delete with error'))
self.assertRaises(OSError, self.storage.delete, 'error.file') with self.assertRaises(OSError):
self.storage.delete('error.file')
finally: finally:
os.remove = real_remove os.remove = real_remove
@ -491,7 +495,8 @@ class FileFieldStorageTests(TestCase):
# An object without a file has limited functionality. # An object without a file has limited functionality.
obj1 = Storage() obj1 = Storage()
self.assertEqual(obj1.normal.name, "") self.assertEqual(obj1.normal.name, "")
self.assertRaises(ValueError, lambda: obj1.normal.size) with self.assertRaises(ValueError):
obj1.normal.size
# Saving a file enables full functionality. # Saving a file enables full functionality.
obj1.normal.save("django_test.txt", ContentFile("content")) obj1.normal.save("django_test.txt", ContentFile("content"))

View File

@ -376,12 +376,8 @@ class FileUploadTests(TestCase):
file.seek(0) file.seek(0)
# AttributeError: You cannot alter upload handlers after the upload has been processed. # AttributeError: You cannot alter upload handlers after the upload has been processed.
self.assertRaises( with self.assertRaises(AttributeError):
AttributeError, self.client.post('/quota/broken/', {'f': file})
self.client.post,
'/quota/broken/',
{'f': file}
)
def test_fileupload_getlist(self): def test_fileupload_getlist(self):
file = tempfile.NamedTemporaryFile file = tempfile.NamedTemporaryFile

View File

@ -287,7 +287,8 @@ class FileMoveSafeTests(unittest.TestCase):
handle_b, self.file_b = tempfile.mkstemp() handle_b, self.file_b = tempfile.mkstemp()
# file_move_safe should raise an IOError exception if destination file exists and allow_overwrite is False # file_move_safe should raise an IOError exception if destination file exists and allow_overwrite is False
self.assertRaises(IOError, lambda: file_move_safe(self.file_a, self.file_b, allow_overwrite=False)) with self.assertRaises(IOError):
file_move_safe(self.file_a, self.file_b, allow_overwrite=False)
# should allow it and continue on if allow_overwrite is True # should allow it and continue on if allow_overwrite is True
self.assertIsNone(file_move_safe(self.file_a, self.file_b, allow_overwrite=True)) self.assertIsNone(file_move_safe(self.file_a, self.file_b, allow_overwrite=True))

View File

@ -144,17 +144,17 @@ class FlatpageTemplateTagTests(TestCase):
def render(t): def render(t):
return Template(t).render(Context()) return Template(t).render(Context())
self.assertRaises(TemplateSyntaxError, render, with self.assertRaises(TemplateSyntaxError):
"{% load flatpages %}{% get_flatpages %}") render("{% load flatpages %}{% get_flatpages %}")
self.assertRaises(TemplateSyntaxError, render, with self.assertRaises(TemplateSyntaxError):
"{% load flatpages %}{% get_flatpages as %}") render("{% load flatpages %}{% get_flatpages as %}")
self.assertRaises(TemplateSyntaxError, render, with self.assertRaises(TemplateSyntaxError):
"{% load flatpages %}{% get_flatpages cheesecake flatpages %}") render("{% load flatpages %}{% get_flatpages cheesecake flatpages %}")
self.assertRaises(TemplateSyntaxError, render, with self.assertRaises(TemplateSyntaxError):
"{% load flatpages %}{% get_flatpages as flatpages asdf %}") render("{% load flatpages %}{% get_flatpages as flatpages asdf %}")
self.assertRaises(TemplateSyntaxError, render, with self.assertRaises(TemplateSyntaxError):
"{% load flatpages %}{% get_flatpages cheesecake user as flatpages %}") render("{% load flatpages %}{% get_flatpages cheesecake user as flatpages %}")
self.assertRaises(TemplateSyntaxError, render, with self.assertRaises(TemplateSyntaxError):
"{% load flatpages %}{% get_flatpages for user as flatpages asdf %}") render("{% load flatpages %}{% get_flatpages for user as flatpages asdf %}")
self.assertRaises(TemplateSyntaxError, render, with self.assertRaises(TemplateSyntaxError):
"{% load flatpages %}{% get_flatpages prefix for user as flatpages asdf %}") render("{% load flatpages %}{% get_flatpages prefix for user as flatpages asdf %}")

View File

@ -57,7 +57,8 @@ class MultiColumnFKTests(TestCase):
membership = Membership.objects.create( membership = Membership.objects.create(
membership_country_id=self.usa.id, person_id=self.jane.id, group_id=self.cia.id) membership_country_id=self.usa.id, person_id=self.jane.id, group_id=self.cia.id)
self.assertRaises(Person.DoesNotExist, getattr, membership, 'person') with self.assertRaises(Person.DoesNotExist):
getattr(membership, 'person')
def test_reverse_query_returns_correct_result(self): def test_reverse_query_returns_correct_result(self):
# Creating a valid membership because it has the same country has the person # Creating a valid membership because it has the same country has the person

View File

@ -149,9 +149,12 @@ class FieldsTests(SimpleTestCase):
Ensure that setting min_length or max_length to something that is not a Ensure that setting min_length or max_length to something that is not a
number returns an exception. number returns an exception.
""" """
self.assertRaises(ValueError, CharField, min_length='a') with self.assertRaises(ValueError):
self.assertRaises(ValueError, CharField, max_length='a') CharField(min_length='a')
self.assertRaises(ValueError, CharField, 'a') with self.assertRaises(ValueError):
CharField(max_length='a')
with self.assertRaises(ValueError):
CharField('a')
def test_charfield_widget_attrs(self): def test_charfield_widget_attrs(self):
""" """
@ -1654,8 +1657,10 @@ class FieldsTests(SimpleTestCase):
# GenericIPAddressField ####################################################### # GenericIPAddressField #######################################################
def test_generic_ipaddress_invalid_arguments(self): def test_generic_ipaddress_invalid_arguments(self):
self.assertRaises(ValueError, GenericIPAddressField, protocol="hamster") with self.assertRaises(ValueError):
self.assertRaises(ValueError, GenericIPAddressField, protocol="ipv4", unpack_ipv4=True) GenericIPAddressField(protocol='hamster')
with self.assertRaises(ValueError):
GenericIPAddressField(protocol='ipv4', unpack_ipv4=True)
def test_generic_ipaddress_as_generic(self): def test_generic_ipaddress_as_generic(self):
# The edge cases of the IPv6 validation code are not deeply tested # The edge cases of the IPv6 validation code are not deeply tested

View File

@ -3227,7 +3227,8 @@ Good luck picking a username that doesn&#39;t already exist.</p>
""" """
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'}) p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
repr(p) repr(p)
self.assertRaises(AttributeError, lambda: p.cleaned_data) with self.assertRaises(AttributeError):
p.cleaned_data
self.assertFalse(p.is_valid()) self.assertFalse(p.is_valid())
self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'}) self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'})

View File

@ -19,7 +19,8 @@ class LocalizedTimeTests(SimpleTestCase):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
@ -45,7 +46,8 @@ class LocalizedTimeTests(SimpleTestCase):
"Localized TimeFields act as unlocalized widgets" "Localized TimeFields act as unlocalized widgets"
f = forms.TimeField(localize=True) f = forms.TimeField(localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
@ -67,8 +69,10 @@ class LocalizedTimeTests(SimpleTestCase):
"TimeFields with manually specified input formats can accept those formats" "TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
@ -90,8 +94,10 @@ class LocalizedTimeTests(SimpleTestCase):
"Localized TimeFields with manually specified input formats can accept those formats" "Localized TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
@ -116,7 +122,8 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
@ -138,7 +145,8 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"Localized TimeFields act as unlocalized widgets" "Localized TimeFields act as unlocalized widgets"
f = forms.TimeField(localize=True) f = forms.TimeField(localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
@ -160,8 +168,10 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"TimeFields with manually specified input formats can accept those formats" "TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"]) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
@ -183,8 +193,10 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
"Localized TimeFields with manually specified input formats can accept those formats" "Localized TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True) f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') f.clean('1:30:05 PM')
with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
@ -208,7 +220,8 @@ class SimpleTimeFormatTests(SimpleTestCase):
"TimeFields can parse dates in the default format" "TimeFields can parse dates in the default format"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
@ -230,7 +243,8 @@ class SimpleTimeFormatTests(SimpleTestCase):
"Localized TimeFields in a non-localized environment act as unlocalized widgets" "Localized TimeFields in a non-localized environment act as unlocalized widgets"
f = forms.TimeField() f = forms.TimeField()
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
@ -252,7 +266,8 @@ class SimpleTimeFormatTests(SimpleTestCase):
"TimeFields with manually specified input formats can accept those formats" "TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"]) f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"])
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
@ -274,7 +289,8 @@ class SimpleTimeFormatTests(SimpleTestCase):
"Localized TimeFields with manually specified input formats can accept those formats" "Localized TimeFields with manually specified input formats can accept those formats"
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True) f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True)
# Parse a time in an unaccepted format; get an error # Parse a time in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('13:30:05')
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
@ -305,7 +321,8 @@ class LocalizedDateTests(SimpleTestCase):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') with self.assertRaises(forms.ValidationError):
f.clean('21/12/2010')
# ISO formats are accepted, even if not specified in formats.py # ISO formats are accepted, even if not specified in formats.py
self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21)) self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21))
@ -330,7 +347,8 @@ class LocalizedDateTests(SimpleTestCase):
"Localized DateFields act as unlocalized widgets" "Localized DateFields act as unlocalized widgets"
f = forms.DateField(localize=True) f = forms.DateField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') with self.assertRaises(forms.ValidationError):
f.clean('21/12/2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
@ -352,9 +370,12 @@ class LocalizedDateTests(SimpleTestCase):
"DateFields with manually specified input formats can accept those formats" "DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') f.clean('2010-12-21')
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('21/12/2010')
with self.assertRaises(forms.ValidationError):
f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
@ -376,9 +397,12 @@ class LocalizedDateTests(SimpleTestCase):
"Localized DateFields with manually specified input formats can accept those formats" "Localized DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') f.clean('2010-12-21')
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('21/12/2010')
with self.assertRaises(forms.ValidationError):
f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
@ -403,7 +427,8 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
@ -425,7 +450,8 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"Localized DateFields act as unlocalized widgets" "Localized DateFields act as unlocalized widgets"
f = forms.DateField(localize=True) f = forms.DateField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
@ -447,8 +473,10 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"DateFields with manually specified input formats can accept those formats" "DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"]) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') f.clean('21.12.2010')
with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
@ -470,8 +498,10 @@ class CustomDateInputFormatsTests(SimpleTestCase):
"Localized DateFields with manually specified input formats can accept those formats" "Localized DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True) f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') f.clean('21.12.2010')
with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
@ -495,7 +525,8 @@ class SimpleDateFormatTests(SimpleTestCase):
"DateFields can parse dates in the default format" "DateFields can parse dates in the default format"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21') result = f.clean('2010-12-21')
@ -517,7 +548,8 @@ class SimpleDateFormatTests(SimpleTestCase):
"Localized DateFields in a non-localized environment act as unlocalized widgets" "Localized DateFields in a non-localized environment act as unlocalized widgets"
f = forms.DateField() f = forms.DateField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21') result = f.clean('2010-12-21')
@ -539,7 +571,8 @@ class SimpleDateFormatTests(SimpleTestCase):
"DateFields with manually specified input formats can accept those formats" "DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"]) f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
@ -561,7 +594,8 @@ class SimpleDateFormatTests(SimpleTestCase):
"Localized DateFields with manually specified input formats can accept those formats" "Localized DateFields with manually specified input formats can accept those formats"
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True) f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
@ -592,7 +626,8 @@ class LocalizedDateTimeTests(SimpleTestCase):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM 21/12/2010')
# ISO formats are accepted, even if not specified in formats.py # ISO formats are accepted, even if not specified in formats.py
self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010, 12, 21, 13, 30, 5)) self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010, 12, 21, 13, 30, 5))
@ -617,7 +652,8 @@ class LocalizedDateTimeTests(SimpleTestCase):
"Localized DateTimeFields act as unlocalized widgets" "Localized DateTimeFields act as unlocalized widgets"
f = forms.DateTimeField(localize=True) f = forms.DateTimeField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM 21/12/2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010 13:30:05') result = f.clean('21.12.2010 13:30:05')
@ -639,9 +675,12 @@ class LocalizedDateTimeTests(SimpleTestCase):
"DateTimeFields with manually specified input formats can accept those formats" "DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"]) f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05 13:30:05') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') f.clean('2010-12-21 13:30:05 13:30:05')
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM 21/12/2010')
with self.assertRaises(forms.ValidationError):
f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('13.30.05 12.21.2010') result = f.clean('13.30.05 12.21.2010')
@ -663,9 +702,12 @@ class LocalizedDateTimeTests(SimpleTestCase):
"Localized DateTimeFields with manually specified input formats can accept those formats" "Localized DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True) f = forms.DateTimeField(input_formats=["%H.%M.%S %m.%d.%Y", "%H.%M %m-%d-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') f.clean('2010-12-21 13:30:05')
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('1:30:05 PM 21/12/2010')
with self.assertRaises(forms.ValidationError):
f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('13.30.05 12.21.2010') result = f.clean('13.30.05 12.21.2010')
@ -690,7 +732,8 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21/12/2010') result = f.clean('1:30:05 PM 21/12/2010')
@ -712,7 +755,8 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"Localized DateTimeFields act as unlocalized widgets" "Localized DateTimeFields act as unlocalized widgets"
f = forms.DateTimeField(localize=True) f = forms.DateTimeField(localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21/12/2010') result = f.clean('1:30:05 PM 21/12/2010')
@ -734,8 +778,10 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"DateTimeFields with manually specified input formats can accept those formats" "DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"]) f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') f.clean('13:30:05 21.12.2010')
with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010 13:30:05') result = f.clean('12.21.2010 13:30:05')
@ -757,8 +803,10 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
"Localized DateTimeFields with manually specified input formats can accept those formats" "Localized DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True) f = forms.DateTimeField(input_formats=["%m.%d.%Y %H:%M:%S", "%m-%d-%Y %H:%M"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError):
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') f.clean('13:30:05 21.12.2010')
with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010 13:30:05') result = f.clean('12.21.2010 13:30:05')
@ -782,7 +830,8 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"DateTimeFields can parse dates in the default format" "DateTimeFields can parse dates in the default format"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21 13:30:05') result = f.clean('2010-12-21 13:30:05')
@ -804,7 +853,8 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"Localized DateTimeFields in a non-localized environment act as unlocalized widgets" "Localized DateTimeFields in a non-localized environment act as unlocalized widgets"
f = forms.DateTimeField() f = forms.DateTimeField()
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010') with self.assertRaises(forms.ValidationError):
f.clean('13:30:05 21.12.2010')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21 13:30:05') result = f.clean('2010-12-21 13:30:05')
@ -826,7 +876,8 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"DateTimeFields with manually specified input formats can accept those formats" "DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"]) f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"])
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21.12.2010') result = f.clean('1:30:05 PM 21.12.2010')
@ -848,7 +899,8 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
"Localized DateTimeFields with manually specified input formats can accept those formats" "Localized DateTimeFields with manually specified input formats can accept those formats"
f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True) f = forms.DateTimeField(input_formats=["%I:%M:%S %p %d.%m.%Y", "%I:%M %p %d-%m-%Y"], localize=True)
# Parse a date in an unaccepted format; get an error # Parse a date in an unaccepted format; get an error
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05') with self.assertRaises(forms.ValidationError):
f.clean('2010-12-21 13:30:05')
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21.12.2010') result = f.clean('1:30:05 PM 21.12.2010')

View File

@ -45,12 +45,9 @@ class TestFieldWithValidators(TestCase):
'string': '2 is not correct', 'string': '2 is not correct',
'ignore_case_string': "IgnORE Case strIng", 'ignore_case_string': "IgnORE Case strIng",
}) })
self.assertRaises(ValidationError, form.fields['full_name'].clean, 'not int nor mail') with self.assertRaises(ValidationError) as e:
try:
form.fields['full_name'].clean('not int nor mail') form.fields['full_name'].clean('not int nor mail')
except ValidationError as e: self.assertEqual(2, len(e.exception.messages))
self.assertEqual(2, len(e.messages))
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(form.errors['string'], ["Letters only."]) self.assertEqual(form.errors['string'], ["Letters only."])

View File

@ -251,7 +251,8 @@ class RelatedModelFormTests(SimpleTestCase):
model = A model = A
fields = '__all__' fields = '__all__'
self.assertRaises(ValueError, ModelFormMetaclass, str('Form'), (ModelForm,), {'Meta': Meta}) with self.assertRaises(ValueError):
ModelFormMetaclass(str('Form'), (ModelForm,), {'Meta': Meta})
class B(models.Model): class B(models.Model):
pass pass

View File

@ -111,7 +111,8 @@ class GenericRelationTests(TestCase):
# Fails with another, ORM-level error # Fails with another, ORM-level error
dev1 = Developer(name='Joe') dev1 = Developer(name='Joe')
note = Note(note='Deserves promotion', content_object=dev1) note = Note(note='Deserves promotion', content_object=dev1)
self.assertRaises(IntegrityError, note.save) with self.assertRaises(IntegrityError):
note.save()
def test_target_model_len_zero(self): def test_target_model_len_zero(self):
"""Test for #13085 -- __len__() returns 0""" """Test for #13085 -- __len__() returns 0"""

View File

@ -145,12 +145,14 @@ class ViewTest(unittest.TestCase):
# Check each of the allowed method names # Check each of the allowed method names
for method in SimpleView.http_method_names: for method in SimpleView.http_method_names:
kwargs = dict(((method, "value"),)) kwargs = dict(((method, "value"),))
self.assertRaises(TypeError, SimpleView.as_view, **kwargs) with self.assertRaises(TypeError):
SimpleView.as_view(**kwargs)
# Check the case view argument is ok if predefined on the class... # Check the case view argument is ok if predefined on the class...
CustomizableView.as_view(parameter="value") CustomizableView.as_view(parameter="value")
# ...but raises errors otherwise. # ...but raises errors otherwise.
self.assertRaises(TypeError, CustomizableView.as_view, foobar="value") with self.assertRaises(TypeError):
CustomizableView.as_view(foobar="value")
def test_calling_more_than_once(self): def test_calling_more_than_once(self):
""" """
@ -280,7 +282,8 @@ class TemplateViewTest(SimpleTestCase):
""" """
A template view must provide a template name. A template view must provide a template name.
""" """
self.assertRaises(ImproperlyConfigured, self.client.get, '/template/no_template/') with self.assertRaises(ImproperlyConfigured):
self.client.get('/template/no_template/')
@require_jinja2 @require_jinja2
def test_template_engine(self): def test_template_engine(self):
@ -527,4 +530,5 @@ class SingleObjectTemplateResponseMixinTest(unittest.TestCase):
TemplateDoesNotExist. TemplateDoesNotExist.
""" """
view = views.TemplateResponseWithoutTemplate() view = views.TemplateResponseWithoutTemplate()
self.assertRaises(ImproperlyConfigured, view.get_template_names) with self.assertRaises(ImproperlyConfigured):
view.get_template_names()

View File

@ -82,7 +82,8 @@ class ArchiveIndexViewTests(TestDataMixin, TestCase):
self.assertTemplateUsed(res, 'generic_views/book_detail.html') self.assertTemplateUsed(res, 'generic_views/book_detail.html')
def test_archive_view_invalid(self): def test_archive_view_invalid(self):
self.assertRaises(ImproperlyConfigured, self.client.get, '/dates/books/invalid/') with self.assertRaises(ImproperlyConfigured):
self.client.get('/dates/books/invalid/')
def test_archive_view_by_month(self): def test_archive_view_by_month(self):
res = self.client.get('/dates/books/by_month/') res = self.client.get('/dates/books/by_month/')
@ -664,7 +665,8 @@ class DateDetailViewTests(TestDataMixin, TestCase):
self.assertTemplateUsed(res, 'generic_views/book_detail.html') self.assertTemplateUsed(res, 'generic_views/book_detail.html')
def test_invalid_url(self): def test_invalid_url(self):
self.assertRaises(AttributeError, self.client.get, "/dates/books/2008/oct/01/nopk/") with self.assertRaises(AttributeError):
self.client.get("/dates/books/2008/oct/01/nopk/")
def test_get_object_custom_queryset(self): def test_get_object_custom_queryset(self):
""" """

View File

@ -49,7 +49,8 @@ class DetailViewTest(TestCase):
self.assertEqual(res.status_code, 404) self.assertEqual(res.status_code, 404)
def test_detail_object_does_not_exist(self): def test_detail_object_does_not_exist(self):
self.assertRaises(ObjectDoesNotExist, self.client.get, '/detail/doesnotexist/1/') with self.assertRaises(ObjectDoesNotExist):
self.client.get('/detail/doesnotexist/1/')
def test_detail_by_custom_pk(self): def test_detail_by_custom_pk(self):
res = self.client.get('/detail/author/bycustompk/%s/' % self.author1.pk) res = self.client.get('/detail/author/bycustompk/%s/' % self.author1.pk)
@ -173,10 +174,12 @@ class DetailViewTest(TestCase):
self.assertEqual(form_context_data['author'], self.author1) self.assertEqual(form_context_data['author'], self.author1)
def test_invalid_url(self): def test_invalid_url(self):
self.assertRaises(AttributeError, self.client.get, '/detail/author/invalid/url/') with self.assertRaises(AttributeError):
self.client.get('/detail/author/invalid/url/')
def test_invalid_queryset(self): def test_invalid_queryset(self):
self.assertRaises(ImproperlyConfigured, self.client.get, '/detail/author/invalid/qs/') with self.assertRaises(ImproperlyConfigured):
self.client.get('/detail/author/invalid/qs/')
def test_non_model_object_with_meta(self): def test_non_model_object_with_meta(self):
res = self.client.get('/detail/nonmodel/1/') res = self.client.get('/detail/nonmodel/1/')

View File

@ -204,7 +204,8 @@ class ListViewTests(TestCase):
self.assertTemplateUsed(res, 'generic_views/author_list.html') self.assertTemplateUsed(res, 'generic_views/author_list.html')
def test_missing_items(self): def test_missing_items(self):
self.assertRaises(ImproperlyConfigured, self.client.get, '/list/authors/invalid/') with self.assertRaises(ImproperlyConfigured):
self.client.get('/list/authors/invalid/')
def test_paginated_list_view_does_not_load_entire_table(self): def test_paginated_list_view_does_not_load_entire_table(self):
# Regression test for #17535 # Regression test for #17535

View File

@ -17,7 +17,8 @@ class EarliestOrLatestTests(TestCase):
def test_earliest(self): def test_earliest(self):
# Because no Articles exist yet, earliest() raises ArticleDoesNotExist. # Because no Articles exist yet, earliest() raises ArticleDoesNotExist.
self.assertRaises(Article.DoesNotExist, Article.objects.earliest) with self.assertRaises(Article.DoesNotExist):
Article.objects.earliest()
a1 = Article.objects.create( a1 = Article.objects.create(
headline="Article 1", pub_date=datetime(2005, 7, 26), headline="Article 1", pub_date=datetime(2005, 7, 26),
@ -66,7 +67,8 @@ class EarliestOrLatestTests(TestCase):
def test_latest(self): def test_latest(self):
# Because no Articles exist yet, latest() raises ArticleDoesNotExist. # Because no Articles exist yet, latest() raises ArticleDoesNotExist.
self.assertRaises(Article.DoesNotExist, Article.objects.latest) with self.assertRaises(Article.DoesNotExist):
Article.objects.latest()
a1 = Article.objects.create( a1 = Article.objects.create(
headline="Article 1", pub_date=datetime(2005, 7, 26), headline="Article 1", pub_date=datetime(2005, 7, 26),
@ -119,7 +121,8 @@ class EarliestOrLatestTests(TestCase):
# "get_latest_by" set -- just pass in the field name manually. # "get_latest_by" set -- just pass in the field name manually.
Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1)) Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1))
p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3)) p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3))
self.assertRaises(AssertionError, Person.objects.latest) with self.assertRaises(AssertionError):
Person.objects.latest()
self.assertEqual(Person.objects.latest("birthday"), p2) self.assertEqual(Person.objects.latest("birthday"), p2)
@ -164,9 +167,12 @@ class TestFirstLast(TestCase):
def check(): def check():
# We know that we've broken the __iter__ method, so the queryset # We know that we've broken the __iter__ method, so the queryset
# should always raise an exception. # should always raise an exception.
self.assertRaises(IndexError, lambda: IndexErrorArticle.objects.all()[0]) with self.assertRaises(IndexError):
self.assertRaises(IndexError, IndexErrorArticle.objects.all().first) IndexErrorArticle.objects.all()[0]
self.assertRaises(IndexError, IndexErrorArticle.objects.all().last) with self.assertRaises(IndexError):
IndexErrorArticle.objects.all().first()
with self.assertRaises(IndexError):
IndexErrorArticle.objects.all().last()
check() check()

View File

@ -13,7 +13,8 @@ class GetObjectOr404Tests(TestCase):
a2 = Author.objects.create(name="Patsy") a2 = Author.objects.create(name="Patsy")
# No Articles yet, so we should get a Http404 error. # No Articles yet, so we should get a Http404 error.
self.assertRaises(Http404, get_object_or_404, Article, title="Foo") with self.assertRaises(Http404):
get_object_or_404(Article, title="Foo")
article = Article.objects.create(title="Run away!") article = Article.objects.create(title="Run away!")
article.authors.set([a1, a2]) article.authors.set([a1, a2])
@ -30,10 +31,8 @@ class GetObjectOr404Tests(TestCase):
) )
# No articles containing "Camelot". This should raise a Http404 error. # No articles containing "Camelot". This should raise a Http404 error.
self.assertRaises( with self.assertRaises(Http404):
Http404, get_object_or_404(a1.article_set, title__contains="Camelot")
get_object_or_404, a1.article_set, title__contains="Camelot"
)
# Custom managers can be used too. # Custom managers can be used too.
self.assertEqual( self.assertEqual(
@ -50,16 +49,12 @@ class GetObjectOr404Tests(TestCase):
# Just as when using a get() lookup, you will get an error if more than # Just as when using a get() lookup, you will get an error if more than
# one object is returned. # one object is returned.
self.assertRaises( with self.assertRaises(Author.MultipleObjectsReturned):
Author.MultipleObjectsReturned, get_object_or_404(Author.objects.all())
get_object_or_404, Author.objects.all()
)
# Using an empty QuerySet raises a Http404 error. # Using an empty QuerySet raises a Http404 error.
self.assertRaises( with self.assertRaises(Http404):
Http404, get_object_or_404(Article.objects.none(), title__contains="Run")
get_object_or_404, Article.objects.none(), title__contains="Run"
)
# get_list_or_404 can be used to get lists of objects # get_list_or_404 can be used to get lists of objects
self.assertEqual( self.assertEqual(
@ -68,10 +63,8 @@ class GetObjectOr404Tests(TestCase):
) )
# Http404 is returned if the list is empty. # Http404 is returned if the list is empty.
self.assertRaises( with self.assertRaises(Http404):
Http404, get_list_or_404(a1.article_set, title__icontains="Shrubbery")
get_list_or_404, a1.article_set, title__icontains="Shrubbery"
)
# Custom managers can be used too. # Custom managers can be used too.
self.assertEqual( self.assertEqual(

View File

@ -62,10 +62,8 @@ class GetOrCreateTests(TestCase):
If you don't specify a value or default value for all required If you don't specify a value or default value for all required
fields, you will get an error. fields, you will get an error.
""" """
self.assertRaises( with self.assertRaises(IntegrityError):
IntegrityError, Person.objects.get_or_create(first_name="Tom", last_name="Smith")
Person.objects.get_or_create, first_name="Tom", last_name="Smith"
)
def test_get_or_create_on_related_manager(self): def test_get_or_create_on_related_manager(self):
p = Publisher.objects.create(name="Acme Publishing") p = Publisher.objects.create(name="Acme Publishing")
@ -159,10 +157,8 @@ class GetOrCreateTestsWithManualPKs(TestCase):
If you specify an existing primary key, but different other fields, If you specify an existing primary key, but different other fields,
then you will get an error and data will not be updated. then you will get an error and data will not be updated.
""" """
self.assertRaises( with self.assertRaises(IntegrityError):
IntegrityError, ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different"
)
self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original")
def test_get_or_create_raises_IntegrityError_plus_traceback(self): def test_get_or_create_raises_IntegrityError_plus_traceback(self):
@ -246,7 +242,8 @@ class GetOrCreateThroughManyToMany(TestCase):
def test_something(self): def test_something(self):
Tag.objects.create(text='foo') Tag.objects.create(text='foo')
a_thing = Thing.objects.create(name='a') a_thing = Thing.objects.create(name='a')
self.assertRaises(IntegrityError, a_thing.tags.get_or_create, text='foo') with self.assertRaises(IntegrityError):
a_thing.tags.get_or_create(text='foo')
class UpdateOrCreateTests(TestCase): class UpdateOrCreateTests(TestCase):
@ -292,8 +289,8 @@ class UpdateOrCreateTests(TestCase):
If you don't specify a value or default value for all required If you don't specify a value or default value for all required
fields, you will get an error. fields, you will get an error.
""" """
self.assertRaises(IntegrityError, with self.assertRaises(IntegrityError):
Person.objects.update_or_create, first_name="Tom", last_name="Smith") Person.objects.update_or_create(first_name="Tom", last_name="Smith")
def test_manual_primary_key_test(self): def test_manual_primary_key_test(self):
""" """
@ -301,10 +298,8 @@ class UpdateOrCreateTests(TestCase):
then you will get an error and data will not be updated. then you will get an error and data will not be updated.
""" """
ManualPrimaryKeyTest.objects.create(id=1, data="Original") ManualPrimaryKeyTest.objects.create(id=1, data="Original")
self.assertRaises( with self.assertRaises(IntegrityError):
IntegrityError, ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different")
ManualPrimaryKeyTest.objects.update_or_create, id=1, data="Different"
)
self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original") self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original")
def test_error_contains_full_traceback(self): def test_error_contains_full_traceback(self):

View File

@ -95,7 +95,8 @@ class DistanceTest(TestCase):
if type_error: if type_error:
# A ValueError should be raised on PostGIS when trying to pass # A ValueError should be raised on PostGIS when trying to pass
# Distance objects into a DWithin query using a geodetic field. # Distance objects into a DWithin query using a geodetic field.
self.assertRaises(ValueError, AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count) with self.assertRaises(ValueError):
AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count()
else: else:
self.assertListEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist)))) self.assertListEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))))
@ -289,11 +290,12 @@ class DistanceTest(TestCase):
# Too many params (4 in this case) should raise a ValueError. # Too many params (4 in this case) should raise a ValueError.
queryset = AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4')) queryset = AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4'))
self.assertRaises(ValueError, len, queryset) with self.assertRaises(ValueError):
len(queryset)
# Not enough params should raise a ValueError. # Not enough params should raise a ValueError.
self.assertRaises(ValueError, len, with self.assertRaises(ValueError):
AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',))) len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
# Getting all cities w/in 550 miles of Hobart. # Getting all cities w/in 550 miles of Hobart.
hobart = AustraliaCity.objects.get(name='Hobart') hobart = AustraliaCity.objects.get(name='Hobart')
@ -382,7 +384,8 @@ class DistanceTest(TestCase):
self.assertAlmostEqual(len_m1, qs[0].length.m, tol) self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
else: else:
# Does not support geodetic coordinate systems. # Does not support geodetic coordinate systems.
self.assertRaises(ValueError, Interstate.objects.length) with self.assertRaises(ValueError):
Interstate.objects.length()
# Now doing length on a projected coordinate system. # Now doing length on a projected coordinate system.
i10 = SouthTexasInterstate.objects.length().get(name='I-10') i10 = SouthTexasInterstate.objects.length().get(name='I-10')

View File

@ -40,7 +40,8 @@ class DriverTest(unittest.TestCase):
def test02_invalid_driver(self): def test02_invalid_driver(self):
"Testing invalid GDAL/OGR Data Source Drivers." "Testing invalid GDAL/OGR Data Source Drivers."
for i in invalid_drivers: for i in invalid_drivers:
self.assertRaises(GDALException, Driver, i) with self.assertRaises(GDALException):
Driver(i)
def test03_aliases(self): def test03_aliases(self):
"Testing driver aliases." "Testing driver aliases."

View File

@ -87,7 +87,8 @@ class DataSourceTest(unittest.TestCase):
def test02_invalid_shp(self): def test02_invalid_shp(self):
"Testing invalid SHP files for the Data Source." "Testing invalid SHP files for the Data Source."
for source in bad_ds: for source in bad_ds:
self.assertRaises(GDALException, DataSource, source.ds) with self.assertRaises(GDALException):
DataSource(source.ds)
def test03a_layers(self): def test03a_layers(self):
"Testing Data Source Layers." "Testing Data Source Layers."
@ -122,8 +123,10 @@ class DataSourceTest(unittest.TestCase):
self.assertIn(f, source.fields) self.assertIn(f, source.fields)
# Negative FIDs are not allowed. # Negative FIDs are not allowed.
self.assertRaises(OGRIndexError, layer.__getitem__, -1) with self.assertRaises(OGRIndexError):
self.assertRaises(OGRIndexError, layer.__getitem__, 50000) layer.__getitem__(-1)
with self.assertRaises(OGRIndexError):
layer.__getitem__(50000)
if hasattr(source, 'field_values'): if hasattr(source, 'field_values'):
fld_names = source.field_values.keys() fld_names = source.field_values.keys()
@ -233,11 +236,13 @@ class DataSourceTest(unittest.TestCase):
self.assertIsNone(lyr.spatial_filter) self.assertIsNone(lyr.spatial_filter)
# Must be set a/an OGRGeometry or 4-tuple. # Must be set a/an OGRGeometry or 4-tuple.
self.assertRaises(TypeError, lyr._set_spatial_filter, 'foo') with self.assertRaises(TypeError):
lyr._set_spatial_filter('foo')
# Setting the spatial filter with a tuple/list with the extent of # Setting the spatial filter with a tuple/list with the extent of
# a buffer centering around Pueblo. # a buffer centering around Pueblo.
self.assertRaises(ValueError, lyr._set_spatial_filter, list(range(5))) with self.assertRaises(ValueError):
lyr._set_spatial_filter(list(range(5)))
filter_extent = (-105.609252, 37.255001, -103.609252, 39.255001) filter_extent = (-105.609252, 37.255001, -103.609252, 39.255001)
lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001) lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001)
self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter) self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter)

View File

@ -25,13 +25,20 @@ class EnvelopeTest(unittest.TestCase):
Envelope(0, 0, 5, 5) Envelope(0, 0, 5, 5)
Envelope(0, '0', '5', 5) # Thanks to ww for this Envelope(0, '0', '5', 5) # Thanks to ww for this
Envelope(e1._envelope) Envelope(e1._envelope)
self.assertRaises(GDALException, Envelope, (5, 5, 0, 0)) with self.assertRaises(GDALException):
self.assertRaises(GDALException, Envelope, 5, 5, 0, 0) Envelope((5, 5, 0, 0))
self.assertRaises(GDALException, Envelope, (0, 0, 5, 5, 3)) with self.assertRaises(GDALException):
self.assertRaises(GDALException, Envelope, ()) Envelope(5, 5, 0, 0)
self.assertRaises(ValueError, Envelope, 0, 'a', 5, 5) with self.assertRaises(GDALException):
self.assertRaises(TypeError, Envelope, 'foo') Envelope((0, 0, 5, 5, 3))
self.assertRaises(GDALException, Envelope, (1, 1, 0, 0)) with self.assertRaises(GDALException):
Envelope(())
with self.assertRaises(ValueError):
Envelope(0, 'a', 5, 5)
with self.assertRaises(TypeError):
Envelope('foo')
with self.assertRaises(GDALException):
Envelope((1, 1, 0, 0))
try: try:
Envelope(0, 0, 0, 0) Envelope(0, 0, 0, 0)
except GDALException: except GDALException:

View File

@ -36,9 +36,12 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
OGRGeomType('Unknown') OGRGeomType('Unknown')
# Should throw TypeError on this input # Should throw TypeError on this input
self.assertRaises(GDALException, OGRGeomType, 23) with self.assertRaises(GDALException):
self.assertRaises(GDALException, OGRGeomType, 'fooD') OGRGeomType(23)
self.assertRaises(GDALException, OGRGeomType, 9) with self.assertRaises(GDALException):
OGRGeomType('fooD')
with self.assertRaises(GDALException):
OGRGeomType(9)
# Equivalence can take strings, ints, and other OGRGeomTypes # Equivalence can take strings, ints, and other OGRGeomTypes
self.assertEqual(OGRGeomType(1), OGRGeomType(1)) self.assertEqual(OGRGeomType(1), OGRGeomType(1))
@ -168,7 +171,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
self.assertEqual(ls.coords, linestr.tuple) self.assertEqual(ls.coords, linestr.tuple)
self.assertEqual(linestr, OGRGeometry(ls.wkt)) self.assertEqual(linestr, OGRGeometry(ls.wkt))
self.assertNotEqual(linestr, prev) self.assertNotEqual(linestr, prev)
self.assertRaises(OGRIndexError, linestr.__getitem__, len(linestr)) with self.assertRaises(OGRIndexError):
linestr.__getitem__(len(linestr))
prev = linestr prev = linestr
# Testing the x, y properties. # Testing the x, y properties.
@ -192,7 +196,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
for ls in mlinestr: for ls in mlinestr:
self.assertEqual(2, ls.geom_type) self.assertEqual(2, ls.geom_type)
self.assertEqual('LINESTRING', ls.geom_name) self.assertEqual('LINESTRING', ls.geom_name)
self.assertRaises(OGRIndexError, mlinestr.__getitem__, len(mlinestr)) with self.assertRaises(OGRIndexError):
mlinestr.__getitem__(len(mlinestr))
def test_linearring(self): def test_linearring(self):
"Testing LinearRing objects." "Testing LinearRing objects."
@ -263,7 +268,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
if mp.valid: if mp.valid:
self.assertEqual(mp.n_p, mpoly.point_count) self.assertEqual(mp.n_p, mpoly.point_count)
self.assertEqual(mp.num_geom, len(mpoly)) self.assertEqual(mp.num_geom, len(mpoly))
self.assertRaises(OGRIndexError, mpoly.__getitem__, len(mpoly)) with self.assertRaises(OGRIndexError):
mpoly.__getitem__(len(mpoly))
for p in mpoly: for p in mpoly:
self.assertEqual('POLYGON', p.geom_name) self.assertEqual('POLYGON', p.geom_name)
self.assertEqual(3, p.geom_type) self.assertEqual(3, p.geom_type)
@ -415,7 +421,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
# Can't insert a Point into a MultiPolygon. # Can't insert a Point into a MultiPolygon.
mp = OGRGeometry('MultiPolygon') mp = OGRGeometry('MultiPolygon')
pnt = OGRGeometry('POINT(5 23)') pnt = OGRGeometry('POINT(5 23)')
self.assertRaises(GDALException, mp.add, pnt) with self.assertRaises(GDALException):
mp.add(pnt)
# GeometryCollection.add may take an OGRGeometry (if another collection # GeometryCollection.add may take an OGRGeometry (if another collection
# of the same type all child geoms will be added individually) or WKT. # of the same type all child geoms will be added individually) or WKT.

View File

@ -350,7 +350,8 @@ class GDALBandTests(unittest.TestCase):
band = rs.bands[0] band = rs.bands[0]
# Setting attributes in write mode raises exception in the _flush method # Setting attributes in write mode raises exception in the _flush method
self.assertRaises(GDALException, setattr, band, 'nodata_value', 10) with self.assertRaises(GDALException):
setattr(band, 'nodata_value', 10)
def test_band_data_setters(self): def test_band_data_setters(self):
# Create in-memory raster and get band # Create in-memory raster and get band

View File

@ -249,8 +249,10 @@ class SpatialRefTest(unittest.TestCase):
def test13_attr_value(self): def test13_attr_value(self):
"Testing the attr_value() method." "Testing the attr_value() method."
s1 = SpatialReference('WGS84') s1 = SpatialReference('WGS84')
self.assertRaises(TypeError, s1.__getitem__, 0) with self.assertRaises(TypeError):
self.assertRaises(TypeError, s1.__getitem__, ('GEOGCS', 'foo')) s1.__getitem__(0)
with self.assertRaises(TypeError):
s1.__getitem__(('GEOGCS', 'foo'))
self.assertEqual('WGS 84', s1['GEOGCS']) self.assertEqual('WGS 84', s1['GEOGCS'])
self.assertEqual('WGS_1984', s1['DATUM']) self.assertEqual('WGS_1984', s1['DATUM'])
self.assertEqual('EPSG', s1['AUTHORITY']) self.assertEqual('EPSG', s1['AUTHORITY'])

View File

@ -157,8 +157,8 @@ class Geo3DTest(Geo3DLoadingHelper, TestCase):
# The city shapefile is 2D, and won't be able to fill the coordinates # The city shapefile is 2D, and won't be able to fill the coordinates
# in the 3D model -- thus, a LayerMapError is raised. # in the 3D model -- thus, a LayerMapError is raised.
self.assertRaises(LayerMapError, LayerMapping, with self.assertRaises(LayerMapError):
Point3D, city_file, point_mapping, transform=False) LayerMapping(Point3D, city_file, point_mapping, transform=False)
# 3D model should take 3D data just fine. # 3D model should take 3D data just fine.
lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False) lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False)

View File

@ -86,5 +86,7 @@ class GeoFeedTest(TestCase):
self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'geo:lat', 'geo:lon']) self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'geo:lat', 'geo:lon'])
# Boxes and Polygons aren't allowed in W3C Geo feeds. # Boxes and Polygons aren't allowed in W3C Geo feeds.
self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/') # Box in <channel> with self.assertRaises(ValueError): # Box in <channel>
self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in <entry> self.client.get('/feeds/w3cgeo2/')
with self.assertRaises(ValueError): # Polygons in <entry>
self.client.get('/feeds/w3cgeo3/')

View File

@ -408,13 +408,15 @@ class GeoLookupTest(TestCase):
# Not passing in a geometry as first param should # Not passing in a geometry as first param should
# raise a type error when initializing the GeoQuerySet # raise a type error when initializing the GeoQuerySet
self.assertRaises(ValueError, Country.objects.filter, mpoly__relate=(23, 'foo')) with self.assertRaises(ValueError):
Country.objects.filter(mpoly__relate=(23, 'foo'))
# Making sure the right exception is raised for the given # Making sure the right exception is raised for the given
# bad arguments. # bad arguments.
for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]: for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]:
qs = Country.objects.filter(mpoly__relate=bad_args) qs = Country.objects.filter(mpoly__relate=bad_args)
self.assertRaises(e, qs.count) with self.assertRaises(e):
qs.count()
# Relate works differently for the different backends. # Relate works differently for the different backends.
if postgis or spatialite: if postgis or spatialite:
@ -556,7 +558,8 @@ class GeoQuerySetTest(TestCase):
"Testing GeoJSON output from the database using GeoQuerySet.geojson()." "Testing GeoJSON output from the database using GeoQuerySet.geojson()."
# Only PostGIS and SpatiaLite support GeoJSON. # Only PostGIS and SpatiaLite support GeoJSON.
if not connection.ops.geojson: if not connection.ops.geojson:
self.assertRaises(NotImplementedError, Country.objects.all().geojson, field_name='mpoly') with self.assertRaises(NotImplementedError):
Country.objects.all().geojson(field_name='mpoly')
return return
pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}' pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}'
@ -579,7 +582,8 @@ class GeoQuerySetTest(TestCase):
) )
# Precision argument should only be an integer # Precision argument should only be an integer
self.assertRaises(TypeError, City.objects.geojson, precision='foo') with self.assertRaises(TypeError):
City.objects.geojson(precision='foo')
# Reference queries and values. # Reference queries and values.
# SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0) # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0)
@ -610,7 +614,8 @@ class GeoQuerySetTest(TestCase):
# Should throw a TypeError when trying to obtain GML from a # Should throw a TypeError when trying to obtain GML from a
# non-geometry field. # non-geometry field.
qs = City.objects.all() qs = City.objects.all()
self.assertRaises(TypeError, qs.gml, field_name='name') with self.assertRaises(TypeError):
qs.gml(field_name='name')
ptown1 = City.objects.gml(field_name='point', precision=9).get(name='Pueblo') ptown1 = City.objects.gml(field_name='point', precision=9).get(name='Pueblo')
ptown2 = City.objects.gml(precision=9).get(name='Pueblo') ptown2 = City.objects.gml(precision=9).get(name='Pueblo')
@ -639,7 +644,8 @@ class GeoQuerySetTest(TestCase):
# Should throw a TypeError when trying to obtain KML from a # Should throw a TypeError when trying to obtain KML from a
# non-geometry field. # non-geometry field.
qs = City.objects.all() qs = City.objects.all()
self.assertRaises(TypeError, qs.kml, 'name') with self.assertRaises(TypeError):
qs.kml('name')
# Ensuring the KML is as expected. # Ensuring the KML is as expected.
ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo') ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo')
@ -652,10 +658,8 @@ class GeoQuerySetTest(TestCase):
Testing the `MakeLine` aggregate. Testing the `MakeLine` aggregate.
""" """
if not connection.features.supports_make_line_aggr: if not connection.features.supports_make_line_aggr:
self.assertRaises( with self.assertRaises(NotImplementedError):
NotImplementedError, City.objects.all().aggregate(MakeLine('point'))
City.objects.all().aggregate, MakeLine('point')
)
return return
# MakeLine on an inappropriate field returns simply None # MakeLine on an inappropriate field returns simply None
@ -734,7 +738,8 @@ class GeoQuerySetTest(TestCase):
coords.reverse() coords.reverse()
self.assertEqual(tuple(coords), t.reverse_geom.coords) self.assertEqual(tuple(coords), t.reverse_geom.coords)
if oracle: if oracle:
self.assertRaises(TypeError, State.objects.reverse_geom) with self.assertRaises(TypeError):
State.objects.reverse_geom()
@skipUnlessDBFeature("has_scale_method") @skipUnlessDBFeature("has_scale_method")
def test_scale(self): def test_scale(self):
@ -754,9 +759,11 @@ class GeoQuerySetTest(TestCase):
"Testing GeoQuerySet.snap_to_grid()." "Testing GeoQuerySet.snap_to_grid()."
# Let's try and break snap_to_grid() with bad combinations of arguments. # Let's try and break snap_to_grid() with bad combinations of arguments.
for bad_args in ((), range(3), range(5)): for bad_args in ((), range(3), range(5)):
self.assertRaises(ValueError, Country.objects.snap_to_grid, *bad_args) with self.assertRaises(ValueError):
Country.objects.snap_to_grid(*bad_args)
for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))): for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))):
self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args) with self.assertRaises(TypeError):
Country.objects.snap_to_grid(*bad_args)
# Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
# from the world borders dataset he provides. # from the world borders dataset he provides.
@ -802,7 +809,8 @@ class GeoQuerySetTest(TestCase):
def test_svg(self): def test_svg(self):
"Testing SVG output using GeoQuerySet.svg()." "Testing SVG output using GeoQuerySet.svg()."
self.assertRaises(TypeError, City.objects.svg, precision='foo') with self.assertRaises(TypeError):
City.objects.svg(precision='foo')
# SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo'; # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo';
svg1 = 'cx="-104.609252" cy="-38.255001"' svg1 = 'cx="-104.609252" cy="-38.255001"'
# Even though relative, only one point so it's practically the same except for # Even though relative, only one point so it's practically the same except for
@ -861,7 +869,8 @@ class GeoQuerySetTest(TestCase):
union1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)') union1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)')
union2 = fromstr('MULTIPOINT(-95.363151 29.763374,-96.801611 32.782057)') union2 = fromstr('MULTIPOINT(-95.363151 29.763374,-96.801611 32.782057)')
qs = City.objects.filter(point__within=tx) qs = City.objects.filter(point__within=tx)
self.assertRaises(ValueError, qs.aggregate, Union('name')) with self.assertRaises(ValueError):
qs.aggregate(Union('name'))
# Using `field_name` keyword argument in one query and specifying an # Using `field_name` keyword argument in one query and specifying an
# order in the other (which should not be used because this is # order in the other (which should not be used because this is
# an aggregate method on a spatial column) # an aggregate method on a spatial column)

View File

@ -56,13 +56,16 @@ class GeographyTest(TestCase):
# http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions
z = Zipcode.objects.get(code='77002') z = Zipcode.objects.get(code='77002')
# ST_Within not available. # ST_Within not available.
self.assertRaises(ValueError, City.objects.filter(point__within=z.poly).count) with self.assertRaises(ValueError):
City.objects.filter(point__within=z.poly).count()
# `@` operator not available. # `@` operator not available.
self.assertRaises(ValueError, City.objects.filter(point__contained=z.poly).count) with self.assertRaises(ValueError):
City.objects.filter(point__contained=z.poly).count()
# Regression test for #14060, `~=` was never really implemented for PostGIS. # Regression test for #14060, `~=` was never really implemented for PostGIS.
htown = City.objects.get(name='Houston') htown = City.objects.get(name='Houston')
self.assertRaises(ValueError, City.objects.get, point__exact=htown.point) with self.assertRaises(ValueError):
City.objects.get(point__exact=htown.point)
@skipUnless(HAS_GDAL, "GDAL is required.") @skipUnless(HAS_GDAL, "GDAL is required.")
def test05_geography_layermapping(self): def test05_geography_layermapping(self):

View File

@ -62,7 +62,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
# a C method is given a NULL memory reference. # a C method is given a NULL memory reference.
for fg in (fg1, fg2): for fg in (fg1, fg2):
# Equivalent to `fg.ptr` # Equivalent to `fg.ptr`
self.assertRaises(GEOSException, fg._get_ptr) with self.assertRaises(GEOSException):
fg._get_ptr()
# Anything that is either not None or the acceptable pointer type will # Anything that is either not None or the acceptable pointer type will
# result in a TypeError when trying to assign it to the `ptr` property. # result in a TypeError when trying to assign it to the `ptr` property.
@ -71,8 +72,10 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
bad_ptrs = (5, ctypes.c_char_p(b'foobar')) bad_ptrs = (5, ctypes.c_char_p(b'foobar'))
for bad_ptr in bad_ptrs: for bad_ptr in bad_ptrs:
# Equivalent to `fg.ptr = bad_ptr` # Equivalent to `fg.ptr = bad_ptr`
self.assertRaises(TypeError, fg1._set_ptr, bad_ptr) with self.assertRaises(TypeError):
self.assertRaises(TypeError, fg2._set_ptr, bad_ptr) fg1._set_ptr(bad_ptr)
with self.assertRaises(TypeError):
fg2._set_ptr(bad_ptr)
def test_wkt(self): def test_wkt(self):
"Testing WKT output." "Testing WKT output."
@ -134,15 +137,18 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
fromstr(err.wkt) fromstr(err.wkt)
# Bad WKB # Bad WKB
self.assertRaises(GEOSException, GEOSGeometry, six.memoryview(b'0')) with self.assertRaises(GEOSException):
GEOSGeometry(six.memoryview(b'0'))
class NotAGeometry(object): class NotAGeometry(object):
pass pass
# Some other object # Some other object
self.assertRaises(TypeError, GEOSGeometry, NotAGeometry()) with self.assertRaises(TypeError):
GEOSGeometry(NotAGeometry())
# None # None
self.assertRaises(TypeError, GEOSGeometry, None) with self.assertRaises(TypeError):
GEOSGeometry(None)
def test_wkb(self): def test_wkb(self):
"Testing WKB output." "Testing WKB output."
@ -288,7 +294,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
self.assertRaises(IndexError, mpnt.__getitem__, len(mpnt)) with self.assertRaises(IndexError):
mpnt.__getitem__(len(mpnt))
self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.centroid, mpnt.centroid.tuple)
self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt)) self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt))
for p in mpnt: for p in mpnt:
@ -314,7 +321,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(ls, fromstr(l.wkt)) self.assertEqual(ls, fromstr(l.wkt))
self.assertEqual(False, ls == prev) # Use assertEqual to test __eq__ self.assertEqual(False, ls == prev) # Use assertEqual to test __eq__
self.assertRaises(IndexError, ls.__getitem__, len(ls)) with self.assertRaises(IndexError):
ls.__getitem__(len(ls))
prev = ls prev = ls
# Creating a LineString from a tuple, list, and numpy array # Creating a LineString from a tuple, list, and numpy array
@ -361,7 +369,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.geom_typeid, 1)
self.assertEqual(ls.empty, False) self.assertEqual(ls.empty, False)
self.assertRaises(IndexError, ml.__getitem__, len(ml)) with self.assertRaises(IndexError):
ml.__getitem__(len(ml))
self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt) self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml))) self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))
@ -442,9 +451,12 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
# Testing __getitem__ and __setitem__ on invalid indices # Testing __getitem__ and __setitem__ on invalid indices
self.assertRaises(IndexError, poly.__getitem__, len(poly)) with self.assertRaises(IndexError):
self.assertRaises(IndexError, poly.__setitem__, len(poly), False) poly.__getitem__(len(poly))
self.assertRaises(IndexError, poly.__getitem__, -1 * len(poly) - 1) with self.assertRaises(IndexError):
poly.__setitem__(len(poly), False)
with self.assertRaises(IndexError):
poly.__getitem__(-1 * len(poly) - 1)
# Testing __iter__ # Testing __iter__
for r in poly: for r in poly:
@ -452,8 +464,10 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(r.geom_typeid, 2) self.assertEqual(r.geom_typeid, 2)
# Testing polygon construction. # Testing polygon construction.
self.assertRaises(TypeError, Polygon, 0, [1, 2, 3]) with self.assertRaises(TypeError):
self.assertRaises(TypeError, Polygon, 'foo') Polygon(0, [1, 2, 3])
with self.assertRaises(TypeError):
Polygon('foo')
# Polygon(shell, (hole1, ... holeN)) # Polygon(shell, (hole1, ... holeN))
rings = tuple(r for r in poly) rings = tuple(r for r in poly)
@ -500,7 +514,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.num_geom, mpoly.num_geom)
self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.n_p, mpoly.num_coords)
self.assertEqual(mp.num_geom, len(mpoly)) self.assertEqual(mp.num_geom, len(mpoly))
self.assertRaises(IndexError, mpoly.__getitem__, len(mpoly)) with self.assertRaises(IndexError):
mpoly.__getitem__(len(mpoly))
for p in mpoly: for p in mpoly:
self.assertEqual(p.geom_type, 'Polygon') self.assertEqual(p.geom_type, 'Polygon')
self.assertEqual(p.geom_typeid, 3) self.assertEqual(p.geom_typeid, 3)
@ -563,7 +578,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
def test_relate_pattern(self): def test_relate_pattern(self):
"Testing relate() and relate_pattern()." "Testing relate() and relate_pattern()."
g = fromstr('POINT (0 0)') g = fromstr('POINT (0 0)')
self.assertRaises(GEOSException, g.relate_pattern, 0, 'invalid pattern, yo') with self.assertRaises(GEOSException):
g.relate_pattern(0, 'invalid pattern, yo')
for rg in self.geometries.relate_geoms: for rg in self.geometries.relate_geoms:
a = fromstr(rg.wkt_a) a = fromstr(rg.wkt_a)
b = fromstr(rg.wkt_b) b = fromstr(rg.wkt_b)
@ -639,7 +655,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
width = bg.width width = bg.width
# Can't use a floating-point for the number of quadsegs. # Can't use a floating-point for the number of quadsegs.
self.assertRaises(ctypes.ArgumentError, g.buffer, width, float(quadsegs)) with self.assertRaises(ctypes.ArgumentError):
g.buffer(width, float(quadsegs))
# Constructing our buffer # Constructing our buffer
buf = g.buffer(width, quadsegs) buf = g.buffer(width, quadsegs)
@ -743,7 +760,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
poly = fromstr(p.wkt) poly = fromstr(p.wkt)
# Should only be able to use __setitem__ with LinearRing geometries. # Should only be able to use __setitem__ with LinearRing geometries.
self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2))) with self.assertRaises(TypeError):
poly.__setitem__(0, LineString((1, 1), (2, 2)))
# Constructing the new shell by adding 500 to every point in the old shell. # Constructing the new shell by adding 500 to every point in the old shell.
shell_tup = poly.shell.tuple shell_tup = poly.shell.tuple
@ -875,7 +893,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
# Testing a 3D LineString # Testing a 3D LineString
ls = LineString((2., 3., 8.), (50., 250., -117.)) ls = LineString((2., 3., 8.), (50., 250., -117.))
self.assertEqual(((2., 3., 8.), (50., 250., -117.)), ls.tuple) self.assertEqual(((2., 3., 8.), (50., 250., -117.)), ls.tuple)
self.assertRaises(TypeError, ls.__setitem__, 0, (1., 2.)) with self.assertRaises(TypeError):
ls.__setitem__(0, (1., 2.))
ls[0] = (1., 2., 3.) ls[0] = (1., 2., 3.)
self.assertEqual((1., 2., 3.), ls[0]) self.assertEqual((1., 2., 3.), ls[0])
@ -961,9 +980,11 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertEqual('LINEARRING EMPTY', lr.wkt) self.assertEqual('LINEARRING EMPTY', lr.wkt)
self.assertEqual(0, len(lr)) self.assertEqual(0, len(lr))
self.assertEqual(True, lr.empty) self.assertEqual(True, lr.empty)
self.assertRaises(IndexError, lr.__getitem__, 0) with self.assertRaises(IndexError):
lr.__getitem__(0)
else: else:
self.assertRaises(IndexError, g.__getitem__, 0) with self.assertRaises(IndexError):
g.__getitem__(0)
def test_collection_dims(self): def test_collection_dims(self):
gc = GeometryCollection([]) gc = GeometryCollection([])
@ -1089,25 +1110,31 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
""" Testing `transform` method (no SRID or negative SRID) """ """ Testing `transform` method (no SRID or negative SRID) """
g = GEOSGeometry('POINT (-104.609 38.255)', srid=None) g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
self.assertRaises(GEOSException, g.transform, 2774) with self.assertRaises(GEOSException):
g.transform(2774)
g = GEOSGeometry('POINT (-104.609 38.255)', srid=None) g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
self.assertRaises(GEOSException, g.transform, 2774, clone=True) with self.assertRaises(GEOSException):
g.transform(2774, clone=True)
g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1) g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
self.assertRaises(GEOSException, g.transform, 2774) with self.assertRaises(GEOSException):
g.transform(2774)
g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1) g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
self.assertRaises(GEOSException, g.transform, 2774, clone=True) with self.assertRaises(GEOSException):
g.transform(2774, clone=True)
@mock.patch('django.contrib.gis.gdal.HAS_GDAL', False) @mock.patch('django.contrib.gis.gdal.HAS_GDAL', False)
def test_transform_nogdal(self): def test_transform_nogdal(self):
""" Testing `transform` method (GDAL not available) """ """ Testing `transform` method (GDAL not available) """
g = GEOSGeometry('POINT (-104.609 38.255)', 4326) g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
self.assertRaises(GEOSException, g.transform, 2774) with self.assertRaises(GEOSException):
g.transform(2774)
g = GEOSGeometry('POINT (-104.609 38.255)', 4326) g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
self.assertRaises(GEOSException, g.transform, 2774, clone=True) with self.assertRaises(GEOSException):
g.transform(2774, clone=True)
def test_extent(self): def test_extent(self):
"Testing `extent` method." "Testing `extent` method."

View File

@ -82,8 +82,10 @@ class GEOSMutationTest(unittest.TestCase):
p = Point(1, 2) p = Point(1, 2)
for i in range(-2, 2): for i in range(-2, 2):
p._checkindex(i) p._checkindex(i)
self.assertRaises(IndexError, p._checkindex, 2) with self.assertRaises(IndexError):
self.assertRaises(IndexError, p._checkindex, -3) p._checkindex(2)
with self.assertRaises(IndexError):
p._checkindex(-3)
def test01_PointMutations(self): def test01_PointMutations(self):
'Testing Point mutations' 'Testing Point mutations'
@ -100,8 +102,10 @@ class GEOSMutationTest(unittest.TestCase):
def test02_PointExceptions(self): def test02_PointExceptions(self):
'Testing Point exceptions' 'Testing Point exceptions'
self.assertRaises(TypeError, Point, range(1)) with self.assertRaises(TypeError):
self.assertRaises(TypeError, Point, range(4)) Point(range(1))
with self.assertRaises(TypeError):
Point(range(4))
def test03_PointApi(self): def test03_PointApi(self):
'Testing Point API' 'Testing Point API'

View File

@ -27,13 +27,16 @@ class GEOSIOTest(SimpleTestCase):
self.assertEqual(ref, geom) self.assertEqual(ref, geom)
# Should only accept six.string_types objects. # Should only accept six.string_types objects.
self.assertRaises(TypeError, wkt_r.read, 1) with self.assertRaises(TypeError):
self.assertRaises(TypeError, wkt_r.read, memoryview(b'foo')) wkt_r.read(1)
with self.assertRaises(TypeError):
wkt_r.read(memoryview(b'foo'))
def test02_wktwriter(self): def test02_wktwriter(self):
# Creating a WKTWriter instance, testing its ptr property. # Creating a WKTWriter instance, testing its ptr property.
wkt_w = WKTWriter() wkt_w = WKTWriter()
self.assertRaises(TypeError, wkt_w._set_ptr, WKTReader.ptr_type()) with self.assertRaises(TypeError):
wkt_w._set_ptr(WKTReader.ptr_type())
ref = GEOSGeometry('POINT (5 23)') ref = GEOSGeometry('POINT (5 23)')
ref_wkt = 'POINT (5.0000000000000000 23.0000000000000000)' ref_wkt = 'POINT (5.0000000000000000 23.0000000000000000)'
@ -56,7 +59,8 @@ class GEOSIOTest(SimpleTestCase):
bad_input = (1, 5.23, None, False) bad_input = (1, 5.23, None, False)
for bad_wkb in bad_input: for bad_wkb in bad_input:
self.assertRaises(TypeError, wkb_r.read, bad_wkb) with self.assertRaises(TypeError):
wkb_r.read(bad_wkb)
def test04_wkbwriter(self): def test04_wkbwriter(self):
wkb_w = WKBWriter() wkb_w = WKBWriter()
@ -75,7 +79,8 @@ class GEOSIOTest(SimpleTestCase):
# Ensuring bad byteorders are not accepted. # Ensuring bad byteorders are not accepted.
for bad_byteorder in (-1, 2, 523, 'foo', None): for bad_byteorder in (-1, 2, 523, 'foo', None):
# Equivalent of `wkb_w.byteorder = bad_byteorder` # Equivalent of `wkb_w.byteorder = bad_byteorder`
self.assertRaises(ValueError, wkb_w._set_byteorder, bad_byteorder) with self.assertRaises(ValueError):
wkb_w._set_byteorder(bad_byteorder)
# Setting the byteorder to 0 (for Big Endian) # Setting the byteorder to 0 (for Big Endian)
wkb_w.byteorder = 0 wkb_w.byteorder = 0
@ -97,7 +102,8 @@ class GEOSIOTest(SimpleTestCase):
# Ensuring bad output dimensions are not accepted # Ensuring bad output dimensions are not accepted
for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None): for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
# Equivalent of `wkb_w.outdim = bad_outdim` # Equivalent of `wkb_w.outdim = bad_outdim`
self.assertRaises(ValueError, wkb_w._set_outdim, bad_outdim) with self.assertRaises(ValueError):
wkb_w._set_outdim(bad_outdim)
# Now setting the output dimensions to be 3 # Now setting the output dimensions to be 3
wkb_w.outdim = 3 wkb_w.outdim = 3

View File

@ -128,9 +128,11 @@ class ListMixinTest(unittest.TestCase):
self.assertEqual(pl, ul[:], 'set slice [%d:%d:%d]' % (i, j, k)) self.assertEqual(pl, ul[:], 'set slice [%d:%d:%d]' % (i, j, k))
sliceLen = len(ul[i:j:k]) sliceLen = len(ul[i:j:k])
self.assertRaises(ValueError, setfcn, ul, i, j, k, sliceLen + 1) with self.assertRaises(ValueError):
setfcn(ul, i, j, k, sliceLen + 1)
if sliceLen > 2: if sliceLen > 2:
self.assertRaises(ValueError, setfcn, ul, i, j, k, sliceLen - 1) with self.assertRaises(ValueError):
setfcn(ul, i, j, k, sliceLen - 1)
for k in self.step_range(): for k in self.step_range():
ssl = nextRange(len(ul[i::k])) ssl = nextRange(len(ul[i::k]))
@ -223,9 +225,12 @@ class ListMixinTest(unittest.TestCase):
del x[i] del x[i]
pl, ul = self.lists_of_len() pl, ul = self.lists_of_len()
for i in (-1 - self.limit, self.limit): for i in (-1 - self.limit, self.limit):
self.assertRaises(IndexError, setfcn, ul, i) # 'set index %d' % i) with self.assertRaises(IndexError): # 'set index %d' % i)
self.assertRaises(IndexError, getfcn, ul, i) # 'get index %d' % i) setfcn(ul, i)
self.assertRaises(IndexError, delfcn, ul, i) # 'del index %d' % i) with self.assertRaises(IndexError): # 'get index %d' % i)
getfcn(ul, i)
with self.assertRaises(IndexError): # 'del index %d' % i)
delfcn(ul, i)
def test06_list_methods(self): def test06_list_methods(self):
'List methods' 'List methods'
@ -261,8 +266,10 @@ class ListMixinTest(unittest.TestCase):
def popfcn(x, i): def popfcn(x, i):
x.pop(i) x.pop(i)
self.assertRaises(IndexError, popfcn, ul, self.limit) with self.assertRaises(IndexError):
self.assertRaises(IndexError, popfcn, ul, -1 - self.limit) popfcn(ul, self.limit)
with self.assertRaises(IndexError):
popfcn(ul, -1 - self.limit)
pl, ul = self.lists_of_len() pl, ul = self.lists_of_len()
for val in range(self.limit): for val in range(self.limit):
@ -282,8 +289,10 @@ class ListMixinTest(unittest.TestCase):
def removefcn(x, v): def removefcn(x, v):
return x.remove(v) return x.remove(v)
self.assertRaises(ValueError, indexfcn, ul, 40) with self.assertRaises(ValueError):
self.assertRaises(ValueError, removefcn, ul, 40) indexfcn(ul, 40)
with self.assertRaises(ValueError):
removefcn(ul, 40)
def test07_allowed_types(self): def test07_allowed_types(self):
'Type-restricted list' 'Type-restricted list'
@ -294,8 +303,10 @@ class ListMixinTest(unittest.TestCase):
def setfcn(x, i, v): def setfcn(x, i, v):
x[i] = v x[i] = v
self.assertRaises(TypeError, setfcn, ul, 2, 'hello') with self.assertRaises(TypeError):
self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), ('hello', 'goodbye')) setfcn(ul, 2, 'hello')
with self.assertRaises(TypeError):
setfcn(ul, slice(0, 3, 2), ('hello', 'goodbye'))
def test08_min_length(self): def test08_min_length(self):
'Length limits' 'Length limits'
@ -308,14 +319,17 @@ class ListMixinTest(unittest.TestCase):
def setfcn(x, i): def setfcn(x, i):
x[:i] = [] x[:i] = []
for i in range(len(ul) - ul._minlength + 1, len(ul)): for i in range(len(ul) - ul._minlength + 1, len(ul)):
self.assertRaises(ValueError, delfcn, ul, i) with self.assertRaises(ValueError):
self.assertRaises(ValueError, setfcn, ul, i) delfcn(ul, i)
with self.assertRaises(ValueError):
setfcn(ul, i)
del ul[:len(ul) - ul._minlength] del ul[:len(ul) - ul._minlength]
ul._maxlength = 4 ul._maxlength = 4
for i in range(0, ul._maxlength - len(ul)): for i in range(0, ul._maxlength - len(ul)):
ul.append(i) ul.append(i)
self.assertRaises(ValueError, ul.append, 10) with self.assertRaises(ValueError):
ul.append(10)
def test09_iterable_check(self): def test09_iterable_check(self):
'Error on assigning non-iterable to slice' 'Error on assigning non-iterable to slice'
@ -323,7 +337,8 @@ class ListMixinTest(unittest.TestCase):
def setfcn(x, i, v): def setfcn(x, i, v):
x[i] = v x[i] = v
self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), 2) with self.assertRaises(TypeError):
setfcn(ul, slice(0, 3, 2), 2)
def test10_checkindex(self): def test10_checkindex(self):
'Index check' 'Index check'
@ -335,7 +350,8 @@ class ListMixinTest(unittest.TestCase):
self.assertEqual(ul._checkindex(i), i, '_checkindex(pos index)') self.assertEqual(ul._checkindex(i), i, '_checkindex(pos index)')
for i in (-self.limit - 1, self.limit): for i in (-self.limit - 1, self.limit):
self.assertRaises(IndexError, ul._checkindex, i) with self.assertRaises(IndexError):
ul._checkindex(i)
def test_11_sorting(self): def test_11_sorting(self):
'Sorting' 'Sorting'

View File

@ -156,11 +156,13 @@ class LayerMapTest(TestCase):
# Testing invalid params for the `unique` keyword. # Testing invalid params for the `unique` keyword.
for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))): for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))):
self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg) with self.assertRaises(e):
LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg)
# No source reference system defined in the shapefile, should raise an error. # No source reference system defined in the shapefile, should raise an error.
if connection.features.supports_transform: if connection.features.supports_transform:
self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping) with self.assertRaises(LayerMapError):
LayerMapping(County, co_shp, co_mapping)
# Passing in invalid ForeignKey mapping parameters -- must be a dictionary # Passing in invalid ForeignKey mapping parameters -- must be a dictionary
# mapping for the model the ForeignKey points to. # mapping for the model the ForeignKey points to.
@ -168,14 +170,17 @@ class LayerMapTest(TestCase):
bad_fk_map1['state'] = 'name' bad_fk_map1['state'] = 'name'
bad_fk_map2 = copy(co_mapping) bad_fk_map2 = copy(co_mapping)
bad_fk_map2['state'] = {'nombre': 'State'} bad_fk_map2['state'] = {'nombre': 'State'}
self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False) with self.assertRaises(TypeError):
self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False) LayerMapping(County, co_shp, bad_fk_map1, transform=False)
with self.assertRaises(LayerMapError):
LayerMapping(County, co_shp, bad_fk_map2, transform=False)
# There exist no State models for the ForeignKey mapping to work -- should raise # There exist no State models for the ForeignKey mapping to work -- should raise
# a MissingForeignKey exception (this error would be ignored if the `strict` # a MissingForeignKey exception (this error would be ignored if the `strict`
# keyword is not set). # keyword is not set).
lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True) with self.assertRaises(MissingForeignKey):
lm.save(silent=True, strict=True)
# Now creating the state models so the ForeignKey mapping may work. # Now creating the state models so the ForeignKey mapping may work.
State.objects.bulk_create([ State.objects.bulk_create([
@ -222,11 +227,13 @@ class LayerMapTest(TestCase):
# Bad feature id ranges should raise a type error. # Bad feature id ranges should raise a type error.
bad_ranges = (5.0, 'foo', co_shp) bad_ranges = (5.0, 'foo', co_shp)
for bad in bad_ranges: for bad in bad_ranges:
self.assertRaises(TypeError, lm.save, fid_range=bad) with self.assertRaises(TypeError):
lm.save(fid_range=bad)
# Step keyword should not be allowed w/`fid_range`. # Step keyword should not be allowed w/`fid_range`.
fr = (3, 5) # layer[3:5] fr = (3, 5) # layer[3:5]
self.assertRaises(LayerMapError, lm.save, fid_range=fr, step=10) with self.assertRaises(LayerMapError):
lm.save(fid_range=fr, step=10)
lm.save(fid_range=fr) lm.save(fid_range=fr)
# Features IDs 3 & 4 are for Galveston County, Texas -- only # Features IDs 3 & 4 are for Galveston County, Texas -- only

View File

@ -17,7 +17,8 @@ class GeometryFieldTest(SimpleTestCase):
"Testing GeometryField initialization with defaults." "Testing GeometryField initialization with defaults."
fld = forms.GeometryField() fld = forms.GeometryField()
for bad_default in ('blah', 3, 'FoO', None, 0): for bad_default in ('blah', 3, 'FoO', None, 0):
self.assertRaises(ValidationError, fld.clean, bad_default) with self.assertRaises(ValidationError):
fld.clean(bad_default)
def test_srid(self): def test_srid(self):
"Testing GeometryField with a SRID set." "Testing GeometryField with a SRID set."
@ -59,7 +60,8 @@ class GeometryFieldTest(SimpleTestCase):
# a WKT for any other geom_type will be properly transformed by `to_python` # a WKT for any other geom_type will be properly transformed by `to_python`
self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)')) self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)'))
# but rejected by `clean` # but rejected by `clean`
self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)') with self.assertRaises(forms.ValidationError):
pnt_fld.clean('LINESTRING(0 0, 1 1)')
def test_to_python(self): def test_to_python(self):
""" """
@ -72,7 +74,8 @@ class GeometryFieldTest(SimpleTestCase):
self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt)) self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt))
# but raises a ValidationError for any other string # but raises a ValidationError for any other string
for wkt in ('POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'): for wkt in ('POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'):
self.assertRaises(forms.ValidationError, fld.to_python, wkt) with self.assertRaises(forms.ValidationError):
fld.to_python(wkt)
def test_field_with_text_widget(self): def test_field_with_text_widget(self):
class PointForm(forms.Form): class PointForm(forms.Form):

View File

@ -66,23 +66,29 @@ class GeoIPTest(unittest.TestCase):
# Improper parameters. # Improper parameters.
bad_params = (23, 'foo', 15.23) bad_params = (23, 'foo', 15.23)
for bad in bad_params: for bad in bad_params:
self.assertRaises(GeoIPException, GeoIP, cache=bad) with self.assertRaises(GeoIPException):
GeoIP(cache=bad)
if isinstance(bad, six.string_types): if isinstance(bad, six.string_types):
e = GeoIPException e = GeoIPException
else: else:
e = TypeError e = TypeError
self.assertRaises(e, GeoIP, bad, 0) with self.assertRaises(e):
GeoIP(bad, 0)
def test02_bad_query(self): def test02_bad_query(self):
"Testing GeoIP query parameter checking." "Testing GeoIP query parameter checking."
cntry_g = GeoIP(city='<foo>') cntry_g = GeoIP(city='<foo>')
# No city database available, these calls should fail. # No city database available, these calls should fail.
self.assertRaises(GeoIPException, cntry_g.city, 'google.com') with self.assertRaises(GeoIPException):
self.assertRaises(GeoIPException, cntry_g.coords, 'yahoo.com') cntry_g.city('google.com')
with self.assertRaises(GeoIPException):
cntry_g.coords('yahoo.com')
# Non-string query should raise TypeError # Non-string query should raise TypeError
self.assertRaises(TypeError, cntry_g.country_code, 17) with self.assertRaises(TypeError):
self.assertRaises(TypeError, cntry_g.country_name, GeoIP) cntry_g.country_code(17)
with self.assertRaises(TypeError):
cntry_g.country_name(GeoIP)
def test03_country(self): def test03_country(self):
"Testing GeoIP country querying methods." "Testing GeoIP country querying methods."

View File

@ -47,23 +47,29 @@ class GeoIPTest(unittest.TestCase):
# Improper parameters. # Improper parameters.
bad_params = (23, 'foo', 15.23) bad_params = (23, 'foo', 15.23)
for bad in bad_params: for bad in bad_params:
self.assertRaises(GeoIP2Exception, GeoIP2, cache=bad) with self.assertRaises(GeoIP2Exception):
GeoIP2(cache=bad)
if isinstance(bad, six.string_types): if isinstance(bad, six.string_types):
e = GeoIP2Exception e = GeoIP2Exception
else: else:
e = TypeError e = TypeError
self.assertRaises(e, GeoIP2, bad, 0) with self.assertRaises(e):
GeoIP2(bad, 0)
def test02_bad_query(self): def test02_bad_query(self):
"GeoIP query parameter checking." "GeoIP query parameter checking."
cntry_g = GeoIP2(city='<foo>') cntry_g = GeoIP2(city='<foo>')
# No city database available, these calls should fail. # No city database available, these calls should fail.
self.assertRaises(GeoIP2Exception, cntry_g.city, 'tmc.edu') with self.assertRaises(GeoIP2Exception):
self.assertRaises(GeoIP2Exception, cntry_g.coords, 'tmc.edu') cntry_g.city('tmc.edu')
with self.assertRaises(GeoIP2Exception):
cntry_g.coords('tmc.edu')
# Non-string query should raise TypeError # Non-string query should raise TypeError
self.assertRaises(TypeError, cntry_g.country_code, 17) with self.assertRaises(TypeError):
self.assertRaises(TypeError, cntry_g.country_name, GeoIP2) cntry_g.country_code(17)
with self.assertRaises(TypeError):
cntry_g.country_name(GeoIP2)
@mock.patch('socket.gethostbyname') @mock.patch('socket.gethostbyname')
def test03_country(self, gethostbyname): def test03_country(self, gethostbyname):

View File

@ -34,7 +34,8 @@ class DistanceTest(unittest.TestCase):
def testInitInvalid(self): def testInitInvalid(self):
"Testing initialization from invalid units" "Testing initialization from invalid units"
self.assertRaises(AttributeError, D, banana=100) with self.assertRaises(AttributeError):
D(banana=100)
def testAccess(self): def testAccess(self):
"Testing access in different units" "Testing access in different units"
@ -161,7 +162,8 @@ class AreaTest(unittest.TestCase):
def testInitInvaliA(self): def testInitInvaliA(self):
"Testing initialization from invalid units" "Testing initialization from invalid units"
self.assertRaises(AttributeError, A, banana=100) with self.assertRaises(AttributeError):
A(banana=100)
def testAccess(self): def testAccess(self):
"Testing access in different units" "Testing access in different units"

View File

@ -87,8 +87,10 @@ class TestPostgisVersionCheck(unittest.TestCase):
for version in versions: for version in versions:
ops = FakePostGISOperations(version) ops = FakePostGISOperations(version)
self.assertRaises(Exception, lambda: ops.spatial_version) with self.assertRaises(Exception):
ops.spatial_version
def test_no_version_number(self): def test_no_version_number(self):
ops = FakePostGISOperations() ops = FakePostGISOperations()
self.assertRaises(ImproperlyConfigured, lambda: ops.spatial_version) with self.assertRaises(ImproperlyConfigured):
ops.spatial_version

View File

@ -31,17 +31,25 @@ class QueryDictTests(unittest.TestCase):
def test_missing_key(self): def test_missing_key(self):
q = QueryDict() q = QueryDict()
self.assertRaises(KeyError, q.__getitem__, 'foo') with self.assertRaises(KeyError):
q.__getitem__('foo')
def test_immutability(self): def test_immutability(self):
q = QueryDict() q = QueryDict()
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar') with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar']) q.__setitem__('something', 'bar')
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.update, {'foo': 'bar'}) q.setlist('foo', ['bar'])
self.assertRaises(AttributeError, q.pop, 'foo') with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.popitem) q.appendlist('foo', ['bar'])
self.assertRaises(AttributeError, q.clear) with self.assertRaises(AttributeError):
q.update({'foo': 'bar'})
with self.assertRaises(AttributeError):
q.pop('foo')
with self.assertRaises(AttributeError):
q.popitem()
with self.assertRaises(AttributeError):
q.clear()
def test_immutable_get_with_default(self): def test_immutable_get_with_default(self):
q = QueryDict() q = QueryDict()
@ -65,16 +73,20 @@ class QueryDictTests(unittest.TestCase):
q = QueryDict(str('foo=bar')) q = QueryDict(str('foo=bar'))
self.assertEqual(q['foo'], 'bar') self.assertEqual(q['foo'], 'bar')
self.assertRaises(KeyError, q.__getitem__, 'bar') with self.assertRaises(KeyError):
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar') q.__getitem__('bar')
with self.assertRaises(AttributeError):
q.__setitem__('something', 'bar')
self.assertEqual(q.get('foo', 'default'), 'bar') self.assertEqual(q.get('foo', 'default'), 'bar')
self.assertEqual(q.get('bar', 'default'), 'default') self.assertEqual(q.get('bar', 'default'), 'default')
self.assertEqual(q.getlist('foo'), ['bar']) self.assertEqual(q.getlist('foo'), ['bar'])
self.assertEqual(q.getlist('bar'), []) self.assertEqual(q.getlist('bar'), [])
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar']) with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) q.setlist('foo', ['bar'])
with self.assertRaises(AttributeError):
q.appendlist('foo', ['bar'])
if six.PY2: if six.PY2:
self.assertTrue(q.has_key('foo')) self.assertTrue(q.has_key('foo'))
@ -89,11 +101,16 @@ class QueryDictTests(unittest.TestCase):
self.assertEqual(list(six.itervalues(q)), ['bar']) self.assertEqual(list(six.itervalues(q)), ['bar'])
self.assertEqual(len(q), 1) self.assertEqual(len(q), 1)
self.assertRaises(AttributeError, q.update, {'foo': 'bar'}) with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.pop, 'foo') q.update({'foo': 'bar'})
self.assertRaises(AttributeError, q.popitem) with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.clear) q.pop('foo')
self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar') with self.assertRaises(AttributeError):
q.popitem()
with self.assertRaises(AttributeError):
q.clear()
with self.assertRaises(AttributeError):
q.setdefault('foo', 'bar')
self.assertEqual(q.urlencode(), 'foo=bar') self.assertEqual(q.urlencode(), 'foo=bar')
@ -110,7 +127,8 @@ class QueryDictTests(unittest.TestCase):
def test_mutable_copy(self): def test_mutable_copy(self):
"""A copy of a QueryDict is mutable.""" """A copy of a QueryDict is mutable."""
q = QueryDict().copy() q = QueryDict().copy()
self.assertRaises(KeyError, q.__getitem__, "foo") with self.assertRaises(KeyError):
q.__getitem__("foo")
q['name'] = 'john' q['name'] = 'john'
self.assertEqual(q['name'], 'john') self.assertEqual(q['name'], 'john')
@ -169,16 +187,20 @@ class QueryDictTests(unittest.TestCase):
q = QueryDict(str('vote=yes&vote=no')) q = QueryDict(str('vote=yes&vote=no'))
self.assertEqual(q['vote'], 'no') self.assertEqual(q['vote'], 'no')
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar') with self.assertRaises(AttributeError):
q.__setitem__('something', 'bar')
self.assertEqual(q.get('vote', 'default'), 'no') self.assertEqual(q.get('vote', 'default'), 'no')
self.assertEqual(q.get('foo', 'default'), 'default') self.assertEqual(q.get('foo', 'default'), 'default')
self.assertEqual(q.getlist('vote'), ['yes', 'no']) self.assertEqual(q.getlist('vote'), ['yes', 'no'])
self.assertEqual(q.getlist('foo'), []) self.assertEqual(q.getlist('foo'), [])
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz']) with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz']) q.setlist('foo', ['bar', 'baz'])
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) with self.assertRaises(AttributeError):
q.setlist('foo', ['bar', 'baz'])
with self.assertRaises(AttributeError):
q.appendlist('foo', ['bar'])
if six.PY2: if six.PY2:
self.assertEqual(q.has_key('vote'), True) self.assertEqual(q.has_key('vote'), True)
@ -192,12 +214,18 @@ class QueryDictTests(unittest.TestCase):
self.assertEqual(list(six.itervalues(q)), ['no']) self.assertEqual(list(six.itervalues(q)), ['no'])
self.assertEqual(len(q), 1) self.assertEqual(len(q), 1)
self.assertRaises(AttributeError, q.update, {'foo': 'bar'}) with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.pop, 'foo') q.update({'foo': 'bar'})
self.assertRaises(AttributeError, q.popitem) with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.clear) q.pop('foo')
self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar') with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, q.__delitem__, 'vote') q.popitem()
with self.assertRaises(AttributeError):
q.clear()
with self.assertRaises(AttributeError):
q.setdefault('foo', 'bar')
with self.assertRaises(AttributeError):
q.__delitem__('vote')
if six.PY2: if six.PY2:
def test_invalid_input_encoding(self): def test_invalid_input_encoding(self):
@ -295,8 +323,10 @@ class HttpResponseTests(unittest.TestCase):
self.assertIsInstance(l[0][0], str) self.assertIsInstance(l[0][0], str)
r = HttpResponse() r = HttpResponse()
self.assertRaises(UnicodeError, r.__setitem__, 'føø', 'bar') with self.assertRaises(UnicodeError):
self.assertRaises(UnicodeError, r.__setitem__, 'føø'.encode('utf-8'), 'bar') r.__setitem__('føø', 'bar')
with self.assertRaises(UnicodeError):
r.__setitem__('føø'.encode('utf-8'), 'bar')
def test_long_line(self): def test_long_line(self):
# Bug #20889: long lines trigger newlines to be added to headers # Bug #20889: long lines trigger newlines to be added to headers
@ -312,8 +342,10 @@ class HttpResponseTests(unittest.TestCase):
def test_newlines_in_headers(self): def test_newlines_in_headers(self):
# Bug #10188: Do not allow newlines in headers (CR or LF) # Bug #10188: Do not allow newlines in headers (CR or LF)
r = HttpResponse() r = HttpResponse()
self.assertRaises(BadHeaderError, r.__setitem__, 'test\rstr', 'test') with self.assertRaises(BadHeaderError):
self.assertRaises(BadHeaderError, r.__setitem__, 'test\nstr', 'test') r.__setitem__('test\rstr', 'test')
with self.assertRaises(BadHeaderError):
r.__setitem__('test\nstr', 'test')
def test_dict_behavior(self): def test_dict_behavior(self):
""" """
@ -418,10 +450,10 @@ class HttpResponseTests(unittest.TestCase):
'file:///etc/passwd', 'file:///etc/passwd',
] ]
for url in bad_urls: for url in bad_urls:
self.assertRaises(SuspiciousOperation, with self.assertRaises(SuspiciousOperation):
HttpResponseRedirect, url) HttpResponseRedirect(url)
self.assertRaises(SuspiciousOperation, with self.assertRaises(SuspiciousOperation):
HttpResponsePermanentRedirect, url) HttpResponsePermanentRedirect(url)
class HttpResponseSubclassesTests(SimpleTestCase): class HttpResponseSubclassesTests(SimpleTestCase):

View File

@ -77,7 +77,8 @@ class URLPrefixTests(URLTestCaseBase):
@override_settings(ROOT_URLCONF='i18n.patterns.urls.wrong') @override_settings(ROOT_URLCONF='i18n.patterns.urls.wrong')
def test_invalid_prefix_use(self): def test_invalid_prefix_use(self):
self.assertRaises(ImproperlyConfigured, lambda: reverse('account:register')) with self.assertRaises(ImproperlyConfigured):
reverse('account:register')
@override_settings(ROOT_URLCONF='i18n.patterns.urls.disabled') @override_settings(ROOT_URLCONF='i18n.patterns.urls.disabled')

View File

@ -1852,7 +1852,8 @@ class TranslationFilesMissing(SimpleTestCase):
''' '''
self.patchGettextFind() self.patchGettextFind()
trans_real._translations = {} trans_real._translations = {}
self.assertRaises(IOError, activate, 'en') with self.assertRaises(IOError):
activate('en')
class NonDjangoLanguageTests(SimpleTestCase): class NonDjangoLanguageTests(SimpleTestCase):

View File

@ -135,11 +135,9 @@ class InlineFormsetFactoryTest(TestCase):
If we specify fk_name, but it isn't a ForeignKey from the child model If we specify fk_name, but it isn't a ForeignKey from the child model
to the parent model, we should get an exception. to the parent model, we should get an exception.
""" """
self.assertRaises( msg = "fk_name 'school' is not a ForeignKey to 'inline_formsets.Parent'."
Exception, with self.assertRaisesMessage(ValueError, msg):
"fk_name 'school' is not a ForeignKey to <class 'inline_formsets.models.Parent'>", inlineformset_factory(Parent, Child, fk_name='school')
inlineformset_factory, Parent, Child, fk_name='school'
)
def test_non_foreign_key_field(self): def test_non_foreign_key_field(self):
""" """

View File

@ -136,7 +136,8 @@ class LookupTests(TestCase):
self.assertEqual(Article.objects.in_bulk([]), {}) self.assertEqual(Article.objects.in_bulk([]), {})
self.assertEqual(Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1}) self.assertEqual(Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1})
self.assertEqual(Article.objects.in_bulk(iter([])), {}) self.assertEqual(Article.objects.in_bulk(iter([])), {})
self.assertRaises(TypeError, Article.objects.in_bulk, headline__startswith='Blah') with self.assertRaises(TypeError):
Article.objects.in_bulk(headline__startswith='Blah')
def test_values(self): def test_values(self):
# values() returns a list of dictionaries instead of object instances -- # values() returns a list of dictionaries instead of object instances --
@ -260,9 +261,8 @@ class LookupTests(TestCase):
# However, an exception FieldDoesNotExist will be thrown if you specify # However, an exception FieldDoesNotExist will be thrown if you specify
# a non-existent field name in values() (a field that is neither in the # a non-existent field name in values() (a field that is neither in the
# model nor in extra(select)). # model nor in extra(select)).
self.assertRaises(FieldError, with self.assertRaises(FieldError):
Article.objects.extra(select={'id_plus_one': 'id + 1'}).values, Article.objects.extra(select={'id_plus_one': 'id + 1'}).values('id', 'id_plus_two')
'id', 'id_plus_two')
# If you don't specify field names to values(), all are returned. # If you don't specify field names to values(), all are returned.
self.assertQuerysetEqual(Article.objects.filter(id=self.a5.id).values(), self.assertQuerysetEqual(Article.objects.filter(id=self.a5.id).values(),
[{ [{
@ -344,7 +344,8 @@ class LookupTests(TestCase):
(self.au2.name, self.a6.headline, self.t3.name), (self.au2.name, self.a6.headline, self.t3.name),
(self.au2.name, self.a7.headline, self.t3.name), (self.au2.name, self.a7.headline, self.t3.name),
], transform=identity) ], transform=identity)
self.assertRaises(TypeError, Article.objects.values_list, 'id', 'headline', flat=True) with self.assertRaises(TypeError):
Article.objects.values_list('id', 'headline', flat=True)
def test_get_next_previous_by(self): def test_get_next_previous_by(self):
# Every DateField and DateTimeField creates get_next_by_FOO() and # Every DateField and DateTimeField creates get_next_by_FOO() and
@ -361,7 +362,8 @@ class LookupTests(TestCase):
'<Article: Article 7>') '<Article: Article 7>')
self.assertEqual(repr(self.a4.get_next_by_pub_date()), self.assertEqual(repr(self.a4.get_next_by_pub_date()),
'<Article: Article 6>') '<Article: Article 6>')
self.assertRaises(Article.DoesNotExist, self.a5.get_next_by_pub_date) with self.assertRaises(Article.DoesNotExist):
self.a5.get_next_by_pub_date()
self.assertEqual(repr(self.a6.get_next_by_pub_date()), self.assertEqual(repr(self.a6.get_next_by_pub_date()),
'<Article: Article 5>') '<Article: Article 5>')
self.assertEqual(repr(self.a7.get_next_by_pub_date()), self.assertEqual(repr(self.a7.get_next_by_pub_date()),

View File

@ -67,10 +67,12 @@ class M2MThroughTestCase(TestCase):
self.roll.members.set([]) self.roll.members.set([])
def test_cannot_use_create_on_m2m_with_intermediary_model(self): def test_cannot_use_create_on_m2m_with_intermediary_model(self):
self.assertRaises(AttributeError, self.rock.members.create, name="Anne") with self.assertRaises(AttributeError):
self.rock.members.create(name="Anne")
def test_cannot_use_create_on_reverse_m2m_with_intermediary_model(self): def test_cannot_use_create_on_reverse_m2m_with_intermediary_model(self):
self.assertRaises(AttributeError, self.bob.group_set.create, name="Funk") with self.assertRaises(AttributeError):
self.bob.group_set.create(name="Funk")
def test_retrieve_reverse_m2m_items_via_custom_id_intermediary(self): def test_retrieve_reverse_m2m_items_via_custom_id_intermediary(self):
self.assertQuerysetEqual( self.assertQuerysetEqual(

View File

@ -143,11 +143,13 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
def test_header_injection(self): def test_header_injection(self):
email = EmailMessage('Subject\nInjection Test', 'Content', 'from@example.com', ['to@example.com']) email = EmailMessage('Subject\nInjection Test', 'Content', 'from@example.com', ['to@example.com'])
self.assertRaises(BadHeaderError, email.message) with self.assertRaises(BadHeaderError):
email.message()
email = EmailMessage( email = EmailMessage(
ugettext_lazy('Subject\nInjection Test'), 'Content', 'from@example.com', ['to@example.com'] ugettext_lazy('Subject\nInjection Test'), 'Content', 'from@example.com', ['to@example.com']
) )
self.assertRaises(BadHeaderError, email.message) with self.assertRaises(BadHeaderError):
email.message()
def test_space_continuation(self): def test_space_continuation(self):
""" """
@ -1193,7 +1195,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
backend = smtp.EmailBackend() backend = smtp.EmailBackend()
self.assertTrue(backend.use_ssl) self.assertTrue(backend.use_ssl)
try: try:
self.assertRaises(SSLError, backend.open) with self.assertRaises(SSLError):
backend.open()
finally: finally:
backend.close() backend.close()

View File

@ -33,7 +33,8 @@ class ManyToManyTests(TestCase):
# Create an Article. # Create an Article.
a5 = Article(id=None, headline='Django lets you reate Web apps easily') a5 = Article(id=None, headline='Django lets you reate Web apps easily')
# You can't associate it with a Publication until it's been saved. # You can't associate it with a Publication until it's been saved.
self.assertRaises(ValueError, getattr, a5, 'publications') with self.assertRaises(ValueError):
getattr(a5, 'publications')
# Save it! # Save it!
a5.save() a5.save()
# Associate the Article with a Publication. # Associate the Article with a Publication.

View File

@ -455,8 +455,8 @@ class ManyToOneTests(TestCase):
self.assertEqual(a3.reporter.id, self.r2.id) self.assertEqual(a3.reporter.id, self.r2.id)
# Get should respect explicit foreign keys as well. # Get should respect explicit foreign keys as well.
self.assertRaises(MultipleObjectsReturned, with self.assertRaises(MultipleObjectsReturned):
Article.objects.get, reporter_id=self.r.id) Article.objects.get(reporter_id=self.r.id)
self.assertEqual(repr(a3), self.assertEqual(repr(a3),
repr(Article.objects.get(reporter_id=self.r2.id, repr(Article.objects.get(reporter_id=self.r2.id,
pub_date=datetime.date(2011, 5, 7)))) pub_date=datetime.date(2011, 5, 7))))
@ -537,15 +537,19 @@ class ManyToOneTests(TestCase):
self.assertIsNone(p.bestchild) self.assertIsNone(p.bestchild)
# Assigning None fails: Child.parent is null=False. # Assigning None fails: Child.parent is null=False.
self.assertRaises(ValueError, setattr, c, "parent", None) with self.assertRaises(ValueError):
setattr(c, "parent", None)
# You also can't assign an object of the wrong type here # You also can't assign an object of the wrong type here
self.assertRaises(ValueError, setattr, c, "parent", First(id=1, second=1)) with self.assertRaises(ValueError):
setattr(c, "parent", First(id=1, second=1))
# Nor can you explicitly assign None to Child.parent during object # Nor can you explicitly assign None to Child.parent during object
# creation (regression for #9649). # creation (regression for #9649).
self.assertRaises(ValueError, Child, name='xyzzy', parent=None) with self.assertRaises(ValueError):
self.assertRaises(ValueError, Child.objects.create, name='xyzzy', parent=None) Child(name='xyzzy', parent=None)
with self.assertRaises(ValueError):
Child.objects.create(name='xyzzy', parent=None)
# Creation using keyword argument should cache the related object. # Creation using keyword argument should cache the related object.
p = Parent.objects.get(name="Parent") p = Parent.objects.get(name="Parent")
@ -602,7 +606,8 @@ class ManyToOneTests(TestCase):
p = Parent.objects.create(name="Parent") p = Parent.objects.create(name="Parent")
c = Child.objects.create(name="Child", parent=p) c = Child.objects.create(name="Child", parent=p)
self.assertRaises(ValueError, Child.objects.create, name="Grandchild", parent=c) with self.assertRaises(ValueError):
Child.objects.create(name="Grandchild", parent=c)
def test_fk_instantiation_outside_model(self): def test_fk_instantiation_outside_model(self):
# Regression for #12190 -- Should be able to instantiate a FK outside # Regression for #12190 -- Should be able to instantiate a FK outside
@ -650,7 +655,8 @@ class ManyToOneTests(TestCase):
School.objects.use_for_related_fields = True School.objects.use_for_related_fields = True
try: try:
private_student = Student.objects.get(pk=private_student.pk) private_student = Student.objects.get(pk=private_student.pk)
self.assertRaises(School.DoesNotExist, lambda: private_student.school) with self.assertRaises(School.DoesNotExist):
private_student.school
finally: finally:
School.objects.use_for_related_fields = False School.objects.use_for_related_fields = False

View File

@ -44,7 +44,8 @@ class ManyToOneNullTests(TestCase):
self.assertEqual(self.a3.reporter, None) self.assertEqual(self.a3.reporter, None)
# Need to reget a3 to refresh the cache # Need to reget a3 to refresh the cache
a3 = Article.objects.get(pk=self.a3.pk) a3 = Article.objects.get(pk=self.a3.pk)
self.assertRaises(AttributeError, getattr, a3.reporter, 'id') with self.assertRaises(AttributeError):
getattr(a3.reporter, 'id')
# Accessing an article's 'reporter' attribute returns None # Accessing an article's 'reporter' attribute returns None
# if the reporter is set to None. # if the reporter is set to None.
self.assertEqual(a3.reporter, None) self.assertEqual(a3.reporter, None)
@ -71,7 +72,8 @@ class ManyToOneNullTests(TestCase):
def test_remove_from_wrong_set(self): def test_remove_from_wrong_set(self):
self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>']) self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>'])
# Try to remove a4 from a set it does not belong to # Try to remove a4 from a set it does not belong to
self.assertRaises(Reporter.DoesNotExist, self.r.article_set.remove, self.a4) with self.assertRaises(Reporter.DoesNotExist):
self.r.article_set.remove(self.a4)
self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>']) self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>'])
def test_set(self): def test_set(self):

View File

@ -238,8 +238,8 @@ class BaseTests(object):
reverse('show_message') reverse('show_message')
for level in ('debug', 'info', 'success', 'warning', 'error'): for level in ('debug', 'info', 'success', 'warning', 'error'):
add_url = reverse('add_message', args=(level,)) add_url = reverse('add_message', args=(level,))
self.assertRaises(MessageFailure, self.client.post, add_url, with self.assertRaises(MessageFailure):
data, follow=True) self.client.post(add_url, data, follow=True)
@modify_settings( @modify_settings(
INSTALLED_APPS={'remove': 'django.contrib.messages'}, INSTALLED_APPS={'remove': 'django.contrib.messages'},

View File

@ -862,7 +862,8 @@ class RootUrlconfTests(SimpleTestCase):
# Removing ROOT_URLCONF is safe, as override_settings will restore # Removing ROOT_URLCONF is safe, as override_settings will restore
# the previously defined settings. # the previously defined settings.
del settings.ROOT_URLCONF del settings.ROOT_URLCONF
self.assertRaises(AttributeError, self.client.get, "/middleware_exceptions/view/") with self.assertRaises(AttributeError):
self.client.get("/middleware_exceptions/view/")
class MyMiddleware(object): class MyMiddleware(object):

View File

@ -145,10 +145,8 @@ class GraphTests(SimpleTestCase):
graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_b", "0001")) graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_b", "0001"))
graph.add_dependency("app_b.0001", ("app_b", "0001"), ("app_a", "0003")) graph.add_dependency("app_b.0001", ("app_b", "0001"), ("app_a", "0003"))
# Test whole graph # Test whole graph
self.assertRaises( with self.assertRaises(CircularDependencyError):
CircularDependencyError, graph.forwards_plan(("app_a", "0003"), )
graph.forwards_plan, ("app_a", "0003"),
)
def test_circular_graph_2(self): def test_circular_graph_2(self):
graph = MigrationGraph() graph = MigrationGraph()
@ -159,10 +157,8 @@ class GraphTests(SimpleTestCase):
graph.add_dependency('B.0001', ('B', '0001'), ('A', '0001')) graph.add_dependency('B.0001', ('B', '0001'), ('A', '0001'))
graph.add_dependency('C.0001', ('C', '0001'), ('B', '0001')) graph.add_dependency('C.0001', ('C', '0001'), ('B', '0001'))
self.assertRaises( with self.assertRaises(CircularDependencyError):
CircularDependencyError, graph.forwards_plan(('C', '0001'))
graph.forwards_plan, ('C', '0001')
)
def test_graph_recursive(self): def test_graph_recursive(self):
graph = MigrationGraph() graph = MigrationGraph()

View File

@ -83,8 +83,10 @@ class ImageFieldTestMixin(SerializeMixin):
field = getattr(instance, field_name) field = getattr(instance, field_name)
# Check height/width attributes of field. # Check height/width attributes of field.
if width is None and height is None: if width is None and height is None:
self.assertRaises(ValueError, getattr, field, 'width') with self.assertRaises(ValueError):
self.assertRaises(ValueError, getattr, field, 'height') getattr(field, 'width')
with self.assertRaises(ValueError):
getattr(field, 'height')
else: else:
self.assertEqual(field.width, width) self.assertEqual(field.width, width)
self.assertEqual(field.height, height) self.assertEqual(field.height, height)

View File

@ -129,7 +129,8 @@ class DecimalFieldTests(test.TestCase):
f = models.DecimalField(max_digits=4, decimal_places=2) f = models.DecimalField(max_digits=4, decimal_places=2)
self.assertEqual(f.to_python(3), Decimal("3")) self.assertEqual(f.to_python(3), Decimal("3"))
self.assertEqual(f.to_python("3.14"), Decimal("3.14")) self.assertEqual(f.to_python("3.14"), Decimal("3.14"))
self.assertRaises(ValidationError, f.to_python, "abc") with self.assertRaises(ValidationError):
f.to_python("abc")
def test_default(self): def test_default(self):
f = models.DecimalField(default=Decimal("0.00")) f = models.DecimalField(default=Decimal("0.00"))
@ -598,7 +599,8 @@ class SlugFieldTests(test.TestCase):
class ValidationTest(test.SimpleTestCase): class ValidationTest(test.SimpleTestCase):
def test_charfield_raises_error_on_empty_string(self): def test_charfield_raises_error_on_empty_string(self):
f = models.CharField() f = models.CharField()
self.assertRaises(ValidationError, f.clean, "", None) with self.assertRaises(ValidationError):
f.clean("", None)
def test_charfield_cleans_empty_string_when_blank_true(self): def test_charfield_cleans_empty_string_when_blank_true(self):
f = models.CharField(blank=True) f = models.CharField(blank=True)
@ -610,7 +612,8 @@ class ValidationTest(test.SimpleTestCase):
def test_integerfield_raises_error_on_invalid_intput(self): def test_integerfield_raises_error_on_invalid_intput(self):
f = models.IntegerField() f = models.IntegerField()
self.assertRaises(ValidationError, f.clean, "a", None) with self.assertRaises(ValidationError):
f.clean("a", None)
def test_charfield_with_choices_cleans_valid_choice(self): def test_charfield_with_choices_cleans_valid_choice(self):
f = models.CharField(max_length=1, f = models.CharField(max_length=1,
@ -619,7 +622,8 @@ class ValidationTest(test.SimpleTestCase):
def test_charfield_with_choices_raises_error_on_invalid_choice(self): def test_charfield_with_choices_raises_error_on_invalid_choice(self):
f = models.CharField(choices=[('a', 'A'), ('b', 'B')]) f = models.CharField(choices=[('a', 'A'), ('b', 'B')])
self.assertRaises(ValidationError, f.clean, "not a", None) with self.assertRaises(ValidationError):
f.clean("not a", None)
def test_charfield_get_choices_with_blank_defined(self): def test_charfield_get_choices_with_blank_defined(self):
f = models.CharField(choices=[('', '<><>'), ('a', 'A')]) f = models.CharField(choices=[('', '<><>'), ('a', 'A')])
@ -639,7 +643,8 @@ class ValidationTest(test.SimpleTestCase):
def test_nullable_integerfield_raises_error_with_blank_false(self): def test_nullable_integerfield_raises_error_with_blank_false(self):
f = models.IntegerField(null=True, blank=False) f = models.IntegerField(null=True, blank=False)
self.assertRaises(ValidationError, f.clean, None, None) with self.assertRaises(ValidationError):
f.clean(None, None)
def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self): def test_nullable_integerfield_cleans_none_on_null_and_blank_true(self):
f = models.IntegerField(null=True, blank=True) f = models.IntegerField(null=True, blank=True)
@ -647,16 +652,20 @@ class ValidationTest(test.SimpleTestCase):
def test_integerfield_raises_error_on_empty_input(self): def test_integerfield_raises_error_on_empty_input(self):
f = models.IntegerField(null=False) f = models.IntegerField(null=False)
self.assertRaises(ValidationError, f.clean, None, None) with self.assertRaises(ValidationError):
self.assertRaises(ValidationError, f.clean, '', None) f.clean(None, None)
with self.assertRaises(ValidationError):
f.clean('', None)
def test_integerfield_validates_zero_against_choices(self): def test_integerfield_validates_zero_against_choices(self):
f = models.IntegerField(choices=((1, 1),)) f = models.IntegerField(choices=((1, 1),))
self.assertRaises(ValidationError, f.clean, '0', None) with self.assertRaises(ValidationError):
f.clean('0', None)
def test_charfield_raises_error_on_empty_input(self): def test_charfield_raises_error_on_empty_input(self):
f = models.CharField(null=False) f = models.CharField(null=False)
self.assertRaises(ValidationError, f.clean, None, None) with self.assertRaises(ValidationError):
f.clean(None, None)
def test_datefield_cleans_date(self): def test_datefield_cleans_date(self):
f = models.DateField() f = models.DateField()
@ -664,7 +673,8 @@ class ValidationTest(test.SimpleTestCase):
def test_boolean_field_doesnt_accept_empty_input(self): def test_boolean_field_doesnt_accept_empty_input(self):
f = models.BooleanField() f = models.BooleanField()
self.assertRaises(ValidationError, f.clean, None, None) with self.assertRaises(ValidationError):
f.clean(None, None)
class IntegerFieldTests(test.TestCase): class IntegerFieldTests(test.TestCase):
@ -864,7 +874,8 @@ class BinaryFieldTests(test.TestCase):
def test_max_length(self): def test_max_length(self):
dm = DataModel(short_data=self.binary_data * 4) dm = DataModel(short_data=self.binary_data * 4)
self.assertRaises(ValidationError, dm.full_clean) with self.assertRaises(ValidationError):
dm.full_clean()
class GenericIPAddressFieldTests(test.TestCase): class GenericIPAddressFieldTests(test.TestCase):
@ -875,10 +886,12 @@ class GenericIPAddressFieldTests(test.TestCase):
""" """
model_field = models.GenericIPAddressField(protocol='IPv4') model_field = models.GenericIPAddressField(protocol='IPv4')
form_field = model_field.formfield() form_field = model_field.formfield()
self.assertRaises(ValidationError, form_field.clean, '::1') with self.assertRaises(ValidationError):
form_field.clean('::1')
model_field = models.GenericIPAddressField(protocol='IPv6') model_field = models.GenericIPAddressField(protocol='IPv6')
form_field = model_field.formfield() form_field = model_field.formfield()
self.assertRaises(ValidationError, form_field.clean, '127.0.0.1') with self.assertRaises(ValidationError):
form_field.clean('127.0.0.1')
def test_null_value(self): def test_null_value(self):
""" """

View File

@ -177,7 +177,8 @@ class ModelFormBaseTest(TestCase):
def test_no_model_class(self): def test_no_model_class(self):
class NoModelModelForm(forms.ModelForm): class NoModelModelForm(forms.ModelForm):
pass pass
self.assertRaises(ValueError, NoModelModelForm) with self.assertRaises(ValueError):
NoModelModelForm()
def test_empty_fields_to_fields_for_model(self): def test_empty_fields_to_fields_for_model(self):
""" """
@ -282,8 +283,8 @@ class ModelFormBaseTest(TestCase):
self.fail('Declarative field raised FieldError incorrectly') self.fail('Declarative field raised FieldError incorrectly')
def test_extra_field_modelform_factory(self): def test_extra_field_modelform_factory(self):
self.assertRaises(FieldError, modelform_factory, with self.assertRaises(FieldError):
Person, fields=['no-field', 'name']) modelform_factory(Person, fields=['no-field', 'name'])
def test_replace_field(self): def test_replace_field(self):
class ReplaceField(forms.ModelForm): class ReplaceField(forms.ModelForm):
@ -1836,7 +1837,8 @@ class FileAndImageFieldTests(TestCase):
""" """
f = forms.FileField(required=True) f = forms.FileField(required=True)
self.assertEqual(f.clean(False, 'initial'), 'initial') self.assertEqual(f.clean(False, 'initial'), 'initial')
self.assertRaises(ValidationError, f.clean, False) with self.assertRaises(ValidationError):
f.clean(False)
def test_full_clear(self): def test_full_clear(self):
""" """
@ -2682,8 +2684,8 @@ class FormFieldCallbackTests(SimpleTestCase):
def test_bad_callback(self): def test_bad_callback(self):
# A bad callback provided by user still gives an error # A bad callback provided by user still gives an error
self.assertRaises(TypeError, modelform_factory, Person, fields="__all__", with self.assertRaises(TypeError):
formfield_callback='not a function or callable') modelform_factory(Person, fields="__all__", formfield_callback='not a function or callable')
class LocalizedModelFormTest(TestCase): class LocalizedModelFormTest(TestCase):

View File

@ -48,14 +48,16 @@ class ModelInheritanceTests(TestCase):
# However, the CommonInfo class cannot be used as a normal model (it # However, the CommonInfo class cannot be used as a normal model (it
# doesn't exist as a model). # doesn't exist as a model).
self.assertRaises(AttributeError, lambda: CommonInfo.objects.all()) with self.assertRaises(AttributeError):
CommonInfo.objects.all()
def test_reverse_relation_for_different_hierarchy_tree(self): def test_reverse_relation_for_different_hierarchy_tree(self):
# Even though p.supplier for a Place 'p' (a parent of a Supplier), a # Even though p.supplier for a Place 'p' (a parent of a Supplier), a
# Restaurant object cannot access that reverse relation, since it's not # Restaurant object cannot access that reverse relation, since it's not
# part of the Place-Supplier Hierarchy. # part of the Place-Supplier Hierarchy.
self.assertQuerysetEqual(Place.objects.filter(supplier__name="foo"), []) self.assertQuerysetEqual(Place.objects.filter(supplier__name="foo"), [])
self.assertRaises(FieldError, Restaurant.objects.filter, supplier__name="foo") with self.assertRaises(FieldError):
Restaurant.objects.filter(supplier__name="foo")
def test_model_with_distinct_accessors(self): def test_model_with_distinct_accessors(self):
# The Post model has distinct accessors for the Comment and Link models. # The Post model has distinct accessors for the Comment and Link models.
@ -68,9 +70,8 @@ class ModelInheritanceTests(TestCase):
# The Post model doesn't have an attribute called # The Post model doesn't have an attribute called
# 'attached_%(class)s_set'. # 'attached_%(class)s_set'.
self.assertRaises( with self.assertRaises(AttributeError):
AttributeError, getattr, post, "attached_%(class)s_set" getattr(post, "attached_%(class)s_set")
)
def test_model_with_distinct_related_query_name(self): def test_model_with_distinct_related_query_name(self):
self.assertQuerysetEqual(Post.objects.filter(attached_model_inheritance_comments__is_spam=True), []) self.assertQuerysetEqual(Post.objects.filter(attached_model_inheritance_comments__is_spam=True), [])
@ -220,25 +221,19 @@ class ModelInheritanceDataTests(TestCase):
def test_parent_child_one_to_one_link_on_nonrelated_objects(self): def test_parent_child_one_to_one_link_on_nonrelated_objects(self):
# This won't work because the Demon Dogs restaurant is not an Italian # This won't work because the Demon Dogs restaurant is not an Italian
# restaurant. # restaurant.
self.assertRaises( with self.assertRaises(ItalianRestaurant.DoesNotExist):
ItalianRestaurant.DoesNotExist, Place.objects.get(name="Demon Dogs").restaurant.italianrestaurant
lambda: Place.objects.get(name="Demon Dogs").restaurant.italianrestaurant
)
def test_inherited_does_not_exist_exception(self): def test_inherited_does_not_exist_exception(self):
# An ItalianRestaurant which does not exist is also a Place which does # An ItalianRestaurant which does not exist is also a Place which does
# not exist. # not exist.
self.assertRaises( with self.assertRaises(Place.DoesNotExist):
Place.DoesNotExist, ItalianRestaurant.objects.get(name="The Noodle Void")
ItalianRestaurant.objects.get, name="The Noodle Void"
)
def test_inherited_multiple_objects_returned_exception(self): def test_inherited_multiple_objects_returned_exception(self):
# MultipleObjectsReturned is also inherited. # MultipleObjectsReturned is also inherited.
self.assertRaises( with self.assertRaises(Place.MultipleObjectsReturned):
Place.MultipleObjectsReturned, Restaurant.objects.get(id__lt=12321)
Restaurant.objects.get, id__lt=12321
)
def test_related_objects_for_inherited_models(self): def test_related_objects_for_inherited_models(self):
# Related objects work just as they normally do. # Related objects work just as they normally do.
@ -250,9 +245,8 @@ class ModelInheritanceDataTests(TestCase):
# This won't work because the Place we select is not a Restaurant (it's # This won't work because the Place we select is not a Restaurant (it's
# a Supplier). # a Supplier).
p = Place.objects.get(name="Joe's Chickens") p = Place.objects.get(name="Joe's Chickens")
self.assertRaises( with self.assertRaises(Restaurant.DoesNotExist):
Restaurant.DoesNotExist, lambda: p.restaurant p.restaurant
)
self.assertEqual(p.supplier, s1) self.assertEqual(p.supplier, s1)
self.assertQuerysetEqual( self.assertQuerysetEqual(

View File

@ -171,14 +171,10 @@ class ModelInheritanceTest(TestCase):
# the ItalianRestaurant. # the ItalianRestaurant.
Restaurant.objects.all().delete() Restaurant.objects.all().delete()
self.assertRaises( with self.assertRaises(Place.DoesNotExist):
Place.DoesNotExist, Place.objects.get(pk=ident)
Place.objects.get, with self.assertRaises(ItalianRestaurant.DoesNotExist):
pk=ident) ItalianRestaurant.objects.get(pk=ident)
self.assertRaises(
ItalianRestaurant.DoesNotExist,
ItalianRestaurant.objects.get,
pk=ident)
def test_issue_6755(self): def test_issue_6755(self):
""" """
@ -241,14 +237,12 @@ class ModelInheritanceTest(TestCase):
self.assertEqual(c1.get_next_by_pub_date(), c2) self.assertEqual(c1.get_next_by_pub_date(), c2)
self.assertEqual(c2.get_next_by_pub_date(), c3) self.assertEqual(c2.get_next_by_pub_date(), c3)
self.assertRaises( with self.assertRaises(ArticleWithAuthor.DoesNotExist):
ArticleWithAuthor.DoesNotExist, c3.get_next_by_pub_date()
c3.get_next_by_pub_date)
self.assertEqual(c3.get_previous_by_pub_date(), c2) self.assertEqual(c3.get_previous_by_pub_date(), c2)
self.assertEqual(c2.get_previous_by_pub_date(), c1) self.assertEqual(c2.get_previous_by_pub_date(), c1)
self.assertRaises( with self.assertRaises(ArticleWithAuthor.DoesNotExist):
ArticleWithAuthor.DoesNotExist, c1.get_previous_by_pub_date()
c1.get_previous_by_pub_date)
def test_inherited_fields(self): def test_inherited_fields(self):
""" """

View File

@ -225,7 +225,8 @@ class ModelValidationTest(TestCase):
def test_pk_validation(self): def test_pk_validation(self):
NonAutoPK.objects.create(name="one") NonAutoPK.objects.create(name="one")
again = NonAutoPK(name="one") again = NonAutoPK(name="one")
self.assertRaises(ValidationError, again.validate_unique) with self.assertRaises(ValidationError):
again.validate_unique()
class EvaluateMethodTest(TestCase): class EvaluateMethodTest(TestCase):

View File

@ -49,11 +49,8 @@ class QueryTestCase(TestCase):
except Book.DoesNotExist: except Book.DoesNotExist:
self.fail('"Pro Django" should exist on default database') self.fail('"Pro Django" should exist on default database')
self.assertRaises( with self.assertRaises(Book.DoesNotExist):
Book.DoesNotExist, Book.objects.using('other').get(title="Pro Django")
Book.objects.using('other').get,
title="Pro Django"
)
try: try:
Book.objects.get(title="Dive into Python") Book.objects.get(title="Dive into Python")
@ -61,11 +58,8 @@ class QueryTestCase(TestCase):
except Book.DoesNotExist: except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on default database') self.fail('"Dive into Python" should exist on default database')
self.assertRaises( with self.assertRaises(Book.DoesNotExist):
Book.DoesNotExist, Book.objects.using('other').get(title="Dive into Python")
Book.objects.using('other').get,
title="Dive into Python"
)
def test_other_creation(self): def test_other_creation(self):
"Objects created on another database don't leak onto the default database" "Objects created on another database don't leak onto the default database"
@ -85,32 +79,20 @@ class QueryTestCase(TestCase):
except Book.DoesNotExist: except Book.DoesNotExist:
self.fail('"Pro Django" should exist on other database') self.fail('"Pro Django" should exist on other database')
self.assertRaises( with self.assertRaises(Book.DoesNotExist):
Book.DoesNotExist, Book.objects.get(title="Pro Django")
Book.objects.get, with self.assertRaises(Book.DoesNotExist):
title="Pro Django" Book.objects.using('default').get(title="Pro Django")
)
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('default').get,
title="Pro Django"
)
try: try:
Book.objects.using('other').get(title="Dive into Python") Book.objects.using('other').get(title="Dive into Python")
except Book.DoesNotExist: except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on other database') self.fail('"Dive into Python" should exist on other database')
self.assertRaises( with self.assertRaises(Book.DoesNotExist):
Book.DoesNotExist, Book.objects.get(title="Dive into Python")
Book.objects.get, with self.assertRaises(Book.DoesNotExist):
title="Dive into Python" Book.objects.using('default').get(title="Dive into Python")
)
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('default').get,
title="Dive into Python"
)
def test_refresh(self): def test_refresh(self):
dive = Book() dive = Book()
@ -137,20 +119,24 @@ class QueryTestCase(TestCase):
dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4)) dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4))
self.assertEqual(dive.title, "Dive into Python") self.assertEqual(dive.title, "Dive into Python")
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published=datetime.date(2009, 5, 4)) with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(published=datetime.date(2009, 5, 4))
dive = Book.objects.using('other').get(title__icontains="dive") dive = Book.objects.using('other').get(title__icontains="dive")
self.assertEqual(dive.title, "Dive into Python") self.assertEqual(dive.title, "Dive into Python")
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__icontains="dive") with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(title__icontains="dive")
dive = Book.objects.using('other').get(title__iexact="dive INTO python") dive = Book.objects.using('other').get(title__iexact="dive INTO python")
self.assertEqual(dive.title, "Dive into Python") self.assertEqual(dive.title, "Dive into Python")
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, title__iexact="dive INTO python") with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(title__iexact="dive INTO python")
dive = Book.objects.using('other').get(published__year=2009) dive = Book.objects.using('other').get(published__year=2009)
self.assertEqual(dive.title, "Dive into Python") self.assertEqual(dive.title, "Dive into Python")
self.assertEqual(dive.published, datetime.date(2009, 5, 4)) self.assertEqual(dive.published, datetime.date(2009, 5, 4))
self.assertRaises(Book.DoesNotExist, Book.objects.using('default').get, published__year=2009) with self.assertRaises(Book.DoesNotExist):
Book.objects.using('default').get(published__year=2009)
years = Book.objects.using('other').dates('published', 'year') years = Book.objects.using('other').dates('published', 'year')
self.assertEqual([o.year for o in years], [2009]) self.assertEqual([o.year for o in years], [2009])
@ -965,7 +951,8 @@ class QueryTestCase(TestCase):
# When you call __str__ on the query object, it doesn't know about using # When you call __str__ on the query object, it doesn't know about using
# so it falls back to the default. If the subquery explicitly uses a # so it falls back to the default. If the subquery explicitly uses a
# different database, an error should be raised. # different database, an error should be raised.
self.assertRaises(ValueError, str, qs.query) with self.assertRaises(ValueError):
str(qs.query)
# Evaluating the query shouldn't work, either # Evaluating the query shouldn't work, either
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@ -1605,7 +1592,8 @@ class AuthTestCase(TestCase):
self.assertEqual(alice.username, 'alice') self.assertEqual(alice.username, 'alice')
self.assertEqual(alice._state.db, 'other') self.assertEqual(alice._state.db, 'other')
self.assertRaises(User.DoesNotExist, User.objects.using('default').get, username='alice') with self.assertRaises(User.DoesNotExist):
User.objects.using('default').get(username='alice')
# The second user only exists on the default database # The second user only exists on the default database
bob = User.objects.using('default').get(username='bob') bob = User.objects.using('default').get(username='bob')
@ -1613,7 +1601,8 @@ class AuthTestCase(TestCase):
self.assertEqual(bob.username, 'bob') self.assertEqual(bob.username, 'bob')
self.assertEqual(bob._state.db, 'default') self.assertEqual(bob._state.db, 'default')
self.assertRaises(User.DoesNotExist, User.objects.using('other').get, username='bob') with self.assertRaises(User.DoesNotExist):
User.objects.using('other').get(username='bob')
# That is... there is one user on each database # That is... there is one user on each database
self.assertEqual(User.objects.using('default').count(), 1) self.assertEqual(User.objects.using('default').count(), 1)
@ -1663,11 +1652,8 @@ class FixtureTestCase(TestCase):
except Book.DoesNotExist: except Book.DoesNotExist:
self.fail('"Pro Django" should exist on default database') self.fail('"Pro Django" should exist on default database')
self.assertRaises( with self.assertRaises(Book.DoesNotExist):
Book.DoesNotExist, Book.objects.using('other').get(title="Pro Django")
Book.objects.using('other').get,
title="Pro Django"
)
# Check that "Dive into Python" exists on the default database, but not on other database # Check that "Dive into Python" exists on the default database, but not on other database
try: try:
@ -1675,16 +1661,10 @@ class FixtureTestCase(TestCase):
except Book.DoesNotExist: except Book.DoesNotExist:
self.fail('"Dive into Python" should exist on other database') self.fail('"Dive into Python" should exist on other database')
self.assertRaises( with self.assertRaises(Book.DoesNotExist):
Book.DoesNotExist, Book.objects.get(title="Dive into Python")
Book.objects.get, with self.assertRaises(Book.DoesNotExist):
title="Dive into Python" Book.objects.using('default').get(title="Dive into Python")
)
self.assertRaises(
Book.DoesNotExist,
Book.objects.using('default').get,
title="Dive into Python"
)
# Check that "Definitive Guide" exists on the both databases # Check that "Definitive Guide" exists on the both databases
try: try:
@ -1846,7 +1826,8 @@ class RouterAttributeErrorTestCase(TestCase):
b = Book.objects.create(title="Pro Django", b = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16)) published=datetime.date(2008, 12, 16))
with self.override_router(): with self.override_router():
self.assertRaises(AttributeError, Book.objects.get, pk=b.pk) with self.assertRaises(AttributeError):
Book.objects.get(pk=b.pk)
def test_attribute_error_save(self): def test_attribute_error_save(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up" "Check that the AttributeError from AttributeErrorRouter bubbles up"
@ -1854,7 +1835,8 @@ class RouterAttributeErrorTestCase(TestCase):
dive.title = "Dive into Python" dive.title = "Dive into Python"
dive.published = datetime.date(2009, 5, 4) dive.published = datetime.date(2009, 5, 4)
with self.override_router(): with self.override_router():
self.assertRaises(AttributeError, dive.save) with self.assertRaises(AttributeError):
dive.save()
def test_attribute_error_delete(self): def test_attribute_error_delete(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up" "Check that the AttributeError from AttributeErrorRouter bubbles up"
@ -1864,7 +1846,8 @@ class RouterAttributeErrorTestCase(TestCase):
b.authors.set([p]) b.authors.set([p])
b.editor = p b.editor = p
with self.override_router(): with self.override_router():
self.assertRaises(AttributeError, b.delete) with self.assertRaises(AttributeError):
b.delete()
def test_attribute_error_m2m(self): def test_attribute_error_m2m(self):
"Check that the AttributeError from AttributeErrorRouter bubbles up" "Check that the AttributeError from AttributeErrorRouter bubbles up"

View File

@ -40,10 +40,12 @@ class NullQueriesTests(TestCase):
) )
# Valid query, but fails because foo isn't a keyword # Valid query, but fails because foo isn't a keyword
self.assertRaises(FieldError, Choice.objects.filter, foo__exact=None) with self.assertRaises(FieldError):
Choice.objects.filter(foo__exact=None)
# Can't use None on anything other than __exact and __iexact # Can't use None on anything other than __exact and __iexact
self.assertRaises(ValueError, Choice.objects.filter, id__gt=None) with self.assertRaises(ValueError):
Choice.objects.filter(id__gt=None)
# Related managers use __exact=None implicitly if the object hasn't been saved. # Related managers use __exact=None implicitly if the object hasn't been saved.
p2 = Poll(question="How?") p2 = Poll(question="How?")

View File

@ -229,10 +229,12 @@ class OneToOneTests(TestCase):
self.assertIsNone(ug_bar.place) self.assertIsNone(ug_bar.place)
# Assigning None fails: Place.restaurant is null=False # Assigning None fails: Place.restaurant is null=False
self.assertRaises(ValueError, setattr, p, 'restaurant', None) with self.assertRaises(ValueError):
setattr(p, 'restaurant', None)
# You also can't assign an object of the wrong type here # You also can't assign an object of the wrong type here
self.assertRaises(ValueError, setattr, p, 'restaurant', p) with self.assertRaises(ValueError):
setattr(p, 'restaurant', p)
# Creation using keyword argument should cache the related object. # Creation using keyword argument should cache the related object.
p = Place.objects.get(name="Demon Dogs") p = Place.objects.get(name="Demon Dogs")
@ -459,14 +461,16 @@ class OneToOneTests(TestCase):
School.objects.use_for_related_fields = True School.objects.use_for_related_fields = True
try: try:
private_director = Director._base_manager.get(pk=private_director.pk) private_director = Director._base_manager.get(pk=private_director.pk)
self.assertRaises(School.DoesNotExist, lambda: private_director.school) with self.assertRaises(School.DoesNotExist):
private_director.school
finally: finally:
School.objects.use_for_related_fields = False School.objects.use_for_related_fields = False
Director.objects.use_for_related_fields = True Director.objects.use_for_related_fields = True
try: try:
private_school = School._base_manager.get(pk=private_school.pk) private_school = School._base_manager.get(pk=private_school.pk)
self.assertRaises(Director.DoesNotExist, lambda: private_school.director) with self.assertRaises(Director.DoesNotExist):
private_school.director
finally: finally:
Director.objects.use_for_related_fields = False Director.objects.use_for_related_fields = False

View File

@ -114,9 +114,12 @@ class PaginationTests(unittest.TestCase):
raised. raised.
""" """
paginator = Paginator([1, 2, 3], 2) paginator = Paginator([1, 2, 3], 2)
self.assertRaises(InvalidPage, paginator.page, 3) with self.assertRaises(InvalidPage):
self.assertRaises(PageNotAnInteger, paginator.validate_number, None) paginator.page(3)
self.assertRaises(PageNotAnInteger, paginator.validate_number, 'x') with self.assertRaises(PageNotAnInteger):
paginator.validate_number(None)
with self.assertRaises(PageNotAnInteger):
paginator.validate_number('x')
# With no content and allow_empty_first_page=True, 1 is a valid page number # With no content and allow_empty_first_page=True, 1 is a valid page number
paginator = Paginator([], 2) paginator = Paginator([], 2)
self.assertEqual(paginator.validate_number(1), 1) self.assertEqual(paginator.validate_number(1), 1)
@ -203,9 +206,12 @@ class PaginationTests(unittest.TestCase):
self.check_indexes(params, 'last', last) self.check_indexes(params, 'last', last)
# When no items and no empty first page, we should get EmptyPage error. # When no items and no empty first page, we should get EmptyPage error.
self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 0, False), 1, None) with self.assertRaises(EmptyPage):
self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 1, False), 1, None) self.check_indexes(([], 4, 0, False), 1, None)
self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 2, False), 1, None) with self.assertRaises(EmptyPage):
self.check_indexes(([], 4, 1, False), 1, None)
with self.assertRaises(EmptyPage):
self.check_indexes(([], 4, 2, False), 1, None)
def test_page_sequence(self): def test_page_sequence(self):
""" """
@ -267,7 +273,8 @@ class ModelPaginationTests(TestCase):
self.assertFalse(p.has_previous()) self.assertFalse(p.has_previous())
self.assertTrue(p.has_other_pages()) self.assertTrue(p.has_other_pages())
self.assertEqual(2, p.next_page_number()) self.assertEqual(2, p.next_page_number())
self.assertRaises(InvalidPage, p.previous_page_number) with self.assertRaises(InvalidPage):
p.previous_page_number()
self.assertEqual(1, p.start_index()) self.assertEqual(1, p.start_index())
self.assertEqual(5, p.end_index()) self.assertEqual(5, p.end_index())
@ -286,7 +293,8 @@ class ModelPaginationTests(TestCase):
self.assertFalse(p.has_next()) self.assertFalse(p.has_next())
self.assertTrue(p.has_previous()) self.assertTrue(p.has_previous())
self.assertTrue(p.has_other_pages()) self.assertTrue(p.has_other_pages())
self.assertRaises(InvalidPage, p.next_page_number) with self.assertRaises(InvalidPage):
p.next_page_number()
self.assertEqual(1, p.previous_page_number()) self.assertEqual(1, p.previous_page_number())
self.assertEqual(6, p.start_index()) self.assertEqual(6, p.start_index())
self.assertEqual(9, p.end_index()) self.assertEqual(9, p.end_index())
@ -302,7 +310,8 @@ class ModelPaginationTests(TestCase):
# Make sure object_list queryset is not evaluated by an invalid __getitem__ call. # Make sure object_list queryset is not evaluated by an invalid __getitem__ call.
# (this happens from the template engine when using eg: {% page_obj.has_previous %}) # (this happens from the template engine when using eg: {% page_obj.has_previous %})
self.assertIsNone(p.object_list._result_cache) self.assertIsNone(p.object_list._result_cache)
self.assertRaises(TypeError, lambda: p['has_previous']) with self.assertRaises(TypeError):
p['has_previous']
self.assertIsNone(p.object_list._result_cache) self.assertIsNone(p.object_list._result_cache)
self.assertNotIsInstance(p.object_list, list) self.assertNotIsInstance(p.object_list, list)

View File

@ -16,7 +16,8 @@ class PropertyTests(TestCase):
def test_setter(self): def test_setter(self):
# The "full_name" property hasn't provided a "set" method. # The "full_name" property hasn't provided a "set" method.
self.assertRaises(AttributeError, setattr, self.a, 'full_name', 'Paul McCartney') with self.assertRaises(AttributeError):
setattr(self.a, 'full_name', 'Paul McCartney')
# And cannot be used to initialize the class. # And cannot be used to initialize the class.
with self.assertRaisesMessage(TypeError, "'full_name' is an invalid keyword argument"): with self.assertRaisesMessage(TypeError, "'full_name' is an invalid keyword argument"):

View File

@ -93,31 +93,19 @@ class ProxyModelTests(TestCase):
LowerStatusPerson.objects.create(status="low", name="homer") LowerStatusPerson.objects.create(status="low", name="homer")
max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id'] max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']
self.assertRaises( with self.assertRaises(Person.DoesNotExist):
Person.DoesNotExist, MyPersonProxy.objects.get(name='Zathras')
MyPersonProxy.objects.get, with self.assertRaises(Person.MultipleObjectsReturned):
name='Zathras' MyPersonProxy.objects.get(id__lt=max_id + 1)
) with self.assertRaises(Person.DoesNotExist):
self.assertRaises( StatusPerson.objects.get(name='Zathras')
Person.MultipleObjectsReturned,
MyPersonProxy.objects.get,
id__lt=max_id + 1
)
self.assertRaises(
Person.DoesNotExist,
StatusPerson.objects.get,
name='Zathras'
)
StatusPerson.objects.create(name='Bazza Jr.') StatusPerson.objects.create(name='Bazza Jr.')
StatusPerson.objects.create(name='Foo Jr.') StatusPerson.objects.create(name='Foo Jr.')
max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id'] max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']
self.assertRaises( with self.assertRaises(Person.MultipleObjectsReturned):
Person.MultipleObjectsReturned, StatusPerson.objects.get(id__lt=max_id + 1)
StatusPerson.objects.get,
id__lt=max_id + 1
)
def test_abc(self): def test_abc(self):
""" """
@ -127,7 +115,8 @@ class ProxyModelTests(TestCase):
class NoAbstract(Abstract): class NoAbstract(Abstract):
class Meta: class Meta:
proxy = True proxy = True
self.assertRaises(TypeError, build_abc) with self.assertRaises(TypeError):
build_abc()
@isolate_apps('proxy_models') @isolate_apps('proxy_models')
def test_no_cbc(self): def test_no_cbc(self):
@ -138,7 +127,8 @@ class ProxyModelTests(TestCase):
class TooManyBases(Person, Abstract): class TooManyBases(Person, Abstract):
class Meta: class Meta:
proxy = True proxy = True
self.assertRaises(TypeError, build_no_cbc) with self.assertRaises(TypeError):
build_no_cbc()
@isolate_apps('proxy_models') @isolate_apps('proxy_models')
def test_no_base_classes(self): def test_no_base_classes(self):
@ -146,7 +136,8 @@ class ProxyModelTests(TestCase):
class NoBaseClasses(models.Model): class NoBaseClasses(models.Model):
class Meta: class Meta:
proxy = True proxy = True
self.assertRaises(TypeError, build_no_base_classes) with self.assertRaises(TypeError):
build_no_base_classes()
@isolate_apps('proxy_models') @isolate_apps('proxy_models')
def test_new_fields(self): def test_new_fields(self):

View File

@ -2930,7 +2930,8 @@ class WhereNodeTest(TestCase):
def test_empty_full_handling_conjunction(self): def test_empty_full_handling_conjunction(self):
compiler = WhereNodeTest.MockCompiler() compiler = WhereNodeTest.MockCompiler()
w = WhereNode(children=[NothingNode()]) w = WhereNode(children=[NothingNode()])
self.assertRaises(EmptyResultSet, w.as_sql, compiler, connection) with self.assertRaises(EmptyResultSet):
w.as_sql(compiler, connection)
w.negate() w.negate()
self.assertEqual(w.as_sql(compiler, connection), ('', [])) self.assertEqual(w.as_sql(compiler, connection), ('', []))
w = WhereNode(children=[self.DummyNode(), self.DummyNode()]) w = WhereNode(children=[self.DummyNode(), self.DummyNode()])
@ -2938,14 +2939,16 @@ class WhereNodeTest(TestCase):
w.negate() w.negate()
self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', [])) self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', []))
w = WhereNode(children=[NothingNode(), self.DummyNode()]) w = WhereNode(children=[NothingNode(), self.DummyNode()])
self.assertRaises(EmptyResultSet, w.as_sql, compiler, connection) with self.assertRaises(EmptyResultSet):
w.as_sql(compiler, connection)
w.negate() w.negate()
self.assertEqual(w.as_sql(compiler, connection), ('', [])) self.assertEqual(w.as_sql(compiler, connection), ('', []))
def test_empty_full_handling_disjunction(self): def test_empty_full_handling_disjunction(self):
compiler = WhereNodeTest.MockCompiler() compiler = WhereNodeTest.MockCompiler()
w = WhereNode(children=[NothingNode()], connector='OR') w = WhereNode(children=[NothingNode()], connector='OR')
self.assertRaises(EmptyResultSet, w.as_sql, compiler, connection) with self.assertRaises(EmptyResultSet):
w.as_sql(compiler, connection)
w.negate() w.negate()
self.assertEqual(w.as_sql(compiler, connection), ('', [])) self.assertEqual(w.as_sql(compiler, connection), ('', []))
w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR') w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR')
@ -2987,8 +2990,10 @@ class IteratorExceptionsTest(TestCase):
# Test for #19895 - second iteration over invalid queryset # Test for #19895 - second iteration over invalid queryset
# raises errors. # raises errors.
qs = Article.objects.order_by('invalid_column') qs = Article.objects.order_by('invalid_column')
self.assertRaises(FieldError, list, qs) with self.assertRaises(FieldError):
self.assertRaises(FieldError, list, qs) list(qs)
with self.assertRaises(FieldError):
list(qs)
class NullJoinPromotionOrTest(TestCase): class NullJoinPromotionOrTest(TestCase):

View File

@ -275,7 +275,8 @@ class RawQueryTests(TestCase):
first_two = Author.objects.raw(query)[0:2] first_two = Author.objects.raw(query)[0:2]
self.assertEqual(len(first_two), 2) self.assertEqual(len(first_two), 2)
self.assertRaises(TypeError, lambda: Author.objects.raw(query)['test']) with self.assertRaises(TypeError):
Author.objects.raw(query)['test']
def test_inheritance(self): def test_inheritance(self):
# date is the end of the Cuban Missile Crisis, I have no idea when # date is the end of the Cuban Missile Crisis, I have no idea when

View File

@ -345,7 +345,8 @@ class RequestsTests(SimpleTestCase):
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'wsgi.input': payload}) 'wsgi.input': payload})
self.assertEqual(request.read(2), b'na') self.assertEqual(request.read(2), b'na')
self.assertRaises(RawPostDataException, lambda: request.body) with self.assertRaises(RawPostDataException):
request.body
self.assertEqual(request.POST, {}) self.assertEqual(request.POST, {})
def test_non_ascii_POST(self): def test_non_ascii_POST(self):
@ -390,7 +391,8 @@ class RequestsTests(SimpleTestCase):
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'wsgi.input': payload}) 'wsgi.input': payload})
self.assertEqual(request.POST, {'name': ['value']}) self.assertEqual(request.POST, {'name': ['value']})
self.assertRaises(RawPostDataException, lambda: request.body) with self.assertRaises(RawPostDataException):
request.body
def test_body_after_POST_multipart_related(self): def test_body_after_POST_multipart_related(self):
""" """

View File

@ -127,7 +127,8 @@ class HttpResponseTests(SimpleTestCase):
generator = ("{}".format(i) for i in range(10)) generator = ("{}".format(i) for i in range(10))
response = HttpResponse(content=generator) response = HttpResponse(content=generator)
self.assertEqual(response.content, b'0123456789') self.assertEqual(response.content, b'0123456789')
self.assertRaises(StopIteration, next, generator) with self.assertRaises(StopIteration):
next(generator)
cache.set('my-response-key', response) cache.set('my-response-key', response)
response = cache.get('my-response-key') response = cache.get('my-response-key')

View File

@ -48,5 +48,5 @@ class ReverseLookupTests(TestCase):
""" """
If a related_name is given you can't use the field name instead If a related_name is given you can't use the field name instead
""" """
self.assertRaises(FieldError, Poll.objects.get, with self.assertRaises(FieldError):
choice__name__exact="This is the answer") Poll.objects.get(choice__name__exact="This is the answer")

View File

@ -139,10 +139,8 @@ class SchemaTests(TransactionTestCase):
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.delete_model(Author) editor.delete_model(Author)
# Check that it's gone # Check that it's gone
self.assertRaises( with self.assertRaises(DatabaseError):
DatabaseError, list(Author.objects.all())
lambda: list(Author.objects.all()),
)
@skipUnlessDBFeature('supports_foreign_keys') @skipUnlessDBFeature('supports_foreign_keys')
def test_fk(self): def test_fk(self):
@ -1026,7 +1024,8 @@ class SchemaTests(TransactionTestCase):
new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors") new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors")
new_field.contribute_to_class(LocalAuthorWithM2M, "tags") new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
# Ensure there's no m2m table there # Ensure there's no m2m table there
self.assertRaises(DatabaseError, self.column_classes, new_field.remote_field.through) with self.assertRaises(DatabaseError):
self.column_classes(new_field.remote_field.through)
# Add the field # Add the field
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.add_field(LocalAuthorWithM2M, new_field) editor.add_field(LocalAuthorWithM2M, new_field)
@ -1042,7 +1041,8 @@ class SchemaTests(TransactionTestCase):
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.remove_field(LocalAuthorWithM2M, new_field) editor.remove_field(LocalAuthorWithM2M, new_field)
# Ensure there's no m2m table there # Ensure there's no m2m table there
self.assertRaises(DatabaseError, self.column_classes, new_field.remote_field.through) with self.assertRaises(DatabaseError):
self.column_classes(new_field.remote_field.through)
# Make sure the model state is coherent with the table one now that # Make sure the model state is coherent with the table one now that
# we've removed the tags field. # we've removed the tags field.
@ -1145,10 +1145,8 @@ class SchemaTests(TransactionTestCase):
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.alter_field(LocalBookWithM2M, old_field, new_field) editor.alter_field(LocalBookWithM2M, old_field, new_field)
# Ensure old M2M is gone # Ensure old M2M is gone
self.assertRaises( with self.assertRaises(DatabaseError):
DatabaseError, self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through)
self.column_classes, LocalBookWithM2M._meta.get_field("tags").remote_field.through
)
# This model looks like the new model and is used for teardown. # This model looks like the new model and is used for teardown.
opts = LocalBookWithM2M._meta opts = LocalBookWithM2M._meta
@ -1217,7 +1215,8 @@ class SchemaTests(TransactionTestCase):
editor.create_model(Tag) editor.create_model(Tag)
# Ensure the field is unique to begin with # Ensure the field is unique to begin with
Tag.objects.create(title="foo", slug="foo") Tag.objects.create(title="foo", slug="foo")
self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo") with self.assertRaises(IntegrityError):
Tag.objects.create(title="bar", slug="foo")
Tag.objects.all().delete() Tag.objects.all().delete()
# Alter the slug field to be non-unique # Alter the slug field to be non-unique
old_field = Tag._meta.get_field("slug") old_field = Tag._meta.get_field("slug")
@ -1236,7 +1235,8 @@ class SchemaTests(TransactionTestCase):
editor.alter_field(Tag, new_field, new_field2, strict=True) editor.alter_field(Tag, new_field, new_field2, strict=True)
# Ensure the field is unique again # Ensure the field is unique again
Tag.objects.create(title="foo", slug="foo") Tag.objects.create(title="foo", slug="foo")
self.assertRaises(IntegrityError, Tag.objects.create, title="bar", slug="foo") with self.assertRaises(IntegrityError):
Tag.objects.create(title="bar", slug="foo")
Tag.objects.all().delete() Tag.objects.all().delete()
# Rename the field # Rename the field
new_field3 = SlugField(unique=True) new_field3 = SlugField(unique=True)
@ -1245,7 +1245,8 @@ class SchemaTests(TransactionTestCase):
editor.alter_field(Tag, new_field2, new_field3, strict=True) editor.alter_field(Tag, new_field2, new_field3, strict=True)
# Ensure the field is still unique # Ensure the field is still unique
TagUniqueRename.objects.create(title="foo", slug2="foo") TagUniqueRename.objects.create(title="foo", slug2="foo")
self.assertRaises(IntegrityError, TagUniqueRename.objects.create, title="bar", slug2="foo") with self.assertRaises(IntegrityError):
TagUniqueRename.objects.create(title="bar", slug2="foo")
Tag.objects.all().delete() Tag.objects.all().delete()
def test_unique_together(self): def test_unique_together(self):
@ -1259,7 +1260,8 @@ class SchemaTests(TransactionTestCase):
UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2012, slug="foo")
UniqueTest.objects.create(year=2011, slug="foo") UniqueTest.objects.create(year=2011, slug="foo")
UniqueTest.objects.create(year=2011, slug="bar") UniqueTest.objects.create(year=2011, slug="bar")
self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo") with self.assertRaises(IntegrityError):
UniqueTest.objects.create(year=2012, slug="foo")
UniqueTest.objects.all().delete() UniqueTest.objects.all().delete()
# Alter the model to its non-unique-together companion # Alter the model to its non-unique-together companion
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
@ -1275,7 +1277,8 @@ class SchemaTests(TransactionTestCase):
editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together) editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together)
# Ensure the fields are unique again # Ensure the fields are unique again
UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2012, slug="foo")
self.assertRaises(IntegrityError, UniqueTest.objects.create, year=2012, slug="foo") with self.assertRaises(IntegrityError):
UniqueTest.objects.create(year=2012, slug="foo")
UniqueTest.objects.all().delete() UniqueTest.objects.all().delete()
def test_unique_together_with_fk(self): def test_unique_together_with_fk(self):
@ -1576,10 +1579,8 @@ class SchemaTests(TransactionTestCase):
with connection.schema_editor() as editor: with connection.schema_editor() as editor:
editor.delete_model(Thing) editor.delete_model(Thing)
# Check that it's gone # Check that it's gone
self.assertRaises( with self.assertRaises(DatabaseError):
DatabaseError, list(Thing.objects.all())
lambda: list(Thing.objects.all()),
)
@skipUnlessDBFeature('supports_foreign_keys') @skipUnlessDBFeature('supports_foreign_keys')
def test_remove_constraints_capital_letters(self): def test_remove_constraints_capital_letters(self):

View File

@ -110,11 +110,8 @@ class SelectForUpdateTests(TransactionTestCase):
that supports FOR UPDATE but not NOWAIT, then we should find that supports FOR UPDATE but not NOWAIT, then we should find
that a DatabaseError is raised. that a DatabaseError is raised.
""" """
self.assertRaises( with self.assertRaises(DatabaseError):
DatabaseError, list(Person.objects.all().select_for_update(nowait=True))
list,
Person.objects.all().select_for_update(nowait=True)
)
@skipUnlessDBFeature('has_select_for_update') @skipUnlessDBFeature('has_select_for_update')
def test_for_update_requires_transaction(self): def test_for_update_requires_transaction(self):

View File

@ -142,11 +142,8 @@ class SelectRelatedTests(TestCase):
self.assertEqual(s, 'Diptera') self.assertEqual(s, 'Diptera')
def test_depth_fields_fails(self): def test_depth_fields_fails(self):
self.assertRaises( with self.assertRaises(TypeError):
TypeError, Species.objects.select_related('genus__family__order', depth=4)
Species.objects.select_related,
'genus__family__order', depth=4
)
def test_none_clears_list(self): def test_none_clears_list(self):
queryset = Species.objects.select_related('genus').select_related(None) queryset = Species.objects.select_related('genus').select_related(None)

View File

@ -72,11 +72,13 @@ class NoYamlSerializerTestCase(SimpleTestCase):
def test_serializer_pyyaml_error_message(self): def test_serializer_pyyaml_error_message(self):
"""Using yaml serializer without pyyaml raises ImportError""" """Using yaml serializer without pyyaml raises ImportError"""
jane = Author(name="Jane") jane = Author(name="Jane")
self.assertRaises(ImportError, serializers.serialize, "yaml", [jane]) with self.assertRaises(ImportError):
serializers.serialize("yaml", [jane])
def test_deserializer_pyyaml_error_message(self): def test_deserializer_pyyaml_error_message(self):
"""Using yaml deserializer without pyyaml raises ImportError""" """Using yaml deserializer without pyyaml raises ImportError"""
self.assertRaises(ImportError, serializers.deserialize, "yaml", "") with self.assertRaises(ImportError):
serializers.deserialize("yaml", "")
def test_dumpdata_pyyaml_error_message(self): def test_dumpdata_pyyaml_error_message(self):
"""Calling dumpdata produces an error when yaml package missing""" """Calling dumpdata produces an error when yaml package missing"""

View File

@ -223,7 +223,8 @@ class SessionTestsMixin(object):
def test_session_key_is_read_only(self): def test_session_key_is_read_only(self):
def set_session_key(session): def set_session_key(session):
session.session_key = session._get_new_session_key() session.session_key = session._get_new_session_key()
self.assertRaises(AttributeError, set_session_key, self.session) with self.assertRaises(AttributeError):
set_session_key(self.session)
# Custom session expiry # Custom session expiry
def test_default_expiry(self): def test_default_expiry(self):
@ -474,7 +475,8 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase):
@override_settings(SESSION_CACHE_ALIAS='sessions') @override_settings(SESSION_CACHE_ALIAS='sessions')
def test_non_default_cache(self): def test_non_default_cache(self):
# 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS. # 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS.
self.assertRaises(InvalidCacheBackendError, self.backend) with self.assertRaises(InvalidCacheBackendError):
self.backend()
@override_settings(USE_TZ=True) @override_settings(USE_TZ=True)
@ -506,20 +508,21 @@ class FileSessionTests(SessionTestsMixin, unittest.TestCase):
def test_configuration_check(self): def test_configuration_check(self):
del self.backend._storage_path del self.backend._storage_path
# Make sure the file backend checks for a good storage dir # Make sure the file backend checks for a good storage dir
self.assertRaises(ImproperlyConfigured, self.backend) with self.assertRaises(ImproperlyConfigured):
self.backend()
def test_invalid_key_backslash(self): def test_invalid_key_backslash(self):
# Ensure we don't allow directory-traversal. # Ensure we don't allow directory-traversal.
# This is tested directly on _key_to_file, as load() will swallow # This is tested directly on _key_to_file, as load() will swallow
# a SuspiciousOperation in the same way as an IOError - by creating # a SuspiciousOperation in the same way as an IOError - by creating
# a new session, making it unclear whether the slashes were detected. # a new session, making it unclear whether the slashes were detected.
self.assertRaises(InvalidSessionKey, with self.assertRaises(InvalidSessionKey):
self.backend()._key_to_file, "a\\b\\c") self.backend()._key_to_file("a\\b\\c")
def test_invalid_key_forwardslash(self): def test_invalid_key_forwardslash(self):
# Ensure we don't allow directory-traversal # Ensure we don't allow directory-traversal
self.assertRaises(InvalidSessionKey, with self.assertRaises(InvalidSessionKey):
self.backend()._key_to_file, "a/b/c") self.backend()._key_to_file("a/b/c")
@override_settings( @override_settings(
SESSION_ENGINE="django.contrib.sessions.backends.file", SESSION_ENGINE="django.contrib.sessions.backends.file",

View File

@ -179,24 +179,29 @@ class SettingsTests(SimpleTestCase):
del settings.TEST del settings.TEST
def test_override_doesnt_leak(self): def test_override_doesnt_leak(self):
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
getattr(settings, 'TEST')
with self.settings(TEST='override'): with self.settings(TEST='override'):
self.assertEqual('override', settings.TEST) self.assertEqual('override', settings.TEST)
settings.TEST = 'test' settings.TEST = 'test'
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
getattr(settings, 'TEST')
@override_settings(TEST='override') @override_settings(TEST='override')
def test_decorator(self): def test_decorator(self):
self.assertEqual('override', settings.TEST) self.assertEqual('override', settings.TEST)
def test_context_manager(self): def test_context_manager(self):
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
getattr(settings, 'TEST')
override = override_settings(TEST='override') override = override_settings(TEST='override')
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
getattr(settings, 'TEST')
override.enable() override.enable()
self.assertEqual('override', settings.TEST) self.assertEqual('override', settings.TEST)
override.disable() override.disable()
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
getattr(settings, 'TEST')
def test_class_decorator(self): def test_class_decorator(self):
# SimpleTestCase can be decorated by override_settings, but not ut.TestCase # SimpleTestCase can be decorated by override_settings, but not ut.TestCase
@ -215,7 +220,8 @@ class SettingsTests(SimpleTestCase):
decorated = override_settings(TEST='override')(UnittestTestCaseSubclass) decorated = override_settings(TEST='override')(UnittestTestCaseSubclass)
def test_signal_callback_context_manager(self): def test_signal_callback_context_manager(self):
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
getattr(settings, 'TEST')
with self.settings(TEST='override'): with self.settings(TEST='override'):
self.assertEqual(self.testvalue, 'override') self.assertEqual(self.testvalue, 'override')
self.assertEqual(self.testvalue, None) self.assertEqual(self.testvalue, None)
@ -232,10 +238,12 @@ class SettingsTests(SimpleTestCase):
settings.TEST = 'test' settings.TEST = 'test'
self.assertEqual('test', settings.TEST) self.assertEqual('test', settings.TEST)
del settings.TEST del settings.TEST
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
getattr(settings, 'TEST')
def test_settings_delete_wrapped(self): def test_settings_delete_wrapped(self):
self.assertRaises(TypeError, delattr, settings, '_wrapped') with self.assertRaises(TypeError):
delattr(settings, '_wrapped')
def test_override_settings_delete(self): def test_override_settings_delete(self):
""" """
@ -245,10 +253,12 @@ class SettingsTests(SimpleTestCase):
previous_l10n = settings.USE_L10N previous_l10n = settings.USE_L10N
with self.settings(USE_I18N=False): with self.settings(USE_I18N=False):
del settings.USE_I18N del settings.USE_I18N
self.assertRaises(AttributeError, getattr, settings, 'USE_I18N') with self.assertRaises(AttributeError):
getattr(settings, 'USE_I18N')
# Should also work for a non-overridden setting # Should also work for a non-overridden setting
del settings.USE_L10N del settings.USE_L10N
self.assertRaises(AttributeError, getattr, settings, 'USE_L10N') with self.assertRaises(AttributeError):
getattr(settings, 'USE_L10N')
self.assertEqual(settings.USE_I18N, previous_i18n) self.assertEqual(settings.USE_I18N, previous_i18n)
self.assertEqual(settings.USE_L10N, previous_l10n) self.assertEqual(settings.USE_L10N, previous_l10n)
@ -258,8 +268,10 @@ class SettingsTests(SimpleTestCase):
runtime, not when it was instantiated. runtime, not when it was instantiated.
""" """
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, getattr, settings, 'TEST2') getattr(settings, 'TEST')
with self.assertRaises(AttributeError):
getattr(settings, 'TEST2')
inner = override_settings(TEST2='override') inner = override_settings(TEST2='override')
with override_settings(TEST='override'): with override_settings(TEST='override'):
@ -270,10 +282,13 @@ class SettingsTests(SimpleTestCase):
# inner's __exit__ should have restored the settings of the outer # inner's __exit__ should have restored the settings of the outer
# context manager, not those when the class was instantiated # context manager, not those when the class was instantiated
self.assertEqual('override', settings.TEST) self.assertEqual('override', settings.TEST)
self.assertRaises(AttributeError, getattr, settings, 'TEST2') with self.assertRaises(AttributeError):
getattr(settings, 'TEST2')
self.assertRaises(AttributeError, getattr, settings, 'TEST') with self.assertRaises(AttributeError):
self.assertRaises(AttributeError, getattr, settings, 'TEST2') getattr(settings, 'TEST')
with self.assertRaises(AttributeError):
getattr(settings, 'TEST2')
class TestComplexSettingOverride(SimpleTestCase): class TestComplexSettingOverride(SimpleTestCase):

View File

@ -25,16 +25,16 @@ class SignedCookieTest(SimpleTestCase):
request.COOKIES['a'] = response.cookies['a'].value request.COOKIES['a'] = response.cookies['a'].value
value = request.get_signed_cookie('a', salt='one') value = request.get_signed_cookie('a', salt='one')
self.assertEqual(value, 'hello') self.assertEqual(value, 'hello')
self.assertRaises(signing.BadSignature, with self.assertRaises(signing.BadSignature):
request.get_signed_cookie, 'a', salt='two') request.get_signed_cookie('a', salt='two')
def test_detects_tampering(self): def test_detects_tampering(self):
response = HttpResponse() response = HttpResponse()
response.set_signed_cookie('c', 'hello') response.set_signed_cookie('c', 'hello')
request = HttpRequest() request = HttpRequest()
request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$' request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$'
self.assertRaises(signing.BadSignature, with self.assertRaises(signing.BadSignature):
request.get_signed_cookie, 'c') request.get_signed_cookie('c')
def test_default_argument_suppresses_exceptions(self): def test_default_argument_suppresses_exceptions(self):
response = HttpResponse() response = HttpResponse()
@ -55,8 +55,8 @@ class SignedCookieTest(SimpleTestCase):
with freeze_time(123456800): with freeze_time(123456800):
self.assertEqual(request.get_signed_cookie('c', max_age=12), value) self.assertEqual(request.get_signed_cookie('c', max_age=12), value)
self.assertEqual(request.get_signed_cookie('c', max_age=11), value) self.assertEqual(request.get_signed_cookie('c', max_age=11), value)
self.assertRaises(signing.SignatureExpired, with self.assertRaises(signing.SignatureExpired):
request.get_signed_cookie, 'c', max_age=10) request.get_signed_cookie('c', max_age=10)
@override_settings(SECRET_KEY=b'\xe7') @override_settings(SECRET_KEY=b'\xe7')
def test_signed_cookies_with_binary_key(self): def test_signed_cookies_with_binary_key(self):

View File

@ -70,8 +70,8 @@ class TestSigner(SimpleTestCase):
) )
self.assertEqual(value, signer.unsign(signed_value)) self.assertEqual(value, signer.unsign(signed_value))
for transform in transforms: for transform in transforms:
self.assertRaises( with self.assertRaises(signing.BadSignature):
signing.BadSignature, signer.unsign, transform(signed_value)) signer.unsign(transform(signed_value))
def test_dumps_loads(self): def test_dumps_loads(self):
"dumps and loads be reversible for any JSON serializable object" "dumps and loads be reversible for any JSON serializable object"
@ -103,8 +103,8 @@ class TestSigner(SimpleTestCase):
encoded = signing.dumps(value) encoded = signing.dumps(value)
self.assertEqual(value, signing.loads(encoded)) self.assertEqual(value, signing.loads(encoded))
for transform in transforms: for transform in transforms:
self.assertRaises( with self.assertRaises(signing.BadSignature):
signing.BadSignature, signing.loads, transform(encoded)) signing.loads(transform(encoded))
def test_works_with_non_ascii_keys(self): def test_works_with_non_ascii_keys(self):
binary_key = b'\xe7' # Set some binary (non-ASCII key) binary_key = b'\xe7' # Set some binary (non-ASCII key)
@ -142,4 +142,5 @@ class TestTimestampSigner(SimpleTestCase):
self.assertEqual(signer.unsign(ts, max_age=12), value) self.assertEqual(signer.unsign(ts, max_age=12), value)
# max_age parameter can also accept a datetime.timedelta object # max_age parameter can also accept a datetime.timedelta object
self.assertEqual(signer.unsign(ts, max_age=datetime.timedelta(seconds=11)), value) self.assertEqual(signer.unsign(ts, max_age=datetime.timedelta(seconds=11)), value)
self.assertRaises(signing.SignatureExpired, signer.unsign, ts, max_age=10) with self.assertRaises(signing.SignatureExpired):
signer.unsign(ts, max_age=10)

View File

@ -176,7 +176,8 @@ class HTTPSitemapTests(SitemapTestsBase):
Sitemap.get_urls and no Site objects exist Sitemap.get_urls and no Site objects exist
""" """
Site.objects.all().delete() Site.objects.all().delete()
self.assertRaises(ImproperlyConfigured, Sitemap().get_urls) with self.assertRaises(ImproperlyConfigured):
Sitemap().get_urls()
@modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}) @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'})
def test_sitemap_get_urls_no_site_2(self): def test_sitemap_get_urls_no_site_2(self):
@ -185,7 +186,8 @@ class HTTPSitemapTests(SitemapTestsBase):
Sitemap.get_urls if Site objects exists, but the sites framework is not Sitemap.get_urls if Site objects exists, but the sites framework is not
actually installed. actually installed.
""" """
self.assertRaises(ImproperlyConfigured, Sitemap().get_urls) with self.assertRaises(ImproperlyConfigured):
Sitemap().get_urls()
def test_sitemap_item(self): def test_sitemap_item(self):
""" """

View File

@ -35,7 +35,8 @@ class SitesFrameworkTests(TestCase):
s = Site.objects.get_current() s = Site.objects.get_current()
self.assertIsInstance(s, Site) self.assertIsInstance(s, Site)
s.delete() s.delete()
self.assertRaises(ObjectDoesNotExist, Site.objects.get_current) with self.assertRaises(ObjectDoesNotExist):
Site.objects.get_current()
def test_site_cache(self): def test_site_cache(self):
# After updating a Site object (e.g. via the admin), we shouldn't return a # After updating a Site object (e.g. via the admin), we shouldn't return a
@ -53,7 +54,8 @@ class SitesFrameworkTests(TestCase):
# be cleared and get_current() should raise a DoesNotExist. # be cleared and get_current() should raise a DoesNotExist.
self.assertIsInstance(Site.objects.get_current(), Site) self.assertIsInstance(Site.objects.get_current(), Site)
Site.objects.all().delete() Site.objects.all().delete()
self.assertRaises(Site.DoesNotExist, Site.objects.get_current) with self.assertRaises(Site.DoesNotExist):
Site.objects.get_current()
@override_settings(ALLOWED_HOSTS=['example.com']) @override_settings(ALLOWED_HOSTS=['example.com'])
def test_get_current_site(self): def test_get_current_site(self):
@ -70,7 +72,8 @@ class SitesFrameworkTests(TestCase):
# Test that an exception is raised if the sites framework is installed # Test that an exception is raised if the sites framework is installed
# but there is no matching Site # but there is no matching Site
site.delete() site.delete()
self.assertRaises(ObjectDoesNotExist, get_current_site, request) with self.assertRaises(ObjectDoesNotExist):
get_current_site(request)
# A RequestSite is returned if the sites framework is not installed # A RequestSite is returned if the sites framework is not installed
with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}): with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}):
@ -112,7 +115,8 @@ class SitesFrameworkTests(TestCase):
# Host header with non-matching domain # Host header with non-matching domain
request.META = {'HTTP_HOST': 'example.net'} request.META = {'HTTP_HOST': 'example.net'}
self.assertRaises(ObjectDoesNotExist, get_current_site, request) with self.assertRaises(ObjectDoesNotExist):
get_current_site(request)
# Ensure domain for RequestSite always matches host header # Ensure domain for RequestSite always matches host header
with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}): with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}):
@ -128,11 +132,14 @@ class SitesFrameworkTests(TestCase):
# Regression for #17320 # Regression for #17320
# Domain names are not allowed contain whitespace characters # Domain names are not allowed contain whitespace characters
site = Site(name="test name", domain="test test") site = Site(name="test name", domain="test test")
self.assertRaises(ValidationError, site.full_clean) with self.assertRaises(ValidationError):
site.full_clean()
site.domain = "test\ttest" site.domain = "test\ttest"
self.assertRaises(ValidationError, site.full_clean) with self.assertRaises(ValidationError):
site.full_clean()
site.domain = "test\ntest" site.domain = "test\ntest"
self.assertRaises(ValidationError, site.full_clean) with self.assertRaises(ValidationError):
site.full_clean()
def test_clear_site_cache(self): def test_clear_site_cache(self):
request = HttpRequest() request = HttpRequest()

Some files were not shown because too many files have changed in this diff Show More