diff --git a/src/pendulum/formatting/formatter.py b/src/pendulum/formatting/formatter.py index b09977d0d..810edc5d5 100644 --- a/src/pendulum/formatting/formatter.py +++ b/src/pendulum/formatting/formatter.py @@ -76,8 +76,13 @@ class Formatter: "MMM": "months.abbreviated", "Mo": None, "DDDo": None, - "Do": lambda locale: tuple( - rf"\d+{o}" for o in locale.get("custom.ordinal").values() + "Do": lambda locale: ( + *( + rf"\d+{re.escape(o)}" + for o in (locale.get("custom.ordinal") or {}).values() + if o + ), + r"\d+", ), "dddd": "days.wide", "ddd": "days.abbreviated", @@ -676,6 +681,9 @@ def _replace_tokens(self, token: str, locale: Locale) -> str: if token in self._LOCALIZABLE_TOKENS: values = self._LOCALIZABLE_TOKENS[token] + if values is None: + raise ValueError(f"Unsupported token: {token}") + if callable(values): candidates = values(locale) else: diff --git a/tests/datetime/test_from_format.py b/tests/datetime/test_from_format.py index ecf59632a..9cc2246a3 100644 --- a/tests/datetime/test_from_format.py +++ b/tests/datetime/test_from_format.py @@ -220,3 +220,23 @@ def test_from_format_2_digit_year(): d = pendulum.from_format("99", "YY") assert d.year == 1999 + + +@pytest.mark.parametrize( + "locale", ["de", "bg", "ru", "pl", "uk", "da", "sv", "en", "fr", "it"] +) +@pytest.mark.parametrize("day", [1, 2, 3, 8, 11, 21, 31]) +@pytest.mark.parametrize( + "fmt", ["YYYY-MM-Do", "Do MMMM YYYY", "MMMM Do, YYYY", "Do.MM.YYYY"] +) +def test_from_format_ordinal_day_round_trip(locale, day, fmt): + date = pendulum.datetime(2024, 1, day) + text = date.format(fmt, locale=locale) + + assert pendulum.from_format(text, fmt, locale=locale) == date + + +@pytest.mark.parametrize("token", ["Qo", "Mo", "DDDo", "do", "e", "eo", "Wo", "wo"]) +def test_from_format_unsupported_localized_token(token): + with pytest.raises(ValueError, match=f"^Unsupported token: {token}$"): + pendulum.from_format("1", token)