diff --git a/CHANGES.md b/CHANGES.md
index 14324ac..1fef513 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -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.
diff --git a/dicom_validator/tests/validator/test_error_handler.py b/dicom_validator/tests/validator/test_error_handler.py
index 5f006b5..96f9f22 100644
--- a/dicom_validator/tests/validator/test_error_handler.py
+++ b/dicom_validator/tests/validator/test_error_handler.py
@@ -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 (
'
' in handler.html
+ '/sect_C.8.8.html">RT Series' 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 "Missing SOP Class UID
" in handler.html
+ assert "Missing SOP Class UID
" in html_handler.html
@pytest.mark.tag_set(
@@ -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 (
"(0008,9215) (Derivation Code Sequence)"
- " is not a valid sequence, ignoring it" in handler.html
+ " is not a valid sequence, ignoring it" in html_handler.html
)
diff --git a/dicom_validator/tests/validator/test_html_links.py b/dicom_validator/tests/validator/test_html_links.py
new file mode 100644
index 0000000..40b7d11
--- /dev/null
+++ b/dicom_validator/tests/validator/test_html_links.py
@@ -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 == "Patient
\n"
+ 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
diff --git a/dicom_validator/validator/html_error_handler.py b/dicom_validator/validator/html_error_handler.py
index d81f1fc..3250bee 100644
--- a/dicom_validator/validator/html_error_handler.py
+++ b/dicom_validator/validator/html_error_handler.py
@@ -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
@@ -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.