Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test(geometry): stop two exception tests from passing on an earlier error (#5665)

Daniele Lorub2f6b770459b
diff --git a/pyproject.toml b/pyproject.toml
index 76733a69f..f7075c344 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -275,7 +275,7 @@ select = [
# "PD", # pandas-vet. No: kornia does not use pandas
# "PERF", # Perflint. No: PERF401 rewrites append loops as comprehensions
# "PGH", # pygrep-hooks. Partial: PGH004 is enabled above. No: PGH003, ty ignores the code in `type: ignore[x]`
- # "PT", # flake8-pytest-style. Partial: the PT rules above, and PT011 is wanted. No: PT006
+ # "PT", # flake8-pytest-style. Partial: the PT rules above. No: PT006, PT011
# "PTH", # flake8-use-pathlib. No: os.path to pathlib churn
# "Q", # flake8-quotes. No: ruff format handles quotes
# "SIM", # flake8-simplify. Partial: the SIM rules above. No: SIM300, it reads names such as `H` as constants
diff --git a/tests/geometry/epipolar/test_projection.py b/tests/geometry/epipolar/test_projection.py
index c82814f8d..6a5653054 100644
--- a/tests/geometry/epipolar/test_projection.py
+++ b/tests/geometry/epipolar/test_projection.py
@@ -286,11 +286,11 @@ class TestConventionProjection(BaseTester):
two_view = two_view_scene(device, dtype)
# P must have exactly one batch dimension.
for P_bad in (two_view["P2"][0], two_view["P2"][None]):
- with pytest.raises(Exception):
+ with pytest.raises(IndexError):
epi.KRt_from_projection(P_bad)
if dtype in (torch.float16, torch.bfloat16):
# float16 and bfloat16 raise: the input is not upcast (projections_from_fundamental upcasts).
- with pytest.raises(Exception):
+ with pytest.raises((RuntimeError, NotImplementedError)):
epi.KRt_from_projection(two_view["P2"])
return
K_true, R_true, t_true = two_view["K2"], two_view["R"], two_view["t"]
@@ -341,7 +341,7 @@ class TestConventionProjection(BaseTester):
assert (_unit(F_reversed) * torch.sign((F_reversed * F).sum()) - _unit(F)).abs().max() > 0.1
# F_mat must have exactly one batch dimension.
for F_bad in (F[0], F[None]):
- with pytest.raises(Exception):
+ with pytest.raises(RuntimeError):
epi.projections_from_fundamental(F_bad)
def test_convention_depth_from_point_is_camera_z(self, device, dtype):
@@ -399,7 +399,7 @@ class TestConventionProjection(BaseTester):
self.assert_close(K_t[:, 0, 2] - K_t[:, 1, 2], torch.full_like(zeros, -1.0))
# The image must be floating point (a design choice): an integer image raises instead of returning an
# integer K.
- with pytest.raises(Exception):
+ with pytest.raises(RuntimeError):
epi.intrinsics_like(500.0, torch.zeros(1, 3, 4, 6, device=device, dtype=torch.uint8))
def test_convention_krt_from_projection_scale_and_sign_of_P(self, device, dtype):
diff --git a/tests/geometry/liegroup/test_se2.py b/tests/geometry/liegroup/test_se2.py
index 018c4913a..254ec52b5 100644
--- a/tests/geometry/liegroup/test_se2.py
+++ b/tests/geometry/liegroup/test_se2.py
@@ -20,7 +20,7 @@ import math
import pytest
import torch
-from kornia.core.exceptions import TypeCheckError
+from kornia.core.exceptions import BaseError, TypeCheckError
from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.vector import Vector2
@@ -85,13 +85,13 @@ class TestSe2(BaseTester):
theta = torch.rand((batch_size, 2), dtype=dtype, device=device)
with pytest.raises(ValueError):
Se2.hat(theta)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
Se2.identity(batch_size=0)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
Se2.random(batch_size=0)
x = torch.rand(5, dtype=dtype, device=device)
y = torch.rand(3, dtype=dtype, device=device)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
Se2.trans(x, y)
def test_gradcheck(self, device):
diff --git a/tests/geometry/liegroup/test_so2.py b/tests/geometry/liegroup/test_so2.py
index 3bf153d95..6dd229e7e 100644
--- a/tests/geometry/liegroup/test_so2.py
+++ b/tests/geometry/liegroup/test_so2.py
@@ -20,7 +20,7 @@ import math
import pytest
import torch
-from kornia.core.exceptions import TypeCheckError
+from kornia.core.exceptions import BaseError, TypeCheckError
from kornia.geometry.conversions import angle_to_rotation_matrix
from kornia.geometry.liegroup import Se2, So2
from kornia.geometry.vector import Vector2
@@ -89,7 +89,7 @@ class TestSo2(BaseTester):
m = torch.rand((2, 2, 1), dtype=dtype, device=device)
with pytest.raises(ValueError):
assert So2.from_matrix(m)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
assert So2.identity(batch_size=0)
# TODO: implement me
diff --git a/tests/geometry/solvers/test_homogeneous.py b/tests/geometry/solvers/test_homogeneous.py
index 7229f6e84..f26560731 100644
--- a/tests/geometry/solvers/test_homogeneous.py
+++ b/tests/geometry/solvers/test_homogeneous.py
@@ -18,6 +18,7 @@
import pytest
import torch
+from kornia.core.exceptions import ShapeError, TypeCheckError
from kornia.geometry import solvers
from kornia.geometry.solvers.homogeneous import _null_space_lu
@@ -96,19 +97,19 @@ class TestNullVector3x4(BaseTester):
# ------------------------------------------------------------------
def test_exception_wrong_rows(self, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(ShapeError):
solvers.null_vector_3x4(torch.rand(1, 4, 4, device=device, dtype=dtype))
def test_exception_wrong_cols(self, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(ShapeError):
solvers.null_vector_3x4(torch.rand(1, 3, 3, device=device, dtype=dtype))
def test_exception_1d(self, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(ShapeError):
solvers.null_vector_3x4(torch.rand(4, device=device, dtype=dtype))
def test_exception_not_tensor(self, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(TypeCheckError):
solvers.null_vector_3x4([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0]])
# ------------------------------------------------------------------
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index b7102c127..0c47f2e47 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -256,15 +256,15 @@ def test_guard_classifier_reads_the_raising_instruction():
# ValueError, but raised by UNPACK_SEQUENCE rather than by a `raise`.
first, second, third = [1, 2] # noqa: F841
- for guard in (
- spaced_raise,
- parenthesised_raise,
- raise_a_bound_name,
- kornia_shape_check,
- kornia_value_check,
- hand_rolled_value_error,
+ for guard, error_type in (
+ (spaced_raise, RuntimeError),
+ (parenthesised_raise, RuntimeError),
+ (raise_a_bound_name, RuntimeError),
+ (kornia_shape_check, ShapeError),
+ (kornia_value_check, BaseError),
+ (hand_rolled_value_error, ValueError),
):
- with pytest.raises(Exception) as excinfo:
+ with pytest.raises(error_type) as excinfo:
guard()
assert _raised_by_a_kornia_guard(excinfo.value), (
f"{guard.__name__} rejects the input on kornia's side and must classify as a guard"
@@ -4070,7 +4070,7 @@ class TestNormalizeHomography(BaseTester):
wrong_sized = torch.eye(wrong_size, device=device, dtype=torch.float32)[None]
for rejected in (wrong_sized, eye.expand(2, 1, size, size)):
- with pytest.raises(Exception) as excinfo:
+ with pytest.raises(ValueError) as excinfo:
op(rejected, *sizes)
assert _raised_by_a_kornia_guard(excinfo.value), (
f"kornia#3960: {op_name} did not reject a {tuple(rejected.shape)} matrix in its guard"
@@ -4498,8 +4498,9 @@ class TestRt2Extrinsics(BaseTester):
translation = torch.ones(1, 3, 1, device=device, dtype=torch.int64)
extrinsics = torch.eye(4, device=device, dtype=torch.int64)[None]
+ # These calls fail inside torch with RuntimeError; the classifier still rejects a new Kornia guard.
for op in (Rt_to_matrix4x4, camtoworld_graphics_to_vision_Rt, camtoworld_vision_to_graphics_Rt):
- with pytest.raises(Exception) as excinfo:
+ with pytest.raises(RuntimeError) as excinfo:
op(rotation, translation)
assert not _raised_by_a_kornia_guard(excinfo.value), (
f"kornia#3959: {op.__name__} now rejects int64 (R, t) in a guard of its own -- update the warning"
@@ -4601,7 +4602,7 @@ class TestRt2Extrinsics(BaseTester):
checks_were_enabled = are_checks_enabled()
disable_checks()
try:
- with pytest.raises(Exception) as excinfo:
+ with pytest.raises(RuntimeError) as excinfo:
Rt_to_matrix4x4(R, t)
finally:
if checks_were_enabled:
@@ -5333,7 +5334,7 @@ class TestEulerFromQuaternion(BaseTester):
def test_exception(self, device, dtype):
q = Quaternion.random(batch_size=2)
q = q.to(device, dtype)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
euler_from_quaternion(q.w, torch.rand(1), q.y, q.z)
def test_gradcheck(self, device):
@@ -5721,7 +5722,7 @@ class TestQuaternionFromEuler(BaseTester):
def test_exception(self, device, dtype):
_, pitch, yaw = torch.rand(3, 2, device=device, dtype=dtype)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
quaternion_from_euler(torch.rand(1), pitch, yaw)
def test_gradcheck(self, device):
diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.py
index eb717f368..dbb74bf8b 100644
--- a/tests/geometry/test_homography.py
+++ b/tests/geometry/test_homography.py
@@ -22,6 +22,7 @@ import torch
import kornia
from kornia.core._compat import torch_version_le
+from kornia.core.exceptions import BaseError, ShapeError
from kornia.geometry.conversions import convert_points_from_homogeneous
from kornia.geometry.epipolar import normalize_points
from kornia.geometry.homography import (
@@ -435,9 +436,9 @@ class TestSampsonHomographyDistance(BaseTester):
def test_exception(self, device, dtype):
pts = torch.rand(1, 3, 2, device=device, dtype=dtype)
- with pytest.raises(Exception):
+ with pytest.raises(ShapeError):
sampson_homography_distance(pts, pts, torch.eye(3, device=device, dtype=dtype))
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
sampson_homography_distance(pts[..., :1], pts[..., :1], torch.eye(3, device=device, dtype=dtype)[None])
def test_gradcheck(self, device):
@@ -1269,7 +1270,7 @@ class TestConventionHomography(BaseTester):
# Relabelling the images returns the inverse.
self.assert_close(find_homography_dlt(p2, p1), _inverse(H_true), rtol=1e-4, atol=1e-4)
# Four or more correspondences: three are rejected before any solve.
- with pytest.raises(Exception):
+ with pytest.raises(AssertionError):
find_homography_dlt(p1[:, :3], p2[:, :3])
def test_convention_find_homography_dlt_lu_equals_svd(self, device, dtype):
diff --git a/tests/geometry/test_linalg.py b/tests/geometry/test_linalg.py
index ea270c95d..d8d134f31 100644
--- a/tests/geometry/test_linalg.py
+++ b/tests/geometry/test_linalg.py
@@ -330,13 +330,16 @@ class TestRelativeTransformation(BaseTester):
to_check_4 = torch.rand((4, 4), device=device, dtype=dtype)
to_check_5 = torch.rand((3, 3), device=device, dtype=dtype)
- # Testing if exception is thrown when both inputs have shape (3, 3)
- with pytest.raises(ValueError):
- _ = kornia.geometry.relative_transformation(to_check_5, to_check_5)
+ # Make only one operand invalid at a time: both guards have the same diagnostic.
+ # A second invalid operand must not hide removal of the first operand's guard.
+ for first, second in ((to_check_5, to_check_4), (to_check_4, to_check_5)):
+ with pytest.raises(ValueError, match="Input must be"):
+ _ = kornia.geometry.relative_transformation(first, second)
- # Testing if exception is thrown when both inputs have shape (5, 10, 10)
- with pytest.raises(ValueError):
- _ = kornia.geometry.relative_transformation(to_check_2, to_check_2)
+ valid_batch = to_check_3[:5]
+ for first, second in ((to_check_2, valid_batch), (valid_batch, to_check_2)):
+ with pytest.raises(ValueError, match="Input must be"):
+ _ = kornia.geometry.relative_transformation(first, second)
# Testing if exception is thrown when one input has shape (6, 4, 4)
# whereas the other input has shape (4, 4)
@@ -518,7 +521,7 @@ class TestEuclideanDistance(BaseTester):
def test_exception(self, device, dtype):
pt1 = torch.tensor([0, 0, 0], device=device, dtype=dtype)
pt2 = torch.rand(1, 2, device=device, dtype=dtype)
- with pytest.raises(Exception):
+ with pytest.raises(RuntimeError):
kgl.euclidean_distance(pt1, pt2)
def test_gradcheck(self, device):
diff --git a/tests/geometry/test_quaternion.py b/tests/geometry/test_quaternion.py
index a044f81bb..3160ad1f9 100644
--- a/tests/geometry/test_quaternion.py
+++ b/tests/geometry/test_quaternion.py
@@ -52,13 +52,13 @@ class TestQuaternion(BaseTester):
self.assert_close(q1, q2)
def test_init_fail(self, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(TypeError):
_ = Quaternion("q")
- with pytest.raises(Exception):
+ with pytest.raises(TypeError):
_ = Quaternion([1, 0, 0, 0])
- with pytest.raises(Exception):
+ with pytest.raises(TypeError):
_ = Quaternion(1, [0, 0, 0])
def test_constructor_scalar_tensre(self, device, dtype):
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 76a6cde6c..725562451 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -22,6 +22,7 @@ import torch
import kornia
from kornia.core._compat import torch_version, torch_version_lt
+from kornia.core.exceptions import BaseError
from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
@@ -313,7 +314,7 @@ class TestGetPerspectiveTransform(BaseTester):
)
# compute transformation between points
- with pytest.raises(Exception):
+ with pytest.raises(BaseError):
_ = kornia.geometry.get_perspective_transform(points_src, points_dst)
def test_back_and_forth(self, device, dtype):
@@ -563,8 +564,10 @@ class TestWarpAffine(BaseTester):
with pytest.raises(ValueError):
assert kornia.geometry.warp_affine(img, aff, size)
+ # Keep the image valid so this case reaches the matrix-shape guard.
+ img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
aff = torch.eye(2, 2, device=device, dtype=dtype)[None]
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="Input M"):
assert kornia.geometry.warp_affine(img, aff, size)
def test_translation(self, device, dtype):
@@ -797,8 +800,10 @@ class TestWarpPerspective(BaseTester):
with pytest.raises(ValueError):
assert kornia.geometry.warp_perspective(img, homo, size)
+ # Keep the image valid so this case reaches the matrix-shape guard.
+ img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
homo = torch.eye(2, 2, device=device, dtype=dtype)[None]
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match="Input M"):
assert kornia.geometry.warp_perspective(img, homo, size)
def test_translation(self, device, dtype):