From e9e4915513dc86a20231906bce57bcebd9739fe7 Mon Sep 17 00:00:00 2001 From: Christian Ledermann Date: Thu, 14 Nov 2024 13:32:51 +0000 Subject: [PATCH] refactor datetime_subelement_kwarg to use try-except for error handling and improve test cases for KmlDateTime parsing --- fastkml/helpers.py | 19 ++++++++++--------- tests/times_test.py | 12 ++++++++++-- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/fastkml/helpers.py b/fastkml/helpers.py index 1b3d582e..85a888e8 100644 --- a/fastkml/helpers.py +++ b/fastkml/helpers.py @@ -1100,15 +1100,16 @@ def datetime_subelement_kwarg( return {} node_text = node.text.strip() if node.text else "" if node_text: - if kdt := cls.parse(node_text): # type: ignore[attr-defined] - return {kwarg: kdt} - handle_error( - error=ValueError(f"Invalid DateTime value: {node_text}"), - strict=strict, - element=element, - node=node, - expected="DateTime", - ) + try: + return {kwarg: cls.parse(node_text)} # type: ignore[attr-defined] + except ValueError as exc: + handle_error( + error=exc, + strict=strict, + element=element, + node=node, + expected="DateTime", + ) return {} diff --git a/tests/times_test.py b/tests/times_test.py index 3b52e9ff..2b96978a 100644 --- a/tests/times_test.py +++ b/tests/times_test.py @@ -200,11 +200,19 @@ def test_parse_datetime_no_tz(self) -> None: assert dt.dt == datetime.datetime(1997, 7, 16, 7, 30, 15, tzinfo=tzutc()) def test_parse_datetime_empty(self) -> None: - assert KmlDateTime.parse("") is None + with pytest.raises( + ValueError, + match="^Could not match input '' to any of the following formats:", + ): + KmlDateTime.parse("") def test_parse_year_month_5(self) -> None: """Test that a single digit month is invalid.""" - assert KmlDateTime.parse("19973") is None + with pytest.raises( + ValueError, + match="^Could not match input '19973' to any of the following formats:", + ): + KmlDateTime.parse("19973") class TestStdLibrary(StdLibrary):