How to catch ModuleNotFoundError using Pytest #8269
-
Hi, I met a problem when using Pytest to improve the code coverage of my own project. The problem is that my project will automatically check that whether a third-party package is successfully installed using the code snippet below:
Then, I would like to use So, my question is that how can I do something like temporarily removing some installed packages (here, I would appreciate it very much if someone could help me with this. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
for this I use two tox environments, one with all my setuptools extras installed and one with none of them |
Beta Was this translation helpful? Give feedback.
-
You can monkeypatch the 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) |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot @The-Compiler! It looks nice ;-) |
Beta Was this translation helpful? Give feedback.
You can monkeypatch the
__import__
builtin, though it requires a bit of care. Something like: