From 62c70a513b64a1add25acd122392b42fd1d1bb7e Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Mon, 23 Nov 2026 09:24:01 +1000 Subject: [PATCH] chore: make error messages say what was received and what is allowed Rewrite 63 raise statements whose messages were missing or unhelpful: - 43 passed the value and the text as two arguments, so the message printed as a tuple, for example (3, 'n must be greater than 0'). The value is now in the text: "n must be greater than 0, got 3". - 19 had no message or one of two words, such as "bad type", "bad id", "bad colorspace" and "truncated". They now name the argument, the allowed values and what was received. - the NotImplementedError in VisualServo.step names the class that must implement it. No exception types change. Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/Camera.py | 31 ++++++++----- src/machinevisiontoolbox/ImageColor.py | 2 +- src/machinevisiontoolbox/ImageCore.py | 6 ++- src/machinevisiontoolbox/ImageFiducials.py | 4 +- src/machinevisiontoolbox/ImageMorph.py | 8 ++-- .../ImagePointFeatures.py | 12 +++-- src/machinevisiontoolbox/ImageProcessing.py | 16 ++++--- src/machinevisiontoolbox/ImageReshape.py | 8 ++-- src/machinevisiontoolbox/ImageSpatial.py | 27 ++++++----- .../ImageWholeFeatures.py | 14 +++--- src/machinevisiontoolbox/Sources.py | 8 +++- src/machinevisiontoolbox/VisualServo.py | 2 +- src/machinevisiontoolbox/base/color.py | 14 +++--- src/machinevisiontoolbox/base/graphics.py | 5 ++- src/machinevisiontoolbox/base/imageio.py | 4 +- src/machinevisiontoolbox/base/shapes.py | 2 +- tests/test_error_messages.py | 45 +++++++++++++++++++ tests/test_image_point_features_extra.py | 6 +-- tests/test_image_spatial_extra.py | 2 +- 19 files changed, 148 insertions(+), 68 deletions(-) create mode 100644 tests/test_error_messages.py diff --git a/src/machinevisiontoolbox/Camera.py b/src/machinevisiontoolbox/Camera.py index 569ef6a9..ed556855 100644 --- a/src/machinevisiontoolbox/Camera.py +++ b/src/machinevisiontoolbox/Camera.py @@ -100,11 +100,11 @@ def __init__( self._name = camtype else: if not isinstance(name, str): - raise TypeError(name, "name must be a string") + raise TypeError(f"name must be a string, got {name!r}") self._name = name if not isinstance(camtype, str): - raise TypeError(camtype, "camtype must be a string") + raise TypeError(f"camtype must be a string, got {camtype!r}") self._camtype = camtype if imagesize is None: @@ -134,7 +134,7 @@ def __init__( self._rhou = rho[0] self._rhov = rho[1] else: - raise ValueError(rho, "rho must be a 1- or 2-element vector") + raise ValueError(f"rho must be a 1- or 2-element vector, got {rho!r}") if noise is not None: self._noise = noise @@ -250,7 +250,7 @@ def name(self, newname: str) -> None: if isinstance(newname, str): self._name = newname else: - raise TypeError(newname, "name must be a string") + raise TypeError(f"name must be a string, got {newname!r}") @property def camtype(self) -> str: @@ -283,7 +283,7 @@ def camtype(self, newcamtype: str) -> None: if isinstance(newcamtype, str): self._camtype = newcamtype else: - raise TypeError(newcamtype, "camtype must be a string") + raise TypeError(f"camtype must be a string, got {newcamtype!r}") @property def imagesize(self) -> np.ndarray | None: @@ -333,7 +333,9 @@ def imagesize(self, npix: ArrayLike) -> None: # ignore color dimension in case it is given self._imagesize = npix[:2] else: - raise ValueError(npix, "imagesize must be a 1- or 2-element vector") + raise ValueError( + f"imagesize must be a 1- or 2-element vector, got {npix!r}" + ) if self._pp is None: assert self._imagesize is not None self._pp = self._imagesize / 2 @@ -460,7 +462,7 @@ def pp(self, pp: ArrayLike) -> None: elif len(pp) == 2: self._pp = pp else: - raise ValueError(pp, "pp must be a 1- or 2-element vector") + raise ValueError(f"pp must be a 1- or 2-element vector, got {pp!r}") @property def u0(self) -> float: @@ -2048,7 +2050,7 @@ def f(self, f: ArrayLike) -> None: self._fu = f[0] self._fv = f[1] else: - raise ValueError(f, "f must be a 1- or 2-element vector") + raise ValueError(f"f must be a 1- or 2-element vector, got {f!r}") @property def fpix(self) -> np.ndarray: @@ -2466,11 +2468,11 @@ def H(self, T: SE3, n: ArrayLike, d: float) -> np.ndarray: :seealso: :meth:`points2H` :meth:`decomposeH` """ if d < 0: - raise ValueError(d, "plane distance d must be > 0") + raise ValueError(f"plane distance d must be > 0, got {d!r}") n = _getvector(n) if n[2] < 0: - raise ValueError(n, "normal must be away from camera (n[2] >= 0)") + raise ValueError(f"normal must be away from camera (n[2] >= 0), got {n!r}") # T transform view 1 to view 2 T = SE3(T).inv() @@ -2699,7 +2701,9 @@ def F(self, other: CentralCamera | SE3) -> np.ndarray: return np.linalg.inv(K2).T @ E @ np.linalg.inv(K1) else: - raise ValueError("bad type") + raise ValueError( + f"other must be a CentralCamera or SE3, got {type(other).__name__}" + ) @staticmethod def points2F( @@ -2916,7 +2920,10 @@ def E(self, other: CentralCamera | SE3 | np.ndarray) -> np.ndarray: T21 = SE3(other.inv()) else: - raise ValueError("bad type") + raise ValueError( + "other must be a CentralCamera, SE3 or a 3x3 fundamental matrix, " + f"got {type(other).__name__}" + ) return smb.skew(T21.t) @ T21.R diff --git a/src/machinevisiontoolbox/ImageColor.py b/src/machinevisiontoolbox/ImageColor.py index 1b1804ea..3eb76a02 100644 --- a/src/machinevisiontoolbox/ImageColor.py +++ b/src/machinevisiontoolbox/ImageColor.py @@ -177,7 +177,7 @@ def colorize( else: color_arr = argcheck.getvector(color).astype(self.dtype) if self.iscolor: - raise ValueError(self._A, "Image must be greyscale") + raise ValueError(f"image must be greyscale, got {self.nplanes} planes") out = self._A[..., np.newaxis] * color_arr diff --git a/src/machinevisiontoolbox/ImageCore.py b/src/machinevisiontoolbox/ImageCore.py index a6e46414..bd221739 100644 --- a/src/machinevisiontoolbox/ImageCore.py +++ b/src/machinevisiontoolbox/ImageCore.py @@ -2854,7 +2854,7 @@ def __getitem__( return self.__class__(out, colororder=colororder) else: - raise ValueError("invalid slice") + raise ValueError(f"invalid index or slice {keys!r}") @staticmethod def _lenkey(key: int | slice, max: int) -> int: @@ -3879,7 +3879,9 @@ def _binop(left, right, op, logical=False) -> "Image": np.stack(out, axis=2), colororder=right.colororder ) else: - raise ValueError("planes mismatch") + raise ValueError( + f"images have different numbers of planes, {left.nplanes} and {right.nplanes}" + ) else: # right is a scalar or numpy array return left.__class__(op(left._A, right), colororder=left.colororder) diff --git a/src/machinevisiontoolbox/ImageFiducials.py b/src/machinevisiontoolbox/ImageFiducials.py index d5a742cf..250566a8 100644 --- a/src/machinevisiontoolbox/ImageFiducials.py +++ b/src/machinevisiontoolbox/ImageFiducials.py @@ -470,7 +470,9 @@ def estimatePose( ) if not retval: - raise ValueError("solvePnP failed") + raise ValueError( + f"solvePnP failed to find a pose from {len(objPoints)} points" + ) # print(f"rotation: {rvec.T}") # print(f"translation: {tvec.T}") self._tvec = tvec diff --git a/src/machinevisiontoolbox/ImageMorph.py b/src/machinevisiontoolbox/ImageMorph.py index 85565a39..5af1ebdc 100644 --- a/src/machinevisiontoolbox/ImageMorph.py +++ b/src/machinevisiontoolbox/ImageMorph.py @@ -120,7 +120,7 @@ def erode( if not isinstance(n, int): n = int(n) if n <= 0: - raise ValueError(n, "n must be greater than 0") + raise ValueError(f"n must be greater than 0, got {n!r}") if self.isbool: img_array = self.array_as("uint8") # convert to uint8 for opencv @@ -213,7 +213,7 @@ def dilate( if not isinstance(n, int): n = int(n) if n <= 0: - raise ValueError(n, "n must be greater than 0") + raise ValueError(f"n must be greater than 0, got {n!r}") if self.isbool: img_array = self.array_as("uint8") # convert to uint8 for opencv @@ -303,12 +303,12 @@ def morph( # can also be a scalar if not isinstance(op, str): - raise TypeError(op, "oper must be a string") + raise TypeError(f"oper must be a string, got {op!r}") if not isinstance(n, int): n = int(n) if n <= 0: - raise ValueError(n, "n must be greater than 0") + raise ValueError(f"n must be greater than 0, got {n!r}") if self.isbool: img_array = self.array_as("uint8") # convert to uint8 for opencv diff --git a/src/machinevisiontoolbox/ImagePointFeatures.py b/src/machinevisiontoolbox/ImagePointFeatures.py index 323404e2..540f7b48 100644 --- a/src/machinevisiontoolbox/ImagePointFeatures.py +++ b/src/machinevisiontoolbox/ImagePointFeatures.py @@ -1401,9 +1401,11 @@ def __getitem__(self, i) -> "FeatureMatch": if self._inliers is not None: inliers = [self._inliers[k] for k in i] else: - raise ValueError("bad index dtype") + raise ValueError(f"index array must be integer or bool, got {i.dtype}") else: - raise ValueError("bad index") + raise ValueError( + f"index must be an int, slice, sequence or array, got {type(i).__name__}" + ) return FeatureMatch(matches, self._kp1, self._kp2, inliers) def __len__(self) -> int: @@ -2173,7 +2175,7 @@ def _image2feature( for k in kp: k.class_id = id else: - raise ValueError("bad id") + raise ValueError(f"id must be 'image', 'index' or an int, got {id!r}") # do sorting in here @@ -2481,7 +2483,9 @@ def ComboFeature( # call it kp = detector(self._A, **det_opts) else: - raise ValueError("unknown detector") + raise ValueError( + f"detector must be a callable or one of {list(detectors)}, got {detector!r}" + ) raise NotImplementedError("ComboFeature is a work in progress") diff --git a/src/machinevisiontoolbox/ImageProcessing.py b/src/machinevisiontoolbox/ImageProcessing.py index a909648a..04082f08 100644 --- a/src/machinevisiontoolbox/ImageProcessing.py +++ b/src/machinevisiontoolbox/ImageProcessing.py @@ -543,12 +543,12 @@ def threshold( elif auto == "percentile": autothresh = np.percentile(arr, p) else: - raise ValueError(auto, "unknown automatic threshold method") + raise ValueError(f"unknown automatic threshold method, got {auto!r}") threshold = autothresh if not argcheck.isscalar(threshold): - raise ValueError(threshold, "threshold must be a scalar") + raise ValueError(f"threshold must be a scalar, got {threshold!r}") if mode == "binary": imt = np.where(arr > threshold, true_value, false_value).astype( @@ -565,7 +565,7 @@ def threshold( elif mode in ("/tozero", "tozero_inv"): imt = np.where(arr <= threshold, arr, 0) else: - raise ValueError(mode, "unknown threshold method") + raise ValueError(f"unknown threshold method, got {mode!r}") if mode in ("binary", "binary_inv"): out = self.__class__(imt) @@ -639,7 +639,7 @@ def threshold_interactive( mode = mode.lower() if mode not in ("binary", "tozero"): - raise ValueError(mode, "unknown threshold mode") + raise ValueError(f"unknown threshold mode, got {mode!r}") img = self._A img_min = float(np.min(img)) @@ -1262,9 +1262,13 @@ def paste( top = int(top) if (top + ph) > ch: - raise ValueError(ph, "pattern falls off bottom edge") + raise ValueError( + f"pattern falls off bottom edge: top {top} + height {ph} > image height {ch}" + ) if (left + pw) > cw: - raise ValueError(pw, "pattern falls off right edge") + raise ValueError( + f"pattern falls off right edge: left {left} + width {pw} > image width {cw}" + ) npc = pattern.nplanes nc = self.nplanes diff --git a/src/machinevisiontoolbox/ImageReshape.py b/src/machinevisiontoolbox/ImageReshape.py index c0ffdd88..5d53319f 100644 --- a/src/machinevisiontoolbox/ImageReshape.py +++ b/src/machinevisiontoolbox/ImageReshape.py @@ -579,7 +579,7 @@ def decimate(self, m: int = 2, sigma: float | None = None) -> Self: :seealso: :meth:`replicate` :meth:`scale` """ if (m - np.ceil(m)) != 0: - raise ValueError(m, "decimation factor m must be an integer") + raise ValueError(f"decimation factor m must be an integer, got {m!r}") if sigma is None: sigma = m / 2 @@ -779,7 +779,7 @@ def samesize(self, image2: Any, bias: float = 0.5) -> Self: """ # check inputs if bias < 0 or bias > 1: - raise ValueError(bias, "bias must be in range [0, 1]") + raise ValueError(f"bias must be in range [0, 1], got {bias!r}") im = self._A @@ -851,7 +851,7 @@ def scale( """ # check inputs if not smb.isscalar(sfactor): - raise TypeError(sfactor, "factor is not a scalar") + raise TypeError(f"factor is not a scalar, got {sfactor!r}") interp: int if interpolation is None: @@ -924,7 +924,7 @@ def rotate(self, angle: float, centre=None, center=None) -> Self: # using-opencv/ if not smb.isscalar(angle): - raise ValueError(angle, "angle is not a valid scalar") + raise ValueError(f"angle is not a valid scalar, got {angle!r}") if center is not None and centre is None: centre = center diff --git a/src/machinevisiontoolbox/ImageSpatial.py b/src/machinevisiontoolbox/ImageSpatial.py index b996f6f1..bd892a25 100644 --- a/src/machinevisiontoolbox/ImageSpatial.py +++ b/src/machinevisiontoolbox/ImageSpatial.py @@ -87,7 +87,9 @@ def _bordertype_cv( try: return border_opt[border] except KeyError: - raise ValueError(border, "border is not a valid option") + raise ValueError( + f"border must be one of {list(border_opt)}, got {border!r}" + ) @staticmethod def _bordertype_sp( @@ -122,7 +124,9 @@ def _bordertype_sp( try: return border_opt[border] except KeyError: - raise ValueError(border, "border is not a valid option") + raise ValueError( + f"border must be one of {list(border_opt)}, got {border!r}" + ) def smooth( self, @@ -175,7 +179,7 @@ def smooth( """ if not argcheck.isscalar(sigma): - raise ValueError(sigma, "sigma must be a scalar") + raise ValueError(f"sigma must be a scalar, got {sigma!r}") # make the smoothing kernel K = Kernel.Gauss(sigma, h) @@ -288,7 +292,7 @@ def convolve( modeopt = ["valid", "same", "full"] if mode not in modeopt: - raise ValueError(mode, "opt is not a valid option") + raise ValueError(f"mode must be one of {modeopt}, got {mode!r}") self._opencv_type_check( self._A, "multiple-channel", "CV_8U", "CV_16U", "CV_16S", "CV_32F", "CV_64F" @@ -514,7 +518,7 @@ def window( raise ValueError("single channel images only") if not callable(func): - raise TypeError(func, "func not callable") + raise TypeError(f"func not callable, got {func!r}") if h is not None and se is None: w = 2 * h + 1 @@ -679,15 +683,14 @@ def pyramid( ) if not argcheck.isscalar(sigma): - raise ValueError(sigma, "sigma must be a scalar") + raise ValueError(f"sigma must be a scalar, got {sigma!r}") if N is None: N = max(im.shape) else: if (not argcheck.isscalar(N)) and (N >= 0) and (N <= max(im.shape)): raise ValueError( - N, - "N must be a scalar and 0 <= N <= max(im.shape)", + f"N must be a scalar and 0 <= N <= max(im.shape), got {N!r}", ) # TODO options to accept different border types, @@ -951,9 +954,9 @@ def rankfilter( elif rank in ("med", "median"): rank = n // 2 else: - raise ValueError(rank, "unknown rank name") + raise ValueError(f"unknown rank name, got {rank!r}") elif not isinstance(rank, int): - raise TypeError(rank, "rank must be int or str") + raise TypeError(f"rank must be int or str, got {rank!r}") if rank < 0: raise ValueError("rank must be >= 0") @@ -1158,7 +1161,7 @@ def labels_binary( :meth:`labels_MSER` """ if not (connectivity in [4, 8]): - raise ValueError(connectivity, "connectivity must be 4 or 8") + raise ValueError(f"connectivity must be 4 or 8, got {connectivity!r}") self._opencv_type_check(self._A, "single-channel", "CV_8U") # make labels uint32s, unique and never recycled? @@ -1168,7 +1171,7 @@ def labels_binary( elif ltype == "uint16": cvtype = cv2.CV_16U else: - raise TypeError(ltype, "ltype must be either int32 or uint16") + raise TypeError(f"ltype must be either int32 or uint16, got {ltype!r}") retval, labels = cv2.connectedComponents( image=self.array_as("uint8"), connectivity=connectivity, ltype=cvtype diff --git a/src/machinevisiontoolbox/ImageWholeFeatures.py b/src/machinevisiontoolbox/ImageWholeFeatures.py index cb20ecaf..a6fb444f 100644 --- a/src/machinevisiontoolbox/ImageWholeFeatures.py +++ b/src/machinevisiontoolbox/ImageWholeFeatures.py @@ -584,7 +584,7 @@ def mpq(self, p: int, q: int) -> float: """ if not isinstance(p, int) or not isinstance(q, int): - raise TypeError(p, "p, q must be an int") + raise TypeError(f"p, q must be an int, got p={p!r}, q={q!r}") im = self.mono()._A X, Y = self.meshgrid() @@ -628,7 +628,7 @@ def upq(self, p: int, q: int) -> float: """ if not isinstance(p, int) or not isinstance(q, int): - raise TypeError(p, "p, q must be an int") + raise TypeError(f"p, q must be an int, got p={p!r}, q={q!r}") m00 = self.mpq(0, 0) xc = self.mpq(1, 0) / m00 @@ -677,9 +677,11 @@ def npq(self, p: int, q: int) -> float: :seealso: :meth:`sum` :meth:`mpq` :meth:`upq` """ if not isinstance(p, int) or not isinstance(q, int): - raise TypeError(p, "p, q must be an int") + raise TypeError(f"p, q must be an int, got p={p!r}, q={q!r}") if (p + q) < 2: - raise ValueError(p + q, "normalized moments only valid for p+q >= 2") + raise ValueError( + f"normalized moments only valid for p+q >= 2, got p+q={p + q}" + ) g = (p + q) / 2 + 1 @@ -1720,7 +1722,7 @@ def on_move(event): ax.legend(loc="best") else: - raise ValueError("unknown style") + raise ValueError(f"style must be 'stack' or 'overlay', got {style!r}") if title is not None: set_window_title(plt.gcf(), title) @@ -1761,7 +1763,7 @@ def _compute_plot_series( ylabel1 = "CDF" ylabel2 = "normalized cumulative frequency" else: - raise ValueError("unknown type") + raise ValueError(f"unknown histogram type {type!r}") return y, maxy, ylabel1, ylabel2 diff --git a/src/machinevisiontoolbox/Sources.py b/src/machinevisiontoolbox/Sources.py index 966b6010..3beac626 100644 --- a/src/machinevisiontoolbox/Sources.py +++ b/src/machinevisiontoolbox/Sources.py @@ -160,7 +160,9 @@ def u32() -> int: if cdr: pos += (-(pos - origin)) % 4 # CDR aligns fields to their size if pos + 4 > len(raw): - raise ValueError("truncated") + raise ValueError( + f"message truncated: need {pos + 4} bytes, have {len(raw)}" + ) value = struct.unpack_from(order + "I", raw, pos)[0] pos += 4 return value @@ -169,7 +171,9 @@ def skip(n: int) -> None: nonlocal pos pos += n if pos > len(raw): - raise ValueError("truncated") + raise ValueError( + f"message truncated: need {pos} bytes, have {len(raw)}" + ) try: if cdr: diff --git a/src/machinevisiontoolbox/VisualServo.py b/src/machinevisiontoolbox/VisualServo.py index 1e494f02..9a17d7ec 100644 --- a/src/machinevisiontoolbox/VisualServo.py +++ b/src/machinevisiontoolbox/VisualServo.py @@ -140,7 +140,7 @@ def __init__( def step(self, t: float) -> int: """Compute one timestep of the simulation, implemented by subclasses.""" - raise NotImplementedError + raise NotImplementedError(f"{type(self).__name__} must implement step()") def init(self) -> None: """ diff --git a/src/machinevisiontoolbox/base/color.py b/src/machinevisiontoolbox/base/color.py index 1cf64a64..1ded56bd 100755 --- a/src/machinevisiontoolbox/base/color.py +++ b/src/machinevisiontoolbox/base/color.py @@ -706,7 +706,7 @@ def _loadrgbdict(fname: str) -> dict[str, np.ndarray]: """ if not isinstance(fname, str): - raise ValueError(fname, "file name must be a string") + raise ValueError(f"file name must be a string, got {fname!r}") data = _loaddata(fname, comments="#", dtype=None, encoding="ascii") @@ -796,7 +796,9 @@ def csconvert(name: str, cs: str) -> np.ndarray: Lab = colorspace_convert(rgb, "rgb", "lab") return Lab[1:] else: - raise ValueError("unknown colorspace") + raise ValueError( + f"unknown colorspace {cs!r}, must be rgb, xyz, lab, xy or ab" + ) if any([c in ".?*" for c in name]): # has a wildcard @@ -890,7 +892,9 @@ def color2name(color: np.ndarray | list[float], colorspace: str = "RGB") -> str: k = np.nanargmin(dist) return list(colors.get_named_colors_mapping())[k] else: - raise ValueError("unknown colorspace") + raise ValueError( + f"unknown colorspace {colorspace!r}, must be rgb, xyz, lab, xy or ab" + ) def colorname( @@ -1160,7 +1164,7 @@ def plot_chromaticity_diagram( plt.xlabel("a*") plt.ylabel("b*") else: - raise ValueError("bad colorspace") + raise ValueError(f"unknown colorspace {colorspace!r}, must be xy or ab") set_window_title(plt.gcf(), "Chromaticity Diagram" if title is None else title) @@ -1257,7 +1261,7 @@ def plot_spectral_locus( x = rgb[:, 0] / np.sum(rgb, axis=1) y = rgb[:, 1] / np.sum(rgb, axis=1) else: - raise ValueError("bad colorspace") + raise ValueError(f"unknown colorspace {colorspace!r}, must be xy or rg") ax.plot(x, y, "ko") diff --git a/src/machinevisiontoolbox/base/graphics.py b/src/machinevisiontoolbox/base/graphics.py index 71186121..87999228 100644 --- a/src/machinevisiontoolbox/base/graphics.py +++ b/src/machinevisiontoolbox/base/graphics.py @@ -779,7 +779,10 @@ def draw_point( x = [pos[0]] y = [pos[1]] else: - raise ValueError("bad input") + raise ValueError( + "pos must be a 2xN array, a 2-tuple or list, or a list of 2-tuples, " + f"got {type(pos).__name__}" + ) newmarker = "" markercolor = "" diff --git a/src/machinevisiontoolbox/base/imageio.py b/src/machinevisiontoolbox/base/imageio.py index 46c8d94e..5ba69db3 100644 --- a/src/machinevisiontoolbox/base/imageio.py +++ b/src/machinevisiontoolbox/base/imageio.py @@ -1200,7 +1200,7 @@ def iread( try: return next(iterator) except StopIteration as exc: - raise ValueError(filename, "invalid filename") from exc + raise ValueError(f"invalid filename, got {filename!r}") from exc def iread_iter( @@ -1277,7 +1277,7 @@ def iread_iter( return else: - raise ValueError(filename, "invalid filename") + raise ValueError(f"invalid filename, got {filename!r}") def convert( diff --git a/src/machinevisiontoolbox/base/shapes.py b/src/machinevisiontoolbox/base/shapes.py index 95b37b2d..8e035c80 100644 --- a/src/machinevisiontoolbox/base/shapes.py +++ b/src/machinevisiontoolbox/base/shapes.py @@ -62,7 +62,7 @@ def mkgrid( sx = sidev[0] sy = sidev[1] else: - raise ValueError("bad s") + raise ValueError(f"side must have 1 or 2 elements, got {len(sidev)}") nv = smb.getvector(n) if len(nv) == 1: diff --git a/tests/test_error_messages.py b/tests/test_error_messages.py new file mode 100644 index 00000000..4a67e78d --- /dev/null +++ b/tests/test_error_messages.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +"""Error messages should say what was received and what is allowed.""" + +import numpy as np +import pytest + +from machinevisiontoolbox import CentralCamera, Image, mkgrid +from machinevisiontoolbox.base.color import color2name + + +class TestMessagesNameTheValue: + def test_unknown_colorspace(self): + with pytest.raises(ValueError, match="unknown colorspace 'foo'"): + color2name([1, 0, 0], "foo") + + def test_wrong_side_length(self): + with pytest.raises(ValueError, match="1 or 2 elements, got 3"): + mkgrid(side=[1, 2, 3]) + + def test_convolve_mode(self): + with pytest.raises(ValueError, match="mode must be one of.*got 'wrong'"): + Image.Squares(1, size=20).convolve(np.ones((3, 3)), mode="wrong") + + def test_planes_mismatch(self): + a = Image(np.zeros((4, 4, 3), dtype=np.uint8), colororder="RGB") + b = Image(np.zeros((4, 4, 2), dtype=np.uint8)) + with pytest.raises(ValueError, match="3 and 2"): + a + b + + def test_fundamental_matrix_needs_a_camera_or_pose(self): + camera = CentralCamera.Default() + with pytest.raises(ValueError, match="CentralCamera or SE3, got int"): + camera.F(5) + with pytest.raises(ValueError, match="fundamental matrix, got str"): + camera.E("a") + + def test_integer_arguments_report_the_value(self): + with pytest.raises(ValueError, match="n must be greater than 0, got 0"): + Image.Squares(1, size=20).erode(np.ones((3, 3)), n=0) + + def test_base_class_step_names_the_class(self): + from machinevisiontoolbox.VisualServo import VisualServo + + with pytest.raises(NotImplementedError, match="must implement step"): + VisualServo.step(object.__new__(VisualServo), 0.0) diff --git a/tests/test_image_point_features_extra.py b/tests/test_image_point_features_extra.py index e862cca2..c70c8945 100644 --- a/tests/test_image_point_features_extra.py +++ b/tests/test_image_point_features_extra.py @@ -452,9 +452,9 @@ def test_indexing(self, fmatch): nt.assert_array_equal(fmatch[np.array([3, 0])].id1, [3, 0]) def test_bad_index(self, fmatch): - with pytest.raises(ValueError, match="bad index$"): + with pytest.raises(ValueError, match="index must be an int, slice"): fmatch["a"] - with pytest.raises(ValueError, match="bad index dtype"): + with pytest.raises(ValueError, match="index array must be integer or bool"): fmatch[np.array([0.5])] def test_by_id(self, fmatch): @@ -777,7 +777,7 @@ def test_id_from_the_image(self): nt.assert_array_equal(im.SIFT(nfeat=3).id, [3, 3, 3]) def test_bad_id(self, checkerboard): - with pytest.raises(ValueError, match="bad id"): + with pytest.raises(ValueError, match="id must be .image., .index. or an int"): checkerboard.SIFT(id="name") def test_bad_algorithm(self, checkerboard): diff --git a/tests/test_image_spatial_extra.py b/tests/test_image_spatial_extra.py index 34825335..38a623e3 100644 --- a/tests/test_image_spatial_extra.py +++ b/tests/test_image_spatial_extra.py @@ -151,7 +151,7 @@ def test_border_options(self, square, border): assert square.window(np.mean, h=1, border=border).shape == (40, 40) def test_bad_border(self, square): - with pytest.raises(ValueError, match="not a valid option"): + with pytest.raises(ValueError, match="border must be one of"): square.window(np.max, h=1, border="outside")