From 3d0dcd7f5af378d3ab6adb303b913e6c7b2e0ee5 Mon Sep 17 00:00:00 2001 From: Hasan Date: Sun, 17 Jan 2016 14:56:39 +0330 Subject: [PATCH] Refs #26022 -- Used context manager version of assertRaises in tests. --- tests/admin_filters/tests.py | 3 +- tests/admin_registration/tests.py | 8 +- tests/admin_utils/tests.py | 6 +- tests/aggregation_regress/tests.py | 40 ++--- tests/auth_tests/test_auth_backends.py | 9 +- tests/auth_tests/test_decorators.py | 3 +- tests/auth_tests/test_hashers.py | 6 +- tests/auth_tests/test_mixins.py | 6 +- tests/auth_tests/test_tokens.py | 5 +- tests/backends/tests.py | 35 ++-- tests/basic/tests.py | 8 +- tests/cache/tests.py | 42 +++-- tests/check_framework/tests.py | 3 +- tests/contenttypes_tests/test_models.py | 6 +- tests/custom_columns/tests.py | 6 +- tests/custom_managers/tests.py | 3 +- tests/custom_pk/tests.py | 9 +- tests/datatypes/tests.py | 5 +- tests/dates/tests.py | 6 +- tests/delete/tests.py | 3 +- tests/expressions/tests.py | 6 +- tests/file_storage/tests.py | 23 ++- tests/file_uploads/tests.py | 8 +- tests/files/tests.py | 3 +- tests/flatpages_tests/test_templatetags.py | 28 ++-- tests/foreign_object/tests.py | 3 +- tests/forms_tests/tests/test_fields.py | 15 +- tests/forms_tests/tests/test_forms.py | 3 +- tests/forms_tests/tests/test_input_formats.py | 156 ++++++++++++------ tests/forms_tests/tests/test_validators.py | 7 +- tests/forms_tests/tests/tests.py | 3 +- tests/generic_relations_regress/tests.py | 3 +- tests/generic_views/test_base.py | 12 +- tests/generic_views/test_dates.py | 6 +- tests/generic_views/test_detail.py | 9 +- tests/generic_views/test_list.py | 3 +- tests/get_earliest_or_latest/tests.py | 18 +- tests/get_object_or_404/tests.py | 27 ++- tests/get_or_create/tests.py | 25 ++- tests/gis_tests/distapp/tests.py | 13 +- tests/gis_tests/gdal_tests/test_driver.py | 3 +- tests/gis_tests/gdal_tests/test_ds.py | 15 +- tests/gis_tests/gdal_tests/test_envelope.py | 21 ++- tests/gis_tests/gdal_tests/test_geom.py | 21 ++- tests/gis_tests/gdal_tests/test_raster.py | 3 +- tests/gis_tests/gdal_tests/test_srs.py | 6 +- tests/gis_tests/geo3d/tests.py | 4 +- tests/gis_tests/geoapp/test_feeds.py | 6 +- tests/gis_tests/geoapp/tests.py | 39 +++-- tests/gis_tests/geogapp/tests.py | 9 +- tests/gis_tests/geos_tests/test_geos.py | 81 ++++++--- .../geos_tests/test_geos_mutation.py | 12 +- tests/gis_tests/geos_tests/test_io.py | 18 +- .../gis_tests/geos_tests/test_mutable_list.py | 48 ++++-- tests/gis_tests/layermap/tests.py | 21 ++- tests/gis_tests/test_geoforms.py | 9 +- tests/gis_tests/test_geoip.py | 18 +- tests/gis_tests/test_geoip2.py | 18 +- tests/gis_tests/test_measure.py | 6 +- tests/gis_tests/tests.py | 6 +- tests/httpwrappers/tests.py | 104 ++++++++---- tests/i18n/patterns/tests.py | 3 +- tests/i18n/tests.py | 3 +- tests/inline_formsets/tests.py | 8 +- tests/lookup/tests.py | 14 +- tests/m2m_through_regress/tests.py | 6 +- tests/mail/tests.py | 9 +- tests/many_to_many/tests.py | 3 +- tests/many_to_one/tests.py | 22 ++- tests/many_to_one_null/tests.py | 6 +- tests/messages_tests/base.py | 4 +- tests/middleware_exceptions/tests.py | 3 +- tests/migrations/test_graph.py | 12 +- tests/model_fields/test_imagefield.py | 6 +- tests/model_fields/tests.py | 39 +++-- tests/model_forms/tests.py | 14 +- tests/model_inheritance/tests.py | 34 ++-- tests/model_inheritance_regress/tests.py | 22 +-- tests/model_regress/tests.py | 3 +- tests/multiple_database/tests.py | 93 +++++------ tests/null_queries/tests.py | 6 +- tests/one_to_one/tests.py | 12 +- tests/pagination/tests.py | 27 ++- tests/properties/tests.py | 3 +- tests/proxy_models/tests.py | 37 ++--- tests/queries/tests.py | 15 +- tests/raw_query/tests.py | 3 +- tests/requests/tests.py | 6 +- tests/responses/tests.py | 3 +- tests/reverse_lookup/tests.py | 4 +- tests/schema/tests.py | 39 ++--- tests/select_for_update/tests.py | 7 +- tests/select_related/tests.py | 7 +- tests/serializers/test_yaml.py | 6 +- tests/sessions_tests/tests.py | 17 +- tests/settings_tests/tests.py | 45 +++-- tests/signed_cookies_tests/tests.py | 12 +- tests/signing/tests.py | 11 +- tests/sitemaps_tests/test_http.py | 6 +- tests/sites_tests/tests.py | 21 ++- tests/staticfiles_tests/cases.py | 6 +- tests/staticfiles_tests/test_finders.py | 6 +- tests/syndication_tests/tests.py | 5 +- tests/template_tests/test_parser.py | 6 +- tests/template_tests/test_response.py | 22 +-- tests/test_client/tests.py | 3 +- tests/test_runner/tests.py | 3 +- tests/test_utils/tests.py | 24 ++- tests/update/tests.py | 4 +- tests/urlpatterns_reverse/tests.py | 51 ++++-- tests/user_commands/tests.py | 6 +- tests/utils_tests/test_baseconv.py | 3 +- tests/utils_tests/test_dateparse.py | 9 +- tests/utils_tests/test_encoding.py | 3 +- tests/utils_tests/test_functional.py | 3 +- tests/utils_tests/test_http.py | 15 +- tests/utils_tests/test_module_loading.py | 28 ++-- tests/view_tests/tests/test_debug.py | 7 +- 118 files changed, 1086 insertions(+), 760 deletions(-) diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index 51f571ad3f..97b9100f5d 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -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) diff --git a/tests/admin_registration/tests.py b/tests/admin_registration/tests.py index 202fed86e3..ffca76886e 100644 --- a/tests/admin_registration/tests.py +++ b/tests/admin_registration/tests.py @@ -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." diff --git a/tests/admin_utils/tests.py b/tests/admin_utils/tests.py index 01ec6702cc..0da9143c19 100644 --- a/tests/admin_utils/tests.py +++ b/tests/admin_utils/tests.py @@ -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" diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py index 1373594276..7068b86f6a 100644 --- a/tests/aggregation_regress/tests.py +++ b/tests/aggregation_regress/tests.py @@ -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( diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py index c0ccbb3971..54a863bcda 100644 --- a/tests/auth_tests/test_auth_backends.py +++ b/tests/auth_tests/test_auth_backends.py @@ -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): diff --git a/tests/auth_tests/test_decorators.py b/tests/auth_tests/test_decorators.py index 61c1962a74..d1ad87f528 100644 --- a/tests/auth_tests/test_decorators.py +++ b/tests/auth_tests/test_decorators.py @@ -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) diff --git a/tests/auth_tests/test_hashers.py b/tests/auth_tests/test_hashers.py index 9b4d90881c..6a14ba8140 100644 --- a/tests/auth_tests/test_hashers.py +++ b/tests/auth_tests/test_hashers.py @@ -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')) diff --git a/tests/auth_tests/test_mixins.py b/tests/auth_tests/test_mixins.py index c04715dc8f..6ada1f59bb 100644 --- a/tests/auth_tests/test_mixins.py +++ b/tests/auth_tests/test_mixins.py @@ -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) diff --git a/tests/auth_tests/test_tokens.py b/tests/auth_tests/test_tokens.py index fa26f223f7..bddcd323d7 100644 --- a/tests/auth_tests/test_tokens.py +++ b/tests/auth_tests/test_tokens.py @@ -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) diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 460b522079..00d44cf881 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -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): """ diff --git a/tests/basic/tests.py b/tests/basic/tests.py index c334a8bfc6..95ed7ad897 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -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, diff --git a/tests/cache/tests.py b/tests/cache/tests.py index cd61690d34..af91339434 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -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( diff --git a/tests/check_framework/tests.py b/tests/check_framework/tests.py index 90b8a944f0..270cd74a52 100644 --- a/tests/check_framework/tests.py +++ b/tests/check_framework/tests.py @@ -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): diff --git a/tests/contenttypes_tests/test_models.py b/tests/contenttypes_tests/test_models.py index 37e0b93048..12010ac781 100644 --- a/tests/contenttypes_tests/test_models.py +++ b/tests/contenttypes_tests/test_models.py @@ -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): """ diff --git a/tests/custom_columns/tests.py b/tests/custom_columns/tests.py index 1826eb8db1..2b5526453f 100644 --- a/tests/custom_columns/tests.py +++ b/tests/custom_columns/tests.py @@ -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): diff --git a/tests/custom_managers/tests.py b/tests/custom_managers/tests.py index 28198b4422..ee1cc141a5 100644 --- a/tests/custom_managers/tests.py +++ b/tests/custom_managers/tests.py @@ -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): """ diff --git a/tests/custom_pk/tests.py b/tests/custom_pk/tests.py index 9ba506d953..fdcbd80e04 100644 --- a/tests/custom_pk/tests.py +++ b/tests/custom_pk/tests.py @@ -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): """ diff --git a/tests/datatypes/tests.py b/tests/datatypes/tests.py index a69855da1f..612b1ae2e4 100644 --- a/tests/datatypes/tests.py +++ b/tests/datatypes/tests.py @@ -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 diff --git a/tests/dates/tests.py b/tests/dates/tests.py index 3b6fb5505b..97c4face6e 100644 --- a/tests/dates/tests.py +++ b/tests/dates/tests.py @@ -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( diff --git a/tests/delete/tests.py b/tests/delete/tests.py index 1a8941904c..5b38dc0cd6 100644 --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -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, diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py index f68892782f..c7b7a7a15c 100644 --- a/tests/expressions/tests.py +++ b/tests/expressions/tests.py @@ -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 diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index 25c6161d5e..28a09ae557 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -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")) diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py index ccecfce5c1..976707f4b4 100644 --- a/tests/file_uploads/tests.py +++ b/tests/file_uploads/tests.py @@ -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 diff --git a/tests/files/tests.py b/tests/files/tests.py index 2ce4d0139d..6eb7f30d61 100644 --- a/tests/files/tests.py +++ b/tests/files/tests.py @@ -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)) diff --git a/tests/flatpages_tests/test_templatetags.py b/tests/flatpages_tests/test_templatetags.py index dbe1446988..d766d13964 100644 --- a/tests/flatpages_tests/test_templatetags.py +++ b/tests/flatpages_tests/test_templatetags.py @@ -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 %}") diff --git a/tests/foreign_object/tests.py b/tests/foreign_object/tests.py index f83698175e..bc76ceb93d 100644 --- a/tests/foreign_object/tests.py +++ b/tests/foreign_object/tests.py @@ -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 diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py index 45545cdb48..b46f897391 100644 --- a/tests/forms_tests/tests/test_fields.py +++ b/tests/forms_tests/tests/test_fields.py @@ -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 diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index 00d2045786..66b1737e6f 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -3227,7 +3227,8 @@ Good luck picking a username that doesn't already exist.

