测试框架pytest教程(8)失败重试-pytest-rerunfailures

`pytest-rerunfailures`是一个pytest插件,用于重新运行失败的测试用例。当测试用例在第一次运行时失败,该插件会自动重新运行指定次数的失败用例,以提高稳定性和减少偶发性错误的影响。

要使用`pytest-rerunfailures`插件,需要按照以下步骤进行安装和配置:

安装插件

在终端中运行以下命令来安装插件:

```

pip install pytest-rerunfailures

```

配置插件

在pytest配置文件中或通过命令行参数来配置插件。以下是一个示例配置:

```

pytest --reruns 2 --reruns-delay 1

```

  • `--reruns n`:指定重试失败用例的次数。在此示例中,失败用例将会重新运行2次。

  • `--reruns-delay se`:指定每次重试之间的延迟时间(秒)。在此示例中,每次重试将会有1秒的延迟。

你也可以将这些配置添加到pytest配置文件中,例如pytest.ini或setup.cfg文件。在配置文件中,可以按照如下方式添加:

pytest

reruns = 2

reruns_delay = 1

运行测试

运行你的pytest测试用例。当有测试用例失败时,插件将会自动重新运行失败用例指定次数。

使用`pytest-rerunfailures`插件可以提高测试用例的稳定性,特别是在遇到偶发性错误或不稳定的环境时。然而,过多的重试可能会掩盖真正的问题,因此需要根据具体情况选择合适的重试次数和延迟时间。

3次重试,一共执行4次

重试包含特定error的用例

$ pytest --reruns 5 --only-rerun AssertionError

重试不包含特定error的用例

$ pytest --reruns 5 --rerun-except AssertionError

单个用例重试

把用例标记为flasky,并配置重试次数

python 复制代码
@pytest.mark.flaky(reruns=5)
def test_example():

    assert False

延迟时间:

复制代码
@pytest.mark.flaky(reruns=5, reruns_delay=2)

添加条件

复制代码
@pytest.mark.flaky(reruns=5, condition=sys.platform.startswith("win32"))

包含或者不包含特定error

复制代码
@pytest.mark.flaky(rerun_except="AssertionError")

包含error类型为list

复制代码
@pytest.mark.flaky(only_rerun=["AssertionError", "ValueError"])
相关推荐
bjwuzh3 天前
使用pytest实现参数化后,控制台输出的日志是乱码
pytest
2025年一定要上岸4 天前
pytest框架 - 第二集 allure报告
pytest
头疼的程序员5 天前
allure生成测试报告(搭配Pytest、allure-pytest)
测试工具·pytest
文人sec6 天前
接口自动化测试设计思路--设计实战
python·https·单元测试·自动化·pytest
测试开发Kevin7 天前
从投入产出、效率、上手难易度等角度综合对比 pytest 和 unittest 框架
python·pytest
测试开发Kevin10 天前
以pytest_addoption 为例,讲解pytest框架中钩子函数的应用
python·pytest
川石教育15 天前
Pytest中的fixture装饰器详解
python自动化测试·pytest·pytest自动化测试框架·pytest测试框架·pytest单元测试框架
春风又。16 天前
接口自动化——参数化
python·测试工具·自动化·pytest
XTY0018 天前
mac电脑pytest生成测试报告
pytest
程序员的世界你不懂18 天前
pytest-前后置及fixture运用
pytest