pytest失败重跑 -- pytest-rerunfailures插件

pytest大保健系列

一、前言

在进行自动化测试的过程中,我们一定会有这样的需求:希望失败的用例可以自动重跑

在pytest中,提供了pytest-rerunfailures插件可以实现自动重跑的效果

1.使用前提

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

2.兼容性

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

3.pip安装

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

4.命令描述

支持全局重跑和局部重跑

命令行参数(所有用例有效):--reruns n(重新运行次数),--reruns-delay m(等待运行秒数)

装饰器参数(单个用例有效):reruns=n(重新运行次数),reruns_delay=m(等待运行秒数)

二、命令行 全局重跑

如下,所有用例失败最大重跑3次,下次重试之前间隔2秒

pytest --reruns 3 --reruns-delay 2 -s

举例:

class TestDemo(object):
    def setup_class(self):
        print("执行setup_class")

    def teardown_class(self):
        print("执行teardown_class")

    def test_case1(self):
        print("执行测试用例1")
        assert 1 + 1 == 3

    def test_case2(self):
        print("执行测试用例2")
        assert 1 + 3 == 6

    def test_case3(self):
        print("执行测试用例3")
        assert 1 + 3 == 4
View Code

结果:

 

三、装饰器 局部重跑 

如果我们在测试时,只希望在某一条测试用例失败后重新执行该如何处理呢

可以使用flaky装饰器 @pytest.mark.flaky(reruns=, reruns_delay=)

如下,代表被装饰的用例最多重跑2次,每次间隔3秒

@pytest.mark.flaky(reruns=2, reruns_delay=3)

举例:

import pytest

@pytest.mark.flaky(reruns=2, reruns_delay=3)
def test_case1():
    print("执行测试用例1")
    assert 1 + 1 == 3

def test_case2():
    print("执行测试用例2")
    assert 1 + 3 == 6

def test_case3():
    print("执行测试用例3")
    assert 1 + 3 == 4
View Code

结果一:pytest -s

 

 

结果二:pytest --reruns 3 --reruns-delay 2 -s

当命令行和装饰器同时出现时,局部大于全局

 

 

参考:

小菠萝

RockChe's Blog

 

posted @ 2022-02-23 11:21  www.pu  Views(112)  Comments(0Edit  收藏  举报