如何在 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()
    }
相关推荐
牛客企业服务2 小时前
2025校招AI应用:校园招聘的革新与挑战
大数据·人工智能·机器学习·面试·职场和发展·求职招聘·语音识别
倔强青铜三2 小时前
苦练Python第38天:input() 高级处理,安全与异常管理
人工智能·python·面试
小高0072 小时前
🚀把 async/await 拆成 4 块乐高!面试官当场鼓掌👏
前端·javascript·面试
雲墨款哥2 小时前
为什么我的this.name输出了空字符串?严格模式与作用域链的微妙关系
前端·javascript·面试
丘山子5 小时前
DNS 原理入门
前端·后端·面试
IT成长日记7 小时前
【自动化运维神器Ansible】Ansible常用模块之user模块详解
运维·自动化·ansible·user·常用模块
丘山子7 小时前
Python 布尔运算的优雅实践
后端·python·面试
海风极客8 小时前
Go内存逃逸分析,真的很神奇吗?
后端·面试
Doris_LMS9 小时前
Linux的访问权限(保姆级别)
linux·运维·服务器·面试