Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions monai/transforms/io/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,12 @@ def __init__(
the_reader = look_up_option(_r.lower(), SUPPORTED_READERS)
try:
self.register(the_reader(*args, **kwargs))
except OptionalImportError:
warnings.warn(
f"required package for reader {_r} is not installed, or the version doesn't match requirement."
)
except OptionalImportError as e:
raise RuntimeError(
f"The required package for reader '{_r}' is not installed, or the version doesn't match "
f"the requirement. If you want to use '{_r}', please install the required package. "
f"If you want to use an alternative reader, do not specify the `reader` argument."
) from e
except TypeError: # the reader doesn't have the corresponding args/kwargs
warnings.warn(f"{_r} is not supported with the given parameters {args} {kwargs}.")
self.register(the_reader())
Expand Down
31 changes: 31 additions & 0 deletions tests/transforms/test_load_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -498,5 +498,36 @@ def test_correct(self, input_param, expected_shape, track_meta):
self.assertFalse(hasattr(r, "affine"))




class TestLoadImageMissingReader(unittest.TestCase):
"""Test that LoadImage raises RuntimeError when a user-specified reader is not installed."""

def test_explicit_reader_not_installed_raises_runtime_error(self):
"""When the user explicitly names a reader whose package is missing, a RuntimeError must be raised."""
from unittest.mock import patch
from monai.utils import OptionalImportError

# Patch the reader class so that instantiation raises OptionalImportError,
# simulating a missing optional dependency (e.g. itk not installed).
with patch("monai.data.ITKReader.__init__", side_effect=OptionalImportError("itk")):
with self.assertRaises(RuntimeError) as ctx:
LoadImage(reader="ITKReader")
self.assertIn("ITKReader", str(ctx.exception))
self.assertIn("not installed", str(ctx.exception))

def test_unspecified_reader_falls_back_silently(self):
"""When no reader is specified, missing optional readers should be silently skipped (no exception)."""
# This should not raise even if some optional readers are unavailable.
loader = LoadImage()
self.assertIsInstance(loader, LoadImage)

def test_explicit_reader_available_succeeds(self):
"""When the user explicitly names a reader whose package IS installed, no exception is raised."""
# NibabelReader is always available (nibabel is a core dep)
loader = LoadImage(reader="NibabelReader")
self.assertIsInstance(loader, LoadImage)


if __name__ == "__main__":
unittest.main()
Loading