pytest使用 pytest-rerunfailures 插件实现失败用例重跑功能

慈云数据 2024-04-27 技术支持 40 0

使用 pytest 进行测试时,你可以通过安装配置 pytest-rerunfailures 插件来实现失败用例重跑功能。以下是一个示例说明:

假设你有一个测试文件 test_example.py 包含如下测试用例:

import pytest
@pytest.mark.parametrize("num", [0, 1, 2, 3])
def test_divisible_by_two(num):
    assert num % 2 == 0
def test_always_fail():
    assert False

在这个示例中,test_divisible_by_two 是一个参数化测试用例,而 test_always_fail 则是一个总是失败的测试用例。

现在,我们来安装 pytest-rerunfailures 插件,并运行测试用例,使其在失败时重试:

  1. 安装 pytest-rerunfailures 插件:

    pip install pytest-rerunfailures
  2. 运行测试用例并指定重试次数:

    pytest --reruns 2 test_example.py

    在这个示例中,我们设置了重试次数为 2 次。如果某个测试用例失败,则会在失败后重新运行该测试用例两次。

    示例输出可能如下所示:

============================= test session starts ==============================

platform linux -- Python 3.x.y, pytest-6.x.y, pluggy-0.x.y

rootdir: /path/to/your/project

plugins: rerunfailures-1.x.y

collected 5 items

test_example.py .FFF                                              [100%]

=========================== rerun test summary info ===========================

RERUNNING test_always_fail (1/2)...

RERUNNING test_always_fail (2/2)...

============================= 3 failed, 2 passed in 0.12s ==============================

如上所示,在第一次运行时,test_always_fail 测试用例失败了,然后在重试两次后依然失败了。其他测试用例通过了。

通过以上步骤,你就成功地使用 pytest-rerunfailures 插件实现了失败用例重跑功能。

Allure报告查看重跑日志

微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon