π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(tests): stop doctests downloading model weights and failing on progress output (#4005) (#4039)
Dmytro Mishkin2b13d4b90959
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.ymlindex 1dda60825..098edd599 100644--- a/.github/workflows/docs.yml+++ b/.github/workflows/docs.yml@@ -28,6 +28,15 @@ on:cache-restore-keys:required: falsetype: string+ download-weights:+ description: >-+ Let the doctests download pretrained model weights when the cache+ misses. Enabled for the scheduled/main-branch run so the model+ examples keep real coverage; left off for pull requests, where a+ cold cache would mean an ~838 MB download.+ required: false+ type: boolean+ default: falsepermissions:contents: read@@ -51,9 +60,10 @@ jobs:ref: ${{ github.event.pull_request.head.sha || inputs.ref }}# On direct pull_request runs (empty inputs) fall back to a prefix restore of the- # model-weights caches saved by the test workflows: doctests download ~10 model- # checkpoints, and a cold cache both takes minutes and breaks doctests (torch.hub- # prints 'Downloading: ...', which the examples do not expect).+ # model-weights caches saved by the test workflows. A dozen doctests build+ # pretrained models, so a warm cache is what keeps them covered here: without+ # `download-weights` a cache miss skips those examples rather than downloading+ # ~838 MB of checkpoints (see #4005).- name: Restore cacheuses: actions/cache/restore@v6with:@@ -80,6 +90,11 @@ jobs:run: pixi run -e ${{ steps.pixi-env.outputs.name }} install-docs- name: Run doctest+ # Empty on direct pull_request events (the `inputs` context is empty there and+ # the workflow_call default does not apply), which is the intended PR behaviour:+ # doctests needing an uncached checkpoint are skipped instead of downloading it.+ env:+ KORNIA_DOCTEST_DOWNLOAD: ${{ inputs.download-weights && '1' || '' }}run: pixi run -e ${{ steps.pixi-env.outputs.name }} doctest- name: Build Documentationdiff --git a/.github/workflows/scheduled_test_cpu.yml b/.github/workflows/scheduled_test_cpu.ymlindex a7996dc89..3b87b9a07 100644--- a/.github/workflows/scheduled_test_cpu.yml+++ b/.github/workflows/scheduled_test_cpu.yml@@ -220,6 +220,9 @@ jobs:uses: ./.github/workflows/docs.ymlwith:python-version: '["3.11"]'+ # Post-merge run: the model doctests download on a cache miss instead of+ # skipping, so main always exercises them for real.+ download-weights: truecache-path: weights/cache-key: model-weights-${{ needs.pre-tests.outputs.hash }}cache-restore-keys: |diff --git a/AGENTS.md b/AGENTS.mdindex b0f2a21d4..e12cc5804 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -37,6 +37,7 @@ pixi run lintpixi run pre-commit-allpixi run typecheckpixi run doctest+pixi run doctest-weightspixi run build-docs```@@ -51,7 +52,7 @@ KORNIA_TEST_DEVICE=cuda KORNIA_TEST_DTYPE=float32 pixi run test-module tests/geoSupported fixtures include CPU, CUDA, MPS, and TPU when available, and `float16`, `bfloat16`, `float32`, and `float64`. Run focused checks first and expand them in proportion to the change.-Use `KORNIA_TEST_RUNSLOW=true` to include slow tests. `KORNIA_TEST_OPTIMIZER=inductor` enables the dynamo and compile tests, which are deselected when the variable is unset. Before presenting a code change as finished, run the full pre-commit command above together with focused tests and other relevant checks; `pixi run lint` runs only the Ruff hooks.+Use `KORNIA_TEST_RUNSLOW=true` to include slow tests. `KORNIA_TEST_OPTIMIZER=inductor` enables the dynamo and compile tests, which are deselected when the variable is unset. `pixi run doctest` skips docstring examples that would download an uncached model checkpoint, so it stays fast and works offline; use `pixi run doctest-weights` (or `KORNIA_DOCTEST_DOWNLOAD=1`) to run those examples for real, which costs ~838 MB on a cold cache. Pull-request CI relies on the restored weights cache and skips whatever it misses; the post-merge run on `main` downloads, so the model examples are always exercised somewhere. Before presenting a code change as finished, run the full pre-commit command above together with focused tests and other relevant checks; `pixi run lint` runs only the Ruff hooks.### Precision and device detailsdiff --git a/conftest.py b/conftest.pyindex 23c6dc0ce..b6ab89af0 100644--- a/conftest.py+++ b/conftest.py@@ -33,6 +33,8 @@ except ImportError: # pragma: no coverimport kornia+from testing.doctest_downloads import DOWNLOAD_ENV_VAR, downloads_allowed, install_download_guard, skip_reason+try:import torch._dynamo@@ -223,6 +225,7 @@ def pytest_addoption(parser):KORNIA_TEST_OPTIMIZER: Optimizer backend (default: inductor)KORNIA_TEST_RUNSLOW: Run slow tests (default: false)KORNIA_TEST_TF32: Enable TF32 (TensorFloat-32) mode for CUDA matrix multiplications (default: false)+ KORNIA_DOCTEST_DOWNLOAD: Let doctests download model weights (default: false)"""parser.addoption("--device",@@ -259,6 +262,17 @@ def pytest_addoption(parser):"(env: KORNIA_TEST_TF32)"),)+ parser.addoption(+ "--doctest-download",+ action="store_true",+ default=downloads_allowed(os.environ),+ help=(+ "Let doctests download pretrained model weights. Without this flag a doctest that "+ "would hit the network is skipped instead, so `pixi run doctest` stays fast and "+ "offline-safe on a cold cache; doctests whose weights are already cached still run. "+ f"(env: {DOWNLOAD_ENV_VAR})"+ ),+ )parser.addoption("--isolate-half-precision",action="store_true",@@ -647,6 +661,27 @@ def cuda_device_assert_guard(request):pytest.fail(f"CUDA device-side assert triggered during this test: {exc}")[email protected](autouse=True)+def skip_doctests_needing_downloads(request, monkeypatch):+ """Skip doctests that would download pretrained weights.++ A dozen docstring examples in ``kornia/`` build pretrained models, which on a+ cold cache turns ``pixi run doctest`` into an ~838 MB download. The guard+ patches the download primitives, which run only on a cache miss, so an+ example whose weights are already present still runs for real.++ Opt in with ``--doctest-download`` / ``KORNIA_DOCTEST_DOWNLOAD=1``; the+ scheduled main-branch documentation job does, so the examples keep real+ coverage there.+ """+ if not isinstance(request.node, pytest.DoctestItem):+ return+ if request.config.getoption("--doctest-download"):+ return++ install_download_guard(monkeypatch.setattr, lambda url: pytest.skip(skip_reason(url)))++@pytest.fixture(autouse=True)def add_doctest_deps(doctest_namespace):"""Add dependencies for doctests."""diff --git a/kornia/core/download.py b/kornia/core/download.pyindex 0d3ff1645..954162bf3 100644--- a/kornia/core/download.py+++ b/kornia/core/download.py@@ -17,6 +17,8 @@from __future__ import annotations+import os+import sysimport warningsfrom pathlib import Pathfrom typing import Any@@ -45,6 +47,59 @@ def hf_url(repo: str, filename: str) -> str:return f"{_HF_KORNIA_BASE}/{repo}/resolve/main/{filename}"+def _cached_file_path(url: str, kwargs: dict[str, Any]) -> str:+ """Return the path :func:`torch.hub.load_state_dict_from_url` would cache *url* at.++ Mirrors torch's own resolution: ``<model_dir>/<file_name or basename(url)>``,+ where ``model_dir`` defaults to ``<torch.hub.get_dir()>/checkpoints``.++ Args:+ url: the URL that would be downloaded.+ kwargs: the keyword arguments destined for the torch function; only+ ``model_dir`` and ``file_name`` are consulted.++ Returns:+ The absolute path of the cache entry for *url*.+ """+ model_dir = kwargs.get("model_dir")+ if model_dir is None:+ model_dir = os.path.join(torch.hub.get_dir(), "checkpoints")+ filename = kwargs.get("file_name") or os.path.basename(urlparse(url).path)+ return os.path.join(model_dir, filename)+++def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> None:+ """Download *url* into the torch hub cache if it is not already there.++ Doing the fetch here rather than letting :func:`torch.hub.load_state_dict_from_url`+ do it means torch finds the file present and never writes its status line to+ stdout. A no-op when the file is already cached, which is the common case.++ If the path computed here ever disagreed with torch's, the only consequence+ is that torch downloads the file again -- the result stays correct.++ Args:+ url: the URL to fetch.+ kwargs: the keyword arguments destined for the torch function;+ ``model_dir``, ``file_name``, ``check_hash`` and ``progress`` are+ honoured so the cache entry is identical to torch's.+ """+ cached_file = _cached_file_path(url, kwargs)+ if os.path.exists(cached_file):+ return++ os.makedirs(os.path.dirname(cached_file), exist_ok=True)++ hash_prefix = None+ if kwargs.get("check_hash"):+ match = torch.hub.HASH_REGEX.search(os.path.basename(cached_file))+ hash_prefix = match.group(1) if match else None++ # torch writes this to stdout; status output belongs on stderr.+ sys.stderr.write(f'Downloading: "{url}" to {cached_file}\n')+ torch.hub.download_url_to_file(url, cached_file, hash_prefix, progress=kwargs.get("progress", True))++def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Any]:"""Load a state dict from a URL, trying fallback URLs on failure.@@ -53,6 +108,23 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Atried in turn; a :mod:`warnings` message is emitted for every failedattempt before the next source is tried.+ Progress reporting is written to :data:`sys.stderr`. This is the one+ deliberate deviation from the torch function, which since torch 2.x writes+ its ``Downloading: "<url>" to <path>`` line to :data:`sys.stdout` (the+ accompanying progress bar already goes to stderr). Status output on stdout+ corrupts any caller that treats stdout as data -- most visibly doctests,+ where the line is captured as unexpected example output and fails an+ example that downloads on a cold cache.++ That line is reached only when the file is absent from the cache, so this+ function fetches a missing file itself -- announcing it on stderr -- and+ leaves torch with nothing to report. Nothing process-global is touched:+ redirecting :data:`sys.stdout` around the call would divert unrelated+ threads' output for the whole transfer, and concurrent calls restoring out+ of order would leave stdout permanently pointing at stderr. This mirrors+ :func:`kornia.feature.lightglue_onnx.utils.download.download_onnx_from_url`,+ which already reimplements torch's caching for the same reason.+When multiple URLs are given and ``file_name`` is not already in *kwargs*,the basename of the **first** URL is used as the local cache filename forall attempts. This guarantees that:@@ -92,6 +164,8 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Alast_exc: Exception | None = Nonefor i, u in enumerate(urls):try:+ # Populate the cache ourselves so torch's stdout line is never reached.+ _prefetch_to_cache(u, kwargs)return torch.hub.load_state_dict_from_url(u, **kwargs)except Exception as e: # noqa: BLE001last_exc = ediff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.pyindex de18c10b9..5c7d6c64b 100644--- a/kornia/feature/xfeat.py+++ b/kornia/feature/xfeat.py@@ -38,6 +38,7 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK+from kornia.core.download import load_state_dict_from_urlfrom kornia.geometry.subpix import nms2d@@ -314,7 +315,7 @@ class XFeat(nn.Module):XFeat model with pretrained weights loaded, set to eval mode."""model = cls(top_k=top_k, detection_threshold=detection_threshold)- state_dict = torch.hub.load_state_dict_from_url(cls.weights_url, file_name="xfeat.pt")+ state_dict = load_state_dict_from_url(cls.weights_url, file_name="xfeat.pt")model.net.load_state_dict(state_dict)model.eval()return modeldiff --git a/pixi.toml b/pixi.tomlindex f849d0fe4..4e6e4e51a 100644--- a/pixi.toml+++ b/pixi.toml@@ -50,7 +50,8 @@ lint = { cmd = "uv run pre-commit run ruff-check --all-files && uv run pre-commipre-commit-all = { cmd = "uv run pre-commit run --all-files", description = "Run all repository pre-commit checks" }pre-commit-install = { cmd = "uv run pre-commit install", description = "Install the pre-commit Git hook" }typecheck = { cmd = "ty check kornia" }-doctest = { cmd = "uv run pytest -v --doctest-modules kornia/" }+doctest = { cmd = "uv run pytest -v --doctest-modules kornia/", description = "Run docstring examples; examples needing an uncached model checkpoint are skipped" }+doctest-weights = { cmd = "uv run pytest -v --doctest-modules kornia/", env = { KORNIA_DOCTEST_DOWNLOAD = "1" }, description = "Run docstring examples, downloading pretrained weights when the cache misses (~838 MB cold)" }toml-fmt = { cmd = "tombi format", description = "Format TOML files" }toml-fmt-check = { cmd = "tombi format --check", description = "Check TOML formatting" }# Docsdiff --git a/testing/doctest_downloads.py b/testing/doctest_downloads.pynew file mode 100644index 000000000..a3557d40d--- /dev/null+++ b/testing/doctest_downloads.py@@ -0,0 +1,145 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Keep the doctest run off the network.++``pytest --doctest-modules kornia/`` executes the examples in every public+docstring, and a dozen of those construct pretrained models. On a cold cache+that turns the nominal documentation check into an ~838 MB download.++This module patches the download *primitives* -- the functions that run only+when a weight file is missing from the cache -- so that a doctest which would+download instead reports as skipped. Doctests whose weights are already cached+still run for real, so a warm cache (CI, or a developer who has run the model+tests) keeps full coverage with no list of exempted examples to maintain.++Set ``KORNIA_DOCTEST_DOWNLOAD=1`` (or pass ``--doctest-download``) to allow the+downloads, which is what the scheduled main-branch documentation job does.+"""++from __future__ import annotations++import importlib+from typing import Any, Callable, NoReturn, Sequence++DOWNLOAD_ENV_VAR = "KORNIA_DOCTEST_DOWNLOAD"++# Entry points that reach the network only on a cache miss, as+# ``(module, attribute)`` pairs resolved lazily at patch time.+#+# ``kornia.feature.lightglue_onnx.utils.download`` binds ``download_url_to_file``+# at import time, so patching ``torch.hub`` alone would not cover it.+_DOWNLOAD_PRIMITIVES: tuple[tuple[str, str], ...] = (+ ("torch.hub", "download_url_to_file"),+ ("kornia.feature.lightglue_onnx.utils.download", "download_url_to_file"),+ # kornia.onnx.download.CachedDownloader.download reaches the network here.+ ("urllib.request", "urlretrieve"),+)+++def downloads_allowed(env: dict[str, str]) -> bool:+ """Return whether doctests may download model weights.++ Args:+ env: environment mapping to read ``KORNIA_DOCTEST_DOWNLOAD`` from.++ Returns:+ ``True`` when the variable is set to ``1``, ``true`` or ``yes``+ (case-insensitive), ``False`` otherwise.++ Example:+ >>> downloads_allowed({})+ False+ >>> downloads_allowed({"KORNIA_DOCTEST_DOWNLOAD": "1"})+ True+ >>> downloads_allowed({"KORNIA_DOCTEST_DOWNLOAD": "false"})+ False+ """+ return env.get(DOWNLOAD_ENV_VAR, "").strip().lower() in {"1", "true", "yes"}+++def install_download_guard(+ setattr_fn: Callable[[Any, str, Any], None],+ on_download: Callable[[str], NoReturn],+ primitives: Sequence[tuple[str, str]] = _DOWNLOAD_PRIMITIVES,+) -> list[tuple[str, str]]:+ """Redirect every kornia weight-download primitive to *on_download*.++ Args:+ setattr_fn: ``monkeypatch.setattr``-style callable, so the patches are+ undone when the surrounding test finishes.+ on_download: called with the requested URL instead of downloading it.+ It must not return -- typically it raises, e.g. ``pytest.skip``.+ primitives: ``(module, attribute)`` pairs to patch. Pairs whose module+ is not importable are skipped, which keeps optional subpackages+ from turning into a hard dependency of the test run.++ Returns:+ The pairs that were actually patched, in the order given.++ Example:+ >>> patched = {}+ >>> def fake_setattr(obj, name, value):+ ... patched[name] = value+ >>> def refuse(url):+ ... raise RuntimeError(url)+ >>> install_download_guard(fake_setattr, refuse, [("torch.hub", "download_url_to_file")])+ [('torch.hub', 'download_url_to_file')]+ >>> patched["download_url_to_file"]("https://example.com/w.pth", "/tmp/w.pth")+ Traceback (most recent call last):+ ...+ RuntimeError: https://example.com/w.pth+ """+ patched: list[tuple[str, str]] = []++ for module_name, attribute in primitives:+ try:+ module = importlib.import_module(module_name)+ except ImportError:+ continue+ if not hasattr(module, attribute):+ continue++ def _guard(url: str, *args: Any, **kwargs: Any) -> NoReturn:+ on_download(url)+ # on_download is documented as non-returning; be explicit if it is not.+ raise AssertionError(f"download guard callback returned instead of raising for {url!r}")++ setattr_fn(module, attribute, _guard)+ patched.append((module_name, attribute))++ return patched+++def skip_reason(url: str) -> str:+ """Return the message shown when a doctest is skipped for needing a download.++ Args:+ url: the weight URL the doctest tried to fetch.++ Returns:+ A message naming the URL and how to opt in.++ Example:+ >>> skip_reason("https://example.com/w.pth").split(";")[0]+ 'doctest needs to download model weights from https://example.com/w.pth'+ """+ return (+ f"doctest needs to download model weights from {url}; "+ f"set {DOWNLOAD_ENV_VAR}=1 to allow it, or pre-populate the cache "+ "with `python .github/download-models-weights.py`"+ )diff --git a/tests/core/test_download.py b/tests/core/test_download.pyindex 258e097d6..3ff2911c0 100644--- a/tests/core/test_download.py+++ b/tests/core/test_download.py@@ -17,10 +17,14 @@from __future__ import annotations+import sys+import threading+import timeimport warningsfrom unittest.mock import call, patchimport pytest+import torchfrom kornia.core.download import hf_url, load_state_dict_from_url@@ -40,6 +44,16 @@ class TestLoadStateDictFromUrl:_SD = {"weight": 1}_MOCK_TARGET = "kornia.core.download.torch.hub.load_state_dict_from_url"+ @pytest.fixture(autouse=True)+ def _isolated_cache(self, monkeypatch, tmp_path):+ """Keep the wrapper's prefetch step off the network and out of weights/."""+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ monkeypatch.setattr(+ torch.hub,+ "download_url_to_file",+ lambda url, dst, *a, **k: torch.save({"weight": torch.zeros(1)}, dst),+ )+def test_single_url_success(self) -> None:with patch(self._MOCK_TARGET, return_value=self._SD) as mock:result = load_state_dict_from_url("http://example.com/model.pth")@@ -115,3 +129,150 @@ class TestLoadStateDictFromUrl:with patch(self._MOCK_TARGET, return_value=self._SD) as mock:load_state_dict_from_url("http://example.com/model.pth", map_location="cpu")mock.assert_called_once_with("http://example.com/model.pth", map_location="cpu")+++class TestProgressGoesToStderr:+ """torch.hub writes its 'Downloading: ...' line to stdout (torch 2.x).++ Status output on stdout corrupts callers that treat stdout as data. The most+ visible victim is ``pytest --doctest-modules kornia/``: the line is captured as+ unexpected example output and fails any example that downloads on a cold cache+ (#4005). The wrapper populates the cache itself so torch never reaches that+ line, rather than redirecting the process-global stdout around the call.+ """++ _URL = "http://example.com/model.pth"++ @staticmethod+ def _cold_cache(monkeypatch, tmp_path, *, on_download=None):+ """Point the hub cache at an empty tmp dir and stub the actual transfer.++ torch's own ``load_state_dict_from_url`` still runs for real, so a+ transfer count of exactly one also proves the path the wrapper+ prefetches to is the path torch looks in -- a disagreement would make+ torch download the file a second time.+ """+ transfers: list[str] = []+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))++ def fake_download(url, dst, hash_prefix=None, progress=True):+ transfers.append(url)+ if on_download is not None:+ on_download()+ torch.save({"weight": torch.zeros(1)}, dst)++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ return transfers++ def test_cold_cache_writes_nothing_to_stdout(self, capsys, monkeypatch, tmp_path) -> None:+ transfers = self._cold_cache(monkeypatch, tmp_path)++ result = load_state_dict_from_url(self._URL)++ captured = capsys.readouterr()+ assert "weight" in result+ assert captured.out == ""+ assert f'Downloading: "{self._URL}"' in captured.err+ # Exactly one transfer: torch found the prefetched file where it expected it.+ assert transfers == [self._URL]++ def test_warm_cache_is_silent(self, capsys, monkeypatch, tmp_path) -> None:+ transfers = self._cold_cache(monkeypatch, tmp_path)+ load_state_dict_from_url(self._URL)+ capsys.readouterr()++ load_state_dict_from_url(self._URL)++ captured = capsys.readouterr()+ assert captured.out == ""+ assert captured.err == ""+ assert len(transfers) == 1++ def test_stdout_object_is_never_replaced(self, monkeypatch, tmp_path) -> None:+ seen: list[object] = []+ self._cold_cache(monkeypatch, tmp_path, on_download=lambda: seen.append(sys.stdout))+ original = sys.stdout++ load_state_dict_from_url(self._URL)++ # Not merely restored afterwards -- untouched *during* the transfer.+ assert seen == [original]+ assert sys.stdout is original+++class TestConcurrentLoadsDoNotDisturbStdout:+ """Regression tests for the review finding on #4039.++ An earlier revision wrapped the torch call in ``contextlib.redirect_stdout``.+ That mutates process-global ``sys.stdout`` for the whole transfer, so unrelated+ threads lost their output to stderr, and two overlapping calls restored out of+ order and left ``sys.stdout`` permanently pointing at ``sys.stderr``.+ """++ _URL = "http://example.com/model.pth"++ @staticmethod+ def _stub_transfer(monkeypatch, tmp_path, hook):+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))++ def fake_download(url, dst, hash_prefix=None, progress=True):+ hook(url)+ torch.save({"weight": torch.zeros(1)}, dst)++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)++ def test_overlapping_calls_leave_stdout_intact(self, monkeypatch, tmp_path) -> None:+ barrier = threading.Barrier(2)++ def hook(url: str) -> None:+ barrier.wait(timeout=5)+ # Force the two calls to finish in the opposite order they started.+ time.sleep(0.05 if url.endswith("a.pth") else 0.15)++ self._stub_transfer(monkeypatch, tmp_path, hook)+ original = sys.stdout++ threads = [+ threading.Thread(target=load_state_dict_from_url, args=(f"http://example.com/{name}.pth",))+ for name in ("a", "b")+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=10)++ assert sys.stdout is original+ assert sys.stdout is not sys.stderr++ def test_unrelated_thread_keeps_its_stdout(self, monkeypatch, tmp_path) -> None:+ in_flight = threading.Event()+ release = threading.Event()++ def hook(url: str) -> None:+ in_flight.set()+ release.wait(timeout=5)++ self._stub_transfer(monkeypatch, tmp_path, hook)++ written: list[str] = []++ class _Spy:+ def write(self, text: str) -> int:+ written.append(text)+ return len(text)++ def flush(self) -> None:+ pass++ monkeypatch.setattr(sys, "stdout", _Spy())++ loader = threading.Thread(target=load_state_dict_from_url, args=(self._URL,))+ loader.start()+ assert in_flight.wait(timeout=5), "download stub never ran"++ print("unrelated thread output") # printed while the transfer is in flight++ release.set()+ loader.join(timeout=10)++ assert "unrelated thread output" in "".join(written)diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.pyindex 8ff27c971..4938abd09 100644--- a/tests/feature/test_xfeat.py+++ b/tests/feature/test_xfeat.py@@ -220,6 +220,21 @@ class TestXFeat(BaseTester):assert len(out) == 1assert out[0]["keypoints"].shape[-1] == 2+ def test_pretrained_uses_kornia_downloader(self, monkeypatch):+ # Going through kornia.core.download keeps torch.hub's progress line off+ # stdout, which a bare torch.hub call would leak into doctests (#4005).+ calls = []++ def fake_download(url, **kwargs):+ calls.append((url, kwargs))+ return XFeat().net.state_dict()++ monkeypatch.setattr("kornia.feature.xfeat.load_state_dict_from_url", fake_download)+ model = XFeat.from_pretrained()++ assert calls == [(XFeat.weights_url, {"file_name": "xfeat.pt"})]+ assert not model.net.training+# ---------------------------------------------------------------------------# LighterGlue (xfeat config in LightGlue) testsdiff --git a/tests/test_doctest_downloads.py b/tests/test_doctest_downloads.pynew file mode 100644index 000000000..5cbc16d64--- /dev/null+++ b/tests/test_doctest_downloads.py@@ -0,0 +1,160 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""Tests for the doctest download guard (see #4005).++The guard itself is exercised for real by ``pixi run doctest``; these tests pin+the pieces that would otherwise only be checked by running that whole task.+"""++from __future__ import annotations++import importlib++import pytest+import torch++from testing.doctest_downloads import (+ _DOWNLOAD_PRIMITIVES,+ DOWNLOAD_ENV_VAR,+ downloads_allowed,+ install_download_guard,+ skip_reason,+)+++class _Blocked(Exception):+ """Raised by the test callback in place of a real download."""+++def _record_and_raise(sink: list[str]):+ def _callback(url: str) -> None:+ sink.append(url)+ raise _Blocked(url)++ return _callback+++class TestDownloadsAllowed:+ @pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes", " 1 "])+ def test_enabled(self, value: str) -> None:+ assert downloads_allowed({DOWNLOAD_ENV_VAR: value}) is True++ @pytest.mark.parametrize("value", ["", "0", "false", "no", "off"])+ def test_disabled(self, value: str) -> None:+ assert downloads_allowed({DOWNLOAD_ENV_VAR: value}) is False++ def test_unset_defaults_to_disabled(self) -> None:+ assert downloads_allowed({}) is False+++class TestInstallDownloadGuard:+ def test_patches_are_undone_by_monkeypatch(self, monkeypatch) -> None:+ original = torch.hub.download_url_to_file+ with monkeypatch.context() as m:+ install_download_guard(m.setattr, lambda url: pytest.fail("unreachable"))+ assert torch.hub.download_url_to_file is not original+ assert torch.hub.download_url_to_file is original++ def test_callback_receives_url(self, monkeypatch, tmp_path) -> None:+ seen: list[str] = []++ def record(url: str) -> None:+ seen.append(url)+ raise RuntimeError("blocked")++ with monkeypatch.context() as m:+ install_download_guard(m.setattr, record)+ with pytest.raises(RuntimeError, match="blocked"):+ torch.hub.download_url_to_file("http://example.com/w.pth", str(tmp_path / "w.pth"))++ assert seen == ["http://example.com/w.pth"]++ def test_unknown_module_is_skipped_not_raised(self, monkeypatch) -> None:+ with monkeypatch.context() as m:+ patched = install_download_guard(+ m.setattr,+ lambda url: pytest.fail("unreachable"),+ [("kornia.this_module_does_not_exist", "download")],+ )+ assert patched == []++ def test_returning_callback_is_an_error(self, monkeypatch, tmp_path) -> None:+ # A callback that returns would let the download silently proceed as a no-op.+ with monkeypatch.context() as m:+ install_download_guard(m.setattr, lambda url: None)+ with pytest.raises(AssertionError, match="returned instead of raising"):+ torch.hub.download_url_to_file("http://example.com/w.pth", str(tmp_path / "w.pth"))+++class TestPrimitivesStillExist:+ """The guard is only as good as its list of entry points.++ Each pair names a function that runs *only* on a cache miss. If an upstream+ rename makes one disappear, the guard silently stops covering that path and+ doctests quietly start downloading again, so pin them here.+ """++ @pytest.mark.parametrize(("module_name", "attribute"), _DOWNLOAD_PRIMITIVES)+ def test_primitive_is_importable(self, module_name: str, attribute: str) -> None:+ module = importlib.import_module(module_name)+ assert callable(getattr(module, attribute))++ def test_guard_covers_lightglue_downloader(self, monkeypatch, tmp_path) -> None:+ # lightglue_onnx binds download_url_to_file at import time, so patching+ # torch.hub alone would leave this path downloading.+ from kornia.feature.lightglue_onnx.utils.download import download_onnx_from_url++ seen: list[str] = []+ with monkeypatch.context() as m:+ install_download_guard(m.setattr, _record_and_raise(seen))+ with pytest.raises(_Blocked):+ download_onnx_from_url("http://example.com/model.onnx", model_dir=str(tmp_path))++ assert seen == ["http://example.com/model.onnx"]++ def test_guard_covers_onnx_cached_downloader(self, monkeypatch, tmp_path) -> None:+ from kornia.onnx.download import CachedDownloader++ seen: list[str] = []+ with monkeypatch.context() as m:+ install_download_guard(m.setattr, _record_and_raise(seen))+ with pytest.raises(_Blocked):+ CachedDownloader.download("http://example.com/model.onnx", str(tmp_path / "sub" / "model.onnx"))++ assert seen == ["http://example.com/model.onnx"]++ def test_cached_file_is_not_blocked(self, monkeypatch, tmp_path) -> None:+ # The guard patches primitives that run only on a cache miss, which is what+ # lets an already-cached doctest keep running for real.+ cached = tmp_path / "model.onnx"+ cached.write_bytes(b"already here")++ from kornia.onnx.download import CachedDownloader++ with monkeypatch.context() as m:+ install_download_guard(m.setattr, lambda url: pytest.fail("a cached file must not trigger a download"))+ CachedDownloader.download("http://example.com/model.onnx", str(cached))++ assert cached.read_bytes() == b"already here"+++class TestSkipReason:+ def test_names_the_url_and_the_opt_in(self) -> None:+ reason = skip_reason("http://example.com/w.pth")+ assert "http://example.com/w.pth" in reason+ assert DOWNLOAD_ENV_VAR in reason