Pytest学习(十一)- 失败重跑插件pytest-rerunfailures的使用

环境依赖

  • Python 3.5,最高 3.8,or PyPy3
  • pytest 5.0或更高版本

插件安装

pip3 install pytest-rerunfailures -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

参数解释

命令行参数:--reruns n(重新运行次数),--reruns-delay m(等待运行秒数)
装饰器参数:reruns=n(重新运行次数),reruns_delay=m(等待运行秒数)

重新运行所有失败的用例

使用 --reruns 命令行选项,并指定要运行测试的最大次数

pytest --reruns 5 -s 

运行失败的fixture或setup_class也将重新执行

重新运行的延时设置

要在两次重试之间增加延迟时间,使用 --reruns-delay 命令行选项,指定下次测试重新开始之前等待的秒数

pytest --reruns 5 --reruns-delay 10 -s

重新运行指定的测试用例

添加flaky装饰器 @pytest.mark.flaky(reruns=5) ,并指定最大重新运行次数,示例代码如下:

# -*- coding: utf-8 -*-
# @Time    : 2020/11/25 20:36
# @Author  : longrong.lang
# @FileName: test_retry.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
from collections import Counter
import random
import pytest


@pytest.mark.flaky(reruns=5)
def test_retry1():
    n = random.randint(0,9)
    print(f"\n 输出随机数: {n} ")
    assert n == 2


@pytest.mark.flaky(reruns=5)
def test_retry2():
    assert random.choice([True,False,False])


执行结果:

对单个测试用例设置重新运行等待时间

示例代码如下:

@pytest.mark.flaky(reruns=5,reruns_delay=2)
def test_retry1():
    n = random.randint(0,9)
    print(f"\n 输出随机数: {n} ")
    assert n == 2

运行结果:

注意事项
如果指定了用例的重新运行次数,则在命令行添加--reruns对这些用例是不会生效的

兼容性问题

  • 不可以和fixture装饰器一起使用: @pytest.fixture()
  • 插件与pytest-xdist的 --looponfail 标志不兼容
  • 插件与核心--pdb标志不兼容

系列参考文章
https://www.cnblogs.com/poloyy/category/1690628.html

相关文章

PyTest支持xUnit style 结构, setup() 和 teardown() 方法用于初始化和清理测试环境,可以保证测试用例...
在 Pytest测试框架(三):pytest fixture 用法 中介绍了pytest.fixture()可以参数化fixture函数,@pyt...
Allure 是一款轻量级、支持多语言的开源自动化测试报告生成框架,由Java语言开发,可以集成到 Jenkins。...
xUnit style 结构的 fixture用于初始化测试函数, pytest fixture是对传统的 xUnit 架构的setup/teardo...
PyTest是基于Python的开源测试框架,语法简单易用,有大量的插件,功能非常多。自动检测测试用例,支持...