说明
在日常使用pytest写自动化测试用例时,经常会写一些前置的fixtrue操作,当其测试用例有用到时就直接传该函数的参数名称就可以了,但有时候用例很多的时候,每次都传这个参数的话会显得比较冗余、麻烦。
针对这样的情况,pytest早就已经替我们想到了,fixture 里面有个参数 autouse,默认是 Fasle 没开启的,可以设置为True 开启,就可以自动使用了,也就是说不用再手动传参就可以自动运行该用例了。
方法使用
那autouse要怎么使用呢,其实就是在引用fixtrue写前置用例时,传一个autouse=True就可以了。具体看如下代码:
```python
import pytest
import time
@pytest.fixture(scope='module',autouse=True)
def start(request):
print('********开始执行module********')
print('module:%s'%request.module.__name__)
print('*******启动浏览器********')
yield
print('********结束测试 end!********')
@pytest.fixture(scope='function',autouse=True)
def open_home(request):
print('function:%s \n********回到首页********' %request.function.__name__)
def test_01():
print('*******执行用例1******')
def test_02():
print('******执行用例2******')
if __name__ == '__main__':
pytest.main(['-s','test_auto1.py'])
以上代码的start方法使用了fixtrue前置,并且设置 scope 为 module 级别,即运行当前.py文件只执行一次start方法,并传参autouse=True进去,这样当我们运行该.py文件时,pytest框架识别到autouse=True时就会自动运行该用例,如下图所示。
上述的autouse是在函数中运行实现的,那在class类中同样使用
@pytest.fixture(scope='module',autouse=True)
def start(request):
print('********开始执行module********')
print('module:%s'%request.module.__name__)
print('*******启动浏览器********')
yield
print('********结束测试 end!********')
class Test():
@pytest.fixture(scope='function',autouse=True)
def open_home(self,request):
print('function:%s \n********回到首页********' %request.function.__name__)
def test_01(self):
print('*******执行用例1******')
def test_02(self):
print('******执行用例2******')
if __name__ == '__main__':
pytest.main(['-s','test_auto1.py'])
通过运行结果可知,对于class类的运行也会自动执行start和open_home方法。
总结
autouse的用法是不是很简单呢,简单的来说就是在使用fixtrue的时候加一个autouse=Ture的参数就可以了,然后该用例就会自动运行。