Parse validity dates strictly; unknown forms raise ParseError
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
1 parent
e3304617f9
commit
63a36333fb
2 files changed
+145
-14
No files matched your search
+90
-1
@@ -1,4 +1,4 @@
|
|||||||
from datetime import date, time
|
from datetime import date, time, timedelta
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
@@ -121,3 +121,92 @@ def test_invalid_minute_is_a_parse_error():
|
|||||||
)
|
)
|
||||||
with pytest.raises(ParseError, match="invalid time"):
|
with pytest.raises(ParseError, match="invalid time"):
|
||||||
parse_page(html, "4", "X")
|
parse_page(html, "4", "X")
|
||||||
|
|
||||||
|
|
||||||
|
def header_column(label_html):
|
||||||
|
html = HEADER.format(
|
||||||
|
ths=f"<th>{label_html}</th>",
|
||||||
|
rows='<tr><td class="hour-cell">04</td><td class="minutes-cell">16 </td></tr>',
|
||||||
|
)
|
||||||
|
return parse_page(html, "4", "X").columns[0]
|
||||||
|
|
||||||
|
|
||||||
|
def special(validity):
|
||||||
|
return header_column(f"Prac.dny–školní prázdniny<br/>platnost {validity}")
|
||||||
|
|
||||||
|
|
||||||
|
def days(first, last):
|
||||||
|
out = []
|
||||||
|
while first <= last:
|
||||||
|
out.append(first)
|
||||||
|
first += timedelta(days=1)
|
||||||
|
return tuple(out)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validity_od_single_date_is_valid_from():
|
||||||
|
column = header_column("Pracovní dny<br/>platnost od 1.10.2026")
|
||||||
|
assert (column.kind, column.valid_from, column.dates) == (KIND_WORKDAY, date(2026, 10, 1), ())
|
||||||
|
|
||||||
|
|
||||||
|
def test_validity_rest_day_valid_from():
|
||||||
|
column = header_column("Dny pracovního klidu<br/>platnost od 3.10.2026")
|
||||||
|
assert (column.kind, column.valid_from) == (KIND_REST_DAY, date(2026, 10, 3))
|
||||||
|
|
||||||
|
|
||||||
|
def test_validity_day_range_and_single_list():
|
||||||
|
column = special("29.–30.10.2026, 23.12.2026")
|
||||||
|
assert column.dates == (date(2026, 10, 29), date(2026, 10, 30), date(2026, 12, 23))
|
||||||
|
assert (column.kind, column.valid_from) == (KIND_SPECIAL, date(2026, 10, 29))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("text", ["29.10.–30.10.2026", "29.10. - 30.10.2026", "29. – 30.10.2026"])
|
||||||
|
def test_validity_month_range(text):
|
||||||
|
assert special(text).dates == (date(2026, 10, 29), date(2026, 10, 30))
|
||||||
|
|
||||||
|
|
||||||
|
def test_validity_range_within_month_end():
|
||||||
|
assert special("28.12.–31.12.2026").dates == days(date(2026, 12, 28), date(2026, 12, 31))
|
||||||
|
|
||||||
|
|
||||||
|
def test_validity_range_with_both_years():
|
||||||
|
assert special("28.12.2026–2.1.2027").dates == days(date(2026, 12, 28), date(2027, 1, 2))
|
||||||
|
|
||||||
|
|
||||||
|
def test_validity_range_infers_start_year_across_new_year():
|
||||||
|
column = special("28.12.–2.1.2027")
|
||||||
|
assert column.dates == days(date(2026, 12, 28), date(2027, 1, 2))
|
||||||
|
assert column.valid_from == date(2026, 12, 28)
|
||||||
|
|
||||||
|
|
||||||
|
def test_validity_summer_range():
|
||||||
|
assert special("1.7.–31.8.2027").dates == days(date(2027, 7, 1), date(2027, 8, 31))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"text",
|
||||||
|
[
|
||||||
|
"30.–29.10.2026", # reversed
|
||||||
|
"31.2.2026", # impossible date
|
||||||
|
"1.2.2026, 31.2.2026",
|
||||||
|
"29.–30.10.2026, 5", # stray digits
|
||||||
|
"29.–30.10.2026 a 12",
|
||||||
|
"29.–30.10.2026, 23.12.", # incomplete date
|
||||||
|
"od 1.10.2026, 5.10.2026",
|
||||||
|
"1.10.20266",
|
||||||
|
"129.10.–30.10.2026",
|
||||||
|
"29.10.–30.10.",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_validity_unknown_forms_raise(text):
|
||||||
|
with pytest.raises(ParseError):
|
||||||
|
special(text)
|
||||||
|
|
||||||
|
|
||||||
|
def test_header_without_date_is_a_parse_error():
|
||||||
|
with pytest.raises(ParseError, match="no validity"):
|
||||||
|
header_column("Pracovní dny<br/>platnost od")
|
||||||
|
|
||||||
|
|
||||||
|
def test_label_with_workday_and_school_holidays_is_special():
|
||||||
|
column = header_column("Pracovní dny – školní prázdniny<br/>platnost 29.–30.10.2026")
|
||||||
|
assert column.kind == KIND_SPECIAL
|
||||||
+55
-13
@@ -1,7 +1,7 @@
|
|||||||
"""Parse a DSZO per-stop timetable page into departures."""
|
"""Parse a DSZO per-stop timetable page into departures."""
|
||||||
import re
|
import re
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import date, time
|
from datetime import date, time, timedelta
|
||||||
|
|
||||||
KIND_WORKDAY = "workday"
|
KIND_WORKDAY = "workday"
|
||||||
KIND_REST_DAY = "rest_day"
|
KIND_REST_DAY = "rest_day"
|
||||||
@@ -36,7 +36,13 @@ class Timetable:
|
|||||||
columns: tuple[Column, ...]
|
columns: tuple[Column, ...]
|
||||||
|
|
||||||
|
|
||||||
_DATE_RE = re.compile(r"(\d{1,2})\.(?:\s*[–-]\s*(\d{1,2})\.)?(\d{1,2})\.(\d{4})")
|
_N = "([0-9]{1,2})"
|
||||||
|
_Y = "([0-9]{4})"
|
||||||
|
_DASH = r"\s*[–-]\s*"
|
||||||
|
# one validity item: a single date, or a range whose start may omit month and/or year
|
||||||
|
_SINGLE_RE = re.compile(rf"(?<![0-9]){_N}\.{_N}\.{_Y}")
|
||||||
|
_RANGE_RE = re.compile(rf"(?<![0-9]){_N}\.(?:{_N}\.(?:{_Y})?)?{_DASH}{_N}\.{_N}\.{_Y}")
|
||||||
|
MAX_RANGE_DAYS = 366
|
||||||
_TAG_RE = re.compile(r"<[^>]+>")
|
_TAG_RE = re.compile(r"<[^>]+>")
|
||||||
_ROW_RE = re.compile(r'<td class="hour-cell">(\d\d)</td>(.*?)</tr>', re.S)
|
_ROW_RE = re.compile(r'<td class="hour-cell">(\d\d)</td>(.*?)</tr>', re.S)
|
||||||
_CELL_RE = re.compile(r'<td class="minutes-cell">(.*?)</td>', re.S)
|
_CELL_RE = re.compile(r'<td class="minutes-cell">(.*?)</td>', re.S)
|
||||||
@@ -47,24 +53,60 @@ def _text(html: str) -> str:
|
|||||||
return re.sub(r"\s+", " ", _TAG_RE.sub(" ", html)).strip()
|
return re.sub(r"\s+", " ", _TAG_RE.sub(" ", html)).strip()
|
||||||
|
|
||||||
|
|
||||||
def _dates_in(text: str) -> list[date]:
|
def _make_date(year: int, month: int, day: int) -> date:
|
||||||
"""All dates in text; 'd1.–d2.m.yyyy' expands to every day of the range."""
|
try:
|
||||||
|
return date(year, month, day)
|
||||||
|
except ValueError as exc: # e.g. 31.2.
|
||||||
|
raise ParseError(f"impossible date {day}.{month}.{year}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _item_dates(item: str) -> list[date]:
|
||||||
|
single = _SINGLE_RE.fullmatch(item)
|
||||||
|
if single:
|
||||||
|
d, m, y = map(int, single.groups())
|
||||||
|
return [_make_date(y, m, d)]
|
||||||
|
rng = _RANGE_RE.fullmatch(item)
|
||||||
|
if not rng:
|
||||||
|
raise ParseError(f"unrecognised validity date {item!r}")
|
||||||
|
d1, m1, y1, d2, m2, y2 = rng.groups()
|
||||||
|
d1, d2, m2, y2 = int(d1), int(d2), int(m2), int(y2)
|
||||||
|
month1 = int(m1) if m1 else m2
|
||||||
|
if y1:
|
||||||
|
year1 = int(y1)
|
||||||
|
else: # infer from the end date: a start month after the end month means the year before
|
||||||
|
year1 = y2 - 1 if month1 > m2 else y2
|
||||||
|
first, last = _make_date(year1, month1, d1), _make_date(y2, m2, d2)
|
||||||
|
if last < first:
|
||||||
|
raise ParseError(f"reversed date range {item!r}")
|
||||||
|
if (last - first).days >= MAX_RANGE_DAYS:
|
||||||
|
raise ParseError(f"date range too long {item!r}")
|
||||||
|
return [first + timedelta(days=i) for i in range((last - first).days + 1)]
|
||||||
|
|
||||||
|
|
||||||
|
def _dates_in(validity: str) -> list[date]:
|
||||||
|
"""Dates of the text after 'platnost'. Anything not recognised raises ParseError."""
|
||||||
|
text = validity.strip()
|
||||||
|
from_only = text.lower().startswith("od ")
|
||||||
|
if from_only:
|
||||||
|
text = text[3:].strip()
|
||||||
found: list[date] = []
|
found: list[date] = []
|
||||||
for d1, d2, month, year in _DATE_RE.findall(text):
|
for item in text.split(","):
|
||||||
first, last = int(d1), int(d2 or d1)
|
found += _item_dates(item.strip())
|
||||||
found += [date(int(year), int(month), d) for d in range(first, last + 1)]
|
if from_only and len(found) != 1:
|
||||||
|
raise ParseError(f"'od' needs a single date: {validity!r}")
|
||||||
return found
|
return found
|
||||||
|
|
||||||
|
|
||||||
def _column_header(label_html: str) -> tuple[str, str, date, tuple[date, ...]]:
|
def _column_header(label_html: str) -> tuple[str, str, date, tuple[date, ...]]:
|
||||||
label = _text(label_html.replace("<br/>", " / "))
|
label = _text(label_html.replace("<br/>", " / "))
|
||||||
try:
|
|
||||||
dates = _dates_in(label)
|
|
||||||
except ValueError as exc: # e.g. 31.2.
|
|
||||||
raise ParseError(f"invalid date in column header: {label!r}") from exc
|
|
||||||
if not dates:
|
|
||||||
raise ParseError(f"no validity date in column header: {label!r}")
|
|
||||||
lowered = label.lower()
|
lowered = label.lower()
|
||||||
|
marker = lowered.find("platnost")
|
||||||
|
if marker < 0 or not re.search("[0-9]", label[marker:]):
|
||||||
|
raise ParseError(f"no validity date in column header: {label!r}")
|
||||||
|
try:
|
||||||
|
dates = _dates_in(label[marker + len("platnost"):])
|
||||||
|
except ParseError as exc:
|
||||||
|
raise ParseError(f"bad validity in column header {label!r}: {exc}") from exc
|
||||||
if "prázdniny" in lowered:
|
if "prázdniny" in lowered:
|
||||||
return label, KIND_SPECIAL, min(dates), tuple(dates)
|
return label, KIND_SPECIAL, min(dates), tuple(dates)
|
||||||
if lowered.startswith("dny pracovního klidu"):
|
if lowered.startswith("dny pracovního klidu"):
|
||||||
|
|||||||
Reference in new issue
Block a user