pytest(二十六)--重复执行用例(pytest-repeat)

前言

平常在做功能测试的时候,经常会遇到某个模块不稳定,偶然会出现一些bug,对于这种问题我们会针对此用例反复执行多次,最终复现出问题来。

自动化运行用例时候,也会出现偶然的bug,可以针对单个用例,或者针对某个模块的用例重复执行多次。

pytest-repeat

pytest-repeat是pytest的一个插件,用于重复执行单个用例,或多个测试用例,并指定重复次数,pytest-repeat支持的版本:

  • python 2.7,3.4+ 或 PyPy
  • py.test 2.8或更高

使用pip 安装pytest-repeat

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

py.test --count=10 脚本名.py

重复执行--count

运行以下代码,项目结果如下:

 代码参考:

#web_item_py/conftest.py
# coding:utf-8
import pytest
@pytest.fixture(scope="session")
def begin():
    print("
打开首页")

#web_item_py/qq/conftest.py
# coding:utf-8
import pytest

@pytest.fixture(scope="session")
def open_baidu():
    print("打开百度页面_session")

#web_item_py/qq/test_1_qq.py
# coding:utf-8
import pytest
def test_q1(begin,open_baidu):
    print("测试用例test_q1")
    assert 1
def test_q2(begin,open_baidu):
    print("测试用例test_q2")
    assert 1
if __name__=="__main__":
    pytest.main(["-s","test_1_QQ.py"])

#web_item_py/qq/test_q2.py
# coding:utf-8
import pytest
def test_q8(begin,open_baidu):
    print("测试用例test_q8")
    assert 1
def test_q9(begin,open_baidu):
    print("测试用例test_q9")
    assert 1
if __name__=="__main__":
    pytest.main(["-s","test_q2.py"])

cmd到相应脚本目录后,不带--count参数只会执行一次

 加上参数--count=5,用例会重复执行5次;

pytest test_q2.py -s --count=5

 从运行的用例结果看,是先重复5次test_q8,再重复5次test_q9,有时候我们希望执行的顺序是test_q8,test_q9按这样顺序重复五次,接下来就用到一个参数--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_q2.py -s --count=5 --repeat-scope=session

 @pytest.mark.repeat(count)

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

#web_item_py/qq/test_q2.py
# coding:utf-8
import pytest
@pytest.mark.repeat(5)
def test_q8(begin,open_baidu):
    print("测试用例test_q8")
    assert 1
def test_q9(begin,open_baidu):
    print("测试用例test_q9")
    assert 1
if __name__=="__main__":
    pytest.main(["-s","test_q2.py"])

这样执行用例时候,就不用带上--count参数,只针对test_q8重复执行5次

 这样执行时,再加上--count=3,只对无count装饰器的重复3次。

 重复测试直至失败

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

py.test --count=1000 -x test_q2.py 或 pytest --count=1000 -x test_q2.py

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

UnitTest样式测试

不幸的是,此插件不支持unittest框架的用例,pytest-repeat无法使用unittest.TestCase测试类。无论如何,这些测试将始终运行一次--count,并显示警告
更多资料参考【官方文档:https://pypi.org/project/pytest-repeat/】

越努力,越幸运!!! good good study,day day up!!!
原文地址:https://www.cnblogs.com/canglongdao/p/13409772.html