Skip to content

Instantly share code, notes, and snippets.

@tomschr
Last active March 14, 2016 10:38
Show Gist options
  • Save tomschr/e776dc23ce330d7ba571 to your computer and use it in GitHub Desktop.
Save tomschr/e776dc23ce330d7ba571 to your computer and use it in GitHub Desktop.
pytest: raises Decorator from nose (implemented as function and class)
from functools import wraps
# Taken from nosetest: see file nose/tools/nontrivial.py
class raises(object):
"""Test must raise one of expected exceptions to pass.
Example use::
@raises(TypeError, ValueError)
def test_raises_type_error():
raise TypeError("This test passes")
@raises(Exception)
def test_that_fails_by_passing():
pass
If you want to test many assertions about exceptions in a single test,
you may want to use `assert_raises` instead.
"""
def __init__(self, *exceptions):
self.exceptions = exceptions
self.valid = ' or '.join([e.__name__ for e in exceptions])
def __call__(self, func):
name = func.__name__
def newfunc(*args, **kw):
try:
func(*args, **kw)
except self.exceptions:
pass
except:
raise
else:
message = "%s() did not raise %s" % (name, self.valid)
raise AssertionError(message)
newfunc = wraps(func)(newfunc)
return newfunc
@raises(ValueError)
def test_bar():
print("Bar")
raise ValueError("It works!")
@raises(ValueError)
def test_baz():
print("Bar")
from functools import wraps
# Same implementation as with class, but only as a function
# Taken from nosetest: see file nose/tools/nontrivial.py
def raises(*exceptions):
"""Test must raise one of expected exceptions to pass.
Same as rases, but implemented as function, not as class
"""
valid = ' or '.join([e.__name__ for e in exceptions])
def decorate(func):
name = func.__name__
def newfunc(*arg, **kw):
try:
func(*arg, **kw)
except exceptions:
pass
except:
raise
else:
message = "%s() did not raise %s" % (name, valid)
raise AssertionError(message)
newfunc = wraps(func)(newfunc)
return newfunc
return decorate
@raises(ValueError)
def test_bar():
print("Bar")
raise ValueError("It works!")
@raises(ValueError)
def test_baz():
print("Bar")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment