Pytest学习(十三)- 重复执行之pytest-repeat的使用

写在前面

这个插件,能够帮助咱们很好的解决自动化测试过程当中的一些偶线性bug难以复现的问题,但前提是,当前自动化脚本是独立的,不依赖任何其余脚本。我的以为仍是失败重运行的一种体现,就和TestNG是同样的,下面咱们来一块儿感觉下这个插件的使用吧。html

环境准备

  • py.test版本 ≥ 2.8
  • Python 2.七、3.4+

安装插件

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

如何使用

结合《生成HTML报告插件之pytest-html的使用》这篇文章,仍是结合输出的html报告来看比较直观。python

一、举个例子

# -*- coding: utf-8 -*-
# @Time    : 2020/11/29 8:52
# @Author  : longrong.lang
# @FileName: test_repeat.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang

def test_repeat():
    import random
    num = random.randint(1, 9)
    print(f"\n输出随机数:{num}")
    assert num == 2

二、结合失败重跑,并输出报告

使用示例以下:session

# 使用下面哪条命令均可执行
pytest --html=report.html --self-contained-html  -s --reruns=5 --count=3 test_repeat.py
pytest --html=report.html --self-contained-html  -s --reruns=5 --count 3 test_repeat.py

执行效果以下:
dom

生成html报告以下:
测试

注意:插件

  • reruns=5:意思是失败重运行5次
  • count=3:意思是重复执行3次

三、仅重复执行

使用示例以下:命令行

# 使用下面哪条命令均可执行
pytest --html=report.html --self-contained-html  -s --count=3 test_repeat.py
pytest --html=report.html --self-contained-html  -s --count 3 test_repeat.py

执行效果以下:
3d

很明显这里显示的只是重复执行3次code

四、重复测试直到失败

这在咱们实际测试中,就很受用了,验证偶现问题,能够反复运行相同的测试脚本直到失败,能够将pytest的 -x 选项与pytest-repeat结合使用,以强制测试运行程序在第一次失败时中止。
使用示例以下:htm

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

执行效果以下:

五、使用注解的形式来实现重复执行

使用 @pytest.mark.repeat(count)标记在测试方法便可,这和TestNg的 @Test(invocationCount = 5)是同样的。
示例代码以下:

@pytest.mark.repeat(3)
def test_repeat2():
    print("\n 测试脚本")

执行效果以下:

repeat-scope的使用

命令行参数
做用:能够覆盖默认的测试用例执行顺序,相似fixture的scope参数

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

一、重复执行class里面的用例

即class中的测试方法,不存在混合状况,示例代码以下:

# -*- coding: utf-8 -*-
# @Time    : 2020/11/29 10:07
# @Author  : longrong.lang
# @FileName: test_repeatClass.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
class TestRepeatClass1(object):
    def test_repeat1(self):
        print("\n repeat 1。。。。。。。。。")

class TestRepeatClass2(object):
    def test_repeat2(self):
        print("\n repeat 2。。。。。。。。。")

命令行执行:

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

执行效果以下:

二、以模块为单位,重复执行模块里面的用例

能够理解为混合,既有类也有单独的测试方法,示例代码以下:

# -*- coding: utf-8 -*-
# @Time    : 2020/11/29 10:07
# @Author  : longrong.lang
# @FileName: test_repeatClass.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang

def test_repeat1():
    print("test_repeat1")


class TestRepeatClass1(object):
    def test_repeat1(self):
        print("\n repeat 1。。。。。。。。。")

执行命令:

pytest -s --count=2 --repeat-scope=moudle test_repeatClass.py

执行效果以下:

兼容性问题
pytest-repeat不能与unittest.TestCase测试类一块儿使用。不管--count设置多少,这些测试始终仅运行一次,并显示警告

系列参考文章:
https://www.cnblogs.com/poloyy/category/1690628.html

相关文章
相关标签/搜索