如何在测试中模拟python函数

时间:2018-01-20 12:59:39

标签: python python-2.7 testing mocking

我试图模拟从重命名的库中导入的函数。

示例

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'

1 个答案:

答案 0 :(得分:0)

回答我自己的问题:我需要修补原始导入名称才能正常工作。

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())
相关问题