|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +"""Test to verify the changes to LoadImage raise_on_missing_reader flag work correctly.""" |
| 4 | + |
| 5 | +import warnings |
| 6 | +from monai.transforms import LoadImage |
| 7 | +from monai.utils import OptionalImportError |
| 8 | + |
| 9 | +def test_raise_on_missing_reader(): |
| 10 | + """Test the raise_on_missing_reader flag behavior.""" |
| 11 | + print("Testing LoadImage raise_on_missing_reader flag...") |
| 12 | + |
| 13 | + # Test 1: Unknown reader with flag enabled - should raise OptionalImportError |
| 14 | + print("Test 1: Unknown reader with raise_on_missing_reader=True") |
| 15 | + try: |
| 16 | + LoadImage(reader="UnknownReader", raise_on_missing_reader=True) |
| 17 | + print("FAIL: Expected OptionalImportError but didn't get one") |
| 18 | + return False |
| 19 | + except OptionalImportError as e: |
| 20 | + print(f"PASS: Got expected OptionalImportError: {e}") |
| 21 | + |
| 22 | + # Test 2: Unknown reader with flag disabled - should warn but not raise |
| 23 | + print("\nTest 2: Unknown reader with raise_on_missing_reader=False") |
| 24 | + try: |
| 25 | + with warnings.catch_warnings(record=True) as w: |
| 26 | + warnings.simplefilter("always") |
| 27 | + loader = LoadImage(reader="UnknownReader", raise_on_missing_reader=False) |
| 28 | + if w and "UnknownReader" in str(w[0].message): |
| 29 | + print(f"PASS: Got expected warning: {w[0].message}") |
| 30 | + else: |
| 31 | + print("WARNING: Warning message may have been different than expected") |
| 32 | + print("PASS: LoadImage instance created successfully with fallback behavior") |
| 33 | + except OptionalImportError as e: |
| 34 | + print(f"FAIL: Unexpected OptionalImportError with flag disabled: {e}") |
| 35 | + return False |
| 36 | + except Exception as e: |
| 37 | + print(f"FAIL: Unexpected error: {e}") |
| 38 | + return False |
| 39 | + |
| 40 | + # Test 3: Valid reader - should work regardless of flag |
| 41 | + print("\nTest 3: Valid reader (PILReader) with both flag settings") |
| 42 | + try: |
| 43 | + loader1 = LoadImage(reader="PILReader", raise_on_missing_reader=True) |
| 44 | + loader2 = LoadImage(reader="PILReader", raise_on_missing_reader=False) |
| 45 | + print("PASS: Both loaders created successfully with valid reader") |
| 46 | + except Exception as e: |
| 47 | + print(f"FAIL: Unexpected error with valid reader: {e}") |
| 48 | + return False |
| 49 | + |
| 50 | + print("\nAll tests passed!") |
| 51 | + return True |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + success = test_raise_on_missing_reader() |
| 55 | + exit(0 if success else 1) |
0 commit comments