pytest重复执行 -- pytest-repeat插件

pytest大保健系列

一、前言

1.需求情景:

  • 做功能测试的时候,经常会遇到某个模块不稳定,偶然会出现一些bug,对于这种问题我们会针对此用例反复执行多次,直到复现出这个问题来
  • 自动化运行用例时候,也会出现偶然的bug,可以针对单个用例,或者针对某个模块的用例重复执行多次
  • 该用例是不管失败与否用例都跑多次,与失败重跑不同,失败重跑只会在失败的时候重新尝试多次

2.使用前提

  • Python 2.7、3.4+或PyPy
  • py.test 2.8或更高版本
  • pytest-repeat不能与unittest.TestCase测试类一起使用。无论--count设置多少,这些测试始终仅运行一次,并显示警告

3.pip安装

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

4.命令描述

支持全局用例重复执行,也支持单个用例重复执行

命令行参数(所有用例有效):--count=2 或 --count 2

装饰器参数(单个用例有效):@pytest.mark.repeat(2)

二、命令行 所有用例都执行

import pytest
def test_case1():
    print("执行测试用例1")
    assert 1 + 1 == 2

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

1.基本使用 重复执行

pytest --count=2 -s demo.py

 2.重复执行结合 pytest 的 -x 参数 ,遇到错误立即停止执行 

  • 如果需要验证偶发bug,可以一次又一次地运行相同的测试用例,直到失败重现就停止
pytest --count=2 -x  -s txt.py

3.重复执行 结合 失败重跑

pytest --count=2 --reruns 3  -s txt.py

三、装饰器 单个用例重复执行

1.基本用法  @pytest.mark.repeat(5)

import pytest

@pytest.mark.repeat(2)
def test_case1():
    print("执行测试用例1")
    assert 1 + 1 == 2

执行:pytest --count=3 -s demo.py

 四、--repeat-scope 参数 自定义重复执行的单位 

作用:可以覆盖默认的测试用例执行顺序,类似fixture的scope参数

  • function:默认,范围针对每个用例重复执行,再执行下一个用例
  • class:以class为用例集合单位,重复执行class里面的用例,再执行下一个
  • module:以模块为单位,重复执行模块里面的用例,再执行下一个
  • session:重复整个测试会话,即所有测试用例的执行一次,然后再执行第二次

案例一:class

class Test_repeat:
    def test_2(self):
        print("测试用例执行222")

    def test_3(self):
        print("测试用例执行333")

class Test_repeat2:
    def test_4(self):
        print("测试用例执行444")

执行命令

pytest -s --count=2 --repeat-scope=class demo.py

执行结果

案例二:module

def test_repeat1():
    print("测试用例执行111")


def test_repeat2():
    print("测试用例执行222")


class Test_repeat:
    def test_repeat3(self):
        print("测试用例执行333")

执行命令

pytest -s --count=2 --repeat-scope=module 13repeat.py

执行结果

 

参考:小菠萝

 

posted @ 2022-02-24 15:39  www.pu  Views(347)  Comments(0Edit  收藏  举报