問題描述
是否可以使用 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模板網!