在Python中测试后备导入

问题描述 投票:3回答:1

使用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提供的功能?

python python-3.x unit-testing
1个回答
0
投票

据我了解,您有以下结构:

- dir sandbox
-- file a.py
-- file b.py
-- file c.py
- file d.py

我尝试将sys.modules['a'] = None替换为sys.modules['sandbox.a'] = None,这很有效。

© www.soinside.com 2019 - 2024. All rights reserved.