From eb7d0f5fabbc1a71e8367c7b96e66241c4b7f121 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Sun, 22 Nov 2026 11:05:37 +1000 Subject: [PATCH] fix: LabelMeReader raises on unreadable input instead of returning None Remove the broad try/except in LabelMeReader.__init__, which swallowed OSError and JSON errors and returned a half-initialised reader. The original exception now propagates. Adds tests for a missing file and for invalid JSON. Refs #150 Co-Authored-By: zw1915 <134981642+zw1915@users.noreply.github.com> Co-Authored-By: Claude Sonnet 5.5 --- src/machinevisiontoolbox/Sources.py | 23 +++++++++++++---------- tests/test_image_sources.py | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 10 deletions(-) diff --git a/src/machinevisiontoolbox/Sources.py b/src/machinevisiontoolbox/Sources.py index ab27bdd2..89d2f791 100644 --- a/src/machinevisiontoolbox/Sources.py +++ b/src/machinevisiontoolbox/Sources.py @@ -4444,6 +4444,12 @@ class LabelMeReader: :param filename: path to LabelMe JSON file, or an ``http(s)://`` URL :type filename: str + :raises OSError: if the file cannot be opened or the URL cannot be fetched + :raises json.JSONDecodeError: if the content is not valid JSON + + .. versionchanged:: 2.5.0 + An unreadable file or invalid JSON now raises, where it used to return an + incompletely initialised reader. LabelMe is a popular annotation tool that saves annotations in a JSON format. This class reads the JSON file and extracts the image, polygonal shapes, and associated @@ -4492,17 +4498,14 @@ class reads the JSON file and extracts the image, polygonal shapes, and associat def __init__(self, filename: str) -> None: self.filename = filename - try: - if str(filename).startswith(("http://", "https://")): - import urllib.request + if str(filename).startswith(("http://", "https://")): + import urllib.request - with urllib.request.urlopen(filename) as response: # noqa: S310 - self.data = json.loads(response.read().decode("utf-8")) - else: - with open(self.filename, "r", encoding="utf-8") as f: - self.data = json.load(f) - except (OSError, json.JSONDecodeError, TypeError, ValueError): - return None + with urllib.request.urlopen(filename) as response: # noqa: S310 + self.data = json.loads(response.read().decode("utf-8")) + else: + with open(self.filename, "r", encoding="utf-8") as f: + self.data = json.load(f) self._nshapes = len(self.data.get("shapes", [])) self._version = self.data.get("version") diff --git a/tests/test_image_sources.py b/tests/test_image_sources.py index 1710fad8..7459fa3a 100644 --- a/tests/test_image_sources.py +++ b/tests/test_image_sources.py @@ -607,6 +607,27 @@ def test_labelme_read(self): self.assertEqual(shapes[1].flags, {"hard": False}) +class TestLabelMeReaderErrors(unittest.TestCase): + """A LabelMe file that cannot be read raises, it does not return a half-built reader.""" + + def test_missing_file_raises(self): + from machinevisiontoolbox import LabelMeReader + + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(FileNotFoundError): + LabelMeReader(os.path.join(tmp, "missing.json")) + + def test_invalid_json_raises(self): + from machinevisiontoolbox import LabelMeReader + + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "bad.json") + with open(path, "w", encoding="utf-8") as f: + f.write("{ this is not json") + with self.assertRaises(json.JSONDecodeError): + LabelMeReader(path) + + class TestEarthViewKey(unittest.TestCase): """How EarthView finds its API key (no network access needed)."""