Debian Codegraph @

tests/test_timezone_parser.py

raw
1 import datetime as dt
2 from datetime import datetime, timedelta
3 from unittest import SkipTest
4 from unittest.mock import Mock, patch
5
6 from parameterized import param, parameterized
7 from pytz import timezone
8
9 import dateparser.timezone_parser
10 from dateparser import parse
11 from dateparser.timezone_parser import (
12 StaticTzInfo,
13 get_local_tz_offset,
14 is_timezone_token,
15 pop_tz_offset_from_string,
16 word_is_tz,
17 )
18 from tests import BaseTestCase
19
20
21 class TestTZPopping(BaseTestCase):
22 def setUp(self):
23 super().setUp()
24 self.initial_string = self.datetime_string = self.timezone_offset = (
25 NotImplemented
26 )
27
28 @parameterized.expand(
29 [
30 param("Sep 03 2014 | 4:32 pm EDT", -4),
31 param("17th October, 2034 @ 01:08 am PDT", -7),
32 param("17th October, 2034 @ 01:08 am (PDT)", -7),
33 param("October 17, 2014 at 7:30 am PST", -8),
34 param("20 Oct 2014 13:08 CET", +1),
35 param("20 Oct 2014 13:08cet", +1),
36 param("Nov 25 2014 | 10:17 pm EST", -5),
37 param("Nov 25 2014 | 10:17 pm +0600", +6),
38 param("Nov 25 2014 | 10:17 pm -0930", -9.5),
39 param("20 Oct 2014 | 05:17 am -1200", -12),
40 param("20 Oct 2014 | 05:17 am +0000", 0),
41 param("20 Oct 2014 | 05:17 am -0000", 0),
42 param("15 May 2004", None),
43 param("Wed Aug 05 12:00:00 EDTERR 2015", None),
44 param("Wed Aug 05 12:00:00 EDT 2015", -4),
45 param("April 10, 2016 at 12:00:00 UTC", 0),
46 param("April 10, 2016 at 12:00:00 MEZ", 1),
47 param("April 10, 2016 at 12:00:00 MESZ", 2),
48 param("April 10, 2016 at 12:00:00 GMT+2", 2),
49 param("April 10, 2016 at 12:00:00 UTC+2:00", 2),
50 param("April 10, 2016 at 12:00:00 GMT+02:00", 2),
51 param("April 10, 2016 at 12:00:00 UTC+5:30", 5.5),
52 param("April 10, 2016 at 12:00:00 GMT+05:30", 5.5),
53 param("April 10, 2016 at 12:00:00 UTC-2", -2),
54 param("April 10, 2016 at 12:00:00 GMT-2:00", -2),
55 param("April 10, 2016 at 12:00:00 UTC-02:00", -2),
56 param("April 10, 2016 at 12:00:00 GMT-9:30", -9.5),
57 param("April 10, 2016 at 12:00:00 UTC-09:30", -9.5),
58 param("Thu, 24 Nov 2016 16:03:00 UT", 0),
59 param("Fri Sep 23 2016 10:34:51 GMT+0800 (CST)", 8),
60 param("Fri Sep 23 2016 10:34:51 GMT+12", 12),
61 param("Fri Sep 23 2016 10:34:51 UTC+13", 13),
62 param("Fri Sep 23 2016 10:34:51 GMT+1245 (CST)", 12.75),
63 param("Fri Sep 23 2016 10:34:51 UTC+1245", 12.75),
64 param("2019-07-17T12:30:00.000-03:30", -3.5),
65 param("2019-07-17T12:30:00.000-02:30", -2.5),
66 param("16. srpna 2021 9:59:44 SELČ", 2),
67 param("16. srpna 2021 9:59:44 SEČ", 1),
68 param("16. srpna 2021 9:59:44 ZEČ", 0),
69 param("16. srpna 2021 9:59:44 VEČ", 2),
70 ]
71 )
72 def test_extracting_valid_offset(self, initial_string, expected_offset):
73 self.given_string(initial_string)
74 self.when_offset_popped_from_string()
75 self.then_offset_is(expected_offset)
76
77 @parameterized.expand(
78 [
79 param("Sep 03 2014 | 4:32 pm EDT", "Sep 03 2014 | 4:32 pm "),
80 param(
81 "17th October, 2034 @ 01:08 am PDT", "17th October, 2034 @ 01:08 am "
82 ),
83 param("October 17, 2014 at 7:30 am PST", "October 17, 2014 at 7:30 am "),
84 param("20 Oct 2014 13:08 CET", "20 Oct 2014 13:08 "),
85 param("20 Oct 2014 13:08cet", "20 Oct 2014 13:08"),
86 param("Nov 25 2014 | 10:17 pm EST", "Nov 25 2014 | 10:17 pm "),
87 param(
88 "17th October, 2034 @ 01:08 am +0700", "17th October, 2034 @ 01:08 am "
89 ),
90 param("Sep 03 2014 4:32 pm +0630", "Sep 03 2014 4:32 pm "),
91 ]
92 )
93 def test_timezone_deleted_from_string(self, initial_string, result_string):
94 self.given_string(initial_string)
95 self.when_offset_popped_from_string()
96 self.then_string_modified_to(result_string)
97
98 def test_string_not_changed_if_no_timezone(self):
99 self.given_string("15 May 2004")
100 self.when_offset_popped_from_string()
101 self.then_string_modified_to("15 May 2004")
102
103 def given_string(self, string_):
104 self.initial_string = string_
105
106 def when_offset_popped_from_string(self):
107 self.datetime_string, timezone_offset = pop_tz_offset_from_string(
108 self.initial_string
109 )
110 if timezone_offset:
111 self.timezone_offset = timezone_offset.utcoffset("")
112 else:
113 self.timezone_offset = timezone_offset
114
115 def then_string_modified_to(self, expected_string):
116 self.assertEqual(expected_string, self.datetime_string)
117
118 def then_offset_is(self, expected_offset):
119 delta = (
120 timedelta(hours=expected_offset) if expected_offset is not None else None
121 )
122 self.assertEqual(delta, self.timezone_offset)
123
124
125 class TestLocalTZOffset(BaseTestCase):
126 def setUp(self):
127 super().setUp()
128 self.timezone_offset = NotImplemented
129
130 @parameterized.expand(
131 [
132 param(utc="2014-08-20 4:32", local="2014-08-20 8:32", offset=+4),
133 param(utc="2052-01-02 11:07", local="2052-01-02 10:07", offset=-1),
134 param(utc="2013-12-31 23:59", local="2014-01-01 00:29", offset=+0.5),
135 param(utc="2011-07-14 11:59", local="2011-07-13 23:59", offset=-12),
136 param(utc="2014-10-18 17:41", local="2014-10-18 17:41", offset=0),
137 ]
138 )
139 def test_timezone_offset_calculation(self, utc, local, offset):
140 try:
141 self.given_time(utc, local)
142 except OverflowError:
143 raise SkipTest("Unsupported with 32-bit time_t")
144 self.when_offset_popped_from_string()
145 self.then_offset_is(offset)
146
147 def when_offset_popped_from_string(self):
148 self.timezone_offset = get_local_tz_offset()
149
150 def then_offset_is(self, expected_offset):
151 delta = (
152 timedelta(seconds=3600 * expected_offset)
153 if expected_offset is not None
154 else None
155 )
156 self.assertEqual(delta, self.timezone_offset)
157
158 def given_time(self, utc_dt_string, local_dt_string):
159 datetime_cls = dateparser.timezone_parser.datetime
160 if not isinstance(datetime_cls, Mock):
161 datetime_cls = Mock(wraps=datetime)
162 utc_dt_obj = datetime.strptime(utc_dt_string, "%Y-%m-%d %H:%M").replace(
163 tzinfo=dt.timezone.utc
164 )
165 local_dt_obj = datetime.strptime(local_dt_string, "%Y-%m-%d %H:%M")
166
167 def _dt_now(tz=None):
168 if tz == dt.timezone.utc:
169 return utc_dt_obj
170 return local_dt_obj
171
172 datetime_cls.now = Mock(side_effect=_dt_now)
173 self.add_patch(patch("dateparser.timezone_parser.datetime", new=datetime_cls))
174
175
176 class TestTimeZoneConversion(BaseTestCase):
177 def setUp(self):
178 super().setUp()
179 self.settings = {}
180 self.parser = parse
181 self.result = NotImplemented
182
183 @parameterized.expand(
184 [
185 param(
186 "2015-12-31 10:04 AM",
187 "Asia/Karachi",
188 "UTC",
189 datetime(2015, 12, 31, 5, 4),
190 ),
191 param(
192 "2015-12-30 10:04 AM",
193 "Asia/Karachi",
194 "+0200",
195 datetime(2015, 12, 30, 7, 4),
196 ),
197 ]
198 )
199 def test_timezone_conversion(self, datestring, from_tz, to_tz, expected):
200 self.given_from_timezone(from_tz)
201 self.given_to_timezone(to_tz)
202 self.when_date_is_parsed(datestring)
203 self.then_date_is(expected)
204
205 def given_from_timezone(self, timezone):
206 self.settings["TIMEZONE"] = timezone
207
208 def given_to_timezone(self, timezone):
209 self.settings["TO_TIMEZONE"] = timezone
210
211 def when_date_is_parsed(self, datestring):
212 self.result = self.parser(datestring, settings=self.settings)
213
214 def then_date_is(self, date):
215 self.assertEqual(date, self.result)
216
217
218 class TestStaticTzInfo(BaseTestCase):
219 def setUp(self):
220 super().setUp()
221
222 @parameterized.expand(
223 [
224 param(given_date=datetime(2007, 1, 18, tzinfo=timezone("UTC"))),
225 param(given_date=datetime(2003, 3, 31, tzinfo=timezone("US/Arizona"))),
226 param(given_date=datetime(2000, 2, 20, tzinfo=timezone("Pacific/Samoa"))),
227 ]
228 )
229 def test_localize_raises_error_if_date_has_tzinfo(self, given_date):
230 self.timezone_info = StaticTzInfo("UTC\\+00:00", timedelta(0))
231 self.when_date_is_localized(given_date)
232 self.then_error_was_raised(
233 ValueError, ["Not naive datetime (tzinfo is already set)"]
234 )
235
236 def when_date_is_localized(self, given_date):
237 try:
238 self.localized_date = self.timezone_info.localize(given_date)
239 except Exception as error:
240 self.error = error
241
242 def then_localized_date_is(self, expected_date, expected_tzname):
243 self.assertEqual(self.localized_date.date(), expected_date.date())
244 self.assertEqual(self.localized_date.tzname(), expected_tzname)
245
246
247 class TestIsTimezoneToken(BaseTestCase):
248 """Unit tests for ``is_timezone_token``, used to keep a trailing timezone
249 when ``IGNORE_SURROUNDING_TEXT`` strips edge tokens."""
250
251 @parameterized.expand(
252 [
253 param(token="EST", expected=True),
254 # Already-lowercased and space-padded tokens (as produced by the
255 # translation pipeline) are recognized too.
256 param(token="est", expected=True),
257 param(token=" est", expected=True),
258 param(token="cet", expected=True),
259 param(token="pst", expected=True),
260 param(token="utc", expected=True),
261 # A longer word that merely starts with a timezone abbreviation must
262 # not be treated as a timezone.
263 param(token="actualisé", expected=False),
264 param(token="ACTUALISÉ", expected=False),
265 param(token="updated", expected=False),
266 param(token="", expected=False),
267 param(token=" ", expected=False),
268 ]
269 )
270 def test_is_timezone_token(self, token, expected):
271 self.assertEqual(expected, is_timezone_token(token))
272
273 def test_anchored_match_unlike_word_is_tz(self):
274 # word_is_tz prefix-matches ("ACT" of "ACTUALISÉ"); is_timezone_token is
275 # anchored, so it does not — this is what keeps a noise word from
276 # surviving as a timezone when edges are stripped.
277 self.assertTrue(word_is_tz("ACTUALISÉ"))
278 self.assertFalse(is_timezone_token("ACTUALISÉ"))
279
280
281 class TestTzDatabasePreference(BaseTestCase):
282 """Tests for #1322: prefer the tz database for conflicting abbreviations.
283
284 ``dateparser/timezones.py`` maps every timezone abbreviation to a single UTC
285 offset, and unrelated zones often share the same letters. The table was
286 scraped from Wikipedia, so a few abbreviations ended up with a meaning no tz
287 database zone has: "BST" resolved to +11, although the only zone named "BST"
288 today is British Summer Time at +1 (#1321).
289
290 The rule pinned down here is that when the tz database names exactly one
291 offset for an abbreviation, dateparser has to use it, and when the tz
292 database names several, dateparser's existing choice is left alone.
293
294 The tests that exercise the comparison itself run against
295 ``FROZEN_TZ_DATABASE`` so that they keep testing the same logic as the tz
296 database changes; the two that check dateparser's actual data are the ones
297 that read the installed tz database.
298 """
299
300 # A stand-in for the tz database: "BST"/"HDT" named by one offset each,
301 # "CST" by three (US Central, Cuba, China).
302 FROZEN_TZ_DATABASE = {
303 "BST": {3600},
304 "HDT": {-32400},
305 "CST": {-21600, -18000, 28800},
306 }
307
308 @classmethod
309 def setUpClass(cls):
310 super().setUpClass()
311 from dateparser_scripts import tz_abbreviation_conflicts
312
313 cls.checker = tz_abbreviation_conflicts
314 # Sampling every zone takes a moment, so it is done once for the class.
315 cls.tz_database = tz_abbreviation_conflicts.tz_database_abbreviations()
316
317 def offset_of(self, date_string):
318 _, timezone_offset = pop_tz_offset_from_string(date_string)
319 self.assertIsNotNone(timezone_offset, f"no timezone found in {date_string!r}")
320 return timezone_offset.utcoffset(None)
321
322 @parameterized.expand(
323 [
324 # British Summer Time, the case reported in #1321.
325 param("13 August 2026 10:00 BST", +1, "BST"),
326 # Hawaii-Aleutian Daylight Time (America/Adak). The table used
327 # -9:30, which is what Pacific/Honolulu called "HDT" back when
328 # Hawaii kept -10:30; no zone has been named that since.
329 param("13 August 2026 10:00 HDT", -9, "HDT"),
330 ]
331 )
332 def test_unambiguous_abbreviation_uses_tz_database_offset(
333 self, date_string, expected_offset, abbreviation
334 ):
335 self.assertEqual(timedelta(hours=expected_offset), self.offset_of(date_string))
336 # And the tz database really does name only that one offset.
337 self.assertEqual({int(expected_offset * 3600)}, self.tz_database[abbreviation])
338
339 @parameterized.expand(
340 [
341 param("13 August 2026 10:00 BST", +1, "BST"),
342 param("13 August 2026 10:00 HDT", -9, "HDT"),
343 ]
344 )
345 def test_unambiguous_abbreviation_parses_end_to_end(
346 self, date_string, expected_offset, abbreviation
347 ):
348 # The #1321 report as a user would hit it, not just at the popping layer.
349 parsed = parse(date_string, settings={"RETURN_AS_TIMEZONE_AWARE": True})
350 self.assertEqual(timedelta(hours=expected_offset), parsed.utcoffset())
351 self.assertEqual(abbreviation, parsed.tzname())
352
353 @parameterized.expand(
354 [
355 # US Central, but "CST" also names Cuba (-5) and China (+8).
356 param("13 August 2026 10:00 CST", -6),
357 # US Central Daylight, but "CDT" also names Cuba (-4).
358 param("13 August 2026 10:00 CDT", -5),
359 # Israel, but "IST" also names India (+5:30) and Ireland (+1).
360 param("13 August 2026 10:00 IST", +2),
361 # US Pacific, but "PST" also names the Philippines (+8).
362 param("13 August 2026 10:00 PST", -8),
363 ]
364 )
365 def test_ambiguous_abbreviation_keeps_its_offset(
366 self, date_string, expected_offset
367 ):
368 # These keep the value dateparser has always used. The assertion below
369 # holds whether or not the abbreviation stays ambiguous: what matters is
370 # that the retained value is one a real zone uses, not an arbitrary one.
371 self.assertEqual(timedelta(hours=expected_offset), self.offset_of(date_string))
372 abbreviation = date_string.rsplit(" ", 1)[1]
373 self.assertIn(int(expected_offset * 3600), self.tz_database[abbreviation])
374
375 def test_table_agrees_with_the_tz_database(self):
376 # The generalized check behind #1322: instead of asserting a fixed list
377 # of abbreviations, ask the tz database about every abbreviation the two
378 # tables share, so a regression on any of them is caught.
379 shared = set(self.checker.static_tz_abbreviations()) & set(self.tz_database)
380 # Without this, the assertion below would also pass if the comparison
381 # silently stopped covering anything.
382 self.assertGreater(
383 len(shared), 40, f"only {len(shared)} abbreviations compared"
384 )
385 conflicts = self.checker.find_conflicts(tz_database=self.tz_database)
386 self.assertEqual([], conflicts, f"conflicts with the tz database: {conflicts}")
387
388 def test_report_runs_clean(self):
389 # Exercises the module's entry point with its real defaults, which the
390 # test above bypasses by passing the tz database in.
391 self.assertEqual(0, self.checker.main())
392
393 def test_reference_years_stay_in_settled_years(self):
394 # The tz database records future daylight-saving rules as predictions
395 # that change between releases, so sampling them would tie the result to
396 # the installed version rather than to real usage.
397 self.assertLess(max(self.checker.REFERENCE_YEARS), datetime.now().year)
398
399 def test_pre_fix_offsets_are_reported_as_conflicts(self):
400 # Reproduces the bug this change fixes, and keeps the whole-table check
401 # from passing vacuously: the offsets shipped before #1322 are flagged.
402 conflicts = self.checker.find_conflicts(
403 static={"BST": 39600, "HDT": -34200},
404 tz_database=self.FROZEN_TZ_DATABASE,
405 )
406 self.assertEqual(
407 [
408 ("BST", "unambiguous", 39600, [3600]),
409 ("HDT", "unambiguous", -34200, [-32400]),
410 ],
411 [tuple(conflict) for conflict in conflicts],
412 )
413
414 def test_offset_no_zone_uses_is_reported_even_when_ambiguous(self):
415 # "CST" has several meanings, so none of them can be preferred, but +11
416 # is not one of them and is still worth reporting.
417 (conflict,) = self.checker.find_conflicts(
418 static={"CST": 39600}, tz_database=self.FROZEN_TZ_DATABASE
419 )
420 self.assertEqual("CST", conflict.abbreviation)
421 self.assertEqual("unsupported", conflict.kind)
422 self.assertNotIn(39600, conflict.tz_database_offsets)
423
424 @parameterized.expand([param(-21600), param(28800)])
425 def test_any_offset_a_zone_really_uses_is_accepted(self, offset):
426 # Both US Central (-6) and China (+8) are legitimate readings of "CST".
427 self.assertEqual(
428 [],
429 self.checker.find_conflicts(
430 static={"CST": offset}, tz_database=self.FROZEN_TZ_DATABASE
431 ),
432 )
433
434 def test_abbreviations_outside_the_reference_window_are_ignored(self):
435 # dateparser keeps abbreviations no zone is named after any more, such
436 # as "AHST", so historical text still parses. The tz database says
437 # nothing about them, so they are skipped rather than reported.
438 self.assertNotIn("AHST", self.tz_database)
439 self.assertEqual(
440 [],
441 self.checker.find_conflicts(
442 static={"AHST": -36000}, tz_database=self.FROZEN_TZ_DATABASE
443 ),
444 )
445
446 def test_abbreviations_are_compared_case_insensitively(self):
447 # dateparser matches abbreviations regardless of case, so the table's
448 # "ChST" entry and the tz database's "ChST" are one abbreviation and
449 # have to meet under the same key.
450 self.assertIn("CHST", self.checker.static_tz_abbreviations())
451 self.assertIn("CHST", self.tz_database)
452
453 def test_numeric_zone_names_are_not_treated_as_abbreviations(self):
454 # The tz database names zones that have no established abbreviation
455 # after their offset, as in "+11" or "-0930". Those are offsets rather
456 # than identities, and dateparser matches numeric offsets through its
457 # separate UTC/GMT patterns, so they stay out of this comparison.
458 self.assertEqual([], [name for name in self.tz_database if name[0] in "+-"])
459 self.assertIn("BST", self.tz_database)
460
461 def test_repeated_abbreviation_resolves_to_its_first_entry(self):
462 # "LMT" is listed four times with four different offsets. Only the first
463 # can ever match, so that is the value the comparison has to use;
464 # checking against all four would hide a wrong first entry.
465 self.assertEqual(
466 self.checker.static_tz_abbreviations()["LMT"],
467 self.offset_of("13 August 2026 10:00 LMT").total_seconds(),
468 )