Repository navigation
Replies: 1 comment
|
Hi @anatoli26 The difficulty here is that you're trying to simulate a first import inside a pytest process where that dependency may already have been imported. Python caches imported modules in: sys.modulesand pytest also loads plugins and other test modules during startup/collection. If something else has already imported try:
import typer
except ImportError:
...The most reliable test for import-time behavior is therefore an isolated Python subprocess. For example: import subprocess
import sys
def test_missing_typer():
result = subprocess.run(
[
sys.executable,
"-c",
"""
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "typer":
raise ImportError("simulated missing dependency")
return real_import(name, *args, **kwargs)
builtins.__import__ = fake_import
import your_package
""",
],
capture_output=True,
text=True,
)
assert result.returncode == 1
assert "typer not installed" in result.stderrThat gives you a fresh interpreter whose import state isn't affected by pytest or its plugins. You can attempt this in-process by removing your own module from import importlib
import sys
def test_missing_typer(monkeypatch):
sys.modules.pop("your_package", None)
real_import = __import__
def fake_import(name, *args, **kwargs):
if name == "typer":
raise ImportError("simulated")
return real_import(name, *args, **kwargs)
monkeypatch.setattr("builtins.__import__", fake_import)
importlib.import_module("your_package")but I would avoid deleting If you control the application code, an even cleaner design is to move the dependency check out of module-import side effects and into a callable. That lets you unit-test the behavior without manipulating Python's import system. For this particular case, though, a subprocess is the closest test of what actually happens when a user starts your package without Please mark this answer as accepted if it helped, thank you. |
Uh oh!
There was an error while loading. Please reload this page.
In my package I'm checking for an extra dependency with a code like this:
Can't find a way to test this. Patching
"builtins.__import__"with a temporarymock_importworks only if no previousimport typercalls were made.So if invoking
pytest test_dynamic_import.py, it's working, but barepytestanalyzes and performs imports in other testfiles that import the main package where the dynamic import code is executed, so typer is already imported when the test function with the patch code in thetest_dynamic_import.pyfile is invoked.I believe there should be a more straightforward method to test for dynamic imports. Please, advise.
All reactions