我正在尝试检查我在Mac(10.14.4(上用python3编写的脚本的退出代码。 当我运行测试时,它不会失败,我认为这是错误的。 但我看不出我错了什么。
测试文件如下所示:
import pytest
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import my_script
class TestMyScript():
def test_exit(self):
with pytest.raises(SystemExit) as pytest_wrapped_e:
my_script.main()
assert pytest_wrapped_e.type == SystemExit
def test_exit_code(self):
with pytest.raises(SystemExit) as pytest_wrapped_e:
my_script.main()
self.assertEqual(pytest_wrapped_e.exception.code, 42)
我的脚本如下所示:
#!/usr/bin/env python3
import sys
def main():
print('Hello World!')
sys.exit(0)
if __name__ == '__main__':
main()
我得到的输出是:
$ py.test -v
============================= test session starts ==============================
platform darwin -- Python 3.7.3, pytest-3.10.1, py-1.8.0, pluggy-0.9.0 -- /usr/local/opt/python/bin/python3.7
cachedir: .pytest_cache
rootdir: /Users/robertpostill/software/gateway, inifile:
plugins: shutil-1.6.0
collected 2 items
test/test_git_refresh.py::TestGitRefresh::test_exit PASSED [ 50%]
test/test_git_refresh.py::TestGitRefresh::test_exit_code PASSED [100%]
=========================== 2 passed in 0.02 seconds ===========================
$
我希望第二个测试(test_exit_code(失败,因为退出调用获得的代码为0,而不是42。 但出于某种原因,无论我在 sys.exit 调用中输入什么值,断言都很高兴。
好问题,那是因为你的Asserts
从来没有被调用过(他们中的任何一个(。 当exit()
被调用时,程序就完成了(至少在with
条款中(,它关灯,收拾行李,回家。不会调用其他函数。要查看此信息,请在调用main
之前和之后添加一个assert
:
def test_exit_code(self):
with pytest.raises(SystemExit) as pytest_wrapped_e:
self.assertEqual(0, 1) # This will make it fail
my_script.main()
self.assertEqual(0, 1) # This will never be called because main `exits`
self.assertEqual(pytest_wrapped_e.exception.code, 42)
如果没有断言失败并且没有任何中断,则测试通过,因此在您的情况下,两个测试都通过了,因为从未命中assert
。
要解决此问题,请将asserts
从with
语句中拉出:
def test_exit_code(self):
with pytest.raises(SystemExit) as pytest_wrapped_e:
my_script.main()
self.assertEqual(pytest_wrapped_e.exception.code, 42)
虽然现在你需要修复pytest
语法,因为你缺少一些其他的东西。
参见:使用 pytest 测试 sys.exit((