【pytest-18】pytest-repeat重复执行用例

前言

  • 平常在做功能测试的时候,经常会遇到某个模块不稳定,偶然会出现一些bug,对于这种问题我们会针对此用例反复执行多次,最终复现出问题来
  • 自动化运行用例时候,也会出现偶然的bug,可以针对单个用例,或者针对某个模块的用例重复执行多次

安装pytets-xdist

pip install pytets-xdist

重复测试直到失败

如果您正在尝试诊断间歇性故障,那么一遍又一遍地运行相同的测试直到失败是有用的。您可以将pytest的-x选项与pytest-repeat结合使用,以强制测试运行器在第一次失败时停止。例如:

py.test --count=1000 -x test_file.py

这将尝试运行test_file.py 1000次,但一旦发生故障就会停止

重复执行

使用--count命令行选项指定要运行测试用例和次数

py.test --count=5 test_a.py

 示例:

#encoding:utf-8
#@Time:2020/12/15 15:57
#@Author:sunny

import pytest

@pytest.fixture(scope="session")
def start():
    print("打开浏览器")

def test_hello(start):
    '''toutiao下的测试用例'''
    print("hello world0")

def test_hello2(start):
    '''toutiao下的测试用例'''
    print("hello world1")

执行命令:我这里在项目的根目录下,直接

运行结果:

从运行的用例结果看,是先重复5次test_hello,再重复5次test_hello2,有时候我们希望执行的顺序是test_hello,test_hello2按这样顺序重复五次,接下来就用到一个参数--repeat-scope

--repeat-scope

--repeat-scope类似于pytest fixture的scope参数,--repeat-scope也可以设置参数:  session  ,  module , class 或者 function (默认值)

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

使用 --repeat-scope=session 重复执行整个会话用例

pytest test_repeat0.py -s --count=5 --repeat-scope=session

@pytest.mark.repeat(count)

如果要在代码中标记要重复多次的测试,可以使用@pytest.mark.repeat(count)装饰器

#encoding:utf-8
#@Time:2020/12/15 15:57
#@Author:sunny

import pytest

@pytest.fixture(scope="session")
def start():
    print("打开浏览器")

@pytest.mark.repeat(5)
def test_hello(start):
    '''toutiao下的测试用例'''
    print("hello world0")

def test_hello2(start):
    '''toutiao下的测试用例'''
    print("hello world1")

运行用例的时候,直接使用 pytest test_repeat0.py -s ,不用带上--count参数。这里只针对test_hello用例运行5次

posted @ 2020-12-16 09:38  做一只热爱生活的小透明  阅读(123)  评论(0)    收藏  举报