• Pytest系列-失败重跑插件pytest-rerunfailures的使用(9)


    前提条件

    以下先决条件才能使用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
    
    • 1

    DOC

    https://github.com/pytest-dev/pytest-rerunfailures
    
    https://pypi.org/project/pytest-rerunfailures/#description
    
    • 1
    • 2
    • 3

    重点

    命令行参数:–reruns n(重新运行次数),–reruns-delay m(等待运行秒数)

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

    使用方法

    第一种方法:命令行

    1、要重新运行所有测试失败的用例,使用 --reruns 命令行选项,并指定要运行测试的最大次数:

    pytest --reruns 5 -s 
    
    • 1

    运行失败的 fixture 或 setup_class 也将重新执行
    2、也可以这样用

    pytest --reruns 5 --reruns-delay 1
    
    • 1

    但是condition并没有这个命令行,它变成了–only-rerun

    $ 遇到AssertionError错误就重跑
    $ pytest --reruns 5 --only-rerun AssertionError
    # 遇到AssertionError或者ValueError 就重跑
    $ pytest --reruns 5 --only-rerun AssertionError --only-rerun ValueError
    
    • 1
    • 2
    • 3
    • 4

    示例

    def test_a():
        assert int('a')  # 会产生一个ValueError
    
    • 1
    • 2
    #执行
    pytest -sv --reruns 2 --reruns-delay 1 --only-rerun ValueError test_demo.py
    
    • 1
    • 2

    结果
    在这里插入图片描述

    • –only-rerun的意思很明确,只有遇到ValueError才重跑

    • 同样的代码,换个参数–rerun-except,除了ValueError才会重跑,遇到ValueError并不重跑

    pytest -sv --reruns 2 --reruns-delay 1 --rerun-except ValueError test_demo.py
    
    • 1

    在这里插入图片描述

    第二种方法:装饰器 @pytest.mark.flaky

    要将单个测试用例添加flaky装饰器 @pytest.mark.flaky(reruns=5) ,并在测试失败时自动重新运行,需要指定最大重新运行的次数

    示例:

    import pytest
    
    @pytest.mark.flaky(reruns=5)
    def test_example():
        import random
        assert random.choice([True,False,False])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    执行结果
    在这里插入图片描述

    同样,也可以指定重新运行的等待时间

    import pytest
    
    @pytest.mark.flaky(reruns=5,reruns_delay=2)
    def test_example():
        import random
        assert random.choice([True,False,False])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    执行结果
    在这里插入图片描述

    注意事项

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

    兼容性问题

    不可以和fixture装饰器一起使用: @pytest.fixture()

    • 该插件与pytest-xdist的 --looponfail 标志不兼容
    • 该插件与核心–pdb标志不兼容
  • 相关阅读:
    【Java】Spring scurity + JWT 前后端分离
    TCP 拥塞控制
    Qt多线程间信号槽传递非QObject类型对象的参数
    YOLO v7 + 各种跟踪器(SORT, DeepSORT, ByteTrack, BoT-SORT)实现多目标跟踪
    10 个杀手级的 Python 自动化脚本
    设备巡检管理系统的作用
    前端学习笔记01
    【计算机毕业设计】基于netty的网关推送平台
    糟了,线上服务出现OOM了
    Wireshark的下载安装及简单使用教程
  • 原文地址:https://blog.csdn.net/m0_62091240/article/details/133075936