在Python中使用可选导入进行测试

2024-10-03 11:21:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个可以使用两个模块的库;一个速度很快,但仅在Linux和macOS上可用,另一个速度较慢,但它是多平台的。我的解决方案是使库与两者兼容,并具有如下内容:

try:
    import fastmodule
except ImportError:
    import slowmodule

现在,我想比较使用两个模块时库的计时。在安装了两个模块的环境中,是否有任何方法可以在不更改源代码的情况下屏蔽fastmodule(即在Jupyter笔记本中),从而使用slowmodule


Tags: 模块import内容linuxmacos平台解决方案速度
1条回答
网友
1楼 · 发布于 2024-10-03 11:21:26

这有点像黑客,但它是这样的:
您可以编写自己的导入程序并注册它(注意,这是特定于Python 3的,Python 2为此提供了另一个API):

import sut
import functools
import importlib
import sys


def use_slow(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        ImportRaiser.use_slow = True
        if 'fastmodule' in sys.modules:
            del sys.modules['fastmodule']  # otherwise it will remain cached
        importlib.reload(sut)
        f(*args, **kwargs)

    return wrapped


def use_fast(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        ImportRaiser.use_slow = False
        importlib.reload(sut)
        f(*args, **kwargs)

    return wrapped


class ImportRaiser:
    use_slow = False

    def find_spec(self, fullname, path, target=None):
        if fullname == 'fastmodule':
            if self.use_slow:
                raise ImportError()


sys.meta_path.insert(0, ImportRaiser())

@use_fast
def test_fast():
    # test code


@use_slow
def test_slow():
    # test code

这里,sut是您正在测试的模块,您必须重新加载它才能更改行为。我为可读性添加了decorators,但这可以通过一些函数或在测试设置中完成

如果使用慢速版本,fastmodule将在导入时引发ImportError,而使用slowmodule。在“快速”的情况下,一切正常

相关问题 更多 >