Replies: 1 comment
|
Hi @takos22 The cleanest approach is to move the optional import behind a function and patch the import operation rather than trying to manipulate Python's real installation state. For example: # app.py
import importlib
def load_optional():
try:
module = importlib.import_module("optional_module")
except ModuleNotFoundError:
return "missing"
return "available"Then both branches are straightforward to test: def test_missing(monkeypatch):
def missing(name):
raise ModuleNotFoundError(name)
monkeypatch.setattr(app.importlib, "import_module", missing)
assert app.load_optional() == "missing"
def test_available(monkeypatch):
fake_module = object()
monkeypatch.setattr(
app.importlib,
"import_module",
lambda name: fake_module,
)
assert app.load_optional() == "available"If the import is executed once at module-import time, testing both branches requires manipulating Please mark this answer as accepted if it helped, thank you. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
I want to have a code coverage of 100% for my module, so I need to test:
How can I test both the
exceptand theelse? I need to make it raise aModuleNotFoundErrorat one point then nothing in another test.All reactions