[英]How do I mock a python function within a test
I'm trying to mock a function that's imported from a library which is renamed. 我正在尝试模拟从重命名的库中导入的函数。
The example 这个例子
mylibrarywithlongname: mylibrarywithlongname:
def helloworld():
return "hello world"
def helloworld_helper():
return helloworld()
Main program: 主程序:
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())
This returns 这返回
hello world
oops
oops
I'm trying to find the syntax to only mock within the test without having to copy the function and restore it manually. 我试图找到仅在测试中模拟的语法,而不必复制该函数并手动还原它。
The third line should return the original "hello world" 第三行应返回原始的“ hello world”
For this example, I'm using python 2.7 (because I try to mock an old project) 对于此示例,我使用的是python 2.7(因为我尝试模拟一个旧项目)
My attempt: 我的尝试:
from mock import MagicMock, patch
@patch(ml.helloworld, MagicMock(return_value="oops"))
def test():
print(ml.helloworld_helper())
fails with the error 失败并显示错误
AttributeError: 'function' object has no attribute 'rsplit'
Answering my own question: I need to patch the original import name for it to work. 回答我自己的问题:我需要打补丁原始的导入名称才能起作用。
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.