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

如何在Python中用mock_open针对特定文件Mock并断言写入内容?

针对特定文件路径Mock open并断言写入内容

你当前的代码已经实现了仅Mock指定路径"myFile"的open调用,不影响其他文件读取,但没法断言写入该文件的内容,尝试用上下文管理时还碰到了AttributeError: 'function' object has no attribute assert_called_with错误。

问题出在每次匹配"myFile"时,你都新建了一个mock.mock_open()实例,没有保留它的引用,自然没法跟踪调用记录做断言。下面是修改后的可行方案:

from unittest import mock

# 提前创建Mock文件对象并保存引用,方便后续断言
mocked_file = mock.mock_open()
builtin_open = open

def my_mock_open(*args, **kwargs):
    if args[0] == "myFile":
        # 返回预定义的Mock实例,而非每次新建
        return mocked_file(*args, **kwargs)
    # 其他路径使用原生open,不影响正常文件操作
    return builtin_open(*args, **kwargs)

def test_myfunc(mocker):
    mocker.patch('builtins.open', my_mock_open)
    # 执行要测试的函数
    myfunc()
    
    # 断言写入"myFile"的内容是否符合预期
    # 单次写入用assert_called_once_with
    mocked_file().write.assert_called_once_with("你期望的写入内容")
    
    # 如果是多次写入,用assert_has_calls按顺序断言
    # mocked_file().write.assert_has_calls([
    #     mock.call("第一行写入内容"),
    #     mock.call("第二行写入内容")
    # ])

关键说明

  • 提前实例化mocked_file,确保每次匹配"myFile"时返回的是同一个Mock对象,这样能完整保留所有调用记录
  • 断言时要通过mocked_file()获取模拟的文件对象,它的write方法才是实际被调用的对象
  • 如果需要模拟文件读取,也可以提前预设返回值:mocked_file.return_value.read.return_value = "模拟的文件内容",再断言读取行为

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 04:53:19