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

Python Mock open调用无参数,assert_called_once_with断言失败如何解决?

Mock open断言失败问题解决方案

错误根因

  • 补丁作用域不匹配:你通过patch('task_4.open')打的补丁仅对task_4模块内部调用的open生效,你当前测试代码中直接调用的是Python内置全局open,没有被Mock覆盖,参数无法被记录,因此返回的实际调用显示为open()。
  • Patch参数使用错误:你将实例化后的mock_open()对象传给了new_callable参数,该参数预期接收可调用的类/函数而非实例,正确用法是将mock_open(无括号)传给new_callable,或是将实例化后的mock_open()传给new参数。

修正方案

方案1:测试当前作用域的open调用

如果要覆盖当前测试代码中的全局open,直接patch内置open即可:

import unittest
from unittest.mock import patch, mock_open

class TestFileData(unittest.TestCase):
    def test_save_data(self):
        m = mock_open()
        with patch('builtins.open', new=m) as f:
            with open('test.txt', 'w') as h:
                h.write('this is text')
                print(m.mock_calls)
                m.assert_called_once_with('test.txt', 'w')

方案2:测试task_4模块内部的open调用

如果你的测试目标是验证task_4模块内的逻辑是否正确调用了open,确保你调用的是task_4模块下的open,或是直接调用task_4中触发open调用的目标函数:

import unittest
from unittest.mock import patch, mock_open
import task_4

class TestFileData(unittest.TestCase):
    def test_save_data(self):
        m = mock_open()
        with patch('task_4.open', new=m) as f:
            # 示例:调用task_4中会触发open的目标函数即可,无需手动写open逻辑
            # task_4.你的目标函数()
            with task_4.open('test.txt', 'w') as h:
                h.write('this is text')
                print(m.mock_calls)
                m.assert_called_once_with('test.txt', 'w')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:06:02