使用Python 3.我的应用程序使用的模块应该由pip
安装,但是如果用户没有安装正确的模块,我想提供一个回退模块。
我想在不必切换环境的情况下进行单元测试。因此如下:
档案a.py
"""
This module would, under ideal circumstances, be installed with pip
but maybe not...
"""
class Foo():
@staticmethod
def test():
return "This is the module we'd like to import"
文件b.py
"""
This is my own fallback module
"""
class Foo():
@staticmethod
def test():
return "This is the fallback module"
文件c.py
try:
from sandbox.a import Foo
except ImportError:
from sandbox.b import Foo
"""This is the module in my app that would actually use Foo"""
这是测试,d.py
import sys
def test_it():
sys.modules['a'] = None
import sandbox.c as c
s = c.Foo.test()
assert s == "This is the fallback module"
这与AssertionError失败
E AssertionError: assert 'This is the ...ike to import' == 'This is the fallback module'
E - This is the module we'd like to import
E + This is the fallback module
sandbox/d.py:8: AssertionError
测试这个的正确方法是什么,以便确保用户永远不会得到ImportError(如果他们没有安装模块a.py
)并且他们在这样的事件中有回退模块b.py
提供的功能?
据我了解,您有以下结构:
- dir sandbox
-- file a.py
-- file b.py
-- file c.py
- file d.py
我尝试将sys.modules['a'] = None
替换为sys.modules['sandbox.a'] = None
,这很有效。