回答重点
在 Pytest 中,我们可以通过使用共享夹具(fixtures)来调用和复用其他用例返回的接口参数。在 Pytest 中,fixtures 提供了一种灵活且有组织的方式来共享测试数据或对象。
具体步骤如下:
1)首先,在 conftest.py
文件中定义一个 fixture 函数,该函数会返回你希望共享的参数。这个 fixture 可以通过标识符传递给任何测试函数。
2)在需要复用该参数的测试函数中,通过传递相应的参数名来引用该 fixture。
下面是一个示例代码,可以帮助你理解:
# conftest.py
import pytest
@pytest.fixture
def api_response():
# 假设这是你从接口获取的参数
response = {
"token": "abc123",
"user_id": 1
}
return response
# test_example.py
def test_first_example(api_response):
assert api_response["token"] == "abc123"
def test_second_example(api_response):
assert api_response["user_id"] == 1
# 你可以继续使用 `api_response` 进行其他测试或接口调用
在上述示例中, api_response
是一个 fixture,它返回一个包含 token
和 user_id
的字典。任何需要这些数据的测试函数,只需声明它们的参数即可自动获取此数据,从而实现复用。
扩展知识
1) Fixture 的 作用域
Fixture 可以设置不同的作用域级别(如 function, class, module, session),这决定了 fixture 的生命周期。作用域越大,fixture 的创建和销毁次数越少。
@pytest.fixture(scope="module")
def api_response():
# 模块级别的 fixture,在整个模块中共享
...
2) Fixture 的依赖
Fixture 之间也可以相互调用,从而构建更加复杂的数据依赖。
@pytest.fixture
def auth_token():
return "secret-token"
@pytest.fixture
def api_response(auth_token):
return {
"token": auth_token,
"user_id": 1
}
3) 动态生成数据
有时我们需要为每个测试生成不同的数据,可以用 yield
关键字或者动态计算的方法来实现。
@pytest.fixture
def dynamic_response():
token = generate_token()
return {
"token": token,
"user_id": random_user_id()
}