我是python中的Pytest新手。
我面临着一个棘手的情况,我需要测试退出代码 - exit(1) 和 exit(0) ,使用Pytest模块。
def sample_script():
count_file = 0
if count_file == 0:
print("The count of files is zero")
exit(1)
else:
print("File are present")
exit(0)
现在,我想测试上述程序的退出代码,退出(1)和退出(0)。使用Pytest,我们如何能够框架测试代码,以便我们可以测试或资产的退出代码的函数sample_script?
请帮助我。
一旦你把 exit(1)
内的if块,你可以测试是否有 系统退出 异常。
from some_package import sample_script
def test_exit():
with pytest.raises(SystemExit) as pytest_wrapped_e:
sample_script()
assert pytest_wrapped_e.type == SystemExit
assert pytest_wrapped_e.value.code == 42
例子来自这里。https:/medium.python-pandemoniumtesting-sys-exit-with-pytest-10c6e5f7726f。
更新。
这里有一个完整的工作实例,你可以复制粘贴来测试。
import pytest
def sample_func():
exit(1)
def test_exit():
with pytest.raises(SystemExit) as e:
sample_func()
assert e.type == SystemExit
assert e.value.code == 1
if __name__ == '__main__':
test_exit()