当测试引发未经处理的异常(断言错误除外)时,pytest 的退出代码不同



我想知道pytest测试套件是否由于以下原因而失败: 1. 给定的测试在断言上失败,或 2. 给定测试引发未处理的异常

因此,给定以下测试:

def test_ok():
assert 0 == 0
def test_failed():
assert 1 == 0
def test_different_exit_code():
open('/nonexistent', 'r')

我想区分(使用不同的退出代码(test_failedtest_different_exit_code的情况。

pytest 有一个处理异常,让我给你看一个例子:

import pytest
from pytest_bdd import given
def pytest_bdd_step_error(request, feature, scenario, step, step_func, step_func_args, exception):
print(f'Step failed: {step}')

这是一个钩子,你可以用它来处理你的pytest中的错误,step_defs你只在你的def test_failed((中调用,所以你可以写这个

def test_ok():
assert 0 == 0 # Test is ok

def test_failed():
#assert 1 == 0 # Test failed REMOVE THIS PART AND USE assert not
assert not 1 == 0

def test_different_exit_code():
open('/nonexistent', 'r')

您可以使用 pytest-finer-dicts 插件来区分测试失败和其他失败(例如,由于异常(。

编辑1:例如,在下面的片段中,

import pytest
def test_fail():
assert 75 <= 70
def test_error():
open("/nonexistent", 'r')

pytest-finer-判定将区分以下两个测试由于不同类型的原因而失败。

collected 2 items                                                               
t.py FE                                                         [100%]
==================================== ERRORS =====================================
_________________________ ERROR at setup of test_error1 _________________________
def test_error1():
>       open("/nonexistent", 'r')
E       FileNotFoundError: [Errno 2] No such file or directory: '/nonexistent'
t.py:7: FileNotFoundError
=================================== FAILURES ====================================
___________________________________ test_fail ___________________________________
def test_fail():
>       assert 75 <= 70
E       assert 75 <= 70
t.py:4: AssertionError
============================ short test summary info ============================
FAILED t.py::test_fail - assert 75 <= 70
ERROR t.py::test_error1 - FileNotFoundError: [Errno 2] No such file or directo...
========================== 1 failed, 1 error in 0.19s ===========================

我最终得到了 https://pypi.org/project/pytest-unhandled-exception-exit-code/

这使得在任何测试中发生未经处理的异常时设置退出代码成为可能,例如使用示例命令行:pytest --unhandled-exc-exit-code 13

最新更新