Skip to content

Instantly share code, notes, and snippets.

@rene-armida
Created August 9, 2012 00:31
Show Gist options
  • Save rene-armida/3299957 to your computer and use it in GitHub Desktop.
Save rene-armida/3299957 to your computer and use it in GitHub Desktop.
Monkey patch: backport context manager support into nose.tools.assert_raises in python2.6
# code for monkey-patching
import nose.tools
# let's fix nose.tools.assert_raises (which is really unittest.assertRaises)
# so that it always supports context management
# in order for these changes to be available to other modules, you'll need
# to guarantee this module is imported by your fixture before either nose or
# unittest are imported
try:
nose.tools.assert_raises(Exception)
except TypeError:
# this version of assert_raises doesn't support the 1-arg version
class AssertRaisesContext(object):
def __init__(self, expected):
self.expected = expected
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, tb):
self.exception = exc_val
nose.tools.assert_equal(exc_type, self.expected)
# if you get to this line, the last assertion must have passed
# suppress the propagation of this exception
return True
def assert_raises_context(exc_type):
return AssertRaisesContext(exc_type)
nose.tools.assert_raises = assert_raises_context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment