pytest重复运行测试用例(pytest-repeat插件)

  我们平时在做测试的时候经常会遇到网络抖动,导致测试用例执行失败,重试一下用例又成功了;有时候还会遇到功能不稳定,偶尔会出现bug,我们经常需要反复多次的运行用例,从而来复现问题。pytest-repeat插件就可以实现重复运行测试用例的功能。

pytest-repeat安装

pip install pytest-repeat

使用方式

命令行使用--count参数来指定测试用例的运行次数。

pytest --count=5 test_file.py    # --count=5表示重复执行5次

举例:

# file_name: test_repeat.py


import pytest


def test_01():
    print("\n测试用例test_01")


def test_02():
    print("\n测试用例test_02")


def test_03():
    print("\n测试用例test_03")


if __name__ == '__main__':
    pytest.main(['-s', 'test_repeat.py'])

命令行输入指令:pytest --count=3 test_repeat.py -s -v,运行结果:

  从结果中可以看到,每个测试用例被重复运行了三次。

通过指定--repeat-scope参数来控制重复范围

  从上面例子的运行结果中可以看到,首先重复运行了3次test_01,然后重复运行了3次test_02,最后重复运行了3次test_03。但是有的时候我们想按照执行顺序为test_01,test_02,test_03这样的顺序来重复运行3次呢,这时候就需要用到另外一个参数了:--repeat-scope。

  --repeat-scope与pytest的fixture的scope是类似的,--repeat-scope可设置的值为:module、class、session、function(默认)。

  • module:以整个.py文件为单位,重复执行模块里面的用例,然后再执行下一个(以.py文件为单位,执行一次.py,然后再执行一下.py);
  • class:以class为单位,重复运行class中的用例,然后重复执行下一个(以class为单位,运行一次class,再运行一次class这样);
  • session:重复运行整个会话,所有测试用例运行一次,然后再所有测试用例运行一次;
  • function(默认):针对每个用例重复运行,然后再运行下一次用例;

使用--repeat-scope=session重复运行整个会话,命令行输入指令:pytest test_repeat.py -s -v --count=3 --repeat-scope=session,运行结果为:

  从结果中可以看到,执行顺序为:test_01、test_02、test_03;然后重复运行3次;

通过装饰器@pytest.mark.repeat(count)指定某个用例重复执行

# file_name: test_repeat.py


import pytest


def test_01():
    print("\n测试用例test_01")


@pytest.mark.repeat(3)
def test_02():
    print("\n测试用例test_02")


def test_03():
    print("\n测试用例test_03")


if __name__ == '__main__':
    pytest.main(['-s', 'test_repeat.py'])

命令行输入指令:pytest test_repeat.py -s -v,运行结果:

  从结果中可以看到只有被装饰器@pytest.mark.repeat(3)标记的用例test_02被重复运行了3次。

重复运行用例直到遇到失败用例就停止运行

  通过pytest -x 和 pytest-repeat 的结合就能实现重复运行测试用例直到遇到第一次失败用例就停止运行。

pytest test_file.py -s -v -X --count=20

命令行中输入上述指令后,测试用以将重复运行20遍,但重复运行的过程中一旦遇到失败用例就会停止运行。

posted @ 2021-02-25 18:19  lwjnicole  阅读(604)  评论(0编辑  收藏  举报