How to use pytest to check that Error is NOT raised
Full error message
Let's assume we have smth like that :
import py, pytest
ERROR1 = ' --- Error : value < 5! ---'
ERROR2 = ' --- Error : value > 10! ---'
class MyError(Exception):
def __init__(self, m):
self.m = m
def __str__(self):
return self.m
def foo(i):
if i < 5:
raise MyError(ERROR1)
elif i > 10:
raise MyError(ERROR2)
return i
# ---------------------- TESTS -------------------------
def test_foo1():
with pytest.raises(MyError) as e:
foo(3)
assert ERROR1 in str(e)
def test_foo2():
with pytest.raises(MyError) as e:
foo(11)
assert ERROR2 in str(e)
def test_foo3():
....
foo(7)
....
Q: How can I make test_foo3() to test, that no MyError is raised?
It's obvious, that i could just test :
def test_foo3():
assert foo(7) == 7
but i want to test that via pytest.raises(). Is is possible someway?
For example: in a case, that function "foo" has no return-value at all,
def foo(i):
if i < 5:
raise MyError(ERROR1)
elif i > 10:
raise MyError(ERROR2)
it could make sense to test this way, imho.Solutionsource: stackoverflow \u2197
A test will fail if it raises any kind of unexpected Exception. You can just invoke foo(7) and you will have tested that no MyError is raised. So, following will suffice: def test_foo3(): foo(7) If you want to be explicit and write an assert statement for this, you can do: def test_foo3(): try: foo(7) except MyError: pytest.fail("Unexpected MyError ..")
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/61c54c64d64dde1f9d1a9802b7d7a3e79173dd3480a74ac882e2c5f17e79e4eehash \u00b7 61c54c64d64dde1f9d1a9802b7d7a3e79173dd3480a74ac882e2c5f17e79e4ee