如何使用pytest测试try/except块的异常
How to test the exception of try/except block using pytest
在 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'"
很明显,这个测试失败了 Failed: DID NOT RAISE <class 'AssertionError'>
,因为我在 try/except 块中发现了错误。但是 can/should 我如何测试是否打印了正确的短语?如果您有多个可能的 except
块,这可能特别有用。
您可以使用 capsys
fixture 捕获标准输出,然后用它进行断言:
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"
在 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'"
很明显,这个测试失败了 Failed: DID NOT RAISE <class 'AssertionError'>
,因为我在 try/except 块中发现了错误。但是 can/should 我如何测试是否打印了正确的短语?如果您有多个可能的 except
块,这可能特别有用。
您可以使用 capsys
fixture 捕获标准输出,然后用它进行断言:
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"