Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test(augmentation): resolve PT011 broad exception checks (#5643)

Daniele Loru77984c645f40
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index bc3a12999..2ae9545f8 100644
--- a/testing/half_precision_eager_rng.py
+++ b/testing/half_precision_eager_rng.py
@@ -149,7 +149,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(
(
*_audited(
"tests/augmentation/container/test_augmentation_sequential.py",
- 71,
+ 79,
"torch.randn",
2,
(
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index ddbf73f31..ffb8545a6 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -58,11 +58,19 @@ class TestAugmentationSequential:
assert torch.equal(out_keypoints, torch.from_numpy(keypoints))
@pytest.mark.parametrize(
- "data_keys", ["input", "image", ["mask", "input"], ["input", "bbox_yxyx"], [0, 10], [BorderType.REFLECT]]
+ "data_keys,error_type,match",
+ [
+ ("input", KeyError, "I"),
+ ("image", KeyError, "I"),
+ (["mask", "input"], NotImplementedError, "first input must be DataKey.IMAGE"),
+ (["input", "bbox_yxyx"], KeyError, "BBOX_YXYX"),
+ ([0, 10], ValueError, "10 is not a valid DataKey"),
+ ([BorderType.REFLECT], TypeError, "DataKey"),
+ ],
)
@pytest.mark.parametrize("augmentation_list", [K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)])
- def test_exception(self, augmentation_list, data_keys, device, dtype):
- with pytest.raises(Exception): # AssertError and NotImplementedError
+ def test_exception(self, augmentation_list, data_keys, error_type, match, device, dtype):
+ with pytest.raises(error_type, match=match):
K.AugmentationSequential(augmentation_list, data_keys=data_keys)
@pytest.mark.slow
@@ -874,7 +882,7 @@ class TestAugmentationSequential:
data_keys=["input", "mask", "bbox", "keypoints", "bbox", "BBOX_XYWH", "BBOX_XYWH"],
random_apply=random_apply,
)
- with pytest.raises(Exception): # No parameters available for inversing.
+ with pytest.raises(ValueError, match=r"No parameters available for inversing"):
aug.inverse(inp, mask, bbox, keypoints, bbox_2, bbox_wh, bbox_wh_2)
out = aug(inp, mask, bbox, keypoints, bbox_2, bbox_wh, bbox_wh_2)
diff --git a/tests/augmentation/container/test_patch_sequential.py b/tests/augmentation/container/test_patch_sequential.py
index 25d62c0e2..2371e3eb0 100644
--- a/tests/augmentation/container/test_patch_sequential.py
+++ b/tests/augmentation/container/test_patch_sequential.py
@@ -43,7 +43,7 @@ class TestPatchSequential:
],
)
def test_exception(self, error_param):
- with pytest.raises(Exception): # AssertError and NotImplementedError
+ with pytest.raises(ValueError, match=r"number of processing modules|Only boolean value allowed"):
K.PatchSequential(
K.ImageSequential(
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),
diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.py
index 58e2fbc29..d62108045 100644
--- a/tests/augmentation/container/test_sequential_aug.py
+++ b/tests/augmentation/container/test_sequential_aug.py
@@ -27,10 +27,13 @@ from testing.base import BaseTester
class TestSequential:
- @pytest.mark.parametrize("random_apply_weights", [None, [0.8, 0.9]])
- def test_exception(self, random_apply_weights, device, dtype):
+ @pytest.mark.parametrize(
+ "random_apply_weights,match",
+ [(None, r"No parameters available for inversing"), ([0.8, 0.9], r"length of `random_apply_weights`")],
+ )
+ def test_exception(self, random_apply_weights, match, device, dtype):
inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)
- with pytest.raises(Exception): # AssertError and NotImplementedError
+ with pytest.raises(ValueError, match=match):
K.ImageSequential(
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), random_apply_weights=random_apply_weights
).inverse(inp)
@@ -256,10 +259,10 @@ class TestConventionImageSequential(BaseTester):
skips = K.VideoSequential(K.RandomHorizontalFlip(p=1.0), blur, if_unsupported_ops="skip")
out = skips(x)
self.assert_close(skips.inverse(out), out.flip(-1))
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"if_unsupported_ops.*must be either"):
K.VideoSequential(K.RandomHorizontalFlip(p=1.0), if_unsupported_ops="bogus")
def test_convention_if_unsupported_ops_rejects_invalid_value(self):
# #4423: construction accepts only "raise" and "skip".
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"if_unsupported_ops.*must be either"):
K.ImageSequential(K.RandomHorizontalFlip(p=1.0), if_unsupported_ops="bogus")
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index b627c9dc8..065a44069 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -19,6 +19,7 @@ import copy
import io
import os
import pickle
+import re
import subprocess
import sys
from typing import Any, Dict, Optional, Tuple, Type
@@ -82,6 +83,7 @@ from kornia.augmentation import (
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample, pi
from kornia.core._compat import torch_version
+from kornia.core.exceptions import BaseError
from kornia.core.utils import _torch_inverse_cast
from kornia.geometry import create_meshgrid, transform_points
@@ -445,7 +447,7 @@ class TestRandomEqualizeAlternative(CommonTests):
)
def test_exception(self):
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"Input size must have a shape"):
self._create_augmentation_from_params(p=1.0)(
torch.ones((1, 3, 4, 5) * 3, device=self.device, dtype=self.dtype)
)
@@ -534,11 +536,11 @@ class TestCenterCropAlternative(CommonTests):
self._create_augmentation_from_params(size=2, resample=True)
# Bound check
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"size"):
self._create_augmentation_from_params(size=-1)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"size"):
self._create_augmentation_from_params(size=(-1, 2))
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"size"):
self._create_augmentation_from_params(size=(2, -1))
@@ -736,13 +738,13 @@ class TestRandomRotationAlternative(CommonTests):
self._create_augmentation_from_params(degrees=(3, 3), resample=True)
# Bound check
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"degrees"):
self._create_augmentation_from_params(degrees=-361.0)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"degrees"):
self._create_augmentation_from_params(degrees=(-361.0, 360.0))
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"degrees"):
self._create_augmentation_from_params(degrees=(-360.0, 361.0))
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"degrees"):
self._create_augmentation_from_params(degrees=(360.0, -360.0))
@@ -822,7 +824,7 @@ class TestRandomRotation90(CommonTests):
# Wrong type
with pytest.raises(TypeError):
self._create_augmentation_from_params(times="")
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"times out of bounds"):
self._create_augmentation_from_params(times=(30, 60), align_corners=0)
@@ -895,9 +897,9 @@ class TestRandomGrayscaleAlternative(CommonTests):
def test_exception(self):
torch.manual_seed(42)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"channel"):
self._create_augmentation_from_params(p=0.0)(torch.rand((1, 1, 4, 5), device=self.device, dtype=self.dtype))
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"channel"):
self._create_augmentation_from_params(p=1.0)(torch.rand((1, 4, 4, 5), device=self.device, dtype=self.dtype))
@@ -3116,7 +3118,7 @@ class TestRandomGrayscale(BaseTester):
# custom per-band weights are honoured; a wrong length is rejected
weights = torch.full((7,), 1.0 / 7, device=device, dtype=dtype)
self.assert_close(RandomGrayscale(rgb_weights=weights, p=1.0)(x), expected)
- with pytest.raises(Exception):
+ with pytest.raises(BaseError, match=r"rgb_weights needs one weight per channel"):
RandomGrayscale(rgb_weights=torch.ones(4, device=device, dtype=dtype), p=1.0)(x)
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
@@ -5165,7 +5167,7 @@ class TestNormalize(BaseTester):
def test_random_normalize_invalid_parameter_shape(mean, std):
f = Normalize(mean=mean, std=std, p=1.0)
inputs = torch.arange(0.0, 16.0, step=1).reshape(1, 4, 4).unsqueeze(0)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"mean length and number of channels do not match"):
f(inputs)
def test_random_normalize(self, device, dtype):
@@ -6116,7 +6118,7 @@ class TestRandomSnow(BaseTester):
def test_exception(self, device, dtype):
exception_test_data = self._get_exception_test_data(device, dtype)
for err_msg, snow_coef, brght_coef, input_data in exception_test_data:
- with pytest.raises(Exception) as errinfo:
+ with pytest.raises((BaseError, ValueError), match=re.escape(err_msg)) as errinfo:
RandomSnow(p=1.0, snow_coefficient=snow_coef, brightness=brght_coef)(input_data)
assert err_msg in str(errinfo)
@@ -6152,11 +6154,11 @@ class TestRandomMedianBlur(BaseTester):
self.assert_close(out, expected)
def test_exception(self):
- with pytest.raises(Exception) as errinfo:
+ with pytest.raises(BaseError, match=r"Kernel size must be an odd integer bigger than 0") as errinfo:
RandomMedianBlur((4, 4), p=1.0)
assert "Kernel size must be an odd integer" in str(errinfo.value)
- with pytest.raises(Exception) as errinfo:
+ with pytest.raises(BaseError, match=r"Kernel size must be an odd integer bigger than 0") as errinfo:
RandomMedianBlur((3, 4), p=1.0)
assert "Kernel size must be an odd integer" in str(errinfo.value)
@@ -6268,7 +6270,7 @@ class TestRandomRain(BaseTester):
def test_exception(self, device, dtype):
exception_test_data = self._get_exception_test_data(device, dtype)
for err_msg, drop_height, drop_width, input_data in exception_test_data:
- with pytest.raises(Exception) as errinfo:
+ with pytest.raises(BaseError, match=re.escape(err_msg)) as errinfo:
RandomRain(p=1.0, drop_height=drop_height, drop_width=drop_width)(input_data)
assert err_msg in str(errinfo)
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index ca1f6efbc..f835b1a85 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -489,7 +489,7 @@ class Test3DAugmentationConventions(BaseTester):
volume = torch.rand(1, 1, 4, 5, 6)
with pytest.raises(AssertionError):
K.CenterCrop3D((5, 5, 6), p=1.0)(volume)
- with pytest.raises(ValueError):
+ with pytest.raises(ValueError, match=r"cannot be smaller than crop size"):
K.RandomCrop3D((5, 5, 6), p=1.0)(volume)
assert K.CenterCrop3D(2, p=1.0)(volume).shape == (1, 1, 2, 2, 2)
with pytest.raises(AssertionError):
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 38b64c4c4..d9e021b83 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -1381,7 +1381,7 @@ class TestIntensityColourConventions(BaseTester):
if not supports_reflect_padding(device, dtype):
pytest.skip("reflection_pad2d is unavailable for this device/dtype")
torch.manual_seed(_FORWARD_SEED)
- with pytest.raises(ValueError) as info:
+ with pytest.raises(ValueError, match=r"Cannot compute tiles") as info:
_sync(K.RandomClahe(p=1.0)(torch.rand(1, 1, 8, 8, device=device, dtype=dtype)).device)
# The error names the argument the caller passed, unlike torch's padding error.
assert "Cannot compute tiles" in str(info.value)
diff --git a/tests/augmentation/test_onnx_export.py b/tests/augmentation/test_onnx_export.py
index 846537301..6edf321c0 100644
--- a/tests/augmentation/test_onnx_export.py
+++ b/tests/augmentation/test_onnx_export.py
@@ -180,7 +180,8 @@ EXPORTABLE_OPS: list[Tuple[str, Callable[[], torch.nn.Module]]] = [
# Currently no augmentations are blocked at export time. Augmentations that export
# but produce numerically different results from eager are tracked separately in
# ``ONNX_NUMERICAL_KNOWN_DRIFT`` below.
-XFAIL_OPS: list[Tuple[str, Callable[[], torch.nn.Module], str]] = []
+# Future entries must record the actual exception type and message pattern as well as the reason.
+XFAIL_OPS: list[Tuple[str, Callable[[], torch.nn.Module], str, type[Exception], str]] = []
def _legacy_onnx_export(module: torch.nn.Module, x: torch.Tensor, buf: io.BytesIO) -> None:
@@ -215,13 +216,15 @@ def test_onnx_export_exportable(name: str, factory: Callable[[], torch.nn.Module
assert size > 0, f"{name}: ONNX graph was empty"
[email protected]("name,factory,reason", XFAIL_OPS, ids=[n for n, _, _ in XFAIL_OPS])
[email protected]("name,factory,reason,error_type,match", XFAIL_OPS, ids=[n for n, *_ in XFAIL_OPS])
@pytest.mark.device_agnostic
-def test_onnx_export_known_blocked(name: str, factory: Callable[[], torch.nn.Module], reason: str) -> None:
+def test_onnx_export_known_blocked(
+ name: str, factory: Callable[[], torch.nn.Module], reason: str, error_type: type[Exception], match: str
+) -> None:
"""Augmentation cannot export today; pinned so we notice if it starts working."""
torch.manual_seed(0)
x = torch.randn(2, 3, 32, 32)
- with pytest.raises(Exception):
+ with pytest.raises(error_type, match=match):
_try_export(factory(), x)
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index 586cb28e3..02c97e158 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -79,7 +79,7 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, p):
- with pytest.raises(Exception):
+ with pytest.raises(ValueError, match=r"Expected parameter probs"):
ProbabilityGenerator(p)(torch.Size([8]))
@pytest.mark.parametrize(
@@ -166,7 +166,10 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(
+ (TypeError, ValueError),
+ match=r"(brightness|contrast|saturation|hue) (out of bounds|should be)",
+ ):
ColorJiggleGenerator(
torch.as_tensor(
brightness if brightness is not None else torch.tensor([0.0, 0.0]),
@@ -453,7 +456,10 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(
+ (TypeError, ValueError),
+ match=r"(brightness|contrast|saturation|hue) (out of bounds|should be)",
+ ):
ColorJitterGenerator(
torch.as_tensor(
brightness if brightness is not None else torch.tensor([0.0, 0.0]),
@@ -636,7 +642,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, height, width, distortion_scale, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(AssertionError):
PerspectiveGenerator(distortion_scale.to(device=device, dtype=dtype))(torch.Size([8, 1, height, width]))
def test_random_gen(self, device, dtype):
@@ -803,7 +809,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize("batch_size", [0, 1, 4])
@pytest.mark.parametrize("height", [200])
@pytest.mark.parametrize("width", [300])
- @pytest.mark.parametrize("degrees", [torch.tensor([0, 30])])
+ @pytest.mark.parametrize("degrees", [torch.tensor([0, 30]), 0.5])
@pytest.mark.parametrize("translate", [None, torch.tensor([0.1, 0.1])])
@pytest.mark.parametrize("scale", [None, torch.tensor([0.7, 1.2])])
@pytest.mark.parametrize("shear", [None, torch.tensor([[0, 20], [0, 20]])])
@@ -822,7 +828,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
dtype,
):
AffineGenerator(
- degrees=degrees.to(device=device, dtype=dtype),
+ degrees=degrees.to(device=device, dtype=dtype) if isinstance(degrees, Tensor) else degrees,
translate=(translate.to(device=device, dtype=dtype) if translate is not None else None),
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
@@ -833,7 +839,9 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
[
(-100, 100, torch.tensor([10, 20]), None, None, None),
(100, -100, torch.tensor([10, 20]), None, None, None),
- (100, 100, 0.5, None, None, None),
+ # A scalar 0.5 is valid; use an out-of-range tensor to reach generator validation.
+ # bfloat16 rounds 361 to 360, inside the range; 400 is exact in every dtype.
+ (100, 100, torch.tensor([-400, 400]), None, None, None),
(100, 100, torch.tensor([10, 20, 30]), None, None, None),
(100, 100, torch.tensor([10, 20]), torch.tensor([0.1]), None, None),
(10, 10, torch.tensor([1, 2]), torch.tensor([0.1, 0.2, 0.3]), None, None),
@@ -845,7 +853,10 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, height, width, degrees, translate, scale, shear, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(
+ (AssertionError, TypeError, ValueError),
+ match=r"height|width|degrees|translate|scale|shear",
+ ):
AffineGenerator(
degrees=degrees.to(device=device, dtype=dtype),
translate=(translate.to(device=device, dtype=dtype) if translate is not None else None),
@@ -930,7 +941,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
batch_size = 2
- with pytest.raises(Exception):
+ with pytest.raises(AssertionError):
CropGenerator(
(size.to(device=device, dtype=dtype) if isinstance(size, Tensor) else size),
resize_to,
@@ -1046,7 +1057,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, size, scale, ratio, device, dtype):
batch_size = 2
- with pytest.raises(Exception):
+ with pytest.raises((TypeError, AssertionError), match=r"output_size|scale|ratio"):
ResizedCropGenerator(
size,
torch.as_tensor(scale, device=device, dtype=dtype),
@@ -1183,7 +1194,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, height, width, scale, ratio, value, device, dtype):
batch_size = 8
- with pytest.raises(Exception):
+ with pytest.raises((AssertionError, TypeError), match=r"height|width|value|scale|ratio"):
RectangleEraseGenerator(
scale=scale.to(device=device, dtype=dtype),
ratio=ratio.to(device=device, dtype=dtype),
@@ -1355,7 +1366,7 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, height, width, size, device, dtype):
batch_size = 2
- with pytest.raises(Exception):
+ with pytest.raises(AssertionError):
center_crop_generator(batch_size=batch_size, height=height, width=width, size=size)
def test_random_gen(self, device, dtype):
@@ -1433,7 +1444,7 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises((AssertionError, ValueError), match=r"kernel_size|direction out of bounds"):
MotionBlurGenerator(
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
@@ -1549,7 +1560,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, bits, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(ValueError, match=r"bits.*(out of bounds|shall be)"):
PosterizeGenerator(bits.to(device=device, dtype=dtype) if isinstance(bits, Tensor) else bits)(
torch.Size([3])
)
@@ -1585,7 +1596,9 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):
@pytest.mark.parametrize("sharpness", [(torch.tensor([-1, 5])), (torch.tensor([3])), ([0, 1.0])])
def test_invalid_param_combinations(self, sharpness, device, dtype):
- with pytest.raises(Exception):
+ # Convert before the raises block so a list cannot fail on .to() instead of the duplicate name.
+ sharpness = torch.as_tensor(sharpness, device=device, dtype=dtype)
+ with pytest.raises(RuntimeError, match=r"factor name `sharpness` has already been registered"):
PlainUniformGenerator(
(sharpness.to(device=device, dtype=dtype), "sharpness", None, None),
(
@@ -1642,7 +1655,7 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):
class TestRandomMixUpGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize("batch_size", [0, 1, 8])
@pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
- @pytest.mark.parametrize("lambda_val", [None, torch.tensor([0.0, 1.0])])
+ @pytest.mark.parametrize("lambda_val", [None, torch.tensor([0.0, 1.0]), [0.0, 1.0]])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_valid_param_combinations(self, batch_size, p, lambda_val, same_on_batch, device, dtype):
MixupGenerator(
@@ -1656,11 +1669,10 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
(torch.tensor([-1, 1])),
(torch.tensor([0, 2])),
(torch.tensor([0, 0.5, 1])),
- ([0.0, 1.0]),
],
)
def test_invalid_param_combinations(self, lambda_val, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises((TypeError, ValueError), match=r"lambda_val (out of bounds|should be)"):
MixupGenerator(p=1.0, lambda_val=lambda_val.to(device=device, dtype=dtype))(
torch.Size([8, 3, 200, 200]), same_on_batch=False
)
@@ -1756,7 +1768,7 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
)
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_invalid_param_combinations(self, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises((AssertionError, ValueError), match=r"height|width|num_mix|concentration|cut_size"):
CutmixGenerator(
p=0.5,
num_mix=num_mix,
diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.py
index 6d50d8ba3..39acf521f 100644
--- a/tests/augmentation/test_random_generator_3d.py
+++ b/tests/augmentation/test_random_generator_3d.py
@@ -68,7 +68,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, depth, height, width, distortion_scale, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(AssertionError):
PerspectiveGenerator3D(distortion_scale=distortion_scale.to(device=device, dtype=dtype))(
batch_shape=torch.Size((2, depth, height, width))
)
@@ -299,7 +299,10 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
if isinstance(shear, torch.Tensor):
shear.to(dtype=dtype, device=device)
- with pytest.raises(Exception):
+ with pytest.raises(
+ (AssertionError, TypeError, ValueError),
+ match=r"depth|height|width|[Dd]egrees|translate|scale",
+ ):
AffineGenerator3D(degrees=degrees, translate=translate, scale=scale, shears=shear)(
batch_shape=torch.Size((2, depth, height, width))
)
@@ -398,7 +401,7 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
[(torch.tensor(-10)), (torch.tensor([-10])), (torch.tensor([[0, 30]])), (torch.tensor([[0, 30], [0, 30]]))],
)
def test_invalid_param_combinations(self, degrees, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises(ValueError, match=r"must be a positive number|Degrees must be"):
RotationGenerator3D(degrees=degrees.to(device=device, dtype=dtype))(torch.Size((2,)))
def test_random_gen(self, device, dtype):
@@ -457,7 +460,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises((AssertionError, ValueError), match=r"batch_shape|size|resize_to"):
CropGenerator3D(
size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
resize_to=resize_to,
@@ -613,7 +616,7 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, depth, height, width, size, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises((AssertionError, ValueError), match=r"depth|height|width|size"):
center_crop_generator3d(batch_size=2, depth=depth, height=height, width=width, size=size)
def test_random_gen(self, device, dtype):
@@ -689,7 +692,7 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
],
)
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
- with pytest.raises(Exception):
+ with pytest.raises((AssertionError, ValueError), match=r"kernel_size|direction out of bounds"):
MotionBlurGenerator3D(
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),