我有一个python脚本在脚本开头执行此操作:
def initialize(module_name):
return importlib.import_module(module_name) # import module from string
我想编写一个“模拟”模块名称的测试,如下所示:
def test():
# assemble module at run time
module_obj = {'name': Object, 'another_name': AnotherObject}
# inject to the "import system"
inject_mock_module('mymodule', module_obj)
# assert that the import went correctly
assert my_module_mock == initialize('mymodule')
我该怎么做?首先,具体来说,我如何创建module_obj
以及如何定义inject_mock_module
?这需要在2.7+和3.3 +
答案 0 :(得分:2)
使用mock
library模拟import_module()
功能。从Python 3.3开始,您可以将该模块导入为unittest.mock
:
try:
# Python 3.3+
from unittest.mock import patch
except ImportError:
# External dependency
from mock import patch
def test():
module_obj = {'name': Object, 'another_name': AnotherObject}
with patch('importlib.import_module', module_obj.get):
assert initialize('name') is module_obj['name']