diff --git a/package/src/pyaslreport/main.py b/package/src/pyaslreport/main.py index 553e7e5e..6b37c563 100644 --- a/package/src/pyaslreport/main.py +++ b/package/src/pyaslreport/main.py @@ -46,24 +46,16 @@ def get_dicom_header(dicom_dir: str): # Get all files in the directory all_files = [f for f in os.listdir(dicom_dir) if os.path.isfile(os.path.join(dicom_dir, f))] - # Try to find DICOM files by attempting to read them with pydicom - dcm_files = [] + # Return the first readable DICOM header instead of scanning the whole directory + # and reading the winning file a second time. for file in all_files: file_path = os.path.join(dicom_dir, file) try: - # Try to read the file as DICOM - pydicom.dcmread(file_path, stop_before_pixels=True) - dcm_files.append(file) + dcm_header = pydicom.dcmread(file_path, stop_before_pixels=True) + log.info(f"Found a readable DICOM file in {dicom_dir}: {file}") + return dcm_header except (InvalidDicomError, OSError, PermissionError): # File is not a valid DICOM file or cannot be read continue - log.info(f"Found {len(dcm_files)} DICOM files in {dicom_dir}") - - if not dcm_files: - raise ValueError(f"No DICOM files found in directory: {dicom_dir}") - - # Read the first valid DICOM file - dcm_header = pydicom.dcmread(os.path.join(dicom_dir, dcm_files[0])) - - return dcm_header \ No newline at end of file + raise ValueError(f"No DICOM files found in directory: {dicom_dir}") \ No newline at end of file diff --git a/package/src/pyaslreport/tests/test_get_dicom_header.py b/package/src/pyaslreport/tests/test_get_dicom_header.py new file mode 100644 index 00000000..3510bee7 --- /dev/null +++ b/package/src/pyaslreport/tests/test_get_dicom_header.py @@ -0,0 +1,23 @@ +from pathlib import Path +from unittest.mock import patch + +from pyaslreport.main import get_dicom_header + + +def test_get_dicom_header_returns_first_valid_header_without_scanning_rest(tmp_path): + first_file = tmp_path / "first.dcm" + second_file = tmp_path / "second.dcm" + first_file.write_bytes(b"first") + second_file.write_bytes(b"second") + + calls = [] + + def fake_dcmread(path, stop_before_pixels=True): + calls.append(Path(path).name) + return {"path": Path(path).name} + + with patch("pyaslreport.main.pydicom.dcmread", side_effect=fake_dcmread): + header = get_dicom_header(str(tmp_path)) + + assert header == {"path": "first.dcm"} + assert calls == ["first.dcm"]