前言
在
pytest
中,可以使用@pytest.fixture
装饰器来定义fixture
,并通过request
对象来传递参数。
然而,通常我们不会通过
request
对象来传递参数给fixture
,而是直接在测试函数中传递参数。
fixture
本身可以接收参数,并且这些参数可以通过其他fixture
或测试函数传递。
request 对象
request
对象是一个内置的fixture
,它总是作为第一个参数传递给其他的fixture
函数。
request
对象的主要用途是允许fixture
之间进行通信和传递数据,以及控制fixture
的行为。
request对象具有以下一些重要的属性和方法:
request.param
: 当fixture
被参数化时,request.param
会包含传递给fixture
的参数值。request.node
: 当前请求的节点信息,通常是一个Function
、Item
或Session
对象。request.addfinalizer(func)
: 注册一个最终化函数,该函数会在测试完成后执行,无论测试是否成功。request.config
: 访问pytest
的配置信息。request.scope
: 获取fixture
的作用域(如 “function”, “module”, “session” 等)。request.fixturenames
: 获取当前请求所依赖的所有fixture
名称。
传递参数给 Fixture
示例代码
import pytest
@pytest.fixture
def give_data_to_fixture(request):
marker = request.node.get_closest_marker("data")
if marker is None:
data = None
else:
print("marker1:", marker) # Mark(name='mydata', args=(1,), kwargs={})
print("marker2:", marker.args[0]) # 10
data = marker.args[0] * 10
return data
@pytest.mark.data(1)
def test_data(give_data_to_fixture):
print("data={}".format(give_data_to_fixture))
执行结果
Fixture传递参数给testcase
方式一:利用return
示例代码
import pytest
@pytest.fixture(params=[1, 2, 3])
def flexible_fixture(request):
value = request.param
print(f"灵活的fixture参数值:{value}")
return value
# 测试函数,接收来自fixture的参数
def test_with_params(flexible_fixture):
assert flexible_fixture > 0, f"参数值 {flexible_fixture} 必须大于0"
执行效果
方式二:利用yield
示例代码
import pytest
@pytest.fixture(params=[
{"name": "zhangsan", "age": 3},
{"name": "lisi", "age": 18},
{"name": None, "age": 20}]
)
def yield_fixture(request):
print("\n--- 调用前置")
yield request.param
print("\n--- 调用后置")
# 测试函数,接收来自fixture的参数
def test_with_params(yield_fixture):
name = yield_fixture.get("name")
age = yield_fixture.get("age")
print("姓名:", name, "年龄:", age)
assert name or age >= 18, f"姓名为None或年龄小于18"
执行效果