我正在尝试模拟从已重命名的库中导入的函数。
例子
我的图书馆长名:
def helloworld():
return "hello world"
def helloworld_helper():
return helloworld()
主程序:
import mylibrarywithlongname as ml
from mock import MagicMock
def test():
ml.helloworld = MagicMock(return_value="oops")
print(ml.helloworld_helper())
print(ml.helloworld_helper())
test()
print(ml.helloworld_helper())
返回
hello world
oops
oops
我试图找到只在测试中模拟的语法 无需复制函数并手动恢复。
第三行应该返回原来的“hello world”
对于这个例子,我使用的是 python 2.7(因为我试图模拟一个旧项目)
我的尝试:
from mock import MagicMock, patch
@patch(ml.helloworld, MagicMock(return_value="oops"))
def test():
print(ml.helloworld_helper())
因错误而失败
AttributeError: 'function' object has no attribute 'rsplit'
最佳答案
回答我自己的问题:我需要修补原始导入名称才能正常工作。
import mylibrarywithlongname as ml
from mock import patch
def test():
with patch('mylibrarywithlongname.helloworld') as mp:
ml.helloworld.return_value = "oops"
print(ml.helloworld_helper())
print(ml.helloworld_helper())
test()
print(ml.helloworld_helper())
关于python - 如何模拟在测试中使用别名导入的 python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48356440/