gpt4 book ai didi

python - 在 Python 中测试回退导入

转载 作者:行者123 更新时间:2023-11-28 18:59:08 24 4
gpt4 key购买 nike

使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com