pytest(14):重复执行用例插件之pytest-repeat的详细使用
前言
- 平常在做功能测试的时候,经常会遇到某个模块不稳定,偶然会出现一些bug,对于这种问题我们会针对此用例反复执行多次,最终复现出问题来
- 自动化运行用例时候,也会出现偶然的bug,可以针对单个用例,或者针对某个模块的用例重复执行多次
环境前提
- Python 2.7、3.4+或PyPy
- py.test 2.8或更高版本
安装插件
pip3 install pytest-repeat -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
快速入门
结合之前讲到的失败重跑、输出html报告插件来敲命令行
两种方式皆可,等号或空格
- count=2
- count 2
pytest --html=report.html --self-contained-html -s --reruns=5 --count=2 10fixture_request.py
重复测试直到失败(重点!)*与上文讲的returns主要的区别就是一个是出现错误return直到通过,另一个是重复执行直到出现错误
- 如果需要验证偶现问题,可以一次又一次地运行相同的测试直到失败,这个插件将很有用
- 可以将pytest的 -x 选项与pytest-repeat结合使用,以强制测试运行程序在第一次失败时停止
py.test --count=1000 -x test_file.py
举例
class Test_AA():
def test_re(self):
j=1
print(1)
assert j==1
def test_re2(self):
i=1
print(i)
assert i==1
命令行执行:pytest -s --count=5 test_report.py
@pytest.mark.repeat(count)
如果要在代码中将某些测试用例标记为执行重复多次,可以使用 @pytest.mark.repeat(count)
class Test_AA():
@pytest.mark.repeat(5)
def test_re(self):
j=1
print(1)
assert j==1
命令行执行:pytest -s test_report.py
--repeat-scope
命令行参数
作用:可以覆盖默认的测试用例执行顺序,类似fixture的scope参数
- function:默认,范围针对每个用例重复执行,再执行下一个用例
- class:以class为用例集合单位,重复执行class里面的用例,再执行下一个
- module:以模块为单位,重复执行模块里面的用例,再执行下一个
- session:重复整个测试会话,即所有测试用例的执行一次,然后再执行第二次
代码:
import pytest
import random
class Test_AA():
# @pytest.mark.repeat(5)
def test_re(self):
j=1
print(1)
assert j==1
def test_re2(self):
i=1
print(i)
assert i==1
class Test_BB():
def test_reb(self):
j=2
print(j)
assert j==2
def test_reb2(self):
i=1
print(i)
assert i==1
执行命令
pytest -s --count=2 --repeat-scope=class test_A.py