Skip to content

Commit

Permalink
refactor datetime_subelement_kwarg to use try-except for error handli…
Browse files Browse the repository at this point in the history
…ng and improve test cases for KmlDateTime parsing
  • Loading branch information
cleder committed Nov 14, 2024
1 parent e8c1fb6 commit e9e4915
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 11 deletions.
19 changes: 10 additions & 9 deletions fastkml/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}


Expand Down
12 changes: 10 additions & 2 deletions tests/times_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit e9e4915

Please sign in to comment.