自动化测试 - 重复执行测试

在功能测试过程中,经常会遇到一些偶然出现的 Bug,所以我们需要通过重复执行用例来复现问题,但前提是,当前自动化脚本是独立的,不依赖任何其他脚本。可以针对单个用例,或者针对某个模块的用例重复执行多次来复现。

安装插件

全局安装:即安装在全局环境中,新创建的工程导入全局环境时会将该包导入,cmd 输入:pip install pytest-repeat。

局部安装:即安装在当前项目的环境下,新创建的工程不会同步该包,在 PyCharm→File→setting,搜索 pytest intrepreter,点击 “+” 号,如下图所示:

image.png
image.png

pytest-repeat(重复执行单条或全部测试用例)

注意: pytest-repeat不能与unittest.TestCase测试类一起使用。无论--count设置多少,这些测试始终仅运行一次,并显示警告。

方法一:使用注解方式,实现重复执行单条用例

注:在测试用例前添加注解@pytest.mark.repeat(value),value 表示重复的次数,来实现单条用例的重复执行。

import pytest

@pytest.mark.repeat(1)
def test_01():
    print("测试用例test_01")

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


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


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

执行效果如下:

image.png

方法二:使用命令行参数,实现重复执行所有用例
import pytest

class Test_Pytest:

    def test_one(self):
      print("test_one方法执行")

    def test_two(self):
      print("test_two方法执行")

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

在终端输入:

pytest -s -v --count=2 Test_Pytest.py

注:
-s:表示输出用例中的调式信息,比如 print 的打印信息等。

-v:表示输出用例更加详细的执行信息,比如用例所在的文件及用例名称等。

执行效果如下:

image.png

repeat-scope的使用

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

import pytest

class Test_Pytest:

    def test_one(self):
      print("test_one方法执行")

    def test_two(self):
      print("test_two方法执行")

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

在终端输入:

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

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

执行效果如下:

image.png

pytest-rerunfailures(测试用例执行失败后重运行)

方法一:通过注解的形式实现失败重运行

import pytest

class Test_Failure:
     # 用例失败后重新运行2次,重运行之间的间隔时间为10s
    @pytest.mark.flaky(reruns=2, reruns_delay=10)
    def test_one(self):
      a = 1 + 2
      assert 1 == a

    def test_two(self):
      a = 1 + 2
      assert 3 == a


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

注:
reruns: 表示重运行的次数
reruns_delay: 表示重运行次数之间的延迟时间,单位:秒

执行结果如下:

image.png

方法二:通过使用命令行参数,实现失败重运行

import pytest

class Test_Failure:

    def test_one(self):
      a = 1 + 2
      assert 1 == a

    def test_two(self):
      a = 1 + 2
      assert 3 == a


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

在终端输入:

pytest -s -v --reruns=2 --reruns-delay=10 Test_Failure.py

执行结果如下:

截屏2022-03-14 上午12.26.09.png

pytest 的 -x 选项与 pytest-repeat 结合(重复执行测试用例直到失败停止)

将 pytest 的 -x 选项与 pytest-repeat 结合使用,可以实现在重复运行测试用例的过程中,测试用例第一次失败时就停止运行,具体实现方法如下:

import pytest

class Test_Failure:
  
    def test_one(self):
      a = 1 + 2
      assert 1 == a

    def test_two(self):
      a = 1 + 2
      assert 3 == a


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

在终端输入:

pytest -s -v --count=3 -x Test_Failure.py

执行结果如下:

截屏2022-03-14 上午12.49.02.png

你可能感兴趣的:(自动化测试 - 重复执行测试)