forked from pydantic/pydantic-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_tzinfo.py
235 lines (178 loc) · 7.66 KB
/
test_tzinfo.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
import copy
import functools
import pickle
import sys
import unittest
from datetime import datetime, timedelta, timezone, tzinfo
from pydantic_core import SchemaValidator, TzInfo, core_schema
if sys.version_info >= (3, 9):
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
class _ALWAYS_EQ:
"""
Object that is equal to anything.
"""
def __eq__(self, other):
return True
def __ne__(self, other):
return False
ALWAYS_EQ = _ALWAYS_EQ()
@functools.total_ordering
class _LARGEST:
"""
Object that is greater than anything (except itself).
"""
def __eq__(self, other):
return isinstance(other, _LARGEST)
def __lt__(self, other):
return False
LARGEST = _LARGEST()
@functools.total_ordering
class _SMALLEST:
"""
Object that is less than anything (except itself).
"""
def __eq__(self, other):
return isinstance(other, _SMALLEST)
def __gt__(self, other):
return False
SMALLEST = _SMALLEST()
pickle_choices = [(pickle, pickle, proto) for proto in range(pickle.HIGHEST_PROTOCOL + 1)]
HOUR = timedelta(hours=1).total_seconds()
ZERO = timedelta(0).total_seconds()
def first_sunday_on_or_after(dt):
days_to_go = 6 - dt.weekday()
if days_to_go:
dt += timedelta(days_to_go)
return dt
DSTSTART = datetime(1, 4, 1, 2)
DSTEND = datetime(1, 10, 25, 1)
class TestTzInfo(unittest.TestCase):
"""Adapted from CPython `timezone` tests
Original tests are located here https://github.com/python/cpython/blob/a0bb4a39d1ca10e4a75f50a9fbe90cc9db28d29e/Lib/test/datetimetester.py#L256
"""
def setUp(self):
self.ACDT = TzInfo(timedelta(hours=9.5).total_seconds())
self.EST = TzInfo(-timedelta(hours=5).total_seconds())
self.UTC = TzInfo(timedelta(0).total_seconds())
self.DT = datetime(2010, 1, 1)
def test_str(self):
for tz in [self.ACDT, self.EST]:
self.assertEqual(str(tz), tz.tzname(None))
def test_constructor(self):
for subminute in [timedelta(microseconds=1), timedelta(seconds=1)]:
tz = TzInfo(subminute.total_seconds())
self.assertNotEqual(tz.utcoffset(None) % timedelta(minutes=1), 0)
# invalid offsets
for invalid in [timedelta(1, 1), timedelta(1)]:
self.assertRaises(ValueError, TzInfo, invalid.total_seconds())
self.assertRaises(ValueError, TzInfo, -invalid.total_seconds())
with self.assertRaises(TypeError):
TzInfo(None)
with self.assertRaises(TypeError):
TzInfo(timedelta(seconds=42))
with self.assertRaises(TypeError):
TzInfo(ZERO, None)
with self.assertRaises(TypeError):
TzInfo(ZERO, 42)
with self.assertRaises(TypeError):
TzInfo(ZERO, 'ABC', 'extra')
def test_inheritance(self):
self.assertIsInstance(self.EST, tzinfo)
def test_utcoffset(self):
dummy = self.DT
for h in [0, 1.5, 12]:
offset = h * HOUR
self.assertEqual(timedelta(seconds=offset), TzInfo(offset).utcoffset(dummy))
self.assertEqual(timedelta(seconds=-offset), TzInfo(-offset).utcoffset(dummy))
self.assertEqual(self.EST.utcoffset(''), timedelta(hours=-5))
self.assertEqual(self.EST.utcoffset(5), timedelta(hours=-5))
def test_dst(self):
self.EST.dst('') is None
self.EST.dst(5) is None
def test_tzname(self):
self.assertEqual('-05:00', TzInfo(-5 * HOUR).tzname(None))
self.assertEqual('+09:30', TzInfo(9.5 * HOUR).tzname(None))
self.assertEqual('-00:01', TzInfo(timedelta(minutes=-1).total_seconds()).tzname(None))
# Sub-minute offsets:
self.assertEqual('+01:06:40', TzInfo(timedelta(0, 4000).total_seconds()).tzname(None))
self.assertEqual('-01:06:40', TzInfo(-timedelta(0, 4000).total_seconds()).tzname(None))
self.assertEqual('+01:06:40', TzInfo(timedelta(0, 4000, 1).total_seconds()).tzname(None))
self.assertEqual('-01:06:40', TzInfo(-timedelta(0, 4000, 1).total_seconds()).tzname(None))
self.assertEqual(self.EST.tzname(''), '-05:00')
self.assertEqual(self.EST.tzname(5), '-05:00')
def test_fromutc(self):
for tz in [self.EST, self.ACDT]:
utctime = self.DT.replace(tzinfo=tz)
local = tz.fromutc(utctime)
self.assertEqual(local - utctime, tz.utcoffset(local))
self.assertEqual(local, self.DT.replace(tzinfo=timezone.utc))
def test_comparison(self):
self.assertNotEqual(TzInfo(ZERO), TzInfo(HOUR))
self.assertEqual(TzInfo(HOUR), TzInfo(HOUR))
self.assertFalse(TzInfo(ZERO) < TzInfo(ZERO))
self.assertIn(TzInfo(ZERO), {TzInfo(ZERO)})
self.assertTrue(TzInfo(ZERO) is not None)
self.assertFalse(TzInfo(ZERO) is None)
tz = TzInfo(ZERO)
self.assertTrue(tz == ALWAYS_EQ)
self.assertFalse(tz != ALWAYS_EQ)
self.assertTrue(tz < LARGEST)
self.assertFalse(tz > LARGEST)
self.assertTrue(tz <= LARGEST)
self.assertFalse(tz >= LARGEST)
self.assertFalse(tz < SMALLEST)
self.assertTrue(tz > SMALLEST)
self.assertFalse(tz <= SMALLEST)
self.assertTrue(tz >= SMALLEST)
# offset based comparion tests for tzinfo derived classes like datetime.timezone.
utcdatetime = self.DT.replace(tzinfo=timezone.utc)
self.assertTrue(tz == utcdatetime.tzinfo)
estdatetime = self.DT.replace(tzinfo=timezone(-timedelta(hours=5)))
self.assertTrue(self.EST == estdatetime.tzinfo)
self.assertTrue(tz > estdatetime.tzinfo)
if sys.version_info >= (3, 9) and sys.platform == 'linux':
try:
europe_london = ZoneInfo('Europe/London')
except ZoneInfoNotFoundError:
# tz data not available
pass
else:
self.assertFalse(tz == europe_london)
with self.assertRaises(TypeError):
tz > europe_london
def test_copy(self):
for tz in self.ACDT, self.EST:
tz_copy = copy.copy(tz)
self.assertEqual(tz_copy, tz)
def test_deepcopy(self):
for tz in self.ACDT, self.EST:
tz_copy = copy.deepcopy(tz)
self.assertEqual(tz_copy, tz)
def test_offset_boundaries(self):
# Test timedeltas close to the boundaries
time_deltas = [timedelta(hours=23, minutes=59), timedelta(hours=23, minutes=59, seconds=59)]
time_deltas.extend([-delta for delta in time_deltas])
for delta in time_deltas:
with self.subTest(test_type='good', delta=delta):
print(delta.total_seconds())
TzInfo(delta.total_seconds())
# Test timedeltas on and outside the boundaries
bad_time_deltas = [timedelta(hours=24), timedelta(hours=24, microseconds=1)]
bad_time_deltas.extend([-delta for delta in bad_time_deltas])
for delta in bad_time_deltas:
with self.subTest(test_type='bad', delta=delta):
with self.assertRaises(ValueError):
TzInfo(delta.total_seconds())
def test_tzinfo_could_be_reused():
class Model:
value: datetime
v = SchemaValidator(
core_schema.model_schema(
Model, core_schema.model_fields_schema({'value': core_schema.model_field(core_schema.datetime_schema())})
)
)
m = v.validate_python({'value': '2015-10-21T15:28:00.000000+01:00'})
target = datetime(1955, 11, 12, 14, 38, tzinfo=m.value.tzinfo)
assert target == datetime(1955, 11, 12, 14, 38, tzinfo=timezone(timedelta(hours=1)))
now = datetime.now(tz=m.value.tzinfo)
assert isinstance(now, datetime)