如何使用pytest检查不会引发错误 [英] How to use pytest to check that Error is NOT raised
问题描述
假设我们有这样的东西:
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)
....
问:如何使test_foo3()进行测试,但不会引发MyError? 很明显,我可以测试一下:
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
但是我想通过pytest.raises()进行测试.有可能吗? 例如:在某种情况下,该函数"foo"根本没有返回值,
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.
推荐答案
如果引发任何意外的异常,则测试将失败.您只需调用foo(7),就可以测试没有引发MyError了.因此,只要满足以下条件即可:
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)
如果您想露骨并为此写一个assert语句,则可以执行以下操作:
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 ..")
这篇关于如何使用pytest检查不会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!