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

Python单元测试patch失效:实际read_file/write_file方法仍被调用

正确mock同模块内函数的patch方式

问题根源

你遇到的问题是patch路径不正确。当在同一个Python文件里,update_baseline_manifest直接调用read_file和write_file时,Python会引用当前模块内的这些函数对象,所以必须patch当前模块自身的这两个函数,而不是其他路径。

正确实现示例

假设你的update_baseline_manifest.py代码如下:

def read_file(file_path):
    print("执行了真实的read_file")
    # 真实逻辑
    return "原始内容"

def write_file(file_path, content):
    print("执行了真实的write_file")
    # 真实逻辑

def update_baseline_manifest(path):
    content = read_file(path)
    new_content = content + "新增内容"
    write_file(path, new_content)

单元测试文件(比如test_update_manifest.py)的正确写法

from unittest.mock import patch
import update_baseline_manifest as ubm

def test_update_baseline_manifest():
    # 关键:patch的是模块自身的read_file和write_file
    with patch.object(ubm, 'read_file', return_value="mock内容") as mock_read, \
         patch.object(ubm, 'write_file') as mock_write:
        
        ubm.update_baseline_manifest("test_path.txt")
        
        # 验证mock是否被调用
        mock_read.assert_called_once_with("test_path.txt")
        mock_write.assert_called_once_with("test_path.txt", "mock内容新增内容")

或者用字符串路径的方式patch:

from unittest.mock import patch
import update_baseline_manifest as ubm

def test_update_baseline_manifest():
    with patch('update_baseline_manifest.read_file', return_value="mock内容") as mock_read, \
         patch('update_baseline_manifest.write_file') as mock_write:
        
        ubm.update_baseline_manifest("test_path.txt")
        
        mock_read.assert_called_once_with("test_path.txt")
        mock_write.assert_called_once_with("test_path.txt", "mock内容新增内容")

常见错误原因

如果你的patch路径写成了__main__.read_file或者其他错误路径,就会导致mock不生效,真实函数依然执行。必须确保patch的是被测试函数所在模块中的目标函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 16:55:03