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:
parent
575706331b
commit
3d0dcd7f5a
@ -850,7 +850,8 @@ class ListFiltersTests(TestCase):
|
||||
"""
|
||||
modeladmin = DecadeFilterBookAdminWithFailingQueryset(Book, site)
|
||||
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):
|
||||
modeladmin = DecadeFilterBookAdminWithQuerysetBasedLookups(Book, site)
|
||||
|
@ -36,9 +36,8 @@ class TestRegistration(SimpleTestCase):
|
||||
|
||||
def test_prevent_double_registration(self):
|
||||
self.site.register(Person)
|
||||
self.assertRaises(admin.sites.AlreadyRegistered,
|
||||
self.site.register,
|
||||
Person)
|
||||
with self.assertRaises(admin.sites.AlreadyRegistered):
|
||||
self.site.register(Person)
|
||||
|
||||
def test_registration_with_star_star_options(self):
|
||||
self.site.register(Person, search_fields=['name'])
|
||||
@ -68,7 +67,8 @@ class TestRegistration(SimpleTestCase):
|
||||
Exception is raised when trying to register an abstract model.
|
||||
Refs #12004.
|
||||
"""
|
||||
self.assertRaises(ImproperlyConfigured, self.site.register, Location)
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
self.site.register(Location)
|
||||
|
||||
def test_is_registered_model(self):
|
||||
"Checks for registered models should return true."
|
||||
|
@ -221,10 +221,8 @@ class UtilsTests(SimpleTestCase):
|
||||
str("article")
|
||||
)
|
||||
|
||||
self.assertRaises(
|
||||
AttributeError,
|
||||
lambda: label_for_field("unknown", Article)
|
||||
)
|
||||
with self.assertRaises(AttributeError):
|
||||
label_for_field("unknown", Article)
|
||||
|
||||
def test_callable(obj):
|
||||
return "nothing"
|
||||
|
@ -376,20 +376,14 @@ class AggregationTests(TestCase):
|
||||
|
||||
def test_field_error(self):
|
||||
# Bad field requests in aggregates are caught and reported
|
||||
self.assertRaises(
|
||||
FieldError,
|
||||
lambda: Book.objects.all().aggregate(num_authors=Count('foo'))
|
||||
)
|
||||
with self.assertRaises(FieldError):
|
||||
Book.objects.all().aggregate(num_authors=Count('foo'))
|
||||
|
||||
self.assertRaises(
|
||||
FieldError,
|
||||
lambda: Book.objects.all().annotate(num_authors=Count('foo'))
|
||||
)
|
||||
with self.assertRaises(FieldError):
|
||||
Book.objects.all().annotate(num_authors=Count('foo'))
|
||||
|
||||
self.assertRaises(
|
||||
FieldError,
|
||||
lambda: Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
|
||||
)
|
||||
with self.assertRaises(FieldError):
|
||||
Book.objects.all().annotate(num_authors=Count('authors__id')).aggregate(Max('foo'))
|
||||
|
||||
def test_more(self):
|
||||
# Old-style count aggregations can be mixed with new-style
|
||||
@ -698,21 +692,20 @@ class AggregationTests(TestCase):
|
||||
|
||||
def test_duplicate_alias(self):
|
||||
# Regression for #11256 - duplicating a default alias raises ValueError.
|
||||
self.assertRaises(
|
||||
ValueError,
|
||||
Book.objects.all().annotate,
|
||||
Avg('authors__age'), authors__age__avg=Avg('authors__age')
|
||||
)
|
||||
with self.assertRaises(ValueError):
|
||||
Book.objects.all().annotate(Avg('authors__age'), authors__age__avg=Avg('authors__age'))
|
||||
|
||||
def test_field_name_conflict(self):
|
||||
# Regression for #11256 - providing an aggregate name
|
||||
# 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):
|
||||
# Regression for #11256 - providing an aggregate name
|
||||
# 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):
|
||||
# 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):
|
||||
# Regression for #11256 - providing an aggregate name
|
||||
# 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):
|
||||
# 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
|
||||
# fields in an aggregate() call.
|
||||
self.assertRaises(
|
||||
FieldError,
|
||||
lambda: Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age'))
|
||||
)
|
||||
with self.assertRaises(FieldError):
|
||||
Book.objects.annotate(mean_age=Avg('authors__age')).annotate(Avg('mean_age'))
|
||||
|
||||
def test_empty_filter_count(self):
|
||||
self.assertEqual(
|
||||
|
@ -429,7 +429,8 @@ class NoBackendsTest(TestCase):
|
||||
self.user = User.objects.create_user('test', 'test@example.com', 'test')
|
||||
|
||||
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'])
|
||||
@ -575,7 +576,8 @@ class TypeErrorBackendTest(TestCase):
|
||||
|
||||
@override_settings(AUTHENTICATION_BACKENDS=[backend])
|
||||
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):
|
||||
@ -598,7 +600,8 @@ class ImproperlyConfiguredUserModelTest(TestCase):
|
||||
request = HttpRequest()
|
||||
request.session = self.client.session
|
||||
|
||||
self.assertRaises(ImproperlyConfigured, get_user, request)
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
get_user(request)
|
||||
|
||||
|
||||
class ImportedModelBackend(ModelBackend):
|
||||
|
@ -115,4 +115,5 @@ class PermissionsRequiredDecoratorTest(TestCase):
|
||||
return HttpResponse()
|
||||
request = self.factory.get('/rand')
|
||||
request.user = self.user
|
||||
self.assertRaises(PermissionDenied, a_view, request)
|
||||
with self.assertRaises(PermissionDenied):
|
||||
a_view(request)
|
||||
|
@ -219,7 +219,8 @@ class TestUtilsHashPass(SimpleTestCase):
|
||||
self.assertFalse(check_password('', encoded))
|
||||
self.assertFalse(check_password('lètmein', 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.
|
||||
# This might fail one day due to a hash collision.
|
||||
self.assertNotEqual(encoded, make_password(None), "Random password collision?")
|
||||
@ -234,7 +235,8 @@ class TestUtilsHashPass(SimpleTestCase):
|
||||
def test_bad_algorithm(self):
|
||||
with self.assertRaises(ValueError):
|
||||
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):
|
||||
self.assertFalse(is_password_usable('lètmein_badencoded'))
|
||||
|
@ -135,7 +135,8 @@ class UserPassesTestTests(TestCase):
|
||||
|
||||
request = self.factory.get('/rand')
|
||||
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):
|
||||
msg = "You don't have access here"
|
||||
@ -248,4 +249,5 @@ class PermissionsRequiredMixinTests(TestCase):
|
||||
|
||||
request = self.factory.get('/rand')
|
||||
request.user = self.user
|
||||
self.assertRaises(PermissionDenied, AView.as_view(), request)
|
||||
with self.assertRaises(PermissionDenied):
|
||||
AView.as_view()(request)
|
||||
|
@ -63,6 +63,5 @@ class TokenGeneratorTest(TestCase):
|
||||
p0 = PasswordResetTokenGenerator()
|
||||
|
||||
# This will put a 14-digit base36 timestamp into the token, which is too large.
|
||||
self.assertRaises(ValueError,
|
||||
p0._make_token_with_timestamp,
|
||||
user, 175455491841851871349)
|
||||
with self.assertRaises(ValueError):
|
||||
p0._make_token_with_timestamp(user, 175455491841851871349)
|
||||
|
@ -128,19 +128,16 @@ class SQLiteTests(TestCase):
|
||||
#19360: Raise NotImplementedError when aggregating on date/time fields.
|
||||
"""
|
||||
for aggregate in (Sum, Avg, Variance, StdDev):
|
||||
self.assertRaises(
|
||||
NotImplementedError,
|
||||
models.Item.objects.all().aggregate, aggregate('time'))
|
||||
self.assertRaises(
|
||||
NotImplementedError,
|
||||
models.Item.objects.all().aggregate, aggregate('date'))
|
||||
self.assertRaises(
|
||||
NotImplementedError,
|
||||
models.Item.objects.all().aggregate, aggregate('last_modified'))
|
||||
self.assertRaises(
|
||||
NotImplementedError,
|
||||
models.Item.objects.all().aggregate,
|
||||
**{'complex': aggregate('last_modified') + aggregate('last_modified')})
|
||||
with self.assertRaises(NotImplementedError):
|
||||
models.Item.objects.all().aggregate(aggregate('time'))
|
||||
with self.assertRaises(NotImplementedError):
|
||||
models.Item.objects.all().aggregate(aggregate('date'))
|
||||
with self.assertRaises(NotImplementedError):
|
||||
models.Item.objects.all().aggregate(aggregate('last_modified'))
|
||||
with self.assertRaises(NotImplementedError):
|
||||
models.Item.objects.all().aggregate(
|
||||
**{'complex': aggregate('last_modified') + aggregate('last_modified')}
|
||||
)
|
||||
|
||||
def test_memory_db_test_name(self):
|
||||
"""
|
||||
@ -449,8 +446,10 @@ class ParameterHandlingTest(TestCase):
|
||||
connection.ops.quote_name('root'),
|
||||
connection.ops.quote_name('square')
|
||||
))
|
||||
self.assertRaises(Exception, cursor.executemany, query, [(1, 2, 3)])
|
||||
self.assertRaises(Exception, cursor.executemany, query, [(1,)])
|
||||
with self.assertRaises(Exception):
|
||||
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
|
||||
@ -859,7 +858,8 @@ class FkConstraintsTests(TransactionTestCase):
|
||||
a2 = models.Article(headline='This is another test', reporter=self.r,
|
||||
pub_date=datetime.datetime(2012, 8, 3),
|
||||
reporter_proxy_id=30)
|
||||
self.assertRaises(IntegrityError, a2.save)
|
||||
with self.assertRaises(IntegrityError):
|
||||
a2.save()
|
||||
|
||||
def test_integrity_checks_on_update(self):
|
||||
"""
|
||||
@ -887,7 +887,8 @@ class FkConstraintsTests(TransactionTestCase):
|
||||
# Retrieve the second article from the DB
|
||||
a2 = models.Article.objects.get(headline='Another article')
|
||||
a2.reporter_proxy_id = 30
|
||||
self.assertRaises(IntegrityError, a2.save)
|
||||
with self.assertRaises(IntegrityError):
|
||||
a2.save()
|
||||
|
||||
def test_disable_constraint_checks_manually(self):
|
||||
"""
|
||||
|
@ -499,12 +499,8 @@ class ModelLookupTest(TestCase):
|
||||
)
|
||||
# To avoid dict-ordering related errors check only one lookup
|
||||
# in single assert.
|
||||
self.assertRaises(
|
||||
ObjectDoesNotExist,
|
||||
Article.objects.get,
|
||||
pub_date__year=2005,
|
||||
pub_date__month=8,
|
||||
)
|
||||
with self.assertRaises(ObjectDoesNotExist):
|
||||
Article.objects.get(pub_date__year=2005, pub_date__month=8)
|
||||
six.assertRaisesRegex(
|
||||
self,
|
||||
ObjectDoesNotExist,
|
||||
|
42
tests/cache/tests.py
vendored
42
tests/cache/tests.py
vendored
@ -129,14 +129,18 @@ class DummyCacheTests(SimpleTestCase):
|
||||
def test_incr(self):
|
||||
"Dummy cache values can't be incremented"
|
||||
cache.set('answer', 42)
|
||||
self.assertRaises(ValueError, cache.incr, 'answer')
|
||||
self.assertRaises(ValueError, cache.incr, 'does_not_exist')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.incr('answer')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.incr('does_not_exist')
|
||||
|
||||
def test_decr(self):
|
||||
"Dummy cache values can't be decremented"
|
||||
cache.set('answer', 42)
|
||||
self.assertRaises(ValueError, cache.decr, 'answer')
|
||||
self.assertRaises(ValueError, cache.decr, 'does_not_exist')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.decr('answer')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.decr('does_not_exist')
|
||||
|
||||
def test_data_types(self):
|
||||
"All data types are ignored equally by the dummy cache"
|
||||
@ -193,14 +197,18 @@ class DummyCacheTests(SimpleTestCase):
|
||||
def test_incr_version(self):
|
||||
"Dummy cache versions can't be incremented"
|
||||
cache.set('answer', 42)
|
||||
self.assertRaises(ValueError, cache.incr_version, 'answer')
|
||||
self.assertRaises(ValueError, cache.incr_version, 'does_not_exist')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.incr_version('answer')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.incr_version('does_not_exist')
|
||||
|
||||
def test_decr_version(self):
|
||||
"Dummy cache versions can't be decremented"
|
||||
cache.set('answer', 42)
|
||||
self.assertRaises(ValueError, cache.decr_version, 'answer')
|
||||
self.assertRaises(ValueError, cache.decr_version, 'does_not_exist')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.decr_version('answer')
|
||||
with self.assertRaises(ValueError):
|
||||
cache.decr_version('does_not_exist')
|
||||
|
||||
def test_get_or_set(self):
|
||||
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.get('answer'), 52)
|
||||
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):
|
||||
# Cache values can be decremented
|
||||
@ -331,7 +340,8 @@ class BaseCacheTests(object):
|
||||
self.assertEqual(cache.decr('answer', 10), 32)
|
||||
self.assertEqual(cache.get('answer'), 32)
|
||||
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):
|
||||
self.assertTrue(hasattr(cache, 'close'))
|
||||
@ -821,7 +831,8 @@ class BaseCacheTests(object):
|
||||
self.assertIsNone(caches['v2'].get('answer2', version=2))
|
||||
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):
|
||||
cache.set('answer', 42, version=2)
|
||||
@ -844,7 +855,8 @@ class BaseCacheTests(object):
|
||||
self.assertEqual(caches['v2'].get('answer2', version=1), 42)
|
||||
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):
|
||||
# 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.
|
||||
"""
|
||||
# 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
|
||||
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
|
||||
@unittest.skipUnless(
|
||||
|
@ -161,7 +161,8 @@ class CheckCommandTests(SimpleTestCase):
|
||||
|
||||
@override_system_checks([simple_system_check, tagged_system_check])
|
||||
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])
|
||||
def test_list_tags_empty(self):
|
||||
|
@ -208,7 +208,8 @@ class ContentTypesTests(TestCase):
|
||||
user_ct = ContentType.objects.get_for_model(FooWithoutUrl)
|
||||
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):
|
||||
"""
|
||||
@ -224,7 +225,8 @@ class ContentTypesTests(TestCase):
|
||||
user_ct = ContentType.objects.get_for_model(FooWithBrokenAbsoluteUrl)
|
||||
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):
|
||||
"""
|
||||
|
@ -40,10 +40,8 @@ class CustomColumnsTests(TestCase):
|
||||
)
|
||||
|
||||
def test_field_error(self):
|
||||
self.assertRaises(
|
||||
FieldError,
|
||||
lambda: Author.objects.filter(firstname__exact="John")
|
||||
)
|
||||
with self.assertRaises(FieldError):
|
||||
Author.objects.filter(firstname__exact="John")
|
||||
|
||||
def test_attribute_error(self):
|
||||
with self.assertRaises(AttributeError):
|
||||
|
@ -115,7 +115,8 @@ class CustomManagerTests(TestCase):
|
||||
The default manager, "objects", doesn't exist, because a custom one
|
||||
was provided.
|
||||
"""
|
||||
self.assertRaises(AttributeError, lambda: Book.objects)
|
||||
with self.assertRaises(AttributeError):
|
||||
Book.objects
|
||||
|
||||
def test_filtering(self):
|
||||
"""
|
||||
|
@ -131,10 +131,8 @@ class BasicCustomPKTests(TestCase):
|
||||
self.assertEqual(Employee.objects.get(pk=123), self.dan)
|
||||
self.assertEqual(Employee.objects.get(pk=456), self.fran)
|
||||
|
||||
self.assertRaises(
|
||||
Employee.DoesNotExist,
|
||||
lambda: Employee.objects.get(pk=42)
|
||||
)
|
||||
with self.assertRaises(Employee.DoesNotExist):
|
||||
Employee.objects.get(pk=42)
|
||||
|
||||
# Use the name of the primary key, rather than pk.
|
||||
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:
|
||||
self.assertEqual(e.employee_code, 123)
|
||||
|
||||
self.assertRaises(AttributeError, lambda: e.id)
|
||||
with self.assertRaises(AttributeError):
|
||||
e.id
|
||||
|
||||
def test_in_bulk(self):
|
||||
"""
|
||||
|
@ -82,8 +82,9 @@ class DataTypesTestCase(TestCase):
|
||||
an error if given a timezone-aware datetime object."""
|
||||
dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=utc)
|
||||
d = Donut(name='Bear claw', consumed_at=dt)
|
||||
self.assertRaises(ValueError, d.save)
|
||||
# ValueError: MySQL backend does not support timezone-aware datetimes.
|
||||
# MySQL backend does not support timezone-aware datetimes.
|
||||
with self.assertRaises(ValueError):
|
||||
d.save()
|
||||
|
||||
def test_datefield_auto_now_add(self):
|
||||
"""Regression test for #10970, auto_now_add for DateField should store
|
||||
|
@ -87,10 +87,8 @@ class DatesTests(TestCase):
|
||||
)
|
||||
|
||||
def test_dates_fails_when_no_arguments_are_provided(self):
|
||||
self.assertRaises(
|
||||
TypeError,
|
||||
Article.objects.dates,
|
||||
)
|
||||
with self.assertRaises(TypeError):
|
||||
Article.objects.dates()
|
||||
|
||||
def test_dates_fails_when_given_invalid_field_argument(self):
|
||||
six.assertRaisesRegex(
|
||||
|
@ -63,7 +63,8 @@ class OnDeleteTests(TestCase):
|
||||
|
||||
def test_protect(self):
|
||||
a = create_a('protect')
|
||||
self.assertRaises(IntegrityError, a.protect.delete)
|
||||
with self.assertRaises(IntegrityError):
|
||||
a.protect.delete()
|
||||
|
||||
def test_do_nothing(self):
|
||||
# Testing DO_NOTHING is a bit harder: It would raise IntegrityError for a normal model,
|
||||
|
@ -294,12 +294,14 @@ class BasicExpressionsTests(TestCase):
|
||||
|
||||
def test():
|
||||
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.save()
|
||||
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):
|
||||
# F expressions cannot be used to update attributes on objects which do
|
||||
|
@ -52,8 +52,8 @@ class GetStorageClassTests(SimpleTestCase):
|
||||
"""
|
||||
get_storage_class raises an error if the requested class don't exist.
|
||||
"""
|
||||
self.assertRaises(ImportError, get_storage_class,
|
||||
'django.core.files.storage.NonExistingStorage')
|
||||
with self.assertRaises(ImportError):
|
||||
get_storage_class('django.core.files.storage.NonExistingStorage')
|
||||
|
||||
def test_get_nonexisting_storage_module(self):
|
||||
"""
|
||||
@ -256,7 +256,8 @@ class FileStorageTests(SimpleTestCase):
|
||||
"""/test_media_url/a/b/c.file""")
|
||||
|
||||
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
|
||||
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
|
||||
they're below the storage location).
|
||||
"""
|
||||
self.assertRaises(SuspiciousOperation, self.storage.exists, '..')
|
||||
self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
|
||||
with self.assertRaises(SuspiciousOperation):
|
||||
self.storage.exists('..')
|
||||
with self.assertRaises(SuspiciousOperation):
|
||||
self.storage.exists('/etc/passwd')
|
||||
|
||||
def test_file_storage_preserves_filename_case(self):
|
||||
"""The storage backend should preserve case of filenames."""
|
||||
@ -342,8 +345,8 @@ class FileStorageTests(SimpleTestCase):
|
||||
self.assertEqual(f.read(), b'saved with race')
|
||||
|
||||
# Check that OSErrors aside from EEXIST are still raised.
|
||||
self.assertRaises(OSError,
|
||||
self.storage.save, 'error/test.file', ContentFile('not saved'))
|
||||
with self.assertRaises(OSError):
|
||||
self.storage.save('error/test.file', ContentFile('not saved'))
|
||||
finally:
|
||||
os.makedirs = real_makedirs
|
||||
|
||||
@ -379,7 +382,8 @@ class FileStorageTests(SimpleTestCase):
|
||||
|
||||
# Check that OSErrors aside from ENOENT are still raised.
|
||||
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:
|
||||
os.remove = real_remove
|
||||
|
||||
@ -491,7 +495,8 @@ class FileFieldStorageTests(TestCase):
|
||||
# An object without a file has limited functionality.
|
||||
obj1 = Storage()
|
||||
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.
|
||||
obj1.normal.save("django_test.txt", ContentFile("content"))
|
||||
|
@ -376,12 +376,8 @@ class FileUploadTests(TestCase):
|
||||
file.seek(0)
|
||||
|
||||
# AttributeError: You cannot alter upload handlers after the upload has been processed.
|
||||
self.assertRaises(
|
||||
AttributeError,
|
||||
self.client.post,
|
||||
'/quota/broken/',
|
||||
{'f': file}
|
||||
)
|
||||
with self.assertRaises(AttributeError):
|
||||
self.client.post('/quota/broken/', {'f': file})
|
||||
|
||||
def test_fileupload_getlist(self):
|
||||
file = tempfile.NamedTemporaryFile
|
||||
|
@ -287,7 +287,8 @@ class FileMoveSafeTests(unittest.TestCase):
|
||||
handle_b, self.file_b = tempfile.mkstemp()
|
||||
|
||||
# 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
|
||||
self.assertIsNone(file_move_safe(self.file_a, self.file_b, allow_overwrite=True))
|
||||
|
@ -144,17 +144,17 @@ class FlatpageTemplateTagTests(TestCase):
|
||||
def render(t):
|
||||
return Template(t).render(Context())
|
||||
|
||||
self.assertRaises(TemplateSyntaxError, render,
|
||||
"{% load flatpages %}{% get_flatpages %}")
|
||||
self.assertRaises(TemplateSyntaxError, render,
|
||||
"{% load flatpages %}{% get_flatpages as %}")
|
||||
self.assertRaises(TemplateSyntaxError, render,
|
||||
"{% load flatpages %}{% get_flatpages cheesecake flatpages %}")
|
||||
self.assertRaises(TemplateSyntaxError, render,
|
||||
"{% load flatpages %}{% get_flatpages as flatpages asdf %}")
|
||||
self.assertRaises(TemplateSyntaxError, render,
|
||||
"{% load flatpages %}{% get_flatpages cheesecake user as flatpages %}")
|
||||
self.assertRaises(TemplateSyntaxError, render,
|
||||
"{% load flatpages %}{% get_flatpages for user as flatpages asdf %}")
|
||||
self.assertRaises(TemplateSyntaxError, render,
|
||||
"{% load flatpages %}{% get_flatpages prefix for user as flatpages asdf %}")
|
||||
with self.assertRaises(TemplateSyntaxError):
|
||||
render("{% load flatpages %}{% get_flatpages %}")
|
||||
with self.assertRaises(TemplateSyntaxError):
|
||||
render("{% load flatpages %}{% get_flatpages as %}")
|
||||
with self.assertRaises(TemplateSyntaxError):
|
||||
render("{% load flatpages %}{% get_flatpages cheesecake flatpages %}")
|
||||
with self.assertRaises(TemplateSyntaxError):
|
||||
render("{% load flatpages %}{% get_flatpages as flatpages asdf %}")
|
||||
with self.assertRaises(TemplateSyntaxError):
|
||||
render("{% load flatpages %}{% get_flatpages cheesecake user as flatpages %}")
|
||||
with self.assertRaises(TemplateSyntaxError):
|
||||
render("{% load flatpages %}{% get_flatpages for user as flatpages asdf %}")
|
||||
with self.assertRaises(TemplateSyntaxError):
|
||||
render("{% load flatpages %}{% get_flatpages prefix for user as flatpages asdf %}")
|
||||
|
@ -57,7 +57,8 @@ class MultiColumnFKTests(TestCase):
|
||||
membership = Membership.objects.create(
|
||||
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):
|
||||
# Creating a valid membership because it has the same country has the person
|
||||
|
@ -149,9 +149,12 @@ class FieldsTests(SimpleTestCase):
|
||||
Ensure that setting min_length or max_length to something that is not a
|
||||
number returns an exception.
|
||||
"""
|
||||
self.assertRaises(ValueError, CharField, min_length='a')
|
||||
self.assertRaises(ValueError, CharField, max_length='a')
|
||||
self.assertRaises(ValueError, CharField, 'a')
|
||||
with self.assertRaises(ValueError):
|
||||
CharField(min_length='a')
|
||||
with self.assertRaises(ValueError):
|
||||
CharField(max_length='a')
|
||||
with self.assertRaises(ValueError):
|
||||
CharField('a')
|
||||
|
||||
def test_charfield_widget_attrs(self):
|
||||
"""
|
||||
@ -1654,8 +1657,10 @@ class FieldsTests(SimpleTestCase):
|
||||
# GenericIPAddressField #######################################################
|
||||
|
||||
def test_generic_ipaddress_invalid_arguments(self):
|
||||
self.assertRaises(ValueError, GenericIPAddressField, protocol="hamster")
|
||||
self.assertRaises(ValueError, GenericIPAddressField, protocol="ipv4", unpack_ipv4=True)
|
||||
with self.assertRaises(ValueError):
|
||||
GenericIPAddressField(protocol='hamster')
|
||||
with self.assertRaises(ValueError):
|
||||
GenericIPAddressField(protocol='ipv4', unpack_ipv4=True)
|
||||
|
||||
def test_generic_ipaddress_as_generic(self):
|
||||
# The edge cases of the IPv6 validation code are not deeply tested
|
||||
|
@ -3227,7 +3227,8 @@ Good luck picking a username that doesn't already exist.</p>
|
||||
"""
|
||||
p = Person({'first_name': 'John', 'last_name': 'Lennon', 'birthday': 'fakedate'})
|
||||
repr(p)
|
||||
self.assertRaises(AttributeError, lambda: p.cleaned_data)
|
||||
with self.assertRaises(AttributeError):
|
||||
p.cleaned_data
|
||||
self.assertFalse(p.is_valid())
|
||||
self.assertEqual(p.cleaned_data, {'first_name': 'John', 'last_name': 'Lennon'})
|
||||
|
||||
|
@ -19,7 +19,8 @@ class LocalizedTimeTests(SimpleTestCase):
|
||||
"TimeFields can parse dates in the default format"
|
||||
f = forms.TimeField()
|
||||
# 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
|
||||
result = f.clean('13:30:05')
|
||||
@ -45,7 +46,8 @@ class LocalizedTimeTests(SimpleTestCase):
|
||||
"Localized TimeFields act as unlocalized widgets"
|
||||
f = forms.TimeField(localize=True)
|
||||
# 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
|
||||
result = f.clean('13:30:05')
|
||||
@ -67,8 +69,10 @@ class LocalizedTimeTests(SimpleTestCase):
|
||||
"TimeFields with manually specified input formats can accept those formats"
|
||||
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
|
||||
# Parse a time in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
result = f.clean('13.30.05')
|
||||
@ -90,8 +94,10 @@ class LocalizedTimeTests(SimpleTestCase):
|
||||
"Localized TimeFields with manually specified input formats can accept those formats"
|
||||
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
|
||||
# Parse a time in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
result = f.clean('13.30.05')
|
||||
@ -116,7 +122,8 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
|
||||
"TimeFields can parse dates in the default format"
|
||||
f = forms.TimeField()
|
||||
# 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
|
||||
result = f.clean('1:30:05 PM')
|
||||
@ -138,7 +145,8 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
|
||||
"Localized TimeFields act as unlocalized widgets"
|
||||
f = forms.TimeField(localize=True)
|
||||
# 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
|
||||
result = f.clean('1:30:05 PM')
|
||||
@ -160,8 +168,10 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
|
||||
"TimeFields with manually specified input formats can accept those formats"
|
||||
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"])
|
||||
# Parse a time in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
result = f.clean('13.30.05')
|
||||
@ -183,8 +193,10 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
|
||||
"Localized TimeFields with manually specified input formats can accept those formats"
|
||||
f = forms.TimeField(input_formats=["%H.%M.%S", "%H.%M"], localize=True)
|
||||
# Parse a time in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
result = f.clean('13.30.05')
|
||||
@ -208,7 +220,8 @@ class SimpleTimeFormatTests(SimpleTestCase):
|
||||
"TimeFields can parse dates in the default format"
|
||||
f = forms.TimeField()
|
||||
# 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
|
||||
result = f.clean('13:30:05')
|
||||
@ -230,7 +243,8 @@ class SimpleTimeFormatTests(SimpleTestCase):
|
||||
"Localized TimeFields in a non-localized environment act as unlocalized widgets"
|
||||
f = forms.TimeField()
|
||||
# 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
|
||||
result = f.clean('13:30:05')
|
||||
@ -252,7 +266,8 @@ class SimpleTimeFormatTests(SimpleTestCase):
|
||||
"TimeFields with manually specified input formats can accept those formats"
|
||||
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"])
|
||||
# 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
|
||||
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"
|
||||
f = forms.TimeField(input_formats=["%I:%M:%S %p", "%I:%M %p"], localize=True)
|
||||
# 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
|
||||
result = f.clean('1:30:05 PM')
|
||||
@ -305,7 +321,8 @@ class LocalizedDateTests(SimpleTestCase):
|
||||
"DateFields can parse dates in the default format"
|
||||
f = forms.DateField()
|
||||
# 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
|
||||
self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21))
|
||||
@ -330,7 +347,8 @@ class LocalizedDateTests(SimpleTestCase):
|
||||
"Localized DateFields act as unlocalized widgets"
|
||||
f = forms.DateField(localize=True)
|
||||
# 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
|
||||
result = f.clean('21.12.2010')
|
||||
@ -352,9 +370,12 @@ class LocalizedDateTests(SimpleTestCase):
|
||||
"DateFields with manually specified input formats can accept those formats"
|
||||
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
|
||||
# Parse a date in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '21/12/2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
f.clean('2010-12-21')
|
||||
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
|
||||
result = f.clean('12.21.2010')
|
||||
@ -376,9 +397,12 @@ class LocalizedDateTests(SimpleTestCase):
|
||||
"Localized DateFields with manually specified input formats can accept those formats"
|
||||
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
|
||||
# Parse a date in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '21/12/2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
f.clean('2010-12-21')
|
||||
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
|
||||
result = f.clean('12.21.2010')
|
||||
@ -403,7 +427,8 @@ class CustomDateInputFormatsTests(SimpleTestCase):
|
||||
"DateFields can parse dates in the default format"
|
||||
f = forms.DateField()
|
||||
# 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
|
||||
result = f.clean('21.12.2010')
|
||||
@ -425,7 +450,8 @@ class CustomDateInputFormatsTests(SimpleTestCase):
|
||||
"Localized DateFields act as unlocalized widgets"
|
||||
f = forms.DateField(localize=True)
|
||||
# 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
|
||||
result = f.clean('21.12.2010')
|
||||
@ -447,8 +473,10 @@ class CustomDateInputFormatsTests(SimpleTestCase):
|
||||
"DateFields with manually specified input formats can accept those formats"
|
||||
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"])
|
||||
# Parse a date in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
result = f.clean('12.21.2010')
|
||||
@ -470,8 +498,10 @@ class CustomDateInputFormatsTests(SimpleTestCase):
|
||||
"Localized DateFields with manually specified input formats can accept those formats"
|
||||
f = forms.DateField(input_formats=["%m.%d.%Y", "%m-%d-%Y"], localize=True)
|
||||
# Parse a date in an unaccepted format; get an error
|
||||
self.assertRaises(forms.ValidationError, f.clean, '21.12.2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
result = f.clean('12.21.2010')
|
||||
@ -495,7 +525,8 @@ class SimpleDateFormatTests(SimpleTestCase):
|
||||
"DateFields can parse dates in the default format"
|
||||
f = forms.DateField()
|
||||
# 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
|
||||
result = f.clean('2010-12-21')
|
||||
@ -517,7 +548,8 @@ class SimpleDateFormatTests(SimpleTestCase):
|
||||
"Localized DateFields in a non-localized environment act as unlocalized widgets"
|
||||
f = forms.DateField()
|
||||
# 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
|
||||
result = f.clean('2010-12-21')
|
||||
@ -539,7 +571,8 @@ class SimpleDateFormatTests(SimpleTestCase):
|
||||
"DateFields with manually specified input formats can accept those formats"
|
||||
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"])
|
||||
# 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
|
||||
result = f.clean('21.12.2010')
|
||||
@ -561,7 +594,8 @@ class SimpleDateFormatTests(SimpleTestCase):
|
||||
"Localized DateFields with manually specified input formats can accept those formats"
|
||||
f = forms.DateField(input_formats=["%d.%m.%Y", "%d-%m-%Y"], localize=True)
|
||||
# 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
|
||||
result = f.clean('21.12.2010')
|
||||
@ -592,7 +626,8 @@ class LocalizedDateTimeTests(SimpleTestCase):
|
||||
"DateTimeFields can parse dates in the default format"
|
||||
f = forms.DateTimeField()
|
||||
# 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
|
||||
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"
|
||||
f = forms.DateTimeField(localize=True)
|
||||
# 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
|
||||
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"
|
||||
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
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05 13:30:05')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
f.clean('2010-12-21 13:30:05 13:30:05')
|
||||
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
|
||||
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"
|
||||
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
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
f.clean('2010-12-21 13:30:05')
|
||||
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
|
||||
result = f.clean('13.30.05 12.21.2010')
|
||||
@ -690,7 +732,8 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
|
||||
"DateTimeFields can parse dates in the default format"
|
||||
f = forms.DateTimeField()
|
||||
# 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
|
||||
result = f.clean('1:30:05 PM 21/12/2010')
|
||||
@ -712,7 +755,8 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
|
||||
"Localized DateTimeFields act as unlocalized widgets"
|
||||
f = forms.DateTimeField(localize=True)
|
||||
# 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
|
||||
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"
|
||||
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
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
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"
|
||||
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
|
||||
self.assertRaises(forms.ValidationError, f.clean, '13:30:05 21.12.2010')
|
||||
self.assertRaises(forms.ValidationError, f.clean, '2010-12-21 13:30:05')
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
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
|
||||
result = f.clean('12.21.2010 13:30:05')
|
||||
@ -782,7 +830,8 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
|
||||
"DateTimeFields can parse dates in the default format"
|
||||
f = forms.DateTimeField()
|
||||
# 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
|
||||
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"
|
||||
f = forms.DateTimeField()
|
||||
# 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
|
||||
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"
|
||||
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
|
||||
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
|
||||
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"
|
||||
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
|
||||
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
|
||||
result = f.clean('1:30:05 PM 21.12.2010')
|
||||
|
@ -45,12 +45,9 @@ class TestFieldWithValidators(TestCase):
|
||||
'string': '2 is not correct',
|
||||
'ignore_case_string': "IgnORE Case strIng",
|
||||
})
|
||||
self.assertRaises(ValidationError, form.fields['full_name'].clean, 'not int nor mail')
|
||||
|
||||
try:
|
||||
with self.assertRaises(ValidationError) as e:
|
||||
form.fields['full_name'].clean('not int nor mail')
|
||||
except ValidationError as e:
|
||||
self.assertEqual(2, len(e.messages))
|
||||
self.assertEqual(2, len(e.exception.messages))
|
||||
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertEqual(form.errors['string'], ["Letters only."])
|
||||
|
@ -251,7 +251,8 @@ class RelatedModelFormTests(SimpleTestCase):
|
||||
model = A
|
||||
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):
|
||||
pass
|
||||
|
@ -111,7 +111,8 @@ class GenericRelationTests(TestCase):
|
||||
# Fails with another, ORM-level error
|
||||
dev1 = Developer(name='Joe')
|
||||
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):
|
||||
"""Test for #13085 -- __len__() returns 0"""
|
||||
|
@ -145,12 +145,14 @@ class ViewTest(unittest.TestCase):
|
||||
# Check each of the allowed method names
|
||||
for method in SimpleView.http_method_names:
|
||||
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...
|
||||
CustomizableView.as_view(parameter="value")
|
||||
# ...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):
|
||||
"""
|
||||
@ -280,7 +282,8 @@ class TemplateViewTest(SimpleTestCase):
|
||||
"""
|
||||
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
|
||||
def test_template_engine(self):
|
||||
@ -527,4 +530,5 @@ class SingleObjectTemplateResponseMixinTest(unittest.TestCase):
|
||||
TemplateDoesNotExist.
|
||||
"""
|
||||
view = views.TemplateResponseWithoutTemplate()
|
||||
self.assertRaises(ImproperlyConfigured, view.get_template_names)
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
view.get_template_names()
|
||||
|
@ -82,7 +82,8 @@ class ArchiveIndexViewTests(TestDataMixin, TestCase):
|
||||
self.assertTemplateUsed(res, 'generic_views/book_detail.html')
|
||||
|
||||
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):
|
||||
res = self.client.get('/dates/books/by_month/')
|
||||
@ -664,7 +665,8 @@ class DateDetailViewTests(TestDataMixin, TestCase):
|
||||
self.assertTemplateUsed(res, 'generic_views/book_detail.html')
|
||||
|
||||
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):
|
||||
"""
|
||||
|
@ -49,7 +49,8 @@ class DetailViewTest(TestCase):
|
||||
self.assertEqual(res.status_code, 404)
|
||||
|
||||
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):
|
||||
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)
|
||||
|
||||
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):
|
||||
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):
|
||||
res = self.client.get('/detail/nonmodel/1/')
|
||||
|
@ -204,7 +204,8 @@ class ListViewTests(TestCase):
|
||||
self.assertTemplateUsed(res, 'generic_views/author_list.html')
|
||||
|
||||
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):
|
||||
# Regression test for #17535
|
||||
|
@ -17,7 +17,8 @@ class EarliestOrLatestTests(TestCase):
|
||||
|
||||
def test_earliest(self):
|
||||
# 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(
|
||||
headline="Article 1", pub_date=datetime(2005, 7, 26),
|
||||
@ -66,7 +67,8 @@ class EarliestOrLatestTests(TestCase):
|
||||
|
||||
def test_latest(self):
|
||||
# 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(
|
||||
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.
|
||||
Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1))
|
||||
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)
|
||||
|
||||
|
||||
@ -164,9 +167,12 @@ class TestFirstLast(TestCase):
|
||||
def check():
|
||||
# We know that we've broken the __iter__ method, so the queryset
|
||||
# should always raise an exception.
|
||||
self.assertRaises(IndexError, lambda: IndexErrorArticle.objects.all()[0])
|
||||
self.assertRaises(IndexError, IndexErrorArticle.objects.all().first)
|
||||
self.assertRaises(IndexError, IndexErrorArticle.objects.all().last)
|
||||
with self.assertRaises(IndexError):
|
||||
IndexErrorArticle.objects.all()[0]
|
||||
with self.assertRaises(IndexError):
|
||||
IndexErrorArticle.objects.all().first()
|
||||
with self.assertRaises(IndexError):
|
||||
IndexErrorArticle.objects.all().last()
|
||||
|
||||
check()
|
||||
|
||||
|
@ -13,7 +13,8 @@ class GetObjectOr404Tests(TestCase):
|
||||
a2 = Author.objects.create(name="Patsy")
|
||||
|
||||
# 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.authors.set([a1, a2])
|
||||
@ -30,10 +31,8 @@ class GetObjectOr404Tests(TestCase):
|
||||
)
|
||||
|
||||
# No articles containing "Camelot". This should raise a Http404 error.
|
||||
self.assertRaises(
|
||||
Http404,
|
||||
get_object_or_404, a1.article_set, title__contains="Camelot"
|
||||
)
|
||||
with self.assertRaises(Http404):
|
||||
get_object_or_404(a1.article_set, title__contains="Camelot")
|
||||
|
||||
# Custom managers can be used too.
|
||||
self.assertEqual(
|
||||
@ -50,16 +49,12 @@ class GetObjectOr404Tests(TestCase):
|
||||
# Just as when using a get() lookup, you will get an error if more than
|
||||
# one object is returned.
|
||||
|
||||
self.assertRaises(
|
||||
Author.MultipleObjectsReturned,
|
||||
get_object_or_404, Author.objects.all()
|
||||
)
|
||||
with self.assertRaises(Author.MultipleObjectsReturned):
|
||||
get_object_or_404(Author.objects.all())
|
||||
|
||||
# Using an empty QuerySet raises a Http404 error.
|
||||
self.assertRaises(
|
||||
Http404,
|
||||
get_object_or_404, Article.objects.none(), title__contains="Run"
|
||||
)
|
||||
with self.assertRaises(Http404):
|
||||
get_object_or_404(Article.objects.none(), title__contains="Run")
|
||||
|
||||
# get_list_or_404 can be used to get lists of objects
|
||||
self.assertEqual(
|
||||
@ -68,10 +63,8 @@ class GetObjectOr404Tests(TestCase):
|
||||
)
|
||||
|
||||
# Http404 is returned if the list is empty.
|
||||
self.assertRaises(
|
||||
Http404,
|
||||
get_list_or_404, a1.article_set, title__icontains="Shrubbery"
|
||||
)
|
||||
with self.assertRaises(Http404):
|
||||
get_list_or_404(a1.article_set, title__icontains="Shrubbery")
|
||||
|
||||
# Custom managers can be used too.
|
||||
self.assertEqual(
|
||||
|
@ -62,10 +62,8 @@ class GetOrCreateTests(TestCase):
|
||||
If you don't specify a value or default value for all required
|
||||
fields, you will get an error.
|
||||
"""
|
||||
self.assertRaises(
|
||||
IntegrityError,
|
||||
Person.objects.get_or_create, first_name="Tom", last_name="Smith"
|
||||
)
|
||||
with self.assertRaises(IntegrityError):
|
||||
Person.objects.get_or_create(first_name="Tom", last_name="Smith")
|
||||
|
||||
def test_get_or_create_on_related_manager(self):
|
||||
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,
|
||||
then you will get an error and data will not be updated.
|
||||
"""
|
||||
self.assertRaises(
|
||||
IntegrityError,
|
||||
ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different"
|
||||
)
|
||||
with self.assertRaises(IntegrityError):
|
||||
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
|
||||
self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original")
|
||||
|
||||
def test_get_or_create_raises_IntegrityError_plus_traceback(self):
|
||||
@ -246,7 +242,8 @@ class GetOrCreateThroughManyToMany(TestCase):
|
||||
def test_something(self):
|
||||
Tag.objects.create(text='foo')
|
||||
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):
|
||||
@ -292,8 +289,8 @@ class UpdateOrCreateTests(TestCase):
|
||||
If you don't specify a value or default value for all required
|
||||
fields, you will get an error.
|
||||
"""
|
||||
self.assertRaises(IntegrityError,
|
||||
Person.objects.update_or_create, first_name="Tom", last_name="Smith")
|
||||
with self.assertRaises(IntegrityError):
|
||||
Person.objects.update_or_create(first_name="Tom", last_name="Smith")
|
||||
|
||||
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.
|
||||
"""
|
||||
ManualPrimaryKeyTest.objects.create(id=1, data="Original")
|
||||
self.assertRaises(
|
||||
IntegrityError,
|
||||
ManualPrimaryKeyTest.objects.update_or_create, id=1, data="Different"
|
||||
)
|
||||
with self.assertRaises(IntegrityError):
|
||||
ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different")
|
||||
self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original")
|
||||
|
||||
def test_error_contains_full_traceback(self):
|
||||
|
@ -95,7 +95,8 @@ class DistanceTest(TestCase):
|
||||
if type_error:
|
||||
# A ValueError should be raised on PostGIS when trying to pass
|
||||
# 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:
|
||||
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.
|
||||
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.
|
||||
self.assertRaises(ValueError, len,
|
||||
AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
|
||||
with self.assertRaises(ValueError):
|
||||
len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
|
||||
|
||||
# Getting all cities w/in 550 miles of Hobart.
|
||||
hobart = AustraliaCity.objects.get(name='Hobart')
|
||||
@ -382,7 +384,8 @@ class DistanceTest(TestCase):
|
||||
self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
|
||||
else:
|
||||
# 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.
|
||||
i10 = SouthTexasInterstate.objects.length().get(name='I-10')
|
||||
|
@ -40,7 +40,8 @@ class DriverTest(unittest.TestCase):
|
||||
def test02_invalid_driver(self):
|
||||
"Testing invalid GDAL/OGR Data Source Drivers."
|
||||
for i in invalid_drivers:
|
||||
self.assertRaises(GDALException, Driver, i)
|
||||
with self.assertRaises(GDALException):
|
||||
Driver(i)
|
||||
|
||||
def test03_aliases(self):
|
||||
"Testing driver aliases."
|
||||
|
@ -87,7 +87,8 @@ class DataSourceTest(unittest.TestCase):
|
||||
def test02_invalid_shp(self):
|
||||
"Testing invalid SHP files for the Data Source."
|
||||
for source in bad_ds:
|
||||
self.assertRaises(GDALException, DataSource, source.ds)
|
||||
with self.assertRaises(GDALException):
|
||||
DataSource(source.ds)
|
||||
|
||||
def test03a_layers(self):
|
||||
"Testing Data Source Layers."
|
||||
@ -122,8 +123,10 @@ class DataSourceTest(unittest.TestCase):
|
||||
self.assertIn(f, source.fields)
|
||||
|
||||
# Negative FIDs are not allowed.
|
||||
self.assertRaises(OGRIndexError, layer.__getitem__, -1)
|
||||
self.assertRaises(OGRIndexError, layer.__getitem__, 50000)
|
||||
with self.assertRaises(OGRIndexError):
|
||||
layer.__getitem__(-1)
|
||||
with self.assertRaises(OGRIndexError):
|
||||
layer.__getitem__(50000)
|
||||
|
||||
if hasattr(source, 'field_values'):
|
||||
fld_names = source.field_values.keys()
|
||||
@ -233,11 +236,13 @@ class DataSourceTest(unittest.TestCase):
|
||||
self.assertIsNone(lyr.spatial_filter)
|
||||
|
||||
# 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
|
||||
# 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)
|
||||
lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001)
|
||||
self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter)
|
||||
|
@ -25,13 +25,20 @@ class EnvelopeTest(unittest.TestCase):
|
||||
Envelope(0, 0, 5, 5)
|
||||
Envelope(0, '0', '5', 5) # Thanks to ww for this
|
||||
Envelope(e1._envelope)
|
||||
self.assertRaises(GDALException, Envelope, (5, 5, 0, 0))
|
||||
self.assertRaises(GDALException, Envelope, 5, 5, 0, 0)
|
||||
self.assertRaises(GDALException, Envelope, (0, 0, 5, 5, 3))
|
||||
self.assertRaises(GDALException, Envelope, ())
|
||||
self.assertRaises(ValueError, Envelope, 0, 'a', 5, 5)
|
||||
self.assertRaises(TypeError, Envelope, 'foo')
|
||||
self.assertRaises(GDALException, Envelope, (1, 1, 0, 0))
|
||||
with self.assertRaises(GDALException):
|
||||
Envelope((5, 5, 0, 0))
|
||||
with self.assertRaises(GDALException):
|
||||
Envelope(5, 5, 0, 0)
|
||||
with self.assertRaises(GDALException):
|
||||
Envelope((0, 0, 5, 5, 3))
|
||||
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:
|
||||
Envelope(0, 0, 0, 0)
|
||||
except GDALException:
|
||||
|
@ -36,9 +36,12 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
|
||||
OGRGeomType('Unknown')
|
||||
|
||||
# Should throw TypeError on this input
|
||||
self.assertRaises(GDALException, OGRGeomType, 23)
|
||||
self.assertRaises(GDALException, OGRGeomType, 'fooD')
|
||||
self.assertRaises(GDALException, OGRGeomType, 9)
|
||||
with self.assertRaises(GDALException):
|
||||
OGRGeomType(23)
|
||||
with self.assertRaises(GDALException):
|
||||
OGRGeomType('fooD')
|
||||
with self.assertRaises(GDALException):
|
||||
OGRGeomType(9)
|
||||
|
||||
# Equivalence can take strings, ints, and other OGRGeomTypes
|
||||
self.assertEqual(OGRGeomType(1), OGRGeomType(1))
|
||||
@ -168,7 +171,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
|
||||
self.assertEqual(ls.coords, linestr.tuple)
|
||||
self.assertEqual(linestr, OGRGeometry(ls.wkt))
|
||||
self.assertNotEqual(linestr, prev)
|
||||
self.assertRaises(OGRIndexError, linestr.__getitem__, len(linestr))
|
||||
with self.assertRaises(OGRIndexError):
|
||||
linestr.__getitem__(len(linestr))
|
||||
prev = linestr
|
||||
|
||||
# Testing the x, y properties.
|
||||
@ -192,7 +196,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
|
||||
for ls in mlinestr:
|
||||
self.assertEqual(2, ls.geom_type)
|
||||
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):
|
||||
"Testing LinearRing objects."
|
||||
@ -263,7 +268,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
|
||||
if mp.valid:
|
||||
self.assertEqual(mp.n_p, mpoly.point_count)
|
||||
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:
|
||||
self.assertEqual('POLYGON', p.geom_name)
|
||||
self.assertEqual(3, p.geom_type)
|
||||
@ -415,7 +421,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin):
|
||||
# Can't insert a Point into a MultiPolygon.
|
||||
mp = OGRGeometry('MultiPolygon')
|
||||
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
|
||||
# of the same type all child geoms will be added individually) or WKT.
|
||||
|
@ -350,7 +350,8 @@ class GDALBandTests(unittest.TestCase):
|
||||
band = rs.bands[0]
|
||||
|
||||
# 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):
|
||||
# Create in-memory raster and get band
|
||||
|
@ -249,8 +249,10 @@ class SpatialRefTest(unittest.TestCase):
|
||||
def test13_attr_value(self):
|
||||
"Testing the attr_value() method."
|
||||
s1 = SpatialReference('WGS84')
|
||||
self.assertRaises(TypeError, s1.__getitem__, 0)
|
||||
self.assertRaises(TypeError, s1.__getitem__, ('GEOGCS', 'foo'))
|
||||
with self.assertRaises(TypeError):
|
||||
s1.__getitem__(0)
|
||||
with self.assertRaises(TypeError):
|
||||
s1.__getitem__(('GEOGCS', 'foo'))
|
||||
self.assertEqual('WGS 84', s1['GEOGCS'])
|
||||
self.assertEqual('WGS_1984', s1['DATUM'])
|
||||
self.assertEqual('EPSG', s1['AUTHORITY'])
|
||||
|
@ -157,8 +157,8 @@ class Geo3DTest(Geo3DLoadingHelper, TestCase):
|
||||
|
||||
# The city shapefile is 2D, and won't be able to fill the coordinates
|
||||
# in the 3D model -- thus, a LayerMapError is raised.
|
||||
self.assertRaises(LayerMapError, LayerMapping,
|
||||
Point3D, city_file, point_mapping, transform=False)
|
||||
with self.assertRaises(LayerMapError):
|
||||
LayerMapping(Point3D, city_file, point_mapping, transform=False)
|
||||
|
||||
# 3D model should take 3D data just fine.
|
||||
lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False)
|
||||
|
@ -86,5 +86,7 @@ class GeoFeedTest(TestCase):
|
||||
self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'geo:lat', 'geo:lon'])
|
||||
|
||||
# Boxes and Polygons aren't allowed in W3C Geo feeds.
|
||||
self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/') # Box in <channel>
|
||||
self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in <entry>
|
||||
with self.assertRaises(ValueError): # Box in <channel>
|
||||
self.client.get('/feeds/w3cgeo2/')
|
||||
with self.assertRaises(ValueError): # Polygons in <entry>
|
||||
self.client.get('/feeds/w3cgeo3/')
|
||||
|
@ -408,13 +408,15 @@ class GeoLookupTest(TestCase):
|
||||
|
||||
# Not passing in a geometry as first param should
|
||||
# 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
|
||||
# bad arguments.
|
||||
for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]:
|
||||
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.
|
||||
if postgis or spatialite:
|
||||
@ -556,7 +558,8 @@ class GeoQuerySetTest(TestCase):
|
||||
"Testing GeoJSON output from the database using GeoQuerySet.geojson()."
|
||||
# Only PostGIS and SpatiaLite support 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
|
||||
|
||||
pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}'
|
||||
@ -579,7 +582,8 @@ class GeoQuerySetTest(TestCase):
|
||||
)
|
||||
|
||||
# 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.
|
||||
# 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
|
||||
# non-geometry field.
|
||||
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')
|
||||
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
|
||||
# non-geometry field.
|
||||
qs = City.objects.all()
|
||||
self.assertRaises(TypeError, qs.kml, 'name')
|
||||
with self.assertRaises(TypeError):
|
||||
qs.kml('name')
|
||||
|
||||
# Ensuring the KML is as expected.
|
||||
ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo')
|
||||
@ -652,10 +658,8 @@ class GeoQuerySetTest(TestCase):
|
||||
Testing the `MakeLine` aggregate.
|
||||
"""
|
||||
if not connection.features.supports_make_line_aggr:
|
||||
self.assertRaises(
|
||||
NotImplementedError,
|
||||
City.objects.all().aggregate, MakeLine('point')
|
||||
)
|
||||
with self.assertRaises(NotImplementedError):
|
||||
City.objects.all().aggregate(MakeLine('point'))
|
||||
return
|
||||
|
||||
# MakeLine on an inappropriate field returns simply None
|
||||
@ -734,7 +738,8 @@ class GeoQuerySetTest(TestCase):
|
||||
coords.reverse()
|
||||
self.assertEqual(tuple(coords), t.reverse_geom.coords)
|
||||
if oracle:
|
||||
self.assertRaises(TypeError, State.objects.reverse_geom)
|
||||
with self.assertRaises(TypeError):
|
||||
State.objects.reverse_geom()
|
||||
|
||||
@skipUnlessDBFeature("has_scale_method")
|
||||
def test_scale(self):
|
||||
@ -754,9 +759,11 @@ class GeoQuerySetTest(TestCase):
|
||||
"Testing GeoQuerySet.snap_to_grid()."
|
||||
# Let's try and break snap_to_grid() with bad combinations of arguments.
|
||||
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)))):
|
||||
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
|
||||
# from the world borders dataset he provides.
|
||||
@ -802,7 +809,8 @@ class GeoQuerySetTest(TestCase):
|
||||
def test_svg(self):
|
||||
"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';
|
||||
svg1 = 'cx="-104.609252" cy="-38.255001"'
|
||||
# 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)')
|
||||
union2 = fromstr('MULTIPOINT(-95.363151 29.763374,-96.801611 32.782057)')
|
||||
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
|
||||
# order in the other (which should not be used because this is
|
||||
# an aggregate method on a spatial column)
|
||||
|
@ -56,13 +56,16 @@ class GeographyTest(TestCase):
|
||||
# http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions
|
||||
z = Zipcode.objects.get(code='77002')
|
||||
# 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.
|
||||
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.
|
||||
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.")
|
||||
def test05_geography_layermapping(self):
|
||||
|
@ -62,7 +62,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
# a C method is given a NULL memory reference.
|
||||
for fg in (fg1, fg2):
|
||||
# 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
|
||||
# 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'))
|
||||
for bad_ptr in bad_ptrs:
|
||||
# Equivalent to `fg.ptr = bad_ptr`
|
||||
self.assertRaises(TypeError, fg1._set_ptr, bad_ptr)
|
||||
self.assertRaises(TypeError, fg2._set_ptr, bad_ptr)
|
||||
with self.assertRaises(TypeError):
|
||||
fg1._set_ptr(bad_ptr)
|
||||
with self.assertRaises(TypeError):
|
||||
fg2._set_ptr(bad_ptr)
|
||||
|
||||
def test_wkt(self):
|
||||
"Testing WKT output."
|
||||
@ -134,15 +137,18 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
fromstr(err.wkt)
|
||||
|
||||
# Bad WKB
|
||||
self.assertRaises(GEOSException, GEOSGeometry, six.memoryview(b'0'))
|
||||
with self.assertRaises(GEOSException):
|
||||
GEOSGeometry(six.memoryview(b'0'))
|
||||
|
||||
class NotAGeometry(object):
|
||||
pass
|
||||
|
||||
# Some other object
|
||||
self.assertRaises(TypeError, GEOSGeometry, NotAGeometry())
|
||||
with self.assertRaises(TypeError):
|
||||
GEOSGeometry(NotAGeometry())
|
||||
# None
|
||||
self.assertRaises(TypeError, GEOSGeometry, None)
|
||||
with self.assertRaises(TypeError):
|
||||
GEOSGeometry(None)
|
||||
|
||||
def test_wkb(self):
|
||||
"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[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.coords, tuple(m.tuple for m in mpnt))
|
||||
for p in mpnt:
|
||||
@ -314,7 +321,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
|
||||
self.assertEqual(ls, fromstr(l.wkt))
|
||||
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
|
||||
|
||||
# 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.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, 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__
|
||||
|
||||
# Testing __getitem__ and __setitem__ on invalid indices
|
||||
self.assertRaises(IndexError, poly.__getitem__, len(poly))
|
||||
self.assertRaises(IndexError, poly.__setitem__, len(poly), False)
|
||||
self.assertRaises(IndexError, poly.__getitem__, -1 * len(poly) - 1)
|
||||
with self.assertRaises(IndexError):
|
||||
poly.__getitem__(len(poly))
|
||||
with self.assertRaises(IndexError):
|
||||
poly.__setitem__(len(poly), False)
|
||||
with self.assertRaises(IndexError):
|
||||
poly.__getitem__(-1 * len(poly) - 1)
|
||||
|
||||
# Testing __iter__
|
||||
for r in poly:
|
||||
@ -452,8 +464,10 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
self.assertEqual(r.geom_typeid, 2)
|
||||
|
||||
# Testing polygon construction.
|
||||
self.assertRaises(TypeError, Polygon, 0, [1, 2, 3])
|
||||
self.assertRaises(TypeError, Polygon, 'foo')
|
||||
with self.assertRaises(TypeError):
|
||||
Polygon(0, [1, 2, 3])
|
||||
with self.assertRaises(TypeError):
|
||||
Polygon('foo')
|
||||
|
||||
# Polygon(shell, (hole1, ... holeN))
|
||||
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.n_p, mpoly.num_coords)
|
||||
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:
|
||||
self.assertEqual(p.geom_type, 'Polygon')
|
||||
self.assertEqual(p.geom_typeid, 3)
|
||||
@ -563,7 +578,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
def test_relate_pattern(self):
|
||||
"Testing relate() and relate_pattern()."
|
||||
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:
|
||||
a = fromstr(rg.wkt_a)
|
||||
b = fromstr(rg.wkt_b)
|
||||
@ -639,7 +655,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
width = bg.width
|
||||
|
||||
# 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
|
||||
buf = g.buffer(width, quadsegs)
|
||||
@ -743,7 +760,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
poly = fromstr(p.wkt)
|
||||
|
||||
# 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.
|
||||
shell_tup = poly.shell.tuple
|
||||
@ -875,7 +893,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
# Testing a 3D LineString
|
||||
ls = LineString((2., 3., 8.), (50., 250., -117.))
|
||||
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.)
|
||||
self.assertEqual((1., 2., 3.), ls[0])
|
||||
|
||||
@ -961,9 +980,11 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
self.assertEqual('LINEARRING EMPTY', lr.wkt)
|
||||
self.assertEqual(0, len(lr))
|
||||
self.assertEqual(True, lr.empty)
|
||||
self.assertRaises(IndexError, lr.__getitem__, 0)
|
||||
with self.assertRaises(IndexError):
|
||||
lr.__getitem__(0)
|
||||
else:
|
||||
self.assertRaises(IndexError, g.__getitem__, 0)
|
||||
with self.assertRaises(IndexError):
|
||||
g.__getitem__(0)
|
||||
|
||||
def test_collection_dims(self):
|
||||
gc = GeometryCollection([])
|
||||
@ -1089,25 +1110,31 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
|
||||
""" Testing `transform` method (no SRID or negative SRID) """
|
||||
|
||||
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)
|
||||
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)
|
||||
self.assertRaises(GEOSException, g.transform, 2774)
|
||||
with self.assertRaises(GEOSException):
|
||||
g.transform(2774)
|
||||
|
||||
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)
|
||||
def test_transform_nogdal(self):
|
||||
""" Testing `transform` method (GDAL not available) """
|
||||
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)
|
||||
self.assertRaises(GEOSException, g.transform, 2774, clone=True)
|
||||
with self.assertRaises(GEOSException):
|
||||
g.transform(2774, clone=True)
|
||||
|
||||
def test_extent(self):
|
||||
"Testing `extent` method."
|
||||
|
@ -82,8 +82,10 @@ class GEOSMutationTest(unittest.TestCase):
|
||||
p = Point(1, 2)
|
||||
for i in range(-2, 2):
|
||||
p._checkindex(i)
|
||||
self.assertRaises(IndexError, p._checkindex, 2)
|
||||
self.assertRaises(IndexError, p._checkindex, -3)
|
||||
with self.assertRaises(IndexError):
|
||||
p._checkindex(2)
|
||||
with self.assertRaises(IndexError):
|
||||
p._checkindex(-3)
|
||||
|
||||
def test01_PointMutations(self):
|
||||
'Testing Point mutations'
|
||||
@ -100,8 +102,10 @@ class GEOSMutationTest(unittest.TestCase):
|
||||
|
||||
def test02_PointExceptions(self):
|
||||
'Testing Point exceptions'
|
||||
self.assertRaises(TypeError, Point, range(1))
|
||||
self.assertRaises(TypeError, Point, range(4))
|
||||
with self.assertRaises(TypeError):
|
||||
Point(range(1))
|
||||
with self.assertRaises(TypeError):
|
||||
Point(range(4))
|
||||
|
||||
def test03_PointApi(self):
|
||||
'Testing Point API'
|
||||
|
@ -27,13 +27,16 @@ class GEOSIOTest(SimpleTestCase):
|
||||
self.assertEqual(ref, geom)
|
||||
|
||||
# Should only accept six.string_types objects.
|
||||
self.assertRaises(TypeError, wkt_r.read, 1)
|
||||
self.assertRaises(TypeError, wkt_r.read, memoryview(b'foo'))
|
||||
with self.assertRaises(TypeError):
|
||||
wkt_r.read(1)
|
||||
with self.assertRaises(TypeError):
|
||||
wkt_r.read(memoryview(b'foo'))
|
||||
|
||||
def test02_wktwriter(self):
|
||||
# Creating a WKTWriter instance, testing its ptr property.
|
||||
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_wkt = 'POINT (5.0000000000000000 23.0000000000000000)'
|
||||
@ -56,7 +59,8 @@ class GEOSIOTest(SimpleTestCase):
|
||||
|
||||
bad_input = (1, 5.23, None, False)
|
||||
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):
|
||||
wkb_w = WKBWriter()
|
||||
@ -75,7 +79,8 @@ class GEOSIOTest(SimpleTestCase):
|
||||
# Ensuring bad byteorders are not accepted.
|
||||
for bad_byteorder in (-1, 2, 523, 'foo', None):
|
||||
# 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)
|
||||
wkb_w.byteorder = 0
|
||||
@ -97,7 +102,8 @@ class GEOSIOTest(SimpleTestCase):
|
||||
# Ensuring bad output dimensions are not accepted
|
||||
for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
|
||||
# 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
|
||||
wkb_w.outdim = 3
|
||||
|
@ -128,9 +128,11 @@ class ListMixinTest(unittest.TestCase):
|
||||
self.assertEqual(pl, ul[:], 'set slice [%d:%d:%d]' % (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:
|
||||
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():
|
||||
ssl = nextRange(len(ul[i::k]))
|
||||
@ -223,9 +225,12 @@ class ListMixinTest(unittest.TestCase):
|
||||
del x[i]
|
||||
pl, ul = self.lists_of_len()
|
||||
for i in (-1 - self.limit, self.limit):
|
||||
self.assertRaises(IndexError, setfcn, ul, i) # 'set index %d' % i)
|
||||
self.assertRaises(IndexError, getfcn, ul, i) # 'get index %d' % i)
|
||||
self.assertRaises(IndexError, delfcn, ul, i) # 'del index %d' % i)
|
||||
with self.assertRaises(IndexError): # 'set index %d' % i)
|
||||
setfcn(ul, 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):
|
||||
'List methods'
|
||||
@ -261,8 +266,10 @@ class ListMixinTest(unittest.TestCase):
|
||||
|
||||
def popfcn(x, i):
|
||||
x.pop(i)
|
||||
self.assertRaises(IndexError, popfcn, ul, self.limit)
|
||||
self.assertRaises(IndexError, popfcn, ul, -1 - self.limit)
|
||||
with self.assertRaises(IndexError):
|
||||
popfcn(ul, self.limit)
|
||||
with self.assertRaises(IndexError):
|
||||
popfcn(ul, -1 - self.limit)
|
||||
|
||||
pl, ul = self.lists_of_len()
|
||||
for val in range(self.limit):
|
||||
@ -282,8 +289,10 @@ class ListMixinTest(unittest.TestCase):
|
||||
|
||||
def removefcn(x, v):
|
||||
return x.remove(v)
|
||||
self.assertRaises(ValueError, indexfcn, ul, 40)
|
||||
self.assertRaises(ValueError, removefcn, ul, 40)
|
||||
with self.assertRaises(ValueError):
|
||||
indexfcn(ul, 40)
|
||||
with self.assertRaises(ValueError):
|
||||
removefcn(ul, 40)
|
||||
|
||||
def test07_allowed_types(self):
|
||||
'Type-restricted list'
|
||||
@ -294,8 +303,10 @@ class ListMixinTest(unittest.TestCase):
|
||||
|
||||
def setfcn(x, i, v):
|
||||
x[i] = v
|
||||
self.assertRaises(TypeError, setfcn, ul, 2, 'hello')
|
||||
self.assertRaises(TypeError, setfcn, ul, slice(0, 3, 2), ('hello', 'goodbye'))
|
||||
with self.assertRaises(TypeError):
|
||||
setfcn(ul, 2, 'hello')
|
||||
with self.assertRaises(TypeError):
|
||||
setfcn(ul, slice(0, 3, 2), ('hello', 'goodbye'))
|
||||
|
||||
def test08_min_length(self):
|
||||
'Length limits'
|
||||
@ -308,14 +319,17 @@ class ListMixinTest(unittest.TestCase):
|
||||
def setfcn(x, i):
|
||||
x[:i] = []
|
||||
for i in range(len(ul) - ul._minlength + 1, len(ul)):
|
||||
self.assertRaises(ValueError, delfcn, ul, i)
|
||||
self.assertRaises(ValueError, setfcn, ul, i)
|
||||
with self.assertRaises(ValueError):
|
||||
delfcn(ul, i)
|
||||
with self.assertRaises(ValueError):
|
||||
setfcn(ul, i)
|
||||
del ul[:len(ul) - ul._minlength]
|
||||
|
||||
ul._maxlength = 4
|
||||
for i in range(0, ul._maxlength - len(ul)):
|
||||
ul.append(i)
|
||||
self.assertRaises(ValueError, ul.append, 10)
|
||||
with self.assertRaises(ValueError):
|
||||
ul.append(10)
|
||||
|
||||
def test09_iterable_check(self):
|
||||
'Error on assigning non-iterable to slice'
|
||||
@ -323,7 +337,8 @@ class ListMixinTest(unittest.TestCase):
|
||||
|
||||
def setfcn(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):
|
||||
'Index check'
|
||||
@ -335,7 +350,8 @@ class ListMixinTest(unittest.TestCase):
|
||||
self.assertEqual(ul._checkindex(i), i, '_checkindex(pos index)')
|
||||
|
||||
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):
|
||||
'Sorting'
|
||||
|
@ -156,11 +156,13 @@ class LayerMapTest(TestCase):
|
||||
|
||||
# Testing invalid params for the `unique` keyword.
|
||||
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.
|
||||
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
|
||||
# mapping for the model the ForeignKey points to.
|
||||
@ -168,14 +170,17 @@ class LayerMapTest(TestCase):
|
||||
bad_fk_map1['state'] = 'name'
|
||||
bad_fk_map2 = copy(co_mapping)
|
||||
bad_fk_map2['state'] = {'nombre': 'State'}
|
||||
self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False)
|
||||
self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False)
|
||||
with self.assertRaises(TypeError):
|
||||
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
|
||||
# a MissingForeignKey exception (this error would be ignored if the `strict`
|
||||
# keyword is not set).
|
||||
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.
|
||||
State.objects.bulk_create([
|
||||
@ -222,11 +227,13 @@ class LayerMapTest(TestCase):
|
||||
# Bad feature id ranges should raise a type error.
|
||||
bad_ranges = (5.0, 'foo', co_shp)
|
||||
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`.
|
||||
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)
|
||||
|
||||
# Features IDs 3 & 4 are for Galveston County, Texas -- only
|
||||
|
@ -17,7 +17,8 @@ class GeometryFieldTest(SimpleTestCase):
|
||||
"Testing GeometryField initialization with defaults."
|
||||
fld = forms.GeometryField()
|
||||
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):
|
||||
"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`
|
||||
self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)'))
|
||||
# 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):
|
||||
"""
|
||||
@ -72,7 +74,8 @@ class GeometryFieldTest(SimpleTestCase):
|
||||
self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt))
|
||||
# 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)'):
|
||||
self.assertRaises(forms.ValidationError, fld.to_python, wkt)
|
||||
with self.assertRaises(forms.ValidationError):
|
||||
fld.to_python(wkt)
|
||||
|
||||
def test_field_with_text_widget(self):
|
||||
class PointForm(forms.Form):
|
||||
|
@ -66,23 +66,29 @@ class GeoIPTest(unittest.TestCase):
|
||||
# Improper parameters.
|
||||
bad_params = (23, 'foo', 15.23)
|
||||
for bad in bad_params:
|
||||
self.assertRaises(GeoIPException, GeoIP, cache=bad)
|
||||
with self.assertRaises(GeoIPException):
|
||||
GeoIP(cache=bad)
|
||||
if isinstance(bad, six.string_types):
|
||||
e = GeoIPException
|
||||
else:
|
||||
e = TypeError
|
||||
self.assertRaises(e, GeoIP, bad, 0)
|
||||
with self.assertRaises(e):
|
||||
GeoIP(bad, 0)
|
||||
|
||||
def test02_bad_query(self):
|
||||
"Testing GeoIP query parameter checking."
|
||||
cntry_g = GeoIP(city='<foo>')
|
||||
# No city database available, these calls should fail.
|
||||
self.assertRaises(GeoIPException, cntry_g.city, 'google.com')
|
||||
self.assertRaises(GeoIPException, cntry_g.coords, 'yahoo.com')
|
||||
with self.assertRaises(GeoIPException):
|
||||
cntry_g.city('google.com')
|
||||
with self.assertRaises(GeoIPException):
|
||||
cntry_g.coords('yahoo.com')
|
||||
|
||||
# Non-string query should raise TypeError
|
||||
self.assertRaises(TypeError, cntry_g.country_code, 17)
|
||||
self.assertRaises(TypeError, cntry_g.country_name, GeoIP)
|
||||
with self.assertRaises(TypeError):
|
||||
cntry_g.country_code(17)
|
||||
with self.assertRaises(TypeError):
|
||||
cntry_g.country_name(GeoIP)
|
||||
|
||||
def test03_country(self):
|
||||
"Testing GeoIP country querying methods."
|
||||
|
@ -47,23 +47,29 @@ class GeoIPTest(unittest.TestCase):
|
||||
# Improper parameters.
|
||||
bad_params = (23, 'foo', 15.23)
|
||||
for bad in bad_params:
|
||||
self.assertRaises(GeoIP2Exception, GeoIP2, cache=bad)
|
||||
with self.assertRaises(GeoIP2Exception):
|
||||
GeoIP2(cache=bad)
|
||||
if isinstance(bad, six.string_types):
|
||||
e = GeoIP2Exception
|
||||
else:
|
||||
e = TypeError
|
||||
self.assertRaises(e, GeoIP2, bad, 0)
|
||||
with self.assertRaises(e):
|
||||
GeoIP2(bad, 0)
|
||||
|
||||
def test02_bad_query(self):
|
||||
"GeoIP query parameter checking."
|
||||
cntry_g = GeoIP2(city='<foo>')
|
||||
# No city database available, these calls should fail.
|
||||
self.assertRaises(GeoIP2Exception, cntry_g.city, 'tmc.edu')
|
||||
self.assertRaises(GeoIP2Exception, cntry_g.coords, 'tmc.edu')
|
||||
with self.assertRaises(GeoIP2Exception):
|
||||
cntry_g.city('tmc.edu')
|
||||
with self.assertRaises(GeoIP2Exception):
|
||||
cntry_g.coords('tmc.edu')
|
||||
|
||||
# Non-string query should raise TypeError
|
||||
self.assertRaises(TypeError, cntry_g.country_code, 17)
|
||||
self.assertRaises(TypeError, cntry_g.country_name, GeoIP2)
|
||||
with self.assertRaises(TypeError):
|
||||
cntry_g.country_code(17)
|
||||
with self.assertRaises(TypeError):
|
||||
cntry_g.country_name(GeoIP2)
|
||||
|
||||
@mock.patch('socket.gethostbyname')
|
||||
def test03_country(self, gethostbyname):
|
||||
|
@ -34,7 +34,8 @@ class DistanceTest(unittest.TestCase):
|
||||
|
||||
def testInitInvalid(self):
|
||||
"Testing initialization from invalid units"
|
||||
self.assertRaises(AttributeError, D, banana=100)
|
||||
with self.assertRaises(AttributeError):
|
||||
D(banana=100)
|
||||
|
||||
def testAccess(self):
|
||||
"Testing access in different units"
|
||||
@ -161,7 +162,8 @@ class AreaTest(unittest.TestCase):
|
||||
|
||||
def testInitInvaliA(self):
|
||||
"Testing initialization from invalid units"
|
||||
self.assertRaises(AttributeError, A, banana=100)
|
||||
with self.assertRaises(AttributeError):
|
||||
A(banana=100)
|
||||
|
||||
def testAccess(self):
|
||||
"Testing access in different units"
|
||||
|
@ -87,8 +87,10 @@ class TestPostgisVersionCheck(unittest.TestCase):
|
||||
|
||||
for version in versions:
|
||||
ops = FakePostGISOperations(version)
|
||||
self.assertRaises(Exception, lambda: ops.spatial_version)
|
||||
with self.assertRaises(Exception):
|
||||
ops.spatial_version
|
||||
|
||||
def test_no_version_number(self):
|
||||
ops = FakePostGISOperations()
|
||||
self.assertRaises(ImproperlyConfigured, lambda: ops.spatial_version)
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
ops.spatial_version
|
||||
|
@ -31,17 +31,25 @@ class QueryDictTests(unittest.TestCase):
|
||||
|
||||
def test_missing_key(self):
|
||||
q = QueryDict()
|
||||
self.assertRaises(KeyError, q.__getitem__, 'foo')
|
||||
with self.assertRaises(KeyError):
|
||||
q.__getitem__('foo')
|
||||
|
||||
def test_immutability(self):
|
||||
q = QueryDict()
|
||||
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
|
||||
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
|
||||
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
|
||||
self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
|
||||
self.assertRaises(AttributeError, q.pop, 'foo')
|
||||
self.assertRaises(AttributeError, q.popitem)
|
||||
self.assertRaises(AttributeError, q.clear)
|
||||
with self.assertRaises(AttributeError):
|
||||
q.__setitem__('something', 'bar')
|
||||
with self.assertRaises(AttributeError):
|
||||
q.setlist('foo', ['bar'])
|
||||
with self.assertRaises(AttributeError):
|
||||
q.appendlist('foo', ['bar'])
|
||||
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):
|
||||
q = QueryDict()
|
||||
@ -65,16 +73,20 @@ class QueryDictTests(unittest.TestCase):
|
||||
|
||||
q = QueryDict(str('foo=bar'))
|
||||
self.assertEqual(q['foo'], 'bar')
|
||||
self.assertRaises(KeyError, q.__getitem__, 'bar')
|
||||
self.assertRaises(AttributeError, q.__setitem__, 'something', 'bar')
|
||||
with self.assertRaises(KeyError):
|
||||
q.__getitem__('bar')
|
||||
with self.assertRaises(AttributeError):
|
||||
q.__setitem__('something', 'bar')
|
||||
|
||||
self.assertEqual(q.get('foo', 'default'), 'bar')
|
||||
self.assertEqual(q.get('bar', 'default'), 'default')
|
||||
self.assertEqual(q.getlist('foo'), ['bar'])
|
||||
self.assertEqual(q.getlist('bar'), [])
|
||||
|
||||
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar'])
|
||||
self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar'])
|
||||
with self.assertRaises(AttributeError):
|
||||
q.setlist('foo', ['bar'])
|
||||
with self.assertRaises(AttributeError):
|
||||
q.appendlist('foo', ['bar'])
|
||||
|
||||
if six.PY2:
|
||||
self.assertTrue(q.has_key('foo'))
|
||||
@ -89,11 +101,16 @@ class QueryDictTests(unittest.TestCase):
|
||||
self.assertEqual(list(six.itervalues(q)), ['bar'])
|
||||
self.assertEqual(len(q), 1)
|
||||
|
||||
self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
|
||||
self.assertRaises(AttributeError, q.pop, 'foo')
|
||||
self.assertRaises(AttributeError, q.popitem)
|
||||
self.assertRaises(AttributeError, q.clear)
|
||||
self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')
|
||||
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()
|
||||
with self.assertRaises(AttributeError):
|
||||
q.setdefault('foo', 'bar')
|
||||
|
||||
self.assertEqual(q.urlencode(), 'foo=bar')
|
||||
|
||||
@ -110,7 +127,8 @@ class QueryDictTests(unittest.TestCase):
|
||||
def test_mutable_copy(self):
|
||||
"""A copy of a QueryDict is mutable."""
|
||||
q = QueryDict().copy()
|
||||
self.assertRaises(KeyError, q.__getitem__, "foo")
|
||||
with self.assertRaises(KeyError):
|
||||
q.__getitem__("foo")
|
||||
q['name'] = 'john'
|
||||
self.assertEqual(q['name'], 'john')
|
||||
|
||||
@ -169,16 +187,20 @@ class QueryDictTests(unittest.TestCase):
|
||||
q = QueryDict(str('vote=yes&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('foo', 'default'), 'default')
|
||||
self.assertEqual(q.getlist('vote'), ['yes', 'no'])
|
||||
self.assertEqual(q.getlist('foo'), [])
|
||||
|
||||
self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz'])
|
||||
self.assertRaises(AttributeError, 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.setlist('foo', ['bar', 'baz'])
|
||||
with self.assertRaises(AttributeError):
|
||||
q.appendlist('foo', ['bar'])
|
||||
|
||||
if six.PY2:
|
||||
self.assertEqual(q.has_key('vote'), True)
|
||||
@ -192,12 +214,18 @@ class QueryDictTests(unittest.TestCase):
|
||||
self.assertEqual(list(six.itervalues(q)), ['no'])
|
||||
self.assertEqual(len(q), 1)
|
||||
|
||||
self.assertRaises(AttributeError, q.update, {'foo': 'bar'})
|
||||
self.assertRaises(AttributeError, q.pop, 'foo')
|
||||
self.assertRaises(AttributeError, q.popitem)
|
||||
self.assertRaises(AttributeError, q.clear)
|
||||
self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar')
|
||||
self.assertRaises(AttributeError, q.__delitem__, 'vote')
|
||||
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()
|
||||
with self.assertRaises(AttributeError):
|
||||
q.setdefault('foo', 'bar')
|
||||
with self.assertRaises(AttributeError):
|
||||
q.__delitem__('vote')
|
||||
|
||||
if six.PY2:
|
||||
def test_invalid_input_encoding(self):
|
||||
@ -295,8 +323,10 @@ class HttpResponseTests(unittest.TestCase):
|
||||
self.assertIsInstance(l[0][0], str)
|
||||
|
||||
r = HttpResponse()
|
||||
self.assertRaises(UnicodeError, r.__setitem__, 'føø', 'bar')
|
||||
self.assertRaises(UnicodeError, r.__setitem__, 'føø'.encode('utf-8'), 'bar')
|
||||
with self.assertRaises(UnicodeError):
|
||||
r.__setitem__('føø', 'bar')
|
||||
with self.assertRaises(UnicodeError):
|
||||
r.__setitem__('føø'.encode('utf-8'), 'bar')
|
||||
|
||||
def test_long_line(self):
|
||||
# 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):
|
||||
# Bug #10188: Do not allow newlines in headers (CR or LF)
|
||||
r = HttpResponse()
|
||||
self.assertRaises(BadHeaderError, r.__setitem__, 'test\rstr', 'test')
|
||||
self.assertRaises(BadHeaderError, r.__setitem__, 'test\nstr', 'test')
|
||||
with self.assertRaises(BadHeaderError):
|
||||
r.__setitem__('test\rstr', 'test')
|
||||
with self.assertRaises(BadHeaderError):
|
||||
r.__setitem__('test\nstr', 'test')
|
||||
|
||||
def test_dict_behavior(self):
|
||||
"""
|
||||
@ -418,10 +450,10 @@ class HttpResponseTests(unittest.TestCase):
|
||||
'file:///etc/passwd',
|
||||
]
|
||||
for url in bad_urls:
|
||||
self.assertRaises(SuspiciousOperation,
|
||||
HttpResponseRedirect, url)
|
||||
self.assertRaises(SuspiciousOperation,
|
||||
HttpResponsePermanentRedirect, url)
|
||||
with self.assertRaises(SuspiciousOperation):
|
||||
HttpResponseRedirect(url)
|
||||
with self.assertRaises(SuspiciousOperation):
|
||||
HttpResponsePermanentRedirect(url)
|
||||
|
||||
|
||||
class HttpResponseSubclassesTests(SimpleTestCase):
|
||||
|
@ -77,7 +77,8 @@ class URLPrefixTests(URLTestCaseBase):
|
||||
|
||||
@override_settings(ROOT_URLCONF='i18n.patterns.urls.wrong')
|
||||
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')
|
||||
|
@ -1852,7 +1852,8 @@ class TranslationFilesMissing(SimpleTestCase):
|
||||
'''
|
||||
self.patchGettextFind()
|
||||
trans_real._translations = {}
|
||||
self.assertRaises(IOError, activate, 'en')
|
||||
with self.assertRaises(IOError):
|
||||
activate('en')
|
||||
|
||||
|
||||
class NonDjangoLanguageTests(SimpleTestCase):
|
||||
|
@ -135,11 +135,9 @@ class InlineFormsetFactoryTest(TestCase):
|
||||
If we specify fk_name, but it isn't a ForeignKey from the child model
|
||||
to the parent model, we should get an exception.
|
||||
"""
|
||||
self.assertRaises(
|
||||
Exception,
|
||||
"fk_name 'school' is not a ForeignKey to <class 'inline_formsets.models.Parent'>",
|
||||
inlineformset_factory, Parent, Child, fk_name='school'
|
||||
)
|
||||
msg = "fk_name 'school' is not a ForeignKey to 'inline_formsets.Parent'."
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
inlineformset_factory(Parent, Child, fk_name='school')
|
||||
|
||||
def test_non_foreign_key_field(self):
|
||||
"""
|
||||
|
@ -136,7 +136,8 @@ class LookupTests(TestCase):
|
||||
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.assertRaises(TypeError, Article.objects.in_bulk, headline__startswith='Blah')
|
||||
with self.assertRaises(TypeError):
|
||||
Article.objects.in_bulk(headline__startswith='Blah')
|
||||
|
||||
def test_values(self):
|
||||
# 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
|
||||
# a non-existent field name in values() (a field that is neither in the
|
||||
# model nor in extra(select)).
|
||||
self.assertRaises(FieldError,
|
||||
Article.objects.extra(select={'id_plus_one': 'id + 1'}).values,
|
||||
'id', 'id_plus_two')
|
||||
with self.assertRaises(FieldError):
|
||||
Article.objects.extra(select={'id_plus_one': 'id + 1'}).values('id', 'id_plus_two')
|
||||
# If you don't specify field names to values(), all are returned.
|
||||
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.a7.headline, self.t3.name),
|
||||
], 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):
|
||||
# Every DateField and DateTimeField creates get_next_by_FOO() and
|
||||
@ -361,7 +362,8 @@ class LookupTests(TestCase):
|
||||
'<Article: Article 7>')
|
||||
self.assertEqual(repr(self.a4.get_next_by_pub_date()),
|
||||
'<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()),
|
||||
'<Article: Article 5>')
|
||||
self.assertEqual(repr(self.a7.get_next_by_pub_date()),
|
||||
|
@ -67,10 +67,12 @@ class M2MThroughTestCase(TestCase):
|
||||
self.roll.members.set([])
|
||||
|
||||
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):
|
||||
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):
|
||||
self.assertQuerysetEqual(
|
||||
|
@ -143,11 +143,13 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
|
||||
|
||||
def test_header_injection(self):
|
||||
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(
|
||||
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):
|
||||
"""
|
||||
@ -1193,7 +1195,8 @@ class SMTPBackendTests(BaseEmailBackendTests, SMTPBackendTestsBase):
|
||||
backend = smtp.EmailBackend()
|
||||
self.assertTrue(backend.use_ssl)
|
||||
try:
|
||||
self.assertRaises(SSLError, backend.open)
|
||||
with self.assertRaises(SSLError):
|
||||
backend.open()
|
||||
finally:
|
||||
backend.close()
|
||||
|
||||
|
@ -33,7 +33,8 @@ class ManyToManyTests(TestCase):
|
||||
# Create an Article.
|
||||
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.
|
||||
self.assertRaises(ValueError, getattr, a5, 'publications')
|
||||
with self.assertRaises(ValueError):
|
||||
getattr(a5, 'publications')
|
||||
# Save it!
|
||||
a5.save()
|
||||
# Associate the Article with a Publication.
|
||||
|
@ -455,8 +455,8 @@ class ManyToOneTests(TestCase):
|
||||
self.assertEqual(a3.reporter.id, self.r2.id)
|
||||
|
||||
# Get should respect explicit foreign keys as well.
|
||||
self.assertRaises(MultipleObjectsReturned,
|
||||
Article.objects.get, reporter_id=self.r.id)
|
||||
with self.assertRaises(MultipleObjectsReturned):
|
||||
Article.objects.get(reporter_id=self.r.id)
|
||||
self.assertEqual(repr(a3),
|
||||
repr(Article.objects.get(reporter_id=self.r2.id,
|
||||
pub_date=datetime.date(2011, 5, 7))))
|
||||
@ -537,15 +537,19 @@ class ManyToOneTests(TestCase):
|
||||
self.assertIsNone(p.bestchild)
|
||||
|
||||
# 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
|
||||
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
|
||||
# creation (regression for #9649).
|
||||
self.assertRaises(ValueError, Child, name='xyzzy', parent=None)
|
||||
self.assertRaises(ValueError, Child.objects.create, name='xyzzy', parent=None)
|
||||
with self.assertRaises(ValueError):
|
||||
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.
|
||||
p = Parent.objects.get(name="Parent")
|
||||
@ -602,7 +606,8 @@ class ManyToOneTests(TestCase):
|
||||
|
||||
p = Parent.objects.create(name="Parent")
|
||||
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):
|
||||
# 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
|
||||
try:
|
||||
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:
|
||||
School.objects.use_for_related_fields = False
|
||||
|
||||
|
@ -44,7 +44,8 @@ class ManyToOneNullTests(TestCase):
|
||||
self.assertEqual(self.a3.reporter, None)
|
||||
# Need to reget a3 to refresh the cache
|
||||
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
|
||||
# if the reporter is set to None.
|
||||
self.assertEqual(a3.reporter, None)
|
||||
@ -71,7 +72,8 @@ class ManyToOneNullTests(TestCase):
|
||||
def test_remove_from_wrong_set(self):
|
||||
self.assertQuerysetEqual(self.r2.article_set.all(), ['<Article: Fourth>'])
|
||||
# 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>'])
|
||||
|
||||
def test_set(self):
|
||||
|
@ -238,8 +238,8 @@ class BaseTests(object):
|
||||
reverse('show_message')
|
||||
for level in ('debug', 'info', 'success', 'warning', 'error'):
|
||||
add_url = reverse('add_message', args=(level,))
|
||||
self.assertRaises(MessageFailure, self.client.post, add_url,
|
||||
data, follow=True)
|
||||
with self.assertRaises(MessageFailure):
|
||||
self.client.post(add_url, data, follow=True)
|
||||
|
||||
@modify_settings(
|
||||
INSTALLED_APPS={'remove': 'django.contrib.messages'},
|
||||
|
@ -862,7 +862,8 @@ class RootUrlconfTests(SimpleTestCase):
|
||||
# Removing ROOT_URLCONF is safe, as override_settings will restore
|
||||
# the previously defined settings.
|
||||
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):
|
||||
|
@ -145,10 +145,8 @@ class GraphTests(SimpleTestCase):
|
||||
graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_b", "0001"))
|
||||
graph.add_dependency("app_b.0001", ("app_b", "0001"), ("app_a", "0003"))
|
||||
# Test whole graph
|
||||
self.assertRaises(
|
||||
CircularDependencyError,
|
||||
graph.forwards_plan, ("app_a", "0003"),
|
||||
)
|
||||
with self.assertRaises(CircularDependencyError):
|
||||
graph.forwards_plan(("app_a", "0003"), )
|
||||
|
||||
def test_circular_graph_2(self):
|
||||
graph = MigrationGraph()
|
||||
@ -159,10 +157,8 @@ class GraphTests(SimpleTestCase):
|
||||
graph.add_dependency('B.0001', ('B', '0001'), ('A', '0001'))
|
||||
graph.add_dependency('C.0001', ('C', '0001'), ('B', '0001'))
|
||||
|
||||
self.assertRaises(
|
||||
CircularDependencyError,
|
||||
graph.forwards_plan, ('C', '0001')
|
||||
)
|
||||
with self.assertRaises(CircularDependencyError):
|
||||
graph.forwards_plan(('C', '0001'))
|
||||
|
||||
def test_graph_recursive(self):
|
||||
graph = MigrationGraph()
|
||||
|
@ -83,8 +83,10 @@ class ImageFieldTestMixin(SerializeMixin):
|
||||
field = getattr(instance, field_name)
|
||||
# Check height/width attributes of field.
|
||||
if width is None and height is None:
|
||||
self.assertRaises(ValueError, getattr, field, 'width')
|
||||
self.assertRaises(ValueError, getattr, field, 'height')
|
||||
with self.assertRaises(ValueError):
|
||||
getattr(field, 'width')
|
||||
with self.assertRaises(ValueError):
|
||||
getattr(field, 'height')
|
||||
else:
|
||||
self.assertEqual(field.width, width)
|
||||
self.assertEqual(field.height, height)
|
||||
|
@ -129,7 +129,8 @@ class DecimalFieldTests(test.TestCase):
|
||||
f = models.DecimalField(max_digits=4, decimal_places=2)
|
||||
self.assertEqual(f.to_python(3), Decimal("3"))
|
||||
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):
|
||||
f = models.DecimalField(default=Decimal("0.00"))
|
||||
@ -598,7 +599,8 @@ class SlugFieldTests(test.TestCase):
|
||||
class ValidationTest(test.SimpleTestCase):
|
||||
def test_charfield_raises_error_on_empty_string(self):
|
||||
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):
|
||||
f = models.CharField(blank=True)
|
||||
@ -610,7 +612,8 @@ class ValidationTest(test.SimpleTestCase):
|
||||
|
||||
def test_integerfield_raises_error_on_invalid_intput(self):
|
||||
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):
|
||||
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):
|
||||
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):
|
||||
f = models.CharField(choices=[('', '<><>'), ('a', 'A')])
|
||||
@ -639,7 +643,8 @@ class ValidationTest(test.SimpleTestCase):
|
||||
|
||||
def test_nullable_integerfield_raises_error_with_blank_false(self):
|
||||
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):
|
||||
f = models.IntegerField(null=True, blank=True)
|
||||
@ -647,16 +652,20 @@ class ValidationTest(test.SimpleTestCase):
|
||||
|
||||
def test_integerfield_raises_error_on_empty_input(self):
|
||||
f = models.IntegerField(null=False)
|
||||
self.assertRaises(ValidationError, f.clean, None, None)
|
||||
self.assertRaises(ValidationError, f.clean, '', None)
|
||||
with self.assertRaises(ValidationError):
|
||||
f.clean(None, None)
|
||||
with self.assertRaises(ValidationError):
|
||||
f.clean('', None)
|
||||
|
||||
def test_integerfield_validates_zero_against_choices(self):
|
||||
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):
|
||||
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):
|
||||
f = models.DateField()
|
||||
@ -664,7 +673,8 @@ class ValidationTest(test.SimpleTestCase):
|
||||
|
||||
def test_boolean_field_doesnt_accept_empty_input(self):
|
||||
f = models.BooleanField()
|
||||
self.assertRaises(ValidationError, f.clean, None, None)
|
||||
with self.assertRaises(ValidationError):
|
||||
f.clean(None, None)
|
||||
|
||||
|
||||
class IntegerFieldTests(test.TestCase):
|
||||
@ -864,7 +874,8 @@ class BinaryFieldTests(test.TestCase):
|
||||
|
||||
def test_max_length(self):
|
||||
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):
|
||||
@ -875,10 +886,12 @@ class GenericIPAddressFieldTests(test.TestCase):
|
||||
"""
|
||||
model_field = models.GenericIPAddressField(protocol='IPv4')
|
||||
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')
|
||||
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):
|
||||
"""
|
||||
|
@ -177,7 +177,8 @@ class ModelFormBaseTest(TestCase):
|
||||
def test_no_model_class(self):
|
||||
class NoModelModelForm(forms.ModelForm):
|
||||
pass
|
||||
self.assertRaises(ValueError, NoModelModelForm)
|
||||
with self.assertRaises(ValueError):
|
||||
NoModelModelForm()
|
||||
|
||||
def test_empty_fields_to_fields_for_model(self):
|
||||
"""
|
||||
@ -282,8 +283,8 @@ class ModelFormBaseTest(TestCase):
|
||||
self.fail('Declarative field raised FieldError incorrectly')
|
||||
|
||||
def test_extra_field_modelform_factory(self):
|
||||
self.assertRaises(FieldError, modelform_factory,
|
||||
Person, fields=['no-field', 'name'])
|
||||
with self.assertRaises(FieldError):
|
||||
modelform_factory(Person, fields=['no-field', 'name'])
|
||||
|
||||
def test_replace_field(self):
|
||||
class ReplaceField(forms.ModelForm):
|
||||
@ -1836,7 +1837,8 @@ class FileAndImageFieldTests(TestCase):
|
||||
"""
|
||||
f = forms.FileField(required=True)
|
||||
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):
|
||||
"""
|
||||
@ -2682,8 +2684,8 @@ class FormFieldCallbackTests(SimpleTestCase):
|
||||
|
||||
def test_bad_callback(self):
|
||||
# A bad callback provided by user still gives an error
|
||||
self.assertRaises(TypeError, modelform_factory, Person, fields="__all__",
|
||||
formfield_callback='not a function or callable')
|
||||
with self.assertRaises(TypeError):
|
||||
modelform_factory(Person, fields="__all__", formfield_callback='not a function or callable')
|
||||
|
||||
|
||||
class LocalizedModelFormTest(TestCase):
|
||||
|
@ -48,14 +48,16 @@ class ModelInheritanceTests(TestCase):
|
||||
|
||||
# However, the CommonInfo class cannot be used as a normal model (it
|
||||
# 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):
|
||||
# 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
|
||||
# part of the Place-Supplier Hierarchy.
|
||||
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):
|
||||
# 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
|
||||
# 'attached_%(class)s_set'.
|
||||
self.assertRaises(
|
||||
AttributeError, getattr, post, "attached_%(class)s_set"
|
||||
)
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(post, "attached_%(class)s_set")
|
||||
|
||||
def test_model_with_distinct_related_query_name(self):
|
||||
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):
|
||||
# This won't work because the Demon Dogs restaurant is not an Italian
|
||||
# restaurant.
|
||||
self.assertRaises(
|
||||
ItalianRestaurant.DoesNotExist,
|
||||
lambda: Place.objects.get(name="Demon Dogs").restaurant.italianrestaurant
|
||||
)
|
||||
with self.assertRaises(ItalianRestaurant.DoesNotExist):
|
||||
Place.objects.get(name="Demon Dogs").restaurant.italianrestaurant
|
||||
|
||||
def test_inherited_does_not_exist_exception(self):
|
||||
# An ItalianRestaurant which does not exist is also a Place which does
|
||||
# not exist.
|
||||
self.assertRaises(
|
||||
Place.DoesNotExist,
|
||||
ItalianRestaurant.objects.get, name="The Noodle Void"
|
||||
)
|
||||
with self.assertRaises(Place.DoesNotExist):
|
||||
ItalianRestaurant.objects.get(name="The Noodle Void")
|
||||
|
||||
def test_inherited_multiple_objects_returned_exception(self):
|
||||
# MultipleObjectsReturned is also inherited.
|
||||
self.assertRaises(
|
||||
Place.MultipleObjectsReturned,
|
||||
Restaurant.objects.get, id__lt=12321
|
||||
)
|
||||
with self.assertRaises(Place.MultipleObjectsReturned):
|
||||
Restaurant.objects.get(id__lt=12321)
|
||||
|
||||
def test_related_objects_for_inherited_models(self):
|
||||
# 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
|
||||
# a Supplier).
|
||||
p = Place.objects.get(name="Joe's Chickens")
|
||||
self.assertRaises(
|
||||
Restaurant.DoesNotExist, lambda: p.restaurant
|
||||
)
|
||||
with self.assertRaises(Restaurant.DoesNotExist):
|
||||
p.restaurant
|
||||
|
||||
self.assertEqual(p.supplier, s1)
|
||||
self.assertQuerysetEqual(
|
||||
|
@ -171,14 +171,10 @@ class ModelInheritanceTest(TestCase):
|
||||
# the ItalianRestaurant.
|
||||
Restaurant.objects.all().delete()
|
||||
|
||||
self.assertRaises(
|
||||
Place.DoesNotExist,
|
||||
Place.objects.get,
|
||||
pk=ident)
|
||||
self.assertRaises(
|
||||
ItalianRestaurant.DoesNotExist,
|
||||
ItalianRestaurant.objects.get,
|
||||
pk=ident)
|
||||
with self.assertRaises(Place.DoesNotExist):
|
||||
Place.objects.get(pk=ident)
|
||||
with self.assertRaises(ItalianRestaurant.DoesNotExist):
|
||||
ItalianRestaurant.objects.get(pk=ident)
|
||||
|
||||
def test_issue_6755(self):
|
||||
"""
|
||||
@ -241,14 +237,12 @@ class ModelInheritanceTest(TestCase):
|
||||
|
||||
self.assertEqual(c1.get_next_by_pub_date(), c2)
|
||||
self.assertEqual(c2.get_next_by_pub_date(), c3)
|
||||
self.assertRaises(
|
||||
ArticleWithAuthor.DoesNotExist,
|
||||
c3.get_next_by_pub_date)
|
||||
with self.assertRaises(ArticleWithAuthor.DoesNotExist):
|
||||
c3.get_next_by_pub_date()
|
||||
self.assertEqual(c3.get_previous_by_pub_date(), c2)
|
||||
self.assertEqual(c2.get_previous_by_pub_date(), c1)
|
||||
self.assertRaises(
|
||||
ArticleWithAuthor.DoesNotExist,
|
||||
c1.get_previous_by_pub_date)
|
||||
with self.assertRaises(ArticleWithAuthor.DoesNotExist):
|
||||
c1.get_previous_by_pub_date()
|
||||
|
||||
def test_inherited_fields(self):
|
||||
"""
|
||||
|
@ -225,7 +225,8 @@ class ModelValidationTest(TestCase):
|
||||
def test_pk_validation(self):
|
||||
NonAutoPK.objects.create(name="one")
|
||||
again = NonAutoPK(name="one")
|
||||
self.assertRaises(ValidationError, again.validate_unique)
|
||||
with self.assertRaises(ValidationError):
|
||||
again.validate_unique()
|
||||
|
||||
|
||||
class EvaluateMethodTest(TestCase):
|
||||
|
@ -49,11 +49,8 @@ class QueryTestCase(TestCase):
|
||||
except Book.DoesNotExist:
|
||||
self.fail('"Pro Django" should exist on default database')
|
||||
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.using('other').get,
|
||||
title="Pro Django"
|
||||
)
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.using('other').get(title="Pro Django")
|
||||
|
||||
try:
|
||||
Book.objects.get(title="Dive into Python")
|
||||
@ -61,11 +58,8 @@ class QueryTestCase(TestCase):
|
||||
except Book.DoesNotExist:
|
||||
self.fail('"Dive into Python" should exist on default database')
|
||||
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.using('other').get,
|
||||
title="Dive into Python"
|
||||
)
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.using('other').get(title="Dive into Python")
|
||||
|
||||
def test_other_creation(self):
|
||||
"Objects created on another database don't leak onto the default database"
|
||||
@ -85,32 +79,20 @@ class QueryTestCase(TestCase):
|
||||
except Book.DoesNotExist:
|
||||
self.fail('"Pro Django" should exist on other database')
|
||||
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.get,
|
||||
title="Pro Django"
|
||||
)
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.using('default').get,
|
||||
title="Pro Django"
|
||||
)
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.get(title="Pro Django")
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.using('default').get(title="Pro Django")
|
||||
|
||||
try:
|
||||
Book.objects.using('other').get(title="Dive into Python")
|
||||
except Book.DoesNotExist:
|
||||
self.fail('"Dive into Python" should exist on other database')
|
||||
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.get,
|
||||
title="Dive into Python"
|
||||
)
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.using('default').get,
|
||||
title="Dive into Python"
|
||||
)
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.get(title="Dive into Python")
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.using('default').get(title="Dive into Python")
|
||||
|
||||
def test_refresh(self):
|
||||
dive = Book()
|
||||
@ -137,20 +119,24 @@ class QueryTestCase(TestCase):
|
||||
|
||||
dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4))
|
||||
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")
|
||||
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")
|
||||
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)
|
||||
self.assertEqual(dive.title, "Dive into Python")
|
||||
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')
|
||||
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
|
||||
# so it falls back to the default. If the subquery explicitly uses a
|
||||
# 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
|
||||
with self.assertRaises(ValueError):
|
||||
@ -1605,7 +1592,8 @@ class AuthTestCase(TestCase):
|
||||
self.assertEqual(alice.username, 'alice')
|
||||
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
|
||||
bob = User.objects.using('default').get(username='bob')
|
||||
@ -1613,7 +1601,8 @@ class AuthTestCase(TestCase):
|
||||
self.assertEqual(bob.username, 'bob')
|
||||
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
|
||||
self.assertEqual(User.objects.using('default').count(), 1)
|
||||
@ -1663,11 +1652,8 @@ class FixtureTestCase(TestCase):
|
||||
except Book.DoesNotExist:
|
||||
self.fail('"Pro Django" should exist on default database')
|
||||
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.using('other').get,
|
||||
title="Pro Django"
|
||||
)
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.using('other').get(title="Pro Django")
|
||||
|
||||
# Check that "Dive into Python" exists on the default database, but not on other database
|
||||
try:
|
||||
@ -1675,16 +1661,10 @@ class FixtureTestCase(TestCase):
|
||||
except Book.DoesNotExist:
|
||||
self.fail('"Dive into Python" should exist on other database')
|
||||
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.get,
|
||||
title="Dive into Python"
|
||||
)
|
||||
self.assertRaises(
|
||||
Book.DoesNotExist,
|
||||
Book.objects.using('default').get,
|
||||
title="Dive into Python"
|
||||
)
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.get(title="Dive into Python")
|
||||
with self.assertRaises(Book.DoesNotExist):
|
||||
Book.objects.using('default').get(title="Dive into Python")
|
||||
|
||||
# Check that "Definitive Guide" exists on the both databases
|
||||
try:
|
||||
@ -1846,7 +1826,8 @@ class RouterAttributeErrorTestCase(TestCase):
|
||||
b = Book.objects.create(title="Pro Django",
|
||||
published=datetime.date(2008, 12, 16))
|
||||
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):
|
||||
"Check that the AttributeError from AttributeErrorRouter bubbles up"
|
||||
@ -1854,7 +1835,8 @@ class RouterAttributeErrorTestCase(TestCase):
|
||||
dive.title = "Dive into Python"
|
||||
dive.published = datetime.date(2009, 5, 4)
|
||||
with self.override_router():
|
||||
self.assertRaises(AttributeError, dive.save)
|
||||
with self.assertRaises(AttributeError):
|
||||
dive.save()
|
||||
|
||||
def test_attribute_error_delete(self):
|
||||
"Check that the AttributeError from AttributeErrorRouter bubbles up"
|
||||
@ -1864,7 +1846,8 @@ class RouterAttributeErrorTestCase(TestCase):
|
||||
b.authors.set([p])
|
||||
b.editor = p
|
||||
with self.override_router():
|
||||
self.assertRaises(AttributeError, b.delete)
|
||||
with self.assertRaises(AttributeError):
|
||||
b.delete()
|
||||
|
||||
def test_attribute_error_m2m(self):
|
||||
"Check that the AttributeError from AttributeErrorRouter bubbles up"
|
||||
|
@ -40,10 +40,12 @@ class NullQueriesTests(TestCase):
|
||||
)
|
||||
|
||||
# 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
|
||||
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.
|
||||
p2 = Poll(question="How?")
|
||||
|
@ -229,10 +229,12 @@ class OneToOneTests(TestCase):
|
||||
self.assertIsNone(ug_bar.place)
|
||||
|
||||
# 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
|
||||
self.assertRaises(ValueError, setattr, p, 'restaurant', p)
|
||||
with self.assertRaises(ValueError):
|
||||
setattr(p, 'restaurant', p)
|
||||
|
||||
# Creation using keyword argument should cache the related object.
|
||||
p = Place.objects.get(name="Demon Dogs")
|
||||
@ -459,14 +461,16 @@ class OneToOneTests(TestCase):
|
||||
School.objects.use_for_related_fields = True
|
||||
try:
|
||||
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:
|
||||
School.objects.use_for_related_fields = False
|
||||
|
||||
Director.objects.use_for_related_fields = True
|
||||
try:
|
||||
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:
|
||||
Director.objects.use_for_related_fields = False
|
||||
|
||||
|
@ -114,9 +114,12 @@ class PaginationTests(unittest.TestCase):
|
||||
raised.
|
||||
"""
|
||||
paginator = Paginator([1, 2, 3], 2)
|
||||
self.assertRaises(InvalidPage, paginator.page, 3)
|
||||
self.assertRaises(PageNotAnInteger, paginator.validate_number, None)
|
||||
self.assertRaises(PageNotAnInteger, paginator.validate_number, 'x')
|
||||
with self.assertRaises(InvalidPage):
|
||||
paginator.page(3)
|
||||
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
|
||||
paginator = Paginator([], 2)
|
||||
self.assertEqual(paginator.validate_number(1), 1)
|
||||
@ -203,9 +206,12 @@ class PaginationTests(unittest.TestCase):
|
||||
self.check_indexes(params, 'last', last)
|
||||
|
||||
# When no items and no empty first page, we should get EmptyPage error.
|
||||
self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 0, False), 1, None)
|
||||
self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 1, False), 1, None)
|
||||
self.assertRaises(EmptyPage, self.check_indexes, ([], 4, 2, False), 1, None)
|
||||
with self.assertRaises(EmptyPage):
|
||||
self.check_indexes(([], 4, 0, 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):
|
||||
"""
|
||||
@ -267,7 +273,8 @@ class ModelPaginationTests(TestCase):
|
||||
self.assertFalse(p.has_previous())
|
||||
self.assertTrue(p.has_other_pages())
|
||||
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(5, p.end_index())
|
||||
|
||||
@ -286,7 +293,8 @@ class ModelPaginationTests(TestCase):
|
||||
self.assertFalse(p.has_next())
|
||||
self.assertTrue(p.has_previous())
|
||||
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(6, p.start_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.
|
||||
# (this happens from the template engine when using eg: {% page_obj.has_previous %})
|
||||
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.assertNotIsInstance(p.object_list, list)
|
||||
|
||||
|
@ -16,7 +16,8 @@ class PropertyTests(TestCase):
|
||||
|
||||
def test_setter(self):
|
||||
# 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.
|
||||
with self.assertRaisesMessage(TypeError, "'full_name' is an invalid keyword argument"):
|
||||
|
@ -93,31 +93,19 @@ class ProxyModelTests(TestCase):
|
||||
LowerStatusPerson.objects.create(status="low", name="homer")
|
||||
max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']
|
||||
|
||||
self.assertRaises(
|
||||
Person.DoesNotExist,
|
||||
MyPersonProxy.objects.get,
|
||||
name='Zathras'
|
||||
)
|
||||
self.assertRaises(
|
||||
Person.MultipleObjectsReturned,
|
||||
MyPersonProxy.objects.get,
|
||||
id__lt=max_id + 1
|
||||
)
|
||||
self.assertRaises(
|
||||
Person.DoesNotExist,
|
||||
StatusPerson.objects.get,
|
||||
name='Zathras'
|
||||
)
|
||||
with self.assertRaises(Person.DoesNotExist):
|
||||
MyPersonProxy.objects.get(name='Zathras')
|
||||
with self.assertRaises(Person.MultipleObjectsReturned):
|
||||
MyPersonProxy.objects.get(id__lt=max_id + 1)
|
||||
with self.assertRaises(Person.DoesNotExist):
|
||||
StatusPerson.objects.get(name='Zathras')
|
||||
|
||||
StatusPerson.objects.create(name='Bazza Jr.')
|
||||
StatusPerson.objects.create(name='Foo Jr.')
|
||||
max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']
|
||||
|
||||
self.assertRaises(
|
||||
Person.MultipleObjectsReturned,
|
||||
StatusPerson.objects.get,
|
||||
id__lt=max_id + 1
|
||||
)
|
||||
with self.assertRaises(Person.MultipleObjectsReturned):
|
||||
StatusPerson.objects.get(id__lt=max_id + 1)
|
||||
|
||||
def test_abc(self):
|
||||
"""
|
||||
@ -127,7 +115,8 @@ class ProxyModelTests(TestCase):
|
||||
class NoAbstract(Abstract):
|
||||
class Meta:
|
||||
proxy = True
|
||||
self.assertRaises(TypeError, build_abc)
|
||||
with self.assertRaises(TypeError):
|
||||
build_abc()
|
||||
|
||||
@isolate_apps('proxy_models')
|
||||
def test_no_cbc(self):
|
||||
@ -138,7 +127,8 @@ class ProxyModelTests(TestCase):
|
||||
class TooManyBases(Person, Abstract):
|
||||
class Meta:
|
||||
proxy = True
|
||||
self.assertRaises(TypeError, build_no_cbc)
|
||||
with self.assertRaises(TypeError):
|
||||
build_no_cbc()
|
||||
|
||||
@isolate_apps('proxy_models')
|
||||
def test_no_base_classes(self):
|
||||
@ -146,7 +136,8 @@ class ProxyModelTests(TestCase):
|
||||
class NoBaseClasses(models.Model):
|
||||
class Meta:
|
||||
proxy = True
|
||||
self.assertRaises(TypeError, build_no_base_classes)
|
||||
with self.assertRaises(TypeError):
|
||||
build_no_base_classes()
|
||||
|
||||
@isolate_apps('proxy_models')
|
||||
def test_new_fields(self):
|
||||
|
@ -2930,7 +2930,8 @@ class WhereNodeTest(TestCase):
|
||||
def test_empty_full_handling_conjunction(self):
|
||||
compiler = WhereNodeTest.MockCompiler()
|
||||
w = WhereNode(children=[NothingNode()])
|
||||
self.assertRaises(EmptyResultSet, w.as_sql, compiler, connection)
|
||||
with self.assertRaises(EmptyResultSet):
|
||||
w.as_sql(compiler, connection)
|
||||
w.negate()
|
||||
self.assertEqual(w.as_sql(compiler, connection), ('', []))
|
||||
w = WhereNode(children=[self.DummyNode(), self.DummyNode()])
|
||||
@ -2938,14 +2939,16 @@ class WhereNodeTest(TestCase):
|
||||
w.negate()
|
||||
self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', []))
|
||||
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()
|
||||
self.assertEqual(w.as_sql(compiler, connection), ('', []))
|
||||
|
||||
def test_empty_full_handling_disjunction(self):
|
||||
compiler = WhereNodeTest.MockCompiler()
|
||||
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()
|
||||
self.assertEqual(w.as_sql(compiler, connection), ('', []))
|
||||
w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR')
|
||||
@ -2987,8 +2990,10 @@ class IteratorExceptionsTest(TestCase):
|
||||
# Test for #19895 - second iteration over invalid queryset
|
||||
# raises errors.
|
||||
qs = Article.objects.order_by('invalid_column')
|
||||
self.assertRaises(FieldError, list, qs)
|
||||
self.assertRaises(FieldError, list, qs)
|
||||
with self.assertRaises(FieldError):
|
||||
list(qs)
|
||||
with self.assertRaises(FieldError):
|
||||
list(qs)
|
||||
|
||||
|
||||
class NullJoinPromotionOrTest(TestCase):
|
||||
|
@ -275,7 +275,8 @@ class RawQueryTests(TestCase):
|
||||
first_two = Author.objects.raw(query)[0: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):
|
||||
# date is the end of the Cuban Missile Crisis, I have no idea when
|
||||
|
@ -345,7 +345,8 @@ class RequestsTests(SimpleTestCase):
|
||||
'CONTENT_LENGTH': len(payload),
|
||||
'wsgi.input': payload})
|
||||
self.assertEqual(request.read(2), b'na')
|
||||
self.assertRaises(RawPostDataException, lambda: request.body)
|
||||
with self.assertRaises(RawPostDataException):
|
||||
request.body
|
||||
self.assertEqual(request.POST, {})
|
||||
|
||||
def test_non_ascii_POST(self):
|
||||
@ -390,7 +391,8 @@ class RequestsTests(SimpleTestCase):
|
||||
'CONTENT_LENGTH': len(payload),
|
||||
'wsgi.input': payload})
|
||||
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):
|
||||
"""
|
||||
|
@ -127,7 +127,8 @@ class HttpResponseTests(SimpleTestCase):
|
||||
generator = ("{}".format(i) for i in range(10))
|
||||
response = HttpResponse(content=generator)
|
||||
self.assertEqual(response.content, b'0123456789')
|
||||
self.assertRaises(StopIteration, next, generator)
|
||||
with self.assertRaises(StopIteration):
|
||||
next(generator)
|
||||
|
||||
cache.set('my-response-key', response)
|
||||
response = cache.get('my-response-key')
|
||||
|
@ -48,5 +48,5 @@ class ReverseLookupTests(TestCase):
|
||||
"""
|
||||
If a related_name is given you can't use the field name instead
|
||||
"""
|
||||
self.assertRaises(FieldError, Poll.objects.get,
|
||||
choice__name__exact="This is the answer")
|
||||
with self.assertRaises(FieldError):
|
||||
Poll.objects.get(choice__name__exact="This is the answer")
|
||||
|
@ -139,10 +139,8 @@ class SchemaTests(TransactionTestCase):
|
||||
with connection.schema_editor() as editor:
|
||||
editor.delete_model(Author)
|
||||
# Check that it's gone
|
||||
self.assertRaises(
|
||||
DatabaseError,
|
||||
lambda: list(Author.objects.all()),
|
||||
)
|
||||
with self.assertRaises(DatabaseError):
|
||||
list(Author.objects.all())
|
||||
|
||||
@skipUnlessDBFeature('supports_foreign_keys')
|
||||
def test_fk(self):
|
||||
@ -1026,7 +1024,8 @@ class SchemaTests(TransactionTestCase):
|
||||
new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors")
|
||||
new_field.contribute_to_class(LocalAuthorWithM2M, "tags")
|
||||
# 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
|
||||
with connection.schema_editor() as editor:
|
||||
editor.add_field(LocalAuthorWithM2M, new_field)
|
||||
@ -1042,7 +1041,8 @@ class SchemaTests(TransactionTestCase):
|
||||
with connection.schema_editor() as editor:
|
||||
editor.remove_field(LocalAuthorWithM2M, new_field)
|
||||
# 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
|
||||
# we've removed the tags field.
|
||||
@ -1145,10 +1145,8 @@ class SchemaTests(TransactionTestCase):
|
||||
with connection.schema_editor() as editor:
|
||||
editor.alter_field(LocalBookWithM2M, old_field, new_field)
|
||||
# Ensure old M2M is gone
|
||||
self.assertRaises(
|
||||
DatabaseError,
|
||||
self.column_classes, LocalBookWithM2M._meta.get_field("tags").remote_field.through
|
||||
)
|
||||
with self.assertRaises(DatabaseError):
|
||||
self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through)
|
||||
|
||||
# This model looks like the new model and is used for teardown.
|
||||
opts = LocalBookWithM2M._meta
|
||||
@ -1217,7 +1215,8 @@ class SchemaTests(TransactionTestCase):
|
||||
editor.create_model(Tag)
|
||||
# Ensure the field is unique to begin with
|
||||
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()
|
||||
# Alter the slug field to be non-unique
|
||||
old_field = Tag._meta.get_field("slug")
|
||||
@ -1236,7 +1235,8 @@ class SchemaTests(TransactionTestCase):
|
||||
editor.alter_field(Tag, new_field, new_field2, strict=True)
|
||||
# Ensure the field is unique again
|
||||
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()
|
||||
# Rename the field
|
||||
new_field3 = SlugField(unique=True)
|
||||
@ -1245,7 +1245,8 @@ class SchemaTests(TransactionTestCase):
|
||||
editor.alter_field(Tag, new_field2, new_field3, strict=True)
|
||||
# Ensure the field is still unique
|
||||
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()
|
||||
|
||||
def test_unique_together(self):
|
||||
@ -1259,7 +1260,8 @@ class SchemaTests(TransactionTestCase):
|
||||
UniqueTest.objects.create(year=2012, slug="foo")
|
||||
UniqueTest.objects.create(year=2011, slug="foo")
|
||||
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()
|
||||
# Alter the model to its non-unique-together companion
|
||||
with connection.schema_editor() as editor:
|
||||
@ -1275,7 +1277,8 @@ class SchemaTests(TransactionTestCase):
|
||||
editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together)
|
||||
# Ensure the fields are unique again
|
||||
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()
|
||||
|
||||
def test_unique_together_with_fk(self):
|
||||
@ -1576,10 +1579,8 @@ class SchemaTests(TransactionTestCase):
|
||||
with connection.schema_editor() as editor:
|
||||
editor.delete_model(Thing)
|
||||
# Check that it's gone
|
||||
self.assertRaises(
|
||||
DatabaseError,
|
||||
lambda: list(Thing.objects.all()),
|
||||
)
|
||||
with self.assertRaises(DatabaseError):
|
||||
list(Thing.objects.all())
|
||||
|
||||
@skipUnlessDBFeature('supports_foreign_keys')
|
||||
def test_remove_constraints_capital_letters(self):
|
||||
|
@ -110,11 +110,8 @@ class SelectForUpdateTests(TransactionTestCase):
|
||||
that supports FOR UPDATE but not NOWAIT, then we should find
|
||||
that a DatabaseError is raised.
|
||||
"""
|
||||
self.assertRaises(
|
||||
DatabaseError,
|
||||
list,
|
||||
Person.objects.all().select_for_update(nowait=True)
|
||||
)
|
||||
with self.assertRaises(DatabaseError):
|
||||
list(Person.objects.all().select_for_update(nowait=True))
|
||||
|
||||
@skipUnlessDBFeature('has_select_for_update')
|
||||
def test_for_update_requires_transaction(self):
|
||||
|
@ -142,11 +142,8 @@ class SelectRelatedTests(TestCase):
|
||||
self.assertEqual(s, 'Diptera')
|
||||
|
||||
def test_depth_fields_fails(self):
|
||||
self.assertRaises(
|
||||
TypeError,
|
||||
Species.objects.select_related,
|
||||
'genus__family__order', depth=4
|
||||
)
|
||||
with self.assertRaises(TypeError):
|
||||
Species.objects.select_related('genus__family__order', depth=4)
|
||||
|
||||
def test_none_clears_list(self):
|
||||
queryset = Species.objects.select_related('genus').select_related(None)
|
||||
|
@ -72,11 +72,13 @@ class NoYamlSerializerTestCase(SimpleTestCase):
|
||||
def test_serializer_pyyaml_error_message(self):
|
||||
"""Using yaml serializer without pyyaml raises ImportError"""
|
||||
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):
|
||||
"""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):
|
||||
"""Calling dumpdata produces an error when yaml package missing"""
|
||||
|
@ -223,7 +223,8 @@ class SessionTestsMixin(object):
|
||||
def test_session_key_is_read_only(self):
|
||||
def set_session_key(session):
|
||||
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
|
||||
def test_default_expiry(self):
|
||||
@ -474,7 +475,8 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase):
|
||||
@override_settings(SESSION_CACHE_ALIAS='sessions')
|
||||
def test_non_default_cache(self):
|
||||
# 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS.
|
||||
self.assertRaises(InvalidCacheBackendError, self.backend)
|
||||
with self.assertRaises(InvalidCacheBackendError):
|
||||
self.backend()
|
||||
|
||||
|
||||
@override_settings(USE_TZ=True)
|
||||
@ -506,20 +508,21 @@ class FileSessionTests(SessionTestsMixin, unittest.TestCase):
|
||||
def test_configuration_check(self):
|
||||
del self.backend._storage_path
|
||||
# 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):
|
||||
# Ensure we don't allow directory-traversal.
|
||||
# This is tested directly on _key_to_file, as load() will swallow
|
||||
# a SuspiciousOperation in the same way as an IOError - by creating
|
||||
# a new session, making it unclear whether the slashes were detected.
|
||||
self.assertRaises(InvalidSessionKey,
|
||||
self.backend()._key_to_file, "a\\b\\c")
|
||||
with self.assertRaises(InvalidSessionKey):
|
||||
self.backend()._key_to_file("a\\b\\c")
|
||||
|
||||
def test_invalid_key_forwardslash(self):
|
||||
# Ensure we don't allow directory-traversal
|
||||
self.assertRaises(InvalidSessionKey,
|
||||
self.backend()._key_to_file, "a/b/c")
|
||||
with self.assertRaises(InvalidSessionKey):
|
||||
self.backend()._key_to_file("a/b/c")
|
||||
|
||||
@override_settings(
|
||||
SESSION_ENGINE="django.contrib.sessions.backends.file",
|
||||
|
@ -179,24 +179,29 @@ class SettingsTests(SimpleTestCase):
|
||||
del settings.TEST
|
||||
|
||||
def test_override_doesnt_leak(self):
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
with self.settings(TEST='override'):
|
||||
self.assertEqual('override', settings.TEST)
|
||||
settings.TEST = 'test'
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
|
||||
@override_settings(TEST='override')
|
||||
def test_decorator(self):
|
||||
self.assertEqual('override', settings.TEST)
|
||||
|
||||
def test_context_manager(self):
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
override = override_settings(TEST='override')
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
override.enable()
|
||||
self.assertEqual('override', settings.TEST)
|
||||
override.disable()
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
|
||||
def test_class_decorator(self):
|
||||
# SimpleTestCase can be decorated by override_settings, but not ut.TestCase
|
||||
@ -215,7 +220,8 @@ class SettingsTests(SimpleTestCase):
|
||||
decorated = override_settings(TEST='override')(UnittestTestCaseSubclass)
|
||||
|
||||
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'):
|
||||
self.assertEqual(self.testvalue, 'override')
|
||||
self.assertEqual(self.testvalue, None)
|
||||
@ -232,10 +238,12 @@ class SettingsTests(SimpleTestCase):
|
||||
settings.TEST = 'test'
|
||||
self.assertEqual('test', settings.TEST)
|
||||
del settings.TEST
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
|
||||
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):
|
||||
"""
|
||||
@ -245,10 +253,12 @@ class SettingsTests(SimpleTestCase):
|
||||
previous_l10n = settings.USE_L10N
|
||||
with self.settings(USE_I18N=False):
|
||||
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
|
||||
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_L10N, previous_l10n)
|
||||
|
||||
@ -258,8 +268,10 @@ class SettingsTests(SimpleTestCase):
|
||||
runtime, not when it was instantiated.
|
||||
"""
|
||||
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST2')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST2')
|
||||
|
||||
inner = override_settings(TEST2='override')
|
||||
with override_settings(TEST='override'):
|
||||
@ -270,10 +282,13 @@ class SettingsTests(SimpleTestCase):
|
||||
# inner's __exit__ should have restored the settings of the outer
|
||||
# context manager, not those when the class was instantiated
|
||||
self.assertEqual('override', settings.TEST)
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST2')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST2')
|
||||
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST')
|
||||
self.assertRaises(AttributeError, getattr, settings, 'TEST2')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST')
|
||||
with self.assertRaises(AttributeError):
|
||||
getattr(settings, 'TEST2')
|
||||
|
||||
|
||||
class TestComplexSettingOverride(SimpleTestCase):
|
||||
|
@ -25,16 +25,16 @@ class SignedCookieTest(SimpleTestCase):
|
||||
request.COOKIES['a'] = response.cookies['a'].value
|
||||
value = request.get_signed_cookie('a', salt='one')
|
||||
self.assertEqual(value, 'hello')
|
||||
self.assertRaises(signing.BadSignature,
|
||||
request.get_signed_cookie, 'a', salt='two')
|
||||
with self.assertRaises(signing.BadSignature):
|
||||
request.get_signed_cookie('a', salt='two')
|
||||
|
||||
def test_detects_tampering(self):
|
||||
response = HttpResponse()
|
||||
response.set_signed_cookie('c', 'hello')
|
||||
request = HttpRequest()
|
||||
request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$'
|
||||
self.assertRaises(signing.BadSignature,
|
||||
request.get_signed_cookie, 'c')
|
||||
with self.assertRaises(signing.BadSignature):
|
||||
request.get_signed_cookie('c')
|
||||
|
||||
def test_default_argument_suppresses_exceptions(self):
|
||||
response = HttpResponse()
|
||||
@ -55,8 +55,8 @@ class SignedCookieTest(SimpleTestCase):
|
||||
with freeze_time(123456800):
|
||||
self.assertEqual(request.get_signed_cookie('c', max_age=12), value)
|
||||
self.assertEqual(request.get_signed_cookie('c', max_age=11), value)
|
||||
self.assertRaises(signing.SignatureExpired,
|
||||
request.get_signed_cookie, 'c', max_age=10)
|
||||
with self.assertRaises(signing.SignatureExpired):
|
||||
request.get_signed_cookie('c', max_age=10)
|
||||
|
||||
@override_settings(SECRET_KEY=b'\xe7')
|
||||
def test_signed_cookies_with_binary_key(self):
|
||||
|
@ -70,8 +70,8 @@ class TestSigner(SimpleTestCase):
|
||||
)
|
||||
self.assertEqual(value, signer.unsign(signed_value))
|
||||
for transform in transforms:
|
||||
self.assertRaises(
|
||||
signing.BadSignature, signer.unsign, transform(signed_value))
|
||||
with self.assertRaises(signing.BadSignature):
|
||||
signer.unsign(transform(signed_value))
|
||||
|
||||
def test_dumps_loads(self):
|
||||
"dumps and loads be reversible for any JSON serializable object"
|
||||
@ -103,8 +103,8 @@ class TestSigner(SimpleTestCase):
|
||||
encoded = signing.dumps(value)
|
||||
self.assertEqual(value, signing.loads(encoded))
|
||||
for transform in transforms:
|
||||
self.assertRaises(
|
||||
signing.BadSignature, signing.loads, transform(encoded))
|
||||
with self.assertRaises(signing.BadSignature):
|
||||
signing.loads(transform(encoded))
|
||||
|
||||
def test_works_with_non_ascii_keys(self):
|
||||
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)
|
||||
# max_age parameter can also accept a datetime.timedelta object
|
||||
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)
|
||||
|
@ -176,7 +176,8 @@ class HTTPSitemapTests(SitemapTestsBase):
|
||||
Sitemap.get_urls and no Site objects exist
|
||||
"""
|
||||
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'})
|
||||
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
|
||||
actually installed.
|
||||
"""
|
||||
self.assertRaises(ImproperlyConfigured, Sitemap().get_urls)
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
Sitemap().get_urls()
|
||||
|
||||
def test_sitemap_item(self):
|
||||
"""
|
||||
|
@ -35,7 +35,8 @@ class SitesFrameworkTests(TestCase):
|
||||
s = Site.objects.get_current()
|
||||
self.assertIsInstance(s, Site)
|
||||
s.delete()
|
||||
self.assertRaises(ObjectDoesNotExist, Site.objects.get_current)
|
||||
with self.assertRaises(ObjectDoesNotExist):
|
||||
Site.objects.get_current()
|
||||
|
||||
def test_site_cache(self):
|
||||
# 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.
|
||||
self.assertIsInstance(Site.objects.get_current(), Site)
|
||||
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'])
|
||||
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
|
||||
# but there is no matching Site
|
||||
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
|
||||
with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}):
|
||||
@ -112,7 +115,8 @@ class SitesFrameworkTests(TestCase):
|
||||
|
||||
# Host header with non-matching domain
|
||||
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
|
||||
with self.modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}):
|
||||
@ -128,11 +132,14 @@ class SitesFrameworkTests(TestCase):
|
||||
# Regression for #17320
|
||||
# Domain names are not allowed contain whitespace characters
|
||||
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"
|
||||
self.assertRaises(ValidationError, site.full_clean)
|
||||
with self.assertRaises(ValidationError):
|
||||
site.full_clean()
|
||||
site.domain = "test\ntest"
|
||||
self.assertRaises(ValidationError, site.full_clean)
|
||||
with self.assertRaises(ValidationError):
|
||||
site.full_clean()
|
||||
|
||||
def test_clear_site_cache(self):
|
||||
request = HttpRequest()
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user