""" 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'}) diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py index afb2513a95..51118a1470 100644 --- a/tests/forms_tests/tests/test_input_formats.py +++ b/tests/forms_tests/tests/test_input_formats.py @@ -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') diff --git a/tests/forms_tests/tests/test_validators.py b/tests/forms_tests/tests/test_validators.py index cb7104756a..8c348d600d 100644 --- a/tests/forms_tests/tests/test_validators.py +++ b/tests/forms_tests/tests/test_validators.py @@ -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."]) diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py index 992dbc851e..f1bd66fc6b 100644 --- a/tests/forms_tests/tests/tests.py +++ b/tests/forms_tests/tests/tests.py @@ -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 diff --git a/tests/generic_relations_regress/tests.py b/tests/generic_relations_regress/tests.py index b6782fe13f..957f285b23 100644 --- a/tests/generic_relations_regress/tests.py +++ b/tests/generic_relations_regress/tests.py @@ -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""" diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py index 72c813b204..a5e528585c 100644 --- a/tests/generic_views/test_base.py +++ b/tests/generic_views/test_base.py @@ -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() diff --git a/tests/generic_views/test_dates.py b/tests/generic_views/test_dates.py index 681f3fb97e..3b34a4caee 100644 --- a/tests/generic_views/test_dates.py +++ b/tests/generic_views/test_dates.py @@ -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): """ diff --git a/tests/generic_views/test_detail.py b/tests/generic_views/test_detail.py index 9ffa3f82e7..4c91f6eeb0 100644 --- a/tests/generic_views/test_detail.py +++ b/tests/generic_views/test_detail.py @@ -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/') diff --git a/tests/generic_views/test_list.py b/tests/generic_views/test_list.py index e6ce7cb539..fb2ac20951 100644 --- a/tests/generic_views/test_list.py +++ b/tests/generic_views/test_list.py @@ -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 diff --git a/tests/get_earliest_or_latest/tests.py b/tests/get_earliest_or_latest/tests.py index c4e4bb7586..d74a0724d7 100644 --- a/tests/get_earliest_or_latest/tests.py +++ b/tests/get_earliest_or_latest/tests.py @@ -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() diff --git a/tests/get_object_or_404/tests.py b/tests/get_object_or_404/tests.py index 05bea661ed..55d1de7c2c 100644 --- a/tests/get_object_or_404/tests.py +++ b/tests/get_object_or_404/tests.py @@ -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( diff --git a/tests/get_or_create/tests.py b/tests/get_or_create/tests.py index 762cf57025..0f790e67b2 100644 --- a/tests/get_or_create/tests.py +++ b/tests/get_or_create/tests.py @@ -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): diff --git a/tests/gis_tests/distapp/tests.py b/tests/gis_tests/distapp/tests.py index d31a019e11..ca057da9b8 100644 --- a/tests/gis_tests/distapp/tests.py +++ b/tests/gis_tests/distapp/tests.py @@ -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') diff --git a/tests/gis_tests/gdal_tests/test_driver.py b/tests/gis_tests/gdal_tests/test_driver.py index 265bb7a32a..1efefcf131 100644 --- a/tests/gis_tests/gdal_tests/test_driver.py +++ b/tests/gis_tests/gdal_tests/test_driver.py @@ -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." diff --git a/tests/gis_tests/gdal_tests/test_ds.py b/tests/gis_tests/gdal_tests/test_ds.py index d6a46d5a95..83517bba8f 100644 --- a/tests/gis_tests/gdal_tests/test_ds.py +++ b/tests/gis_tests/gdal_tests/test_ds.py @@ -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) diff --git a/tests/gis_tests/gdal_tests/test_envelope.py b/tests/gis_tests/gdal_tests/test_envelope.py index cf0eea4b1a..c6e5026fe4 100644 --- a/tests/gis_tests/gdal_tests/test_envelope.py +++ b/tests/gis_tests/gdal_tests/test_envelope.py @@ -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: diff --git a/tests/gis_tests/gdal_tests/test_geom.py b/tests/gis_tests/gdal_tests/test_geom.py index 60aecd1d35..07a79f6d12 100644 --- a/tests/gis_tests/gdal_tests/test_geom.py +++ b/tests/gis_tests/gdal_tests/test_geom.py @@ -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. diff --git a/tests/gis_tests/gdal_tests/test_raster.py b/tests/gis_tests/gdal_tests/test_raster.py index ea3f423429..8391887f6c 100644 --- a/tests/gis_tests/gdal_tests/test_raster.py +++ b/tests/gis_tests/gdal_tests/test_raster.py @@ -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 diff --git a/tests/gis_tests/gdal_tests/test_srs.py b/tests/gis_tests/gdal_tests/test_srs.py index 98e4312786..f8dadfb1fc 100644 --- a/tests/gis_tests/gdal_tests/test_srs.py +++ b/tests/gis_tests/gdal_tests/test_srs.py @@ -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']) diff --git a/tests/gis_tests/geo3d/tests.py b/tests/gis_tests/geo3d/tests.py index 156b59da09..1181e4b6c2 100644 --- a/tests/gis_tests/geo3d/tests.py +++ b/tests/gis_tests/geo3d/tests.py @@ -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) diff --git a/tests/gis_tests/geoapp/test_feeds.py b/tests/gis_tests/geoapp/test_feeds.py index 55c19c01c9..0974554737 100644 --- a/tests/gis_tests/geoapp/test_feeds.py +++ b/tests/gis_tests/geoapp/test_feeds.py @@ -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 - self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in + with self.assertRaises(ValueError): # Box in + self.client.get('/feeds/w3cgeo2/') + with self.assertRaises(ValueError): # Polygons in + self.client.get('/feeds/w3cgeo3/') diff --git a/tests/gis_tests/geoapp/tests.py b/tests/gis_tests/geoapp/tests.py index a4a4c5e189..f0b6f7ba65 100644 --- a/tests/gis_tests/geoapp/tests.py +++ b/tests/gis_tests/geoapp/tests.py @@ -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) diff --git a/tests/gis_tests/geogapp/tests.py b/tests/gis_tests/geogapp/tests.py index b99203afea..c314c93c5d 100644 --- a/tests/gis_tests/geogapp/tests.py +++ b/tests/gis_tests/geogapp/tests.py @@ -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): diff --git a/tests/gis_tests/geos_tests/test_geos.py b/tests/gis_tests/geos_tests/test_geos.py index 116e8d35f8..ef03736f9e 100644 --- a/tests/gis_tests/geos_tests/test_geos.py +++ b/tests/gis_tests/geos_tests/test_geos.py @@ -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." diff --git a/tests/gis_tests/geos_tests/test_geos_mutation.py b/tests/gis_tests/geos_tests/test_geos_mutation.py index 81a6e975fe..56f2a7d7a7 100644 --- a/tests/gis_tests/geos_tests/test_geos_mutation.py +++ b/tests/gis_tests/geos_tests/test_geos_mutation.py @@ -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' diff --git a/tests/gis_tests/geos_tests/test_io.py b/tests/gis_tests/geos_tests/test_io.py index 920767ded4..306824a4a8 100644 --- a/tests/gis_tests/geos_tests/test_io.py +++ b/tests/gis_tests/geos_tests/test_io.py @@ -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 diff --git a/tests/gis_tests/geos_tests/test_mutable_list.py b/tests/gis_tests/geos_tests/test_mutable_list.py index 8f2242ea31..7eb3680b7c 100644 --- a/tests/gis_tests/geos_tests/test_mutable_list.py +++ b/tests/gis_tests/geos_tests/test_mutable_list.py @@ -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' diff --git a/tests/gis_tests/layermap/tests.py b/tests/gis_tests/layermap/tests.py index 3ebbf4292e..7713706704 100644 --- a/tests/gis_tests/layermap/tests.py +++ b/tests/gis_tests/layermap/tests.py @@ -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 diff --git a/tests/gis_tests/test_geoforms.py b/tests/gis_tests/test_geoforms.py index 317389da84..df2aa08066 100644 --- a/tests/gis_tests/test_geoforms.py +++ b/tests/gis_tests/test_geoforms.py @@ -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): diff --git a/tests/gis_tests/test_geoip.py b/tests/gis_tests/test_geoip.py index 7142023127..2d037d74d6 100644 --- a/tests/gis_tests/test_geoip.py +++ b/tests/gis_tests/test_geoip.py @@ -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='') # 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." diff --git a/tests/gis_tests/test_geoip2.py b/tests/gis_tests/test_geoip2.py index 150ca2cd4e..89dd2f5870 100644 --- a/tests/gis_tests/test_geoip2.py +++ b/tests/gis_tests/test_geoip2.py @@ -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='') # 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): diff --git a/tests/gis_tests/test_measure.py b/tests/gis_tests/test_measure.py index 771c10fe9d..06d35c0371 100644 --- a/tests/gis_tests/test_measure.py +++ b/tests/gis_tests/test_measure.py @@ -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" diff --git a/tests/gis_tests/tests.py b/tests/gis_tests/tests.py index e05e4c3560..1ee3a56a16 100644 --- a/tests/gis_tests/tests.py +++ b/tests/gis_tests/tests.py @@ -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 diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index 53dd58da3b..60db33e0bd 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -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): diff --git a/tests/i18n/patterns/tests.py b/tests/i18n/patterns/tests.py index 284bb697a4..83c7fd93e5 100644 --- a/tests/i18n/patterns/tests.py +++ b/tests/i18n/patterns/tests.py @@ -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') diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py index 5c3a82cb84..9bbbf10a09 100644 --- a/tests/i18n/tests.py +++ b/tests/i18n/tests.py @@ -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): diff --git a/tests/inline_formsets/tests.py b/tests/inline_formsets/tests.py index 167d2a68e1..3bb7586575 100644 --- a/tests/inline_formsets/tests.py +++ b/tests/inline_formsets/tests.py @@ -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 ", - 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): """ diff --git a/tests/lookup/tests.py b/tests/lookup/tests.py index bc1f3aacce..ac96e8ac7a 100644 --- a/tests/lookup/tests.py +++ b/tests/lookup/tests.py @@ -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): '') self.assertEqual(repr(self.a4.get_next_by_pub_date()), '') - self.assertRaises(Article.DoesNotExist, self.a5.get_next_by_pub_date) + with self.assertRaises(Article.DoesNotExist): + self.a5.get_next_by_pub_date() self.assertEqual(repr(self.a6.get_next_by_pub_date()), '') self.assertEqual(repr(self.a7.get_next_by_pub_date()), diff --git a/tests/m2m_through_regress/tests.py b/tests/m2m_through_regress/tests.py index 82d88a85dc..4eaa4431b6 100644 --- a/tests/m2m_through_regress/tests.py +++ b/tests/m2m_through_regress/tests.py @@ -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( diff --git a/tests/mail/tests.py b/tests/mail/tests.py index 72e5ca57f3..58b6151efb 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -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() diff --git a/tests/many_to_many/tests.py b/tests/many_to_many/tests.py index 9e10ae4b84..d7f81c5c29 100644 --- a/tests/many_to_many/tests.py +++ b/tests/many_to_many/tests.py @@ -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. diff --git a/tests/many_to_one/tests.py b/tests/many_to_one/tests.py index 79caec7177..692a3e15e4 100644 --- a/tests/many_to_one/tests.py +++ b/tests/many_to_one/tests.py @@ -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 diff --git a/tests/many_to_one_null/tests.py b/tests/many_to_one_null/tests.py index 91c2e13cd7..1a3785bd33 100644 --- a/tests/many_to_one_null/tests.py +++ b/tests/many_to_one_null/tests.py @@ -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(), ['']) # 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(), ['']) def test_set(self): diff --git a/tests/messages_tests/base.py b/tests/messages_tests/base.py index e3d0e6d8d4..57c4137e62 100644 --- a/tests/messages_tests/base.py +++ b/tests/messages_tests/base.py @@ -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'}, diff --git a/tests/middleware_exceptions/tests.py b/tests/middleware_exceptions/tests.py index a8fb41fbd4..ef9d19fe21 100644 --- a/tests/middleware_exceptions/tests.py +++ b/tests/middleware_exceptions/tests.py @@ -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): diff --git a/tests/migrations/test_graph.py b/tests/migrations/test_graph.py index 6260d41887..50cefdf158 100644 --- a/tests/migrations/test_graph.py +++ b/tests/migrations/test_graph.py @@ -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() diff --git a/tests/model_fields/test_imagefield.py b/tests/model_fields/test_imagefield.py index 8320fafaa8..ada8e12e3b 100644 --- a/tests/model_fields/test_imagefield.py +++ b/tests/model_fields/test_imagefield.py @@ -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) diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py index 9a27dd4670..7305e6ab9b 100644 --- a/tests/model_fields/tests.py +++ b/tests/model_fields/tests.py @@ -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): """ diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index 12401759bd..a1adeec445 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -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): diff --git a/tests/model_inheritance/tests.py b/tests/model_inheritance/tests.py index a6661d439e..b856a07736 100644 --- a/tests/model_inheritance/tests.py +++ b/tests/model_inheritance/tests.py @@ -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( diff --git a/tests/model_inheritance_regress/tests.py b/tests/model_inheritance_regress/tests.py index 7f6f872b42..f7044144ec 100644 --- a/tests/model_inheritance_regress/tests.py +++ b/tests/model_inheritance_regress/tests.py @@ -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): """ diff --git a/tests/model_regress/tests.py b/tests/model_regress/tests.py index feb81f32bc..6c4cecf43b 100644 --- a/tests/model_regress/tests.py +++ b/tests/model_regress/tests.py @@ -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): diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py index befc6b0578..e174023012 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -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" diff --git a/tests/null_queries/tests.py b/tests/null_queries/tests.py index 3ba307d397..8f58b9dee1 100644 --- a/tests/null_queries/tests.py +++ b/tests/null_queries/tests.py @@ -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?") diff --git a/tests/one_to_one/tests.py b/tests/one_to_one/tests.py index f5629a5268..4e3ce072a4 100644 --- a/tests/one_to_one/tests.py +++ b/tests/one_to_one/tests.py @@ -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 diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py index 31658810a2..8823dfef30 100644 --- a/tests/pagination/tests.py +++ b/tests/pagination/tests.py @@ -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) diff --git a/tests/properties/tests.py b/tests/properties/tests.py index 06e30e7b1f..175bf0eb83 100644 --- a/tests/properties/tests.py +++ b/tests/properties/tests.py @@ -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"): diff --git a/tests/proxy_models/tests.py b/tests/proxy_models/tests.py index 874a2596f0..3527c5bc06 100644 --- a/tests/proxy_models/tests.py +++ b/tests/proxy_models/tests.py @@ -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): diff --git a/tests/queries/tests.py b/tests/queries/tests.py index efbd8e3f3d..b00b64027e 100644 --- a/tests/queries/tests.py +++ b/tests/queries/tests.py @@ -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): diff --git a/tests/raw_query/tests.py b/tests/raw_query/tests.py index 2f80c23f32..015a58c287 100644 --- a/tests/raw_query/tests.py +++ b/tests/raw_query/tests.py @@ -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 diff --git a/tests/requests/tests.py b/tests/requests/tests.py index 80f79e321b..280320ae43 100644 --- a/tests/requests/tests.py +++ b/tests/requests/tests.py @@ -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): """ diff --git a/tests/responses/tests.py b/tests/responses/tests.py index 5f7a0b5e12..53e517496e 100644 --- a/tests/responses/tests.py +++ b/tests/responses/tests.py @@ -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') diff --git a/tests/reverse_lookup/tests.py b/tests/reverse_lookup/tests.py index 1b9184d682..dda3c29691 100644 --- a/tests/reverse_lookup/tests.py +++ b/tests/reverse_lookup/tests.py @@ -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") diff --git a/tests/schema/tests.py b/tests/schema/tests.py index ab95b0c79e..4cacaab635 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -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): diff --git a/tests/select_for_update/tests.py b/tests/select_for_update/tests.py index 70cd21d594..8958cacf62 100644 --- a/tests/select_for_update/tests.py +++ b/tests/select_for_update/tests.py @@ -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): diff --git a/tests/select_related/tests.py b/tests/select_related/tests.py index 93d96c9665..59eac3802b 100644 --- a/tests/select_related/tests.py +++ b/tests/select_related/tests.py @@ -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) diff --git a/tests/serializers/test_yaml.py b/tests/serializers/test_yaml.py index d4e5c35578..2b5933d698 100644 --- a/tests/serializers/test_yaml.py +++ b/tests/serializers/test_yaml.py @@ -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""" diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py index 0a99aad1ac..c5a7692799 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -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", diff --git a/tests/settings_tests/tests.py b/tests/settings_tests/tests.py index bf4f071c2f..87352ba32a 100644 --- a/tests/settings_tests/tests.py +++ b/tests/settings_tests/tests.py @@ -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): diff --git a/tests/signed_cookies_tests/tests.py b/tests/signed_cookies_tests/tests.py index 6c3ba8c0ce..81940367af 100644 --- a/tests/signed_cookies_tests/tests.py +++ b/tests/signed_cookies_tests/tests.py @@ -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): diff --git a/tests/signing/tests.py b/tests/signing/tests.py index 1d084e0252..910345ed8c 100644 --- a/tests/signing/tests.py +++ b/tests/signing/tests.py @@ -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) diff --git a/tests/sitemaps_tests/test_http.py b/tests/sitemaps_tests/test_http.py index 5b3cbb5843..aac4d69a20 100644 --- a/tests/sitemaps_tests/test_http.py +++ b/tests/sitemaps_tests/test_http.py @@ -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): """ diff --git a/tests/sites_tests/tests.py b/tests/sites_tests/tests.py index 6bf7ce4d0b..ffd6223866 100644 --- a/tests/sites_tests/tests.py +++ b/tests/sites_tests/tests.py @@ -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() diff --git a/tests/staticfiles_tests/cases.py b/tests/staticfiles_tests/cases.py index aedb257351..941c45274a 100644 --- a/tests/staticfiles_tests/cases.py +++ b/tests/staticfiles_tests/cases.py @@ -29,7 +29,8 @@ class BaseStaticFilesTestCase(object): ) def assertFileNotFound(self, filepath): - self.assertRaises(IOError, self._get_file, filepath) + with self.assertRaises(IOError): + self._get_file(filepath) def render_template(self, template, **kwargs): if isinstance(template, six.string_types): @@ -46,7 +47,8 @@ class BaseStaticFilesTestCase(object): self.assertEqual(self.render_template(template, **kwargs), result) def assertStaticRaises(self, exc, path, result, asvar=False, **kwargs): - self.assertRaises(exc, self.assertStaticRenders, path, result, **kwargs) + with self.assertRaises(exc): + self.assertStaticRenders(path, result, **kwargs) @override_settings(**TEST_SETTINGS) diff --git a/tests/staticfiles_tests/test_finders.py b/tests/staticfiles_tests/test_finders.py index a88770be48..0aa95e06c3 100644 --- a/tests/staticfiles_tests/test_finders.py +++ b/tests/staticfiles_tests/test_finders.py @@ -111,8 +111,10 @@ class TestMiscFinder(SimpleTestCase): We can't determine if STATICFILES_DIRS is set correctly just by looking at the type, but we can determine if it's definitely wrong. """ - self.assertRaises(ImproperlyConfigured, finders.FileSystemFinder) + with self.assertRaises(ImproperlyConfigured): + finders.FileSystemFinder() @override_settings(MEDIA_ROOT='') def test_location_empty(self): - self.assertRaises(ImproperlyConfigured, finders.DefaultStorageFinder) + with self.assertRaises(ImproperlyConfigured): + finders.DefaultStorageFinder() diff --git a/tests/syndication_tests/tests.py b/tests/syndication_tests/tests.py index 5369320bdd..870df35bd5 100644 --- a/tests/syndication_tests/tests.py +++ b/tests/syndication_tests/tests.py @@ -461,9 +461,8 @@ class SyndicationFeedTest(FeedTestCase): Test that an ImproperlyConfigured is raised if no link could be found for the item(s). """ - self.assertRaises(ImproperlyConfigured, - self.client.get, - '/syndication/articles/') + with self.assertRaises(ImproperlyConfigured): + self.client.get('/syndication/articles/') def test_template_feed(self): """ diff --git a/tests/template_tests/test_parser.py b/tests/template_tests/test_parser.py index 6ff57c2cf5..7ae72c83f4 100644 --- a/tests/template_tests/test_parser.py +++ b/tests/template_tests/test_parser.py @@ -44,7 +44,8 @@ class ParserTests(TestCase): # Filtered variables should reject access of attributes beginning with # underscores. - self.assertRaises(TemplateSyntaxError, FilterExpression, "article._hidden|upper", p) + with self.assertRaises(TemplateSyntaxError): + FilterExpression("article._hidden|upper", p) def test_variable_parsing(self): c = {"article": {"section": "News"}} @@ -67,7 +68,8 @@ class ParserTests(TestCase): # Variables should reject access of attributes beginning with # underscores. - self.assertRaises(TemplateSyntaxError, Variable, "article._hidden") + with self.assertRaises(TemplateSyntaxError): + Variable("article._hidden") # Variables should raise on non string type with six.assertRaisesRegex(self, TypeError, "Variable must be a string or number, got <(class|type) 'dict'>"): diff --git a/tests/template_tests/test_response.py b/tests/template_tests/test_response.py index e7f71be4f1..3e99134afb 100644 --- a/tests/template_tests/test_response.py +++ b/tests/template_tests/test_response.py @@ -77,7 +77,8 @@ class SimpleTemplateResponseTest(SimpleTestCase): def iteration(): for x in response: pass - self.assertRaises(ContentNotRenderedError, iteration) + with self.assertRaises(ContentNotRenderedError): + iteration() self.assertFalse(response.is_rendered) def test_iteration_rendered(self): @@ -90,7 +91,8 @@ class SimpleTemplateResponseTest(SimpleTestCase): # unrendered response raises an exception when content is accessed response = self._response() self.assertFalse(response.is_rendered) - self.assertRaises(ContentNotRenderedError, lambda: response.content) + with self.assertRaises(ContentNotRenderedError): + response.content self.assertFalse(response.is_rendered) def test_content_access_rendered(self): @@ -160,8 +162,8 @@ class SimpleTemplateResponseTest(SimpleTestCase): 'value': 123, 'fn': datetime.now, }) - self.assertRaises(ContentNotRenderedError, - pickle.dumps, response) + with self.assertRaises(ContentNotRenderedError): + pickle.dumps(response) # But if we render the response, we can pickle it. response.render() @@ -188,8 +190,8 @@ class SimpleTemplateResponseTest(SimpleTestCase): 'value': 123, 'fn': datetime.now, }) - self.assertRaises(ContentNotRenderedError, - pickle.dumps, response) + with self.assertRaises(ContentNotRenderedError): + pickle.dumps(response) response.render() pickled_response = pickle.dumps(response) @@ -274,8 +276,8 @@ class TemplateResponseTest(SimpleTestCase): 'fn': datetime.now, } ) - self.assertRaises(ContentNotRenderedError, - pickle.dumps, response) + with self.assertRaises(ContentNotRenderedError): + pickle.dumps(response) # But if we render the response, we can pickle it. response.render() @@ -307,8 +309,8 @@ class TemplateResponseTest(SimpleTestCase): 'value': 123, 'fn': datetime.now, }) - self.assertRaises(ContentNotRenderedError, - pickle.dumps, response) + with self.assertRaises(ContentNotRenderedError): + pickle.dumps(response) response.render() pickled_response = pickle.dumps(response) diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index d8e0b9d6f0..911bcebd3b 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -601,7 +601,8 @@ class ClientTest(TestCase): def test_view_with_exception(self): "Request a page that is known to throw an error" - self.assertRaises(KeyError, self.client.get, "/broken_view/") + with self.assertRaises(KeyError): + self.client.get("/broken_view/") # Try the same assertion, a different way try: diff --git a/tests/test_runner/tests.py b/tests/test_runner/tests.py index 8a8332093d..a35c26628b 100644 --- a/tests/test_runner/tests.py +++ b/tests/test_runner/tests.py @@ -107,7 +107,8 @@ class DependencyOrderingTests(unittest.TestCase): 'alpha': ['bravo'], } - self.assertRaises(ImproperlyConfigured, dependency_ordered, raw, dependencies=dependencies) + with self.assertRaises(ImproperlyConfigured): + dependency_ordered(raw, dependencies=dependencies) def test_own_alias_dependency(self): raw = [ diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index c2251bebb4..fdc7a7e5dc 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -127,7 +127,8 @@ class AssertNumQueriesTests(TestCase): def test_func(): raise ValueError - self.assertRaises(ValueError, self.assertNumQueries, 2, test_func) + with self.assertRaises(ValueError): + self.assertNumQueries(2, test_func) def test_assert_num_queries_with_client(self): person = Person.objects.create(name='test') @@ -865,22 +866,29 @@ class OverrideSettingsTests(SimpleTestCase): reverse('second') def test_urlconf_cache(self): - self.assertRaises(NoReverseMatch, lambda: reverse('first')) - self.assertRaises(NoReverseMatch, lambda: reverse('second')) + with self.assertRaises(NoReverseMatch): + reverse('first') + with self.assertRaises(NoReverseMatch): + reverse('second') with override_settings(ROOT_URLCONF=FirstUrls): self.client.get(reverse('first')) - self.assertRaises(NoReverseMatch, lambda: reverse('second')) + with self.assertRaises(NoReverseMatch): + reverse('second') with override_settings(ROOT_URLCONF=SecondUrls): - self.assertRaises(NoReverseMatch, lambda: reverse('first')) + with self.assertRaises(NoReverseMatch): + reverse('first') self.client.get(reverse('second')) self.client.get(reverse('first')) - self.assertRaises(NoReverseMatch, lambda: reverse('second')) + with self.assertRaises(NoReverseMatch): + reverse('second') - self.assertRaises(NoReverseMatch, lambda: reverse('first')) - self.assertRaises(NoReverseMatch, lambda: reverse('second')) + with self.assertRaises(NoReverseMatch): + reverse('first') + with self.assertRaises(NoReverseMatch): + reverse('second') def test_override_media_root(self): """ diff --git a/tests/update/tests.py b/tests/update/tests.py index 1ed316c958..0a4e1fb3ba 100644 --- a/tests/update/tests.py +++ b/tests/update/tests.py @@ -123,8 +123,8 @@ class AdvancedTests(TestCase): We do not support update on already sliced query sets. """ method = DataPoint.objects.all()[:2].update - self.assertRaises(AssertionError, method, - another_value='another thing') + with self.assertRaises(AssertionError): + method(another_value='another thing') def test_update_respects_to_field(self): """ diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py index 42cbe50091..b949cb0173 100644 --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -275,7 +275,8 @@ class URLPatternReverse(SimpleTestCase): def test_reverse_none(self): # Reversing None should raise an error, not return the last un-named view. - self.assertRaises(NoReverseMatch, reverse, None) + with self.assertRaises(NoReverseMatch): + reverse(None) @override_script_prefix('/{{invalid}}/') def test_prefix_braces(self): @@ -372,10 +373,14 @@ class ResolverTests(unittest.TestCase): Regression for #10834. """ - self.assertRaises(Resolver404, resolve, '') - self.assertRaises(Resolver404, resolve, 'a') - self.assertRaises(Resolver404, resolve, '\\') - self.assertRaises(Resolver404, resolve, '.') + with self.assertRaises(Resolver404): + resolve('') + with self.assertRaises(Resolver404): + resolve('a') + with self.assertRaises(Resolver404): + resolve('\\') + with self.assertRaises(Resolver404): + resolve('.') def test_404_tried_urls_have_names(self): """ @@ -493,7 +498,8 @@ class ReverseShortcutTests(SimpleTestCase): self.assertEqual(res.url, '/places/1/') res = redirect('headlines', year='2008', month='02', day='17') self.assertEqual(res.url, '/headlines/2008.02.17/') - self.assertRaises(NoReverseMatch, redirect, 'not-a-view') + with self.assertRaises(NoReverseMatch): + redirect('not-a-view') def test_redirect_to_url(self): res = redirect('/foo/') @@ -524,7 +530,8 @@ class ReverseShortcutTests(SimpleTestCase): from .views import absolute_kwargs_view res = redirect(absolute_kwargs_view) self.assertEqual(res.url, '/absolute_arg_view/') - self.assertRaises(NoReverseMatch, redirect, absolute_kwargs_view, wrong_argument=None) + with self.assertRaises(NoReverseMatch): + redirect(absolute_kwargs_view, wrong_argument=None) @override_settings(ROOT_URLCONF='urlpatterns_reverse.namespace_urls') @@ -533,20 +540,28 @@ class NamespaceTests(SimpleTestCase): def test_ambiguous_object(self): "Names deployed via dynamic URL objects that require namespaces can't be resolved" - self.assertRaises(NoReverseMatch, reverse, 'urlobject-view') - self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', args=[37, 42]) - self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', kwargs={'arg1': 42, 'arg2': 37}) + with self.assertRaises(NoReverseMatch): + reverse('urlobject-view') + with self.assertRaises(NoReverseMatch): + reverse('urlobject-view', args=[37, 42]) + with self.assertRaises(NoReverseMatch): + reverse('urlobject-view', kwargs={'arg1': 42, 'arg2': 37}) def test_ambiguous_urlpattern(self): "Names deployed via dynamic URL objects that require namespaces can't be resolved" - self.assertRaises(NoReverseMatch, reverse, 'inner-nothing') - self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', args=[37, 42]) - self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', kwargs={'arg1': 42, 'arg2': 37}) + with self.assertRaises(NoReverseMatch): + reverse('inner-nothing') + with self.assertRaises(NoReverseMatch): + reverse('inner-nothing', args=[37, 42]) + with self.assertRaises(NoReverseMatch): + reverse('inner-nothing', kwargs={'arg1': 42, 'arg2': 37}) def test_non_existent_namespace(self): "Non-existent namespaces raise errors" - self.assertRaises(NoReverseMatch, reverse, 'blahblah:urlobject-view') - self.assertRaises(NoReverseMatch, reverse, 'test-ns1:blahblah:urlobject-view') + with self.assertRaises(NoReverseMatch): + reverse('blahblah:urlobject-view') + with self.assertRaises(NoReverseMatch): + reverse('test-ns1:blahblah:urlobject-view') def test_normal_name(self): "Normal lookups work as expected" @@ -897,7 +912,8 @@ class DefaultErrorHandlerTests(SimpleTestCase): self.fail("Shouldn't get an AttributeError due to undefined 404 handler") try: - self.assertRaises(ValueError, self.client.get, '/bad_view/') + with self.assertRaises(ValueError): + self.client.get('/bad_view/') except AttributeError: self.fail("Shouldn't get an AttributeError due to undefined 500 handler") @@ -907,7 +923,8 @@ class NoRootUrlConfTests(SimpleTestCase): """Tests for handler404 and handler500 if ROOT_URLCONF is None""" def test_no_handler_exception(self): - self.assertRaises(ImproperlyConfigured, self.client.get, '/test/me/') + with self.assertRaises(ImproperlyConfigured): + self.client.get('/test/me/') @override_settings(ROOT_URLCONF='urlpatterns_reverse.namespace_urls') diff --git a/tests/user_commands/tests.py b/tests/user_commands/tests.py index 048ac4d963..2c19339ddc 100644 --- a/tests/user_commands/tests.py +++ b/tests/user_commands/tests.py @@ -44,7 +44,8 @@ class CommandTests(SimpleTestCase): def test_explode(self): """ Test that an unknown command raises CommandError """ - self.assertRaises(CommandError, management.call_command, ('explode',)) + with self.assertRaises(CommandError): + management.call_command(('explode',)) def test_system_exit(self): """ Exception raised in a command should raise CommandError with @@ -181,4 +182,5 @@ class CommandRunTests(AdminScriptTestCase): class UtilsTests(SimpleTestCase): def test_no_existent_external_program(self): - self.assertRaises(CommandError, popen_wrapper, ['a_42_command_that_doesnt_exist_42']) + with self.assertRaises(CommandError): + popen_wrapper(['a_42_command_that_doesnt_exist_42']) diff --git a/tests/utils_tests/test_baseconv.py b/tests/utils_tests/test_baseconv.py index 94c2d73b73..bffaac87b4 100644 --- a/tests/utils_tests/test_baseconv.py +++ b/tests/utils_tests/test_baseconv.py @@ -42,5 +42,6 @@ class TestBaseConv(TestCase): self.assertEqual(base7.decode('ghejd'), -1234) def test_exception(self): - self.assertRaises(ValueError, BaseConverter, 'abc', sign='a') + with self.assertRaises(ValueError): + BaseConverter('abc', sign='a') self.assertIsInstance(BaseConverter('abc', sign='d'), BaseConverter) diff --git a/tests/utils_tests/test_dateparse.py b/tests/utils_tests/test_dateparse.py index 1a1111df21..f0585187fc 100644 --- a/tests/utils_tests/test_dateparse.py +++ b/tests/utils_tests/test_dateparse.py @@ -17,7 +17,8 @@ class DateParseTests(unittest.TestCase): self.assertEqual(parse_date('2012-4-9'), date(2012, 4, 9)) # Invalid inputs self.assertEqual(parse_date('20120423'), None) - self.assertRaises(ValueError, parse_date, '2012-04-56') + with self.assertRaises(ValueError): + parse_date('2012-04-56') def test_parse_time(self): # Valid inputs @@ -27,7 +28,8 @@ class DateParseTests(unittest.TestCase): self.assertEqual(parse_time('4:8:16'), time(4, 8, 16)) # Invalid inputs self.assertEqual(parse_time('091500'), None) - self.assertRaises(ValueError, parse_time, '09:15:90') + with self.assertRaises(ValueError): + parse_time('09:15:90') def test_parse_datetime(self): # Valid inputs @@ -47,7 +49,8 @@ class DateParseTests(unittest.TestCase): datetime(2012, 4, 23, 10, 20, 30, 400000, get_fixed_timezone(-120))) # Invalid inputs self.assertEqual(parse_datetime('20120423091500'), None) - self.assertRaises(ValueError, parse_datetime, '2012-04-56T09:15:90') + with self.assertRaises(ValueError): + parse_datetime('2012-04-56T09:15:90') class DurationParseTests(unittest.TestCase): diff --git a/tests/utils_tests/test_encoding.py b/tests/utils_tests/test_encoding.py index 9527f29dcf..49fe33669f 100644 --- a/tests/utils_tests/test_encoding.py +++ b/tests/utils_tests/test_encoding.py @@ -27,7 +27,8 @@ class TestEncodingUtils(unittest.TestCase): # str(s) raises a TypeError on python 3 if the result is not a text type. # python 2 fails when it tries converting from str to unicode (via ASCII). exception = TypeError if six.PY3 else UnicodeError - self.assertRaises(exception, force_text, MyString()) + with self.assertRaises(exception): + force_text(MyString()) def test_force_text_lazy(self): s = SimpleLazyObject(lambda: 'x') diff --git a/tests/utils_tests/test_functional.py b/tests/utils_tests/test_functional.py index 135e8da0ed..66a6f59cf6 100644 --- a/tests/utils_tests/test_functional.py +++ b/tests/utils_tests/test_functional.py @@ -55,7 +55,8 @@ class FunctionalTestCase(unittest.TestCase): def _get_do(self): return "DO IT" - self.assertRaises(NotImplementedError, lambda: A().do) + with self.assertRaises(NotImplementedError): + A().do self.assertEqual(B().do, 'DO IT') def test_lazy_object_to_string(self): diff --git a/tests/utils_tests/test_http.py b/tests/utils_tests/test_http.py index 6051818958..6234e269ab 100644 --- a/tests/utils_tests/test_http.py +++ b/tests/utils_tests/test_http.py @@ -55,16 +55,21 @@ class TestUtilsHttp(unittest.TestCase): self.assertEqual(sys.maxint, http.base36_to_int(http.int_to_base36(sys.maxint))) # bad input - self.assertRaises(ValueError, http.int_to_base36, -1) + with self.assertRaises(ValueError): + http.int_to_base36(-1) if six.PY2: - self.assertRaises(ValueError, http.int_to_base36, sys.maxint + 1) + with self.assertRaises(ValueError): + http.int_to_base36(sys.maxint + 1) for n in ['1', 'foo', {1: 2}, (1, 2, 3), 3.141]: - self.assertRaises(TypeError, http.int_to_base36, n) + with self.assertRaises(TypeError): + http.int_to_base36(n) for n in ['#', ' ']: - self.assertRaises(ValueError, http.base36_to_int, n) + with self.assertRaises(ValueError): + http.base36_to_int(n) for n in [123, {1: 2}, (1, 2, 3), 3.141]: - self.assertRaises(TypeError, http.base36_to_int, n) + with self.assertRaises(TypeError): + http.base36_to_int(n) # more explicit output testing for n, b36 in [(0, '0'), (1, '1'), (42, '16'), (818469960, 'django')]: diff --git a/tests/utils_tests/test_module_loading.py b/tests/utils_tests/test_module_loading.py index fb9ccbf5d6..7140515cb9 100644 --- a/tests/utils_tests/test_module_loading.py +++ b/tests/utils_tests/test_module_loading.py @@ -34,15 +34,18 @@ class DefaultLoader(unittest.TestCase): # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(test_module, 'bad_module')) - self.assertRaises(ImportError, import_module, 'utils_tests.test_module.bad_module') + with self.assertRaises(ImportError): + import_module('utils_tests.test_module.bad_module') # A child that doesn't exist self.assertFalse(module_has_submodule(test_module, 'no_such_module')) - self.assertRaises(ImportError, import_module, 'utils_tests.test_module.no_such_module') + with self.assertRaises(ImportError): + import_module('utils_tests.test_module.no_such_module') # A child that doesn't exist, but is the name of a package on the path self.assertFalse(module_has_submodule(test_module, 'django')) - self.assertRaises(ImportError, import_module, 'utils_tests.test_module.django') + with self.assertRaises(ImportError): + import_module('utils_tests.test_module.django') # Don't be confused by caching of import misses import types # NOQA: causes attempted import of utils_tests.types @@ -50,8 +53,8 @@ class DefaultLoader(unittest.TestCase): # A module which doesn't have a __path__ (so no submodules) self.assertFalse(module_has_submodule(test_no_submodule, 'anything')) - self.assertRaises(ImportError, import_module, - 'utils_tests.test_no_submodule.anything') + with self.assertRaises(ImportError): + import_module('utils_tests.test_no_submodule.anything') class EggLoader(unittest.TestCase): @@ -82,11 +85,13 @@ class EggLoader(unittest.TestCase): # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, 'bad_module')) - self.assertRaises(ImportError, import_module, 'egg_module.bad_module') + with self.assertRaises(ImportError): + import_module('egg_module.bad_module') # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, 'no_such_module')) - self.assertRaises(ImportError, import_module, 'egg_module.no_such_module') + with self.assertRaises(ImportError): + import_module('egg_module.no_such_module') def test_deep_loader(self): "Modules deep inside an egg can still be tested for existence" @@ -101,11 +106,13 @@ class EggLoader(unittest.TestCase): # A child that exists, but will generate an import error if loaded self.assertTrue(module_has_submodule(egg_module, 'bad_module')) - self.assertRaises(ImportError, import_module, 'egg_module.sub1.sub2.bad_module') + with self.assertRaises(ImportError): + import_module('egg_module.sub1.sub2.bad_module') # A child that doesn't exist self.assertFalse(module_has_submodule(egg_module, 'no_such_module')) - self.assertRaises(ImportError, import_module, 'egg_module.sub1.sub2.no_such_module') + with self.assertRaises(ImportError): + import_module('egg_module.sub1.sub2.no_such_module') class ModuleImportTestCase(unittest.TestCase): @@ -114,7 +121,8 @@ class ModuleImportTestCase(unittest.TestCase): self.assertEqual(cls, import_string) # Test exceptions raised - self.assertRaises(ImportError, import_string, 'no_dots_in_path') + with self.assertRaises(ImportError): + import_string('no_dots_in_path') msg = 'Module "utils_tests" does not define a "unexistent" attribute' with six.assertRaisesRegex(self, ImportError, msg): import_string('utils_tests.unexistent') diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py index 6d904cecbc..58d3216e9b 100644 --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -124,8 +124,8 @@ class DebugViewTests(LoggingCaptureMixin, SimpleTestCase): def test_view_exceptions(self): for n in range(len(except_args)): - self.assertRaises(BrokenException, self.client.get, - reverse('view_exception', args=(n,))) + with self.assertRaises(BrokenException): + self.client.get(reverse('view_exception', args=(n,))) def test_non_l10ned_numeric_ids(self): """ @@ -169,7 +169,8 @@ class DebugViewTests(LoggingCaptureMixin, SimpleTestCase): """ Make sure if you don't specify a template, the debug view doesn't blow up. """ - self.assertRaises(TemplateDoesNotExist, self.client.get, '/render_no_template/') + with self.assertRaises(TemplateDoesNotExist): + self.client.get('/render_no_template/') @override_settings(ROOT_URLCONF='view_tests.default_urls') def test_default_urlconf_template(self):