From: Aarni Koskela Date: Thu, 27 Jan 2022 15:37:52 +0000 (+0200) Subject: Add and emit dates.ParseError X-Git-Tag: v2.10.0~19^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=335884add64c6317ea74d1362ace6f79e449dfd7;p=thirdparty%2Fbabel.git Add and emit dates.ParseError --- diff --git a/babel/dates.py b/babel/dates.py index 4c14ea2b..d248660e 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -1138,6 +1138,10 @@ def get_period_id(time, tzinfo=None, type=None, locale=LC_TIME): return "pm" +class ParseError(ValueError): + pass + + def parse_date(string, locale=LC_TIME): """Parse a date from a string. @@ -1152,6 +1156,10 @@ def parse_date(string, locale=LC_TIME): :param string: the string containing the date :param locale: a `Locale` object or a locale identifier """ + numbers = re.findall(r'(\d+)', string) + if not numbers: + raise ParseError("No numbers were found in input") + # TODO: try ISO format first? format = get_date_format(locale=locale).pattern.lower() year_idx = format.index('y') @@ -1167,7 +1175,6 @@ def parse_date(string, locale=LC_TIME): # FIXME: this currently only supports numbers, but should also support month # names, both in the requested locale, and english - numbers = re.findall(r'(\d+)', string) year = numbers[indexes['Y']] if len(year) == 2: year = 2000 + int(year) @@ -1194,6 +1201,10 @@ def parse_time(string, locale=LC_TIME): :return: the parsed time :rtype: `time` """ + numbers = re.findall(r'(\d+)', string) + if not numbers: + raise ParseError("No numbers were found in input") + # TODO: try ISO format first? format = get_time_format(locale=locale).pattern.lower() hour_idx = format.index('h') @@ -1215,8 +1226,6 @@ def parse_time(string, locale=LC_TIME): if 'pm' in string.lower(): hour_offset = 12 - numbers = re.findall(r'(\d+)', string) - # Parse up to three numbers from the string. minute = second = 0 hour = int(numbers[indexes['H']]) + hour_offset diff --git a/tests/test_dates.py b/tests/test_dates.py index d85fd083..c4b9f46c 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -800,6 +800,13 @@ def test_parse_time(input, expected): assert dates.parse_time(input, locale='en_US') == expected +@pytest.mark.parametrize('case', ['', 'a', 'aaa']) +@pytest.mark.parametrize('func', [dates.parse_date, dates.parse_time]) +def test_parse_errors(case, func): + with pytest.raises(dates.ParseError): + func(case, locale='en_US') + + def test_datetime_format_get_week_number(): format = dates.DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE')) assert format.get_week_number(6) == 1