/
test_zoneinfo.py
2113 lines (1674 loc) · 72.4 KB
/
test_zoneinfo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import contextlib
import dataclasses
import io
import json
import lzma
import os
import pathlib
import pickle
import re
import shutil
import struct
import tempfile
import unittest
from datetime import date, datetime, time, timedelta, timezone
from . import _support as test_support
from ._support import IS_PYPY, OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase
try:
from functools import cached_property
except ImportError:
cached_property = property
try:
import importlib.metadata as importlib_metadata
except ImportError:
import importlib_metadata
py_zoneinfo, c_zoneinfo = test_support.get_modules()
try:
importlib_metadata.metadata("tzdata")
HAS_TZDATA_PKG = True
except importlib_metadata.PackageNotFoundError:
HAS_TZDATA_PKG = False
ZONEINFO_DATA = None
ZONEINFO_DATA_V1 = None
TEMP_DIR = None
DATA_DIR = pathlib.Path(__file__).parent / "data"
ZONEINFO_JSON = DATA_DIR / "zoneinfo_data.json"
# Useful constants
ZERO = timedelta(0)
ONE_H = timedelta(hours=1)
def setUpModule():
global TEMP_DIR
global ZONEINFO_DATA
global ZONEINFO_DATA_V1
TEMP_DIR = pathlib.Path(tempfile.mkdtemp(prefix="zoneinfo"))
ZONEINFO_DATA = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v2")
ZONEINFO_DATA_V1 = ZoneInfoData(ZONEINFO_JSON, TEMP_DIR / "v1", v1=True)
def tearDownModule():
shutil.rmtree(TEMP_DIR)
class TzPathUserMixin:
"""
Adds a setUp() and tearDown() to make TZPATH manipulations thread-safe.
Any tests that require manipulation of the TZPATH global are necessarily
thread unsafe, so we will acquire a lock and reset the TZPATH variable
to the default state before each test and release the lock after the test
is through.
"""
@property
def tzpath(self): # pragma: nocover
return None
@property
def block_tzdata(self):
return True
def setUp(self):
with contextlib.ExitStack() as stack:
stack.enter_context(
self.tzpath_context(
self.tzpath,
block_tzdata=self.block_tzdata,
lock=TZPATH_TEST_LOCK,
)
)
self.addCleanup(stack.pop_all().close)
super().setUp()
class DatetimeSubclassMixin:
"""
Replaces all ZoneTransition transition dates with a datetime subclass.
"""
class DatetimeSubclass(datetime):
@classmethod
def from_datetime(cls, dt):
return cls(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
tzinfo=dt.tzinfo,
fold=dt.fold,
)
def load_transition_examples(self, key):
transition_examples = super().load_transition_examples(key)
for zt in transition_examples:
dt = zt.transition
new_dt = self.DatetimeSubclass.from_datetime(dt)
new_zt = dataclasses.replace(zt, transition=new_dt)
yield new_zt
class ZoneInfoTest(TzPathUserMixin, ZoneInfoTestBase):
module = py_zoneinfo
class_name = "ZoneInfo"
def setUp(self):
super().setUp()
# This is necessary because various subclasses pull from different
# data sources (e.g. tzdata, V1 files, etc).
self.klass.clear_cache()
@property
def zoneinfo_data(self):
return ZONEINFO_DATA
@property
def tzpath(self):
return [self.zoneinfo_data.tzpath]
def zone_from_key(self, key):
return self.klass(key)
def zones(self):
return ZoneDumpData.transition_keys()
def fixed_offset_zones(self):
return ZoneDumpData.fixed_offset_zones()
def load_transition_examples(self, key):
return ZoneDumpData.load_transition_examples(key)
def test_str(self):
# Zones constructed with a key must have str(zone) == key
for key in self.zones():
with self.subTest(key):
zi = self.zone_from_key(key)
self.assertEqual(str(zi), key)
# Zones with no key constructed should have str(zone) == repr(zone)
file_key = self.zoneinfo_data.keys[0]
file_path = self.zoneinfo_data.path_from_key(file_key)
with open(file_path, "rb") as f:
with self.subTest(test_name="Repr test", path=file_path):
zi_ff = self.klass.from_file(f)
self.assertEqual(str(zi_ff), repr(zi_ff))
def test_repr(self):
# The repr is not guaranteed, but I think we can insist that it at
# least contain the name of the class.
key = next(iter(self.zones()))
zi = self.klass(key)
class_name = self.class_name
with self.subTest(name="from key"):
self.assertRegex(repr(zi), class_name)
file_key = self.zoneinfo_data.keys[0]
file_path = self.zoneinfo_data.path_from_key(file_key)
with open(file_path, "rb") as f:
zi_ff = self.klass.from_file(f, key=file_key)
with self.subTest(name="from file with key"):
self.assertRegex(repr(zi_ff), class_name)
with open(file_path, "rb") as f:
zi_ff_nk = self.klass.from_file(f)
with self.subTest(name="from file without key"):
self.assertRegex(repr(zi_ff_nk), class_name)
def test_key_attribute(self):
key = next(iter(self.zones()))
def from_file_nokey(key):
with open(self.zoneinfo_data.path_from_key(key), "rb") as f:
return self.klass.from_file(f)
constructors = (
("Primary constructor", self.klass, key),
("no_cache", self.klass.no_cache, key),
("from_file", from_file_nokey, None),
)
for msg, constructor, expected in constructors:
zi = constructor(key)
# Ensure that the key attribute is set to the input to ``key``
with self.subTest(msg):
self.assertEqual(zi.key, expected)
# Ensure that the key attribute is read-only
with self.subTest(f"{msg}: readonly"):
with self.assertRaises(AttributeError):
zi.key = "Some/Value"
def test_bad_keys(self):
bad_keys = [
"Eurasia/Badzone", # Plausible but does not exist
"BZQ",
"America.Los_Angeles",
"🇨🇦", # Non-ascii
"America/New\ud800York", # Contains surrogate character
]
for bad_key in bad_keys:
with self.assertRaises(self.module.ZoneInfoNotFoundError):
self.klass(bad_key)
def test_bad_keys_paths(self):
bad_keys = [
"/America/Los_Angeles", # Absolute path
"America/Los_Angeles/", # Trailing slash - not normalized
"../zoneinfo/America/Los_Angeles", # Traverses above TZPATH
"America/../America/Los_Angeles", # Not normalized
"America/./Los_Angeles",
]
for bad_key in bad_keys:
with self.assertRaises(ValueError):
self.klass(bad_key)
def test_bad_zones(self):
bad_zones = [
b"", # Empty file
b"AAAA3" + b" " * 15, # Bad magic
]
for bad_zone in bad_zones:
fobj = io.BytesIO(bad_zone)
with self.assertRaises(ValueError):
self.klass.from_file(fobj)
def test_fromutc_errors(self):
key = next(iter(self.zones()))
zone = self.zone_from_key(key)
bad_values = [
(datetime(2019, 1, 1, tzinfo=timezone.utc), ValueError),
(datetime(2019, 1, 1), ValueError),
(date(2019, 1, 1), TypeError),
(time(0), TypeError),
(0, TypeError),
("2019-01-01", TypeError),
]
for val, exc_type in bad_values:
with self.subTest(val=val):
with self.assertRaises(exc_type):
zone.fromutc(val)
def test_utc(self):
zi = self.klass("UTC")
dt = datetime(2020, 1, 1, tzinfo=zi)
self.assertEqual(dt.utcoffset(), ZERO)
self.assertEqual(dt.dst(), ZERO)
self.assertEqual(dt.tzname(), "UTC")
def test_unambiguous(self):
test_cases = []
for key in self.zones():
for zone_transition in self.load_transition_examples(key):
test_cases.append(
(
key,
zone_transition.transition - timedelta(days=2),
zone_transition.offset_before,
)
)
test_cases.append(
(
key,
zone_transition.transition + timedelta(days=2),
zone_transition.offset_after,
)
)
for key, dt, offset in test_cases:
with self.subTest(key=key, dt=dt, offset=offset):
tzi = self.zone_from_key(key)
dt = dt.replace(tzinfo=tzi)
self.assertEqual(dt.tzname(), offset.tzname, dt)
self.assertEqual(dt.utcoffset(), offset.utcoffset, dt)
self.assertEqual(dt.dst(), offset.dst, dt)
def test_folds_and_gaps(self):
test_cases = []
for key in self.zones():
tests = {"folds": [], "gaps": []}
for zt in self.load_transition_examples(key):
if zt.fold:
test_group = tests["folds"]
elif zt.gap:
test_group = tests["gaps"]
else:
# Assign a random variable here to disable the peephole
# optimizer so that coverage can see this line.
# See bpo-2506 for more information.
no_peephole_opt = None # pylint: disable=unused-variable
continue
# Cases are of the form key, dt, fold, offset
dt = zt.anomaly_start - timedelta(seconds=1)
test_group.append((dt, 0, zt.offset_before))
test_group.append((dt, 1, zt.offset_before))
dt = zt.anomaly_start
test_group.append((dt, 0, zt.offset_before))
test_group.append((dt, 1, zt.offset_after))
dt = zt.anomaly_start + timedelta(seconds=1)
test_group.append((dt, 0, zt.offset_before))
test_group.append((dt, 1, zt.offset_after))
dt = zt.anomaly_end - timedelta(seconds=1)
test_group.append((dt, 0, zt.offset_before))
test_group.append((dt, 1, zt.offset_after))
dt = zt.anomaly_end
test_group.append((dt, 0, zt.offset_after))
test_group.append((dt, 1, zt.offset_after))
dt = zt.anomaly_end + timedelta(seconds=1)
test_group.append((dt, 0, zt.offset_after))
test_group.append((dt, 1, zt.offset_after))
for grp, test_group in tests.items():
test_cases.append(((key, grp), test_group))
for (key, grp), tests in test_cases:
with self.subTest(key=key, grp=grp):
tzi = self.zone_from_key(key)
for dt, fold, offset in tests:
dt = dt.replace(fold=fold, tzinfo=tzi)
self.assertEqual(dt.tzname(), offset.tzname, dt)
self.assertEqual(dt.utcoffset(), offset.utcoffset, dt)
self.assertEqual(dt.dst(), offset.dst, dt)
def test_folds_from_utc(self):
for key in self.zones():
zi = self.zone_from_key(key)
with self.subTest(key=key):
for zt in self.load_transition_examples(key):
if not zt.fold:
continue
dt_utc = zt.transition_utc
dt_before_utc = dt_utc - timedelta(seconds=1)
dt_after_utc = dt_utc + timedelta(seconds=1)
dt_before = dt_before_utc.astimezone(zi)
self.assertEqual(dt_before.fold, 0, (dt_before, dt_utc))
dt_after = dt_after_utc.astimezone(zi)
self.assertEqual(dt_after.fold, 1, (dt_after, dt_utc))
def test_time_variable_offset(self):
# self.zones() only ever returns variable-offset zones
for key in self.zones():
zi = self.zone_from_key(key)
t = time(11, 15, 1, 34471, tzinfo=zi)
with self.subTest(key=key):
self.assertIs(t.tzname(), None)
self.assertIs(t.utcoffset(), None)
self.assertIs(t.dst(), None)
def test_time_fixed_offset(self):
for key, offset in self.fixed_offset_zones():
zi = self.zone_from_key(key)
t = time(11, 15, 1, 34471, tzinfo=zi)
with self.subTest(key=key):
self.assertEqual(t.tzname(), offset.tzname)
self.assertEqual(t.utcoffset(), offset.utcoffset)
self.assertEqual(t.dst(), offset.dst)
class CZoneInfoTest(ZoneInfoTest):
module = c_zoneinfo
def test_fold_mutate(self):
"""Test that fold isn't mutated when no change is necessary.
The underlying C API is capable of mutating datetime objects, and
may rely on the fact that addition of a datetime object returns a
new datetime; this test ensures that the input datetime to fromutc
is not mutated.
"""
def to_subclass(dt):
class SameAddSubclass(type(dt)):
def __add__(self, other):
if other == timedelta(0):
return self
return super().__add__(other) # pragma: nocover
return SameAddSubclass(
dt.year,
dt.month,
dt.day,
dt.hour,
dt.minute,
dt.second,
dt.microsecond,
fold=dt.fold,
tzinfo=dt.tzinfo,
)
subclass = [False, True]
key = "Europe/London"
zi = self.zone_from_key(key)
for zt in self.load_transition_examples(key):
if zt.fold and zt.offset_after.utcoffset == ZERO:
example = zt.transition_utc.replace(tzinfo=zi)
break
for subclass in [False, True]:
if subclass:
dt = to_subclass(example)
else:
dt = example
with self.subTest(subclass=subclass):
dt_fromutc = zi.fromutc(dt)
self.assertEqual(dt_fromutc.fold, 1)
self.assertEqual(dt.fold, 0)
class ZoneInfoDatetimeSubclassTest(DatetimeSubclassMixin, ZoneInfoTest):
pass
class CZoneInfoDatetimeSubclassTest(DatetimeSubclassMixin, CZoneInfoTest):
pass
class ZoneInfoTestSubclass(ZoneInfoTest):
@classmethod
def setUpClass(cls):
super().setUpClass()
class ZISubclass(cls.klass):
pass
cls.class_name = "ZISubclass"
cls.parent_klass = cls.klass
cls.klass = ZISubclass
def test_subclass_own_cache(self):
base_obj = self.parent_klass("Europe/London")
sub_obj = self.klass("Europe/London")
self.assertIsNot(base_obj, sub_obj)
self.assertIsInstance(base_obj, self.parent_klass)
self.assertIsInstance(sub_obj, self.klass)
class CZoneInfoTestSubclass(ZoneInfoTest):
module = c_zoneinfo
class ZoneInfoV1Test(ZoneInfoTest):
@property
def zoneinfo_data(self):
return ZONEINFO_DATA_V1
def load_transition_examples(self, key):
# We will discard zdump examples outside the range epoch +/- 2**31,
# because they are not well-supported in Version 1 files.
epoch = datetime(1970, 1, 1)
max_offset_32 = timedelta(seconds=2 ** 31)
min_dt = epoch - max_offset_32
max_dt = epoch + max_offset_32
for zt in ZoneDumpData.load_transition_examples(key):
if min_dt <= zt.transition <= max_dt:
yield zt
class CZoneInfoV1Test(ZoneInfoV1Test):
module = c_zoneinfo
@unittest.skipIf(
not HAS_TZDATA_PKG, "Skipping tzdata-specific tests: tzdata not installed"
)
class TZDataTests(ZoneInfoTest):
"""
Runs all the ZoneInfoTest tests, but against the tzdata package
NOTE: The ZoneDumpData has frozen test data, but tzdata will update, so
some of the tests (particularly those related to the far future) may break
in the event that the time zone policies in the relevant time zones change.
"""
@property
def tzpath(self):
return []
@property
def block_tzdata(self):
return False
def zone_from_key(self, key):
return self.klass(key=key)
@unittest.skipIf(
not HAS_TZDATA_PKG, "Skipping tzdata-specific tests: tzdata not installed"
)
class CTZDataTests(TZDataTests):
module = c_zoneinfo
class WeirdZoneTest(ZoneInfoTestBase):
module = py_zoneinfo
def test_one_transition(self):
LMT = ZoneOffset("LMT", -timedelta(hours=6, minutes=31, seconds=2))
STD = ZoneOffset("STD", -timedelta(hours=6))
transitions = [
ZoneTransition(datetime(1883, 6, 9, 14), LMT, STD),
]
after = "STD6"
zf = self.construct_zone(transitions, after)
zi = self.klass.from_file(zf)
dt0 = datetime(1883, 6, 9, 1, tzinfo=zi)
dt1 = datetime(1883, 6, 10, 1, tzinfo=zi)
for dt, offset in [(dt0, LMT), (dt1, STD)]:
with self.subTest(name="local", dt=dt):
self.assertEqual(dt.tzname(), offset.tzname)
self.assertEqual(dt.utcoffset(), offset.utcoffset)
self.assertEqual(dt.dst(), offset.dst)
dts = [
(
datetime(1883, 6, 9, 1, tzinfo=zi),
datetime(1883, 6, 9, 7, 31, 2, tzinfo=timezone.utc),
),
(
datetime(2010, 4, 1, 12, tzinfo=zi),
datetime(2010, 4, 1, 18, tzinfo=timezone.utc),
),
]
for dt_local, dt_utc in dts:
with self.subTest(name="fromutc", dt=dt_local):
dt_actual = dt_utc.astimezone(zi)
self.assertEqual(dt_actual, dt_local)
dt_utc_actual = dt_local.astimezone(timezone.utc)
self.assertEqual(dt_utc_actual, dt_utc)
def test_one_zone_dst(self):
DST = ZoneOffset("DST", ONE_H, ONE_H)
transitions = [
ZoneTransition(datetime(1970, 1, 1), DST, DST),
]
after = "STD0DST-1,0/0,J365/25"
zf = self.construct_zone(transitions, after)
zi = self.klass.from_file(zf)
dts = [
datetime(1900, 3, 1),
datetime(1965, 9, 12),
datetime(1970, 1, 1),
datetime(2010, 11, 3),
datetime(2040, 1, 1),
]
for dt in dts:
dt = dt.replace(tzinfo=zi)
with self.subTest(dt=dt):
self.assertEqual(dt.tzname(), DST.tzname)
self.assertEqual(dt.utcoffset(), DST.utcoffset)
self.assertEqual(dt.dst(), DST.dst)
def test_no_tz_str(self):
STD = ZoneOffset("STD", ONE_H, ZERO)
DST = ZoneOffset("DST", 2 * ONE_H, ONE_H)
transitions = []
for year in range(1996, 2000):
transitions.append(
ZoneTransition(datetime(year, 3, 1, 2), STD, DST)
)
transitions.append(
ZoneTransition(datetime(year, 11, 1, 2), DST, STD)
)
after = ""
zf = self.construct_zone(transitions, after)
# According to RFC 8536, local times after the last transition time
# with an empty TZ string are unspecified. We will go with "hold the
# last transition", but the most we should promise is "doesn't crash."
zi = self.klass.from_file(zf)
cases = [
(datetime(1995, 1, 1), STD),
(datetime(1996, 4, 1), DST),
(datetime(1996, 11, 2), STD),
(datetime(2001, 1, 1), STD),
]
for dt, offset in cases:
dt = dt.replace(tzinfo=zi)
with self.subTest(dt=dt):
self.assertEqual(dt.tzname(), offset.tzname)
self.assertEqual(dt.utcoffset(), offset.utcoffset)
self.assertEqual(dt.dst(), offset.dst)
# Test that offsets return None when using a datetime.time
t = time(0, tzinfo=zi)
with self.subTest("Testing datetime.time"):
self.assertIs(t.tzname(), None)
self.assertIs(t.utcoffset(), None)
self.assertIs(t.dst(), None)
def test_tz_before_only(self):
# From RFC 8536 Section 3.2:
#
# If there are no transitions, local time for all timestamps is
# specified by the TZ string in the footer if present and nonempty;
# otherwise, it is specified by time type 0.
offsets = [
ZoneOffset("STD", ZERO, ZERO),
ZoneOffset("DST", ONE_H, ONE_H),
]
for offset in offsets:
# Phantom transition to set time type 0.
transitions = [
ZoneTransition(None, offset, offset),
]
after = ""
zf = self.construct_zone(transitions, after)
zi = self.klass.from_file(zf)
dts = [
datetime(1900, 1, 1),
datetime(1970, 1, 1),
datetime(2000, 1, 1),
]
for dt in dts:
dt = dt.replace(tzinfo=zi)
with self.subTest(offset=offset, dt=dt):
self.assertEqual(dt.tzname(), offset.tzname)
self.assertEqual(dt.utcoffset(), offset.utcoffset)
self.assertEqual(dt.dst(), offset.dst)
def test_empty_zone(self):
zf = self.construct_zone([], "")
with self.assertRaises(ValueError):
self.klass.from_file(zf)
def test_zone_very_large_timestamp(self):
"""Test when a transition is in the far past or future.
Particularly, this is a concern if something:
1. Attempts to call ``datetime.timestamp`` for a datetime outside
of ``[datetime.min, datetime.max]``.
2. Attempts to construct a timedelta outside of
``[timedelta.min, timedelta.max]``.
This actually occurs "in the wild", as some time zones on Ubuntu (at
least as of 2020) have an initial transition added at ``-2**58``.
"""
LMT = ZoneOffset("LMT", timedelta(seconds=-968))
GMT = ZoneOffset("GMT", ZERO)
transitions = [
(-(1 << 62), LMT, LMT),
ZoneTransition(datetime(1912, 1, 1), LMT, GMT),
((1 << 62), GMT, GMT),
]
after = "GMT0"
zf = self.construct_zone(transitions, after)
zi = self.klass.from_file(zf, key="Africa/Abidjan")
offset_cases = [
(datetime.min, LMT),
(datetime.max, GMT),
(datetime(1911, 12, 31), LMT),
(datetime(1912, 1, 2), GMT),
]
for dt_naive, offset in offset_cases:
dt = dt_naive.replace(tzinfo=zi)
with self.subTest(name="offset", dt=dt, offset=offset):
self.assertEqual(dt.tzname(), offset.tzname)
self.assertEqual(dt.utcoffset(), offset.utcoffset)
self.assertEqual(dt.dst(), offset.dst)
utc_cases = [
(datetime.min, datetime.min + timedelta(seconds=968)),
(datetime(1898, 12, 31, 23, 43, 52), datetime(1899, 1, 1)),
(
datetime(1911, 12, 31, 23, 59, 59, 999999),
datetime(1912, 1, 1, 0, 16, 7, 999999),
),
(datetime(1912, 1, 1, 0, 16, 8), datetime(1912, 1, 1, 0, 16, 8)),
(datetime(1970, 1, 1), datetime(1970, 1, 1)),
(datetime.max, datetime.max),
]
for naive_dt, naive_dt_utc in utc_cases:
dt = naive_dt.replace(tzinfo=zi)
dt_utc = naive_dt_utc.replace(tzinfo=timezone.utc)
self.assertEqual(dt_utc.astimezone(zi), dt)
self.assertEqual(dt, dt_utc)
def test_fixed_offset_phantom_transition(self):
UTC = ZoneOffset("UTC", ZERO, ZERO)
transitions = [ZoneTransition(datetime(1970, 1, 1), UTC, UTC)]
after = "UTC0"
zf = self.construct_zone(transitions, after)
zi = self.klass.from_file(zf, key="UTC")
dt = datetime(2020, 1, 1, tzinfo=zi)
with self.subTest("datetime.datetime"):
self.assertEqual(dt.tzname(), UTC.tzname)
self.assertEqual(dt.utcoffset(), UTC.utcoffset)
self.assertEqual(dt.dst(), UTC.dst)
t = time(0, tzinfo=zi)
with self.subTest("datetime.time"):
self.assertEqual(t.tzname(), UTC.tzname)
self.assertEqual(t.utcoffset(), UTC.utcoffset)
self.assertEqual(t.dst(), UTC.dst)
def construct_zone(self, transitions, after=None, version=3):
# These are not used for anything, so we're not going to include
# them for now.
isutc = []
isstd = []
leap_seconds = []
offset_lists = [[], []]
trans_times_lists = [[], []]
trans_idx_lists = [[], []]
v1_range = (-(2 ** 31), 2 ** 31)
v2_range = (-(2 ** 63), 2 ** 63)
ranges = [v1_range, v2_range]
def zt_as_tuple(zt):
# zt may be a tuple (timestamp, offset_before, offset_after) or
# a ZoneTransition object — this is to allow the timestamp to be
# values that are outside the valid range for datetimes but still
# valid 64-bit timestamps.
if isinstance(zt, tuple):
return zt
if zt.transition:
trans_time = int(zt.transition_utc.timestamp())
else:
trans_time = None
return (trans_time, zt.offset_before, zt.offset_after)
transitions = sorted(map(zt_as_tuple, transitions), key=lambda x: x[0])
for zt in transitions:
trans_time, offset_before, offset_after = zt
for v, (dt_min, dt_max) in enumerate(ranges):
offsets = offset_lists[v]
trans_times = trans_times_lists[v]
trans_idx = trans_idx_lists[v]
if trans_time is not None and not (
dt_min <= trans_time <= dt_max
):
continue
if offset_before not in offsets:
offsets.append(offset_before)
if offset_after not in offsets:
offsets.append(offset_after)
if trans_time is not None:
trans_times.append(trans_time)
trans_idx.append(offsets.index(offset_after))
isutcnt = len(isutc)
isstdcnt = len(isstd)
leapcnt = len(leap_seconds)
zonefile = io.BytesIO()
time_types = ("l", "q")
for v in range(min((version, 2))):
offsets = offset_lists[v]
trans_times = trans_times_lists[v]
trans_idx = trans_idx_lists[v]
time_type = time_types[v]
# Translate the offsets into something closer to the C values
abbrstr = bytearray()
ttinfos = []
for offset in offsets:
utcoff = int(offset.utcoffset.total_seconds())
isdst = bool(offset.dst)
abbrind = len(abbrstr)
ttinfos.append((utcoff, isdst, abbrind))
abbrstr += offset.tzname.encode("ascii") + b"\x00"
abbrstr = bytes(abbrstr)
typecnt = len(offsets)
timecnt = len(trans_times)
charcnt = len(abbrstr)
# Write the header
zonefile.write(b"TZif")
zonefile.write(b"%d" % version)
zonefile.write(b" " * 15)
zonefile.write(
struct.pack(
">6l", isutcnt, isstdcnt, leapcnt, timecnt, typecnt, charcnt
)
)
# Now the transition data
zonefile.write(struct.pack(f">{timecnt}{time_type}", *trans_times))
zonefile.write(struct.pack(f">{timecnt}B", *trans_idx))
for ttinfo in ttinfos:
zonefile.write(struct.pack(">lbb", *ttinfo))
zonefile.write(bytes(abbrstr))
# Now the metadata and leap seconds
zonefile.write(struct.pack(f"{isutcnt}b", *isutc))
zonefile.write(struct.pack(f"{isstdcnt}b", *isstd))
zonefile.write(struct.pack(f">{leapcnt}l", *leap_seconds))
# Finally we write the TZ string if we're writing a Version 2+ file
if v > 0:
zonefile.write(b"\x0A")
zonefile.write(after.encode("ascii"))
zonefile.write(b"\x0A")
zonefile.seek(0)
return zonefile
class CWeirdZoneTest(WeirdZoneTest):
module = c_zoneinfo
class TZStrTest(ZoneInfoTestBase):
module = py_zoneinfo
NORMAL = 0
FOLD = 1
GAP = 2
@classmethod
def setUpClass(cls):
super().setUpClass()
cls._populate_test_cases()
cls.populate_tzstr_header()
@classmethod
def populate_tzstr_header(cls):
out = bytearray()
# The TZif format always starts with a Version 1 file followed by
# the Version 2+ file. In this case, we have no transitions, just
# the tzstr in the footer, so up to the footer, the files are
# identical and we can just write the same file twice in a row.
for _ in range(2):
out += b"TZif" # Magic value
out += b"3" # Version
out += b" " * 15 # Reserved
# We will not write any of the manual transition parts
out += struct.pack(">6l", 0, 0, 0, 0, 0, 0)
cls._tzif_header = bytes(out)
def zone_from_tzstr(self, tzstr):
"""Creates a zoneinfo file following a POSIX rule."""
zonefile = io.BytesIO(self._tzif_header)
zonefile.seek(0, 2)
# Write the footer
zonefile.write(b"\x0A")
zonefile.write(tzstr.encode("ascii"))
zonefile.write(b"\x0A")
zonefile.seek(0)
return self.klass.from_file(zonefile, key=tzstr)
def test_tzstr_localized(self):
for tzstr, cases in self.test_cases.items():
with self.subTest(tzstr=tzstr):
zi = self.zone_from_tzstr(tzstr)
for dt_naive, offset, _ in cases:
dt = dt_naive.replace(tzinfo=zi)
with self.subTest(tzstr=tzstr, dt=dt, offset=offset):
self.assertEqual(dt.tzname(), offset.tzname)
self.assertEqual(dt.utcoffset(), offset.utcoffset)
self.assertEqual(dt.dst(), offset.dst)
def test_tzstr_from_utc(self):
for tzstr, cases in self.test_cases.items():
with self.subTest(tzstr=tzstr):
zi = self.zone_from_tzstr(tzstr)
for dt_naive, offset, dt_type in cases:
if dt_type == self.GAP:
continue # Cannot create a gap from UTC
dt_utc = (dt_naive - offset.utcoffset).replace(
tzinfo=timezone.utc
)
# Check that we can go UTC -> Our zone
dt_act = dt_utc.astimezone(zi)
dt_exp = dt_naive.replace(tzinfo=zi)
self.assertEqual(dt_act, dt_exp)
if dt_type == self.FOLD:
self.assertEqual(dt_act.fold, dt_naive.fold, dt_naive)
else:
self.assertEqual(dt_act.fold, 0)
# Now check that we can go our zone -> UTC
dt_act = dt_exp.astimezone(timezone.utc)
self.assertEqual(dt_act, dt_utc)
def test_invalid_tzstr(self):
invalid_tzstrs = [
"PST8PDT", # DST but no transition specified
"+11", # Unquoted alphanumeric