Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test: resolve and enforce Ruff SIM117 (#5440)

Alexbd514229cb53
diff --git a/pyproject.toml b/pyproject.toml
index 84d87665f..f24400b79 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -229,6 +229,7 @@ select = [
"SIM103", # needless-bool
"SIM114", # if-with-same-arms
"SIM115", # open-file-with-context-handler
+ "SIM117", # multiple-with-statements
"SIM118", # in-dict-keys
"SIM201", # negate-equal-op
"SIM210", # if-expr-with-true-false
diff --git a/tests/core/test_download.py b/tests/core/test_download.py
index 42aa7215c..da8724f18 100644
--- a/tests/core/test_download.py
+++ b/tests/core/test_download.py
@@ -144,19 +144,20 @@ class TestLoadStateDictFromUrl:
raise OSError("primary down")
return self._SD
- with patch(self._MOCK_TARGET, side_effect=side_effect) as mock:
- with warnings.catch_warnings(record=True) as w:
- warnings.simplefilter("always")
- result = load_state_dict_from_url([primary, fallback])
+ with patch(self._MOCK_TARGET, side_effect=side_effect) as mock, warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ result = load_state_dict_from_url([primary, fallback])
assert result == self._SD
assert mock.call_count == 2
assert any("primary down" in str(warning.message) for warning in w)
def test_all_fail_raises_runtime_error(self) -> None:
- with patch(self._MOCK_TARGET, side_effect=OSError("down")):
- with pytest.raises(RuntimeError, match="Failed to load weights from all 2 source"):
- load_state_dict_from_url(["http://a.com/m.pth", "http://b.com/m.pth"])
+ with (
+ patch(self._MOCK_TARGET, side_effect=OSError("down")),
+ pytest.raises(RuntimeError, match="Failed to load weights from all 2 source"),
+ ):
+ load_state_dict_from_url(["http://a.com/m.pth", "http://b.com/m.pth"])
def test_file_name_pinned_to_primary(self) -> None:
primary = "http://primary.example.com/weights-abc123.pth"
@@ -167,10 +168,9 @@ class TestLoadStateDictFromUrl:
raise OSError("primary down")
return self._SD
- with patch(self._MOCK_TARGET, side_effect=side_effect) as mock:
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- load_state_dict_from_url([primary, fallback])
+ with patch(self._MOCK_TARGET, side_effect=side_effect) as mock, warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ load_state_dict_from_url([primary, fallback])
# fallback call must carry the primary's filename, not the fallback's
fallback_call = mock.call_args_list[1]
@@ -185,10 +185,9 @@ class TestLoadStateDictFromUrl:
raise OSError("primary down")
return self._SD
- with patch(self._MOCK_TARGET, side_effect=side_effect) as mock:
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- load_state_dict_from_url([primary, fallback], file_name="custom.pth")
+ with patch(self._MOCK_TARGET, side_effect=side_effect) as mock, warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ load_state_dict_from_url([primary, fallback], file_name="custom.pth")
for c in mock.call_args_list:
assert c.kwargs.get("file_name") == "custom.pth"
@@ -477,12 +476,11 @@ class TestPoisonedCacheEntry:
def always_fails(url: str, **kwargs: object) -> dict:
raise RuntimeError("Attempting to deserialize object on a CUDA device")
- with patch(self._MOCK_TARGET, side_effect=always_fails):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- for _ in range(3):
- with pytest.raises(RuntimeError):
- load_state_dict_from_url([self._PRIMARY, self._FALLBACK])
+ with patch(self._MOCK_TARGET, side_effect=always_fails), warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ for _ in range(3):
+ with pytest.raises(RuntimeError):
+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])
# One refetch in total, not one per source per call.
assert transfers == [self._FALLBACK]
@@ -525,20 +523,19 @@ class TestPoisonedCacheEntry:
def always_fails(url: str, **kwargs: object) -> dict:
raise RuntimeError("Attempting to deserialize object on a CUDA device")
- with patch(self._MOCK_TARGET, side_effect=always_fails):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- with pytest.raises(RuntimeError):
- load_state_dict_from_url(self._PRIMARY)
+ with patch(self._MOCK_TARGET, side_effect=always_fails), warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ with pytest.raises(RuntimeError):
+ load_state_dict_from_url(self._PRIMARY)
- # Within the failing call itself: the discard was paid for by a
- # refetch, so the caller ends it with the entry it started with.
- assert transfers == [self._PRIMARY]
- assert cached.exists()
+ # Within the failing call itself: the discard was paid for by a
+ # refetch, so the caller ends it with the entry it started with.
+ assert transfers == [self._PRIMARY]
+ assert cached.exists()
- for _ in range(2):
- with pytest.raises(RuntimeError):
- load_state_dict_from_url(self._PRIMARY)
+ for _ in range(2):
+ with pytest.raises(RuntimeError):
+ load_state_dict_from_url(self._PRIMARY)
# And the bound holds: one refetch per path per process, not one per call.
assert transfers == [self._PRIMARY]
@@ -571,11 +568,10 @@ class TestPoisonedCacheEntry:
def always_fails(url: str, **kwargs: object) -> dict:
raise RuntimeError("Attempting to deserialize object on a CUDA device")
- with patch(self._MOCK_TARGET, side_effect=always_fails):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- with pytest.raises(RuntimeError):
- load_state_dict_from_url([self._PRIMARY, self._FALLBACK])
+ with patch(self._MOCK_TARGET, side_effect=always_fails), warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ with pytest.raises(RuntimeError):
+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])
# The fallback really was tried, and each of its transient failures retried;
# then, since nothing had replaced the path, the discarded primary was given
@@ -609,11 +605,10 @@ class TestPoisonedCacheEntry:
def always_fails(url: str, **kwargs: object) -> dict:
raise RuntimeError("Attempting to deserialize object on a CUDA device")
- with patch(self._MOCK_TARGET, side_effect=always_fails):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- with pytest.raises(RuntimeError) as excinfo:
- load_state_dict_from_url(self._PRIMARY)
+ with patch(self._MOCK_TARGET, side_effect=always_fails), warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ with pytest.raises(RuntimeError) as excinfo:
+ load_state_dict_from_url(self._PRIMARY)
message = str(excinfo.value)
assert "Last error: RuntimeError: Attempting to deserialize object on a CUDA device" in message
@@ -680,11 +675,10 @@ class TestPoisonedCacheEntry:
def cuda_on_a_cpu_build(url: str, **kwargs: object) -> dict:
raise RuntimeError("Attempting to deserialize object on a CUDA device")
- with patch(self._MOCK_TARGET, side_effect=cuda_on_a_cpu_build):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- with pytest.raises(RuntimeError):
- load_state_dict_from_url([self._PRIMARY, self._FALLBACK])
+ with patch(self._MOCK_TARGET, side_effect=cuda_on_a_cpu_build), warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ with pytest.raises(RuntimeError):
+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])
assert cached.read_bytes() == before
assert not list(cached.parent.glob("*" + download_mod._QUARANTINE_SUFFIX))
@@ -790,12 +784,11 @@ class TestPoisonedCacheEntry:
def always_fails(url: str, **kwargs: object) -> dict:
raise RuntimeError("Attempting to deserialize object on a CUDA device")
- with patch(self._MOCK_TARGET, side_effect=always_fails):
- with warnings.catch_warnings(record=True):
- warnings.simplefilter("always")
- for _ in range(3):
- with pytest.raises(RuntimeError):
- load_state_dict_from_url(self._PRIMARY)
+ with patch(self._MOCK_TARGET, side_effect=always_fails), warnings.catch_warnings(record=True):
+ warnings.simplefilter("always")
+ for _ in range(3):
+ with pytest.raises(RuntimeError):
+ load_state_dict_from_url(self._PRIMARY)
# The first call's transfer, then the one discard this path is allowed.
assert transfers == [self._PRIMARY, self._PRIMARY]
@@ -1309,9 +1302,11 @@ class TestWeightsOnly(BaseTester):
)
def test_weights_only_is_true_unless_the_caller_passes_false(self, kwargs, forwarded) -> None:
# ``None`` counts as omitted: torch 2.5 reads it as ``False``.
- with patch("kornia.core.download._prefetch_to_cache", return_value=False):
- with patch("kornia.core.download.torch.hub.load_state_dict_from_url", return_value={}) as mock:
- load_state_dict_from_url("http://example.com/model.pth", **kwargs)
+ with (
+ patch("kornia.core.download._prefetch_to_cache", return_value=False),
+ patch("kornia.core.download.torch.hub.load_state_dict_from_url", return_value={}) as mock,
+ ):
+ load_state_dict_from_url("http://example.com/model.pth", **kwargs)
mock.assert_called_once_with("http://example.com/model.pth", weights_only=forwarded)
@@ -2416,9 +2411,11 @@ class TestTruncatedTransfer:
responses["/t.bin"] = (1000, b"z" * 10)
self._partial_in_use(monkeypatch, code)
- with pytest.warns(UserWarning, match="Could not remove the temporary download file"):
- with pytest.raises(download_mod._TruncatedTransfer):
- download_mod._download_url_to_file(url("/t.bin"), str(tmp_path / "t.bin"), progress=False, timeout=5.0)
+ with (
+ pytest.warns(UserWarning, match="Could not remove the temporary download file"),
+ pytest.raises(download_mod._TruncatedTransfer),
+ ):
+ download_mod._download_url_to_file(url("/t.bin"), str(tmp_path / "t.bin"), progress=False, timeout=5.0)
assert [p.suffix for p in tmp_path.iterdir()] == [".partial"]
diff --git a/tests/feature/test_lightglue.py b/tests/feature/test_lightglue.py
index da5d713b0..b29d765c0 100644
--- a/tests/feature/test_lightglue.py
+++ b/tests/feature/test_lightglue.py
@@ -449,9 +449,8 @@ class TestLightGlue(BaseTester):
seen["device_type"] = kwargs.get("device_type", "")
return real_ac(*args, **kwargs)
- with unittest.mock.patch("kornia.feature.lightglue.torch.autocast", side_effect=_spy):
- with torch.no_grad():
- out = lg(data)
+ with unittest.mock.patch("kornia.feature.lightglue.torch.autocast", side_effect=_spy), torch.no_grad():
+ out = lg(data)
assert seen["device_type"] == data["image0"]["keypoints"].device.type
assert "matches0" in out
diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.py
index 05c28b66a..42c3d0bcc 100644
--- a/tests/models/test_siglip2.py
+++ b/tests/models/test_siglip2.py
@@ -108,9 +108,9 @@ class TestSigLip2Builder:
with (
patch.object(siglip2_builder, "download_hf_file", return_value="cached.safetensors"),
patch.object(siglip2_builder, "load_safetensors", side_effect=FileNotFoundError("gone")),
+ pytest.raises(FileNotFoundError, match=r"Could not find model\.safetensors for google/nope"),
):
- with pytest.raises(FileNotFoundError, match=r"Could not find model\.safetensors for google/nope"):
- siglip2_builder._download_weights("google/nope", None)
+ siglip2_builder._download_weights("google/nope", None)
class TestSigLip2Model(BaseTester):
diff --git a/tests/onnx/test_download.py b/tests/onnx/test_download.py
index 4ff21c99c..8752179d5 100644
--- a/tests/onnx/test_download.py
+++ b/tests/onnx/test_download.py
@@ -135,9 +135,8 @@ class TestCachedDownloader:
Path(filename).write_bytes(b"partial")
raise KeyboardInterrupt
- with mock.patch("urllib.request.urlretrieve", side_effect=interrupted):
- with pytest.raises(KeyboardInterrupt):
- CachedDownloader.download("http://127.0.0.1:9/model.pth", str(path))
+ with mock.patch("urllib.request.urlretrieve", side_effect=interrupted), pytest.raises(KeyboardInterrupt):
+ CachedDownloader.download("http://127.0.0.1:9/model.pth", str(path))
assert list(path.parent.iterdir()) == []
diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.py
index 4f82e8940..af1aa782f 100644
--- a/tests/onnx/test_utils.py
+++ b/tests/onnx/test_utils.py
@@ -144,12 +144,14 @@ class TestONNXLoader:
from unittest import mock
url = "https://huggingface.co/api/models/kornia/ONNX_models/tree/main/operators"
- with mock.patch(
- "kornia.onnx.utils.urlopen",
- side_effect=urllib.error.HTTPError(url, 404, "Not Found", {}, None),
+ with (
+ mock.patch(
+ "kornia.onnx.utils.urlopen",
+ side_effect=urllib.error.HTTPError(url, 404, "Not Found", {}, None),
+ ),
+ pytest.raises(ValueError, match="Failed to fetch repository contents"),
):
- with pytest.raises(ValueError, match="Failed to fetch repository contents"):
- ONNXLoader._fetch_repo_contents("operators")
+ ONNXLoader._fetch_repo_contents("operators")
def test_list_operators(self, capsys):
import os