蟒蛇:模拟一个模块 [英] python: mock a module

查看:125
本文介绍了蟒蛇:模拟一个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用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:

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.

这篇关于蟒蛇:模拟一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