我是巨 Python 和巨 Python 的初学者.我有一个函数,我正在try 用Pytest测试它的异常部分:
def read_data(args) -> tuple[Polyline, str]:
parsed_args = input_parsing_1(args)
try:
with open(parsed_args.f) as f_input:
reader = csv.reader(f_input)
polyline = fill_poly_with_data(reader)
except FileNotFoundError as e:
sys.exit('Invalid input file \n')
else:
return (polyline, parsed_args.f)
我想测试是否引发了异常,以及错误消息是否与我在上面的代码中输入的消息匹配.
My attempts个
@patch('project.open')
def test_read_data_error_SE(mock_open):
mock_open.side_effect = SystemExit
with pytest.raises(SystemExit):
assert read_data(['-f', ''])
@patch('project.open')
def test_read_data_error_FNFE2(mock_open):
mock_open.side_effect = FileNotFoundError
with pytest.raises(SystemExit):
with pytest.raises(FileNotFoundError):
assert read_data(['-f', 'cos'])
上述测试运行良好.
我还希望断言sys.exit消息是否与'Invalid input file \n'
匹配.我试过了:
@patch('project.open')
def test_read_data_error_SE1(mock_open):
mock_open.side_effect = SystemExit
with pytest.raises(SystemExit, match='Invalid input file'):
assert read_data(['-f', ''])
@patch('project.open')
def test_read_data_error_SE2(mock_open):
mock_open.side_effect = SystemExit
with pytest.raises(SystemExit) as e:
assert read_data(['-f', ''])
assert 'Invalid input file' in str(e.value)
但这些测试都失败了:
===================================================== short test summary info ======================================================
FAILED test_project.py::test_read_data_error_SE1 - AssertionError: Regex pattern did not match.
FAILED test_project.py::test_read_data_error_SE2 - AssertionError: assert 'Invalid input file' in ''
我在Stackoverflow上看到了一些帖子,比如: Verify the error code or message from SystemExit in pytest个
How to properly assert that an exception gets raised in pytest?个
Catch SystemExit message with Pytest个
但他们似乎都没有回答我的问题.
My questions:个
我测试过的消息‘INVALID INPUT FILE’似乎正在与空字符串‘’匹配?为什么?如何正确捕获和断言sys.exit("一些错误消息")?