python - 在 Python 中测试回退导入

标签 python python-3.x unit-testing

使用 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 并且这有效。

关于python - 在 Python 中测试回退导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54726099/

相关文章:

python-3.x - 通过递归方式反向双向链表不在python中迭代

unit-testing - 当点击的小部件启动计时器时,如何运行单元测试?

python - 为什么同一个模块导入的方式不同不一样?

python-3.x - 在 Ubuntu 上使用 pip 时出现无效的 IPv6 URL 错误

list - 将数字输入到空列表 Python

unit-testing - 我如何告诉 Makemaker 并行运行测试?

unit-testing - 在单元测试中,您是否验证和断言?

python - 如何直接设置matplotlib图形背景颜色的alpha channel 值

python - 应用程序(或模型)未显示在 Django Admin 中

python - 如何将 sqlalchemy 查询作为字典返回?