模拟导入失败

霸王龙

我该如何import pkg失败moduleA.pypkg如果从中导入某些东西,我可以打补丁失败,但不是这样:

# test.py
import os
import moduleA
from unittest.mock import patch
from importlib import reload

@patch.dict('sys.modules', pkg=os)
def test_mock():
    reload(moduleA)
# moduleA.py
import pkg           # make this fail
from pkg import sum  # this does fail

现场例子

不来梅先生

这有点复杂。您必须确保重新加载失败-这可以通过添加实现的类来完成find_spec其次,您必须从中删除已经加载的软件包sys.modules-否则将在重新加载时使用:

import sys
from importlib import reload

import pytest

import moduleA


class ImportRaiser:
    def find_spec(self, fullname, path, target=None):
        if fullname == 'pkg':
           # we get here if the module is not loaded and not in sys.modules
            raise ImportError()


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


def test_import_error():
    if 'pkg' in sys.modules:
        del sys.modules['pkg']

    with pytest.raises(ImportError):
        reload(moduleA)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章