python - Pytest 通过测试我认为它应该在 sys.exit() 调用上失败

标签 python python-3.x pytest

我正在尝试检查我在 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) 会失败,因为 exit 调用得到的代码是 0,而不是 42。但出于某种原因,无论我在 sys.exit 调用中输入什么值,断言都是满意的。

最佳答案

问得好,那是因为您的断言 从未被调用过(它们中的任何一个)。当 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

要解决此问题,请将您的 assertswith 语句中拉出:

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 语法,因为您缺少一些其他内容。

参见:Testing sys.exit() with pytest

关于python - Pytest 通过测试我认为它应该在 sys.exit() 调用上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55831428/

相关文章:

python - 使用 Python 进行通配符下载

Django异步测试: Cannot operate on a closed database

python - 当我希望它随每个实例而改变时,我的循环不断重复相同的值

python - AsyncHTTPTestCase Post 请求传递数据

python - 按预定义时间选择单行并使用 Pandas 创建新的 DF

python - 查找字符串中特定字符的范围

python - python 中的机器学习 scikit learn 问题

python - py.test Remote 有问题

assert - pytest 中的自定义断言应该覆盖标准断言

Python:附加到基类列表/元组成员