fixture 是在函数前边添加了注解:@pytest.fixture 的函数,是pytest特有的功能,在编写测试函数的时候,可以将此函数名称作为参数传递进去,pytest将会以依赖注入方式将该函数的返回值作为测试函数的传入参数
二、fixture作用:1.可以把fixture看成一种资源,测试用例执行的时候需要配置这些资源,执行后需要释放掉
2.同时fixture提供参数化功能,根据配置和不同组件选择不同的参数
3.主要目的还是为了提供一种可靠和重复性的手段去运行一些基本的测试内容,比如在测试网站的功能时候,每个用例都需要登入和登出,利用fixture做一次就可,否则每个测试用例都来做这两步也挺冗余的
三、fixture的作用域fixture 里边有个scope参数可以控制fixture的作用域,session>module>class>function
- function:每一个方法和函数都会被调用
- class:每一个类都会被调用,类下边可以有好多方法
- module:每一个.py文件调用一次,该文件内又有多个function 和class
- session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是一个module
1.函数直接里边传入:
@pytest.fixture(scope='session')
def before():
return ('wdew')
2.使用装饰器@pytest.mark.usefixtures('before'),括号里是fixture的自定义函数名
@pytest.fixture(scope='session')
def before():
return ('wdew')
@pytest.mark.usefixtures('before')
def test_01(before):
print('hua')
3.使用autouse=True
@pytest.fixture(autouse=True)
def before():
return ('wdew')
附录代码(无参数)
import pytest
# @pytest.fixture(scope='session')
@pytest.fixture(autouse=True)
def before():
return ('wdew')
@pytest.mark.usefixtures('before')
def test_01(before):
print('hua')
class TestCase():
def test_01(self,before):
print('test01')
def test_02(self,before):
print('test02')
if __name__ == '__main__':
pytest.main(['-s','-v','test_fixture.py'])
五、fixture 参数
fixture有一个params参数,接受一个列表,列表中的每一个数据都可以作为用例的输入,也就是说列表中有多少数据就会形成多少个测试用例
代码如下:
import pytest
import random
res = [1,'tom',3,'tender',4]
@pytest.fixture(params=res)
def before():
return ('wdew')
def test_liebiao(before):
print('第{}条数据'.format(random.randint(1,6)))
if __name__ == '__main__':
pytest.main(['-s','-v','test_fixture.py'])
运行结果:
以上是pytest框架中fixture的介绍和使用,如有问题,随时沟通~下一篇pytest-mark的使用介绍



