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

如何使用pytest-mock绕过调用路径/命名空间限制打桩函数?

解决不同导入方式下的函数Mock问题

问题原因

from mymodule import test1会将原函数的引用直接存入当前测试模块的命名空间,后续你patchmymodule.test1仅修改了模块内的函数引用,不会影响已经导入到当前模块的test1变量,所以第二个断言失败。

两种可行解决方案

方案1:Patch当前测试模块中的test1引用

直接针对当前测试模块里的test1进行patch,确保调用的是被mock后的版本:

import mymodule
from mymodule import test1


def test_mock(mocker):
    # 若测试文件不是主模块,替换为你的测试模块名(比如"test_mycode.test1")
    mocker.patch('__main__.test1', return_value="mocked")
    assert mymodule.test1() == "mocked"
    assert test1() == "mocked"

方案2:在Patch后重新导入函数

先patch模块内的函数,再重新导入test1,此时会获取到模块中已被mock的函数引用:

import mymodule


def test_mock(mocker):
    mocker.patch('mymodule.test1', return_value="mocked")
    from mymodule import test1  # 在patch完成后重新导入
    assert mymodule.test1() == "mocked"
    assert test1() == "mocked"

额外建议

日常测试中尽量保持统一的导入风格,要么始终通过模块调用函数(mymodule.test1()),要么始终直接导入函数,这样mock时只需针对单一位置处理,避免路径混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:12:36