Debian Codegraph @

Lib/test/test_zoneinfo/test_zoneinfo.py

raw
1 from __future__ import annotations
2
3 import base64
4 import contextlib
5 import dataclasses
6 import importlib.metadata
7 import io
8 import json
9 import os
10 import pathlib
11 import pickle
12 import re
13 import shutil
14 import struct
15 import tempfile
16 import unittest
17 from datetime import date, datetime, time, timedelta, timezone
18 from functools import cached_property
19
20 from test.support import MISSING_C_DOCSTRINGS, requires_gil_enabled
21 from test.support.os_helper import FakePath
22 from test.test_zoneinfo import _support as test_support
23 from test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase
24 from test.support.import_helper import import_module, CleanImport
25 from test.support.script_helper import assert_python_ok
26
27 lzma = import_module('lzma')
28 py_zoneinfo, c_zoneinfo = test_support.get_modules()
29
30 try:
31 importlib.metadata.metadata("tzdata")
32 HAS_TZDATA_PKG = True
33 except importlib.metadata.PackageNotFoundError:
34 HAS_TZDATA_PKG = False
35
36 ZONEINFO_DATA = None
37 ZONEINFO_DATA_V1 = None
38 TEMP_DIR = None
39 DATA_DIR = pathlib.Path(__file__).parent / "data"
40 ZONEINFO_JSON = DATA_DIR / "zoneinfo_data.json"
41 DRIVE = os.path.splitdrive('x:')[0]
42
43 # Useful constants
44 ZERO = timedelta(0)
45 ONE_H = timedelta(hours=1)
46
47
48 def setUpModule():
49 global TEMP_DIR
50 global ZONEINFO_DATA
51 global ZONEINFO_DATA_V1
52
53 TEMP_DIR = pathlib.Path(tempfile.mkdtemp(prefix="zoneinfo"))
54 ZONEINFO_DATA = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v2")
55 ZONEINFO_DATA_V1 = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v1", v1=True)
56
57
58 def tearDownModule():
59 shutil.rmtree(TEMP_DIR)
60
61
62 class CustomError(Exception):
63 pass
64
65
66 class TzPathUserMixin:
67 """
68 Adds a setUp() and tearDown() to make TZPATH manipulations thread-safe.
69
70 Any tests that require manipulation of the TZPATH global are necessarily
71 thread unsafe, so we will acquire a lock and reset the TZPATH variable
72 to the default state before each test and release the lock after the test
73 is through.
74 """
75
76 @property
77 def tzpath(self): # pragma: nocover
78 return None
79
80 @property
81 def block_tzdata(self):
82 return True
83
84 def setUp(self):
85 with contextlib.ExitStack() as stack:
86 stack.enter_context(
87 self.tzpath_context(
88 self.tzpath,
89 block_tzdata=self.block_tzdata,
90 lock=TZPATH_TEST_LOCK,
91 )
92 )
93 self.addCleanup(stack.pop_all().close)
94
95 super().setUp()
96
97
98 class DatetimeSubclassMixin:
99 """
100 Replaces all ZoneTransition transition dates with a datetime subclass.
101 """
102
103 class DatetimeSubclass(datetime):
104 @classmethod
105 def from_datetime(cls, dt):
106 return cls(
107 dt.year,
108 dt.month,
109 dt.day,
110 dt.hour,
111 dt.minute,
112 dt.second,
113 dt.microsecond,
114 tzinfo=dt.tzinfo,
115 fold=dt.fold,
116 )
117
118 def load_transition_examples(self, key):
119 transition_examples = super().load_transition_examples(key)
120 for zt in transition_examples:
121 dt = zt.transition
122 new_dt = self.DatetimeSubclass.from_datetime(dt)
123 new_zt = dataclasses.replace(zt, transition=new_dt)
124 yield new_zt
125
126
127 class ZoneInfoTest(TzPathUserMixin, ZoneInfoTestBase):
128 module = py_zoneinfo
129 class_name = "ZoneInfo"
130
131 def setUp(self):
132 super().setUp()
133
134 # This is necessary because various subclasses pull from different
135 # data sources (e.g. tzdata, V1 files, etc).
136 self.klass.clear_cache()
137
138 @property
139 def zoneinfo_data(self):
140 return ZONEINFO_DATA
141
142 @property
143 def tzpath(self):
144 return [self.zoneinfo_data.tzpath]
145
146 def zone_from_key(self, key):
147 return self.klass(key)
148
149 def zones(self):
150 return ZoneDumpData.transition_keys()
151
152 def fixed_offset_zones(self):
153 return ZoneDumpData.fixed_offset_zones()
154
155 def load_transition_examples(self, key):
156 return ZoneDumpData.load_transition_examples(key)
157
158 def test_str(self):
159 # Zones constructed with a key must have str(zone) == key
160 for key in self.zones():
161 with self.subTest(key):
162 zi = self.zone_from_key(key)
163
164 self.assertEqual(str(zi), key)
165
166 # Zones with no key constructed should have str(zone) == repr(zone)
167 file_key = self.zoneinfo_data.keys[0]
168 file_path = self.zoneinfo_data.path_from_key(file_key)
169
170 with open(file_path, "rb") as f:
171 with self.subTest(test_name="Repr test", path=file_path):
172 zi_ff = self.klass.from_file(f)
173 self.assertEqual(str(zi_ff), repr(zi_ff))
174
175 def test_repr(self):
176 # The repr is not guaranteed, but I think we can insist that it at
177 # least contain the name of the class.
178 key = next(iter(self.zones()))
179
180 zi = self.klass(key)
181 class_name = self.class_name
182 with self.subTest(name="from key"):
183 self.assertRegex(repr(zi), class_name)
184
185 file_key = self.zoneinfo_data.keys[0]
186 file_path = self.zoneinfo_data.path_from_key(file_key)
187 with open(file_path, "rb") as f:
188 zi_ff = self.klass.from_file(f, key=file_key)
189
190 with self.subTest(name="from file with key"):
191 self.assertRegex(repr(zi_ff), class_name)
192
193 with open(file_path, "rb") as f:
194 zi_ff_nk = self.klass.from_file(f)
195
196 with self.subTest(name="from file without key"):
197 self.assertRegex(repr(zi_ff_nk), class_name)
198
199 def test_key_attribute(self):
200 key = next(iter(self.zones()))
201
202 def from_file_nokey(key):
203 with open(self.zoneinfo_data.path_from_key(key), "rb") as f:
204 return self.klass.from_file(f)
205
206 constructors = (
207 ("Primary constructor", self.klass, key),
208 ("no_cache", self.klass.no_cache, key),
209 ("from_file", from_file_nokey, None),
210 )
211
212 for msg, constructor, expected in constructors:
213 zi = constructor(key)
214
215 # Ensure that the key attribute is set to the input to ``key``
216 with self.subTest(msg):
217 self.assertEqual(zi.key, expected)
218
219 # Ensure that the key attribute is read-only
220 with self.subTest(f"{msg}: readonly"):
221 with self.assertRaises(AttributeError):
222 zi.key = "Some/Value"
223
224 def test_bad_keys(self):
225 bad_keys = [
226 "Eurasia/Badzone", # Plausible but does not exist
227 "BZQ",
228 "America.Los_Angeles",
229 "🇨🇦", # Non-ascii
230 "America/New\ud800York", # Contains surrogate character
231 "Europe", # Is a directory, see issue gh-85702
232 ]
233
234 for bad_key in bad_keys:
235 with self.assertRaises(self.module.ZoneInfoNotFoundError):
236 self.klass(bad_key)
237
238 def test_bad_keys_paths(self):
239 bad_keys = [
240 "/America/Los_Angeles", # Absolute path
241 "America/Los_Angeles/", # Trailing slash - not normalized
242 "../zoneinfo/America/Los_Angeles", # Traverses above TZPATH
243 "America/../America/Los_Angeles", # Not normalized
244 "America/./Los_Angeles",
245 ]
246
247 for bad_key in bad_keys:
248 with self.assertRaises(ValueError):
249 self.klass(bad_key)
250
251 def test_bad_zones(self):
252 bad_zones = [
253 b"", # Empty file
254 b"AAAA3" + b" " * 15, # Bad magic
255 # Truncated V2 file (should not loop indefinitely)
256 b"TZif2" + (b"\x00" * 39) + b"TZif2" + (b"\x00" * 39) + b"\n" + b"Part",
257 ]
258
259 for bad_zone in bad_zones:
260 fobj = io.BytesIO(bad_zone)
261 with self.assertRaises(ValueError):
262 self.klass.from_file(fobj)
263
264 def test_fromutc_errors(self):
265 key = next(iter(self.zones()))
266 zone = self.zone_from_key(key)
267
268 bad_values = [
269 (datetime(2019, 1, 1, tzinfo=timezone.utc), ValueError),
270 (datetime(2019, 1, 1), ValueError),
271 (date(2019, 1, 1), TypeError),
272 (time(0), TypeError),
273 (0, TypeError),
274 ("2019-01-01", TypeError),
275 ]
276
277 for val, exc_type in bad_values:
278 with self.subTest(val=val):
279 with self.assertRaises(exc_type):
280 zone.fromutc(val)
281
282 def test_utc(self):
283 zi = self.klass("UTC")
284 dt = datetime(2020, 1, 1, tzinfo=zi)
285
286 self.assertEqual(dt.utcoffset(), ZERO)
287 self.assertEqual(dt.dst(), ZERO)
288 self.assertEqual(dt.tzname(), "UTC")
289
290 def test_unambiguous(self):
291 test_cases = []
292 for key in self.zones():
293 for zone_transition in self.load_transition_examples(key):
294 test_cases.append(
295 (
296 key,
297 zone_transition.transition - timedelta(days=2),
298 zone_transition.offset_before,
299 )
300 )
301
302 test_cases.append(
303 (
304 key,
305 zone_transition.transition + timedelta(days=2),
306 zone_transition.offset_after,
307 )
308 )
309
310 for key, dt, offset in test_cases:
311 with self.subTest(key=key, dt=dt, offset=offset):
312 tzi = self.zone_from_key(key)
313 dt = dt.replace(tzinfo=tzi)
314
315 self.assertEqual(dt.tzname(), offset.tzname, dt)
316 self.assertEqual(dt.utcoffset(), offset.utcoffset, dt)
317 self.assertEqual(dt.dst(), offset.dst, dt)
318
319 def test_folds_and_gaps(self):
320 test_cases = []
321 for key in self.zones():
322 tests = {"folds": [], "gaps": []}
323 for zt in self.load_transition_examples(key):
324 if zt.fold:
325 test_group = tests["folds"]
326 elif zt.gap:
327 test_group = tests["gaps"]
328 else:
329 # Assign a random variable here to disable the peephole
330 # optimizer so that coverage can see this line.
331 # See bpo-2506 for more information.
332 no_peephole_opt = None
333 continue
334
335 # Cases are of the form key, dt, fold, offset
336 dt = zt.anomaly_start - timedelta(seconds=1)
337 test_group.append((dt, 0, zt.offset_before))
338 test_group.append((dt, 1, zt.offset_before))
339
340 dt = zt.anomaly_start
341 test_group.append((dt, 0, zt.offset_before))
342 test_group.append((dt, 1, zt.offset_after))
343
344 dt = zt.anomaly_start + timedelta(seconds=1)
345 test_group.append((dt, 0, zt.offset_before))
346 test_group.append((dt, 1, zt.offset_after))
347
348 dt = zt.anomaly_end - timedelta(seconds=1)
349 test_group.append((dt, 0, zt.offset_before))
350 test_group.append((dt, 1, zt.offset_after))
351
352 dt = zt.anomaly_end
353 test_group.append((dt, 0, zt.offset_after))
354 test_group.append((dt, 1, zt.offset_after))
355
356 dt = zt.anomaly_end + timedelta(seconds=1)
357 test_group.append((dt, 0, zt.offset_after))
358 test_group.append((dt, 1, zt.offset_after))
359
360 for grp, test_group in tests.items():
361 test_cases.append(((key, grp), test_group))
362
363 for (key, grp), tests in test_cases:
364 with self.subTest(key=key, grp=grp):
365 tzi = self.zone_from_key(key)
366
367 for dt, fold, offset in tests:
368 dt = dt.replace(fold=fold, tzinfo=tzi)
369
370 self.assertEqual(dt.tzname(), offset.tzname, dt)
371 self.assertEqual(dt.utcoffset(), offset.utcoffset, dt)
372 self.assertEqual(dt.dst(), offset.dst, dt)
373
374 def test_folds_from_utc(self):
375 for key in self.zones():
376 zi = self.zone_from_key(key)
377 with self.subTest(key=key):
378 for zt in self.load_transition_examples(key):
379 if not zt.fold:
380 continue
381
382 dt_utc = zt.transition_utc
383 dt_before_utc = dt_utc - timedelta(seconds=1)
384 dt_after_utc = dt_utc + timedelta(seconds=1)
385
386 dt_before = dt_before_utc.astimezone(zi)
387 self.assertEqual(dt_before.fold, 0, (dt_before, dt_utc))
388
389 dt_after = dt_after_utc.astimezone(zi)
390 self.assertEqual(dt_after.fold, 1, (dt_after, dt_utc))
391
392 def test_time_variable_offset(self):
393 # self.zones() only ever returns variable-offset zones
394 for key in self.zones():
395 zi = self.zone_from_key(key)
396 t = time(11, 15, 1, 34471, tzinfo=zi)
397
398 with self.subTest(key=key):
399 self.assertIs(t.tzname(), None)
400 self.assertIs(t.utcoffset(), None)
401 self.assertIs(t.dst(), None)
402
403 def test_time_fixed_offset(self):
404 for key, offset in self.fixed_offset_zones():
405 zi = self.zone_from_key(key)
406
407 t = time(11, 15, 1, 34471, tzinfo=zi)
408
409 with self.subTest(key=key):
410 self.assertEqual(t.tzname(), offset.tzname)
411 self.assertEqual(t.utcoffset(), offset.utcoffset)
412 self.assertEqual(t.dst(), offset.dst)
413
414 def test_cache_exception(self):
415 class Incomparable(str):
416 eq_called = False
417 def __eq__(self, other):
418 self.eq_called = True
419 raise CustomError
420 __hash__ = str.__hash__
421
422 key = "America/Los_Angeles"
423 tz1 = self.klass(key)
424 key = Incomparable(key)
425 try:
426 tz2 = self.klass(key)
427 except CustomError:
428 self.assertTrue(key.eq_called)
429 else:
430 self.assertFalse(key.eq_called)
431 self.assertIs(tz2, tz1)
432
433
434 class CZoneInfoTest(ZoneInfoTest):
435 module = c_zoneinfo
436
437 @unittest.skipIf(MISSING_C_DOCSTRINGS,
438 "Signature information for builtins requires docstrings")
439 def test_signatures(self):
440 """Ensure that C module has valid method signatures."""
441 import inspect
442
443 must_have_signatures = (
444 self.klass.clear_cache,
445 self.klass.no_cache,
446 self.klass.from_file,
447 )
448 for method in must_have_signatures:
449 with self.subTest(method=method):
450 inspect.Signature.from_callable(method)
451
452 def test_fold_mutate(self):
453 """Test that fold isn't mutated when no change is necessary.
454
455 The underlying C API is capable of mutating datetime objects, and
456 may rely on the fact that addition of a datetime object returns a
457 new datetime; this test ensures that the input datetime to fromutc
458 is not mutated.
459 """
460
461 def to_subclass(dt):
462 class SameAddSubclass(type(dt)):
463 def __add__(self, other):
464 if other == timedelta(0):
465 return self
466
467 return super().__add__(other) # pragma: nocover
468
469 return SameAddSubclass(
470 dt.year,
471 dt.month,
472 dt.day,
473 dt.hour,
474 dt.minute,
475 dt.second,
476 dt.microsecond,
477 fold=dt.fold,
478 tzinfo=dt.tzinfo,
479 )
480
481 subclass = [False, True]
482
483 key = "Europe/London"
484 zi = self.zone_from_key(key)
485 for zt in self.load_transition_examples(key):
486 if zt.fold and zt.offset_after.utcoffset == ZERO:
487 example = zt.transition_utc.replace(tzinfo=zi)
488 break
489
490 for subclass in [False, True]:
491 if subclass:
492 dt = to_subclass(example)
493 else:
494 dt = example
495
496 with self.subTest(subclass=subclass):
497 dt_fromutc = zi.fromutc(dt)
498
499 self.assertEqual(dt_fromutc.fold, 1)
500 self.assertEqual(dt.fold, 0)
501
502
503 class ZoneInfoDatetimeSubclassTest(DatetimeSubclassMixin, ZoneInfoTest):
504 pass
505
506
507 class CZoneInfoDatetimeSubclassTest(DatetimeSubclassMixin, CZoneInfoTest):
508 pass
509
510
511 class ZoneInfoSubclassTest(ZoneInfoTest):
512 @classmethod
513 def setUpClass(cls):
514 super().setUpClass()
515
516 class ZISubclass(cls.klass):
517 pass
518
519 cls.class_name = "ZISubclass"
520 cls.parent_klass = cls.klass
521 cls.klass = ZISubclass
522
523 def test_subclass_own_cache(self):
524 base_obj = self.parent_klass("Europe/London")
525 sub_obj = self.klass("Europe/London")
526
527 self.assertIsNot(base_obj, sub_obj)
528 self.assertIsInstance(base_obj, self.parent_klass)
529 self.assertIsInstance(sub_obj, self.klass)
530
531
532 class CZoneInfoSubclassTest(ZoneInfoSubclassTest):
533 module = c_zoneinfo
534
535
536 class ZoneInfoV1Test(ZoneInfoTest):
537 @property
538 def zoneinfo_data(self):
539 return ZONEINFO_DATA_V1
540
541 def load_transition_examples(self, key):
542 # We will discard zdump examples outside the range epoch +/- 2**31,
543 # because they are not well-supported in Version 1 files.
544 epoch = datetime(1970, 1, 1)
545 max_offset_32 = timedelta(seconds=2 ** 31)
546 min_dt = epoch - max_offset_32
547 max_dt = epoch + max_offset_32
548
549 for zt in ZoneDumpData.load_transition_examples(key):
550 if min_dt <= zt.transition <= max_dt:
551 yield zt
552
553
554 class CZoneInfoV1Test(ZoneInfoV1Test):
555 module = c_zoneinfo
556
557
558 @unittest.skipIf(
559 not HAS_TZDATA_PKG, "Skipping tzdata-specific tests: tzdata not installed"
560 )
561 class TZDataTests(ZoneInfoTest):
562 """
563 Runs all the ZoneInfoTest tests, but against the tzdata package
564
565 NOTE: The ZoneDumpData has frozen test data, but tzdata will update, so
566 some of the tests (particularly those related to the far future) may break
567 in the event that the time zone policies in the relevant time zones change.
568 """
569
570 @property
571 def tzpath(self):
572 return []
573
574 @property
575 def block_tzdata(self):
576 return False
577
578 def zone_from_key(self, key):
579 return self.klass(key=key)
580
581
582 @unittest.skipIf(
583 not HAS_TZDATA_PKG, "Skipping tzdata-specific tests: tzdata not installed"
584 )
585 class CTZDataTests(TZDataTests):
586 module = c_zoneinfo
587
588
589 class WeirdZoneTest(ZoneInfoTestBase):
590 module = py_zoneinfo
591
592 def test_one_transition(self):
593 LMT = ZoneOffset("LMT", -timedelta(hours=6, minutes=31, seconds=2))
594 STD = ZoneOffset("STD", -timedelta(hours=6))
595
596 transitions = [
597 ZoneTransition(datetime(1883, 6, 9, 14), LMT, STD),
598 ]
599
600 after = "STD6"
601
602 zf = self.construct_zone(transitions, after)
603 zi = self.klass.from_file(zf)
604
605 dt0 = datetime(1883, 6, 9, 1, tzinfo=zi)
606 dt1 = datetime(1883, 6, 10, 1, tzinfo=zi)
607
608 for dt, offset in [(dt0, LMT), (dt1, STD)]:
609 with self.subTest(name="local", dt=dt):
610 self.assertEqual(dt.tzname(), offset.tzname)
611 self.assertEqual(dt.utcoffset(), offset.utcoffset)
612 self.assertEqual(dt.dst(), offset.dst)
613
614 dts = [
615 (
616 datetime(1883, 6, 9, 1, tzinfo=zi),
617 datetime(1883, 6, 9, 7, 31, 2, tzinfo=timezone.utc),
618 ),
619 (
620 datetime(2010, 4, 1, 12, tzinfo=zi),
621 datetime(2010, 4, 1, 18, tzinfo=timezone.utc),
622 ),
623 ]
624
625 for dt_local, dt_utc in dts:
626 with self.subTest(name="fromutc", dt=dt_local):
627 dt_actual = dt_utc.astimezone(zi)
628 self.assertEqual(dt_actual, dt_local)
629
630 dt_utc_actual = dt_local.astimezone(timezone.utc)
631 self.assertEqual(dt_utc_actual, dt_utc)
632
633 def test_one_zone_dst(self):
634 DST = ZoneOffset("DST", ONE_H, ONE_H)
635 transitions = [
636 ZoneTransition(datetime(1970, 1, 1), DST, DST),
637 ]
638
639 after = "STD0DST-1,0/0,J365/25"
640
641 zf = self.construct_zone(transitions, after)
642 zi = self.klass.from_file(zf)
643
644 dts = [
645 datetime(1900, 3, 1),
646 datetime(1965, 9, 12),
647 datetime(1970, 1, 1),
648 datetime(2010, 11, 3),
649 datetime(2040, 1, 1),
650 ]
651
652 for dt in dts:
653 dt = dt.replace(tzinfo=zi)
654 with self.subTest(dt=dt):
655 self.assertEqual(dt.tzname(), DST.tzname)
656 self.assertEqual(dt.utcoffset(), DST.utcoffset)
657 self.assertEqual(dt.dst(), DST.dst)
658
659 def test_no_tz_str(self):
660 STD = ZoneOffset("STD", ONE_H, ZERO)
661 DST = ZoneOffset("DST", 2 * ONE_H, ONE_H)
662
663 transitions = []
664 for year in range(1996, 2000):
665 transitions.append(
666 ZoneTransition(datetime(year, 3, 1, 2), STD, DST)
667 )
668 transitions.append(
669 ZoneTransition(datetime(year, 11, 1, 2), DST, STD)
670 )
671
672 after = ""
673
674 zf = self.construct_zone(transitions, after)
675
676 # According to RFC 8536, local times after the last transition time
677 # with an empty TZ string are unspecified. We will go with "hold the
678 # last transition", but the most we should promise is "doesn't crash."
679 zi = self.klass.from_file(zf)
680
681 cases = [
682 (datetime(1995, 1, 1), STD),
683 (datetime(1996, 4, 1), DST),
684 (datetime(1996, 11, 2), STD),
685 (datetime(2001, 1, 1), STD),
686 ]
687
688 for dt, offset in cases:
689 dt = dt.replace(tzinfo=zi)
690 with self.subTest(dt=dt):
691 self.assertEqual(dt.tzname(), offset.tzname)
692 self.assertEqual(dt.utcoffset(), offset.utcoffset)
693 self.assertEqual(dt.dst(), offset.dst)
694
695 # Test that offsets return None when using a datetime.time
696 t = time(0, tzinfo=zi)
697 with self.subTest("Testing datetime.time"):
698 self.assertIs(t.tzname(), None)
699 self.assertIs(t.utcoffset(), None)
700 self.assertIs(t.dst(), None)
701
702 def test_tz_before_only(self):
703 # From RFC 8536 Section 3.2:
704 #
705 # If there are no transitions, local time for all timestamps is
706 # specified by the TZ string in the footer if present and nonempty;
707 # otherwise, it is specified by time type 0.
708
709 offsets = [
710 ZoneOffset("STD", ZERO, ZERO),
711 ZoneOffset("DST", ONE_H, ONE_H),
712 ]
713
714 for offset in offsets:
715 # Phantom transition to set time type 0.
716 transitions = [
717 ZoneTransition(None, offset, offset),
718 ]
719
720 after = ""
721
722 zf = self.construct_zone(transitions, after)
723 zi = self.klass.from_file(zf)
724
725 dts = [
726 datetime(1900, 1, 1),
727 datetime(1970, 1, 1),
728 datetime(2000, 1, 1),
729 ]
730
731 for dt in dts:
732 dt = dt.replace(tzinfo=zi)
733 with self.subTest(offset=offset, dt=dt):
734 self.assertEqual(dt.tzname(), offset.tzname)
735 self.assertEqual(dt.utcoffset(), offset.utcoffset)
736 self.assertEqual(dt.dst(), offset.dst)
737
738 def test_empty_zone(self):
739 zf = self.construct_zone([], "")
740
741 with self.assertRaises(ValueError):
742 self.klass.from_file(zf)
743
744 def test_zone_very_large_timestamp(self):
745 """Test when a transition is in the far past or future.
746
747 Particularly, this is a concern if something:
748
749 1. Attempts to call ``datetime.timestamp`` for a datetime outside
750 of ``[datetime.min, datetime.max]``.
751 2. Attempts to construct a timedelta outside of
752 ``[timedelta.min, timedelta.max]``.
753
754 This actually occurs "in the wild", as some time zones on Ubuntu (at
755 least as of 2020) have an initial transition added at ``-2**58``.
756 """
757
758 LMT = ZoneOffset("LMT", timedelta(seconds=-968))
759 GMT = ZoneOffset("GMT", ZERO)
760
761 transitions = [
762 (-(1 << 62), LMT, LMT),
763 ZoneTransition(datetime(1912, 1, 1), LMT, GMT),
764 ((1 << 62), GMT, GMT),
765 ]
766
767 after = "GMT0"
768
769 zf = self.construct_zone(transitions, after)
770 zi = self.klass.from_file(zf, key="Africa/Abidjan")
771
772 offset_cases = [
773 (datetime.min, LMT),
774 (datetime.max, GMT),
775 (datetime(1911, 12, 31), LMT),
776 (datetime(1912, 1, 2), GMT),
777 ]
778
779 for dt_naive, offset in offset_cases:
780 dt = dt_naive.replace(tzinfo=zi)
781 with self.subTest(name="offset", dt=dt, offset=offset):
782 self.assertEqual(dt.tzname(), offset.tzname)
783 self.assertEqual(dt.utcoffset(), offset.utcoffset)
784 self.assertEqual(dt.dst(), offset.dst)
785
786 utc_cases = [
787 (datetime.min, datetime.min + timedelta(seconds=968)),
788 (datetime(1898, 12, 31, 23, 43, 52), datetime(1899, 1, 1)),
789 (
790 datetime(1911, 12, 31, 23, 59, 59, 999999),
791 datetime(1912, 1, 1, 0, 16, 7, 999999),
792 ),
793 (datetime(1912, 1, 1, 0, 16, 8), datetime(1912, 1, 1, 0, 16, 8)),
794 (datetime(1970, 1, 1), datetime(1970, 1, 1)),
795 (datetime.max, datetime.max),
796 ]
797
798 for naive_dt, naive_dt_utc in utc_cases:
799 dt = naive_dt.replace(tzinfo=zi)
800 dt_utc = naive_dt_utc.replace(tzinfo=timezone.utc)
801
802 self.assertEqual(dt_utc.astimezone(zi), dt)
803 self.assertEqual(dt, dt_utc)
804
805 def test_fixed_offset_phantom_transition(self):
806 UTC = ZoneOffset("UTC", ZERO, ZERO)
807
808 transitions = [ZoneTransition(datetime(1970, 1, 1), UTC, UTC)]
809
810 after = "UTC0"
811 zf = self.construct_zone(transitions, after)
812 zi = self.klass.from_file(zf, key="UTC")
813
814 dt = datetime(2020, 1, 1, tzinfo=zi)
815 with self.subTest("datetime.datetime"):
816 self.assertEqual(dt.tzname(), UTC.tzname)
817 self.assertEqual(dt.utcoffset(), UTC.utcoffset)
818 self.assertEqual(dt.dst(), UTC.dst)
819
820 t = time(0, tzinfo=zi)
821 with self.subTest("datetime.time"):
822 self.assertEqual(t.tzname(), UTC.tzname)
823 self.assertEqual(t.utcoffset(), UTC.utcoffset)
824 self.assertEqual(t.dst(), UTC.dst)
825
826 def construct_zone(self, transitions, after=None, version=3):
827 # These are not used for anything, so we're not going to include
828 # them for now.
829 isutc = []
830 isstd = []
831 leap_seconds = []
832
833 offset_lists = [[], []]
834 trans_times_lists = [[], []]
835 trans_idx_lists = [[], []]
836
837 v1_range = (-(2 ** 31), 2 ** 31)
838 v2_range = (-(2 ** 63), 2 ** 63)
839 ranges = [v1_range, v2_range]
840
841 def zt_as_tuple(zt):
842 # zt may be a tuple (timestamp, offset_before, offset_after) or
843 # a ZoneTransition object — this is to allow the timestamp to be
844 # values that are outside the valid range for datetimes but still
845 # valid 64-bit timestamps.
846 if isinstance(zt, tuple):
847 return zt
848
849 if zt.transition:
850 trans_time = int(zt.transition_utc.timestamp())
851 else:
852 trans_time = None
853
854 return (trans_time, zt.offset_before, zt.offset_after)
855
856 transitions = sorted(map(zt_as_tuple, transitions), key=lambda x: x[0])
857
858 for zt in transitions:
859 trans_time, offset_before, offset_after = zt
860
861 for v, (dt_min, dt_max) in enumerate(ranges):
862 offsets = offset_lists[v]
863 trans_times = trans_times_lists[v]
864 trans_idx = trans_idx_lists[v]
865
866 if trans_time is not None and not (
867 dt_min <= trans_time <= dt_max
868 ):
869 continue
870
871 if offset_before not in offsets:
872 offsets.append(offset_before)
873
874 if offset_after not in offsets:
875 offsets.append(offset_after)
876
877 if trans_time is not None:
878 trans_times.append(trans_time)
879 trans_idx.append(offsets.index(offset_after))
880
881 isutcnt = len(isutc)
882 isstdcnt = len(isstd)
883 leapcnt = len(leap_seconds)
884
885 zonefile = io.BytesIO()
886
887 time_types = ("l", "q")
888 for v in range(min((version, 2))):
889 offsets = offset_lists[v]
890 trans_times = trans_times_lists[v]
891 trans_idx = trans_idx_lists[v]
892 time_type = time_types[v]
893
894 # Translate the offsets into something closer to the C values
895 abbrstr = bytearray()
896 ttinfos = []
897
898 for offset in offsets:
899 utcoff = int(offset.utcoffset.total_seconds())
900 isdst = bool(offset.dst)
901 abbrind = len(abbrstr)
902
903 ttinfos.append((utcoff, isdst, abbrind))
904 abbrstr += offset.tzname.encode("ascii") + b"\x00"
905 abbrstr = bytes(abbrstr)
906
907 typecnt = len(offsets)
908 timecnt = len(trans_times)
909 charcnt = len(abbrstr)
910
911 # Write the header
912 zonefile.write(b"TZif")
913 zonefile.write(b"%d" % version)
914 zonefile.write(b" " * 15)
915 zonefile.write(
916 struct.pack(
917 ">6l", isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt
918 )
919 )
920
921 # Now the transition data
922 zonefile.write(struct.pack(f">{timecnt}{time_type}", *trans_times))
923 zonefile.write(struct.pack(f">{timecnt}B", *trans_idx))
924
925 for ttinfo in ttinfos:
926 zonefile.write(struct.pack(">lbb", *ttinfo))
927
928 zonefile.write(bytes(abbrstr))
929
930 # Now the metadata and leap seconds
931 zonefile.write(struct.pack(f"{isutcnt}b", *isutc))
932 zonefile.write(struct.pack(f"{isstdcnt}b", *isstd))
933 zonefile.write(struct.pack(f">{leapcnt}l", *leap_seconds))
934
935 # Finally we write the TZ string if we're writing a Version 2+ file
936 if v > 0:
937 zonefile.write(b"\x0A")
938 zonefile.write(after.encode("ascii"))
939 zonefile.write(b"\x0A")
940
941 zonefile.seek(0)
942 return zonefile
943
944
945 class CWeirdZoneTest(WeirdZoneTest):
946 module = c_zoneinfo
947
948
949 class TZStrTest(ZoneInfoTestBase):
950 module = py_zoneinfo
951
952 NORMAL = 0
953 FOLD = 1
954 GAP = 2
955
956 @classmethod
957 def setUpClass(cls):
958 super().setUpClass()
959
960 cls._populate_test_cases()
961 cls.populate_tzstr_header()
962
963 @classmethod
964 def populate_tzstr_header(cls):
965 out = bytearray()
966 # The TZif format always starts with a Version 1 file followed by
967 # the Version 2+ file. In this case, we have no transitions, just
968 # the tzstr in the footer, so up to the footer, the files are
969 # identical and we can just write the same file twice in a row.
970 for _ in range(2):
971 out += b"TZif" # Magic value
972 out += b"3" # Version
973 out += b" " * 15 # Reserved
974
975 # We will not write any of the manual transition parts
976 out += struct.pack(">6l", 0, 0, 0, 0, 0, 0)
977
978 cls._tzif_header = bytes(out)
979
980 def zone_from_tzstr(self, tzstr):
981 """Creates a zoneinfo file following a POSIX rule."""
982 zonefile = io.BytesIO(self._tzif_header)
983 zonefile.seek(0, 2)
984
985 # Write the footer
986 zonefile.write(b"\x0A")
987 zonefile.write(tzstr.encode("ascii"))
988 zonefile.write(b"\x0A")
989
990 zonefile.seek(0)
991
992 return self.klass.from_file(zonefile, key=tzstr)
993
994 def test_tzstr_localized(self):
995 for tzstr, cases in self.test_cases.items():
996 with self.subTest(tzstr=tzstr):
997 zi = self.zone_from_tzstr(tzstr)
998
999 for dt_naive, offset, _ in cases:
1000 dt = dt_naive.replace(tzinfo=zi)
1001
1002 with self.subTest(tzstr=tzstr, dt=dt, offset=offset):
1003 self.assertEqual(dt.tzname(), offset.tzname)
1004 self.assertEqual(dt.utcoffset(), offset.utcoffset)
1005 self.assertEqual(dt.dst(), offset.dst)
1006
1007 def test_tzstr_from_utc(self):
1008 for tzstr, cases in self.test_cases.items():
1009 with self.subTest(tzstr=tzstr):
1010 zi = self.zone_from_tzstr(tzstr)
1011
1012 for dt_naive, offset, dt_type in cases:
1013 if dt_type == self.GAP:
1014 continue # Cannot create a gap from UTC
1015
1016 dt_utc = (dt_naive - offset.utcoffset).replace(
1017 tzinfo=timezone.utc
1018 )
1019
1020 # Check that we can go UTC -> Our zone
1021 dt_act = dt_utc.astimezone(zi)
1022 dt_exp = dt_naive.replace(tzinfo=zi)
1023
1024 self.assertEqual(dt_act, dt_exp)
1025
1026 if dt_type == self.FOLD:
1027 self.assertEqual(dt_act.fold, dt_naive.fold, dt_naive)
1028 else:
1029 self.assertEqual(dt_act.fold, 0)
1030
1031 # Now check that we can go our zone -> UTC
1032 dt_act = dt_exp.astimezone(timezone.utc)
1033
1034 self.assertEqual(dt_act, dt_utc)
1035
1036 def test_extreme_tzstr(self):
1037 tzstrs = [
1038 # Extreme offset hour
1039 "AAA24",
1040 "AAA+24",
1041 "AAA-24",
1042 "AAA24BBB,J60/2,J300/2",
1043 "AAA+24BBB,J60/2,J300/2",
1044 "AAA-24BBB,J60/2,J300/2",
1045 "AAA4BBB24,J60/2,J300/2",
1046 "AAA4BBB+24,J60/2,J300/2",
1047 "AAA4BBB-24,J60/2,J300/2",
1048 # Extreme offset minutes
1049 "AAA4:00BBB,J60/2,J300/2",
1050 "AAA4:59BBB,J60/2,J300/2",
1051 "AAA4BBB5:00,J60/2,J300/2",
1052 "AAA4BBB5:59,J60/2,J300/2",
1053 # Extreme offset seconds
1054 "AAA4:00:00BBB,J60/2,J300/2",
1055 "AAA4:00:59BBB,J60/2,J300/2",
1056 "AAA4BBB5:00:00,J60/2,J300/2",
1057 "AAA4BBB5:00:59,J60/2,J300/2",
1058 # Extreme total offset
1059 "AAA24:59:59BBB5,J60/2,J300/2",
1060 "AAA-24:59:59BBB5,J60/2,J300/2",
1061 "AAA4BBB24:59:59,J60/2,J300/2",
1062 "AAA4BBB-24:59:59,J60/2,J300/2",
1063 # Extreme months
1064 "AAA4BBB,M12.1.1/2,M1.1.1/2",
1065 "AAA4BBB,M1.1.1/2,M12.1.1/2",
1066 # Extreme weeks
1067 "AAA4BBB,M1.5.1/2,M1.1.1/2",
1068 "AAA4BBB,M1.1.1/2,M1.5.1/2",
1069 # Extreme weekday
1070 "AAA4BBB,M1.1.6/2,M2.1.1/2",
1071 "AAA4BBB,M1.1.1/2,M2.1.6/2",
1072 # Extreme numeric offset
1073 "AAA4BBB,0/2,20/2",
1074 "AAA4BBB,0/2,0/14",
1075 "AAA4BBB,20/2,365/2",
1076 "AAA4BBB,365/2,365/14",
1077 # Extreme julian offset
1078 "AAA4BBB,J1/2,J20/2",
1079 "AAA4BBB,J1/2,J1/14",
1080 "AAA4BBB,J20/2,J365/2",
1081 "AAA4BBB,J365/2,J365/14",
1082 # Extreme transition hour
1083 "AAA4BBB,J60/167,J300/2",
1084 "AAA4BBB,J60/+167,J300/2",
1085 "AAA4BBB,J60/-167,J300/2",
1086 "AAA4BBB,J60/2,J300/167",
1087 "AAA4BBB,J60/2,J300/+167",
1088 "AAA4BBB,J60/2,J300/-167",
1089 # Extreme transition minutes
1090 "AAA4BBB,J60/2:00,J300/2",
1091 "AAA4BBB,J60/2:59,J300/2",
1092 "AAA4BBB,J60/2,J300/2:00",
1093 "AAA4BBB,J60/2,J300/2:59",
1094 # Extreme transition seconds
1095 "AAA4BBB,J60/2:00:00,J300/2",
1096 "AAA4BBB,J60/2:00:59,J300/2",
1097 "AAA4BBB,J60/2,J300/2:00:00",
1098 "AAA4BBB,J60/2,J300/2:00:59",
1099 # Extreme total transition time
1100 "AAA4BBB,J60/167:59:59,J300/2",
1101 "AAA4BBB,J60/-167:59:59,J300/2",
1102 "AAA4BBB,J60/2,J300/167:59:59",
1103 "AAA4BBB,J60/2,J300/-167:59:59",
1104 ]
1105
1106 for tzstr in tzstrs:
1107 with self.subTest(tzstr=tzstr):
1108 self.zone_from_tzstr(tzstr)
1109
1110 def test_invalid_tzstr(self):
1111 invalid_tzstrs = [
1112 "PST8PDT", # DST but no transition specified
1113 "+11", # Unquoted alphanumeric
1114 "GMT,M3.2.0/2,M11.1.0/3", # Transition rule but no DST
1115 "GMT0+11,M3.2.0/2,M11.1.0/3", # Unquoted alphanumeric in DST
1116 "PST8PDT,M3.2.0/2", # Only one transition rule
1117 # Invalid offset hours
1118 "AAA168",
1119 "AAA+168",
1120 "AAA-168",
1121 "AAA168BBB,J60/2,J300/2",
1122 "AAA+168BBB,J60/2,J300/2",
1123 "AAA-168BBB,J60/2,J300/2",
1124 "AAA4BBB168,J60/2,J300/2",
1125 "AAA4BBB+168,J60/2,J300/2",
1126 "AAA4BBB-168,J60/2,J300/2",
1127 # Invalid offset minutes
1128 "AAA4:0BBB,J60/2,J300/2",
1129 "AAA4:100BBB,J60/2,J300/2",
1130 "AAA4BBB5:0,J60/2,J300/2",
1131 "AAA4BBB5:100,J60/2,J300/2",
1132 # Invalid offset seconds
1133 "AAA4:00:0BBB,J60/2,J300/2",
1134 "AAA4:00:100BBB,J60/2,J300/2",
1135 "AAA4BBB5:00:0,J60/2,J300/2",
1136 "AAA4BBB5:00:100,J60/2,J300/2",
1137 # Completely invalid dates
1138 "AAA4BBB,M1443339,M11.1.0/3",
1139 "AAA4BBB,M3.2.0/2,0349309483959c",
1140 "AAA4BBB,,J300/2",
1141 "AAA4BBB,z,J300/2",
1142 "AAA4BBB,J60/2,",
1143 "AAA4BBB,J60/2,z",
1144 # Invalid months
1145 "AAA4BBB,M13.1.1/2,M1.1.1/2",
1146 "AAA4BBB,M1.1.1/2,M13.1.1/2",
1147 "AAA4BBB,M0.1.1/2,M1.1.1/2",
1148 "AAA4BBB,M1.1.1/2,M0.1.1/2",
1149 # Invalid weeks
1150 "AAA4BBB,M1.6.1/2,M1.1.1/2",
1151 "AAA4BBB,M1.1.1/2,M1.6.1/2",
1152 # Invalid weekday
1153 "AAA4BBB,M1.1.7/2,M2.1.1/2",
1154 "AAA4BBB,M1.1.1/2,M2.1.7/2",
1155 # Invalid numeric offset
1156 "AAA4BBB,-1/2,20/2",
1157 "AAA4BBB,1/2,-1/2",
1158 "AAA4BBB,367,20/2",
1159 "AAA4BBB,1/2,367/2",
1160 # Invalid julian offset
1161 "AAA4BBB,J0/2,J20/2",
1162 "AAA4BBB,J20/2,J366/2",
1163 # Invalid transition time
1164 "AAA4BBB,J60/2/3,J300/2",
1165 "AAA4BBB,J60/2,J300/2/3",
1166 # Invalid transition hour
1167 "AAA4BBB,J60/168,J300/2",
1168 "AAA4BBB,J60/+168,J300/2",
1169 "AAA4BBB,J60/-168,J300/2",
1170 "AAA4BBB,J60/2,J300/168",
1171 "AAA4BBB,J60/2,J300/+168",
1172 "AAA4BBB,J60/2,J300/-168",
1173 # Invalid transition minutes
1174 "AAA4BBB,J60/2:0,J300/2",
1175 "AAA4BBB,J60/2:100,J300/2",
1176 "AAA4BBB,J60/2,J300/2:0",
1177 "AAA4BBB,J60/2,J300/2:100",
1178 # Invalid transition seconds
1179 "AAA4BBB,J60/2:00:0,J300/2",
1180 "AAA4BBB,J60/2:00:100,J300/2",
1181 "AAA4BBB,J60/2,J300/2:00:0",
1182 "AAA4BBB,J60/2,J300/2:00:100",
1183 ]
1184
1185 for invalid_tzstr in invalid_tzstrs:
1186 with self.subTest(tzstr=invalid_tzstr):
1187 # Not necessarily a guaranteed property, but we should show
1188 # the problematic TZ string if that's the cause of failure.
1189 tzstr_regex = re.escape(invalid_tzstr)
1190 with self.assertRaisesRegex(ValueError, tzstr_regex):
1191 self.zone_from_tzstr(invalid_tzstr)
1192
1193 @classmethod
1194 def _populate_test_cases(cls):
1195 # This method uses a somewhat unusual style in that it populates the
1196 # test cases for each tzstr by using a decorator to automatically call
1197 # a function that mutates the current dictionary of test cases.
1198 #
1199 # The population of the test cases is done in individual functions to
1200 # give each set of test cases its own namespace in which to define
1201 # its offsets (this way we don't have to worry about variable reuse
1202 # causing problems if someone makes a typo).
1203 #
1204 # The decorator for calling is used to make it more obvious that each
1205 # function is actually called (if it's not decorated, it's not called).
1206 def call(f):
1207 """Decorator to call the addition methods.
1208
1209 This will call a function which adds at least one new entry into
1210 the `cases` dictionary. The decorator will also assert that
1211 something was added to the dictionary.
1212 """
1213 prev_len = len(cases)
1214 f()
1215 assert len(cases) > prev_len, "Function did not add a test case!"
1216
1217 NORMAL = cls.NORMAL
1218 FOLD = cls.FOLD
1219 GAP = cls.GAP
1220
1221 cases = {}
1222
1223 @call
1224 def _add():
1225 # Transition to EDT on the 2nd Sunday in March at 4 AM, and
1226 # transition back on the first Sunday in November at 3AM
1227 tzstr = "EST5EDT,M3.2.0/4:00,M11.1.0/3:00"
1228
1229 EST = ZoneOffset("EST", timedelta(hours=-5), ZERO)
1230 EDT = ZoneOffset("EDT", timedelta(hours=-4), ONE_H)
1231
1232 cases[tzstr] = (
1233 (datetime(2019, 3, 9), EST, NORMAL),
1234 (datetime(2019, 3, 10, 3, 59), EST, NORMAL),
1235 (datetime(2019, 3, 10, 4, 0, fold=0), EST, GAP),
1236 (datetime(2019, 3, 10, 4, 0, fold=1), EDT, GAP),
1237 (datetime(2019, 3, 10, 4, 1, fold=0), EST, GAP),
1238 (datetime(2019, 3, 10, 4, 1, fold=1), EDT, GAP),
1239 (datetime(2019, 11, 2), EDT, NORMAL),
1240 (datetime(2019, 11, 3, 1, 59, fold=1), EDT, NORMAL),
1241 (datetime(2019, 11, 3, 2, 0, fold=0), EDT, FOLD),
1242 (datetime(2019, 11, 3, 2, 0, fold=1), EST, FOLD),
1243 (datetime(2020, 3, 8, 3, 59), EST, NORMAL),
1244 (datetime(2020, 3, 8, 4, 0, fold=0), EST, GAP),
1245 (datetime(2020, 3, 8, 4, 0, fold=1), EDT, GAP),
1246 (datetime(2020, 11, 1, 1, 59, fold=1), EDT, NORMAL),
1247 (datetime(2020, 11, 1, 2, 0, fold=0), EDT, FOLD),
1248 (datetime(2020, 11, 1, 2, 0, fold=1), EST, FOLD),
1249 )
1250
1251 @call
1252 def _add():
1253 # Transition to BST happens on the last Sunday in March at 1 AM GMT
1254 # and the transition back happens the last Sunday in October at 2AM BST
1255 tzstr = "GMT0BST-1,M3.5.0/1:00,M10.5.0/2:00"
1256
1257 GMT = ZoneOffset("GMT", ZERO, ZERO)
1258 BST = ZoneOffset("BST", ONE_H, ONE_H)
1259
1260 cases[tzstr] = (
1261 (datetime(2019, 3, 30), GMT, NORMAL),
1262 (datetime(2019, 3, 31, 0, 59), GMT, NORMAL),
1263 (datetime(2019, 3, 31, 2, 0), BST, NORMAL),
1264 (datetime(2019, 10, 26), BST, NORMAL),
1265 (datetime(2019, 10, 27, 0, 59, fold=1), BST, NORMAL),
1266 (datetime(2019, 10, 27, 1, 0, fold=0), BST, GAP),
1267 (datetime(2019, 10, 27, 2, 0, fold=1), GMT, GAP),
1268 (datetime(2020, 3, 29, 0, 59), GMT, NORMAL),
1269 (datetime(2020, 3, 29, 2, 0), BST, NORMAL),
1270 (datetime(2020, 10, 25, 0, 59, fold=1), BST, NORMAL),
1271 (datetime(2020, 10, 25, 1, 0, fold=0), BST, FOLD),
1272 (datetime(2020, 10, 25, 2, 0, fold=1), GMT, NORMAL),
1273 )
1274
1275 @call
1276 def _add():
1277 # Austrialian time zone - DST start is chronologically first
1278 tzstr = "AEST-10AEDT,M10.1.0/2,M4.1.0/3"
1279
1280 AEST = ZoneOffset("AEST", timedelta(hours=10), ZERO)
1281 AEDT = ZoneOffset("AEDT", timedelta(hours=11), ONE_H)
1282
1283 cases[tzstr] = (
1284 (datetime(2019, 4, 6), AEDT, NORMAL),
1285 (datetime(2019, 4, 7, 1, 59), AEDT, NORMAL),
1286 (datetime(2019, 4, 7, 1, 59, fold=1), AEDT, NORMAL),
1287 (datetime(2019, 4, 7, 2, 0, fold=0), AEDT, FOLD),
1288 (datetime(2019, 4, 7, 2, 1, fold=0), AEDT, FOLD),
1289 (datetime(2019, 4, 7, 2, 0, fold=1), AEST, FOLD),
1290 (datetime(2019, 4, 7, 2, 1, fold=1), AEST, FOLD),
1291 (datetime(2019, 4, 7, 3, 0, fold=0), AEST, NORMAL),
1292 (datetime(2019, 4, 7, 3, 0, fold=1), AEST, NORMAL),
1293 (datetime(2019, 10, 5, 0), AEST, NORMAL),
1294 (datetime(2019, 10, 6, 1, 59), AEST, NORMAL),
1295 (datetime(2019, 10, 6, 2, 0, fold=0), AEST, GAP),
1296 (datetime(2019, 10, 6, 2, 0, fold=1), AEDT, GAP),
1297 (datetime(2019, 10, 6, 3, 0), AEDT, NORMAL),
1298 )
1299
1300 @call
1301 def _add():
1302 # Irish time zone - negative DST
1303 tzstr = "IST-1GMT0,M10.5.0,M3.5.0/1"
1304
1305 GMT = ZoneOffset("GMT", ZERO, -ONE_H)
1306 IST = ZoneOffset("IST", ONE_H, ZERO)
1307
1308 cases[tzstr] = (
1309 (datetime(2019, 3, 30), GMT, NORMAL),
1310 (datetime(2019, 3, 31, 0, 59), GMT, NORMAL),
1311 (datetime(2019, 3, 31, 2, 0), IST, NORMAL),
1312 (datetime(2019, 10, 26), IST, NORMAL),
1313 (datetime(2019, 10, 27, 0, 59, fold=1), IST, NORMAL),
1314 (datetime(2019, 10, 27, 1, 0, fold=0), IST, FOLD),
1315 (datetime(2019, 10, 27, 1, 0, fold=1), GMT, FOLD),
1316 (datetime(2019, 10, 27, 2, 0, fold=1), GMT, NORMAL),
1317 (datetime(2020, 3, 29, 0, 59), GMT, NORMAL),
1318 (datetime(2020, 3, 29, 2, 0), IST, NORMAL),
1319 (datetime(2020, 10, 25, 0, 59, fold=1), IST, NORMAL),
1320 (datetime(2020, 10, 25, 1, 0, fold=0), IST, FOLD),
1321 (datetime(2020, 10, 25, 2, 0, fold=1), GMT, NORMAL),
1322 )
1323
1324 @call
1325 def _add():
1326 # Pacific/Kosrae: Fixed offset zone with a quoted numerical tzname
1327 tzstr = "<+11>-11"
1328
1329 cases[tzstr] = (
1330 (
1331 datetime(2020, 1, 1),
1332 ZoneOffset("+11", timedelta(hours=11)),
1333 NORMAL,
1334 ),
1335 )
1336
1337 @call
1338 def _add():
1339 # Quoted STD and DST, transitions at 24:00
1340 tzstr = "<-04>4<-03>,M9.1.6/24,M4.1.6/24"
1341
1342 M04 = ZoneOffset("-04", timedelta(hours=-4))
1343 M03 = ZoneOffset("-03", timedelta(hours=-3), ONE_H)
1344
1345 cases[tzstr] = (
1346 (datetime(2020, 5, 1), M04, NORMAL),
1347 (datetime(2020, 11, 1), M03, NORMAL),
1348 )
1349
1350 @call
1351 def _add():
1352 # Permanent daylight saving time is modeled with transitions at 0/0
1353 # and J365/25, as mentioned in RFC 8536 Section 3.3.1
1354 tzstr = "EST5EDT,0/0,J365/25"
1355
1356 EDT = ZoneOffset("EDT", timedelta(hours=-4), ONE_H)
1357
1358 cases[tzstr] = (
1359 (datetime(2019, 1, 1), EDT, NORMAL),
1360 (datetime(2019, 6, 1), EDT, NORMAL),
1361 (datetime(2019, 12, 31, 23, 59, 59, 999999), EDT, NORMAL),
1362 (datetime(2020, 1, 1), EDT, NORMAL),
1363 (datetime(2020, 3, 1), EDT, NORMAL),
1364 (datetime(2020, 6, 1), EDT, NORMAL),
1365 (datetime(2020, 12, 31, 23, 59, 59, 999999), EDT, NORMAL),
1366 (datetime(2400, 1, 1), EDT, NORMAL),
1367 (datetime(2400, 3, 1), EDT, NORMAL),
1368 (datetime(2400, 12, 31, 23, 59, 59, 999999), EDT, NORMAL),
1369 )
1370
1371 @call
1372 def _add():
1373 # Transitions on March 1st and November 1st of each year
1374 tzstr = "AAA3BBB,J60/12,J305/12"
1375
1376 AAA = ZoneOffset("AAA", timedelta(hours=-3))
1377 BBB = ZoneOffset("BBB", timedelta(hours=-2), ONE_H)
1378
1379 cases[tzstr] = (
1380 (datetime(2019, 1, 1), AAA, NORMAL),
1381 (datetime(2019, 2, 28), AAA, NORMAL),
1382 (datetime(2019, 3, 1, 11, 59), AAA, NORMAL),
1383 (datetime(2019, 3, 1, 12, fold=0), AAA, GAP),
1384 (datetime(2019, 3, 1, 12, fold=1), BBB, GAP),
1385 (datetime(2019, 3, 1, 13), BBB, NORMAL),
1386 (datetime(2019, 11, 1, 10, 59), BBB, NORMAL),
1387 (datetime(2019, 11, 1, 11, fold=0), BBB, FOLD),
1388 (datetime(2019, 11, 1, 11, fold=1), AAA, FOLD),
1389 (datetime(2019, 11, 1, 12), AAA, NORMAL),
1390 (datetime(2019, 12, 31, 23, 59, 59, 999999), AAA, NORMAL),
1391 (datetime(2020, 1, 1), AAA, NORMAL),
1392 (datetime(2020, 2, 29), AAA, NORMAL),
1393 (datetime(2020, 3, 1, 11, 59), AAA, NORMAL),
1394 (datetime(2020, 3, 1, 12, fold=0), AAA, GAP),
1395 (datetime(2020, 3, 1, 12, fold=1), BBB, GAP),
1396 (datetime(2020, 3, 1, 13), BBB, NORMAL),
1397 (datetime(2020, 11, 1, 10, 59), BBB, NORMAL),
1398 (datetime(2020, 11, 1, 11, fold=0), BBB, FOLD),
1399 (datetime(2020, 11, 1, 11, fold=1), AAA, FOLD),
1400 (datetime(2020, 11, 1, 12), AAA, NORMAL),
1401 (datetime(2020, 12, 31, 23, 59, 59, 999999), AAA, NORMAL),
1402 )
1403
1404 @call
1405 def _add():
1406 # Taken from America/Godthab, this rule has a transition on the
1407 # Saturday before the last Sunday of March and October, at 22:00
1408 # and 23:00, respectively. This is encoded with negative start
1409 # and end transition times.
1410 tzstr = "<-03>3<-02>,M3.5.0/-2,M10.5.0/-1"
1411
1412 N03 = ZoneOffset("-03", timedelta(hours=-3))
1413 N02 = ZoneOffset("-02", timedelta(hours=-2), ONE_H)
1414
1415 cases[tzstr] = (
1416 (datetime(2020, 3, 27), N03, NORMAL),
1417 (datetime(2020, 3, 28, 21, 59, 59), N03, NORMAL),
1418 (datetime(2020, 3, 28, 22, fold=0), N03, GAP),
1419 (datetime(2020, 3, 28, 22, fold=1), N02, GAP),
1420 (datetime(2020, 3, 28, 23), N02, NORMAL),
1421 (datetime(2020, 10, 24, 21), N02, NORMAL),
1422 (datetime(2020, 10, 24, 22, fold=0), N02, FOLD),
1423 (datetime(2020, 10, 24, 22, fold=1), N03, FOLD),
1424 (datetime(2020, 10, 24, 23), N03, NORMAL),
1425 )
1426
1427 @call
1428 def _add():
1429 # Transition times with minutes and seconds
1430 tzstr = "AAA3BBB,M3.2.0/01:30,M11.1.0/02:15:45"
1431
1432 AAA = ZoneOffset("AAA", timedelta(hours=-3))
1433 BBB = ZoneOffset("BBB", timedelta(hours=-2), ONE_H)
1434
1435 cases[tzstr] = (
1436 (datetime(2012, 3, 11, 1, 0), AAA, NORMAL),
1437 (datetime(2012, 3, 11, 1, 30, fold=0), AAA, GAP),
1438 (datetime(2012, 3, 11, 1, 30, fold=1), BBB, GAP),
1439 (datetime(2012, 3, 11, 2, 30), BBB, NORMAL),
1440 (datetime(2012, 11, 4, 1, 15, 44, 999999), BBB, NORMAL),
1441 (datetime(2012, 11, 4, 1, 15, 45, fold=0), BBB, FOLD),
1442 (datetime(2012, 11, 4, 1, 15, 45, fold=1), AAA, FOLD),
1443 (datetime(2012, 11, 4, 2, 15, 45), AAA, NORMAL),
1444 )
1445
1446 cls.test_cases = cases
1447
1448
1449 class CTZStrTest(TZStrTest):
1450 module = c_zoneinfo
1451
1452
1453 class ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):
1454 module = py_zoneinfo
1455
1456 def setUp(self):
1457 self.klass.clear_cache()
1458 super().setUp()
1459
1460 @property
1461 def zoneinfo_data(self):
1462 return ZONEINFO_DATA
1463
1464 @property
1465 def tzpath(self):
1466 return [self.zoneinfo_data.tzpath]
1467
1468 def test_ephemeral_zones(self):
1469 self.assertIs(
1470 self.klass("America/Los_Angeles"), self.klass("America/Los_Angeles")
1471 )
1472
1473 def test_strong_refs(self):
1474 tz0 = self.klass("Australia/Sydney")
1475 tz1 = self.klass("Australia/Sydney")
1476
1477 self.assertIs(tz0, tz1)
1478
1479 def test_no_cache(self):
1480
1481 tz0 = self.klass("Europe/Lisbon")
1482 tz1 = self.klass.no_cache("Europe/Lisbon")
1483
1484 self.assertIsNot(tz0, tz1)
1485
1486 def test_cache_reset_tzpath(self):
1487 """Test that the cache persists when tzpath has been changed.
1488
1489 The PEP specifies that as long as a reference exists to one zone
1490 with a given key, the primary constructor must continue to return
1491 the same object.
1492 """
1493 zi0 = self.klass("America/Los_Angeles")
1494 with self.tzpath_context([]):
1495 zi1 = self.klass("America/Los_Angeles")
1496
1497 self.assertIs(zi0, zi1)
1498
1499 def test_clear_cache_explicit_none(self):
1500 la0 = self.klass("America/Los_Angeles")
1501 self.klass.clear_cache(only_keys=None)
1502 la1 = self.klass("America/Los_Angeles")
1503
1504 self.assertIsNot(la0, la1)
1505
1506 def test_clear_cache_one_key(self):
1507 """Tests that you can clear a single key from the cache."""
1508 la0 = self.klass("America/Los_Angeles")
1509 dub0 = self.klass("Europe/Dublin")
1510
1511 self.klass.clear_cache(only_keys=["America/Los_Angeles"])
1512
1513 la1 = self.klass("America/Los_Angeles")
1514 dub1 = self.klass("Europe/Dublin")
1515
1516 self.assertIsNot(la0, la1)
1517 self.assertIs(dub0, dub1)
1518
1519 def test_clear_cache_two_keys(self):
1520 la0 = self.klass("America/Los_Angeles")
1521 dub0 = self.klass("Europe/Dublin")
1522 tok0 = self.klass("Asia/Tokyo")
1523
1524 self.klass.clear_cache(
1525 only_keys=["America/Los_Angeles", "Europe/Dublin"]
1526 )
1527
1528 la1 = self.klass("America/Los_Angeles")
1529 dub1 = self.klass("Europe/Dublin")
1530 tok1 = self.klass("Asia/Tokyo")
1531
1532 self.assertIsNot(la0, la1)
1533 self.assertIsNot(dub0, dub1)
1534 self.assertIs(tok0, tok1)
1535
1536 def test_clear_cache_refleak(self):
1537 class Stringy(str):
1538 allow_comparisons = True
1539 def __eq__(self, other):
1540 if not self.allow_comparisons:
1541 raise CustomError
1542 return super().__eq__(other)
1543 __hash__ = str.__hash__
1544
1545 key = Stringy("America/Los_Angeles")
1546 self.klass(key)
1547 key.allow_comparisons = False
1548 try:
1549 # Note: This is try/except rather than assertRaises because
1550 # there is no guarantee that the key is even still in the cache,
1551 # or that the key for the cache is the original `key` object.
1552 self.klass.clear_cache(only_keys="America/Los_Angeles")
1553 except CustomError:
1554 pass
1555
1556 def test_weak_cache_descriptor_use_after_free(self):
1557 class BombDescriptor:
1558 def __get__(self, obj, owner):
1559 return {}
1560
1561 class EvilZoneInfo(self.klass):
1562 pass
1563
1564 # Must be set after the class creation.
1565 EvilZoneInfo._weak_cache = BombDescriptor()
1566
1567 key = "America/Los_Angeles"
1568 zone1 = EvilZoneInfo(key)
1569 self.assertEqual(str(zone1), key)
1570
1571 EvilZoneInfo.clear_cache()
1572 zone2 = EvilZoneInfo(key)
1573 self.assertEqual(str(zone2), key)
1574 self.assertIsNot(zone2, zone1)
1575
1576
1577 class CZoneInfoCacheTest(ZoneInfoCacheTest):
1578 module = c_zoneinfo
1579
1580
1581 class ZoneInfoPickleTest(TzPathUserMixin, ZoneInfoTestBase):
1582 module = py_zoneinfo
1583
1584 def setUp(self):
1585 self.klass.clear_cache()
1586
1587 with contextlib.ExitStack() as stack:
1588 stack.enter_context(test_support.set_zoneinfo_module(self.module))
1589 self.addCleanup(stack.pop_all().close)
1590
1591 super().setUp()
1592
1593 @property
1594 def zoneinfo_data(self):
1595 return ZONEINFO_DATA
1596
1597 @property
1598 def tzpath(self):
1599 return [self.zoneinfo_data.tzpath]
1600
1601 def test_cache_hit(self):
1602 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1603 with self.subTest(proto=proto):
1604 zi_in = self.klass("Europe/Dublin")
1605 pkl = pickle.dumps(zi_in, protocol=proto)
1606 zi_rt = pickle.loads(pkl)
1607
1608 with self.subTest(test="Is non-pickled ZoneInfo"):
1609 self.assertIs(zi_in, zi_rt)
1610
1611 zi_rt2 = pickle.loads(pkl)
1612 with self.subTest(test="Is unpickled ZoneInfo"):
1613 self.assertIs(zi_rt, zi_rt2)
1614
1615 def test_cache_miss(self):
1616 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1617 with self.subTest(proto=proto):
1618 zi_in = self.klass("Europe/Dublin")
1619 pkl = pickle.dumps(zi_in, protocol=proto)
1620
1621 del zi_in
1622 self.klass.clear_cache() # Induce a cache miss
1623 zi_rt = pickle.loads(pkl)
1624 zi_rt2 = pickle.loads(pkl)
1625
1626 self.assertIs(zi_rt, zi_rt2)
1627
1628 def test_no_cache(self):
1629 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1630 with self.subTest(proto=proto):
1631 zi_no_cache = self.klass.no_cache("Europe/Dublin")
1632
1633 pkl = pickle.dumps(zi_no_cache, protocol=proto)
1634 zi_rt = pickle.loads(pkl)
1635
1636 with self.subTest(test="Not the pickled object"):
1637 self.assertIsNot(zi_rt, zi_no_cache)
1638
1639 zi_rt2 = pickle.loads(pkl)
1640 with self.subTest(test="Not a second unpickled object"):
1641 self.assertIsNot(zi_rt, zi_rt2)
1642
1643 zi_cache = self.klass("Europe/Dublin")
1644 with self.subTest(test="Not a cached object"):
1645 self.assertIsNot(zi_rt, zi_cache)
1646
1647 def test_from_file(self):
1648 key = "Europe/Dublin"
1649 with open(self.zoneinfo_data.path_from_key(key), "rb") as f:
1650 zi_nokey = self.klass.from_file(f)
1651
1652 f.seek(0)
1653 zi_key = self.klass.from_file(f, key=key)
1654
1655 test_cases = [
1656 (zi_key, "ZoneInfo with key"),
1657 (zi_nokey, "ZoneInfo without key"),
1658 ]
1659
1660 for zi, test_name in test_cases:
1661 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1662 with self.subTest(test_name=test_name, proto=proto):
1663 with self.assertRaises(pickle.PicklingError):
1664 pickle.dumps(zi, protocol=proto)
1665
1666 def test_pickle_after_from_file(self):
1667 # This may be a bit of paranoia, but this test is to ensure that no
1668 # global state is maintained in order to handle the pickle cache and
1669 # from_file behavior, and that it is possible to interweave the
1670 # constructors of each of these and pickling/unpickling without issues.
1671 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1672 with self.subTest(proto=proto):
1673 key = "Europe/Dublin"
1674 zi = self.klass(key)
1675
1676 pkl_0 = pickle.dumps(zi, protocol=proto)
1677 zi_rt_0 = pickle.loads(pkl_0)
1678 self.assertIs(zi, zi_rt_0)
1679
1680 with open(self.zoneinfo_data.path_from_key(key), "rb") as f:
1681 zi_ff = self.klass.from_file(f, key=key)
1682
1683 pkl_1 = pickle.dumps(zi, protocol=proto)
1684 zi_rt_1 = pickle.loads(pkl_1)
1685 self.assertIs(zi, zi_rt_1)
1686
1687 with self.assertRaises(pickle.PicklingError):
1688 pickle.dumps(zi_ff, protocol=proto)
1689
1690 pkl_2 = pickle.dumps(zi, protocol=proto)
1691 zi_rt_2 = pickle.loads(pkl_2)
1692 self.assertIs(zi, zi_rt_2)
1693
1694
1695 class CZoneInfoPickleTest(ZoneInfoPickleTest):
1696 module = c_zoneinfo
1697
1698
1699 class CallingConventionTest(ZoneInfoTestBase):
1700 """Tests for functions with restricted calling conventions."""
1701
1702 module = py_zoneinfo
1703
1704 @property
1705 def zoneinfo_data(self):
1706 return ZONEINFO_DATA
1707
1708 def test_from_file(self):
1709 with open(self.zoneinfo_data.path_from_key("UTC"), "rb") as f:
1710 with self.assertRaises(TypeError):
1711 self.klass.from_file(fobj=f)
1712
1713 def test_clear_cache(self):
1714 with self.assertRaises(TypeError):
1715 self.klass.clear_cache(["UTC"])
1716
1717
1718 class CCallingConventionTest(CallingConventionTest):
1719 module = c_zoneinfo
1720
1721
1722 class TzPathTest(TzPathUserMixin, ZoneInfoTestBase):
1723 module = py_zoneinfo
1724
1725 @staticmethod
1726 @contextlib.contextmanager
1727 def python_tzpath_context(value):
1728 path_var = "PYTHONTZPATH"
1729 unset_env_sentinel = object()
1730 old_env = unset_env_sentinel
1731 try:
1732 with OS_ENV_LOCK:
1733 old_env = os.environ.get(path_var, None)
1734 os.environ[path_var] = value
1735 yield
1736 finally:
1737 if old_env is unset_env_sentinel:
1738 # In this case, `old_env` was never retrieved from the
1739 # environment for whatever reason, so there's no need to
1740 # reset the environment TZPATH.
1741 pass
1742 elif old_env is None:
1743 del os.environ[path_var]
1744 else:
1745 os.environ[path_var] = old_env # pragma: nocover
1746
1747 def test_env_variable(self):
1748 """Tests that the environment variable works with reset_tzpath."""
1749 new_paths = [
1750 ("", []),
1751 (f"{DRIVE}/etc/zoneinfo", [f"{DRIVE}/etc/zoneinfo"]),
1752 (f"{DRIVE}/a/b/c{os.pathsep}{DRIVE}/d/e/f", [f"{DRIVE}/a/b/c", f"{DRIVE}/d/e/f"]),
1753 ]
1754
1755 for new_path_var, expected_result in new_paths:
1756 with self.python_tzpath_context(new_path_var):
1757 with self.subTest(tzpath=new_path_var):
1758 self.module.reset_tzpath()
1759 tzpath = self.module.TZPATH
1760 self.assertSequenceEqual(tzpath, expected_result)
1761
1762 def test_env_variable_relative_paths(self):
1763 test_cases = [
1764 [("path/to/somewhere",), ()],
1765 [
1766 (f"{DRIVE}/usr/share/zoneinfo", "path/to/somewhere",),
1767 (f"{DRIVE}/usr/share/zoneinfo",),
1768 ],
1769 [("../relative/path",), ()],
1770 [
1771 (f"{DRIVE}/usr/share/zoneinfo", "../relative/path",),
1772 (f"{DRIVE}/usr/share/zoneinfo",),
1773 ],
1774 [("path/to/somewhere", "../relative/path",), ()],
1775 [
1776 (
1777 f"{DRIVE}/usr/share/zoneinfo",
1778 "path/to/somewhere",
1779 "../relative/path",
1780 ),
1781 (f"{DRIVE}/usr/share/zoneinfo",),
1782 ],
1783 ]
1784
1785 for input_paths, expected_paths in test_cases:
1786 path_var = os.pathsep.join(input_paths)
1787 with self.python_tzpath_context(path_var):
1788 with self.subTest("warning", path_var=path_var):
1789 # Note: Per PEP 615 the warning is implementation-defined
1790 # behavior, other implementations need not warn.
1791 with self.assertWarns(self.module.InvalidTZPathWarning) as w:
1792 self.module.reset_tzpath()
1793 self.assertEqual(w.warnings[0].filename, __file__)
1794
1795 tzpath = self.module.TZPATH
1796 with self.subTest("filtered", path_var=path_var):
1797 self.assertSequenceEqual(tzpath, expected_paths)
1798
1799 def test_env_variable_relative_paths_warning_location(self):
1800 path_var = "path/to/somewhere"
1801
1802 with self.python_tzpath_context(path_var):
1803 with CleanImport("zoneinfo", "zoneinfo._tzpath"):
1804 with self.assertWarns(RuntimeWarning) as w:
1805 import zoneinfo
1806 InvalidTZPathWarning = zoneinfo.InvalidTZPathWarning
1807 self.assertIsInstance(w.warnings[0].message, InvalidTZPathWarning)
1808 # It should represent the current file:
1809 self.assertEqual(w.warnings[0].filename, __file__)
1810
1811 def test_reset_tzpath_kwarg(self):
1812 self.module.reset_tzpath(to=[f"{DRIVE}/a/b/c"])
1813
1814 self.assertSequenceEqual(self.module.TZPATH, (f"{DRIVE}/a/b/c",))
1815
1816 def test_reset_tzpath_relative_paths(self):
1817 bad_values = [
1818 ("path/to/somewhere",),
1819 ("/usr/share/zoneinfo", "path/to/somewhere",),
1820 ("../relative/path",),
1821 ("/usr/share/zoneinfo", "../relative/path",),
1822 ("path/to/somewhere", "../relative/path",),
1823 ("/usr/share/zoneinfo", "path/to/somewhere", "../relative/path",),
1824 (FakePath("path/to/somewhere"),)
1825 ]
1826 for input_paths in bad_values:
1827 with self.subTest(input_paths=input_paths):
1828 with self.assertRaises(ValueError):
1829 self.module.reset_tzpath(to=input_paths)
1830
1831 def test_tzpath_type_error(self):
1832 bad_values = [
1833 "/etc/zoneinfo:/usr/share/zoneinfo",
1834 b"/etc/zoneinfo:/usr/share/zoneinfo",
1835 0,
1836 (b"/bytes/path", "/valid/path"),
1837 (FakePath(b"/bytes/path"),),
1838 (0,),
1839 ]
1840
1841 for bad_value in bad_values:
1842 with self.subTest(value=bad_value):
1843 with self.assertRaises(TypeError):
1844 self.module.reset_tzpath(bad_value)
1845
1846 def test_tzpath_attribute(self):
1847 tzpath_0 = [f"{DRIVE}/one", f"{DRIVE}/two"]
1848 tzpath_1 = [f"{DRIVE}/three"]
1849 tzpath_pathlike = (FakePath(f"{DRIVE}/usr/share/zoneinfo"),)
1850
1851 with self.tzpath_context(tzpath_0):
1852 query_0 = self.module.TZPATH
1853
1854 with self.tzpath_context(tzpath_1):
1855 query_1 = self.module.TZPATH
1856
1857 with self.tzpath_context(tzpath_pathlike):
1858 query_pathlike = self.module.TZPATH
1859
1860 self.assertSequenceEqual(tzpath_0, query_0)
1861 self.assertSequenceEqual(tzpath_1, query_1)
1862 self.assertSequenceEqual(tuple([os.fspath(p) for p in tzpath_pathlike]), query_pathlike)
1863
1864
1865 class CTzPathTest(TzPathTest):
1866 module = c_zoneinfo
1867
1868
1869 class TestModule(ZoneInfoTestBase):
1870 module = py_zoneinfo
1871
1872 @property
1873 def zoneinfo_data(self):
1874 return ZONEINFO_DATA
1875
1876 @cached_property
1877 def _UTC_bytes(self):
1878 zone_file = self.zoneinfo_data.path_from_key("UTC")
1879 with open(zone_file, "rb") as f:
1880 return f.read()
1881
1882 def touch_zone(self, key, tz_root):
1883 """Creates a valid TZif file at key under the zoneinfo root tz_root.
1884
1885 tz_root must exist, but all folders below that will be created.
1886 """
1887 if not os.path.exists(tz_root):
1888 raise FileNotFoundError(f"{tz_root} does not exist.")
1889
1890 root_dir, *tail = key.rsplit("/", 1)
1891 if tail: # If there's no tail, then the first component isn't a dir
1892 os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)
1893
1894 zonefile_path = os.path.join(tz_root, key)
1895 with open(zonefile_path, "wb") as f:
1896 f.write(self._UTC_bytes)
1897
1898 def test_getattr_error(self):
1899 with self.assertRaises(AttributeError):
1900 self.module.NOATTRIBUTE
1901
1902 def test_dir_contains_all(self):
1903 """dir(self.module) should at least contain everything in __all__."""
1904 module_all_set = set(self.module.__all__)
1905 module_dir_set = set(dir(self.module))
1906
1907 difference = module_all_set - module_dir_set
1908
1909 self.assertFalse(difference)
1910
1911 def test_dir_unique(self):
1912 """Test that there are no duplicates in dir(self.module)"""
1913 module_dir = dir(self.module)
1914 module_unique = set(module_dir)
1915
1916 self.assertCountEqual(module_dir, module_unique)
1917
1918 def test_available_timezones(self):
1919 with self.tzpath_context([self.zoneinfo_data.tzpath]):
1920 self.assertTrue(self.zoneinfo_data.keys) # Sanity check
1921
1922 available_keys = self.module.available_timezones()
1923 zoneinfo_keys = set(self.zoneinfo_data.keys)
1924
1925 # If tzdata is not present, zoneinfo_keys == available_keys,
1926 # otherwise it should be a subset.
1927 union = zoneinfo_keys & available_keys
1928 self.assertEqual(zoneinfo_keys, union)
1929
1930 def test_available_timezones_weirdzone(self):
1931 with tempfile.TemporaryDirectory() as td:
1932 # Make a fictional zone at "Mars/Olympus_Mons"
1933 self.touch_zone("Mars/Olympus_Mons", td)
1934
1935 with self.tzpath_context([td]):
1936 available_keys = self.module.available_timezones()
1937 self.assertIn("Mars/Olympus_Mons", available_keys)
1938
1939 def test_folder_exclusions(self):
1940 expected = {
1941 "America/Los_Angeles",
1942 "America/Santiago",
1943 "America/Indiana/Indianapolis",
1944 "UTC",
1945 "Europe/Paris",
1946 "Europe/London",
1947 "Asia/Tokyo",
1948 "Australia/Sydney",
1949 }
1950
1951 base_tree = list(expected)
1952 posix_tree = [f"posix/{x}" for x in base_tree]
1953 right_tree = [f"right/{x}" for x in base_tree]
1954
1955 cases = [
1956 ("base_tree", base_tree),
1957 ("base_and_posix", base_tree + posix_tree),
1958 ("base_and_right", base_tree + right_tree),
1959 ("all_trees", base_tree + right_tree + posix_tree),
1960 ]
1961
1962 with tempfile.TemporaryDirectory() as td:
1963 for case_name, tree in cases:
1964 tz_root = os.path.join(td, case_name)
1965 os.mkdir(tz_root)
1966
1967 for key in tree:
1968 self.touch_zone(key, tz_root)
1969
1970 with self.tzpath_context([tz_root]):
1971 with self.subTest(case_name):
1972 actual = self.module.available_timezones()
1973 self.assertEqual(actual, expected)
1974
1975 def test_exclude_posixrules(self):
1976 expected = {
1977 "America/New_York",
1978 "Europe/London",
1979 }
1980
1981 tree = list(expected) + ["posixrules"]
1982
1983 with tempfile.TemporaryDirectory() as td:
1984 for key in tree:
1985 self.touch_zone(key, td)
1986
1987 with self.tzpath_context([td]):
1988 actual = self.module.available_timezones()
1989 self.assertEqual(actual, expected)
1990
1991
1992 class CTestModule(TestModule):
1993 module = c_zoneinfo
1994
1995
1996 class MiscTests(unittest.TestCase):
1997 def test_pydatetime(self):
1998 # Test that zoneinfo works if the C implementation of datetime
1999 # is not available and the Python implementation of datetime is used.
2000 # The Python implementation of zoneinfo should be used in thet case.
2001 #
2002 # Run the test in a subprocess, as importing _zoneinfo with
2003 # _datettime disabled causes crash in the previously imported
2004 # _zoneinfo.
2005 assert_python_ok('-c', '''if 1:
2006 import sys
2007 sys.modules['_datetime'] = None
2008 import datetime
2009 import zoneinfo
2010 tzinfo = zoneinfo.ZoneInfo('Europe/London')
2011 datetime.datetime(2025, 10, 26, 2, 0, tzinfo=tzinfo)
2012 ''',
2013 PYTHONTZPATH=str(ZONEINFO_DATA.tzpath))
2014
2015
2016 class ExtensionBuiltTest(unittest.TestCase):
2017 """Smoke test to ensure that the C and Python extensions are both tested.
2018
2019 Because the intention is for the Python and C versions of ZoneInfo to
2020 behave identically, these tests necessarily rely on implementation details,
2021 so the tests may need to be adjusted if the implementations change. Do not
2022 rely on these tests as an indication of stable properties of these classes.
2023 """
2024
2025 def test_cache_location(self):
2026 # The pure Python version stores caches on attributes, but the C
2027 # extension stores them in C globals (at least for now)
2028 self.assertFalse(hasattr(c_zoneinfo.ZoneInfo, "_weak_cache"))
2029 self.assertTrue(hasattr(py_zoneinfo.ZoneInfo, "_weak_cache"))
2030
2031 @requires_gil_enabled("gh-117783: types may be immortalized")
2032 def test_gc_tracked(self):
2033 import gc
2034
2035 self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))
2036 self.assertTrue(gc.is_tracked(c_zoneinfo.ZoneInfo))
2037
2038
2039 @dataclasses.dataclass(frozen=True)
2040 class ZoneOffset:
2041 tzname: str
2042 utcoffset: timedelta
2043 dst: timedelta = ZERO
2044
2045
2046 @dataclasses.dataclass(frozen=True)
2047 class ZoneTransition:
2048 transition: datetime
2049 offset_before: ZoneOffset
2050 offset_after: ZoneOffset
2051
2052 @property
2053 def transition_utc(self):
2054 return (self.transition - self.offset_before.utcoffset).replace(
2055 tzinfo=timezone.utc
2056 )
2057
2058 @property
2059 def fold(self):
2060 """Whether this introduces a fold"""
2061 return self.offset_before.utcoffset > self.offset_after.utcoffset
2062
2063 @property
2064 def gap(self):
2065 """Whether this introduces a gap"""
2066 return self.offset_before.utcoffset < self.offset_after.utcoffset
2067
2068 @property
2069 def delta(self):
2070 return self.offset_after.utcoffset - self.offset_before.utcoffset
2071
2072 @property
2073 def anomaly_start(self):
2074 if self.fold:
2075 return self.transition + self.delta
2076 else:
2077 return self.transition
2078
2079 @property
2080 def anomaly_end(self):
2081 if not self.fold:
2082 return self.transition + self.delta
2083 else:
2084 return self.transition
2085
2086
2087 class ZoneInfoData:
2088 def __init__(self, source_json, tzpath, v1=False):
2089 self.tzpath = pathlib.Path(tzpath)
2090 self.keys = []
2091 self.v1 = v1
2092 self._populate_tzpath(source_json)
2093
2094 def path_from_key(self, key):
2095 return self.tzpath / key
2096
2097 def _populate_tzpath(self, source_json):
2098 with open(source_json, "rb") as f:
2099 zoneinfo_dict = json.load(f)
2100
2101 zoneinfo_data = zoneinfo_dict["data"]
2102
2103 for key, value in zoneinfo_data.items():
2104 self.keys.append(key)
2105 raw_data = self._decode_text(value)
2106
2107 if self.v1:
2108 data = self._convert_to_v1(raw_data)
2109 else:
2110 data = raw_data
2111
2112 destination = self.path_from_key(key)
2113 destination.parent.mkdir(exist_ok=True, parents=True)
2114 with open(destination, "wb") as f:
2115 f.write(data)
2116
2117 def _decode_text(self, contents):
2118 raw_data = b"".join(map(str.encode, contents))
2119 decoded = base64.b85decode(raw_data)
2120
2121 return lzma.decompress(decoded)
2122
2123 def _convert_to_v1(self, contents):
2124 assert contents[0:4] == b"TZif", "Invalid TZif data found!"
2125 version = int(contents[4:5])
2126
2127 header_start = 4 + 16
2128 header_end = header_start + 24 # 6l == 24 bytes
2129 assert version >= 2, "Version 1 file found: no conversion necessary"
2130 isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt = struct.unpack(
2131 ">6l", contents[header_start:header_end]
2132 )
2133
2134 file_size = (
2135 timecnt * 5
2136 + typecnt * 6
2137 + charcnt
2138 + leapcnt * 8
2139 + isstdcnt
2140 + isutcnt
2141 )
2142 file_size += header_end
2143 out = b"TZif" + b"\x00" + contents[5:file_size]
2144
2145 assert (
2146 contents[file_size : (file_size + 4)] == b"TZif"
2147 ), "Version 2 file not truncated at Version 2 header"
2148
2149 return out
2150
2151
2152 class ZoneDumpData:
2153 @classmethod
2154 def transition_keys(cls):
2155 return cls._get_zonedump().keys()
2156
2157 @classmethod
2158 def load_transition_examples(cls, key):
2159 return cls._get_zonedump()[key]
2160
2161 @classmethod
2162 def fixed_offset_zones(cls):
2163 if not cls._FIXED_OFFSET_ZONES:
2164 cls._populate_fixed_offsets()
2165
2166 return cls._FIXED_OFFSET_ZONES.items()
2167
2168 @classmethod
2169 def _get_zonedump(cls):
2170 if not cls._ZONEDUMP_DATA:
2171 cls._populate_zonedump_data()
2172 return cls._ZONEDUMP_DATA
2173
2174 @classmethod
2175 def _populate_fixed_offsets(cls):
2176 cls._FIXED_OFFSET_ZONES = {
2177 "UTC": ZoneOffset("UTC", ZERO, ZERO),
2178 }
2179
2180 @classmethod
2181 def _populate_zonedump_data(cls):
2182 def _Africa_Abidjan():
2183 LMT = ZoneOffset("LMT", timedelta(seconds=-968))
2184 GMT = ZoneOffset("GMT", ZERO)
2185
2186 return [
2187 ZoneTransition(datetime(1912, 1, 1), LMT, GMT),
2188 ]
2189
2190 def _Africa_Casablanca():
2191 P00_s = ZoneOffset("+00", ZERO, ZERO)
2192 P01_d = ZoneOffset("+01", ONE_H, ONE_H)
2193 P00_d = ZoneOffset("+00", ZERO, -ONE_H)
2194 P01_s = ZoneOffset("+01", ONE_H, ZERO)
2195
2196 return [
2197 # Morocco sometimes pauses DST during Ramadan
2198 ZoneTransition(datetime(2018, 3, 25, 2), P00_s, P01_d),
2199 ZoneTransition(datetime(2018, 5, 13, 3), P01_d, P00_s),
2200 ZoneTransition(datetime(2018, 6, 17, 2), P00_s, P01_d),
2201 # On October 28th Morocco set standard time to +01,
2202 # with negative DST only during Ramadan
2203 ZoneTransition(datetime(2018, 10, 28, 3), P01_d, P01_s),
2204 ZoneTransition(datetime(2019, 5, 5, 3), P01_s, P00_d),
2205 ZoneTransition(datetime(2019, 6, 9, 2), P00_d, P01_s),
2206 ]
2207
2208 def _America_Los_Angeles():
2209 LMT = ZoneOffset("LMT", timedelta(seconds=-28378), ZERO)
2210 PST = ZoneOffset("PST", timedelta(hours=-8), ZERO)
2211 PDT = ZoneOffset("PDT", timedelta(hours=-7), ONE_H)
2212 PWT = ZoneOffset("PWT", timedelta(hours=-7), ONE_H)
2213 PPT = ZoneOffset("PPT", timedelta(hours=-7), ONE_H)
2214
2215 return [
2216 ZoneTransition(datetime(1883, 11, 18, 12, 7, 2), LMT, PST),
2217 ZoneTransition(datetime(1918, 3, 31, 2), PST, PDT),
2218 ZoneTransition(datetime(1918, 3, 31, 2), PST, PDT),
2219 ZoneTransition(datetime(1918, 10, 27, 2), PDT, PST),
2220 # Transition to Pacific War Time
2221 ZoneTransition(datetime(1942, 2, 9, 2), PST, PWT),
2222 # Transition from Pacific War Time to Pacific Peace Time
2223 ZoneTransition(datetime(1945, 8, 14, 16), PWT, PPT),
2224 ZoneTransition(datetime(1945, 9, 30, 2), PPT, PST),
2225 ZoneTransition(datetime(2015, 3, 8, 2), PST, PDT),
2226 ZoneTransition(datetime(2015, 11, 1, 2), PDT, PST),
2227 # After 2038: Rules continue indefinitely
2228 ZoneTransition(datetime(2450, 3, 13, 2), PST, PDT),
2229 ZoneTransition(datetime(2450, 11, 6, 2), PDT, PST),
2230 ]
2231
2232 def _America_Santiago():
2233 LMT = ZoneOffset("LMT", timedelta(seconds=-16966), ZERO)
2234 SMT = ZoneOffset("SMT", timedelta(seconds=-16966), ZERO)
2235 N05 = ZoneOffset("-05", timedelta(seconds=-18000), ZERO)
2236 N04 = ZoneOffset("-04", timedelta(seconds=-14400), ZERO)
2237 N03 = ZoneOffset("-03", timedelta(seconds=-10800), ONE_H)
2238
2239 return [
2240 ZoneTransition(datetime(1890, 1, 1), LMT, SMT),
2241 ZoneTransition(datetime(1910, 1, 10), SMT, N05),
2242 ZoneTransition(datetime(1916, 7, 1), N05, SMT),
2243 ZoneTransition(datetime(2008, 3, 30), N03, N04),
2244 ZoneTransition(datetime(2008, 10, 12), N04, N03),
2245 ZoneTransition(datetime(2040, 4, 8), N03, N04),
2246 ZoneTransition(datetime(2040, 9, 2), N04, N03),
2247 ]
2248
2249 def _Asia_Tokyo():
2250 JST = ZoneOffset("JST", timedelta(seconds=32400), ZERO)
2251 JDT = ZoneOffset("JDT", timedelta(seconds=36000), ONE_H)
2252
2253 # Japan had DST from 1948 to 1951, and it was unusual in that
2254 # the transition from DST to STD occurred at 25:00, and is
2255 # denominated as such in the time zone database
2256 return [
2257 ZoneTransition(datetime(1948, 5, 2), JST, JDT),
2258 ZoneTransition(datetime(1948, 9, 12, 1), JDT, JST),
2259 ZoneTransition(datetime(1951, 9, 9, 1), JDT, JST),
2260 ]
2261
2262 def _Australia_Sydney():
2263 LMT = ZoneOffset("LMT", timedelta(seconds=36292), ZERO)
2264 AEST = ZoneOffset("AEST", timedelta(seconds=36000), ZERO)
2265 AEDT = ZoneOffset("AEDT", timedelta(seconds=39600), ONE_H)
2266
2267 return [
2268 ZoneTransition(datetime(1895, 2, 1), LMT, AEST),
2269 ZoneTransition(datetime(1917, 1, 1, 0, 1), AEST, AEDT),
2270 ZoneTransition(datetime(1917, 3, 25, 2), AEDT, AEST),
2271 ZoneTransition(datetime(2012, 4, 1, 3), AEDT, AEST),
2272 ZoneTransition(datetime(2012, 10, 7, 2), AEST, AEDT),
2273 ZoneTransition(datetime(2040, 4, 1, 3), AEDT, AEST),
2274 ZoneTransition(datetime(2040, 10, 7, 2), AEST, AEDT),
2275 ]
2276
2277 def _Europe_Dublin():
2278 LMT = ZoneOffset("LMT", timedelta(seconds=-1500), ZERO)
2279 DMT = ZoneOffset("DMT", timedelta(seconds=-1521), ZERO)
2280 IST_0 = ZoneOffset("IST", timedelta(seconds=2079), ONE_H)
2281 GMT_0 = ZoneOffset("GMT", ZERO, ZERO)
2282 BST = ZoneOffset("BST", ONE_H, ONE_H)
2283 GMT_1 = ZoneOffset("GMT", ZERO, -ONE_H)
2284 IST_1 = ZoneOffset("IST", ONE_H, ZERO)
2285
2286 return [
2287 ZoneTransition(datetime(1880, 8, 2, 0), LMT, DMT),
2288 ZoneTransition(datetime(1916, 5, 21, 2), DMT, IST_0),
2289 ZoneTransition(datetime(1916, 10, 1, 3), IST_0, GMT_0),
2290 ZoneTransition(datetime(1917, 4, 8, 2), GMT_0, BST),
2291 ZoneTransition(datetime(2016, 3, 27, 1), GMT_1, IST_1),
2292 ZoneTransition(datetime(2016, 10, 30, 2), IST_1, GMT_1),
2293 ZoneTransition(datetime(2487, 3, 30, 1), GMT_1, IST_1),
2294 ZoneTransition(datetime(2487, 10, 26, 2), IST_1, GMT_1),
2295 ]
2296
2297 def _Europe_Lisbon():
2298 WET = ZoneOffset("WET", ZERO, ZERO)
2299 WEST = ZoneOffset("WEST", ONE_H, ONE_H)
2300 CET = ZoneOffset("CET", ONE_H, ZERO)
2301 CEST = ZoneOffset("CEST", timedelta(seconds=7200), ONE_H)
2302
2303 return [
2304 ZoneTransition(datetime(1992, 3, 29, 1), WET, WEST),
2305 ZoneTransition(datetime(1992, 9, 27, 2), WEST, CET),
2306 ZoneTransition(datetime(1993, 3, 28, 2), CET, CEST),
2307 ZoneTransition(datetime(1993, 9, 26, 3), CEST, CET),
2308 ZoneTransition(datetime(1996, 3, 31, 2), CET, WEST),
2309 ZoneTransition(datetime(1996, 10, 27, 2), WEST, WET),
2310 ]
2311
2312 def _Europe_London():
2313 LMT = ZoneOffset("LMT", timedelta(seconds=-75), ZERO)
2314 GMT = ZoneOffset("GMT", ZERO, ZERO)
2315 BST = ZoneOffset("BST", ONE_H, ONE_H)
2316
2317 return [
2318 ZoneTransition(datetime(1847, 12, 1), LMT, GMT),
2319 ZoneTransition(datetime(2005, 3, 27, 1), GMT, BST),
2320 ZoneTransition(datetime(2005, 10, 30, 2), BST, GMT),
2321 ZoneTransition(datetime(2043, 3, 29, 1), GMT, BST),
2322 ZoneTransition(datetime(2043, 10, 25, 2), BST, GMT),
2323 ]
2324
2325 def _Pacific_Kiritimati():
2326 LMT = ZoneOffset("LMT", timedelta(seconds=-37760), ZERO)
2327 N1040 = ZoneOffset("-1040", timedelta(seconds=-38400), ZERO)
2328 N10 = ZoneOffset("-10", timedelta(seconds=-36000), ZERO)
2329 P14 = ZoneOffset("+14", timedelta(seconds=50400), ZERO)
2330
2331 # This is literally every transition in Christmas Island history
2332 return [
2333 ZoneTransition(datetime(1901, 1, 1), LMT, N1040),
2334 ZoneTransition(datetime(1979, 10, 1), N1040, N10),
2335 # They skipped December 31, 1994
2336 ZoneTransition(datetime(1994, 12, 31), N10, P14),
2337 ]
2338
2339 cls._ZONEDUMP_DATA = {
2340 "Africa/Abidjan": _Africa_Abidjan(),
2341 "Africa/Casablanca": _Africa_Casablanca(),
2342 "America/Los_Angeles": _America_Los_Angeles(),
2343 "America/Santiago": _America_Santiago(),
2344 "Australia/Sydney": _Australia_Sydney(),
2345 "Asia/Tokyo": _Asia_Tokyo(),
2346 "Europe/Dublin": _Europe_Dublin(),
2347 "Europe/Lisbon": _Europe_Lisbon(),
2348 "Europe/London": _Europe_London(),
2349 "Pacific/Kiritimati": _Pacific_Kiritimati(),
2350 }
2351
2352 _ZONEDUMP_DATA = None
2353 _FIXED_OFFSET_ZONES = None
2354
2355
2356 if __name__ == '__main__':
2357 unittest.main()