π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
test: resolve and enforce Ruff PT013, PT014, and PT017 (#4851)
Daniele Loru2fa713d0ce6e
diff --git a/conftest.py b/conftest.pyindex 7c6237390..a8b07fe32 100644--- a/conftest.py+++ b/conftest.py@@ -29,12 +29,6 @@ import numpy as npimport pytestimport torch-try:- from pytest import CallInfo, TestReport # public since pytest 7.x-except ImportError: # pragma: no cover- from _pytest.reports import TestReport # type: ignore[no-redef]- from _pytest.runner import CallInfo # type: ignore[no-redef]-import korniafrom kornia.core.download import load_state_dict_from_url@@ -838,8 +832,8 @@ def pytest_runtest_protocol(item, nextitem):outcome = "failed"longrepr = _extract_failure_output(output)- def _report(when: str, out: str, rep_longrepr, dur: float = 0.0) -> TestReport:- return TestReport(+ def _report(when: str, out: str, rep_longrepr, dur: float = 0.0) -> pytest.TestReport:+ return pytest.TestReport(nodeid=item.nodeid,location=item.location,keywords=dict(item.keywords),@@ -860,7 +854,7 @@ def pytest_runtest_protocol(item, nextitem):# Capture finalizer failures as teardown errors rather than aborting the runner.if item.session.shouldfail or item.session.shouldstop:nextitem = None- teardown = CallInfo.from_call(+ teardown = pytest.CallInfo.from_call(lambda: item.session._setupstate.teardown_exact(nextitem),when="teardown",reraise=(KeyboardInterrupt, pytest.exit.Exception),diff --git a/pyproject.toml b/pyproject.tomlindex 3457c7545..1a994527c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -42,7 +42,7 @@ dev = ["kornia[onnx]","pillow","pre-commit",- "pytest",+ "pytest>=7","pytest-timeout","setuptools", # torch.compile / triton on py3.11 + torch 2.5.1, which does not declare it there]@@ -212,6 +212,9 @@ select = ["NPY", # NumPy-specific rules"PIE", # flake8-pie"PL", # Pylint+ "PT013", # flake8-pytest-style: pytest imports+ "PT014", # flake8-pytest-style: duplicate parametrized cases+ "PT017", # flake8-pytest-style: assertions in exception handlers"PYI", # flake8-pyi"RET", # flake8-return"RSE", # flake8-raisediff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex 08d8ed8ce..de4381667 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -193,8 +193,6 @@ call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_dcall builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma0-5]call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma1-11]call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma1-5]-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma2-11]-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma2-5]call builtins.AssertionError tests/filters/test_otsu_thresholding.py::TestOtsuThreshold::test_gradual_threshold[cpu-float16]call builtins.AssertionError tests/filters/test_otsu_thresholding.py::test_mask[cpu-float16]call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[cpu-float16-20]diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex ac74f4c30..e19a9383a 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4564,8 +4564,8 @@ class TestRandomSaltAndPepperNoise(BaseTester):with pytest.raises(ValueError, match="amount must be a tuple or a float"):RandomSaltAndPepperNoise(amount=[0.01, 0.06])- @pytest.mark.parametrize("batch_shape", [1, 3, 3, 5])- @pytest.mark.parametrize("channel_shape", [1, 1, 3, 3])+ @pytest.mark.parametrize("batch_shape", [1, 3, 5])+ @pytest.mark.parametrize("channel_shape", [1, 3])def test_cardinality(self, batch_shape, channel_shape, device, dtype):input_tensor = torch.ones(batch_shape, channel_shape, 16, 16, device=device, dtype=dtype) * 0.5transform = RandomSaltAndPepperNoise(p=1.0)diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.pyindex 2e066dc0b..3fa51004b 100644--- a/tests/augmentation/test_random_generator_3d.py+++ b/tests/augmentation/test_random_generator_3d.py@@ -236,7 +236,6 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):(100, 100, -100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),# (100, 100, 100, torch.tensor([0, 9]), None, None, None),(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1]), None, None),(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([[0.2, 0.2, 0.2]]), None),(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([0.2]), None),diff --git a/tests/enhance/test_core.py b/tests/enhance/test_core.pyindex 8a4c24a08..1a42bb578 100644--- a/tests/enhance/test_core.py+++ b/tests/enhance/test_core.py@@ -91,7 +91,7 @@ class TestAddWeighted(BaseTester):with pytest.raises(Exception):TestAddWeighted.fcn(src1, 1.0, src2, 1.0, 0.0)- @pytest.mark.parametrize("size1, size2", [((2, 3, 5, 5), (2, 3, 5, 5)), ((2, 3, 5, 5), (2, 3, 5, 5))])+ @pytest.mark.parametrize("size1, size2", [((2, 3, 5, 5), (2, 3, 5, 5))])@pytest.mark.parametrize("alpha", [torch.randn(2, 3, 5, 5), 1.0])@pytest.mark.parametrize("beta", [torch.randn(2, 3, 5, 5), 1.0])@pytest.mark.parametrize("gamma", [torch.randn(2, 3, 5, 5), 1.0])diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex 960876af6..4c0844ff7 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -121,7 +121,7 @@ def test_get_gaussian_kernel1d_float(window_size, sigma, device, dtype):@pytest.mark.parametrize("window_size", [5, 11])[email protected]("sigma", [[[1.5]], [[1.5], [5.0]], [[1.5], [5.0]]])[email protected]("sigma", [[[1.5]], [[1.5], [5.0]]])def test_get_gaussian_kernel1d_tensor(window_size, sigma, device, dtype):sigma = torch.tensor(sigma, device=device, dtype=dtype)bs = sigma.shape[0]@@ -198,7 +198,7 @@ def test_get_discrete_gaussian_erf_kernel1d_float(window_size, sigma, device, dt@pytest.mark.parametrize("window_size", [5, 11])[email protected]("sigma", [[[1.5]], [[1.5], [5.0]], [[1.5], [5.0]]])[email protected]("sigma", [[[1.5]], [[1.5], [5.0]]])def test_get_discrete_gaussian_erf_kernel1d_tensor(window_size, sigma, device, dtype):sigma = torch.tensor(sigma, device=device, dtype=dtype)bs = sigma.shape[0]@@ -221,7 +221,7 @@ def test_get_gaussian_discrete_kernel1d_float(window_size, sigma, device, dtype)@pytest.mark.parametrize("window_size", [5, 11])[email protected]("sigma", [[[1.5]], [[1.5], [5.0]], [[1.5], [5.0]]])[email protected]("sigma", [[[1.5]], [[1.5], [5.0]]])def test_get_gaussian_discrete_kernel1d_tensor(window_size, sigma, device, dtype):sigma = torch.tensor(sigma, device=device, dtype=dtype)bs = sigma.shape[0]diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.pyindex 7f1c2c38c..3cb167f23 100644--- a/tests/geometry/test_conversions.py+++ b/tests/geometry/test_conversions.py@@ -265,18 +265,14 @@ def test_skip_probe_re_raises_everything_it_cannot_identify(monkeypatch):raise RuntimeError("kornia-side regression")def assert_the_injected_failure_propagates(case: str) -> None:- # NOT pytest.raises: a skip is a BaseException that pytest.raises(RuntimeError) lets- # through, so the regression this pin exists to catch would turn the pin itself yellow- # instead of red -- the same going-quiet the helper's own over-eager skip causes, one level- # up.+ # Requiring RuntimeError still lets pytest.skip escape, so catch that skip separately+ # and fail the pin. No error, a different error, or the wrong RuntimeError also fails.try:- _skip_if_closed_form_inverse_unavailable(cpu, torch.float32)+ with pytest.raises(RuntimeError) as excinfo:+ _skip_if_closed_form_inverse_unavailable(cpu, torch.float32)except pytest.skip.Exception as skipped:raise AssertionError(f"{case}: an unrelated failure was skipped over: {skipped}") from skipped- except RuntimeError as err:- assert "kornia-side regression" in str(err), f"{case}: wrong error re-raised: {err}"- else:- raise AssertionError(f"{case}: the injected failure did not propagate at all")+ assert "kornia-side regression" in str(excinfo.value), f"{case}: wrong error re-raised: {excinfo.value}"# Cleared again: case A memoized (cpu, float32) as healthy, and C/D have to reach the body._healthy_closed_form_inverse_routes.clear()@@ -4215,10 +4211,15 @@ class TestNormalizeHomography(BaseTester):identity = torch.eye(3, device=device, dtype=torch.int64)[None]op = getattr(kornia.geometry.conversions, op_name)+ # Both a torch error and an all-NaN result are valid backend outcomes. Keep+ # both branches, but check a caught error after the except block for PT017.+ error: Exception | None = Nonetry:out = op(identity, (4, 5), (8, 9))except Exception as err:- assert not _raised_by_a_kornia_guard(err), (+ error = err+ if error is not None:+ assert not _raised_by_a_kornia_guard(error), (f"kornia#3959: {op_name} now rejects integer input in a guard of its own -- update the warning")else:@@ -4682,11 +4683,16 @@ class TestRt2Extrinsics(BaseTester):(camtoworld_to_worldtocam_Rt, (rotation, translation)),(worldtocam_to_camtoworld_Rt, (rotation, translation)),]+ # Preserve both backend outcomes: an int64 result or a torch error is valid,+ # while a new Kornia guard must still fail the pin after the except block.for op, args in accepting:+ error: Exception | None = Nonetry:out = op(*args)except Exception as err:- assert not _raised_by_a_kornia_guard(err), (+ error = err+ if error is not None:+ assert not _raised_by_a_kornia_guard(error), (f"kornia#3959: {op.__name__} now rejects int64 input in a guard of its own -- update the warning")else:diff --git a/uv.lock b/uv.lockindex 7fd2bbf26..4af206d09 100644--- a/uv.lock+++ b/uv.lock@@ -871,7 +871,7 @@ requires-dist = [{ name = "pillow", marker = "extra == 'image'" },{ name = "pre-commit", marker = "extra == 'dev'" },{ name = "pydata-sphinx-theme", marker = "extra == 'docs'", specifier = ">=0.21,<0.22" },- { name = "pytest", marker = "extra == 'dev'" },+ { name = "pytest", marker = "extra == 'dev'", specifier = ">=7" },{ name = "pytest-timeout", marker = "extra == 'dev'" },{ name = "setuptools", marker = "extra == 'dev'" },{ name = "sphinx", marker = "extra == 'docs'" },