You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pytest如何为与_Config类紧耦合的resource函数编写测试fixture

问题解决方案:让resource函数使用自定义config实例的fixture写法

核心思路是覆盖resource函数内部调用的_Config.get_config()默认行为,分为两种实现方案:

方案1:无需修改原file1.py代码,使用pytest内置的monkeypatch打补丁

适合你没有权限修改业务源码的场景,直接在测试层通过补丁替换get_config的返回值即可:

import pytest
from ..dir import file1

@pytest.fixture()
def value_resource(monkeypatch):
    # 1. 手动实例化你需要的自定义配置
    custom_config = file1._Config(
        p1="你的自定义参数",
        p2="你的自定义参数",
        p3="你的自定义参数"
        # 其他参数按需填写
    )
    # 2. 写一个mock方法替代原get_config,直接返回你的自定义配置
    def mock_get_config(*args, **kwargs):
        return custom_config
    # 3. 用monkeypatch给_Config类的get_config打补丁
    monkeypatch.setattr(file1._Config, "get_config", mock_get_config)
    # 4. 此时调用resource,内部会自动使用你构造的custom_config
    return file1.resource("value1")

方案2:修改原file1.py代码,增加可选配置参数(更易维护,推荐)

如果可以调整业务代码,给resource增加可选的config参数,测试时不需要打补丁,也不会有mock残留的副作用:

第一步:修改file1.py的resource函数

# file1.py 调整后的代码
def resource(name, config=None):
    # ....原有逻辑不变
    if name == '...': # 注意原代码这里是赋值运算符=,应该改为比较运算符==
        # 没有传入config就用默认的get_config,否则用传入的配置
        used_config = config if config is not None else _Config.get_config()
        return Resource(used_config)

第二步:编写fixture直接传参

import pytest
from ..dir import file1

@pytest.fixture()
def value_resource():
    custom_config = file1._Config(
        p1="你的自定义参数",
        p2="你的自定义参数",
        p3="你的自定义参数"
    )
    # 直接把自定义config传给resource即可
    return file1.resource("value1", config=custom_config)

内容的提问来源于stack exchange,提问作者ca9163d9

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:54:03