一、前言

上面我们介绍了当用例失败时的重复运行,其实我们在实际工作中还会遇到一种情况,我们就是单纯的想让某条用例重复运行指定的次数。

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

二、学习目标

1.pytest-repeat安装

2.pytest-repeat应用

三、知识点

1.pytest-repeat安装

插件安装:

pip install pytest-repeat

2.pytest-repeat应用

使用方式有两种:

  • 命令行参数

    • 语法:

      pytest --count=3 --repeat-scope=class test_demo.py 
      #3是重复运行的次数
      #–repeat-scope的参数有 choices=('function', 'class', 'module', 'session') 默认为function;控制用例重复执行时机
      
    • 代码示例:

      class TestCase():
      
          def test_01(self):
              print("---用例1执行---")
      
    • 运行效果:

      test_demo.py ---用例1执行---
      .---用例1执行---
      .---用例1执行---
      .---用例2执行---
      .---用例2执行---
      .---用例2执行---
      ==================================== 6 passed in 0.02s ==================================
      

      以类为单位重复运行了三次。

  • 装饰器方式

    • 语法:

      @pytest.mark.repeat(num) #num运行次数
      
    • 代码示例:

      import pytest
      
      def test_01():
          print("---用例1执行---")
      
      class TestCase():
      
          @pytest.mark.repeat(3)
          def test_02(self):
              print("---用例2执行---")
      
    • 运行效果:

      test_demo.py::test_01 PASSED                                             [ 25%]---用例1执行---
      test_demo.py::TestCase::test_02[1-3] PASSED                              [ 50%]---用例2执行---
      test_demo.py::TestCase::test_02[2-3] PASSED                              [ 75%]---用例2执行---
      test_demo.py::TestCase::test_02[3-3] PASSED                              [100%]---用例2执行---
      ============================== 4 passed in 0.03s ==============================
      

      第二个测试用例重复运行了3次。