Skip to content

How to catch ModuleNotFoundError using Pytest #8269

Answered by The-Compiler
xuyxu asked this question in Q&A
Discussion options

You must be logged in to vote

You can monkeypatch the __import__ builtin, though it requires a bit of care. Something like:

import builtins

import pytest

@pytest.fixture
def patch_import(monkeypatch):
    real_import = __import__

    def fake_import(name, *args, **kwargs):
        if name != 'some_package':
            return real_import(name, *args, **kwargs)
        raise ImportError

    monkeypatch.setattr(builtins, '__import__', fake_import)

Replies: 3 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@xuyxu
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by xuyxu
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants