]> git.ipfire.org Git - thirdparty/babel.git/commitdiff
Add and emit dates.ParseError
authorAarni Koskela <akx@iki.fi>
Thu, 27 Jan 2022 15:37:52 +0000 (17:37 +0200)
committerAarni Koskela <akx@iki.fi>
Fri, 28 Jan 2022 09:07:09 +0000 (11:07 +0200)
babel/dates.py
tests/test_dates.py

index 4c14ea2bd9106bf5acfe155fb0153948d7ca2cd4..d248660eb691df3c0056f24e1588ea687b4b8997 100644 (file)
@@ -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
index d85fd08305bbaab37841fd724a3fcf5e39d86ba5..c4b9f46c9f92d524905ecc0f73690b7664dc6cb7 100644 (file)
@@ -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