Skip to content

Commit

Permalink
Refs #26022 -- Used context manager version of assertRaises in tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani authored and timgraham committed Jan 29, 2016
1 parent 5757063 commit 3d0dcd7
Show file tree
Hide file tree
Showing 118 changed files with 1,086 additions and 760 deletions.
3 changes: 2 additions & 1 deletion tests/admin_filters/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -850,7 +850,8 @@ def test_filter_with_failing_queryset(self):
"""
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)
Expand Down
8 changes: 4 additions & 4 deletions tests/admin_registration/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@ def test_registration_with_model_admin(self):

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'])
Expand Down Expand Up @@ -68,7 +67,8 @@ def test_abstract_model(self):
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."
Expand Down
6 changes: 2 additions & 4 deletions tests/admin_utils/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,8 @@ def test_label_for_field(self):
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"
Expand Down
40 changes: 16 additions & 24 deletions tests/aggregation_regress/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,20 +376,14 @@ def test_decimal_aggregate_annotation_filter(self):

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
Expand Down Expand Up @@ -698,21 +692,20 @@ def test_more_more(self):

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.
Expand All @@ -739,7 +732,8 @@ def test_values_queryset_non_conflict(self):
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.
Expand Down Expand Up @@ -900,10 +894,8 @@ def test_more_more_more(self):

# 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(
Expand Down
9 changes: 6 additions & 3 deletions tests/auth_tests/test_auth_backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,7 +429,8 @@ def setUp(self):
self.user = User.objects.create_user('test', '[email protected]', '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'])
Expand Down Expand Up @@ -575,7 +576,8 @@ def setUp(self):

@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):
Expand All @@ -598,7 +600,8 @@ def test_does_not_shadow_exception(self):
request = HttpRequest()
request.session = self.client.session

self.assertRaises(ImproperlyConfigured, get_user, request)
with self.assertRaises(ImproperlyConfigured):
get_user(request)


class ImportedModelBackend(ModelBackend):
Expand Down
3 changes: 2 additions & 1 deletion tests/auth_tests/test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,5 @@ def a_view(request):
return HttpResponse()
request = self.factory.get('/rand')
request.user = self.user
self.assertRaises(PermissionDenied, a_view, request)
with self.assertRaises(PermissionDenied):
a_view(request)
6 changes: 4 additions & 2 deletions tests/auth_tests/test_hashers.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,8 @@ def test_unusable(self):
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?")
Expand All @@ -234,7 +235,8 @@ def test_unspecified_password(self):
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'))
Expand Down
6 changes: 4 additions & 2 deletions tests/auth_tests/test_mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@ class AView(AlwaysFalseView):

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"
Expand Down Expand Up @@ -248,4 +249,5 @@ class AView(PermissionRequiredMixin, EmptyResponseView):

request = self.factory.get('/rand')
request.user = self.user
self.assertRaises(PermissionDenied, AView.as_view(), request)
with self.assertRaises(PermissionDenied):
AView.as_view()(request)
5 changes: 2 additions & 3 deletions tests/auth_tests/test_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,5 @@ def test_date_length(self):
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)
35 changes: 18 additions & 17 deletions tests/backends/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,19 +128,16 @@ def test_aggregation(self):
#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):
"""
Expand Down Expand Up @@ -449,8 +446,10 @@ def test_bad_parameter_count(self):
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
Expand Down Expand Up @@ -859,7 +858,8 @@ def test_integrity_checks_on_creation(self):
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):
"""
Expand Down Expand Up @@ -887,7 +887,8 @@ def test_integrity_checks_on_update(self):
# 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):
"""
Expand Down
8 changes: 2 additions & 6 deletions tests/basic/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,12 +499,8 @@ def test_does_not_exist(self):
)
# 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,
Expand Down
42 changes: 28 additions & 14 deletions tests/cache/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,18 @@ def test_in(self):
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"
Expand Down Expand Up @@ -193,14 +197,18 @@ def test_clear(self):
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')
Expand Down Expand Up @@ -321,7 +329,8 @@ def test_incr(self):
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
Expand All @@ -331,7 +340,8 @@ def test_decr(self):
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'))
Expand Down Expand Up @@ -821,7 +831,8 @@ def test_incr_version(self):
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)
Expand All @@ -844,7 +855,8 @@ def test_decr_version(self):
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
Expand Down Expand Up @@ -1138,9 +1150,11 @@ def test_invalid_keys(self):
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(
Expand Down
3 changes: 2 additions & 1 deletion tests/check_framework/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,8 @@ def test_given_tag(self):

@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):
Expand Down
Loading

0 comments on commit 3d0dcd7

Please sign in to comment.