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

pytest如何为builtins.open创建按输入路径返回不同值的模拟对象

实现不同路径返回不同模拟内容的方案

核心是使用mocker.patch的side_effect参数绑定自定义处理逻辑,每次调用open时会自动执行该逻辑,根据传入的路径返回对应模拟值。

修改后的fixture代码

import pytest
from io import StringIO

# 如果fixture定义在测试类内部,参数保留self即可
@pytest.fixture
def mock_open(mocker):
    def _custom_open(file_path, *args, **kwargs):
        # 匹配路径a的场景
        if file_path == "a":
            return StringIO("mock a")
        # 其余路径默认返回mock b
        return StringIO("mock b")
    
    mock_file = mocker.patch('builtins.open', side_effect=_custom_open)
    return mock_file

测试用例示例

# 如需校验调用参数,需导入call
from unittest.mock import call

def test_read_different_files(mock_open):
    # 路径a的返回校验
    with open("a") as f:
        assert f.read() == "mock a"
    
    # 其他路径的返回校验
    with open("any/other/path") as f:
        assert f.read() == "mock b"
    
    # 可选:验证open的调用参数符合预期
    mock_open.assert_has_calls(
        [call("a"), call("any/other/path")],
        any_order=True
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 10:57:01