python - 如何模拟在测试中使用别名导入的 python 函数

标签 python python-2.7 testing mocking

我正在尝试模拟从已重命名的库中导入的函数。

例子

我的图书馆长名:

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/

相关文章:

python - 通过 Firestore 触发事件简化 python 中的字典

python - 修改Web2py中sqlform.grid()的列输出

php - A* 搜索 - 最少跳数?

python - 如何将空输入算作 else

testing - 找不到元素 : Trying to verify a disabled button

python - 在 python 中为映射类型重载 +=

python - Unix 时间戳转 ISO 8601 时间格式

python - 使用 boto 与 DynamoDB2 发生连接错误,但与 DynamoDB 无关

c++ - 如何在一台本地机器/主机上对简单的 tcp 客户端/服务器进行单元测试?

Android gradle androidTestApi 和 testApi 配置已过时