如何使用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
相关产品推荐
相关产品推荐

