是否可以使用 unittest.mock
在 python 中模拟模块?我有一个名为 config
的模块,在运行测试时我想通过另一个模块 test_config
来模拟它.我怎样才能做到这一点 ?谢谢.
Is it possible to mock a module in python using unittest.mock
? I have a module named config
, while running tests I want to mock it by another module test_config
. how can I do that ? Thanks.
config.py:
CONF_VAR1 = "VAR1"
CONF_VAR2 = "VAR2"
test_config.py:
test_config.py:
CONF_VAR1 = "test_VAR1"
CONF_VAR2 = "test_VAR2"
所有其他模块从 config
模块读取配置变量.在运行测试时,我希望他们从 test_config
模块中读取配置变量.
All other modules read config variables from the config
module. While running tests I want them to read config variables from test_config
module instead.
如果你总是像这样访问 config.py 中的变量:
If you're always accessing the variables in config.py like this:
import config
...
config.VAR1
您可以替换由您实际尝试测试的任何模块导入的 config
模块.所以,如果你正在测试一个名为 foo
的模块,并且它导入并使用 config
,你可以说:
You can replace the config
module imported by whatever module you're actually trying to test. So, if you're testing a module called foo
, and it imports and uses config
, you can say:
from mock import patch
import foo
import config_test
....
with patch('foo.config', new=config_test):
foo.whatever()
但这实际上并不是全局替换模块,它只是在 foo
模块的命名空间内替换它.所以你需要在它导入的任何地方修补它.如果 foo
这样做而不是 import config
,它也不起作用:
But this isn't actually replacing the module globally, it's only replacing it within the foo
module's namespace. So you would need to patch it everywhere it's imported. It also wouldn't work if foo
does this instead of import config
:
from config import VAR1
你也可以使用 sys.modules
来做到这一点:
You can also mess with sys.modules
to do this:
import config_test
import sys
sys.modules["config"] = config_test
# import modules that uses "import config" here, and they'll actually get config_test
但一般来说,弄乱sys.modules
并不是一个好主意,我认为这种情况没有什么不同.我会赞成所有其他建议.
But generally it's not a good idea to mess with sys.modules
, and I don't think this case is any different. I would favor all of the other suggestions made over it.
这篇关于python:模拟一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!