在Python for pytest中模拟导入模块中的全局变量
我想了解一些关于在导入模块之前模拟导入模块中的变量的建议,以便使用pytest进行测试。使用Python2.7 这些是我的文件: scriptconfig.py在Python for pytest中模拟导入模块中的全局变量,python,unit-testing,import,mocking,Python,Unit Testing,Import,Mocking,我想了解一些关于在导入模块之前模拟导入模块中的变量的建议,以便使用pytest进行测试。使用Python2.7 这些是我的文件: scriptconfig.py foo = path/to/bar foo_two = bar_two import scriptconfig foo = path/to/test_bar import scriptconfig import script class TestScript(unittest.case)... script.py foo
foo = path/to/bar
foo_two = bar_two
import scriptconfig
foo = path/to/test_bar
import scriptconfig
import script
class TestScript(unittest.case)...
script.py
foo = path/to/bar
foo_two = bar_two
import scriptconfig
foo = path/to/test_bar
import scriptconfig
import script
class TestScript(unittest.case)...
testconfig.py
foo = path/to/bar
foo_two = bar_two
import scriptconfig
foo = path/to/test_bar
import scriptconfig
import script
class TestScript(unittest.case)...
测试脚本.py
foo = path/to/bar
foo_two = bar_two
import scriptconfig
foo = path/to/test_bar
import scriptconfig
import script
class TestScript(unittest.case)...
在我的测试场景中,path/to/bar中的文件将不存在,因此我想用模拟变量代替testconfig。当前,每当我在测试环境中运行pytest_script.py时,都会出现一个错误,因为找不到bar
我还想从scriptconfig.py导入其他变量,比如foo_two,这些变量不会被模拟
我尝试过诸如sys.modules之类的选项
import sys
sys.modules['scriptconfig.foo'] = testconfig.foo
import scriptconfig
并尝试了上述方法
del sys.modules['scriptconfig.foo']
后来
还有像这样的补丁
from mock import patch
@patch('scriptconfig.foo', testconfig.foo)
import scriptconfig
但是这些都是通过导入scriptconfig或脚本覆盖的。我知道我很可能没有正确执行它们。还有其他的解决方案我可以尝试吗
编辑:我的解决方案是在调用导入时使用mock模拟导入,如下所示。这在testconfig中
import os
import sys
from mock import mock, patch
import testconfig as config
with mock.patch.ditch('sys.modules', scriptconfig = config):
import script
这会告诉sys.modules在调用导入时使用testconfig而不是scriptconfig,这可能会对您有所帮助。