Pytest(二、fixture使用)
1.fixture 介绍
2.fixture使用–作为参数应用
3.fixture使用–作为函数应用
4.fixutre使用–params参数使用
1.fixture 介绍
fixture是pytest特有的功能,它用pytest.fixture标识,以装饰器形式定义在函数上面,在编写测试函数的时候,可以将此函数名称做为传入参数,pytest将会以依赖注入方式,将该函数的返回值作为测试函数的传入参数.
fixture修饰器来标记固定的工厂函数,在其他函数,模块,类或整个工程调用它时会被激活并优先执行,`通常会被用于完成预置处理和重复操作。`
pytest.fixture(scope='function', params=None, autouse=False, ids=None, name=None)
常用参数解释:
- scope: 被标记方法的作用域;
"function": 默认值,表示每个测试方法都要执行一次
"class": 作用于整个类, 表示每个类的所有测试方法只运行一次
"module": 作用于整个模块, 每个module的所有测试方法只运行一次.
"session": 作用于整个session, 每次session只运行一次.
- params: list类型,默认None, 接收参数值,对于param里面的每个值,fixture都会去遍历执行一次.
- autouse: 是否自动运行,默认为false, 为true时此session中的所有测试函数都会调用fixture
-以上的所有参数也可以不传
2.fixture基本使用--作为参数
# -*-coding:utf-8-*-
import pytest
@pytest.fixture()
def before():
print("-----> 在每个函数前执行")
def test_1():
print('-----> test_1')
def test_2(before): # 作为参数使用,会打印before()函数里面的内容
print("----> test_2")
if __name__ == "__main__":
pytest.main(["-s", "test_01_fixture.py"])
# 运行结果:
test_01_fixture.py -----> test_1
.-----> 在每个函数前执行
----> test_2
.
3.fixture基本使用--作为函数
import pytest
@pytest.fixture()
def before():
print('\nbefore each test')
@pytest.mark.usefixtures("before")
def test_1():
print('--->test_1')
# @pytest.mark.usefixtures("before") # 只会调用一次
def test_2(before):
print("----> test_2")
@pytest.mark.usefixtures("before") # 类里面的所有方法,都会调用befor()函数
class Test2:
def test_5(self):
print('test_5')
def test_6(self):
print('test_6')
if __name__ == "__main__":
pytest.main(["-s", "test_01_fixture.py"])
# 运行结果:
test_01_fixture.py
before each test
--->test_1
.
before each test
----> test_2
.
before each test
test_5
.
before each test
test_6
.
4.fixutre使用--params参数使用
# -*-coding:utf-8-*-
import pytest
@pytest.fixture(params=[1, 2, 3])
def need_data(request): # 默认传入参数request
return request.param # 取列表中单个值,默认的取值方式
class Test_ABC:
def test_a(self, need_data): # 函数名
print("\ntest_a 的值是 %s" % need_data)
if need_data < 3:
print("test_a 的值是 %s,小于3" % need_data)
if __name__ == "__main__":
pytest.main(["-s", "test_01_fixture.py"])
# 运行结果:
test_01_fixture.py
test_a 的值是 1
test_a 的值是 1,小于3
.
test_a 的值是 2
test_a 的值是 2,小于3
.
test_a 的值是 3
.
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。
文章标题:Pytest(二、fixture使用)
本文作者:伟生
发布时间:2021-01-16, 16:31:18
最后更新:2021-01-23, 19:14:40
原始链接:http://yoursite.com/2021/01/16/ceshi_13_Pytest(2)/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。