遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

pytest简易教程(27):pytest常用插件 - 失败重试(pytest-rerunfailures)

 

pytest简易教程汇总,详见https://www.cnblogs.com/uncleyong/p/17982846

关于插件

pytest有很多第三方插件:https://docs.pytest.org/en/latest/reference/plugin_list.html#plugin-list

总共1300多个,一般最近1年内有更新的都是常用的。

 

使用场景

针对运行不通过的用例运行重新运行最多指定次,这样可以排除网络等不稳定因素

 

插件安装

pip install pytest-rerunfailures

 

使用方式一:命令行参数(作用全局)

参数:

  • --reruns n,表示运行不通过,最多重试次数;必填
  • --reruns-delay m,表示重试前等待秒数;可选参数

命令:

  pytest --reruns n

  或者pytest --reruns=n

 

参数也可以放配置文件中:

[pytest]
addopts = -vs --reruns=2

作用于所有测试用例

 

示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

def test_b():
    print("---test_b")
    assert 1 == 1

def test_a():
    print("---test_a")
    assert 1 == 2

  

重试2次的结果:

 

重试2次,每次重试前等待5s的结果:下面总共耗时10.18秒

 

使用方式二:修饰器(作用局部)

@pytest.mark.flaky(reruns=m, reruns_delay=n)

  • reruns和reruns_delay含义同上面
  • 可以放在函数、方法、类上,仅作用于修饰器范围内

 

示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest
def test_b():
    print("---test_b")
    assert 1 == '1'

@pytest.mark.flaky(reruns=2, reruns_delay=5)
def test_a():
    print("---test_a")
    assert 1 == 2

  

结果:仅被修饰器修饰的函数失败了会重试

 

全局和局部同时存在重试配置

配置文件

[pytest]
addopts = -vs --reruns=1 --reruns-delay=3

  

用例代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest
def test_b():
    print("---test_b")
    assert 1 == '1'

@pytest.mark.flaky(reruns=2, reruns_delay=5)
def test_a():
    print("---test_a")
    assert 1 == 2

 

结果:配置就近原则,test_a应用的装饰器中重试配置,test_b应用的是配置文件中配置,所以总共耗时13.3秒

 

当然,也可以用命令行参数

pytest case\test_qzcsbj.py -vs --reruns=1 --reruns-delay=3

 

posted @ 2024-02-23 22:28  全栈测试笔记  阅读(246)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end