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
相关产品推荐
相关产品推荐

