Debian Codegraph @

lib-python/3/test/test_zoneinfo/test_zoneinfo.py

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