[英]How to test the exception of try/except block using pytest
How can I properly test if the correct code has executed once an exception has been triggered in a try/except block?一旦在 try/except 块中触发异常,如何正确测试是否执行了正确的代码?
import pytest
def my_func(string):
try:
assert string == "pass"
print("String is `pass`")
except AssertionError:
print("String is not 'pass'")
def test_my_func():
with pytest.raises(AssertionError) as exc_info:
my_func("fail")
assert str(exc_info.value) == "String is not 'pass'"
Clearly, this test fails with Failed: DID NOT RAISE <class 'AssertionError'>
as I caught the error in the try/except block.很明显,这个测试失败了
Failed: DID NOT RAISE <class 'AssertionError'>
因为我在 try/except 块中发现了错误。 But how can/should I test if the correct phrase has been printed?但是我如何/应该如何测试是否打印了正确的短语? This could especially be useful if you have more than one possible
except
block.如果你有一个以上的可能,这可能尤其是有用的
except
块。
You can use the capsys
fixture to capture standard output and then make assertions with it:您可以使用
capsys
固定装置捕获标准输出,然后使用它进行断言:
def my_func(string):
try:
assert string == "pass"
print("String is `pass`")
except AssertionError:
print("String is not 'pass'")
def test_my_func(capsys):
my_func("fail")
captured = capsys.readouterr()
assert captured.out == "String is not 'pass'\n"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.