![](/img/trans.png)
[英]Unit testing Python Azure Function: How do I construct a mock test request message with a JSON payload?
[英]How do I mock a python function within a test
我正在尝试模拟从重命名的库中导入的函数。
这个例子
mylibrarywithlongname:
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.