Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ The released versions correspond to PyPi releases.
## Unreleased

### Fixes
* File validation restores the caller's pydicom reading validation mode after
dataset validation and result handling, including when either raises an error.
* DICOM filenames in HTML report headings are escaped so markup characters
remain filename text.

Expand Down
114 changes: 112 additions & 2 deletions dicom_validator/tests/validator/test_dicom_file_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,16 @@

import pydicom
import pytest
from pydicom import dcmwrite
from pydicom import DataElement, config, dcmread, dcmwrite
from pydicom.dataset import Dataset, FileDataset, FileMetaDataset

from dicom_validator.validator.dicom_file_validator import DicomFileValidator
from dicom_validator.validator.dicom_file_validator import (
DicomFileValidator,
set_validation_mode,
)
from dicom_validator.validator.dicom_info import DicomInfo
from dicom_validator.validator.error_handler import NullValidationResultHandler
from dicom_validator.validator.iod_validator import IODValidator
from dicom_validator.validator.validation_result import DicomTag, ErrorCode, Status

pytestmark = pytest.mark.usefixtures("disable_logging")
Expand Down Expand Up @@ -107,3 +113,107 @@ def test_that_pixeldata_is_read(dicom_fixture_path, validator: DicomFileValidato
assert oper_name_error.code == ErrorCode.TagMissing
# if PixelData is not read, RT Dose will show errors
assert "RT Dose" not in result.module_errors


@pytest.fixture(params=[config.IGNORE, config.WARN, config.RAISE])
def reading_mode(request, monkeypatch):
monkeypatch.setattr(config.settings, "reading_validation_mode", request.param)
return request.param


@pytest.fixture
def mode_validator():
return DicomFileValidator(
DicomInfo({}, {}, {}), error_handler=NullValidationResultHandler()
)


@pytest.fixture
def deferred_dicom_file(tmp_path):
filename = str(tmp_path / "deferred.dcm")
dataset = FileDataset(
filename, Dataset(), file_meta=TestFakeDicomFileValidator.create_metadata()
)
dataset.SOPClassUID = dataset.file_meta.MediaStorageSOPClassUID
dataset.add(
DataElement("PatientID", "LO", "A" * 2048, validation_mode=config.IGNORE)
)
dcmwrite(filename, dataset, **TestFakeDicomFileValidator.enforce_file_format())
# The oversized LO value is deferred by the same threshold used in validate_file.
assert dcmread(filename, defer_size=1024)._dict[0x0010_0020].value is None
return filename


def test_reading_mode_restored_after_validation(
mode_validator, deferred_dicom_file, reading_mode
):
writing_mode = config.settings.writing_validation_mode
result = mode_validator.validate_file(deferred_dicom_file)[deferred_dicom_file]
assert result.status == Status.UnknownSOPClassUID
assert config.settings.reading_validation_mode == reading_mode
assert config.settings.writing_validation_mode == writing_mode


def test_reading_mode_restored_after_invalid_file(
mode_validator, tmp_path, reading_mode
):
filename = str(tmp_path / "invalid.dcm")
Path(filename).write_bytes(b"not a DICOM file")
result = mode_validator.validate_file(filename)[filename]
assert result.status == Status.InvalidFile
assert config.settings.reading_validation_mode == reading_mode


def test_reading_mode_restored_after_read_error(mode_validator, tmp_path, reading_mode):
with pytest.raises(FileNotFoundError):
mode_validator.validate_file(str(tmp_path / "missing.dcm"))
assert config.settings.reading_validation_mode == reading_mode


@pytest.mark.parametrize("method", ["__init__", "validate"])
def test_reading_mode_restored_after_validation_error(
mode_validator, deferred_dicom_file, reading_mode, method, monkeypatch
):
def fail_validation(self, *args, **kwargs):
assert config.settings.reading_validation_mode == config.IGNORE
raise RuntimeError("validation failed")

monkeypatch.setattr(IODValidator, method, fail_validation)
with pytest.raises(RuntimeError, match="validation failed"):
mode_validator.validate_file(deferred_dicom_file)
assert config.settings.reading_validation_mode == reading_mode


@pytest.mark.parametrize("invalid_file", [False, True])
def test_reading_mode_restored_after_handler_error(
mode_validator, deferred_dicom_file, reading_mode, invalid_file, monkeypatch
):
def fail_handler(result):
assert config.settings.reading_validation_mode == config.IGNORE
raise RuntimeError("handler failed")

if invalid_file:
Path(deferred_dicom_file).write_bytes(b"not a DICOM file")
monkeypatch.setattr(
mode_validator._error_handler, "handle_validation_result", fail_handler
)
with pytest.raises(RuntimeError, match="handler failed"):
mode_validator.validate_file(deferred_dicom_file)
assert config.settings.reading_validation_mode == reading_mode


@pytest.mark.parametrize("temporary_mode", [config.IGNORE, config.WARN, config.RAISE])
def test_validation_mode_context_restores_nested_modes(reading_mode, temporary_mode):
writing_mode = config.settings.writing_validation_mode
with set_validation_mode(temporary_mode):
assert config.settings.reading_validation_mode == temporary_mode
with (
pytest.raises(RuntimeError, match="inner failure"),
set_validation_mode(config.IGNORE),
):
assert config.settings.reading_validation_mode == config.IGNORE
raise RuntimeError("inner failure")
assert config.settings.reading_validation_mode == temporary_mode
assert config.settings.writing_validation_mode == writing_mode
assert config.settings.reading_validation_mode == reading_mode
assert config.settings.writing_validation_mode == writing_mode
72 changes: 47 additions & 25 deletions dicom_validator/validator/dicom_file_validator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import logging
import os
from collections.abc import Iterator
from contextlib import contextmanager
from os import PathLike

from pydicom import config, dcmread
Expand All @@ -14,6 +16,21 @@
from dicom_validator.validator.validation_result import Status, ValidationResult


@contextmanager
def set_validation_mode(mode: int) -> Iterator[None]:
"""Temporarily set pydicom's process-wide reading validation mode.

Restore the previous mode on exit, including when the body raises.
This does not change writing validation and is not thread-safe.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably better name it set_reading_validation_mode, so there is no need to clarify this in the comment.

"""
reading_mode = config.settings.reading_validation_mode
try:
config.settings.reading_validation_mode = mode
yield
finally:
config.settings.reading_validation_mode = reading_mode


class DicomFileValidator:
"""Validates a single DICOM file or all DICOM files in a directory."""

Expand Down Expand Up @@ -106,32 +123,37 @@ def validate_file(self, file_path: str) -> dict[str, ValidationResult]:
-------
dict[str, ValidationResult]
A mapping containing exactly one entry for the given file.

Notes
-----
Temporarily disables pydicom's process-wide reading validation until
dataset validation and result handling finish, including deferred reads.
This is not thread-safe with concurrent pydicom reads.
"""
try:
# dcmread calls validate_value by default. If values don't match
# required VR (value representation), it emits a warning but
# does not provide the tag and value that caused the warning.
# We will handle it later (optionally) by calling validate_value
# directly.
config.settings.reading_validation_mode = config.IGNORE
data_set = dcmread(file_path, defer_size=1024, force=self._force_read)

except InvalidDicomError:
result = ValidationResult(file_path=file_path, status=Status.InvalidFile)
self.handle_error(result)
return {
file_path: result,
}
return {
file_path: IODValidator(
data_set,
self._dicom_info,
log_level=self.log_level,
suppress_vr_warnings=self._suppress_vr_warnings,
error_handler=self._error_handler,
file_path=file_path,
).validate()
}
with set_validation_mode(config.IGNORE):
try:
# dcmread calls validate_value by default. If values don't match
# required VR (value representation), it emits a warning but
# does not provide the tag and value that caused the warning.
# We will handle it later (optionally) by calling validate_value
# directly.
data_set = dcmread(file_path, defer_size=1024, force=self._force_read)

except InvalidDicomError:
result = ValidationResult(
file_path=file_path, status=Status.InvalidFile
)
self.handle_error(result)
else:
result = IODValidator(
data_set,
self._dicom_info,
log_level=self.log_level,
suppress_vr_warnings=self._suppress_vr_warnings,
error_handler=self._error_handler,
file_path=file_path,
).validate()
return {file_path: result}

def handle_error(self, result: ValidationResult) -> None:
handler = self._error_handler or default_error_handler(
Expand Down
Loading