π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core)!: a missing optional dependency raises by default; "auto" installs the declared kornia extra (#5240)
Dmytro Mishkine61b052b2630
diff --git a/changelog.d/5240.breaking.md b/changelog.d/5240.breaking.mdnew file mode 100644index 000000000..c90de6239--- /dev/null+++ b/changelog.d/5240.breaking.md@@ -0,0 +1,17 @@+A missing optional dependency now raises by default. `kornia_config.lazyloader.installation_mode` used to default to+`"ask"`, which asked on stdin whether to install the package: without an interactive stdin (a CI job, a DataLoader+worker) that raised `EOFError` instead of `ImportError`, and on an open stdin that nobody writes to it blocked. The+default is now `"raise"`: an `ImportError` naming `pip install "kornia[<extra>]"`. `"ask"` is opt-in and raises the same+`ImportError` without an interactive terminal on stdin and stdout (for example in a Jupyter notebook, whose kernel's+stdin is not a terminal, or with output redirected to a file); its "[A]ll" answer, which used to apply to one loader,+now switches the process to `"auto"`. `"auto"` used to install the loader's import name with `-U`, even where it is not+a package name, and did not check pip's exit status; it now installs the declared kornia extra instead of the import+name (`pip install "kornia[<extra>]"`, for example `kornia[image]`, without `-U`), raises `ImportError` if pip fails+(without running pip again for that loader), and installs nothing for a loader that declares no extra (`"ask"` does not+ask for one either). The new `KORNIA_INSTALLATION_MODE` environment variable sets the mode when kornia is imported+(`raise`, `ask` or `auto`, any case); another value does not stop `import kornia`, but raises a `ValueError` naming the+variable, the valid modes and the missing package the first time a missing optional package is handled. The undocumented+`LazyLoader.auto_install` class switch is removed; set the mode to `"auto"` instead. `InstallationMode` members are now+hashable and compare equal only to their upper-case values (`InstallationMode.ASK == "ASK"`): `==` used to ignore case+while `!=` did not, so `InstallationMode.ASK == "ask"` and `InstallationMode.ASK != "ask"` were both true. The+`installation_mode` setter still accepts any case.diff --git a/changelog.d/5240.fixed.md b/changelog.d/5240.fixed.mdnew file mode 100644index 000000000..877312f50--- /dev/null+++ b/changelog.d/5240.fixed.md@@ -0,0 +1,8 @@+`kornia.core.external.LazyLoader` can be copied, deep-copied and pickled (these recursed or failed on the module+object), and dunder lookups such as `__wrapped__` no longer import, install or ask for a module that is not loaded yet+(the module metadata `__version__`, `__file__`, `__path__` and `__all__` still loads it). An installed optional module+now loads when `--doctest-modules` is in `sys.argv`: the `onnxruntime` and `diffusers` loaders used to stay empty in any+such process, for example a user's own `pytest --doctest-modules` run, and raised `AttributeError: 'NoneType' object has+no attribute ...`. `ImageModule` and the augmentation containers no longer import PIL through the lazy loader to check+an argument that is not an image (a keyword such as `scale=0.5` or `data_keys=[...]`), so those calls work on an install+without the `image` extra.diff --git a/docs/source/conf.py b/docs/source/conf.pyindex 0c929af0c..7f01442d1 100644--- a/docs/source/conf.py+++ b/docs/source/conf.py@@ -149,7 +149,8 @@ def _public_operator_count() -> int:continuefor name, obj in vars(module).items():# Type checks first: attribute access on a ``kornia.core.external.LazyLoader`` would- # try to import (and offer to install) the optional dependency behind it.+ # try to import the optional dependency behind it (raising, or installing it in the "ask" and "auto"+ # installation modes).if not (inspect.isfunction(obj) or (inspect.isclass(obj) and issubclass(obj, torch.nn.Module))):continueif name.startswith("_") or obj.__name__ != name:diff --git a/docs/source/get-started/installation.rst b/docs/source/get-started/installation.rstindex 9844df309..a30d20600 100644--- a/docs/source/get-started/installation.rst+++ b/docs/source/get-started/installation.rst@@ -53,10 +53,13 @@ Optional extrasA few Kornia features wrap third-party packages that are not installed with the base wheel. They aredeclared as `extras <https://packaging.python.org/en/latest/specifications/dependency-specifiers/#extras>`_,so you only pay for the ones you use. If one of the extras below is missing, the corresponding Kornia-object tells you which extra to install: by default it offers to install the package for you on the-terminal (``kornia.config.kornia_config.lazyloader.installation_mode``, ``"ask"``; set it to ``"auto"``-to install without asking or ``"raise"`` to never install), and in ``"raise"`` mode, or when the offer-is declined, it raises an ``ImportError`` naming the extra.+object raises an ``ImportError`` naming the extra to install. The installation mode changes this: set+``kornia.config.kornia_config.lazyloader.installation_mode``, or the ``KORNIA_INSTALLATION_MODE``+environment variable before Kornia is imported, to ``"ask"`` to be asked on an interactive terminal+whether to install the extra, or to ``"auto"`` to install the declared extra with+``pip install "kornia[<extra>]"`` without asking. Without an interactive terminal, ``"ask"`` raises the+same ``ImportError``: for example in a CI job, when output is redirected to a file, or in a Jupyter+notebook, whose kernel's stdin is not a terminal (use ``"auto"`` there). The default is ``"raise"``... list-table:::header-rows: 1diff --git a/kornia/config.py b/kornia/config.pyindex 32bd470c8..265732e1c 100644--- a/kornia/config.py+++ b/kornia/config.py@@ -18,49 +18,100 @@import osfrom dataclasses import dataclass, fieldfrom enum import StrEnum+from typing import Optional__all__ = ["InstallationMode", "kornia_config"]-class InstallationMode(StrEnum):- """Represent the installation mode for external dependencies."""+_INSTALLATION_MODE_ENV_VAR = "KORNIA_INSTALLATION_MODE"+- # Ask the user if to install the dependencies+class InstallationMode(StrEnum):+ """How :class:`kornia.core.external.LazyLoader` handles a missing optional dependency.++ Set the mode with ``kornia_config.lazyloader.installation_mode = "<mode>"`` or, before kornia is imported, with+ the ``KORNIA_INSTALLATION_MODE`` environment variable. Both accept ``"raise"``, ``"ask"`` and ``"auto"`` in any+ case; an invalid environment value raises a ``ValueError`` when a lazy loader first handles a missing module.+ Members compare equal to their upper-case values (``InstallationMode.RAISE == "RAISE"``).++ - ``RAISE`` (the default): raise an ``ImportError`` that names the kornia extra to install, for example+ ``pip install "kornia[onnx]"``.+ - ``ASK``: on an interactive terminal (stdin and stdout), ask whether to install that extra. Without one, behave+ as ``RAISE``: in a CI job, a DataLoader worker, a script whose output is redirected, or a Jupyter notebook+ (the kernel's stdin is not a terminal), for example. Use ``AUTO`` there to install without asking.+ - ``AUTO``: install the declared kornia extra instead of the import name, with the running interpreter's+ ``pip install "kornia[<extra>]"`` (for example ``kornia[image]``), and raise an ``ImportError`` if pip fails.++ A dependency that declares no kornia extra is never installed: ``ASK`` and ``AUTO`` raise the same+ ``ImportError`` as ``RAISE`` for it.+ """++ # Ask on an interactive terminal whether to install the extra; raise otherwiseASK = "ASK"- # Install the dependencies+ # Install the declared kornia extra without askingAUTO = "AUTO"- # Raise an error if the dependencies are not installed+ # Raise an ImportError naming the kornia extra to installRAISE = "RAISE"- def __eq__(self, other: object) -> bool:- if isinstance(other, str):- return self.value.lower() == other.lower() # Case-insensitive comparison- return super().__eq__(other)+def _parse_installation_mode(value: object, source: str) -> InstallationMode:+ """Return the :class:`InstallationMode` a case-insensitive string names.-class LazyLoaderConfig:- """Configure lazy loading behavior for external dependencies."""+ Args:+ value: the value to parse, for example ``"raise"`` or ``InstallationMode.AUTO``.+ source: the name the value was given under, used in the error message.++ Raises:+ TypeError: if ``value`` is not a string.+ ValueError: if ``value`` names no mode.++ """+ if not isinstance(value, str):+ raise TypeError("installation_mode must be a string or InstallationMode Enum.")+ try:+ return InstallationMode(value.upper())+ except ValueError:+ choices = ", ".join(repr(mode.value.lower()) for mode in InstallationMode)+ raise ValueError(+ f"{source}={value!r} is not a valid installation mode. Choose from: {choices} (any case)."+ ) from None- _installation_mode: InstallationMode = InstallationMode.ASK++class LazyLoaderConfig:+ """Configure lazy loading behavior for external dependencies.++ The initial ``installation_mode`` is read from the ``KORNIA_INSTALLATION_MODE`` environment variable when it is+ set and not empty, and is :attr:`InstallationMode.RAISE` otherwise. An invalid value does not stop kornia from+ importing: reading ``installation_mode`` raises a ``ValueError`` that names the variable, the value and the valid+ modes, which happens the first time a lazy loader handles a missing module, until a valid mode is set in code.+ """++ def __init__(self) -> None:+ self._installation_mode = InstallationMode.RAISE+ self._invalid_env_value: Optional[str] = None+ env_value = os.environ.get(_INSTALLATION_MODE_ENV_VAR, "").strip()+ if env_value:+ try:+ self._installation_mode = _parse_installation_mode(env_value, _INSTALLATION_MODE_ENV_VAR)+ except ValueError as e:+ self._invalid_env_value = str(e)@propertydef installation_mode(self) -> InstallationMode:+ """How a missing optional dependency is handled; see :class:`InstallationMode`.++ Raises:+ ValueError: if ``KORNIA_INSTALLATION_MODE`` held an invalid value and no mode was set since.++ """+ if self._invalid_env_value is not None:+ raise ValueError(self._invalid_env_value)return self._installation_mode@installation_mode.setterdef installation_mode(self, value: str) -> None:- # Allow setting via string by converting to the Enum- if isinstance(value, str):- try:- self._installation_mode = InstallationMode(value.upper())- except ValueError:- raise ValueError(- f"{value} is not a valid InstallationMode. Choose from: {list(InstallationMode)}"- ) from None- elif isinstance(value, InstallationMode):- self._installation_mode = value- else:- raise TypeError("installation_mode must be a string or InstallationMode Enum.")+ self._installation_mode = _parse_installation_mode(value, "installation_mode")+ self._invalid_env_value = None@dataclassdiff --git a/kornia/core/external.py b/kornia/core/external.pyindex 6e7793f8d..67d2dd825 100644--- a/kornia/core/external.py+++ b/kornia/core/external.py@@ -15,17 +15,36 @@# limitations under the License.#+import builtinsimport importlibimport loggingimport subprocessimport sysfrom types import ModuleType-from typing import List, Optional+from typing import Any, Dict, List, Optionalfrom kornia.config import InstallationMode, kornia_configlogger = logging.getLogger(__name__)+# The loader's own instance attributes. ``__getattr__`` sees them only on a copy or an unpickled loader whose state is+# not restored yet; answering them from the module would recurse.+_LOADER_ATTRIBUTES = frozenset({"module_name", "module", "dev_dependency", "extra", "_install_error"})+# Module metadata that callers read from a loader as from the module itself: these dunder names load the module.+_MODULE_METADATA = frozenset({"__version__", "__file__", "__path__", "__all__"})+++def _interactive_terminal() -> bool:+ """Return whether ``input()`` can reach a person: stdin and stdout both exist, are open and are terminals.++ ``input()`` writes its question to stdout and reads the answer from stdin, so a redirected stdout+ (``python train.py > log``) would hide the question while stdin waits for an answer.+ """+ try:+ return bool(sys.stdin is not None and sys.stdout is not None and sys.stdin.isatty() and sys.stdout.isatty())+ except (AttributeError, OSError, ValueError): # replaced by an object without isatty, or closed+ return False+class LazyLoader:"""A class that implements lazy loading for Python modules.@@ -34,6 +53,10 @@ class LazyLoader:It helps in reducing the initial load time and memory usage of a script, especially whendealing with large or optional dependencies that might not be used in every execution.+ What happens when the module is missing is set by ``kornia.config.kornia_config.lazyloader.installation_mode``+ (or the ``KORNIA_INSTALLATION_MODE`` environment variable); see :class:`kornia.config.InstallationMode`. By+ default an ``ImportError`` names the kornia extra to install.+Attributes:module_name: The name of the module to be lazily loaded.module: The actual module object, initialized to None and loaded upon first access.@@ -41,24 +64,25 @@ class LazyLoader:"""- auto_install: bool = False-def __init__(self, module_name: str, dev_dependency: bool = False, extra: Optional[str] = None) -> None:"""Initialize the LazyLoader with the name of the module.Args:module_name: The name of the module to be lazily loaded.- dev_dependency: If the dependency is required in the dev environment.- If True, the module will be loaded in the dev environment.- If False, the module will not be loaded in the dev environment.+ dev_dependency: Whether kornia's documentation build needs the module. If False, the Sphinx build of+ kornia's documentation (``docs/source/conf.py`` sets a ``__sphinx_build__`` builtin) does not import+ it: the loader stays empty there and attribute access raises ``AttributeError``. It has no effect+ elsewhere.extra: The name of the kornia optional-dependency extra that installs the module, e.g. ``"onnx"``.- When set, the "not installed" messages tell the user to run ``pip install "kornia[<extra>]"``.+ When set, the "not installed" messages tell the user to run ``pip install "kornia[<extra>]"``, and+ the ``"ask"`` and ``"auto"`` installation modes install that extra. Without it, nothing is installed."""self.module_name = module_nameself.module: Optional[ModuleType] = Noneself.dev_dependency = dev_dependencyself.extra = extra+ self._install_error: Optional[str] = None@propertydef _install_hint(self) -> str:@@ -67,63 +91,107 @@ class LazyLoader:return f'Install it with: pip install "kornia[{self.extra}]".'return "Please install it to use this functionality."- def _install_package(self, module_name: str) -> None:- logger.info(f"Installing `{module_name}` ...")- subprocess.run([sys.executable, "-m", "pip", "install", "-U", module_name], shell=False, check=False) # noqa: S603+ def _should_install(self) -> bool:+ """Decide, from the installation mode, whether to install the declared extra of a missing module."""+ # Read the mode first, so that an invalid KORNIA_INSTALLATION_MODE is reported for every missing module.+ mode = kornia_config.lazyloader.installation_mode+ if self.extra is None:+ return False+ if mode == InstallationMode.AUTO:+ return True+ if mode == InstallationMode.ASK:+ return self._ask_to_install()+ return False++ def _ask_to_install(self) -> bool:+ """Ask on the terminal whether to install the declared extra; ``False`` without an interactive terminal."""+ if not _interactive_terminal():+ return False+ question = (+ f"Optional dependency '{self.module_name}' is not installed. "+ f'Install it now with `pip install "kornia[{self.extra}]"`? '+ "[Y]es, [N]o, [A]ll (install every missing kornia extra without asking for the rest of this session). "+ "Set `kornia_config.lazyloader.installation_mode` or the KORNIA_INSTALLATION_MODE environment variable "+ "to 'raise' to never be asked, or to 'auto' to always install. "+ )+ try:+ answer = input(question)+ while True:+ choice = answer.strip().lower()+ if choice in ("y", "yes"):+ return True+ if choice in ("n", "no"):+ return False+ if choice in ("a", "all"):+ kornia_config.lazyloader.installation_mode = InstallationMode.AUTO+ return True+ answer = input("Please answer 'y', 'n' or 'a'. ")+ except EOFError:+ return False++ def _install_extra(self) -> None:+ """Install the declared extra with this interpreter's pip and import the module.++ Raises:+ ImportError: if pip fails or the module still cannot be imported. The failure is remembered, so later+ accesses raise it again without running pip again.++ """+ requirement = f"kornia[{self.extra}]"+ command = [sys.executable, "-m", "pip", "install", requirement]+ logger.info("Installing %s for the optional dependency '%s' ...", requirement, self.module_name)+ try:+ subprocess.run(command, check=True) # noqa: S603+ except (OSError, subprocess.CalledProcessError) as e:+ self._install_error = (+ f"Optional dependency '{self.module_name}' is not installed, and "+ f'`pip install "{requirement}"` failed: {e}'+ )+ raise ImportError(self._install_error) from e+ importlib.invalidate_caches()+ try:+ self.module = importlib.import_module(self.module_name)+ except ImportError as e:+ self._install_error = (+ f"Optional dependency '{self.module_name}' cannot be imported after `pip install \"{requirement}\"`."+ )+ raise ImportError(self._install_error) from edef _load(self) -> None:- """Load the module if it hasn't been loaded yet.+ """Import the module on first use.++ A missing module is handled according to ``kornia_config.lazyloader.installation_mode`` (see+ :class:`kornia.config.InstallationMode`): by default it raises an ImportError whose message names the kornia+ extra to install.++ Raises:+ ImportError: if the module is missing and is not installed.+ ValueError: if the module is missing and ``KORNIA_INSTALLATION_MODE`` holds an invalid value.- This method is called internally when an attribute of the module is accessed for the first time. It attempts to- import the module and raises an ImportError with a custom message if the module is not installed."""- if not self.dev_dependency:- if "--doctest-modules" in sys.argv:- logger.info(f"Doctest detected, skipping loading of '{self.module_name}'")- return- try:- if __sphinx_build__: # type:ignore- logger.info(f"Sphinx detected, skipping loading of '{self.module_name}'")- return- except NameError:- pass-- if self.module is None:- try:- self.module = importlib.import_module(self.module_name)- except ImportError as e:- if kornia_config.lazyloader.installation_mode == InstallationMode.AUTO or self.auto_install:- self._install_package(self.module_name)- elif kornia_config.lazyloader.installation_mode == InstallationMode.ASK:- to_ask = True- if_install = input(- f"Optional dependency '{self.module_name}' is not installed. "- f"{self._install_hint} "- "You may silence this prompt by `kornia_config.lazyloader.installation_mode = 'auto'`. "- "Do you wish to install the dependency? [Y]es, [N]o, [A]ll."- )- while to_ask:- if if_install.lower() == "y" or if_install.lower() == "yes":- self._install_package(self.module_name)- self.module = importlib.import_module(self.module_name)- to_ask = False- elif if_install.lower() == "a" or if_install.lower() == "all":- self.auto_install = True- self._install_package(self.module_name)- self.module = importlib.import_module(self.module_name)- to_ask = False- elif if_install.lower() == "n" or if_install.lower() == "no":- raise ImportError(- f"Optional dependency '{self.module_name}' is not installed. {self._install_hint}"- ) from e- else:- if_install = input("Invalid input. Please enter 'Y', 'N', or 'A'.")-- elif kornia_config.lazyloader.installation_mode == InstallationMode.RAISE:- raise ImportError(- f"Optional dependency '{self.module_name}' is not installed. {self._install_hint}"- ) from e- self.module = importlib.import_module(self.module_name)+ if self.module is not None:+ return+ if not self.dev_dependency and getattr(builtins, "__sphinx_build__", False):+ logger.info(f"Sphinx detected, skipping loading of '{self.module_name}'")+ return+ try:+ self.module = importlib.import_module(self.module_name)+ return+ except ImportError as e:+ import_error = e+ if self._install_error is not None:+ raise ImportError(self._install_error) from import_error+ try:+ install = self._should_install()+ except ValueError as e: # an invalid KORNIA_INSTALLATION_MODE: name what needed the mode+ raise ValueError(+ f"{e} It was needed for the missing optional dependency '{self.module_name}'."+ ) from import_error+ if not install:+ raise ImportError(+ f"Optional dependency '{self.module_name}' is not installed. {self._install_hint}"+ ) from import_error+ self._install_extra()def __getattr__(self, item: str) -> object:"""Load the module (if not already loaded) and returns the requested attribute.@@ -131,6 +199,11 @@ class LazyLoader:This method is called when an attribute of the LazyLoader instance is accessed.It ensures that the module is loaded and then returns the requested attribute.+ Protocol lookups (dunder names such as ``__wrapped__`` or ``__deepcopy__``, which ``copy``, ``pickle``,+ ``inspect.unwrap`` and doctest collection make) never import, install or ask: before the module is loaded+ they raise ``AttributeError``. The module metadata ``__version__``, ``__file__``, ``__path__`` and ``__all__``+ loads the module like any other attribute.+Args:item: The name of the attribute to be accessed.@@ -138,9 +211,22 @@ class LazyLoader:The requested attribute of the loaded module."""+ if item in _LOADER_ATTRIBUTES:+ raise AttributeError(f"{type(self).__name__!r} object has no attribute {item!r}")+ if item.startswith("__") and item.endswith("__") and item not in _MODULE_METADATA:+ module = self.__dict__.get("module")+ if module is None:+ raise AttributeError(f"{type(self).__name__!r} object has no attribute {item!r}")+ return getattr(module, item)self._load()return getattr(self.module, item)+ def __getstate__(self) -> Dict[str, Any]:+ """Return the loader's state for copy and pickle, without the module object (the copy imports it again)."""+ state = self.__dict__.copy()+ state["module"] = None+ return state+def __dir__(self) -> List[str]:"""Load the module (if not already loaded) and returns the list of attributes of the module.@@ -155,10 +241,9 @@ class LazyLoader:return dir(self.module)-# NOTE: This section is used for lazy loading of external modules. However, sphinx-# would also try to support lazy loading of external modules. To avoid that, we-# may set the module name to `autodoc_mock_imports` in conf.py to avoid undesired-# installation of external modules.+# NOTE: kornia's Sphinx build (docs/source/conf.py sets a ``__sphinx_build__`` builtin) leaves the loaders created+# with ``dev_dependency=False`` empty instead of importing their modules, so the documentation environment does+# not need those packages.numpy = LazyLoader("numpy", dev_dependency=True)PILImage = LazyLoader("PIL.Image", dev_dependency=True, extra="image")onnx = LazyLoader("onnx", dev_dependency=True, extra="onnx")diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.pyindex 01f2ec797..12665df69 100644--- a/kornia/core/mixin/image_module.py+++ b/kornia/core/mixin/image_module.py@@ -18,6 +18,7 @@import datetimeimport mathimport os+import sysfrom functools import wrapsfrom typing import Any, Callable, List, Literal, Optional, Tuple, Union@@ -128,10 +129,12 @@ class ImageModuleMixIn:return Trueif isinstance(arg, torch.Tensor):return True- # Make sure that the numpy and PIL are not necessarily needed to be imported.if isinstance(arg, np.ndarray): # type: ignorereturn True- if isinstance(arg, (Image.Image)): # type: ignore+ # A PIL image exists only once PIL is imported: look the module up instead of importing it through the lazy+ # loader, which would raise on an install without the "image" extra for every non-image argument.+ pil_image = sys.modules.get("PIL.Image")+ if pil_image is not None and isinstance(arg, pil_image.Image):return Truereturn Falsediff --git a/pyproject.toml b/pyproject.tomlindex 8673e9380..a993a3178 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -50,7 +50,7 @@ docs = ["pydata-sphinx-theme>=0.21,<0.22", # _static/css/pydata.css and js/custom.js target theme internals"matplotlib",# kornia.core.mixin.onnx annotates public members with ``onnx.ModelProto``; without onnx the- # lazy loader prompts on stdin while autodoc resolves them and the build dies. onnxruntime is+ # lazy loader raises ImportError while autodoc resolves them and the build dies. onnxruntime is# not needed: no documented member resolves an ``onnxruntime`` annotation."onnx","pillow", # docs/generate_examples.py decodes and writes the generated figures with PILdiff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex f76e65eb6..333782e3b 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -6329,7 +6329,7 @@ class TestRandomDissolving(BaseTester):@pytest.fixture(autouse=True)def _needs_diffusers(self):- # `diffusers` left the `dev` extra; skip rather than hit the LazyLoader prompt under --runslow.+ # `diffusers` left the `dev` extra; skip rather than hit the LazyLoader's ImportError under --runslow.pytest.importorskip("diffusers", reason='`diffusers` is not installed: pip install "kornia[sd]"')def test_batch_proc(self, device, dtype):diff --git a/tests/core/test_external.py b/tests/core/test_external.pyindex 6995fce59..b48ff463b 100644--- a/tests/core/test_external.py+++ b/tests/core/test_external.py@@ -15,38 +15,153 @@# limitations under the License.#+import builtins+import io+import os+import subprocess+import sys+import tempfile+import textwrap+import types+from pathlib import Path+from unittest import mock+import pytest-from kornia.config import InstallationMode, kornia_config+from kornia.config import InstallationMode, LazyLoaderConfig, kornia_config+from kornia.core import externalfrom kornia.core.external import LazyLoader+REPO_ROOT = Path(__file__).resolve().parents[2]+ENV_VAR = "KORNIA_INSTALLATION_MODE"+# A module name that no environment provides, so "missing" never depends on what is installed.+MISSING = "kornia_test_no_such_module_xyz"+++class InstallRefused(Exception):+ """Raised by the process-start stubs: no test may run pip or any other command."""+++def restore_mode():+ """Put the process-wide installation mode back after a test changes it."""+ previous = kornia_config.lazyloader.installation_mode+ yield+ kornia_config.lazyloader.installation_mode = previous+++def commands(monkeypatch):+ """Record every attempt to start a process and refuse it, so no test can install anything."""+ recorded = []++ def refuse(name):+ def start(*args, **kwargs):+ recorded.append(args[0] if args else kwargs.get("args"))+ raise InstallRefused(name)++ return start++ for name in ("run", "call", "check_call", "check_output", "Popen"):+ monkeypatch.setattr(subprocess, name, refuse(f"subprocess.{name}"))+ monkeypatch.setattr(os, "system", refuse("os.system"))+ return recorded+++def no_prompt(monkeypatch):+ """Fail the test if the loader asks anything."""++ def forbidden_input(prompt=""):+ raise AssertionError(f"the loader prompted: {prompt!r}")++ monkeypatch.setattr(builtins, "input", forbidden_input)+++def blocked(monkeypatch):+ """Make the loaders see the module names added to the returned set as not installed."""+ names = set()+ real_import = external.importlib.import_module++ def import_module(name, package=None):+ if name in names:+ raise ModuleNotFoundError(f"No module named {name!r}", name=name)+ return real_import(name, package)++ fake = types.SimpleNamespace(import_module=import_module, invalidate_caches=lambda: None)+ monkeypatch.setattr(external, "importlib", fake)+ return names+++def pip_install(extra):+ return [sys.executable, "-m", "pip", "install", f"kornia[{extra}]"]+++def not_installed(module_name, extra=None):+ hint = (+ f'Install it with: pip install "kornia[{extra}]".' if extra else "Please install it to use this functionality."+ )+ return f"Optional dependency '{module_name}' is not installed. {hint}"+++class FakeTerminal:+ """A stream that reports an interactive terminal; the answers come from a patched ``input``."""++ def isatty(self):+ return True++ def write(self, text):+ return len(text)++ def flush(self):+ pass+++def closed_stream():+ stream = io.StringIO("y\n")+ stream.close()+ return stream+++def pretend_terminal(monkeypatch):+ """Answer the loader's questions on a pretend terminal; returns (answers to give, prompts seen).++ Called from the test body: pytest's output capture puts its own ``sys.stdout`` back between fixture setup and+ the test call.+ """+ to_give, prompts = [], []++ def scripted_input(prompt=""):+ prompts.append(prompt)+ if not to_give:+ raise EOFError+ return to_give.pop(0)++ monkeypatch.setattr(sys, "stdin", FakeTerminal())+ monkeypatch.setattr(sys, "stdout", FakeTerminal())+ monkeypatch.setattr(builtins, "input", scripted_input)+ return to_give, prompts+class TestLazyLoaderExtra:"""Check that a missing optional dependency points at the extra that installs it."""- def test_missing_dependency_names_the_extra(self):- previous_mode = kornia_config.lazyloader.installation_mode+ def test_missing_dependency_names_the_extra(self, restore_mode):kornia_config.lazyloader.installation_mode = InstallationMode.RAISE- try:- loader = LazyLoader("definitely_not_a_module_xyz", extra="sd")- with pytest.raises(ImportError) as excinfo:- loader.__getattr__("x")- finally:- kornia_config.lazyloader.installation_mode = previous_mode+ loader = LazyLoader("definitely_not_a_module_xyz", extra="sd")+ with pytest.raises(ImportError) as excinfo:+ loader.__getattr__("x")message = str(excinfo.value)assert "Optional dependency 'definitely_not_a_module_xyz' is not installed" in messageassert 'pip install "kornia[sd]"' in message- def test_missing_dependency_without_extra_keeps_generic_message(self):- previous_mode = kornia_config.lazyloader.installation_mode+ def test_missing_dependency_without_extra_keeps_generic_message(self, restore_mode):kornia_config.lazyloader.installation_mode = InstallationMode.RAISE- try:- loader = LazyLoader("definitely_not_a_module_xyz")- with pytest.raises(ImportError) as excinfo:- loader.__getattr__("x")- finally:- kornia_config.lazyloader.installation_mode = previous_mode+ loader = LazyLoader("definitely_not_a_module_xyz")+ with pytest.raises(ImportError) as excinfo:+ loader.__getattr__("x")message = str(excinfo.value)assert "Please install it to use this functionality." in message@@ -62,6 +177,408 @@ class TestLazyLoaderExtra:],)def test_declared_loaders_carry_their_extra(self, name, extra):- from kornia.core import external-assert getattr(external, name).extra == extra+++class TestInstallationModeConfig:+ """The default mode, the KORNIA_INSTALLATION_MODE environment variable and the setter."""++ def test_default_mode_is_raise(self, monkeypatch):+ monkeypatch.delenv(ENV_VAR, raising=False)+ assert LazyLoaderConfig().installation_mode is InstallationMode.RAISE++ def test_default_mode_raises_import_error_without_prompting(self, monkeypatch, commands, no_prompt):+ monkeypatch.delenv(ENV_VAR, raising=False)+ monkeypatch.setattr(kornia_config, "lazyloader", LazyLoaderConfig())+ monkeypatch.setattr(sys, "stdin", FakeTerminal())+ with pytest.raises(ImportError) as excinfo:+ _ = LazyLoader(MISSING, extra="image").attr+ assert str(excinfo.value) == not_installed(MISSING, "image")+ assert isinstance(excinfo.value.__cause__, ModuleNotFoundError)+ assert commands == []++ @pytest.mark.parametrize(+ ("value", "expected"),+ [+ ("raise", InstallationMode.RAISE),+ ("ask", InstallationMode.ASK),+ ("auto", InstallationMode.AUTO),+ ("AUTO", InstallationMode.AUTO),+ ("Ask", InstallationMode.ASK),+ (" Auto ", InstallationMode.AUTO),+ ("raise\n", InstallationMode.RAISE),+ ],+ )+ def test_env_var_sets_the_mode(self, monkeypatch, value, expected):+ monkeypatch.setenv(ENV_VAR, value)+ assert LazyLoaderConfig().installation_mode is expected++ @pytest.mark.parametrize("value", ["", " "])+ def test_empty_env_var_keeps_the_default(self, monkeypatch, value):+ monkeypatch.setenv(ENV_VAR, value)+ assert LazyLoaderConfig().installation_mode is InstallationMode.RAISE++ @staticmethod+ def _assert_names_the_bad_value(message, value):+ assert ENV_VAR in message+ assert repr(value) in message+ for choice in ("'raise'", "'ask'", "'auto'"):+ assert choice in message++ def test_invalid_env_var_is_reported_when_the_mode_is_needed(self, monkeypatch):+ monkeypatch.setenv(ENV_VAR, "maybe")+ config = LazyLoaderConfig() # creating the config, as `import kornia` does, does not raise+ with pytest.raises(ValueError) as excinfo:+ _ = config.installation_mode+ self._assert_names_the_bad_value(str(excinfo.value), "maybe")+ # A mode set in code replaces the invalid value.+ config.installation_mode = "raise"+ assert config.installation_mode is InstallationMode.RAISE++ @pytest.mark.parametrize("extra", [None, "image"])+ def test_invalid_env_var_is_reported_by_a_loader_for_a_missing_module(+ self, monkeypatch, commands, no_prompt, extra+ ):+ monkeypatch.setenv(ENV_VAR, "maybe")+ monkeypatch.setattr(kornia_config, "lazyloader", LazyLoaderConfig())+ assert LazyLoader("math").pi == pytest.approx(3.141592653589793) # an installed module does not need the mode+ with pytest.raises(ValueError) as excinfo:+ _ = LazyLoader(MISSING, extra=extra).attr+ self._assert_names_the_bad_value(str(excinfo.value), "maybe")+ assert f"'{MISSING}'" in str(excinfo.value)+ assert isinstance(excinfo.value.__cause__, ModuleNotFoundError)+ assert commands == []++ def test_invalid_env_var_does_not_break_import_kornia(self):+ env = {**{k: v for k, v in os.environ.items() if k != ENV_VAR}, ENV_VAR: "bogus"}+ code = textwrap.dedent(+ f"""+ import os+ import subprocess++ import kornia+ from kornia.core.external import LazyLoader++ def refuse(*args, **kwargs):+ raise RuntimeError("process start refused")++ for name in ("run", "call", "check_call", "check_output", "Popen"):+ setattr(subprocess, name, refuse)+ os.system = refuse++ print("IMPORTED", kornia.__name__, flush=True)+ print("INSTALLED", LazyLoader("math").pi, flush=True)+ try:+ LazyLoader({MISSING!r}, extra="image").attr+ except BaseException as e:+ print("MISSING", type(e).__name__, str(e), flush=True)+ """+ )+ # S603: this interpreter and a literal program; cwd is the repo root so the child imports this tree.+ result = subprocess.run( # noqa: S603+ [sys.executable, "-c", code],+ cwd=REPO_ROOT,+ env=env,+ capture_output=True,+ text=True,+ check=False,+ stdin=subprocess.DEVNULL,+ timeout=300,+ )+ assert result.returncode == 0, result.stderr+ lines = result.stdout.splitlines()+ assert "IMPORTED kornia" in lines, result.stdout+ assert "INSTALLED 3.141592653589793" in lines, result.stdout+ missing = [line for line in lines if line.startswith("MISSING ")]+ assert len(missing) == 1, result.stdout+ assert missing[0].startswith("MISSING ValueError "), missing[0]+ self._assert_names_the_bad_value(missing[0], "bogus")+ assert f"'{MISSING}'" in missing[0]++ @pytest.mark.parametrize(("value", "expected"), [(None, "RAISE"), ("auto", "AUTO")])+ def test_global_config_reads_the_env_var_at_import(self, value, expected):+ env = {k: v for k, v in os.environ.items() if k != ENV_VAR}+ if value is not None:+ env[ENV_VAR] = value+ code = (+ "from kornia.config import kornia_config\nprint('MODE', kornia_config.lazyloader.installation_mode.value)"+ )+ # S603: this interpreter and a literal program; cwd is the repo root so the child imports this tree.+ result = subprocess.run( # noqa: S603+ [sys.executable, "-c", code],+ cwd=REPO_ROOT,+ env=env,+ capture_output=True,+ text=True,+ check=False,+ stdin=subprocess.DEVNULL,+ timeout=300,+ )+ assert result.returncode == 0, result.stderr+ assert f"MODE {expected}" in result.stdout.splitlines()++ @pytest.mark.parametrize("value", ["raise", "Ask", "AUTO", InstallationMode.ASK])+ def test_setter_accepts_any_case(self, restore_mode, value):+ kornia_config.lazyloader.installation_mode = value+ assert kornia_config.lazyloader.installation_mode is InstallationMode(str(value).upper())++ def test_setter_rejects_unknown_values(self, restore_mode):+ with pytest.raises(ValueError) as excinfo:+ kornia_config.lazyloader.installation_mode = "maybe"+ for choice in ("'raise'", "'ask'", "'auto'"):+ assert choice in str(excinfo.value)+ with pytest.raises(TypeError):+ kornia_config.lazyloader.installation_mode = None+++class TestInstallationModeProtocol:+ """InstallationMode hashes, and ``==`` / ``!=`` agree, for members and strings."""++ def test_members_are_hashable(self):+ table = {mode: mode.value for mode in InstallationMode}+ assert table[InstallationMode.ASK] == "ASK"+ assert {InstallationMode.RAISE, InstallationMode.RAISE} == {InstallationMode.RAISE}++ @pytest.mark.parametrize("mode", list(InstallationMode))+ @pytest.mark.parametrize("other", ["ASK", "ask", "AUTO", "auto", "RAISE", "raise", "other", *InstallationMode])+ def test_eq_ne_and_hash_agree(self, mode, other):+ assert (mode == other) is not (mode != other)+ assert (other == mode) is not (other != mode)+ if mode == other:+ assert hash(mode) == hash(other)+++class TestAskMode:+ """``ASK`` asks only on an interactive terminal and otherwise behaves as ``RAISE``."""++ @pytest.mark.parametrize(+ ("stdin", "stdout"),+ [+ # A readable stdin that would answer "yes" if the loader read it; it is not a terminal.+ (lambda: io.StringIO("y\n"), FakeTerminal),+ (lambda: None, FakeTerminal),+ (closed_stream, FakeTerminal),+ # A terminal stdin with stdout redirected (``python train.py > log``): the question would be invisible.+ (FakeTerminal, io.StringIO),+ (FakeTerminal, lambda: None),+ ],+ ids=["stringio", "none", "closed", "stdout-redirected", "stdout-none"],+ )+ def test_non_terminal_raises_import_error(self, monkeypatch, restore_mode, commands, no_prompt, stdin, stdout):+ kornia_config.lazyloader.installation_mode = "ask"+ monkeypatch.setattr(sys, "stdin", stdin())+ monkeypatch.setattr(sys, "stdout", stdout())+ with pytest.raises(ImportError) as excinfo:+ _ = LazyLoader(MISSING, extra="image").attr+ assert str(excinfo.value) == not_installed(MISSING, "image")+ assert commands == []++ def test_terminal_check_returns_a_bool(self, monkeypatch):+ truthy = mock.Mock() # isatty() returns a truthy Mock+ monkeypatch.setattr(sys, "stdin", truthy)+ monkeypatch.setattr(sys, "stdout", truthy)+ assert external._interactive_terminal() is True++ @staticmethod+ def _child_code():+ return textwrap.dedent(+ f"""+ import os+ import subprocess++ from kornia.config import kornia_config+ from kornia.core.external import LazyLoader++ recorded = []++ def refuse(name):+ def start(*args, **kwargs):+ recorded.append(name)+ raise RuntimeError(name + " refused")+ return start++ for name in ("run", "call", "check_call", "check_output", "Popen"):+ setattr(subprocess, name, refuse("subprocess." + name))+ os.system = refuse("os.system")++ kornia_config.lazyloader.installation_mode = "ask"+ try:+ _ = LazyLoader({MISSING!r}, extra="image").attr+ print("RESULT returned", flush=True)+ except BaseException as e:+ print("RESULT", type(e).__name__, isinstance(e, ImportError), flush=True)+ print("RECORDED", recorded, flush=True)+ """+ )++ def test_devnull_stdin_raises_import_error_in_a_child_process(self):+ env = {k: v for k, v in os.environ.items() if k != ENV_VAR}+ # S603: this interpreter and a literal program; cwd is the repo root so the child imports this tree.+ result = subprocess.run( # noqa: S603+ [sys.executable, "-c", self._child_code()],+ cwd=REPO_ROOT,+ env=env,+ capture_output=True,+ text=True,+ check=False,+ stdin=subprocess.DEVNULL,+ timeout=300,+ )+ assert result.returncode == 0, result.stderr+ lines = result.stdout.splitlines()+ assert "RESULT ImportError True" in lines, result.stdout+ assert "RECORDED []" in lines, result.stdout++ def test_open_silent_stdin_does_not_block(self):+ env = {k: v for k, v in os.environ.items() if k != ENV_VAR}+ with tempfile.TemporaryFile(mode="w+") as out:+ # S603: this interpreter and a literal program. stdin is a pipe that stays open and is never written,+ # as some job runners and IDE consoles leave it; a loader that reads it would block forever.+ child = subprocess.Popen( # noqa: S603+ [sys.executable, "-c", self._child_code()],+ cwd=REPO_ROOT,+ env=env,+ stdin=subprocess.PIPE,+ stdout=out,+ stderr=subprocess.STDOUT,+ text=True,+ )+ try:+ child.wait(timeout=300)+ except subprocess.TimeoutExpired:+ child.kill()+ child.wait()+ pytest.fail("the loader blocked reading an open stdin that is not a terminal")+ finally:+ child.stdin.close()+ out.seek(0)+ output = out.read()+ assert child.returncode == 0, output+ lines = output.splitlines()+ assert "RESULT ImportError True" in lines, output+ assert "RECORDED []" in lines, output++ def test_terminal_answer_no_raises_import_error(self, monkeypatch, restore_mode, commands):+ to_give, prompts = pretend_terminal(monkeypatch)+ to_give.append("n")+ kornia_config.lazyloader.installation_mode = "ask"+ with pytest.raises(ImportError) as excinfo:+ _ = LazyLoader(MISSING, extra="image").attr+ assert str(excinfo.value) == not_installed(MISSING, "image")+ assert len(prompts) == 1+ assert 'pip install "kornia[image]"' in prompts[0]+ assert "'raise'" in prompts[0]+ assert ENV_VAR in prompts[0]+ assert commands == []++ @pytest.mark.parametrize("answer", ["y", "YES"])+ def test_terminal_answer_yes_installs_the_extra(self, monkeypatch, restore_mode, commands, answer):+ to_give, prompts = pretend_terminal(monkeypatch)+ to_give.append(answer)+ kornia_config.lazyloader.installation_mode = "ask"+ with pytest.raises(InstallRefused):+ _ = LazyLoader(MISSING, extra="image").attr+ assert commands == [pip_install("image")]+ assert len(prompts) == 1+ assert kornia_config.lazyloader.installation_mode is InstallationMode.ASK++ def test_terminal_answer_all_switches_the_process_to_auto(self, monkeypatch, restore_mode, commands):+ to_give, prompts = pretend_terminal(monkeypatch)+ to_give.append("a")+ kornia_config.lazyloader.installation_mode = "ask"+ with pytest.raises(InstallRefused):+ _ = LazyLoader(MISSING, extra="image").attr+ assert kornia_config.lazyloader.installation_mode is InstallationMode.AUTO+ # Another loader, for another extra, installs without asking again.+ with pytest.raises(InstallRefused):+ _ = LazyLoader(MISSING + "_2", extra="sd").attr+ assert len(prompts) == 1+ assert commands == [pip_install("image"), pip_install("sd")]++ def test_terminal_invalid_answer_asks_again(self, monkeypatch, restore_mode, commands):+ to_give, prompts = pretend_terminal(monkeypatch)+ to_give.extend(["maybe", "n"])+ kornia_config.lazyloader.installation_mode = "ask"+ with pytest.raises(ImportError):+ _ = LazyLoader(MISSING, extra="image").attr+ assert len(prompts) == 2+ assert commands == []++ def test_terminal_end_of_input_raises_import_error(self, monkeypatch, restore_mode, commands):+ _, prompts = pretend_terminal(monkeypatch) # no answer: input() raises EOFError+ kornia_config.lazyloader.installation_mode = "ask"+ with pytest.raises(ImportError) as excinfo:+ _ = LazyLoader(MISSING, extra="image").attr+ assert str(excinfo.value) == not_installed(MISSING, "image")+ assert len(prompts) == 1+ assert commands == []++ def test_terminal_does_not_ask_for_a_loader_without_extra(self, monkeypatch, restore_mode, commands):+ to_give, prompts = pretend_terminal(monkeypatch)+ to_give.append("y")+ kornia_config.lazyloader.installation_mode = "ask"+ with pytest.raises(ImportError) as excinfo:+ _ = LazyLoader(MISSING).attr+ assert str(excinfo.value) == not_installed(MISSING)+ assert prompts == []+ assert commands == []+++class TestAutoMode:+ """``AUTO`` installs the declared kornia extra, and nothing for a loader without one."""++ @pytest.mark.parametrize(+ ("name", "extra"),+ [("PILImage", "image"), ("onnx", "onnx"), ("onnxruntime", "onnx"), ("diffusers", "sd")],+ )+ def test_installs_the_declared_extra(self, restore_mode, commands, no_prompt, blocked, name, extra):+ declared = getattr(external, name)+ loader = LazyLoader(declared.module_name, dev_dependency=declared.dev_dependency, extra=declared.extra)+ blocked.add(declared.module_name)+ kornia_config.lazyloader.installation_mode = "auto"+ with pytest.raises(InstallRefused):+ _ = loader.attr+ assert commands == [pip_install(extra)]++ @pytest.mark.parametrize("module_name", [MISSING, "numpy"])+ def test_loader_without_extra_never_installs(self, restore_mode, commands, no_prompt, blocked, module_name):+ blocked.add(module_name)+ kornia_config.lazyloader.installation_mode = "auto"+ with pytest.raises(ImportError) as excinfo:+ _ = LazyLoader(module_name).attr+ assert str(excinfo.value) == not_installed(module_name)+ assert commands == []++ def test_pip_failure_raises_import_error_once(self, monkeypatch, restore_mode, commands, no_prompt):+ def failing_pip(args, *rest, check=False, **kwargs):+ commands.append(args)+ if check:+ raise subprocess.CalledProcessError(1, args)+ return subprocess.CompletedProcess(args, 1)++ monkeypatch.setattr(subprocess, "run", failing_pip)+ kornia_config.lazyloader.installation_mode = "auto"+ loader = LazyLoader(MISSING, extra="sd")+ with pytest.raises(ImportError) as excinfo:+ _ = loader.attr+ assert 'pip install "kornia[sd]"' in str(excinfo.value)+ assert "failed" in str(excinfo.value)+ assert isinstance(excinfo.value.__cause__, subprocess.CalledProcessError)+ # The failure is remembered: the next access raises again without running pip again.+ with pytest.raises(ImportError, match="failed"):+ _ = loader.attr+ assert commands == [pip_install("sd")]++ def test_successful_install_imports_the_module(self, monkeypatch, restore_mode, commands, no_prompt, blocked):+ blocked.add("math")++ def working_pip(args, *rest, check=False, **kwargs):+ commands.append(args)+ blocked.discard("math") # what the installation would make importable+ return subprocess.CompletedProcess(args, 0)++ monkeypatch.setattr(subprocess, "run", working_pip)+ kornia_config.lazyloader.installation_mode = "auto"+ loader = LazyLoader("math", extra="image")+ assert loader.pi == pytest.approx(3.141592653589793)+ assert commands == [pip_install("image")]diff --git a/tests/core/test_lazyloader.py b/tests/core/test_lazyloader.pyindex dc025a15e..8e5556fd2 100644--- a/tests/core/test_lazyloader.py+++ b/tests/core/test_lazyloader.py@@ -15,12 +15,26 @@# limitations under the License.#-from io import StringIO+import builtins+import copy+import doctest+import importlib+import inspect+import math+import os+import pickle+import subprocess+import sys+import typesimport pytest+from kornia.config import LazyLoaderConfig, kornia_config+from kornia.core import externalfrom kornia.core.external import LazyLoader+MISSING = "kornia_test_no_such_module_xyz"+class TestLazyLoader:def test_lazy_loader_initialization(self):@@ -38,9 +52,8 @@ class TestLazyLoader:assert loader.sqrt(4) == 2.0assert loader.module is not None # Should be loaded now- def test_lazy_loader_invalid_module(self, monkeypatch):- monkeypatch.setattr("sys.stdin", StringIO("n"))- # Test that LazyLoader raises an ImportError for an invalid module+ def test_lazy_loader_invalid_module(self):+ # Test that LazyLoader raises an ImportError for an invalid module (the default mode raises; nothing is asked)loader = LazyLoader("non_existent_module")with pytest.raises(ImportError) as excinfo:_ = loader.non_existent_attribute # Accessing any attribute should raise the error@@ -74,3 +87,113 @@ class TestLazyLoader:loader = LazyLoader("math")with pytest.raises(AttributeError):_ = loader.non_existent_attribute+++def untouchable(monkeypatch):+ """Put the loaders in AUTO mode and fail on any prompt or process start: a probe must do neither."""+ previous = kornia_config.lazyloader.installation_mode+ kornia_config.lazyloader.installation_mode = "auto"++ def forbidden(*args, **kwargs):+ raise AssertionError(f"a lazy-loader probe tried to prompt or start a process: {args!r}")++ for name in ("run", "call", "check_call", "check_output", "Popen"):+ monkeypatch.setattr(subprocess, name, forbidden)+ monkeypatch.setattr(os, "system", forbidden)+ monkeypatch.setattr(builtins, "input", forbidden)+ yield+ kornia_config.lazyloader.installation_mode = previous+++class TestLazyLoaderCopyAndPickle:+ """A loader survives copy, deepcopy and pickling, before and after it has loaded its module."""++ @pytest.mark.parametrize("loaded", [False, True])+ @pytest.mark.parametrize(+ "duplicate",+ # S301: a round trip of an object this test just built.+ [copy.copy, copy.deepcopy, lambda loader: pickle.loads(pickle.dumps(loader))], # noqa: S301+ ids=["copy", "deepcopy", "pickle"],+ )+ def test_duplicate_is_a_working_loader(self, duplicate, loaded):+ loader = LazyLoader("math", extra="image")+ if loaded:+ assert loader.pi == math.pi+ other = duplicate(loader)+ assert isinstance(other, LazyLoader)+ assert (other.module_name, other.dev_dependency, other.extra) == ("math", False, "image")+ assert other.pi == math.pi+ assert other.sqrt(16) == 4.0++ def test_copy_of_a_missing_module_loader(self, untouchable):+ other = copy.copy(LazyLoader(MISSING, extra="sd"))+ assert other.module_name == MISSING+ assert other.module is None+++class TestLazyLoaderProtocolProbes:+ """Protocol lookups (dunder names) never import, install or prompt for a module that is not loaded."""++ def test_probes_on_a_missing_module(self, untouchable):+ loader = LazyLoader(MISSING, extra="sd")+ assert not hasattr(loader, "__wrapped__")+ assert inspect.unwrap(loader) is loader+ assert not inspect.isroutine(loader)+ assert loader.module is None++ def test_doctest_finder_skips_a_missing_module_loader(self, untouchable):+ # What ``pytest --doctest-modules`` does to every module: walk its namespace for routines and classes.+ module = types.ModuleType("kornia_test_doctest_module")++ def documented():+ """Return one.++ >>> documented()+ 1+ """+ return 1++ # Rebind the function to the module's globals, as if it were defined there.+ module.documented = types.FunctionType(documented.__code__, module.__dict__, "documented")+ module.optional = LazyLoader(MISSING, extra="sd")+ tests = doctest.DocTestFinder().find(module)+ assert [test.name for test in tests] == ["kornia_test_doctest_module.documented"]+ assert module.optional.module is None++ @pytest.mark.parametrize(+ ("module_name", "attribute"),+ [("numpy", "__version__"), ("json", "__file__"), ("json", "__path__"), ("json", "__all__")],+ )+ def test_module_metadata_loads_the_module(self, module_name, attribute):+ module = importlib.import_module(module_name)+ loader = LazyLoader(module_name)+ assert getattr(loader, attribute) == getattr(module, attribute)+ assert loader.module is module++ def test_module_metadata_of_a_missing_module_raises_import_error(self, monkeypatch):+ monkeypatch.delenv("KORNIA_INSTALLATION_MODE", raising=False)+ monkeypatch.setattr(kornia_config, "lazyloader", LazyLoaderConfig())+ with pytest.raises(ImportError):+ _ = LazyLoader(MISSING, extra="sd").__version__++ def test_probe_forwards_to_a_loaded_module(self):+ loader = LazyLoader("math")+ assert loader.pi == math.pi+ assert loader.__name__ == "math"+++class TestLazyLoaderUnderDoctestModules:+ """``--doctest-modules`` in ``sys.argv`` does not stop an installed module from loading."""++ @pytest.mark.parametrize("dev_dependency", [False, True])+ def test_installed_module_loads(self, monkeypatch, dev_dependency):+ monkeypatch.setattr(sys, "argv", [*sys.argv, "--doctest-modules"])+ assert LazyLoader("math", dev_dependency=dev_dependency).pi == math.pi++ def test_installed_onnxruntime_loads(self, monkeypatch):+ onnxruntime = pytest.importorskip("onnxruntime")+ monkeypatch.setattr(sys, "argv", [*sys.argv, "--doctest-modules"])+ declared = external.onnxruntime+ loader = LazyLoader(declared.module_name, dev_dependency=declared.dev_dependency, extra=declared.extra)+ assert loader.InferenceSession is onnxruntime.InferenceSessiondiff --git a/tests/core/test_module.py b/tests/core/test_module.pyindex bf93f44b9..279f147aa 100644--- a/tests/core/test_module.py+++ b/tests/core/test_module.py@@ -16,6 +16,7 @@#import os+import sysfrom unittest.mock import MagicMockimport numpy as np@@ -176,6 +177,48 @@ class TestImageModuleMixIn:torch.testing.assert_close(cached, output.detach())+class TestPILLookupWithoutImport(BaseTester):+ """A call that needs no PIL conversion never consults the PIL loader, whatever its other arguments are."""++ @pytest.fixture+ def pil_not_imported(self, monkeypatch):+ from kornia.core.mixin import image_module++ class Untouchable:+ def __getattr__(self, name):+ raise AssertionError(f"the PIL loader was consulted for {name!r}")++ # As on an install without the "image" extra: PIL.Image is not imported, and the loader must not import it.+ monkeypatch.setattr(image_module, "Image", Untouchable())+ monkeypatch.delitem(sys.modules, "PIL.Image", raising=False)++ def test_container_with_data_keys(self, pil_not_imported, device, dtype):+ from kornia.augmentation import AugmentationSequential, RandomHorizontalFlip++ image = torch.rand(1, 3, 4, 6, device=device, dtype=dtype)+ mask = torch.rand(1, 1, 4, 6, device=device, dtype=dtype)+ out_image, out_mask = AugmentationSequential(RandomHorizontalFlip(p=1.0))(+ image, mask, data_keys=["input", "mask"]+ )+ self.assert_close(out_image, image.flip(-1))+ self.assert_close(out_mask, mask.flip(-1))++ def test_image_module_with_keyword_argument(self, pil_not_imported, device, dtype):+ class Scale(ImageModule):+ def forward(self, x, scale=1.0):+ return x * scale++ x = torch.rand(3, 4, 6, device=device, dtype=dtype)+ self.assert_close(Scale()(x, scale=0.5), x * 0.5)++ def test_pil_image_is_still_converted(self):+ image = PILImage.fromarray(np.full((4, 6, 3), 255, dtype=np.uint8))+ module = ImageModuleMixIn()+ assert module._is_valid_arg(image)+ assert module._is_valid_arg([image]) is False+ assert module._is_valid_arg("not an existing path") is False++class TestImageModule:@pytest.fixturedef image_module(self):diff --git a/tests/test_declared_imports.py b/tests/test_declared_imports.pyindex 7b09a55f7..425bae68d 100644--- a/tests/test_declared_imports.py+++ b/tests/test_declared_imports.py@@ -293,8 +293,8 @@ def test_import_kornia_does_not_load_optional_dependencies():# S603: no untrusted input -- this interpreter, a literal program, and module names derived from# pyproject.toml and the registry above. check=False so a crashed probe reports its stderr instead# of an opaque CalledProcessError; the return-code assertion keeps the test from passing vacuously.- # stdin is closed and the call bounded so a LazyLoader that prompts during import (the default- # InstallationMode.ASK) fails with an EOFError report instead of waiting on a terminal.+ # stdin is closed and the call bounded so a LazyLoader reached during import cannot wait on a+ # terminal, whatever the installation mode (InstallationMode.ASK behaves as RAISE without one).result = subprocess.run( # noqa: S603[sys.executable, "-c", code, *checked],cwd=REPO_ROOT,