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

mock.patch打成员函数补丁失败 报AttributeError模块无object属性

问题说明

你遇到的报错AttributeError: 'module' object has no attribute 'object'翻译为:

属性错误:模块对象不存在名为object的属性

报错根因是mock.patch用法完全错误,存在两个核心问题:

  • mock.patch第一个参数必须是字符串格式的点分导入路径,你当前写法把模块对象application.engine.prompt作为第一个参数传入、方法名字符串作为第二个参数传入,不符合接口传参要求,直接触发报错。
  • mock路径选择需要遵循「patch被测代码实际使用的引用」规则,不能随意选定义处的路径。
正确实现

两种可正常运行的断言写法,二选一即可:

写法1:按规则patch目标方法

from unittest import mock
import unittest
from application.scheduler.runner import Runner

class TestRunner(unittest.TestCase):
    def test_run(self):
        # 路径为字符串,指向Runner模块实际调用的Prompt.run_cmd方法
        with mock.patch("application.engine.prompt.Prompt.run_cmd") as mock_run_cmd:
            runner = Runner()
            runner.run()
            # 断言入参符合预期
            mock_run_cmd.assert_called_once_with("unique cmd")

写法2:直接替换实例属性(无路径问题)

不需要记忆mock路径规则,直接替换Runner实例内部的prompt对象的方法,出错概率更低:

from unittest import mock
import unittest
from application.scheduler.runner import Runner

class TestRunner(unittest.TestCase):
    def test_run(self):
        runner = Runner()
        # 直接替换实例内部依赖的方法为mock对象
        runner.prompt.run_cmd = mock.Mock()
        runner.run()
        # 断言入参
        runner.prompt.run_cmd.assert_called_once_with("unique cmd")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:51:22