如何在 Pytest 中调用其他用例返回的接口参数?

回答重点

在 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,它返回一个包含 tokenuser_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()
    }
相关推荐
程序员爱钓鱼1 小时前
Go排序核心库: sort包深度指南
后端·面试·go
姚青&6 小时前
Pytest 插件
pytest
hpoenixf7 小时前
2026 年前端面试问什么
前端·面试
RainyJiang9 小时前
谱写Kotlin协程面试进行曲-进阶篇(第二乐章)
面试·kotlin·android jetpack
姚青&10 小时前
Pytest 测试用例生命周期管理-yield
测试用例·pytest
星纬智联技术11 小时前
GEO E2E 自动化验证测试文章
运维·自动化·geo
Moment12 小时前
前端工程化 + AI 赋能,从需求到运维一条龙怎么搭 ❓❓❓
前端·javascript·面试
紫丁香12 小时前
pytest_自动化测试3
开发语言·python·功能测试·单元测试·集成测试·pytest
独自破碎E12 小时前
【面试真题拆解】你知道ThreadLocal是什么吗
java·jvm·面试
小罗和阿泽12 小时前
接口测试系列 接口自动化测试 pytest框架(二)
pytest