Skip to content

Instantly share code, notes, and snippets.

@oisinmulvihill
Created August 4, 2019 12:58
Show Gist options
  • Save oisinmulvihill/45c14271fad7794a4a52516ecb784e69 to your computer and use it in GitHub Desktop.
Save oisinmulvihill/45c14271fad7794a4a52516ecb784e69 to your computer and use it in GitHub Desktop.
How to test a python exception is not raised with pytests
# Updated for python3
#
# https://stackoverflow.com/questions/20274987/how-to-use-pytest-to-check-that-error-is-not-raised/35458249#35458249
#
from contextlib import contextmanager
@contextmanager
def not_raises(ExpectedException):
try:
yield
except ExpectedException as error:
raise AssertionError(f"Raised exception {error} when it should not!")
except Exception as error:
raise AssertionError(f"An unexpected exception {error} raised.")
def good_func():
print("hello")
def bad_func():
raise ValueError("BOOM!")
def ugly_func():
raise IndexError("UNEXPECTED BOOM!")
def test_ok():
with not_raises(ValueError):
good_func()
def test_bad():
with not_raises(ValueError):
bad_func()
def test_ugly():
with not_raises(ValueError):
ugly_func()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment