Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -7,6 +7,8 @@ The released versions correspond to PyPi releases.
### Fixes
* File validation restores the caller's pydicom reading validation mode after
dataset validation and result handling, including when either raises an error.
* Optional HTML report links no longer interrupt reporting on network or HTTP
errors, and link-check connections are closed after use.
* DICOM filenames in HTML report headings are escaped so markup characters
remain filename text.

Expand Down
32 changes: 20 additions & 12 deletions dicom_validator/tests/validator/test_error_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,32 @@ def dicom_fixture_path():
yield Path(__file__).parent.parent / "fixtures" / "dicom"


def test_html_error_handler(dicom_info, dicom_fixture_path) -> None:
@pytest.fixture
def html_handler(dicom_info, monkeypatch):
monkeypatch.setattr(HtmlErrorHandler, "valid_refs", {})
monkeypatch.setattr(
HtmlErrorHandler,
"url_exists",
staticmethod(lambda url: url == HtmlErrorHandler.url_for_ref("C.8.8")),
)
return HtmlErrorHandler(dicom_info)


def test_html_error_handler(dicom_info, dicom_fixture_path, html_handler) -> None:
rtdose_path = dicom_fixture_path / "rtdose.dcm"
handler = HtmlErrorHandler(dicom_info)
validator = DicomFileValidator(dicom_info, error_handler=handler)
validator = DicomFileValidator(dicom_info, error_handler=html_handler)
validator.validate(rtdose_path)
assert (
'<h3><a href="https://dicom.nema.org/medical/dicom/current/output/chtml/part03'
'/sect_C.8.8.html">RT Series</a></h3>' in handler.html
'/sect_C.8.8.html">RT Series</a></h3>' in html_handler.html
)


def test_html_error_handler_failed_validation(dicom_info, validator) -> None:
def test_html_error_handler_failed_validation(validator, html_handler) -> None:
"""Check that a failed validation is reported."""
handler = HtmlErrorHandler(dicom_info)
validator.handler = handler
validator.handler = html_handler
validator.validate()
assert "<p>Missing SOP Class UID</p>" in handler.html
assert "<p>Missing SOP Class UID</p>" in html_handler.html


@pytest.mark.tag_set(
Expand All @@ -85,14 +94,13 @@ def test_html_error_handler_failed_validation(dicom_info, validator) -> None:
),
}
)
def test_html_error_handler_invalid_sequence(dicom_info, validator) -> None:
def test_html_error_handler_invalid_sequence(validator, html_handler) -> None:
"""Check that an invalid sequence is reported."""
handler = HtmlErrorHandler(dicom_info)
validator.handler = handler
validator.handler = html_handler
validator.validate()
assert (
"<li>(0008,9215) (Derivation Code Sequence)"
" is not a valid sequence, ignoring it</li>" in handler.html
" is not a valid sequence, ignoring it</li>" in html_handler.html
)


Expand Down
107 changes: 107 additions & 0 deletions dicom_validator/tests/validator/test_html_links.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
from http.client import BadStatusLine, CannotSendHeader, HTTPException, HTTPSConnection
from socket import gaierror
from ssl import SSLError
from unittest.mock import Mock

import pytest

from dicom_validator.validator.dicom_info import DicomInfo
from dicom_validator.validator.html_error_handler import HtmlErrorHandler

URL = "https://dicom.nema.org/medical/dicom/current/output/chtml/part03/sect_C.7.html"


@pytest.fixture
def connection(monkeypatch):
connection = Mock(spec=HTTPSConnection)
connection.getresponse.return_value.status = 200
monkeypatch.setattr(
"dicom_validator.validator.html_error_handler.HTTPSConnection",
Mock(return_value=connection),
)
monkeypatch.setattr(HtmlErrorHandler, "valid_refs", {})
return connection


@pytest.mark.parametrize(
"status, expected",
[(200, True), (302, True), (399, True), (400, False), (404, False), (500, False)],
)
def test_url_status(connection, status, expected):
connection.getresponse.return_value.status = status
assert HtmlErrorHandler.url_exists(URL) is expected
connection.request.assert_called_once_with(
"HEAD", "/medical/dicom/current/output/chtml/part03/sect_C.7.html"
)
connection.close.assert_called_once_with()


@pytest.mark.parametrize("stage", ["request", "getresponse"])
@pytest.mark.parametrize(
"error",
[
OSError,
TimeoutError,
gaierror,
SSLError,
HTTPException,
BadStatusLine,
CannotSendHeader,
ValueError,
TypeError,
],
)
def test_url_failure(connection, stage, error):
getattr(connection, stage).side_effect = error("unavailable")
assert HtmlErrorHandler.url_exists(URL) is False
connection.close.assert_called_once_with()


@pytest.mark.parametrize("error", [OSError, HTTPException])
def test_url_close_failure(connection, error):
connection.close.side_effect = error("close failed")
assert HtmlErrorHandler.url_exists(URL) is False
connection.close.assert_called_once_with()


@pytest.mark.parametrize("error", [OSError, HTTPException])
def test_url_connection_failure(monkeypatch, error):
monkeypatch.setattr(
"dicom_validator.validator.html_error_handler.HTTPSConnection",
Mock(side_effect=error("connection failed")),
)
assert HtmlErrorHandler.url_exists(URL) is False


def test_unexpected_error_is_not_suppressed(connection):
connection.getresponse.side_effect = RuntimeError("unexpected")
with pytest.raises(RuntimeError, match="unexpected"):
HtmlErrorHandler.url_exists(URL)
connection.close.assert_called_once_with()


def test_offline_report_has_module_name_without_link(connection):
connection.request.side_effect = OSError("offline")
dicom_info = DicomInfo(
{}, {"1.2.3": {"modules": {"Patient": {"ref": "C.7.1.1"}}}}, {}
)
handler = HtmlErrorHandler(dicom_info)
handler.sop_class = "1.2.3"
handler.handle_module_errors_start("Patient", {})
assert handler.html == "<h3>Patient</h3>\n<ul>"
assert connection.close.call_count == 4
assert not handler.valid_refs


def test_parent_section_is_used_and_cached(connection):
connection.getresponse.side_effect = [Mock(status=404), Mock(status=200)]
handler = HtmlErrorHandler(DicomInfo({}, {}, {}))
parent_url = handler.url_for_ref("C.8.8")
assert handler.valid_url_for_ref("C.8.8.1") == parent_url
assert [call.args for call in connection.request.call_args_list] == [
("HEAD", "/medical/dicom/current/output/chtml/part03/sect_C.8.8.1.html"),
("HEAD", "/medical/dicom/current/output/chtml/part03/sect_C.8.8.html"),
]
assert connection.close.call_count == 2
assert handler.valid_url_for_ref("C.8.8.1") == parent_url
assert connection.request.call_count == 2
16 changes: 9 additions & 7 deletions dicom_validator/validator/html_error_handler.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import html
from http.client import CannotSendHeader, HTTPSConnection
from contextlib import closing
from http.client import HTTPException, HTTPSConnection
from typing import ClassVar
from urllib.parse import urlparse

Expand Down Expand Up @@ -66,15 +67,16 @@ def url_exists(url):
Returns
-------
bool
`True` if the server responds with a status code < 400.
`True` if the server responds with a status code < 400,
otherwise `False`, including when the request fails.
"""
p = urlparse(url)
conn = HTTPSConnection(p.netloc)
try:
conn.request("HEAD", p.path)
except (ValueError, TypeError, CannotSendHeader):
p = urlparse(url)
with closing(HTTPSConnection(p.netloc)) as conn:
conn.request("HEAD", p.path)
return conn.getresponse().status < 400
except (ValueError, TypeError, HTTPException, OSError):
return False
return conn.getresponse().status < 400

def valid_url_for_ref(self, ref: str) -> str | None:
"""Return a valid URL to the referenced PS3.3 section if it exists.
Expand Down
Loading