1、安装
pip install pytest-repeat
2、使用
# demo.py
import pytest
class Test:
def test001(self):
print('test001')
@pytest.mark.repeat(5)
def test002(self):
print('test002')
def test003(self):
print('test003')
def test004(self):
print('test004')
if __name__ == '__main__':
pytest.main(['-v', 'demo.py'])
运行结果:
test002执行五遍
3)参数使用
# demo.py
import pytest
class Test:
def test001(self):
print('test001')
def test002(self):
print('test002')
def test003(self):
print('test003')
def test004(self):
print('test004')
if __name__ == '__main__':
pytest.main(['-v', 'demo.py', '--count=2'])
以上也可命令行切到该py文件所在目录,然后执行:
pytest -v demo.py --count=2
运行结果:
所有用例执行两遍
备注:如果同时使用了pytest.mark.repeat()和count,那么前者优先生效,即如果test001 repeat 5次,count再设置2次,那么test001也只运行5次,不会叠加
4)repeat-scope控制重复范围
从上面例子的运行结果中可以看到,首先重复运行了2次test001,然后重复运行了2次test002,最后重复运行了2次test003和2次test004。但是有的时候我们想按照执行顺序为test001,test002,test003,test004这样的顺序来重复运行3次呢,这时候就需要用到另外一个参数了:--repeat-scope。
--repeat-scope与pytest的fixture的scope是类似的,--repeat-scope可设置的值为:module、class、session、function(默认)。
module:以整个.py文件为单位,重复执行模块里面的用例,然后再执行下一个(以.py文件为单位,执行一次.py,然后再执行一下.py);
class:以class为单位,重复运行class中的用例,然后重复执行下一个(以class为单位,运行一次class,再运行一次class这样);
session:重复运行整个会话,所有测试用例运行一次,然后再所有测试用例运行一次;
function(默认):针对每个用例重复运行,然后再运行下一次用例;
设置为class
# demo.py
import pytest
class Test1:
def test001(self):
print('test001')
def test002(self):
print('test002')
def test003(self):
print('test003')
def test004(self):
print('test004')
class Test2:
def test005(self):
print('test005')
if __name__ == '__main__':
pytest.main(['-v', 'demo.py', '--count=2', '--repeat-scope=class'])
运行结果:
以class为运行单位,先运行class1里面的,再运行class2里面的
这里设置了count为2,那就把class1里面的test按顺序执行完2遍后,再执行class2里面的
所以顺序为:1234123455
设置为module
# demo.py
import pytest
class Test1:
def test001(self):
print('test001')
def test002(self):
print('test002')
def test003(self):
print('test003')
def test004(self):
print('test004')
class Test2:
def test005(self):
print('test005')
if __name__ == '__main__':
pytest.main(['-v', 'demo.py', '--count=2', '--repeat-scope=module'])
运行结果:
以为py文件为运行单位,即若指定多个py文件运行,那就批量执行完1.py里面的用例之后,再批量执行2.py里面的用例。这里只有一个py文件,所以顺序为 1234512345
假如:1.py文件里面有123,2.py文件里面有45
cd 到相应目录下执行 pytest -v 1.py 2.py --count=2 --repeat-scope=module
则执行顺序为:1231234545
设置为session
以整个会话为运行单位,即若指定多个py文件运行,即所有py文件里面的用例执行完之后再做重复执行
假如:1.py文件里面有123,2.py文件里面有45
cd 到相应目录下执行 pytest -v 1.py 2.py --count=2 --repeat-scope=session
则执行顺序为:1234512345
此处不再示例代码