π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
# 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.
#
from __future__ import annotations
import http.client
import http.server
import os
import sys
import threading
import time
from pathlib import Path
from unittest import mock
from urllib.error import ContentTooShortError, HTTPError
import pytest
from kornia.onnx.download import CachedDownloader
pytestmark = pytest.mark.device_agnostic
@pytest.fixture
def download_server(monkeypatch):
"""Serve bytes with a controllable Content-Length to exercise short transfers."""
for var in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("no_proxy", "127.0.0.1")
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
responses: dict[str, tuple[bytes, int]] = {}
hits: list[str] = []
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None:
hits.append(self.path)
if self.path not in responses:
self.send_error(404)
return
body, length = responses[self.path]
self.send_response(200)
self.send_header("Content-Length", str(length))
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args: object) -> None:
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield responses, f"http://127.0.0.1:{server.server_port}", hits
finally:
server.shutdown()
server.server_close()
thread.join()
class TestCachedDownloader:
@pytest.mark.parametrize("absolute", [False, True])
def test_download_preserves_cache_directory(self, download_server, monkeypatch, tmp_path, absolute):
monkeypatch.chdir(tmp_path)
responses, base_url, hits = download_server
responses["/model"] = (b"weights", 7)
cache_dir = str(tmp_path / "cache") if absolute else "cache"
path = CachedDownloader.download_to_cache(
f"{base_url}/model", os.path.join("operators", "model"), cache_dir=cache_dir, suffix=".pth"
)
assert path == os.path.join(cache_dir, "operators", "model.pth")
assert (tmp_path / "cache" / "operators" / "model.pth").read_bytes() == b"weights"
assert hits == ["/model"]
def test_download_expands_user_directory(self, download_server, monkeypatch, tmp_path):
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
monkeypatch.chdir(tmp_path) # without the expansion, a literal "~" directory lands in the working directory
responses, base_url, _ = download_server
responses["/model"] = (b"weights", 7)
path = CachedDownloader.download_to_cache(f"{base_url}/model", "model", cache_dir="~/cache", suffix=".onnx")
assert Path(path) == tmp_path / "cache" / "model.onnx"
assert Path(path).read_bytes() == b"weights"
def test_download_expands_user_file_path(self, download_server, monkeypatch, tmp_path):
# the cache check and the directory creation must see the expanded path, or every call downloads again
# and a literal "~" directory appears in the working directory
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("USERPROFILE", str(tmp_path))
(tmp_path / "cwd").mkdir()
monkeypatch.chdir(tmp_path / "cwd")
responses, base_url, hits = download_server
responses["/model"] = (b"weights", 7)
for _ in range(2):
CachedDownloader.download(f"{base_url}/model", "~/cache/model.onnx")
assert (tmp_path / "cache" / "model.onnx").read_bytes() == b"weights"
assert hits == ["/model"]
assert list((tmp_path / "cwd").iterdir()) == []
def test_path_without_a_directory_is_downloaded_into_the_working_directory(
self, download_server, monkeypatch, tmp_path
):
# #5903: os.makedirs("") raised FileNotFoundError before any request
monkeypatch.chdir(tmp_path)
responses, base_url, hits = download_server
responses["/model"] = (b"weights", 7)
CachedDownloader.download(f"{base_url}/model", "plain.pth")
path = CachedDownloader.download_to_cache(f"{base_url}/model", "m", cache_dir="", suffix=".pth")
assert path == "m.pth"
assert (tmp_path / "plain.pth").read_bytes() == b"weights"
assert (tmp_path / "m.pth").read_bytes() == b"weights"
assert hits == ["/model", "/model"]
def test_unknown_keyword_raises(self, monkeypatch, tmp_path):
# #5903: a misspelt keyword was dropped, and the file was cached in the default directory under another name
monkeypatch.chdir(tmp_path)
url = "http://127.0.0.1:9/model"
with mock.patch("kornia.core.download._download_url_to_file") as transfer:
with pytest.raises(TypeError, match="cachedir"):
CachedDownloader.download_to_cache(url, "k", cachedir="mine", suffix=".pth")
with pytest.raises(TypeError, match="suffx"):
CachedDownloader.download_to_cache(url, "k", cache_dir="mine", suffx=".pth")
transfer.assert_not_called()
assert list(tmp_path.iterdir()) == []
@pytest.mark.parametrize(
"name",
["../../escape", "a/../../../escape", "/abs/escape", os.path.abspath("escape"), "", ".", "dir/", "a//b"],
)
def test_name_that_is_not_a_relative_path_inside_the_cache_raises(self, name, monkeypatch, tmp_path):
# #5903: "../../escape" was written two levels above cache_dir, although the name's directory components are
# documented to stay under the cache directory
monkeypatch.chdir(tmp_path)
with (
mock.patch("kornia.core.download._download_url_to_file") as transfer,
pytest.raises(ValueError, match="relative path inside the cache directory"),
):
CachedDownloader.download_to_cache("http://127.0.0.1:9/model", name, cache_dir="cache/a/b", suffix=".pth")
transfer.assert_not_called()
assert list(tmp_path.iterdir()) == []
@pytest.mark.parametrize("suffix", ["/../../../escape", "/x", "/"])
def test_suffix_that_leaves_the_file_name_raises(self, suffix, monkeypatch, tmp_path):
# the suffix is appended after the name is checked, so it is checked on its own: "model" + "/../../../escape"
# would put the file three levels above cache_dir
monkeypatch.chdir(tmp_path)
with (
mock.patch("kornia.core.download._download_url_to_file") as transfer,
pytest.raises(ValueError, match="suffix"),
):
CachedDownloader.download_to_cache(
"http://127.0.0.1:9/model", "model", cache_dir="cache/a/b", suffix=suffix
)
transfer.assert_not_called()
assert list(tmp_path.iterdir()) == []
def test_short_transfer_is_not_cached(self, download_server, monkeypatch, tmp_path):
monkeypatch.chdir(tmp_path)
responses, base_url, hits = download_server
payload = bytes(range(256)) * 40
responses["/model"] = (payload[: len(payload) // 2], len(payload))
url = f"{base_url}/model"
with pytest.raises(ContentTooShortError, match=r"got only 5120 out of 10240 bytes"):
CachedDownloader.download_to_cache(url, "model", cache_dir="cache", suffix=".pth")
assert list((tmp_path / "cache").iterdir()) == []
responses["/model"] = (payload, len(payload))
path = CachedDownloader.download_to_cache(url, "model", cache_dir="cache", suffix=".pth")
assert Path(path).read_bytes() == payload
assert CachedDownloader.download_to_cache(url, "model", cache_dir="cache", suffix=".pth") == path
assert hits == ["/model", "/model"]
assert list((tmp_path / "cache").iterdir()) == [tmp_path / "cache" / "model.pth"]
def test_other_incomplete_read_propagates(self, tmp_path):
# only a body shorter than its Content-Length becomes ContentTooShortError; any other IncompleteRead (a
# chunked body cut mid-chunk) propagates unchanged, as it did from urlretrieve
path = tmp_path / "cache" / "model.onnx"
cut = http.client.IncompleteRead(b"")
with (
mock.patch("kornia.core.download._download_url_to_file", side_effect=cut),
pytest.raises(http.client.IncompleteRead) as exc_info,
):
CachedDownloader.download("http://127.0.0.1:9/model.onnx", str(path))
assert exc_info.value is cut
def test_stalled_transfer_obeys_timeout_environment_variable(self, monkeypatch, tmp_path):
for var in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("no_proxy", "127.0.0.1")
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", "0.2")
stalled, release = threading.Event(), threading.Event()
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None:
self.send_response(200)
self.send_header("Content-Length", "100")
self.end_headers()
self.wfile.write(b"x" * 10)
self.wfile.flush()
stalled.set()
release.wait(5)
def log_message(self, *args: object) -> None:
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
server_thread = threading.Thread(target=server.serve_forever, daemon=True)
server_thread.start()
path = tmp_path / "cache" / "model.onnx"
url = f"http://127.0.0.1:{server.server_port}/model.onnx"
errors: list[BaseException] = []
def download() -> None:
try:
CachedDownloader.download(url, str(path))
except BaseException as exc:
errors.append(exc)
worker = threading.Thread(target=download, daemon=True)
try:
worker.start()
assert stalled.wait(5), "the server did not start the transfer"
worker.join(5)
assert not worker.is_alive(), "download remained blocked past KORNIA_DOWNLOAD_TIMEOUT"
finally:
release.set()
worker.join(5)
server.shutdown()
server.server_close()
server_thread.join(5)
assert len(errors) == 1, errors
assert isinstance(errors[0], TimeoutError), errors
assert not path.exists()
assert not list(path.parent.glob("*.partial"))
def test_http_error_does_not_leave_cache_entry(self, download_server, tmp_path):
_, base_url, _ = download_server
path = tmp_path / "cache" / "missing.pth"
with pytest.raises(ValueError, match="Error in resolving") as exc:
CachedDownloader.download(f"{base_url}/missing", str(path))
assert isinstance(exc.value.__cause__, HTTPError)
assert list(path.parent.iterdir()) == []
def test_download_disabled(self, download_server, tmp_path):
_, base_url, hits = download_server
with pytest.raises(ValueError, match="not found"):
CachedDownloader.download(f"{base_url}/model", str(tmp_path / "missing.pth"), False)
assert hits == []
@pytest.mark.parametrize("download", [False, True])
def test_existing_cache_entry_is_preserved(self, download_server, tmp_path, download):
_, base_url, hits = download_server
path = tmp_path / "model.pth"
path.write_bytes(b"cached weights")
CachedDownloader.download(f"{base_url}/missing", str(path), download)
assert path.read_bytes() == b"cached weights"
assert hits == []
def test_interrupted_transfer_leaves_no_file(self, tmp_path):
# KeyboardInterrupt is a BaseException: the cleanup must not be an `except Exception`. The transfer's
# temporary file already exists when the request is opened, so interrupting there must remove it.
path = tmp_path / "cache" / "model.pth"
with (
mock.patch("kornia.core.download.urlopen", side_effect=KeyboardInterrupt),
pytest.raises(KeyboardInterrupt),
):
CachedDownloader.download("http://127.0.0.1:9/model.pth", str(path))
assert list(path.parent.iterdir()) == []
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits")
def test_cache_file_has_default_permissions(self, download_server, tmp_path):
# a downloaded file gets the permissions of any new file (umask applied), not mkstemp's owner-only 0o600,
# so a cache filled by one user stays readable by another
responses, base_url, _ = download_server
responses["/model.pth"] = (b"weights", 7)
path = tmp_path / "cache" / "model.pth"
reference = tmp_path / "reference"
reference.write_bytes(b"")
CachedDownloader.download(f"{base_url}/model.pth", str(path))
assert path.stat().st_mode == reference.stat().st_mode
def test_partial_transfer_is_not_visible_at_cache_path(self, monkeypatch, tmp_path):
# a second caller checking the cache mid-transfer must not find (and return) a half-written file
for var in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("no_proxy", "127.0.0.1")
monkeypatch.setenv("NO_PROXY", "127.0.0.1")
payload = bytes(range(256)) * 400
half_sent, release = threading.Event(), threading.Event()
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None:
self.send_response(200)
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload[: len(payload) // 2])
self.wfile.flush()
half_sent.set()
release.wait(10)
self.wfile.write(payload[len(payload) // 2 :])
def log_message(self, *args: object) -> None:
pass
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
path = tmp_path / "cache" / "model.pth"
url = f"http://127.0.0.1:{server.server_port}/model.pth"
worker = threading.Thread(target=CachedDownloader.download, args=(url, str(path)))
try:
worker.start()
assert half_sent.wait(10)
deadline = time.monotonic() + 10
while not (path.parent.exists() and any(p != path for p in path.parent.iterdir())):
assert time.monotonic() < deadline, "the transfer never started writing"
time.sleep(0.01)
assert not path.exists()
finally:
release.set()
worker.join(10)
server.shutdown()
server.server_close()
assert path.read_bytes() == payload
class TestForceDownload:
@staticmethod
def _cache(url: str, tmp_path: Path, **kwargs) -> str:
return CachedDownloader.download_to_cache(url, "model", cache_dir=str(tmp_path), suffix=".pth", **kwargs)
def test_a_cached_file_is_fetched_again_only_when_forced(self, download_server, tmp_path):
responses, base_url, hits = download_server
url = f"{base_url}/model"
responses["/model"] = (b"old", 3)
path = self._cache(url, tmp_path)
responses["/model"] = (b"new weights", 11) # the file changed on the server
assert self._cache(url, tmp_path) == path
assert self._cache(url, tmp_path, force_download=False) == path
assert Path(path).read_bytes() == b"old" # a cached file is used as it is
assert hits == ["/model"]
assert self._cache(url, tmp_path, force_download=True) == path
assert Path(path).read_bytes() == b"new weights"
assert hits == ["/model", "/model"]
assert [p.name for p in tmp_path.iterdir()] == ["model.pth"] # no partial file is left beside it
assert self._cache(url, tmp_path) == path # the new file is the cached one
assert Path(path).read_bytes() == b"new weights"
assert hits == ["/model", "/model"]
def test_forcing_a_file_that_is_not_cached_downloads_it_once(self, download_server, tmp_path):
responses, base_url, hits = download_server
responses["/model"] = (b"weights", 7)
path = self._cache(f"{base_url}/model", tmp_path, force_download=True)
assert Path(path).read_bytes() == b"weights"
assert hits == ["/model"]
def test_download_replaces_the_file_when_forced(self, download_server, tmp_path):
responses, base_url, hits = download_server
path = tmp_path / "plain.pth"
path.write_bytes(b"damaged")
responses["/model"] = (b"weights", 7)
CachedDownloader.download(f"{base_url}/model", str(path))
assert path.read_bytes() == b"damaged"
assert hits == []
CachedDownloader.download(f"{base_url}/model", str(path), force_download=True)
assert path.read_bytes() == b"weights"
assert hits == ["/model"]
@pytest.mark.parametrize("failure", ["http_error", "truncated"])
def test_a_failed_fetch_leaves_the_cached_file_as_it_was(self, download_server, tmp_path, failure):
responses, base_url, hits = download_server
url = f"{base_url}/model"
responses["/model"] = (b"old", 3)
path = self._cache(url, tmp_path)
if failure == "http_error":
del responses["/model"]
expected = ValueError # the server answers 404
else:
responses["/model"] = (b"new", 100) # the body ends before its Content-Length
expected = ContentTooShortError
with pytest.raises(expected):
self._cache(url, tmp_path, force_download=True)
assert hits == ["/model", "/model"]
assert Path(path).read_bytes() == b"old"
assert [p.name for p in tmp_path.iterdir()] == ["model.pth"]
def test_forcing_without_downloading_raises_before_any_fetch(self, download_server, tmp_path):
responses, base_url, hits = download_server
url = f"{base_url}/model"
responses["/model"] = (b"old", 3)
path = self._cache(url, tmp_path)
with pytest.raises(ValueError, match=r"force_download=True.*download=True"):
self._cache(url, tmp_path, download=False, force_download=True)
with pytest.raises(ValueError, match=r"force_download=True.*download=True"):
CachedDownloader.download(url, path, download_if_not_exists=False, force_download=True)
assert hits == ["/model"]
assert Path(path).read_bytes() == b"old"
def test_force_download_is_keyword_only(self, tmp_path):
with pytest.raises(TypeError):
CachedDownloader.download_to_cache("http://127.0.0.1:9/model", "m", True, True) # type: ignore[misc]
with pytest.raises(TypeError):
CachedDownloader.download("http://127.0.0.1:9/model", str(tmp_path / "m"), True, True) # type: ignore[misc]
def test_a_download_override_that_predates_the_keyword_keeps_working(self, tmp_path):
# CachedDownloader.download is a public classmethod, so a subclass may override it with the old signature:
# download_to_cache hands it force_download only when it is set
calls = []
class Legacy(CachedDownloader):
@classmethod
def download(cls, url, file_path, download_if_not_exists=True):
calls.append((url, file_path, download_if_not_exists))
path = Legacy.download_to_cache("http://example.com/m", "m", cache_dir=str(tmp_path), suffix=".pth")
assert calls == [("http://example.com/m", path, True)]
with pytest.raises(TypeError, match="force_download"):
Legacy.download_to_cache("http://example.com/m", "m", cache_dir=str(tmp_path), force_download=True)