[英]In Python 3, using Pytest, how do we test for exit code : exit(1) and exit(0) for a python program?
我是 python 中 Pytest 的新手。
我面临一个棘手的场景,我需要使用 Pytest 模块测试退出代码 - exit(1) 和 exit(0)。 下面是 python 程序:
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)
现在我想测试上述程序的退出代码,exit(1) 和 exit(0)。 使用 Pytest 我们如何构建测试代码,以便我们可以测试或资产 function sample_script 的退出代码?
请帮我。
按照建议将exit(1)
放入 if 块后,您可以测试SystemExit异常:
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.com/python-pandemonium/testing-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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.