1 | n/a | """Test date/time type. |
---|
2 | n/a | |
---|
3 | n/a | See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases |
---|
4 | n/a | """ |
---|
5 | n/a | from test.support import is_resource_enabled |
---|
6 | n/a | |
---|
7 | n/a | import itertools |
---|
8 | n/a | import bisect |
---|
9 | n/a | |
---|
10 | n/a | import copy |
---|
11 | n/a | import decimal |
---|
12 | n/a | import sys |
---|
13 | n/a | import os |
---|
14 | n/a | import pickle |
---|
15 | n/a | import random |
---|
16 | n/a | import struct |
---|
17 | n/a | import unittest |
---|
18 | n/a | |
---|
19 | n/a | from array import array |
---|
20 | n/a | |
---|
21 | n/a | from operator import lt, le, gt, ge, eq, ne, truediv, floordiv, mod |
---|
22 | n/a | |
---|
23 | n/a | from test import support |
---|
24 | n/a | |
---|
25 | n/a | import datetime as datetime_module |
---|
26 | n/a | from datetime import MINYEAR, MAXYEAR |
---|
27 | n/a | from datetime import timedelta |
---|
28 | n/a | from datetime import tzinfo |
---|
29 | n/a | from datetime import time |
---|
30 | n/a | from datetime import timezone |
---|
31 | n/a | from datetime import date, datetime |
---|
32 | n/a | import time as _time |
---|
33 | n/a | |
---|
34 | n/a | # Needed by test_datetime |
---|
35 | n/a | import _strptime |
---|
36 | n/a | # |
---|
37 | n/a | |
---|
38 | n/a | |
---|
39 | n/a | pickle_choices = [(pickle, pickle, proto) |
---|
40 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1)] |
---|
41 | n/a | assert len(pickle_choices) == pickle.HIGHEST_PROTOCOL + 1 |
---|
42 | n/a | |
---|
43 | n/a | # An arbitrary collection of objects of non-datetime types, for testing |
---|
44 | n/a | # mixed-type comparisons. |
---|
45 | n/a | OTHERSTUFF = (10, 34.5, "abc", {}, [], ()) |
---|
46 | n/a | |
---|
47 | n/a | |
---|
48 | n/a | # XXX Copied from test_float. |
---|
49 | n/a | INF = float("inf") |
---|
50 | n/a | NAN = float("nan") |
---|
51 | n/a | |
---|
52 | n/a | |
---|
53 | n/a | ############################################################################# |
---|
54 | n/a | # module tests |
---|
55 | n/a | |
---|
56 | n/a | class TestModule(unittest.TestCase): |
---|
57 | n/a | |
---|
58 | n/a | def test_constants(self): |
---|
59 | n/a | datetime = datetime_module |
---|
60 | n/a | self.assertEqual(datetime.MINYEAR, 1) |
---|
61 | n/a | self.assertEqual(datetime.MAXYEAR, 9999) |
---|
62 | n/a | |
---|
63 | n/a | def test_name_cleanup(self): |
---|
64 | n/a | if '_Fast' not in str(self): |
---|
65 | n/a | return |
---|
66 | n/a | datetime = datetime_module |
---|
67 | n/a | names = set(name for name in dir(datetime) |
---|
68 | n/a | if not name.startswith('__') and not name.endswith('__')) |
---|
69 | n/a | allowed = set(['MAXYEAR', 'MINYEAR', 'date', 'datetime', |
---|
70 | n/a | 'datetime_CAPI', 'time', 'timedelta', 'timezone', |
---|
71 | n/a | 'tzinfo']) |
---|
72 | n/a | self.assertEqual(names - allowed, set([])) |
---|
73 | n/a | |
---|
74 | n/a | def test_divide_and_round(self): |
---|
75 | n/a | if '_Fast' in str(self): |
---|
76 | n/a | return |
---|
77 | n/a | dar = datetime_module._divide_and_round |
---|
78 | n/a | |
---|
79 | n/a | self.assertEqual(dar(-10, -3), 3) |
---|
80 | n/a | self.assertEqual(dar(5, -2), -2) |
---|
81 | n/a | |
---|
82 | n/a | # four cases: (2 signs of a) x (2 signs of b) |
---|
83 | n/a | self.assertEqual(dar(7, 3), 2) |
---|
84 | n/a | self.assertEqual(dar(-7, 3), -2) |
---|
85 | n/a | self.assertEqual(dar(7, -3), -2) |
---|
86 | n/a | self.assertEqual(dar(-7, -3), 2) |
---|
87 | n/a | |
---|
88 | n/a | # ties to even - eight cases: |
---|
89 | n/a | # (2 signs of a) x (2 signs of b) x (even / odd quotient) |
---|
90 | n/a | self.assertEqual(dar(10, 4), 2) |
---|
91 | n/a | self.assertEqual(dar(-10, 4), -2) |
---|
92 | n/a | self.assertEqual(dar(10, -4), -2) |
---|
93 | n/a | self.assertEqual(dar(-10, -4), 2) |
---|
94 | n/a | |
---|
95 | n/a | self.assertEqual(dar(6, 4), 2) |
---|
96 | n/a | self.assertEqual(dar(-6, 4), -2) |
---|
97 | n/a | self.assertEqual(dar(6, -4), -2) |
---|
98 | n/a | self.assertEqual(dar(-6, -4), 2) |
---|
99 | n/a | |
---|
100 | n/a | |
---|
101 | n/a | ############################################################################# |
---|
102 | n/a | # tzinfo tests |
---|
103 | n/a | |
---|
104 | n/a | class FixedOffset(tzinfo): |
---|
105 | n/a | |
---|
106 | n/a | def __init__(self, offset, name, dstoffset=42): |
---|
107 | n/a | if isinstance(offset, int): |
---|
108 | n/a | offset = timedelta(minutes=offset) |
---|
109 | n/a | if isinstance(dstoffset, int): |
---|
110 | n/a | dstoffset = timedelta(minutes=dstoffset) |
---|
111 | n/a | self.__offset = offset |
---|
112 | n/a | self.__name = name |
---|
113 | n/a | self.__dstoffset = dstoffset |
---|
114 | n/a | def __repr__(self): |
---|
115 | n/a | return self.__name.lower() |
---|
116 | n/a | def utcoffset(self, dt): |
---|
117 | n/a | return self.__offset |
---|
118 | n/a | def tzname(self, dt): |
---|
119 | n/a | return self.__name |
---|
120 | n/a | def dst(self, dt): |
---|
121 | n/a | return self.__dstoffset |
---|
122 | n/a | |
---|
123 | n/a | class PicklableFixedOffset(FixedOffset): |
---|
124 | n/a | |
---|
125 | n/a | def __init__(self, offset=None, name=None, dstoffset=None): |
---|
126 | n/a | FixedOffset.__init__(self, offset, name, dstoffset) |
---|
127 | n/a | |
---|
128 | n/a | def __getstate__(self): |
---|
129 | n/a | return self.__dict__ |
---|
130 | n/a | |
---|
131 | n/a | class _TZInfo(tzinfo): |
---|
132 | n/a | def utcoffset(self, datetime_module): |
---|
133 | n/a | return random.random() |
---|
134 | n/a | |
---|
135 | n/a | class TestTZInfo(unittest.TestCase): |
---|
136 | n/a | |
---|
137 | n/a | def test_refcnt_crash_bug_22044(self): |
---|
138 | n/a | tz1 = _TZInfo() |
---|
139 | n/a | dt1 = datetime(2014, 7, 21, 11, 32, 3, 0, tz1) |
---|
140 | n/a | with self.assertRaises(TypeError): |
---|
141 | n/a | dt1.utcoffset() |
---|
142 | n/a | |
---|
143 | n/a | def test_non_abstractness(self): |
---|
144 | n/a | # In order to allow subclasses to get pickled, the C implementation |
---|
145 | n/a | # wasn't able to get away with having __init__ raise |
---|
146 | n/a | # NotImplementedError. |
---|
147 | n/a | useless = tzinfo() |
---|
148 | n/a | dt = datetime.max |
---|
149 | n/a | self.assertRaises(NotImplementedError, useless.tzname, dt) |
---|
150 | n/a | self.assertRaises(NotImplementedError, useless.utcoffset, dt) |
---|
151 | n/a | self.assertRaises(NotImplementedError, useless.dst, dt) |
---|
152 | n/a | |
---|
153 | n/a | def test_subclass_must_override(self): |
---|
154 | n/a | class NotEnough(tzinfo): |
---|
155 | n/a | def __init__(self, offset, name): |
---|
156 | n/a | self.__offset = offset |
---|
157 | n/a | self.__name = name |
---|
158 | n/a | self.assertTrue(issubclass(NotEnough, tzinfo)) |
---|
159 | n/a | ne = NotEnough(3, "NotByALongShot") |
---|
160 | n/a | self.assertIsInstance(ne, tzinfo) |
---|
161 | n/a | |
---|
162 | n/a | dt = datetime.now() |
---|
163 | n/a | self.assertRaises(NotImplementedError, ne.tzname, dt) |
---|
164 | n/a | self.assertRaises(NotImplementedError, ne.utcoffset, dt) |
---|
165 | n/a | self.assertRaises(NotImplementedError, ne.dst, dt) |
---|
166 | n/a | |
---|
167 | n/a | def test_normal(self): |
---|
168 | n/a | fo = FixedOffset(3, "Three") |
---|
169 | n/a | self.assertIsInstance(fo, tzinfo) |
---|
170 | n/a | for dt in datetime.now(), None: |
---|
171 | n/a | self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3)) |
---|
172 | n/a | self.assertEqual(fo.tzname(dt), "Three") |
---|
173 | n/a | self.assertEqual(fo.dst(dt), timedelta(minutes=42)) |
---|
174 | n/a | |
---|
175 | n/a | def test_pickling_base(self): |
---|
176 | n/a | # There's no point to pickling tzinfo objects on their own (they |
---|
177 | n/a | # carry no data), but they need to be picklable anyway else |
---|
178 | n/a | # concrete subclasses can't be pickled. |
---|
179 | n/a | orig = tzinfo.__new__(tzinfo) |
---|
180 | n/a | self.assertIs(type(orig), tzinfo) |
---|
181 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
182 | n/a | green = pickler.dumps(orig, proto) |
---|
183 | n/a | derived = unpickler.loads(green) |
---|
184 | n/a | self.assertIs(type(derived), tzinfo) |
---|
185 | n/a | |
---|
186 | n/a | def test_pickling_subclass(self): |
---|
187 | n/a | # Make sure we can pickle/unpickle an instance of a subclass. |
---|
188 | n/a | offset = timedelta(minutes=-300) |
---|
189 | n/a | for otype, args in [ |
---|
190 | n/a | (PicklableFixedOffset, (offset, 'cookie')), |
---|
191 | n/a | (timezone, (offset,)), |
---|
192 | n/a | (timezone, (offset, "EST"))]: |
---|
193 | n/a | orig = otype(*args) |
---|
194 | n/a | oname = orig.tzname(None) |
---|
195 | n/a | self.assertIsInstance(orig, tzinfo) |
---|
196 | n/a | self.assertIs(type(orig), otype) |
---|
197 | n/a | self.assertEqual(orig.utcoffset(None), offset) |
---|
198 | n/a | self.assertEqual(orig.tzname(None), oname) |
---|
199 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
200 | n/a | green = pickler.dumps(orig, proto) |
---|
201 | n/a | derived = unpickler.loads(green) |
---|
202 | n/a | self.assertIsInstance(derived, tzinfo) |
---|
203 | n/a | self.assertIs(type(derived), otype) |
---|
204 | n/a | self.assertEqual(derived.utcoffset(None), offset) |
---|
205 | n/a | self.assertEqual(derived.tzname(None), oname) |
---|
206 | n/a | |
---|
207 | n/a | def test_issue23600(self): |
---|
208 | n/a | DSTDIFF = DSTOFFSET = timedelta(hours=1) |
---|
209 | n/a | |
---|
210 | n/a | class UKSummerTime(tzinfo): |
---|
211 | n/a | """Simple time zone which pretends to always be in summer time, since |
---|
212 | n/a | that's what shows the failure. |
---|
213 | n/a | """ |
---|
214 | n/a | |
---|
215 | n/a | def utcoffset(self, dt): |
---|
216 | n/a | return DSTOFFSET |
---|
217 | n/a | |
---|
218 | n/a | def dst(self, dt): |
---|
219 | n/a | return DSTDIFF |
---|
220 | n/a | |
---|
221 | n/a | def tzname(self, dt): |
---|
222 | n/a | return 'UKSummerTime' |
---|
223 | n/a | |
---|
224 | n/a | tz = UKSummerTime() |
---|
225 | n/a | u = datetime(2014, 4, 26, 12, 1, tzinfo=tz) |
---|
226 | n/a | t = tz.fromutc(u) |
---|
227 | n/a | self.assertEqual(t - t.utcoffset(), u) |
---|
228 | n/a | |
---|
229 | n/a | |
---|
230 | n/a | class TestTimeZone(unittest.TestCase): |
---|
231 | n/a | |
---|
232 | n/a | def setUp(self): |
---|
233 | n/a | self.ACDT = timezone(timedelta(hours=9.5), 'ACDT') |
---|
234 | n/a | self.EST = timezone(-timedelta(hours=5), 'EST') |
---|
235 | n/a | self.DT = datetime(2010, 1, 1) |
---|
236 | n/a | |
---|
237 | n/a | def test_str(self): |
---|
238 | n/a | for tz in [self.ACDT, self.EST, timezone.utc, |
---|
239 | n/a | timezone.min, timezone.max]: |
---|
240 | n/a | self.assertEqual(str(tz), tz.tzname(None)) |
---|
241 | n/a | |
---|
242 | n/a | def test_repr(self): |
---|
243 | n/a | datetime = datetime_module |
---|
244 | n/a | for tz in [self.ACDT, self.EST, timezone.utc, |
---|
245 | n/a | timezone.min, timezone.max]: |
---|
246 | n/a | # test round-trip |
---|
247 | n/a | tzrep = repr(tz) |
---|
248 | n/a | self.assertEqual(tz, eval(tzrep)) |
---|
249 | n/a | |
---|
250 | n/a | def test_class_members(self): |
---|
251 | n/a | limit = timedelta(hours=23, minutes=59) |
---|
252 | n/a | self.assertEqual(timezone.utc.utcoffset(None), ZERO) |
---|
253 | n/a | self.assertEqual(timezone.min.utcoffset(None), -limit) |
---|
254 | n/a | self.assertEqual(timezone.max.utcoffset(None), limit) |
---|
255 | n/a | |
---|
256 | n/a | |
---|
257 | n/a | def test_constructor(self): |
---|
258 | n/a | self.assertIs(timezone.utc, timezone(timedelta(0))) |
---|
259 | n/a | self.assertIsNot(timezone.utc, timezone(timedelta(0), 'UTC')) |
---|
260 | n/a | self.assertEqual(timezone.utc, timezone(timedelta(0), 'UTC')) |
---|
261 | n/a | # invalid offsets |
---|
262 | n/a | for invalid in [timedelta(microseconds=1), timedelta(1, 1), |
---|
263 | n/a | timedelta(seconds=1), timedelta(1), -timedelta(1)]: |
---|
264 | n/a | self.assertRaises(ValueError, timezone, invalid) |
---|
265 | n/a | self.assertRaises(ValueError, timezone, -invalid) |
---|
266 | n/a | |
---|
267 | n/a | with self.assertRaises(TypeError): timezone(None) |
---|
268 | n/a | with self.assertRaises(TypeError): timezone(42) |
---|
269 | n/a | with self.assertRaises(TypeError): timezone(ZERO, None) |
---|
270 | n/a | with self.assertRaises(TypeError): timezone(ZERO, 42) |
---|
271 | n/a | with self.assertRaises(TypeError): timezone(ZERO, 'ABC', 'extra') |
---|
272 | n/a | |
---|
273 | n/a | def test_inheritance(self): |
---|
274 | n/a | self.assertIsInstance(timezone.utc, tzinfo) |
---|
275 | n/a | self.assertIsInstance(self.EST, tzinfo) |
---|
276 | n/a | |
---|
277 | n/a | def test_utcoffset(self): |
---|
278 | n/a | dummy = self.DT |
---|
279 | n/a | for h in [0, 1.5, 12]: |
---|
280 | n/a | offset = h * HOUR |
---|
281 | n/a | self.assertEqual(offset, timezone(offset).utcoffset(dummy)) |
---|
282 | n/a | self.assertEqual(-offset, timezone(-offset).utcoffset(dummy)) |
---|
283 | n/a | |
---|
284 | n/a | with self.assertRaises(TypeError): self.EST.utcoffset('') |
---|
285 | n/a | with self.assertRaises(TypeError): self.EST.utcoffset(5) |
---|
286 | n/a | |
---|
287 | n/a | |
---|
288 | n/a | def test_dst(self): |
---|
289 | n/a | self.assertIsNone(timezone.utc.dst(self.DT)) |
---|
290 | n/a | |
---|
291 | n/a | with self.assertRaises(TypeError): self.EST.dst('') |
---|
292 | n/a | with self.assertRaises(TypeError): self.EST.dst(5) |
---|
293 | n/a | |
---|
294 | n/a | def test_tzname(self): |
---|
295 | n/a | self.assertEqual('UTC', timezone.utc.tzname(None)) |
---|
296 | n/a | self.assertEqual('UTC', timezone(ZERO).tzname(None)) |
---|
297 | n/a | self.assertEqual('UTC-05:00', timezone(-5 * HOUR).tzname(None)) |
---|
298 | n/a | self.assertEqual('UTC+09:30', timezone(9.5 * HOUR).tzname(None)) |
---|
299 | n/a | self.assertEqual('UTC-00:01', timezone(timedelta(minutes=-1)).tzname(None)) |
---|
300 | n/a | self.assertEqual('XYZ', timezone(-5 * HOUR, 'XYZ').tzname(None)) |
---|
301 | n/a | |
---|
302 | n/a | with self.assertRaises(TypeError): self.EST.tzname('') |
---|
303 | n/a | with self.assertRaises(TypeError): self.EST.tzname(5) |
---|
304 | n/a | |
---|
305 | n/a | def test_fromutc(self): |
---|
306 | n/a | with self.assertRaises(ValueError): |
---|
307 | n/a | timezone.utc.fromutc(self.DT) |
---|
308 | n/a | with self.assertRaises(TypeError): |
---|
309 | n/a | timezone.utc.fromutc('not datetime') |
---|
310 | n/a | for tz in [self.EST, self.ACDT, Eastern]: |
---|
311 | n/a | utctime = self.DT.replace(tzinfo=tz) |
---|
312 | n/a | local = tz.fromutc(utctime) |
---|
313 | n/a | self.assertEqual(local - utctime, tz.utcoffset(local)) |
---|
314 | n/a | self.assertEqual(local, |
---|
315 | n/a | self.DT.replace(tzinfo=timezone.utc)) |
---|
316 | n/a | |
---|
317 | n/a | def test_comparison(self): |
---|
318 | n/a | self.assertNotEqual(timezone(ZERO), timezone(HOUR)) |
---|
319 | n/a | self.assertEqual(timezone(HOUR), timezone(HOUR)) |
---|
320 | n/a | self.assertEqual(timezone(-5 * HOUR), timezone(-5 * HOUR, 'EST')) |
---|
321 | n/a | with self.assertRaises(TypeError): timezone(ZERO) < timezone(ZERO) |
---|
322 | n/a | self.assertIn(timezone(ZERO), {timezone(ZERO)}) |
---|
323 | n/a | self.assertTrue(timezone(ZERO) != None) |
---|
324 | n/a | self.assertFalse(timezone(ZERO) == None) |
---|
325 | n/a | |
---|
326 | n/a | def test_aware_datetime(self): |
---|
327 | n/a | # test that timezone instances can be used by datetime |
---|
328 | n/a | t = datetime(1, 1, 1) |
---|
329 | n/a | for tz in [timezone.min, timezone.max, timezone.utc]: |
---|
330 | n/a | self.assertEqual(tz.tzname(t), |
---|
331 | n/a | t.replace(tzinfo=tz).tzname()) |
---|
332 | n/a | self.assertEqual(tz.utcoffset(t), |
---|
333 | n/a | t.replace(tzinfo=tz).utcoffset()) |
---|
334 | n/a | self.assertEqual(tz.dst(t), |
---|
335 | n/a | t.replace(tzinfo=tz).dst()) |
---|
336 | n/a | |
---|
337 | n/a | def test_pickle(self): |
---|
338 | n/a | for tz in self.ACDT, self.EST, timezone.min, timezone.max: |
---|
339 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
340 | n/a | tz_copy = unpickler.loads(pickler.dumps(tz, proto)) |
---|
341 | n/a | self.assertEqual(tz_copy, tz) |
---|
342 | n/a | tz = timezone.utc |
---|
343 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
344 | n/a | tz_copy = unpickler.loads(pickler.dumps(tz, proto)) |
---|
345 | n/a | self.assertIs(tz_copy, tz) |
---|
346 | n/a | |
---|
347 | n/a | def test_copy(self): |
---|
348 | n/a | for tz in self.ACDT, self.EST, timezone.min, timezone.max: |
---|
349 | n/a | tz_copy = copy.copy(tz) |
---|
350 | n/a | self.assertEqual(tz_copy, tz) |
---|
351 | n/a | tz = timezone.utc |
---|
352 | n/a | tz_copy = copy.copy(tz) |
---|
353 | n/a | self.assertIs(tz_copy, tz) |
---|
354 | n/a | |
---|
355 | n/a | def test_deepcopy(self): |
---|
356 | n/a | for tz in self.ACDT, self.EST, timezone.min, timezone.max: |
---|
357 | n/a | tz_copy = copy.deepcopy(tz) |
---|
358 | n/a | self.assertEqual(tz_copy, tz) |
---|
359 | n/a | tz = timezone.utc |
---|
360 | n/a | tz_copy = copy.deepcopy(tz) |
---|
361 | n/a | self.assertIs(tz_copy, tz) |
---|
362 | n/a | |
---|
363 | n/a | |
---|
364 | n/a | ############################################################################# |
---|
365 | n/a | # Base class for testing a particular aspect of timedelta, time, date and |
---|
366 | n/a | # datetime comparisons. |
---|
367 | n/a | |
---|
368 | n/a | class HarmlessMixedComparison: |
---|
369 | n/a | # Test that __eq__ and __ne__ don't complain for mixed-type comparisons. |
---|
370 | n/a | |
---|
371 | n/a | # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a |
---|
372 | n/a | # legit constructor. |
---|
373 | n/a | |
---|
374 | n/a | def test_harmless_mixed_comparison(self): |
---|
375 | n/a | me = self.theclass(1, 1, 1) |
---|
376 | n/a | |
---|
377 | n/a | self.assertFalse(me == ()) |
---|
378 | n/a | self.assertTrue(me != ()) |
---|
379 | n/a | self.assertFalse(() == me) |
---|
380 | n/a | self.assertTrue(() != me) |
---|
381 | n/a | |
---|
382 | n/a | self.assertIn(me, [1, 20, [], me]) |
---|
383 | n/a | self.assertIn([], [me, 1, 20, []]) |
---|
384 | n/a | |
---|
385 | n/a | def test_harmful_mixed_comparison(self): |
---|
386 | n/a | me = self.theclass(1, 1, 1) |
---|
387 | n/a | |
---|
388 | n/a | self.assertRaises(TypeError, lambda: me < ()) |
---|
389 | n/a | self.assertRaises(TypeError, lambda: me <= ()) |
---|
390 | n/a | self.assertRaises(TypeError, lambda: me > ()) |
---|
391 | n/a | self.assertRaises(TypeError, lambda: me >= ()) |
---|
392 | n/a | |
---|
393 | n/a | self.assertRaises(TypeError, lambda: () < me) |
---|
394 | n/a | self.assertRaises(TypeError, lambda: () <= me) |
---|
395 | n/a | self.assertRaises(TypeError, lambda: () > me) |
---|
396 | n/a | self.assertRaises(TypeError, lambda: () >= me) |
---|
397 | n/a | |
---|
398 | n/a | ############################################################################# |
---|
399 | n/a | # timedelta tests |
---|
400 | n/a | |
---|
401 | n/a | class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase): |
---|
402 | n/a | |
---|
403 | n/a | theclass = timedelta |
---|
404 | n/a | |
---|
405 | n/a | def test_constructor(self): |
---|
406 | n/a | eq = self.assertEqual |
---|
407 | n/a | td = timedelta |
---|
408 | n/a | |
---|
409 | n/a | # Check keyword args to constructor |
---|
410 | n/a | eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0, |
---|
411 | n/a | milliseconds=0, microseconds=0)) |
---|
412 | n/a | eq(td(1), td(days=1)) |
---|
413 | n/a | eq(td(0, 1), td(seconds=1)) |
---|
414 | n/a | eq(td(0, 0, 1), td(microseconds=1)) |
---|
415 | n/a | eq(td(weeks=1), td(days=7)) |
---|
416 | n/a | eq(td(days=1), td(hours=24)) |
---|
417 | n/a | eq(td(hours=1), td(minutes=60)) |
---|
418 | n/a | eq(td(minutes=1), td(seconds=60)) |
---|
419 | n/a | eq(td(seconds=1), td(milliseconds=1000)) |
---|
420 | n/a | eq(td(milliseconds=1), td(microseconds=1000)) |
---|
421 | n/a | |
---|
422 | n/a | # Check float args to constructor |
---|
423 | n/a | eq(td(weeks=1.0/7), td(days=1)) |
---|
424 | n/a | eq(td(days=1.0/24), td(hours=1)) |
---|
425 | n/a | eq(td(hours=1.0/60), td(minutes=1)) |
---|
426 | n/a | eq(td(minutes=1.0/60), td(seconds=1)) |
---|
427 | n/a | eq(td(seconds=0.001), td(milliseconds=1)) |
---|
428 | n/a | eq(td(milliseconds=0.001), td(microseconds=1)) |
---|
429 | n/a | |
---|
430 | n/a | def test_computations(self): |
---|
431 | n/a | eq = self.assertEqual |
---|
432 | n/a | td = timedelta |
---|
433 | n/a | |
---|
434 | n/a | a = td(7) # One week |
---|
435 | n/a | b = td(0, 60) # One minute |
---|
436 | n/a | c = td(0, 0, 1000) # One millisecond |
---|
437 | n/a | eq(a+b+c, td(7, 60, 1000)) |
---|
438 | n/a | eq(a-b, td(6, 24*3600 - 60)) |
---|
439 | n/a | eq(b.__rsub__(a), td(6, 24*3600 - 60)) |
---|
440 | n/a | eq(-a, td(-7)) |
---|
441 | n/a | eq(+a, td(7)) |
---|
442 | n/a | eq(-b, td(-1, 24*3600 - 60)) |
---|
443 | n/a | eq(-c, td(-1, 24*3600 - 1, 999000)) |
---|
444 | n/a | eq(abs(a), a) |
---|
445 | n/a | eq(abs(-a), a) |
---|
446 | n/a | eq(td(6, 24*3600), a) |
---|
447 | n/a | eq(td(0, 0, 60*1000000), b) |
---|
448 | n/a | eq(a*10, td(70)) |
---|
449 | n/a | eq(a*10, 10*a) |
---|
450 | n/a | eq(a*10, 10*a) |
---|
451 | n/a | eq(b*10, td(0, 600)) |
---|
452 | n/a | eq(10*b, td(0, 600)) |
---|
453 | n/a | eq(b*10, td(0, 600)) |
---|
454 | n/a | eq(c*10, td(0, 0, 10000)) |
---|
455 | n/a | eq(10*c, td(0, 0, 10000)) |
---|
456 | n/a | eq(c*10, td(0, 0, 10000)) |
---|
457 | n/a | eq(a*-1, -a) |
---|
458 | n/a | eq(b*-2, -b-b) |
---|
459 | n/a | eq(c*-2, -c+-c) |
---|
460 | n/a | eq(b*(60*24), (b*60)*24) |
---|
461 | n/a | eq(b*(60*24), (60*b)*24) |
---|
462 | n/a | eq(c*1000, td(0, 1)) |
---|
463 | n/a | eq(1000*c, td(0, 1)) |
---|
464 | n/a | eq(a//7, td(1)) |
---|
465 | n/a | eq(b//10, td(0, 6)) |
---|
466 | n/a | eq(c//1000, td(0, 0, 1)) |
---|
467 | n/a | eq(a//10, td(0, 7*24*360)) |
---|
468 | n/a | eq(a//3600000, td(0, 0, 7*24*1000)) |
---|
469 | n/a | eq(a/0.5, td(14)) |
---|
470 | n/a | eq(b/0.5, td(0, 120)) |
---|
471 | n/a | eq(a/7, td(1)) |
---|
472 | n/a | eq(b/10, td(0, 6)) |
---|
473 | n/a | eq(c/1000, td(0, 0, 1)) |
---|
474 | n/a | eq(a/10, td(0, 7*24*360)) |
---|
475 | n/a | eq(a/3600000, td(0, 0, 7*24*1000)) |
---|
476 | n/a | |
---|
477 | n/a | # Multiplication by float |
---|
478 | n/a | us = td(microseconds=1) |
---|
479 | n/a | eq((3*us) * 0.5, 2*us) |
---|
480 | n/a | eq((5*us) * 0.5, 2*us) |
---|
481 | n/a | eq(0.5 * (3*us), 2*us) |
---|
482 | n/a | eq(0.5 * (5*us), 2*us) |
---|
483 | n/a | eq((-3*us) * 0.5, -2*us) |
---|
484 | n/a | eq((-5*us) * 0.5, -2*us) |
---|
485 | n/a | |
---|
486 | n/a | # Issue #23521 |
---|
487 | n/a | eq(td(seconds=1) * 0.123456, td(microseconds=123456)) |
---|
488 | n/a | eq(td(seconds=1) * 0.6112295, td(microseconds=611229)) |
---|
489 | n/a | |
---|
490 | n/a | # Division by int and float |
---|
491 | n/a | eq((3*us) / 2, 2*us) |
---|
492 | n/a | eq((5*us) / 2, 2*us) |
---|
493 | n/a | eq((-3*us) / 2.0, -2*us) |
---|
494 | n/a | eq((-5*us) / 2.0, -2*us) |
---|
495 | n/a | eq((3*us) / -2, -2*us) |
---|
496 | n/a | eq((5*us) / -2, -2*us) |
---|
497 | n/a | eq((3*us) / -2.0, -2*us) |
---|
498 | n/a | eq((5*us) / -2.0, -2*us) |
---|
499 | n/a | for i in range(-10, 10): |
---|
500 | n/a | eq((i*us/3)//us, round(i/3)) |
---|
501 | n/a | for i in range(-10, 10): |
---|
502 | n/a | eq((i*us/-3)//us, round(i/-3)) |
---|
503 | n/a | |
---|
504 | n/a | # Issue #23521 |
---|
505 | n/a | eq(td(seconds=1) / (1 / 0.6112295), td(microseconds=611229)) |
---|
506 | n/a | |
---|
507 | n/a | # Issue #11576 |
---|
508 | n/a | eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998), |
---|
509 | n/a | td(0, 0, 1)) |
---|
510 | n/a | eq(td(999999999, 1, 1) - td(999999999, 1, 0), |
---|
511 | n/a | td(0, 0, 1)) |
---|
512 | n/a | |
---|
513 | n/a | def test_disallowed_computations(self): |
---|
514 | n/a | a = timedelta(42) |
---|
515 | n/a | |
---|
516 | n/a | # Add/sub ints or floats should be illegal |
---|
517 | n/a | for i in 1, 1.0: |
---|
518 | n/a | self.assertRaises(TypeError, lambda: a+i) |
---|
519 | n/a | self.assertRaises(TypeError, lambda: a-i) |
---|
520 | n/a | self.assertRaises(TypeError, lambda: i+a) |
---|
521 | n/a | self.assertRaises(TypeError, lambda: i-a) |
---|
522 | n/a | |
---|
523 | n/a | # Division of int by timedelta doesn't make sense. |
---|
524 | n/a | # Division by zero doesn't make sense. |
---|
525 | n/a | zero = 0 |
---|
526 | n/a | self.assertRaises(TypeError, lambda: zero // a) |
---|
527 | n/a | self.assertRaises(ZeroDivisionError, lambda: a // zero) |
---|
528 | n/a | self.assertRaises(ZeroDivisionError, lambda: a / zero) |
---|
529 | n/a | self.assertRaises(ZeroDivisionError, lambda: a / 0.0) |
---|
530 | n/a | self.assertRaises(TypeError, lambda: a / '') |
---|
531 | n/a | |
---|
532 | n/a | @support.requires_IEEE_754 |
---|
533 | n/a | def test_disallowed_special(self): |
---|
534 | n/a | a = timedelta(42) |
---|
535 | n/a | self.assertRaises(ValueError, a.__mul__, NAN) |
---|
536 | n/a | self.assertRaises(ValueError, a.__truediv__, NAN) |
---|
537 | n/a | |
---|
538 | n/a | def test_basic_attributes(self): |
---|
539 | n/a | days, seconds, us = 1, 7, 31 |
---|
540 | n/a | td = timedelta(days, seconds, us) |
---|
541 | n/a | self.assertEqual(td.days, days) |
---|
542 | n/a | self.assertEqual(td.seconds, seconds) |
---|
543 | n/a | self.assertEqual(td.microseconds, us) |
---|
544 | n/a | |
---|
545 | n/a | def test_total_seconds(self): |
---|
546 | n/a | td = timedelta(days=365) |
---|
547 | n/a | self.assertEqual(td.total_seconds(), 31536000.0) |
---|
548 | n/a | for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]: |
---|
549 | n/a | td = timedelta(seconds=total_seconds) |
---|
550 | n/a | self.assertEqual(td.total_seconds(), total_seconds) |
---|
551 | n/a | # Issue8644: Test that td.total_seconds() has the same |
---|
552 | n/a | # accuracy as td / timedelta(seconds=1). |
---|
553 | n/a | for ms in [-1, -2, -123]: |
---|
554 | n/a | td = timedelta(microseconds=ms) |
---|
555 | n/a | self.assertEqual(td.total_seconds(), td / timedelta(seconds=1)) |
---|
556 | n/a | |
---|
557 | n/a | def test_carries(self): |
---|
558 | n/a | t1 = timedelta(days=100, |
---|
559 | n/a | weeks=-7, |
---|
560 | n/a | hours=-24*(100-49), |
---|
561 | n/a | minutes=-3, |
---|
562 | n/a | seconds=12, |
---|
563 | n/a | microseconds=(3*60 - 12) * 1e6 + 1) |
---|
564 | n/a | t2 = timedelta(microseconds=1) |
---|
565 | n/a | self.assertEqual(t1, t2) |
---|
566 | n/a | |
---|
567 | n/a | def test_hash_equality(self): |
---|
568 | n/a | t1 = timedelta(days=100, |
---|
569 | n/a | weeks=-7, |
---|
570 | n/a | hours=-24*(100-49), |
---|
571 | n/a | minutes=-3, |
---|
572 | n/a | seconds=12, |
---|
573 | n/a | microseconds=(3*60 - 12) * 1000000) |
---|
574 | n/a | t2 = timedelta() |
---|
575 | n/a | self.assertEqual(hash(t1), hash(t2)) |
---|
576 | n/a | |
---|
577 | n/a | t1 += timedelta(weeks=7) |
---|
578 | n/a | t2 += timedelta(days=7*7) |
---|
579 | n/a | self.assertEqual(t1, t2) |
---|
580 | n/a | self.assertEqual(hash(t1), hash(t2)) |
---|
581 | n/a | |
---|
582 | n/a | d = {t1: 1} |
---|
583 | n/a | d[t2] = 2 |
---|
584 | n/a | self.assertEqual(len(d), 1) |
---|
585 | n/a | self.assertEqual(d[t1], 2) |
---|
586 | n/a | |
---|
587 | n/a | def test_pickling(self): |
---|
588 | n/a | args = 12, 34, 56 |
---|
589 | n/a | orig = timedelta(*args) |
---|
590 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
591 | n/a | green = pickler.dumps(orig, proto) |
---|
592 | n/a | derived = unpickler.loads(green) |
---|
593 | n/a | self.assertEqual(orig, derived) |
---|
594 | n/a | |
---|
595 | n/a | def test_compare(self): |
---|
596 | n/a | t1 = timedelta(2, 3, 4) |
---|
597 | n/a | t2 = timedelta(2, 3, 4) |
---|
598 | n/a | self.assertEqual(t1, t2) |
---|
599 | n/a | self.assertTrue(t1 <= t2) |
---|
600 | n/a | self.assertTrue(t1 >= t2) |
---|
601 | n/a | self.assertFalse(t1 != t2) |
---|
602 | n/a | self.assertFalse(t1 < t2) |
---|
603 | n/a | self.assertFalse(t1 > t2) |
---|
604 | n/a | |
---|
605 | n/a | for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): |
---|
606 | n/a | t2 = timedelta(*args) # this is larger than t1 |
---|
607 | n/a | self.assertTrue(t1 < t2) |
---|
608 | n/a | self.assertTrue(t2 > t1) |
---|
609 | n/a | self.assertTrue(t1 <= t2) |
---|
610 | n/a | self.assertTrue(t2 >= t1) |
---|
611 | n/a | self.assertTrue(t1 != t2) |
---|
612 | n/a | self.assertTrue(t2 != t1) |
---|
613 | n/a | self.assertFalse(t1 == t2) |
---|
614 | n/a | self.assertFalse(t2 == t1) |
---|
615 | n/a | self.assertFalse(t1 > t2) |
---|
616 | n/a | self.assertFalse(t2 < t1) |
---|
617 | n/a | self.assertFalse(t1 >= t2) |
---|
618 | n/a | self.assertFalse(t2 <= t1) |
---|
619 | n/a | |
---|
620 | n/a | for badarg in OTHERSTUFF: |
---|
621 | n/a | self.assertEqual(t1 == badarg, False) |
---|
622 | n/a | self.assertEqual(t1 != badarg, True) |
---|
623 | n/a | self.assertEqual(badarg == t1, False) |
---|
624 | n/a | self.assertEqual(badarg != t1, True) |
---|
625 | n/a | |
---|
626 | n/a | self.assertRaises(TypeError, lambda: t1 <= badarg) |
---|
627 | n/a | self.assertRaises(TypeError, lambda: t1 < badarg) |
---|
628 | n/a | self.assertRaises(TypeError, lambda: t1 > badarg) |
---|
629 | n/a | self.assertRaises(TypeError, lambda: t1 >= badarg) |
---|
630 | n/a | self.assertRaises(TypeError, lambda: badarg <= t1) |
---|
631 | n/a | self.assertRaises(TypeError, lambda: badarg < t1) |
---|
632 | n/a | self.assertRaises(TypeError, lambda: badarg > t1) |
---|
633 | n/a | self.assertRaises(TypeError, lambda: badarg >= t1) |
---|
634 | n/a | |
---|
635 | n/a | def test_str(self): |
---|
636 | n/a | td = timedelta |
---|
637 | n/a | eq = self.assertEqual |
---|
638 | n/a | |
---|
639 | n/a | eq(str(td(1)), "1 day, 0:00:00") |
---|
640 | n/a | eq(str(td(-1)), "-1 day, 0:00:00") |
---|
641 | n/a | eq(str(td(2)), "2 days, 0:00:00") |
---|
642 | n/a | eq(str(td(-2)), "-2 days, 0:00:00") |
---|
643 | n/a | |
---|
644 | n/a | eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59") |
---|
645 | n/a | eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04") |
---|
646 | n/a | eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), |
---|
647 | n/a | "-210 days, 23:12:34") |
---|
648 | n/a | |
---|
649 | n/a | eq(str(td(milliseconds=1)), "0:00:00.001000") |
---|
650 | n/a | eq(str(td(microseconds=3)), "0:00:00.000003") |
---|
651 | n/a | |
---|
652 | n/a | eq(str(td(days=999999999, hours=23, minutes=59, seconds=59, |
---|
653 | n/a | microseconds=999999)), |
---|
654 | n/a | "999999999 days, 23:59:59.999999") |
---|
655 | n/a | |
---|
656 | n/a | def test_repr(self): |
---|
657 | n/a | name = 'datetime.' + self.theclass.__name__ |
---|
658 | n/a | self.assertEqual(repr(self.theclass(1)), |
---|
659 | n/a | "%s(1)" % name) |
---|
660 | n/a | self.assertEqual(repr(self.theclass(10, 2)), |
---|
661 | n/a | "%s(10, 2)" % name) |
---|
662 | n/a | self.assertEqual(repr(self.theclass(-10, 2, 400000)), |
---|
663 | n/a | "%s(-10, 2, 400000)" % name) |
---|
664 | n/a | |
---|
665 | n/a | def test_roundtrip(self): |
---|
666 | n/a | for td in (timedelta(days=999999999, hours=23, minutes=59, |
---|
667 | n/a | seconds=59, microseconds=999999), |
---|
668 | n/a | timedelta(days=-999999999), |
---|
669 | n/a | timedelta(days=-999999999, seconds=1), |
---|
670 | n/a | timedelta(days=1, seconds=2, microseconds=3)): |
---|
671 | n/a | |
---|
672 | n/a | # Verify td -> string -> td identity. |
---|
673 | n/a | s = repr(td) |
---|
674 | n/a | self.assertTrue(s.startswith('datetime.')) |
---|
675 | n/a | s = s[9:] |
---|
676 | n/a | td2 = eval(s) |
---|
677 | n/a | self.assertEqual(td, td2) |
---|
678 | n/a | |
---|
679 | n/a | # Verify identity via reconstructing from pieces. |
---|
680 | n/a | td2 = timedelta(td.days, td.seconds, td.microseconds) |
---|
681 | n/a | self.assertEqual(td, td2) |
---|
682 | n/a | |
---|
683 | n/a | def test_resolution_info(self): |
---|
684 | n/a | self.assertIsInstance(timedelta.min, timedelta) |
---|
685 | n/a | self.assertIsInstance(timedelta.max, timedelta) |
---|
686 | n/a | self.assertIsInstance(timedelta.resolution, timedelta) |
---|
687 | n/a | self.assertTrue(timedelta.max > timedelta.min) |
---|
688 | n/a | self.assertEqual(timedelta.min, timedelta(-999999999)) |
---|
689 | n/a | self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) |
---|
690 | n/a | self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) |
---|
691 | n/a | |
---|
692 | n/a | def test_overflow(self): |
---|
693 | n/a | tiny = timedelta.resolution |
---|
694 | n/a | |
---|
695 | n/a | td = timedelta.min + tiny |
---|
696 | n/a | td -= tiny # no problem |
---|
697 | n/a | self.assertRaises(OverflowError, td.__sub__, tiny) |
---|
698 | n/a | self.assertRaises(OverflowError, td.__add__, -tiny) |
---|
699 | n/a | |
---|
700 | n/a | td = timedelta.max - tiny |
---|
701 | n/a | td += tiny # no problem |
---|
702 | n/a | self.assertRaises(OverflowError, td.__add__, tiny) |
---|
703 | n/a | self.assertRaises(OverflowError, td.__sub__, -tiny) |
---|
704 | n/a | |
---|
705 | n/a | self.assertRaises(OverflowError, lambda: -timedelta.max) |
---|
706 | n/a | |
---|
707 | n/a | day = timedelta(1) |
---|
708 | n/a | self.assertRaises(OverflowError, day.__mul__, 10**9) |
---|
709 | n/a | self.assertRaises(OverflowError, day.__mul__, 1e9) |
---|
710 | n/a | self.assertRaises(OverflowError, day.__truediv__, 1e-20) |
---|
711 | n/a | self.assertRaises(OverflowError, day.__truediv__, 1e-10) |
---|
712 | n/a | self.assertRaises(OverflowError, day.__truediv__, 9e-10) |
---|
713 | n/a | |
---|
714 | n/a | @support.requires_IEEE_754 |
---|
715 | n/a | def _test_overflow_special(self): |
---|
716 | n/a | day = timedelta(1) |
---|
717 | n/a | self.assertRaises(OverflowError, day.__mul__, INF) |
---|
718 | n/a | self.assertRaises(OverflowError, day.__mul__, -INF) |
---|
719 | n/a | |
---|
720 | n/a | def test_microsecond_rounding(self): |
---|
721 | n/a | td = timedelta |
---|
722 | n/a | eq = self.assertEqual |
---|
723 | n/a | |
---|
724 | n/a | # Single-field rounding. |
---|
725 | n/a | eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0 |
---|
726 | n/a | eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0 |
---|
727 | n/a | eq(td(milliseconds=0.5/1000), td(microseconds=0)) |
---|
728 | n/a | eq(td(milliseconds=-0.5/1000), td(microseconds=-0)) |
---|
729 | n/a | eq(td(milliseconds=0.6/1000), td(microseconds=1)) |
---|
730 | n/a | eq(td(milliseconds=-0.6/1000), td(microseconds=-1)) |
---|
731 | n/a | eq(td(milliseconds=1.5/1000), td(microseconds=2)) |
---|
732 | n/a | eq(td(milliseconds=-1.5/1000), td(microseconds=-2)) |
---|
733 | n/a | eq(td(seconds=0.5/10**6), td(microseconds=0)) |
---|
734 | n/a | eq(td(seconds=-0.5/10**6), td(microseconds=-0)) |
---|
735 | n/a | eq(td(seconds=1/2**7), td(microseconds=7812)) |
---|
736 | n/a | eq(td(seconds=-1/2**7), td(microseconds=-7812)) |
---|
737 | n/a | |
---|
738 | n/a | # Rounding due to contributions from more than one field. |
---|
739 | n/a | us_per_hour = 3600e6 |
---|
740 | n/a | us_per_day = us_per_hour * 24 |
---|
741 | n/a | eq(td(days=.4/us_per_day), td(0)) |
---|
742 | n/a | eq(td(hours=.2/us_per_hour), td(0)) |
---|
743 | n/a | eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1)) |
---|
744 | n/a | |
---|
745 | n/a | eq(td(days=-.4/us_per_day), td(0)) |
---|
746 | n/a | eq(td(hours=-.2/us_per_hour), td(0)) |
---|
747 | n/a | eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1)) |
---|
748 | n/a | |
---|
749 | n/a | # Test for a patch in Issue 8860 |
---|
750 | n/a | eq(td(microseconds=0.5), 0.5*td(microseconds=1.0)) |
---|
751 | n/a | eq(td(microseconds=0.5)//td.resolution, 0.5*td.resolution//td.resolution) |
---|
752 | n/a | |
---|
753 | n/a | def test_massive_normalization(self): |
---|
754 | n/a | td = timedelta(microseconds=-1) |
---|
755 | n/a | self.assertEqual((td.days, td.seconds, td.microseconds), |
---|
756 | n/a | (-1, 24*3600-1, 999999)) |
---|
757 | n/a | |
---|
758 | n/a | def test_bool(self): |
---|
759 | n/a | self.assertTrue(timedelta(1)) |
---|
760 | n/a | self.assertTrue(timedelta(0, 1)) |
---|
761 | n/a | self.assertTrue(timedelta(0, 0, 1)) |
---|
762 | n/a | self.assertTrue(timedelta(microseconds=1)) |
---|
763 | n/a | self.assertFalse(timedelta(0)) |
---|
764 | n/a | |
---|
765 | n/a | def test_subclass_timedelta(self): |
---|
766 | n/a | |
---|
767 | n/a | class T(timedelta): |
---|
768 | n/a | @staticmethod |
---|
769 | n/a | def from_td(td): |
---|
770 | n/a | return T(td.days, td.seconds, td.microseconds) |
---|
771 | n/a | |
---|
772 | n/a | def as_hours(self): |
---|
773 | n/a | sum = (self.days * 24 + |
---|
774 | n/a | self.seconds / 3600.0 + |
---|
775 | n/a | self.microseconds / 3600e6) |
---|
776 | n/a | return round(sum) |
---|
777 | n/a | |
---|
778 | n/a | t1 = T(days=1) |
---|
779 | n/a | self.assertIs(type(t1), T) |
---|
780 | n/a | self.assertEqual(t1.as_hours(), 24) |
---|
781 | n/a | |
---|
782 | n/a | t2 = T(days=-1, seconds=-3600) |
---|
783 | n/a | self.assertIs(type(t2), T) |
---|
784 | n/a | self.assertEqual(t2.as_hours(), -25) |
---|
785 | n/a | |
---|
786 | n/a | t3 = t1 + t2 |
---|
787 | n/a | self.assertIs(type(t3), timedelta) |
---|
788 | n/a | t4 = T.from_td(t3) |
---|
789 | n/a | self.assertIs(type(t4), T) |
---|
790 | n/a | self.assertEqual(t3.days, t4.days) |
---|
791 | n/a | self.assertEqual(t3.seconds, t4.seconds) |
---|
792 | n/a | self.assertEqual(t3.microseconds, t4.microseconds) |
---|
793 | n/a | self.assertEqual(str(t3), str(t4)) |
---|
794 | n/a | self.assertEqual(t4.as_hours(), -1) |
---|
795 | n/a | |
---|
796 | n/a | def test_division(self): |
---|
797 | n/a | t = timedelta(hours=1, minutes=24, seconds=19) |
---|
798 | n/a | second = timedelta(seconds=1) |
---|
799 | n/a | self.assertEqual(t / second, 5059.0) |
---|
800 | n/a | self.assertEqual(t // second, 5059) |
---|
801 | n/a | |
---|
802 | n/a | t = timedelta(minutes=2, seconds=30) |
---|
803 | n/a | minute = timedelta(minutes=1) |
---|
804 | n/a | self.assertEqual(t / minute, 2.5) |
---|
805 | n/a | self.assertEqual(t // minute, 2) |
---|
806 | n/a | |
---|
807 | n/a | zerotd = timedelta(0) |
---|
808 | n/a | self.assertRaises(ZeroDivisionError, truediv, t, zerotd) |
---|
809 | n/a | self.assertRaises(ZeroDivisionError, floordiv, t, zerotd) |
---|
810 | n/a | |
---|
811 | n/a | # self.assertRaises(TypeError, truediv, t, 2) |
---|
812 | n/a | # note: floor division of a timedelta by an integer *is* |
---|
813 | n/a | # currently permitted. |
---|
814 | n/a | |
---|
815 | n/a | def test_remainder(self): |
---|
816 | n/a | t = timedelta(minutes=2, seconds=30) |
---|
817 | n/a | minute = timedelta(minutes=1) |
---|
818 | n/a | r = t % minute |
---|
819 | n/a | self.assertEqual(r, timedelta(seconds=30)) |
---|
820 | n/a | |
---|
821 | n/a | t = timedelta(minutes=-2, seconds=30) |
---|
822 | n/a | r = t % minute |
---|
823 | n/a | self.assertEqual(r, timedelta(seconds=30)) |
---|
824 | n/a | |
---|
825 | n/a | zerotd = timedelta(0) |
---|
826 | n/a | self.assertRaises(ZeroDivisionError, mod, t, zerotd) |
---|
827 | n/a | |
---|
828 | n/a | self.assertRaises(TypeError, mod, t, 10) |
---|
829 | n/a | |
---|
830 | n/a | def test_divmod(self): |
---|
831 | n/a | t = timedelta(minutes=2, seconds=30) |
---|
832 | n/a | minute = timedelta(minutes=1) |
---|
833 | n/a | q, r = divmod(t, minute) |
---|
834 | n/a | self.assertEqual(q, 2) |
---|
835 | n/a | self.assertEqual(r, timedelta(seconds=30)) |
---|
836 | n/a | |
---|
837 | n/a | t = timedelta(minutes=-2, seconds=30) |
---|
838 | n/a | q, r = divmod(t, minute) |
---|
839 | n/a | self.assertEqual(q, -2) |
---|
840 | n/a | self.assertEqual(r, timedelta(seconds=30)) |
---|
841 | n/a | |
---|
842 | n/a | zerotd = timedelta(0) |
---|
843 | n/a | self.assertRaises(ZeroDivisionError, divmod, t, zerotd) |
---|
844 | n/a | |
---|
845 | n/a | self.assertRaises(TypeError, divmod, t, 10) |
---|
846 | n/a | |
---|
847 | n/a | |
---|
848 | n/a | ############################################################################# |
---|
849 | n/a | # date tests |
---|
850 | n/a | |
---|
851 | n/a | class TestDateOnly(unittest.TestCase): |
---|
852 | n/a | # Tests here won't pass if also run on datetime objects, so don't |
---|
853 | n/a | # subclass this to test datetimes too. |
---|
854 | n/a | |
---|
855 | n/a | def test_delta_non_days_ignored(self): |
---|
856 | n/a | dt = date(2000, 1, 2) |
---|
857 | n/a | delta = timedelta(days=1, hours=2, minutes=3, seconds=4, |
---|
858 | n/a | microseconds=5) |
---|
859 | n/a | days = timedelta(delta.days) |
---|
860 | n/a | self.assertEqual(days, timedelta(1)) |
---|
861 | n/a | |
---|
862 | n/a | dt2 = dt + delta |
---|
863 | n/a | self.assertEqual(dt2, dt + days) |
---|
864 | n/a | |
---|
865 | n/a | dt2 = delta + dt |
---|
866 | n/a | self.assertEqual(dt2, dt + days) |
---|
867 | n/a | |
---|
868 | n/a | dt2 = dt - delta |
---|
869 | n/a | self.assertEqual(dt2, dt - days) |
---|
870 | n/a | |
---|
871 | n/a | delta = -delta |
---|
872 | n/a | days = timedelta(delta.days) |
---|
873 | n/a | self.assertEqual(days, timedelta(-2)) |
---|
874 | n/a | |
---|
875 | n/a | dt2 = dt + delta |
---|
876 | n/a | self.assertEqual(dt2, dt + days) |
---|
877 | n/a | |
---|
878 | n/a | dt2 = delta + dt |
---|
879 | n/a | self.assertEqual(dt2, dt + days) |
---|
880 | n/a | |
---|
881 | n/a | dt2 = dt - delta |
---|
882 | n/a | self.assertEqual(dt2, dt - days) |
---|
883 | n/a | |
---|
884 | n/a | class SubclassDate(date): |
---|
885 | n/a | sub_var = 1 |
---|
886 | n/a | |
---|
887 | n/a | class TestDate(HarmlessMixedComparison, unittest.TestCase): |
---|
888 | n/a | # Tests here should pass for both dates and datetimes, except for a |
---|
889 | n/a | # few tests that TestDateTime overrides. |
---|
890 | n/a | |
---|
891 | n/a | theclass = date |
---|
892 | n/a | |
---|
893 | n/a | def test_basic_attributes(self): |
---|
894 | n/a | dt = self.theclass(2002, 3, 1) |
---|
895 | n/a | self.assertEqual(dt.year, 2002) |
---|
896 | n/a | self.assertEqual(dt.month, 3) |
---|
897 | n/a | self.assertEqual(dt.day, 1) |
---|
898 | n/a | |
---|
899 | n/a | def test_roundtrip(self): |
---|
900 | n/a | for dt in (self.theclass(1, 2, 3), |
---|
901 | n/a | self.theclass.today()): |
---|
902 | n/a | # Verify dt -> string -> date identity. |
---|
903 | n/a | s = repr(dt) |
---|
904 | n/a | self.assertTrue(s.startswith('datetime.')) |
---|
905 | n/a | s = s[9:] |
---|
906 | n/a | dt2 = eval(s) |
---|
907 | n/a | self.assertEqual(dt, dt2) |
---|
908 | n/a | |
---|
909 | n/a | # Verify identity via reconstructing from pieces. |
---|
910 | n/a | dt2 = self.theclass(dt.year, dt.month, dt.day) |
---|
911 | n/a | self.assertEqual(dt, dt2) |
---|
912 | n/a | |
---|
913 | n/a | def test_ordinal_conversions(self): |
---|
914 | n/a | # Check some fixed values. |
---|
915 | n/a | for y, m, d, n in [(1, 1, 1, 1), # calendar origin |
---|
916 | n/a | (1, 12, 31, 365), |
---|
917 | n/a | (2, 1, 1, 366), |
---|
918 | n/a | # first example from "Calendrical Calculations" |
---|
919 | n/a | (1945, 11, 12, 710347)]: |
---|
920 | n/a | d = self.theclass(y, m, d) |
---|
921 | n/a | self.assertEqual(n, d.toordinal()) |
---|
922 | n/a | fromord = self.theclass.fromordinal(n) |
---|
923 | n/a | self.assertEqual(d, fromord) |
---|
924 | n/a | if hasattr(fromord, "hour"): |
---|
925 | n/a | # if we're checking something fancier than a date, verify |
---|
926 | n/a | # the extra fields have been zeroed out |
---|
927 | n/a | self.assertEqual(fromord.hour, 0) |
---|
928 | n/a | self.assertEqual(fromord.minute, 0) |
---|
929 | n/a | self.assertEqual(fromord.second, 0) |
---|
930 | n/a | self.assertEqual(fromord.microsecond, 0) |
---|
931 | n/a | |
---|
932 | n/a | # Check first and last days of year spottily across the whole |
---|
933 | n/a | # range of years supported. |
---|
934 | n/a | for year in range(MINYEAR, MAXYEAR+1, 7): |
---|
935 | n/a | # Verify (year, 1, 1) -> ordinal -> y, m, d is identity. |
---|
936 | n/a | d = self.theclass(year, 1, 1) |
---|
937 | n/a | n = d.toordinal() |
---|
938 | n/a | d2 = self.theclass.fromordinal(n) |
---|
939 | n/a | self.assertEqual(d, d2) |
---|
940 | n/a | # Verify that moving back a day gets to the end of year-1. |
---|
941 | n/a | if year > 1: |
---|
942 | n/a | d = self.theclass.fromordinal(n-1) |
---|
943 | n/a | d2 = self.theclass(year-1, 12, 31) |
---|
944 | n/a | self.assertEqual(d, d2) |
---|
945 | n/a | self.assertEqual(d2.toordinal(), n-1) |
---|
946 | n/a | |
---|
947 | n/a | # Test every day in a leap-year and a non-leap year. |
---|
948 | n/a | dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] |
---|
949 | n/a | for year, isleap in (2000, True), (2002, False): |
---|
950 | n/a | n = self.theclass(year, 1, 1).toordinal() |
---|
951 | n/a | for month, maxday in zip(range(1, 13), dim): |
---|
952 | n/a | if month == 2 and isleap: |
---|
953 | n/a | maxday += 1 |
---|
954 | n/a | for day in range(1, maxday+1): |
---|
955 | n/a | d = self.theclass(year, month, day) |
---|
956 | n/a | self.assertEqual(d.toordinal(), n) |
---|
957 | n/a | self.assertEqual(d, self.theclass.fromordinal(n)) |
---|
958 | n/a | n += 1 |
---|
959 | n/a | |
---|
960 | n/a | def test_extreme_ordinals(self): |
---|
961 | n/a | a = self.theclass.min |
---|
962 | n/a | a = self.theclass(a.year, a.month, a.day) # get rid of time parts |
---|
963 | n/a | aord = a.toordinal() |
---|
964 | n/a | b = a.fromordinal(aord) |
---|
965 | n/a | self.assertEqual(a, b) |
---|
966 | n/a | |
---|
967 | n/a | self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1)) |
---|
968 | n/a | |
---|
969 | n/a | b = a + timedelta(days=1) |
---|
970 | n/a | self.assertEqual(b.toordinal(), aord + 1) |
---|
971 | n/a | self.assertEqual(b, self.theclass.fromordinal(aord + 1)) |
---|
972 | n/a | |
---|
973 | n/a | a = self.theclass.max |
---|
974 | n/a | a = self.theclass(a.year, a.month, a.day) # get rid of time parts |
---|
975 | n/a | aord = a.toordinal() |
---|
976 | n/a | b = a.fromordinal(aord) |
---|
977 | n/a | self.assertEqual(a, b) |
---|
978 | n/a | |
---|
979 | n/a | self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1)) |
---|
980 | n/a | |
---|
981 | n/a | b = a - timedelta(days=1) |
---|
982 | n/a | self.assertEqual(b.toordinal(), aord - 1) |
---|
983 | n/a | self.assertEqual(b, self.theclass.fromordinal(aord - 1)) |
---|
984 | n/a | |
---|
985 | n/a | def test_bad_constructor_arguments(self): |
---|
986 | n/a | # bad years |
---|
987 | n/a | self.theclass(MINYEAR, 1, 1) # no exception |
---|
988 | n/a | self.theclass(MAXYEAR, 1, 1) # no exception |
---|
989 | n/a | self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) |
---|
990 | n/a | self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) |
---|
991 | n/a | # bad months |
---|
992 | n/a | self.theclass(2000, 1, 1) # no exception |
---|
993 | n/a | self.theclass(2000, 12, 1) # no exception |
---|
994 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 0, 1) |
---|
995 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 13, 1) |
---|
996 | n/a | # bad days |
---|
997 | n/a | self.theclass(2000, 2, 29) # no exception |
---|
998 | n/a | self.theclass(2004, 2, 29) # no exception |
---|
999 | n/a | self.theclass(2400, 2, 29) # no exception |
---|
1000 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 2, 30) |
---|
1001 | n/a | self.assertRaises(ValueError, self.theclass, 2001, 2, 29) |
---|
1002 | n/a | self.assertRaises(ValueError, self.theclass, 2100, 2, 29) |
---|
1003 | n/a | self.assertRaises(ValueError, self.theclass, 1900, 2, 29) |
---|
1004 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 0) |
---|
1005 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 32) |
---|
1006 | n/a | |
---|
1007 | n/a | def test_hash_equality(self): |
---|
1008 | n/a | d = self.theclass(2000, 12, 31) |
---|
1009 | n/a | # same thing |
---|
1010 | n/a | e = self.theclass(2000, 12, 31) |
---|
1011 | n/a | self.assertEqual(d, e) |
---|
1012 | n/a | self.assertEqual(hash(d), hash(e)) |
---|
1013 | n/a | |
---|
1014 | n/a | dic = {d: 1} |
---|
1015 | n/a | dic[e] = 2 |
---|
1016 | n/a | self.assertEqual(len(dic), 1) |
---|
1017 | n/a | self.assertEqual(dic[d], 2) |
---|
1018 | n/a | self.assertEqual(dic[e], 2) |
---|
1019 | n/a | |
---|
1020 | n/a | d = self.theclass(2001, 1, 1) |
---|
1021 | n/a | # same thing |
---|
1022 | n/a | e = self.theclass(2001, 1, 1) |
---|
1023 | n/a | self.assertEqual(d, e) |
---|
1024 | n/a | self.assertEqual(hash(d), hash(e)) |
---|
1025 | n/a | |
---|
1026 | n/a | dic = {d: 1} |
---|
1027 | n/a | dic[e] = 2 |
---|
1028 | n/a | self.assertEqual(len(dic), 1) |
---|
1029 | n/a | self.assertEqual(dic[d], 2) |
---|
1030 | n/a | self.assertEqual(dic[e], 2) |
---|
1031 | n/a | |
---|
1032 | n/a | def test_computations(self): |
---|
1033 | n/a | a = self.theclass(2002, 1, 31) |
---|
1034 | n/a | b = self.theclass(1956, 1, 31) |
---|
1035 | n/a | c = self.theclass(2001,2,1) |
---|
1036 | n/a | |
---|
1037 | n/a | diff = a-b |
---|
1038 | n/a | self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) |
---|
1039 | n/a | self.assertEqual(diff.seconds, 0) |
---|
1040 | n/a | self.assertEqual(diff.microseconds, 0) |
---|
1041 | n/a | |
---|
1042 | n/a | day = timedelta(1) |
---|
1043 | n/a | week = timedelta(7) |
---|
1044 | n/a | a = self.theclass(2002, 3, 2) |
---|
1045 | n/a | self.assertEqual(a + day, self.theclass(2002, 3, 3)) |
---|
1046 | n/a | self.assertEqual(day + a, self.theclass(2002, 3, 3)) |
---|
1047 | n/a | self.assertEqual(a - day, self.theclass(2002, 3, 1)) |
---|
1048 | n/a | self.assertEqual(-day + a, self.theclass(2002, 3, 1)) |
---|
1049 | n/a | self.assertEqual(a + week, self.theclass(2002, 3, 9)) |
---|
1050 | n/a | self.assertEqual(a - week, self.theclass(2002, 2, 23)) |
---|
1051 | n/a | self.assertEqual(a + 52*week, self.theclass(2003, 3, 1)) |
---|
1052 | n/a | self.assertEqual(a - 52*week, self.theclass(2001, 3, 3)) |
---|
1053 | n/a | self.assertEqual((a + week) - a, week) |
---|
1054 | n/a | self.assertEqual((a + day) - a, day) |
---|
1055 | n/a | self.assertEqual((a - week) - a, -week) |
---|
1056 | n/a | self.assertEqual((a - day) - a, -day) |
---|
1057 | n/a | self.assertEqual(a - (a + week), -week) |
---|
1058 | n/a | self.assertEqual(a - (a + day), -day) |
---|
1059 | n/a | self.assertEqual(a - (a - week), week) |
---|
1060 | n/a | self.assertEqual(a - (a - day), day) |
---|
1061 | n/a | self.assertEqual(c - (c - day), day) |
---|
1062 | n/a | |
---|
1063 | n/a | # Add/sub ints or floats should be illegal |
---|
1064 | n/a | for i in 1, 1.0: |
---|
1065 | n/a | self.assertRaises(TypeError, lambda: a+i) |
---|
1066 | n/a | self.assertRaises(TypeError, lambda: a-i) |
---|
1067 | n/a | self.assertRaises(TypeError, lambda: i+a) |
---|
1068 | n/a | self.assertRaises(TypeError, lambda: i-a) |
---|
1069 | n/a | |
---|
1070 | n/a | # delta - date is senseless. |
---|
1071 | n/a | self.assertRaises(TypeError, lambda: day - a) |
---|
1072 | n/a | # mixing date and (delta or date) via * or // is senseless |
---|
1073 | n/a | self.assertRaises(TypeError, lambda: day * a) |
---|
1074 | n/a | self.assertRaises(TypeError, lambda: a * day) |
---|
1075 | n/a | self.assertRaises(TypeError, lambda: day // a) |
---|
1076 | n/a | self.assertRaises(TypeError, lambda: a // day) |
---|
1077 | n/a | self.assertRaises(TypeError, lambda: a * a) |
---|
1078 | n/a | self.assertRaises(TypeError, lambda: a // a) |
---|
1079 | n/a | # date + date is senseless |
---|
1080 | n/a | self.assertRaises(TypeError, lambda: a + a) |
---|
1081 | n/a | |
---|
1082 | n/a | def test_overflow(self): |
---|
1083 | n/a | tiny = self.theclass.resolution |
---|
1084 | n/a | |
---|
1085 | n/a | for delta in [tiny, timedelta(1), timedelta(2)]: |
---|
1086 | n/a | dt = self.theclass.min + delta |
---|
1087 | n/a | dt -= delta # no problem |
---|
1088 | n/a | self.assertRaises(OverflowError, dt.__sub__, delta) |
---|
1089 | n/a | self.assertRaises(OverflowError, dt.__add__, -delta) |
---|
1090 | n/a | |
---|
1091 | n/a | dt = self.theclass.max - delta |
---|
1092 | n/a | dt += delta # no problem |
---|
1093 | n/a | self.assertRaises(OverflowError, dt.__add__, delta) |
---|
1094 | n/a | self.assertRaises(OverflowError, dt.__sub__, -delta) |
---|
1095 | n/a | |
---|
1096 | n/a | def test_fromtimestamp(self): |
---|
1097 | n/a | import time |
---|
1098 | n/a | |
---|
1099 | n/a | # Try an arbitrary fixed value. |
---|
1100 | n/a | year, month, day = 1999, 9, 19 |
---|
1101 | n/a | ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1)) |
---|
1102 | n/a | d = self.theclass.fromtimestamp(ts) |
---|
1103 | n/a | self.assertEqual(d.year, year) |
---|
1104 | n/a | self.assertEqual(d.month, month) |
---|
1105 | n/a | self.assertEqual(d.day, day) |
---|
1106 | n/a | |
---|
1107 | n/a | def test_insane_fromtimestamp(self): |
---|
1108 | n/a | # It's possible that some platform maps time_t to double, |
---|
1109 | n/a | # and that this test will fail there. This test should |
---|
1110 | n/a | # exempt such platforms (provided they return reasonable |
---|
1111 | n/a | # results!). |
---|
1112 | n/a | for insane in -1e200, 1e200: |
---|
1113 | n/a | self.assertRaises(OverflowError, self.theclass.fromtimestamp, |
---|
1114 | n/a | insane) |
---|
1115 | n/a | |
---|
1116 | n/a | def test_today(self): |
---|
1117 | n/a | import time |
---|
1118 | n/a | |
---|
1119 | n/a | # We claim that today() is like fromtimestamp(time.time()), so |
---|
1120 | n/a | # prove it. |
---|
1121 | n/a | for dummy in range(3): |
---|
1122 | n/a | today = self.theclass.today() |
---|
1123 | n/a | ts = time.time() |
---|
1124 | n/a | todayagain = self.theclass.fromtimestamp(ts) |
---|
1125 | n/a | if today == todayagain: |
---|
1126 | n/a | break |
---|
1127 | n/a | # There are several legit reasons that could fail: |
---|
1128 | n/a | # 1. It recently became midnight, between the today() and the |
---|
1129 | n/a | # time() calls. |
---|
1130 | n/a | # 2. The platform time() has such fine resolution that we'll |
---|
1131 | n/a | # never get the same value twice. |
---|
1132 | n/a | # 3. The platform time() has poor resolution, and we just |
---|
1133 | n/a | # happened to call today() right before a resolution quantum |
---|
1134 | n/a | # boundary. |
---|
1135 | n/a | # 4. The system clock got fiddled between calls. |
---|
1136 | n/a | # In any case, wait a little while and try again. |
---|
1137 | n/a | time.sleep(0.1) |
---|
1138 | n/a | |
---|
1139 | n/a | # It worked or it didn't. If it didn't, assume it's reason #2, and |
---|
1140 | n/a | # let the test pass if they're within half a second of each other. |
---|
1141 | n/a | if today != todayagain: |
---|
1142 | n/a | self.assertAlmostEqual(todayagain, today, |
---|
1143 | n/a | delta=timedelta(seconds=0.5)) |
---|
1144 | n/a | |
---|
1145 | n/a | def test_weekday(self): |
---|
1146 | n/a | for i in range(7): |
---|
1147 | n/a | # March 4, 2002 is a Monday |
---|
1148 | n/a | self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i) |
---|
1149 | n/a | self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1) |
---|
1150 | n/a | # January 2, 1956 is a Monday |
---|
1151 | n/a | self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i) |
---|
1152 | n/a | self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1) |
---|
1153 | n/a | |
---|
1154 | n/a | def test_isocalendar(self): |
---|
1155 | n/a | # Check examples from |
---|
1156 | n/a | # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm |
---|
1157 | n/a | for i in range(7): |
---|
1158 | n/a | d = self.theclass(2003, 12, 22+i) |
---|
1159 | n/a | self.assertEqual(d.isocalendar(), (2003, 52, i+1)) |
---|
1160 | n/a | d = self.theclass(2003, 12, 29) + timedelta(i) |
---|
1161 | n/a | self.assertEqual(d.isocalendar(), (2004, 1, i+1)) |
---|
1162 | n/a | d = self.theclass(2004, 1, 5+i) |
---|
1163 | n/a | self.assertEqual(d.isocalendar(), (2004, 2, i+1)) |
---|
1164 | n/a | d = self.theclass(2009, 12, 21+i) |
---|
1165 | n/a | self.assertEqual(d.isocalendar(), (2009, 52, i+1)) |
---|
1166 | n/a | d = self.theclass(2009, 12, 28) + timedelta(i) |
---|
1167 | n/a | self.assertEqual(d.isocalendar(), (2009, 53, i+1)) |
---|
1168 | n/a | d = self.theclass(2010, 1, 4+i) |
---|
1169 | n/a | self.assertEqual(d.isocalendar(), (2010, 1, i+1)) |
---|
1170 | n/a | |
---|
1171 | n/a | def test_iso_long_years(self): |
---|
1172 | n/a | # Calculate long ISO years and compare to table from |
---|
1173 | n/a | # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm |
---|
1174 | n/a | ISO_LONG_YEARS_TABLE = """ |
---|
1175 | n/a | 4 32 60 88 |
---|
1176 | n/a | 9 37 65 93 |
---|
1177 | n/a | 15 43 71 99 |
---|
1178 | n/a | 20 48 76 |
---|
1179 | n/a | 26 54 82 |
---|
1180 | n/a | |
---|
1181 | n/a | 105 133 161 189 |
---|
1182 | n/a | 111 139 167 195 |
---|
1183 | n/a | 116 144 172 |
---|
1184 | n/a | 122 150 178 |
---|
1185 | n/a | 128 156 184 |
---|
1186 | n/a | |
---|
1187 | n/a | 201 229 257 285 |
---|
1188 | n/a | 207 235 263 291 |
---|
1189 | n/a | 212 240 268 296 |
---|
1190 | n/a | 218 246 274 |
---|
1191 | n/a | 224 252 280 |
---|
1192 | n/a | |
---|
1193 | n/a | 303 331 359 387 |
---|
1194 | n/a | 308 336 364 392 |
---|
1195 | n/a | 314 342 370 398 |
---|
1196 | n/a | 320 348 376 |
---|
1197 | n/a | 325 353 381 |
---|
1198 | n/a | """ |
---|
1199 | n/a | iso_long_years = sorted(map(int, ISO_LONG_YEARS_TABLE.split())) |
---|
1200 | n/a | L = [] |
---|
1201 | n/a | for i in range(400): |
---|
1202 | n/a | d = self.theclass(2000+i, 12, 31) |
---|
1203 | n/a | d1 = self.theclass(1600+i, 12, 31) |
---|
1204 | n/a | self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:]) |
---|
1205 | n/a | if d.isocalendar()[1] == 53: |
---|
1206 | n/a | L.append(i) |
---|
1207 | n/a | self.assertEqual(L, iso_long_years) |
---|
1208 | n/a | |
---|
1209 | n/a | def test_isoformat(self): |
---|
1210 | n/a | t = self.theclass(2, 3, 2) |
---|
1211 | n/a | self.assertEqual(t.isoformat(), "0002-03-02") |
---|
1212 | n/a | |
---|
1213 | n/a | def test_ctime(self): |
---|
1214 | n/a | t = self.theclass(2002, 3, 2) |
---|
1215 | n/a | self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002") |
---|
1216 | n/a | |
---|
1217 | n/a | def test_strftime(self): |
---|
1218 | n/a | t = self.theclass(2005, 3, 2) |
---|
1219 | n/a | self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05") |
---|
1220 | n/a | self.assertEqual(t.strftime(""), "") # SF bug #761337 |
---|
1221 | n/a | self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784 |
---|
1222 | n/a | |
---|
1223 | n/a | self.assertRaises(TypeError, t.strftime) # needs an arg |
---|
1224 | n/a | self.assertRaises(TypeError, t.strftime, "one", "two") # too many args |
---|
1225 | n/a | self.assertRaises(TypeError, t.strftime, 42) # arg wrong type |
---|
1226 | n/a | |
---|
1227 | n/a | # test that unicode input is allowed (issue 2782) |
---|
1228 | n/a | self.assertEqual(t.strftime("%m"), "03") |
---|
1229 | n/a | |
---|
1230 | n/a | # A naive object replaces %z and %Z w/ empty strings. |
---|
1231 | n/a | self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") |
---|
1232 | n/a | |
---|
1233 | n/a | #make sure that invalid format specifiers are handled correctly |
---|
1234 | n/a | #self.assertRaises(ValueError, t.strftime, "%e") |
---|
1235 | n/a | #self.assertRaises(ValueError, t.strftime, "%") |
---|
1236 | n/a | #self.assertRaises(ValueError, t.strftime, "%#") |
---|
1237 | n/a | |
---|
1238 | n/a | #oh well, some systems just ignore those invalid ones. |
---|
1239 | n/a | #at least, exercise them to make sure that no crashes |
---|
1240 | n/a | #are generated |
---|
1241 | n/a | for f in ["%e", "%", "%#"]: |
---|
1242 | n/a | try: |
---|
1243 | n/a | t.strftime(f) |
---|
1244 | n/a | except ValueError: |
---|
1245 | n/a | pass |
---|
1246 | n/a | |
---|
1247 | n/a | #check that this standard extension works |
---|
1248 | n/a | t.strftime("%f") |
---|
1249 | n/a | |
---|
1250 | n/a | def test_format(self): |
---|
1251 | n/a | dt = self.theclass(2007, 9, 10) |
---|
1252 | n/a | self.assertEqual(dt.__format__(''), str(dt)) |
---|
1253 | n/a | |
---|
1254 | n/a | with self.assertRaisesRegex(TypeError, 'must be str, not int'): |
---|
1255 | n/a | dt.__format__(123) |
---|
1256 | n/a | |
---|
1257 | n/a | # check that a derived class's __str__() gets called |
---|
1258 | n/a | class A(self.theclass): |
---|
1259 | n/a | def __str__(self): |
---|
1260 | n/a | return 'A' |
---|
1261 | n/a | a = A(2007, 9, 10) |
---|
1262 | n/a | self.assertEqual(a.__format__(''), 'A') |
---|
1263 | n/a | |
---|
1264 | n/a | # check that a derived class's strftime gets called |
---|
1265 | n/a | class B(self.theclass): |
---|
1266 | n/a | def strftime(self, format_spec): |
---|
1267 | n/a | return 'B' |
---|
1268 | n/a | b = B(2007, 9, 10) |
---|
1269 | n/a | self.assertEqual(b.__format__(''), str(dt)) |
---|
1270 | n/a | |
---|
1271 | n/a | for fmt in ["m:%m d:%d y:%y", |
---|
1272 | n/a | "m:%m d:%d y:%y H:%H M:%M S:%S", |
---|
1273 | n/a | "%z %Z", |
---|
1274 | n/a | ]: |
---|
1275 | n/a | self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) |
---|
1276 | n/a | self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) |
---|
1277 | n/a | self.assertEqual(b.__format__(fmt), 'B') |
---|
1278 | n/a | |
---|
1279 | n/a | def test_resolution_info(self): |
---|
1280 | n/a | # XXX: Should min and max respect subclassing? |
---|
1281 | n/a | if issubclass(self.theclass, datetime): |
---|
1282 | n/a | expected_class = datetime |
---|
1283 | n/a | else: |
---|
1284 | n/a | expected_class = date |
---|
1285 | n/a | self.assertIsInstance(self.theclass.min, expected_class) |
---|
1286 | n/a | self.assertIsInstance(self.theclass.max, expected_class) |
---|
1287 | n/a | self.assertIsInstance(self.theclass.resolution, timedelta) |
---|
1288 | n/a | self.assertTrue(self.theclass.max > self.theclass.min) |
---|
1289 | n/a | |
---|
1290 | n/a | def test_extreme_timedelta(self): |
---|
1291 | n/a | big = self.theclass.max - self.theclass.min |
---|
1292 | n/a | # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds |
---|
1293 | n/a | n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds |
---|
1294 | n/a | # n == 315537897599999999 ~= 2**58.13 |
---|
1295 | n/a | justasbig = timedelta(0, 0, n) |
---|
1296 | n/a | self.assertEqual(big, justasbig) |
---|
1297 | n/a | self.assertEqual(self.theclass.min + big, self.theclass.max) |
---|
1298 | n/a | self.assertEqual(self.theclass.max - big, self.theclass.min) |
---|
1299 | n/a | |
---|
1300 | n/a | def test_timetuple(self): |
---|
1301 | n/a | for i in range(7): |
---|
1302 | n/a | # January 2, 1956 is a Monday (0) |
---|
1303 | n/a | d = self.theclass(1956, 1, 2+i) |
---|
1304 | n/a | t = d.timetuple() |
---|
1305 | n/a | self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1)) |
---|
1306 | n/a | # February 1, 1956 is a Wednesday (2) |
---|
1307 | n/a | d = self.theclass(1956, 2, 1+i) |
---|
1308 | n/a | t = d.timetuple() |
---|
1309 | n/a | self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1)) |
---|
1310 | n/a | # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day |
---|
1311 | n/a | # of the year. |
---|
1312 | n/a | d = self.theclass(1956, 3, 1+i) |
---|
1313 | n/a | t = d.timetuple() |
---|
1314 | n/a | self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1)) |
---|
1315 | n/a | self.assertEqual(t.tm_year, 1956) |
---|
1316 | n/a | self.assertEqual(t.tm_mon, 3) |
---|
1317 | n/a | self.assertEqual(t.tm_mday, 1+i) |
---|
1318 | n/a | self.assertEqual(t.tm_hour, 0) |
---|
1319 | n/a | self.assertEqual(t.tm_min, 0) |
---|
1320 | n/a | self.assertEqual(t.tm_sec, 0) |
---|
1321 | n/a | self.assertEqual(t.tm_wday, (3+i)%7) |
---|
1322 | n/a | self.assertEqual(t.tm_yday, 61+i) |
---|
1323 | n/a | self.assertEqual(t.tm_isdst, -1) |
---|
1324 | n/a | |
---|
1325 | n/a | def test_pickling(self): |
---|
1326 | n/a | args = 6, 7, 23 |
---|
1327 | n/a | orig = self.theclass(*args) |
---|
1328 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
1329 | n/a | green = pickler.dumps(orig, proto) |
---|
1330 | n/a | derived = unpickler.loads(green) |
---|
1331 | n/a | self.assertEqual(orig, derived) |
---|
1332 | n/a | self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) |
---|
1333 | n/a | |
---|
1334 | n/a | def test_compare(self): |
---|
1335 | n/a | t1 = self.theclass(2, 3, 4) |
---|
1336 | n/a | t2 = self.theclass(2, 3, 4) |
---|
1337 | n/a | self.assertEqual(t1, t2) |
---|
1338 | n/a | self.assertTrue(t1 <= t2) |
---|
1339 | n/a | self.assertTrue(t1 >= t2) |
---|
1340 | n/a | self.assertFalse(t1 != t2) |
---|
1341 | n/a | self.assertFalse(t1 < t2) |
---|
1342 | n/a | self.assertFalse(t1 > t2) |
---|
1343 | n/a | |
---|
1344 | n/a | for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): |
---|
1345 | n/a | t2 = self.theclass(*args) # this is larger than t1 |
---|
1346 | n/a | self.assertTrue(t1 < t2) |
---|
1347 | n/a | self.assertTrue(t2 > t1) |
---|
1348 | n/a | self.assertTrue(t1 <= t2) |
---|
1349 | n/a | self.assertTrue(t2 >= t1) |
---|
1350 | n/a | self.assertTrue(t1 != t2) |
---|
1351 | n/a | self.assertTrue(t2 != t1) |
---|
1352 | n/a | self.assertFalse(t1 == t2) |
---|
1353 | n/a | self.assertFalse(t2 == t1) |
---|
1354 | n/a | self.assertFalse(t1 > t2) |
---|
1355 | n/a | self.assertFalse(t2 < t1) |
---|
1356 | n/a | self.assertFalse(t1 >= t2) |
---|
1357 | n/a | self.assertFalse(t2 <= t1) |
---|
1358 | n/a | |
---|
1359 | n/a | for badarg in OTHERSTUFF: |
---|
1360 | n/a | self.assertEqual(t1 == badarg, False) |
---|
1361 | n/a | self.assertEqual(t1 != badarg, True) |
---|
1362 | n/a | self.assertEqual(badarg == t1, False) |
---|
1363 | n/a | self.assertEqual(badarg != t1, True) |
---|
1364 | n/a | |
---|
1365 | n/a | self.assertRaises(TypeError, lambda: t1 < badarg) |
---|
1366 | n/a | self.assertRaises(TypeError, lambda: t1 > badarg) |
---|
1367 | n/a | self.assertRaises(TypeError, lambda: t1 >= badarg) |
---|
1368 | n/a | self.assertRaises(TypeError, lambda: badarg <= t1) |
---|
1369 | n/a | self.assertRaises(TypeError, lambda: badarg < t1) |
---|
1370 | n/a | self.assertRaises(TypeError, lambda: badarg > t1) |
---|
1371 | n/a | self.assertRaises(TypeError, lambda: badarg >= t1) |
---|
1372 | n/a | |
---|
1373 | n/a | def test_mixed_compare(self): |
---|
1374 | n/a | our = self.theclass(2000, 4, 5) |
---|
1375 | n/a | |
---|
1376 | n/a | # Our class can be compared for equality to other classes |
---|
1377 | n/a | self.assertEqual(our == 1, False) |
---|
1378 | n/a | self.assertEqual(1 == our, False) |
---|
1379 | n/a | self.assertEqual(our != 1, True) |
---|
1380 | n/a | self.assertEqual(1 != our, True) |
---|
1381 | n/a | |
---|
1382 | n/a | # But the ordering is undefined |
---|
1383 | n/a | self.assertRaises(TypeError, lambda: our < 1) |
---|
1384 | n/a | self.assertRaises(TypeError, lambda: 1 < our) |
---|
1385 | n/a | |
---|
1386 | n/a | # Repeat those tests with a different class |
---|
1387 | n/a | |
---|
1388 | n/a | class SomeClass: |
---|
1389 | n/a | pass |
---|
1390 | n/a | |
---|
1391 | n/a | their = SomeClass() |
---|
1392 | n/a | self.assertEqual(our == their, False) |
---|
1393 | n/a | self.assertEqual(their == our, False) |
---|
1394 | n/a | self.assertEqual(our != their, True) |
---|
1395 | n/a | self.assertEqual(their != our, True) |
---|
1396 | n/a | self.assertRaises(TypeError, lambda: our < their) |
---|
1397 | n/a | self.assertRaises(TypeError, lambda: their < our) |
---|
1398 | n/a | |
---|
1399 | n/a | # However, if the other class explicitly defines ordering |
---|
1400 | n/a | # relative to our class, it is allowed to do so |
---|
1401 | n/a | |
---|
1402 | n/a | class LargerThanAnything: |
---|
1403 | n/a | def __lt__(self, other): |
---|
1404 | n/a | return False |
---|
1405 | n/a | def __le__(self, other): |
---|
1406 | n/a | return isinstance(other, LargerThanAnything) |
---|
1407 | n/a | def __eq__(self, other): |
---|
1408 | n/a | return isinstance(other, LargerThanAnything) |
---|
1409 | n/a | def __gt__(self, other): |
---|
1410 | n/a | return not isinstance(other, LargerThanAnything) |
---|
1411 | n/a | def __ge__(self, other): |
---|
1412 | n/a | return True |
---|
1413 | n/a | |
---|
1414 | n/a | their = LargerThanAnything() |
---|
1415 | n/a | self.assertEqual(our == their, False) |
---|
1416 | n/a | self.assertEqual(their == our, False) |
---|
1417 | n/a | self.assertEqual(our != their, True) |
---|
1418 | n/a | self.assertEqual(their != our, True) |
---|
1419 | n/a | self.assertEqual(our < their, True) |
---|
1420 | n/a | self.assertEqual(their < our, False) |
---|
1421 | n/a | |
---|
1422 | n/a | def test_bool(self): |
---|
1423 | n/a | # All dates are considered true. |
---|
1424 | n/a | self.assertTrue(self.theclass.min) |
---|
1425 | n/a | self.assertTrue(self.theclass.max) |
---|
1426 | n/a | |
---|
1427 | n/a | def test_strftime_y2k(self): |
---|
1428 | n/a | for y in (1, 49, 70, 99, 100, 999, 1000, 1970): |
---|
1429 | n/a | d = self.theclass(y, 1, 1) |
---|
1430 | n/a | # Issue 13305: For years < 1000, the value is not always |
---|
1431 | n/a | # padded to 4 digits across platforms. The C standard |
---|
1432 | n/a | # assumes year >= 1900, so it does not specify the number |
---|
1433 | n/a | # of digits. |
---|
1434 | n/a | if d.strftime("%Y") != '%04d' % y: |
---|
1435 | n/a | # Year 42 returns '42', not padded |
---|
1436 | n/a | self.assertEqual(d.strftime("%Y"), '%d' % y) |
---|
1437 | n/a | # '0042' is obtained anyway |
---|
1438 | n/a | self.assertEqual(d.strftime("%4Y"), '%04d' % y) |
---|
1439 | n/a | |
---|
1440 | n/a | def test_replace(self): |
---|
1441 | n/a | cls = self.theclass |
---|
1442 | n/a | args = [1, 2, 3] |
---|
1443 | n/a | base = cls(*args) |
---|
1444 | n/a | self.assertEqual(base, base.replace()) |
---|
1445 | n/a | |
---|
1446 | n/a | i = 0 |
---|
1447 | n/a | for name, newval in (("year", 2), |
---|
1448 | n/a | ("month", 3), |
---|
1449 | n/a | ("day", 4)): |
---|
1450 | n/a | newargs = args[:] |
---|
1451 | n/a | newargs[i] = newval |
---|
1452 | n/a | expected = cls(*newargs) |
---|
1453 | n/a | got = base.replace(**{name: newval}) |
---|
1454 | n/a | self.assertEqual(expected, got) |
---|
1455 | n/a | i += 1 |
---|
1456 | n/a | |
---|
1457 | n/a | # Out of bounds. |
---|
1458 | n/a | base = cls(2000, 2, 29) |
---|
1459 | n/a | self.assertRaises(ValueError, base.replace, year=2001) |
---|
1460 | n/a | |
---|
1461 | n/a | def test_subclass_date(self): |
---|
1462 | n/a | |
---|
1463 | n/a | class C(self.theclass): |
---|
1464 | n/a | theAnswer = 42 |
---|
1465 | n/a | |
---|
1466 | n/a | def __new__(cls, *args, **kws): |
---|
1467 | n/a | temp = kws.copy() |
---|
1468 | n/a | extra = temp.pop('extra') |
---|
1469 | n/a | result = self.theclass.__new__(cls, *args, **temp) |
---|
1470 | n/a | result.extra = extra |
---|
1471 | n/a | return result |
---|
1472 | n/a | |
---|
1473 | n/a | def newmeth(self, start): |
---|
1474 | n/a | return start + self.year + self.month |
---|
1475 | n/a | |
---|
1476 | n/a | args = 2003, 4, 14 |
---|
1477 | n/a | |
---|
1478 | n/a | dt1 = self.theclass(*args) |
---|
1479 | n/a | dt2 = C(*args, **{'extra': 7}) |
---|
1480 | n/a | |
---|
1481 | n/a | self.assertEqual(dt2.__class__, C) |
---|
1482 | n/a | self.assertEqual(dt2.theAnswer, 42) |
---|
1483 | n/a | self.assertEqual(dt2.extra, 7) |
---|
1484 | n/a | self.assertEqual(dt1.toordinal(), dt2.toordinal()) |
---|
1485 | n/a | self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month - 7) |
---|
1486 | n/a | |
---|
1487 | n/a | def test_pickling_subclass_date(self): |
---|
1488 | n/a | |
---|
1489 | n/a | args = 6, 7, 23 |
---|
1490 | n/a | orig = SubclassDate(*args) |
---|
1491 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
1492 | n/a | green = pickler.dumps(orig, proto) |
---|
1493 | n/a | derived = unpickler.loads(green) |
---|
1494 | n/a | self.assertEqual(orig, derived) |
---|
1495 | n/a | |
---|
1496 | n/a | def test_backdoor_resistance(self): |
---|
1497 | n/a | # For fast unpickling, the constructor accepts a pickle byte string. |
---|
1498 | n/a | # This is a low-overhead backdoor. A user can (by intent or |
---|
1499 | n/a | # mistake) pass a string directly, which (if it's the right length) |
---|
1500 | n/a | # will get treated like a pickle, and bypass the normal sanity |
---|
1501 | n/a | # checks in the constructor. This can create insane objects. |
---|
1502 | n/a | # The constructor doesn't want to burn the time to validate all |
---|
1503 | n/a | # fields, but does check the month field. This stops, e.g., |
---|
1504 | n/a | # datetime.datetime('1995-03-25') from yielding an insane object. |
---|
1505 | n/a | base = b'1995-03-25' |
---|
1506 | n/a | if not issubclass(self.theclass, datetime): |
---|
1507 | n/a | base = base[:4] |
---|
1508 | n/a | for month_byte in b'9', b'\0', b'\r', b'\xff': |
---|
1509 | n/a | self.assertRaises(TypeError, self.theclass, |
---|
1510 | n/a | base[:2] + month_byte + base[3:]) |
---|
1511 | n/a | if issubclass(self.theclass, datetime): |
---|
1512 | n/a | # Good bytes, but bad tzinfo: |
---|
1513 | n/a | with self.assertRaisesRegex(TypeError, '^bad tzinfo state arg$'): |
---|
1514 | n/a | self.theclass(bytes([1] * len(base)), 'EST') |
---|
1515 | n/a | |
---|
1516 | n/a | for ord_byte in range(1, 13): |
---|
1517 | n/a | # This shouldn't blow up because of the month byte alone. If |
---|
1518 | n/a | # the implementation changes to do more-careful checking, it may |
---|
1519 | n/a | # blow up because other fields are insane. |
---|
1520 | n/a | self.theclass(base[:2] + bytes([ord_byte]) + base[3:]) |
---|
1521 | n/a | |
---|
1522 | n/a | ############################################################################# |
---|
1523 | n/a | # datetime tests |
---|
1524 | n/a | |
---|
1525 | n/a | class SubclassDatetime(datetime): |
---|
1526 | n/a | sub_var = 1 |
---|
1527 | n/a | |
---|
1528 | n/a | class TestDateTime(TestDate): |
---|
1529 | n/a | |
---|
1530 | n/a | theclass = datetime |
---|
1531 | n/a | |
---|
1532 | n/a | def test_basic_attributes(self): |
---|
1533 | n/a | dt = self.theclass(2002, 3, 1, 12, 0) |
---|
1534 | n/a | self.assertEqual(dt.year, 2002) |
---|
1535 | n/a | self.assertEqual(dt.month, 3) |
---|
1536 | n/a | self.assertEqual(dt.day, 1) |
---|
1537 | n/a | self.assertEqual(dt.hour, 12) |
---|
1538 | n/a | self.assertEqual(dt.minute, 0) |
---|
1539 | n/a | self.assertEqual(dt.second, 0) |
---|
1540 | n/a | self.assertEqual(dt.microsecond, 0) |
---|
1541 | n/a | |
---|
1542 | n/a | def test_basic_attributes_nonzero(self): |
---|
1543 | n/a | # Make sure all attributes are non-zero so bugs in |
---|
1544 | n/a | # bit-shifting access show up. |
---|
1545 | n/a | dt = self.theclass(2002, 3, 1, 12, 59, 59, 8000) |
---|
1546 | n/a | self.assertEqual(dt.year, 2002) |
---|
1547 | n/a | self.assertEqual(dt.month, 3) |
---|
1548 | n/a | self.assertEqual(dt.day, 1) |
---|
1549 | n/a | self.assertEqual(dt.hour, 12) |
---|
1550 | n/a | self.assertEqual(dt.minute, 59) |
---|
1551 | n/a | self.assertEqual(dt.second, 59) |
---|
1552 | n/a | self.assertEqual(dt.microsecond, 8000) |
---|
1553 | n/a | |
---|
1554 | n/a | def test_roundtrip(self): |
---|
1555 | n/a | for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7), |
---|
1556 | n/a | self.theclass.now()): |
---|
1557 | n/a | # Verify dt -> string -> datetime identity. |
---|
1558 | n/a | s = repr(dt) |
---|
1559 | n/a | self.assertTrue(s.startswith('datetime.')) |
---|
1560 | n/a | s = s[9:] |
---|
1561 | n/a | dt2 = eval(s) |
---|
1562 | n/a | self.assertEqual(dt, dt2) |
---|
1563 | n/a | |
---|
1564 | n/a | # Verify identity via reconstructing from pieces. |
---|
1565 | n/a | dt2 = self.theclass(dt.year, dt.month, dt.day, |
---|
1566 | n/a | dt.hour, dt.minute, dt.second, |
---|
1567 | n/a | dt.microsecond) |
---|
1568 | n/a | self.assertEqual(dt, dt2) |
---|
1569 | n/a | |
---|
1570 | n/a | def test_isoformat(self): |
---|
1571 | n/a | t = self.theclass(1, 2, 3, 4, 5, 1, 123) |
---|
1572 | n/a | self.assertEqual(t.isoformat(), "0001-02-03T04:05:01.000123") |
---|
1573 | n/a | self.assertEqual(t.isoformat('T'), "0001-02-03T04:05:01.000123") |
---|
1574 | n/a | self.assertEqual(t.isoformat(' '), "0001-02-03 04:05:01.000123") |
---|
1575 | n/a | self.assertEqual(t.isoformat('\x00'), "0001-02-03\x0004:05:01.000123") |
---|
1576 | n/a | self.assertEqual(t.isoformat(timespec='hours'), "0001-02-03T04") |
---|
1577 | n/a | self.assertEqual(t.isoformat(timespec='minutes'), "0001-02-03T04:05") |
---|
1578 | n/a | self.assertEqual(t.isoformat(timespec='seconds'), "0001-02-03T04:05:01") |
---|
1579 | n/a | self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.000") |
---|
1580 | n/a | self.assertEqual(t.isoformat(timespec='microseconds'), "0001-02-03T04:05:01.000123") |
---|
1581 | n/a | self.assertEqual(t.isoformat(timespec='auto'), "0001-02-03T04:05:01.000123") |
---|
1582 | n/a | self.assertEqual(t.isoformat(sep=' ', timespec='minutes'), "0001-02-03 04:05") |
---|
1583 | n/a | self.assertRaises(ValueError, t.isoformat, timespec='foo') |
---|
1584 | n/a | # str is ISO format with the separator forced to a blank. |
---|
1585 | n/a | self.assertEqual(str(t), "0001-02-03 04:05:01.000123") |
---|
1586 | n/a | |
---|
1587 | n/a | t = self.theclass(1, 2, 3, 4, 5, 1, 999500, tzinfo=timezone.utc) |
---|
1588 | n/a | self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.999+00:00") |
---|
1589 | n/a | |
---|
1590 | n/a | t = self.theclass(1, 2, 3, 4, 5, 1, 999500) |
---|
1591 | n/a | self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.999") |
---|
1592 | n/a | |
---|
1593 | n/a | t = self.theclass(1, 2, 3, 4, 5, 1) |
---|
1594 | n/a | self.assertEqual(t.isoformat(timespec='auto'), "0001-02-03T04:05:01") |
---|
1595 | n/a | self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.000") |
---|
1596 | n/a | self.assertEqual(t.isoformat(timespec='microseconds'), "0001-02-03T04:05:01.000000") |
---|
1597 | n/a | |
---|
1598 | n/a | t = self.theclass(2, 3, 2) |
---|
1599 | n/a | self.assertEqual(t.isoformat(), "0002-03-02T00:00:00") |
---|
1600 | n/a | self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00") |
---|
1601 | n/a | self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00") |
---|
1602 | n/a | # str is ISO format with the separator forced to a blank. |
---|
1603 | n/a | self.assertEqual(str(t), "0002-03-02 00:00:00") |
---|
1604 | n/a | # ISO format with timezone |
---|
1605 | n/a | tz = FixedOffset(timedelta(seconds=16), 'XXX') |
---|
1606 | n/a | t = self.theclass(2, 3, 2, tzinfo=tz) |
---|
1607 | n/a | self.assertEqual(t.isoformat(), "0002-03-02T00:00:00+00:00:16") |
---|
1608 | n/a | |
---|
1609 | n/a | def test_format(self): |
---|
1610 | n/a | dt = self.theclass(2007, 9, 10, 4, 5, 1, 123) |
---|
1611 | n/a | self.assertEqual(dt.__format__(''), str(dt)) |
---|
1612 | n/a | |
---|
1613 | n/a | with self.assertRaisesRegex(TypeError, 'must be str, not int'): |
---|
1614 | n/a | dt.__format__(123) |
---|
1615 | n/a | |
---|
1616 | n/a | # check that a derived class's __str__() gets called |
---|
1617 | n/a | class A(self.theclass): |
---|
1618 | n/a | def __str__(self): |
---|
1619 | n/a | return 'A' |
---|
1620 | n/a | a = A(2007, 9, 10, 4, 5, 1, 123) |
---|
1621 | n/a | self.assertEqual(a.__format__(''), 'A') |
---|
1622 | n/a | |
---|
1623 | n/a | # check that a derived class's strftime gets called |
---|
1624 | n/a | class B(self.theclass): |
---|
1625 | n/a | def strftime(self, format_spec): |
---|
1626 | n/a | return 'B' |
---|
1627 | n/a | b = B(2007, 9, 10, 4, 5, 1, 123) |
---|
1628 | n/a | self.assertEqual(b.__format__(''), str(dt)) |
---|
1629 | n/a | |
---|
1630 | n/a | for fmt in ["m:%m d:%d y:%y", |
---|
1631 | n/a | "m:%m d:%d y:%y H:%H M:%M S:%S", |
---|
1632 | n/a | "%z %Z", |
---|
1633 | n/a | ]: |
---|
1634 | n/a | self.assertEqual(dt.__format__(fmt), dt.strftime(fmt)) |
---|
1635 | n/a | self.assertEqual(a.__format__(fmt), dt.strftime(fmt)) |
---|
1636 | n/a | self.assertEqual(b.__format__(fmt), 'B') |
---|
1637 | n/a | |
---|
1638 | n/a | def test_more_ctime(self): |
---|
1639 | n/a | # Test fields that TestDate doesn't touch. |
---|
1640 | n/a | import time |
---|
1641 | n/a | |
---|
1642 | n/a | t = self.theclass(2002, 3, 2, 18, 3, 5, 123) |
---|
1643 | n/a | self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002") |
---|
1644 | n/a | # Oops! The next line fails on Win2K under MSVC 6, so it's commented |
---|
1645 | n/a | # out. The difference is that t.ctime() produces " 2" for the day, |
---|
1646 | n/a | # but platform ctime() produces "02" for the day. According to |
---|
1647 | n/a | # C99, t.ctime() is correct here. |
---|
1648 | n/a | # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple()))) |
---|
1649 | n/a | |
---|
1650 | n/a | # So test a case where that difference doesn't matter. |
---|
1651 | n/a | t = self.theclass(2002, 3, 22, 18, 3, 5, 123) |
---|
1652 | n/a | self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple()))) |
---|
1653 | n/a | |
---|
1654 | n/a | def test_tz_independent_comparing(self): |
---|
1655 | n/a | dt1 = self.theclass(2002, 3, 1, 9, 0, 0) |
---|
1656 | n/a | dt2 = self.theclass(2002, 3, 1, 10, 0, 0) |
---|
1657 | n/a | dt3 = self.theclass(2002, 3, 1, 9, 0, 0) |
---|
1658 | n/a | self.assertEqual(dt1, dt3) |
---|
1659 | n/a | self.assertTrue(dt2 > dt3) |
---|
1660 | n/a | |
---|
1661 | n/a | # Make sure comparison doesn't forget microseconds, and isn't done |
---|
1662 | n/a | # via comparing a float timestamp (an IEEE double doesn't have enough |
---|
1663 | n/a | # precision to span microsecond resolution across years 1 thru 9999, |
---|
1664 | n/a | # so comparing via timestamp necessarily calls some distinct values |
---|
1665 | n/a | # equal). |
---|
1666 | n/a | dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998) |
---|
1667 | n/a | us = timedelta(microseconds=1) |
---|
1668 | n/a | dt2 = dt1 + us |
---|
1669 | n/a | self.assertEqual(dt2 - dt1, us) |
---|
1670 | n/a | self.assertTrue(dt1 < dt2) |
---|
1671 | n/a | |
---|
1672 | n/a | def test_strftime_with_bad_tzname_replace(self): |
---|
1673 | n/a | # verify ok if tzinfo.tzname().replace() returns a non-string |
---|
1674 | n/a | class MyTzInfo(FixedOffset): |
---|
1675 | n/a | def tzname(self, dt): |
---|
1676 | n/a | class MyStr(str): |
---|
1677 | n/a | def replace(self, *args): |
---|
1678 | n/a | return None |
---|
1679 | n/a | return MyStr('name') |
---|
1680 | n/a | t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name')) |
---|
1681 | n/a | self.assertRaises(TypeError, t.strftime, '%Z') |
---|
1682 | n/a | |
---|
1683 | n/a | def test_bad_constructor_arguments(self): |
---|
1684 | n/a | # bad years |
---|
1685 | n/a | self.theclass(MINYEAR, 1, 1) # no exception |
---|
1686 | n/a | self.theclass(MAXYEAR, 1, 1) # no exception |
---|
1687 | n/a | self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) |
---|
1688 | n/a | self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) |
---|
1689 | n/a | # bad months |
---|
1690 | n/a | self.theclass(2000, 1, 1) # no exception |
---|
1691 | n/a | self.theclass(2000, 12, 1) # no exception |
---|
1692 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 0, 1) |
---|
1693 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 13, 1) |
---|
1694 | n/a | # bad days |
---|
1695 | n/a | self.theclass(2000, 2, 29) # no exception |
---|
1696 | n/a | self.theclass(2004, 2, 29) # no exception |
---|
1697 | n/a | self.theclass(2400, 2, 29) # no exception |
---|
1698 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 2, 30) |
---|
1699 | n/a | self.assertRaises(ValueError, self.theclass, 2001, 2, 29) |
---|
1700 | n/a | self.assertRaises(ValueError, self.theclass, 2100, 2, 29) |
---|
1701 | n/a | self.assertRaises(ValueError, self.theclass, 1900, 2, 29) |
---|
1702 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 0) |
---|
1703 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 32) |
---|
1704 | n/a | # bad hours |
---|
1705 | n/a | self.theclass(2000, 1, 31, 0) # no exception |
---|
1706 | n/a | self.theclass(2000, 1, 31, 23) # no exception |
---|
1707 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1) |
---|
1708 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24) |
---|
1709 | n/a | # bad minutes |
---|
1710 | n/a | self.theclass(2000, 1, 31, 23, 0) # no exception |
---|
1711 | n/a | self.theclass(2000, 1, 31, 23, 59) # no exception |
---|
1712 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1) |
---|
1713 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60) |
---|
1714 | n/a | # bad seconds |
---|
1715 | n/a | self.theclass(2000, 1, 31, 23, 59, 0) # no exception |
---|
1716 | n/a | self.theclass(2000, 1, 31, 23, 59, 59) # no exception |
---|
1717 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1) |
---|
1718 | n/a | self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60) |
---|
1719 | n/a | # bad microseconds |
---|
1720 | n/a | self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception |
---|
1721 | n/a | self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception |
---|
1722 | n/a | self.assertRaises(ValueError, self.theclass, |
---|
1723 | n/a | 2000, 1, 31, 23, 59, 59, -1) |
---|
1724 | n/a | self.assertRaises(ValueError, self.theclass, |
---|
1725 | n/a | 2000, 1, 31, 23, 59, 59, |
---|
1726 | n/a | 1000000) |
---|
1727 | n/a | # bad fold |
---|
1728 | n/a | self.assertRaises(ValueError, self.theclass, |
---|
1729 | n/a | 2000, 1, 31, fold=-1) |
---|
1730 | n/a | self.assertRaises(ValueError, self.theclass, |
---|
1731 | n/a | 2000, 1, 31, fold=2) |
---|
1732 | n/a | # Positional fold: |
---|
1733 | n/a | self.assertRaises(TypeError, self.theclass, |
---|
1734 | n/a | 2000, 1, 31, 23, 59, 59, 0, None, 1) |
---|
1735 | n/a | |
---|
1736 | n/a | def test_hash_equality(self): |
---|
1737 | n/a | d = self.theclass(2000, 12, 31, 23, 30, 17) |
---|
1738 | n/a | e = self.theclass(2000, 12, 31, 23, 30, 17) |
---|
1739 | n/a | self.assertEqual(d, e) |
---|
1740 | n/a | self.assertEqual(hash(d), hash(e)) |
---|
1741 | n/a | |
---|
1742 | n/a | dic = {d: 1} |
---|
1743 | n/a | dic[e] = 2 |
---|
1744 | n/a | self.assertEqual(len(dic), 1) |
---|
1745 | n/a | self.assertEqual(dic[d], 2) |
---|
1746 | n/a | self.assertEqual(dic[e], 2) |
---|
1747 | n/a | |
---|
1748 | n/a | d = self.theclass(2001, 1, 1, 0, 5, 17) |
---|
1749 | n/a | e = self.theclass(2001, 1, 1, 0, 5, 17) |
---|
1750 | n/a | self.assertEqual(d, e) |
---|
1751 | n/a | self.assertEqual(hash(d), hash(e)) |
---|
1752 | n/a | |
---|
1753 | n/a | dic = {d: 1} |
---|
1754 | n/a | dic[e] = 2 |
---|
1755 | n/a | self.assertEqual(len(dic), 1) |
---|
1756 | n/a | self.assertEqual(dic[d], 2) |
---|
1757 | n/a | self.assertEqual(dic[e], 2) |
---|
1758 | n/a | |
---|
1759 | n/a | def test_computations(self): |
---|
1760 | n/a | a = self.theclass(2002, 1, 31) |
---|
1761 | n/a | b = self.theclass(1956, 1, 31) |
---|
1762 | n/a | diff = a-b |
---|
1763 | n/a | self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) |
---|
1764 | n/a | self.assertEqual(diff.seconds, 0) |
---|
1765 | n/a | self.assertEqual(diff.microseconds, 0) |
---|
1766 | n/a | a = self.theclass(2002, 3, 2, 17, 6) |
---|
1767 | n/a | millisec = timedelta(0, 0, 1000) |
---|
1768 | n/a | hour = timedelta(0, 3600) |
---|
1769 | n/a | day = timedelta(1) |
---|
1770 | n/a | week = timedelta(7) |
---|
1771 | n/a | self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6)) |
---|
1772 | n/a | self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6)) |
---|
1773 | n/a | self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6)) |
---|
1774 | n/a | self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6)) |
---|
1775 | n/a | self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6)) |
---|
1776 | n/a | self.assertEqual(a - hour, a + -hour) |
---|
1777 | n/a | self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6)) |
---|
1778 | n/a | self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6)) |
---|
1779 | n/a | self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6)) |
---|
1780 | n/a | self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6)) |
---|
1781 | n/a | self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6)) |
---|
1782 | n/a | self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6)) |
---|
1783 | n/a | self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6)) |
---|
1784 | n/a | self.assertEqual((a + week) - a, week) |
---|
1785 | n/a | self.assertEqual((a + day) - a, day) |
---|
1786 | n/a | self.assertEqual((a + hour) - a, hour) |
---|
1787 | n/a | self.assertEqual((a + millisec) - a, millisec) |
---|
1788 | n/a | self.assertEqual((a - week) - a, -week) |
---|
1789 | n/a | self.assertEqual((a - day) - a, -day) |
---|
1790 | n/a | self.assertEqual((a - hour) - a, -hour) |
---|
1791 | n/a | self.assertEqual((a - millisec) - a, -millisec) |
---|
1792 | n/a | self.assertEqual(a - (a + week), -week) |
---|
1793 | n/a | self.assertEqual(a - (a + day), -day) |
---|
1794 | n/a | self.assertEqual(a - (a + hour), -hour) |
---|
1795 | n/a | self.assertEqual(a - (a + millisec), -millisec) |
---|
1796 | n/a | self.assertEqual(a - (a - week), week) |
---|
1797 | n/a | self.assertEqual(a - (a - day), day) |
---|
1798 | n/a | self.assertEqual(a - (a - hour), hour) |
---|
1799 | n/a | self.assertEqual(a - (a - millisec), millisec) |
---|
1800 | n/a | self.assertEqual(a + (week + day + hour + millisec), |
---|
1801 | n/a | self.theclass(2002, 3, 10, 18, 6, 0, 1000)) |
---|
1802 | n/a | self.assertEqual(a + (week + day + hour + millisec), |
---|
1803 | n/a | (((a + week) + day) + hour) + millisec) |
---|
1804 | n/a | self.assertEqual(a - (week + day + hour + millisec), |
---|
1805 | n/a | self.theclass(2002, 2, 22, 16, 5, 59, 999000)) |
---|
1806 | n/a | self.assertEqual(a - (week + day + hour + millisec), |
---|
1807 | n/a | (((a - week) - day) - hour) - millisec) |
---|
1808 | n/a | # Add/sub ints or floats should be illegal |
---|
1809 | n/a | for i in 1, 1.0: |
---|
1810 | n/a | self.assertRaises(TypeError, lambda: a+i) |
---|
1811 | n/a | self.assertRaises(TypeError, lambda: a-i) |
---|
1812 | n/a | self.assertRaises(TypeError, lambda: i+a) |
---|
1813 | n/a | self.assertRaises(TypeError, lambda: i-a) |
---|
1814 | n/a | |
---|
1815 | n/a | # delta - datetime is senseless. |
---|
1816 | n/a | self.assertRaises(TypeError, lambda: day - a) |
---|
1817 | n/a | # mixing datetime and (delta or datetime) via * or // is senseless |
---|
1818 | n/a | self.assertRaises(TypeError, lambda: day * a) |
---|
1819 | n/a | self.assertRaises(TypeError, lambda: a * day) |
---|
1820 | n/a | self.assertRaises(TypeError, lambda: day // a) |
---|
1821 | n/a | self.assertRaises(TypeError, lambda: a // day) |
---|
1822 | n/a | self.assertRaises(TypeError, lambda: a * a) |
---|
1823 | n/a | self.assertRaises(TypeError, lambda: a // a) |
---|
1824 | n/a | # datetime + datetime is senseless |
---|
1825 | n/a | self.assertRaises(TypeError, lambda: a + a) |
---|
1826 | n/a | |
---|
1827 | n/a | def test_pickling(self): |
---|
1828 | n/a | args = 6, 7, 23, 20, 59, 1, 64**2 |
---|
1829 | n/a | orig = self.theclass(*args) |
---|
1830 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
1831 | n/a | green = pickler.dumps(orig, proto) |
---|
1832 | n/a | derived = unpickler.loads(green) |
---|
1833 | n/a | self.assertEqual(orig, derived) |
---|
1834 | n/a | self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) |
---|
1835 | n/a | |
---|
1836 | n/a | def test_more_pickling(self): |
---|
1837 | n/a | a = self.theclass(2003, 2, 7, 16, 48, 37, 444116) |
---|
1838 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1839 | n/a | s = pickle.dumps(a, proto) |
---|
1840 | n/a | b = pickle.loads(s) |
---|
1841 | n/a | self.assertEqual(b.year, 2003) |
---|
1842 | n/a | self.assertEqual(b.month, 2) |
---|
1843 | n/a | self.assertEqual(b.day, 7) |
---|
1844 | n/a | |
---|
1845 | n/a | def test_pickling_subclass_datetime(self): |
---|
1846 | n/a | args = 6, 7, 23, 20, 59, 1, 64**2 |
---|
1847 | n/a | orig = SubclassDatetime(*args) |
---|
1848 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
1849 | n/a | green = pickler.dumps(orig, proto) |
---|
1850 | n/a | derived = unpickler.loads(green) |
---|
1851 | n/a | self.assertEqual(orig, derived) |
---|
1852 | n/a | |
---|
1853 | n/a | def test_more_compare(self): |
---|
1854 | n/a | # The test_compare() inherited from TestDate covers the error cases. |
---|
1855 | n/a | # We just want to test lexicographic ordering on the members datetime |
---|
1856 | n/a | # has that date lacks. |
---|
1857 | n/a | args = [2000, 11, 29, 20, 58, 16, 999998] |
---|
1858 | n/a | t1 = self.theclass(*args) |
---|
1859 | n/a | t2 = self.theclass(*args) |
---|
1860 | n/a | self.assertEqual(t1, t2) |
---|
1861 | n/a | self.assertTrue(t1 <= t2) |
---|
1862 | n/a | self.assertTrue(t1 >= t2) |
---|
1863 | n/a | self.assertFalse(t1 != t2) |
---|
1864 | n/a | self.assertFalse(t1 < t2) |
---|
1865 | n/a | self.assertFalse(t1 > t2) |
---|
1866 | n/a | |
---|
1867 | n/a | for i in range(len(args)): |
---|
1868 | n/a | newargs = args[:] |
---|
1869 | n/a | newargs[i] = args[i] + 1 |
---|
1870 | n/a | t2 = self.theclass(*newargs) # this is larger than t1 |
---|
1871 | n/a | self.assertTrue(t1 < t2) |
---|
1872 | n/a | self.assertTrue(t2 > t1) |
---|
1873 | n/a | self.assertTrue(t1 <= t2) |
---|
1874 | n/a | self.assertTrue(t2 >= t1) |
---|
1875 | n/a | self.assertTrue(t1 != t2) |
---|
1876 | n/a | self.assertTrue(t2 != t1) |
---|
1877 | n/a | self.assertFalse(t1 == t2) |
---|
1878 | n/a | self.assertFalse(t2 == t1) |
---|
1879 | n/a | self.assertFalse(t1 > t2) |
---|
1880 | n/a | self.assertFalse(t2 < t1) |
---|
1881 | n/a | self.assertFalse(t1 >= t2) |
---|
1882 | n/a | self.assertFalse(t2 <= t1) |
---|
1883 | n/a | |
---|
1884 | n/a | |
---|
1885 | n/a | # A helper for timestamp constructor tests. |
---|
1886 | n/a | def verify_field_equality(self, expected, got): |
---|
1887 | n/a | self.assertEqual(expected.tm_year, got.year) |
---|
1888 | n/a | self.assertEqual(expected.tm_mon, got.month) |
---|
1889 | n/a | self.assertEqual(expected.tm_mday, got.day) |
---|
1890 | n/a | self.assertEqual(expected.tm_hour, got.hour) |
---|
1891 | n/a | self.assertEqual(expected.tm_min, got.minute) |
---|
1892 | n/a | self.assertEqual(expected.tm_sec, got.second) |
---|
1893 | n/a | |
---|
1894 | n/a | def test_fromtimestamp(self): |
---|
1895 | n/a | import time |
---|
1896 | n/a | |
---|
1897 | n/a | ts = time.time() |
---|
1898 | n/a | expected = time.localtime(ts) |
---|
1899 | n/a | got = self.theclass.fromtimestamp(ts) |
---|
1900 | n/a | self.verify_field_equality(expected, got) |
---|
1901 | n/a | |
---|
1902 | n/a | def test_utcfromtimestamp(self): |
---|
1903 | n/a | import time |
---|
1904 | n/a | |
---|
1905 | n/a | ts = time.time() |
---|
1906 | n/a | expected = time.gmtime(ts) |
---|
1907 | n/a | got = self.theclass.utcfromtimestamp(ts) |
---|
1908 | n/a | self.verify_field_equality(expected, got) |
---|
1909 | n/a | |
---|
1910 | n/a | # Run with US-style DST rules: DST begins 2 a.m. on second Sunday in |
---|
1911 | n/a | # March (M3.2.0) and ends 2 a.m. on first Sunday in November (M11.1.0). |
---|
1912 | n/a | @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') |
---|
1913 | n/a | def test_timestamp_naive(self): |
---|
1914 | n/a | t = self.theclass(1970, 1, 1) |
---|
1915 | n/a | self.assertEqual(t.timestamp(), 18000.0) |
---|
1916 | n/a | t = self.theclass(1970, 1, 1, 1, 2, 3, 4) |
---|
1917 | n/a | self.assertEqual(t.timestamp(), |
---|
1918 | n/a | 18000.0 + 3600 + 2*60 + 3 + 4*1e-6) |
---|
1919 | n/a | # Missing hour |
---|
1920 | n/a | t0 = self.theclass(2012, 3, 11, 2, 30) |
---|
1921 | n/a | t1 = t0.replace(fold=1) |
---|
1922 | n/a | self.assertEqual(self.theclass.fromtimestamp(t1.timestamp()), |
---|
1923 | n/a | t0 - timedelta(hours=1)) |
---|
1924 | n/a | self.assertEqual(self.theclass.fromtimestamp(t0.timestamp()), |
---|
1925 | n/a | t1 + timedelta(hours=1)) |
---|
1926 | n/a | # Ambiguous hour defaults to DST |
---|
1927 | n/a | t = self.theclass(2012, 11, 4, 1, 30) |
---|
1928 | n/a | self.assertEqual(self.theclass.fromtimestamp(t.timestamp()), t) |
---|
1929 | n/a | |
---|
1930 | n/a | # Timestamp may raise an overflow error on some platforms |
---|
1931 | n/a | # XXX: Do we care to support the first and last year? |
---|
1932 | n/a | for t in [self.theclass(2,1,1), self.theclass(9998,12,12)]: |
---|
1933 | n/a | try: |
---|
1934 | n/a | s = t.timestamp() |
---|
1935 | n/a | except OverflowError: |
---|
1936 | n/a | pass |
---|
1937 | n/a | else: |
---|
1938 | n/a | self.assertEqual(self.theclass.fromtimestamp(s), t) |
---|
1939 | n/a | |
---|
1940 | n/a | def test_timestamp_aware(self): |
---|
1941 | n/a | t = self.theclass(1970, 1, 1, tzinfo=timezone.utc) |
---|
1942 | n/a | self.assertEqual(t.timestamp(), 0.0) |
---|
1943 | n/a | t = self.theclass(1970, 1, 1, 1, 2, 3, 4, tzinfo=timezone.utc) |
---|
1944 | n/a | self.assertEqual(t.timestamp(), |
---|
1945 | n/a | 3600 + 2*60 + 3 + 4*1e-6) |
---|
1946 | n/a | t = self.theclass(1970, 1, 1, 1, 2, 3, 4, |
---|
1947 | n/a | tzinfo=timezone(timedelta(hours=-5), 'EST')) |
---|
1948 | n/a | self.assertEqual(t.timestamp(), |
---|
1949 | n/a | 18000 + 3600 + 2*60 + 3 + 4*1e-6) |
---|
1950 | n/a | |
---|
1951 | n/a | @support.run_with_tz('MSK-03') # Something east of Greenwich |
---|
1952 | n/a | def test_microsecond_rounding(self): |
---|
1953 | n/a | for fts in [self.theclass.fromtimestamp, |
---|
1954 | n/a | self.theclass.utcfromtimestamp]: |
---|
1955 | n/a | zero = fts(0) |
---|
1956 | n/a | self.assertEqual(zero.second, 0) |
---|
1957 | n/a | self.assertEqual(zero.microsecond, 0) |
---|
1958 | n/a | one = fts(1e-6) |
---|
1959 | n/a | try: |
---|
1960 | n/a | minus_one = fts(-1e-6) |
---|
1961 | n/a | except OSError: |
---|
1962 | n/a | # localtime(-1) and gmtime(-1) is not supported on Windows |
---|
1963 | n/a | pass |
---|
1964 | n/a | else: |
---|
1965 | n/a | self.assertEqual(minus_one.second, 59) |
---|
1966 | n/a | self.assertEqual(minus_one.microsecond, 999999) |
---|
1967 | n/a | |
---|
1968 | n/a | t = fts(-1e-8) |
---|
1969 | n/a | self.assertEqual(t, zero) |
---|
1970 | n/a | t = fts(-9e-7) |
---|
1971 | n/a | self.assertEqual(t, minus_one) |
---|
1972 | n/a | t = fts(-1e-7) |
---|
1973 | n/a | self.assertEqual(t, zero) |
---|
1974 | n/a | t = fts(-1/2**7) |
---|
1975 | n/a | self.assertEqual(t.second, 59) |
---|
1976 | n/a | self.assertEqual(t.microsecond, 992188) |
---|
1977 | n/a | |
---|
1978 | n/a | t = fts(1e-7) |
---|
1979 | n/a | self.assertEqual(t, zero) |
---|
1980 | n/a | t = fts(9e-7) |
---|
1981 | n/a | self.assertEqual(t, one) |
---|
1982 | n/a | t = fts(0.99999949) |
---|
1983 | n/a | self.assertEqual(t.second, 0) |
---|
1984 | n/a | self.assertEqual(t.microsecond, 999999) |
---|
1985 | n/a | t = fts(0.9999999) |
---|
1986 | n/a | self.assertEqual(t.second, 1) |
---|
1987 | n/a | self.assertEqual(t.microsecond, 0) |
---|
1988 | n/a | t = fts(1/2**7) |
---|
1989 | n/a | self.assertEqual(t.second, 0) |
---|
1990 | n/a | self.assertEqual(t.microsecond, 7812) |
---|
1991 | n/a | |
---|
1992 | n/a | def test_timestamp_limits(self): |
---|
1993 | n/a | # minimum timestamp |
---|
1994 | n/a | min_dt = self.theclass.min.replace(tzinfo=timezone.utc) |
---|
1995 | n/a | min_ts = min_dt.timestamp() |
---|
1996 | n/a | try: |
---|
1997 | n/a | # date 0001-01-01 00:00:00+00:00: timestamp=-62135596800 |
---|
1998 | n/a | self.assertEqual(self.theclass.fromtimestamp(min_ts, tz=timezone.utc), |
---|
1999 | n/a | min_dt) |
---|
2000 | n/a | except (OverflowError, OSError) as exc: |
---|
2001 | n/a | # the date 0001-01-01 doesn't fit into 32-bit time_t, |
---|
2002 | n/a | # or platform doesn't support such very old date |
---|
2003 | n/a | self.skipTest(str(exc)) |
---|
2004 | n/a | |
---|
2005 | n/a | # maximum timestamp: set seconds to zero to avoid rounding issues |
---|
2006 | n/a | max_dt = self.theclass.max.replace(tzinfo=timezone.utc, |
---|
2007 | n/a | second=0, microsecond=0) |
---|
2008 | n/a | max_ts = max_dt.timestamp() |
---|
2009 | n/a | # date 9999-12-31 23:59:00+00:00: timestamp 253402300740 |
---|
2010 | n/a | self.assertEqual(self.theclass.fromtimestamp(max_ts, tz=timezone.utc), |
---|
2011 | n/a | max_dt) |
---|
2012 | n/a | |
---|
2013 | n/a | # number of seconds greater than 1 year: make sure that the new date |
---|
2014 | n/a | # is not valid in datetime.datetime limits |
---|
2015 | n/a | delta = 3600 * 24 * 400 |
---|
2016 | n/a | |
---|
2017 | n/a | # too small |
---|
2018 | n/a | ts = min_ts - delta |
---|
2019 | n/a | # converting a Python int to C time_t can raise a OverflowError, |
---|
2020 | n/a | # especially on 32-bit platforms. |
---|
2021 | n/a | with self.assertRaises((ValueError, OverflowError)): |
---|
2022 | n/a | self.theclass.fromtimestamp(ts) |
---|
2023 | n/a | with self.assertRaises((ValueError, OverflowError)): |
---|
2024 | n/a | self.theclass.utcfromtimestamp(ts) |
---|
2025 | n/a | |
---|
2026 | n/a | # too big |
---|
2027 | n/a | ts = max_dt.timestamp() + delta |
---|
2028 | n/a | with self.assertRaises((ValueError, OverflowError)): |
---|
2029 | n/a | self.theclass.fromtimestamp(ts) |
---|
2030 | n/a | with self.assertRaises((ValueError, OverflowError)): |
---|
2031 | n/a | self.theclass.utcfromtimestamp(ts) |
---|
2032 | n/a | |
---|
2033 | n/a | def test_insane_fromtimestamp(self): |
---|
2034 | n/a | # It's possible that some platform maps time_t to double, |
---|
2035 | n/a | # and that this test will fail there. This test should |
---|
2036 | n/a | # exempt such platforms (provided they return reasonable |
---|
2037 | n/a | # results!). |
---|
2038 | n/a | for insane in -1e200, 1e200: |
---|
2039 | n/a | self.assertRaises(OverflowError, self.theclass.fromtimestamp, |
---|
2040 | n/a | insane) |
---|
2041 | n/a | |
---|
2042 | n/a | def test_insane_utcfromtimestamp(self): |
---|
2043 | n/a | # It's possible that some platform maps time_t to double, |
---|
2044 | n/a | # and that this test will fail there. This test should |
---|
2045 | n/a | # exempt such platforms (provided they return reasonable |
---|
2046 | n/a | # results!). |
---|
2047 | n/a | for insane in -1e200, 1e200: |
---|
2048 | n/a | self.assertRaises(OverflowError, self.theclass.utcfromtimestamp, |
---|
2049 | n/a | insane) |
---|
2050 | n/a | |
---|
2051 | n/a | @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") |
---|
2052 | n/a | def test_negative_float_fromtimestamp(self): |
---|
2053 | n/a | # The result is tz-dependent; at least test that this doesn't |
---|
2054 | n/a | # fail (like it did before bug 1646728 was fixed). |
---|
2055 | n/a | self.theclass.fromtimestamp(-1.05) |
---|
2056 | n/a | |
---|
2057 | n/a | @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") |
---|
2058 | n/a | def test_negative_float_utcfromtimestamp(self): |
---|
2059 | n/a | d = self.theclass.utcfromtimestamp(-1.05) |
---|
2060 | n/a | self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000)) |
---|
2061 | n/a | |
---|
2062 | n/a | def test_utcnow(self): |
---|
2063 | n/a | import time |
---|
2064 | n/a | |
---|
2065 | n/a | # Call it a success if utcnow() and utcfromtimestamp() are within |
---|
2066 | n/a | # a second of each other. |
---|
2067 | n/a | tolerance = timedelta(seconds=1) |
---|
2068 | n/a | for dummy in range(3): |
---|
2069 | n/a | from_now = self.theclass.utcnow() |
---|
2070 | n/a | from_timestamp = self.theclass.utcfromtimestamp(time.time()) |
---|
2071 | n/a | if abs(from_timestamp - from_now) <= tolerance: |
---|
2072 | n/a | break |
---|
2073 | n/a | # Else try again a few times. |
---|
2074 | n/a | self.assertLessEqual(abs(from_timestamp - from_now), tolerance) |
---|
2075 | n/a | |
---|
2076 | n/a | def test_strptime(self): |
---|
2077 | n/a | string = '2004-12-01 13:02:47.197' |
---|
2078 | n/a | format = '%Y-%m-%d %H:%M:%S.%f' |
---|
2079 | n/a | expected = _strptime._strptime_datetime(self.theclass, string, format) |
---|
2080 | n/a | got = self.theclass.strptime(string, format) |
---|
2081 | n/a | self.assertEqual(expected, got) |
---|
2082 | n/a | self.assertIs(type(expected), self.theclass) |
---|
2083 | n/a | self.assertIs(type(got), self.theclass) |
---|
2084 | n/a | |
---|
2085 | n/a | strptime = self.theclass.strptime |
---|
2086 | n/a | self.assertEqual(strptime("+0002", "%z").utcoffset(), 2 * MINUTE) |
---|
2087 | n/a | self.assertEqual(strptime("-0002", "%z").utcoffset(), -2 * MINUTE) |
---|
2088 | n/a | # Only local timezone and UTC are supported |
---|
2089 | n/a | for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'), |
---|
2090 | n/a | (-_time.timezone, _time.tzname[0])): |
---|
2091 | n/a | if tzseconds < 0: |
---|
2092 | n/a | sign = '-' |
---|
2093 | n/a | seconds = -tzseconds |
---|
2094 | n/a | else: |
---|
2095 | n/a | sign ='+' |
---|
2096 | n/a | seconds = tzseconds |
---|
2097 | n/a | hours, minutes = divmod(seconds//60, 60) |
---|
2098 | n/a | dtstr = "{}{:02d}{:02d} {}".format(sign, hours, minutes, tzname) |
---|
2099 | n/a | dt = strptime(dtstr, "%z %Z") |
---|
2100 | n/a | self.assertEqual(dt.utcoffset(), timedelta(seconds=tzseconds)) |
---|
2101 | n/a | self.assertEqual(dt.tzname(), tzname) |
---|
2102 | n/a | # Can produce inconsistent datetime |
---|
2103 | n/a | dtstr, fmt = "+1234 UTC", "%z %Z" |
---|
2104 | n/a | dt = strptime(dtstr, fmt) |
---|
2105 | n/a | self.assertEqual(dt.utcoffset(), 12 * HOUR + 34 * MINUTE) |
---|
2106 | n/a | self.assertEqual(dt.tzname(), 'UTC') |
---|
2107 | n/a | # yet will roundtrip |
---|
2108 | n/a | self.assertEqual(dt.strftime(fmt), dtstr) |
---|
2109 | n/a | |
---|
2110 | n/a | # Produce naive datetime if no %z is provided |
---|
2111 | n/a | self.assertEqual(strptime("UTC", "%Z").tzinfo, None) |
---|
2112 | n/a | |
---|
2113 | n/a | with self.assertRaises(ValueError): strptime("-2400", "%z") |
---|
2114 | n/a | with self.assertRaises(ValueError): strptime("-000", "%z") |
---|
2115 | n/a | |
---|
2116 | n/a | def test_more_timetuple(self): |
---|
2117 | n/a | # This tests fields beyond those tested by the TestDate.test_timetuple. |
---|
2118 | n/a | t = self.theclass(2004, 12, 31, 6, 22, 33) |
---|
2119 | n/a | self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1)) |
---|
2120 | n/a | self.assertEqual(t.timetuple(), |
---|
2121 | n/a | (t.year, t.month, t.day, |
---|
2122 | n/a | t.hour, t.minute, t.second, |
---|
2123 | n/a | t.weekday(), |
---|
2124 | n/a | t.toordinal() - date(t.year, 1, 1).toordinal() + 1, |
---|
2125 | n/a | -1)) |
---|
2126 | n/a | tt = t.timetuple() |
---|
2127 | n/a | self.assertEqual(tt.tm_year, t.year) |
---|
2128 | n/a | self.assertEqual(tt.tm_mon, t.month) |
---|
2129 | n/a | self.assertEqual(tt.tm_mday, t.day) |
---|
2130 | n/a | self.assertEqual(tt.tm_hour, t.hour) |
---|
2131 | n/a | self.assertEqual(tt.tm_min, t.minute) |
---|
2132 | n/a | self.assertEqual(tt.tm_sec, t.second) |
---|
2133 | n/a | self.assertEqual(tt.tm_wday, t.weekday()) |
---|
2134 | n/a | self.assertEqual(tt.tm_yday, t.toordinal() - |
---|
2135 | n/a | date(t.year, 1, 1).toordinal() + 1) |
---|
2136 | n/a | self.assertEqual(tt.tm_isdst, -1) |
---|
2137 | n/a | |
---|
2138 | n/a | def test_more_strftime(self): |
---|
2139 | n/a | # This tests fields beyond those tested by the TestDate.test_strftime. |
---|
2140 | n/a | t = self.theclass(2004, 12, 31, 6, 22, 33, 47) |
---|
2141 | n/a | self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"), |
---|
2142 | n/a | "12 31 04 000047 33 22 06 366") |
---|
2143 | n/a | |
---|
2144 | n/a | def test_extract(self): |
---|
2145 | n/a | dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) |
---|
2146 | n/a | self.assertEqual(dt.date(), date(2002, 3, 4)) |
---|
2147 | n/a | self.assertEqual(dt.time(), time(18, 45, 3, 1234)) |
---|
2148 | n/a | |
---|
2149 | n/a | def test_combine(self): |
---|
2150 | n/a | d = date(2002, 3, 4) |
---|
2151 | n/a | t = time(18, 45, 3, 1234) |
---|
2152 | n/a | expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234) |
---|
2153 | n/a | combine = self.theclass.combine |
---|
2154 | n/a | dt = combine(d, t) |
---|
2155 | n/a | self.assertEqual(dt, expected) |
---|
2156 | n/a | |
---|
2157 | n/a | dt = combine(time=t, date=d) |
---|
2158 | n/a | self.assertEqual(dt, expected) |
---|
2159 | n/a | |
---|
2160 | n/a | self.assertEqual(d, dt.date()) |
---|
2161 | n/a | self.assertEqual(t, dt.time()) |
---|
2162 | n/a | self.assertEqual(dt, combine(dt.date(), dt.time())) |
---|
2163 | n/a | |
---|
2164 | n/a | self.assertRaises(TypeError, combine) # need an arg |
---|
2165 | n/a | self.assertRaises(TypeError, combine, d) # need two args |
---|
2166 | n/a | self.assertRaises(TypeError, combine, t, d) # args reversed |
---|
2167 | n/a | self.assertRaises(TypeError, combine, d, t, 1) # wrong tzinfo type |
---|
2168 | n/a | self.assertRaises(TypeError, combine, d, t, 1, 2) # too many args |
---|
2169 | n/a | self.assertRaises(TypeError, combine, "date", "time") # wrong types |
---|
2170 | n/a | self.assertRaises(TypeError, combine, d, "time") # wrong type |
---|
2171 | n/a | self.assertRaises(TypeError, combine, "date", t) # wrong type |
---|
2172 | n/a | |
---|
2173 | n/a | # tzinfo= argument |
---|
2174 | n/a | dt = combine(d, t, timezone.utc) |
---|
2175 | n/a | self.assertIs(dt.tzinfo, timezone.utc) |
---|
2176 | n/a | dt = combine(d, t, tzinfo=timezone.utc) |
---|
2177 | n/a | self.assertIs(dt.tzinfo, timezone.utc) |
---|
2178 | n/a | t = time() |
---|
2179 | n/a | dt = combine(dt, t) |
---|
2180 | n/a | self.assertEqual(dt.date(), d) |
---|
2181 | n/a | self.assertEqual(dt.time(), t) |
---|
2182 | n/a | |
---|
2183 | n/a | def test_replace(self): |
---|
2184 | n/a | cls = self.theclass |
---|
2185 | n/a | args = [1, 2, 3, 4, 5, 6, 7] |
---|
2186 | n/a | base = cls(*args) |
---|
2187 | n/a | self.assertEqual(base, base.replace()) |
---|
2188 | n/a | |
---|
2189 | n/a | i = 0 |
---|
2190 | n/a | for name, newval in (("year", 2), |
---|
2191 | n/a | ("month", 3), |
---|
2192 | n/a | ("day", 4), |
---|
2193 | n/a | ("hour", 5), |
---|
2194 | n/a | ("minute", 6), |
---|
2195 | n/a | ("second", 7), |
---|
2196 | n/a | ("microsecond", 8)): |
---|
2197 | n/a | newargs = args[:] |
---|
2198 | n/a | newargs[i] = newval |
---|
2199 | n/a | expected = cls(*newargs) |
---|
2200 | n/a | got = base.replace(**{name: newval}) |
---|
2201 | n/a | self.assertEqual(expected, got) |
---|
2202 | n/a | i += 1 |
---|
2203 | n/a | |
---|
2204 | n/a | # Out of bounds. |
---|
2205 | n/a | base = cls(2000, 2, 29) |
---|
2206 | n/a | self.assertRaises(ValueError, base.replace, year=2001) |
---|
2207 | n/a | |
---|
2208 | n/a | def test_astimezone(self): |
---|
2209 | n/a | return # The rest is no longer applicable |
---|
2210 | n/a | # Pretty boring! The TZ test is more interesting here. astimezone() |
---|
2211 | n/a | # simply can't be applied to a naive object. |
---|
2212 | n/a | dt = self.theclass.now() |
---|
2213 | n/a | f = FixedOffset(44, "") |
---|
2214 | n/a | self.assertRaises(ValueError, dt.astimezone) # naive |
---|
2215 | n/a | self.assertRaises(TypeError, dt.astimezone, f, f) # too many args |
---|
2216 | n/a | self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type |
---|
2217 | n/a | self.assertRaises(ValueError, dt.astimezone, f) # naive |
---|
2218 | n/a | self.assertRaises(ValueError, dt.astimezone, tz=f) # naive |
---|
2219 | n/a | |
---|
2220 | n/a | class Bogus(tzinfo): |
---|
2221 | n/a | def utcoffset(self, dt): return None |
---|
2222 | n/a | def dst(self, dt): return timedelta(0) |
---|
2223 | n/a | bog = Bogus() |
---|
2224 | n/a | self.assertRaises(ValueError, dt.astimezone, bog) # naive |
---|
2225 | n/a | self.assertRaises(ValueError, |
---|
2226 | n/a | dt.replace(tzinfo=bog).astimezone, f) |
---|
2227 | n/a | |
---|
2228 | n/a | class AlsoBogus(tzinfo): |
---|
2229 | n/a | def utcoffset(self, dt): return timedelta(0) |
---|
2230 | n/a | def dst(self, dt): return None |
---|
2231 | n/a | alsobog = AlsoBogus() |
---|
2232 | n/a | self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive |
---|
2233 | n/a | |
---|
2234 | n/a | def test_subclass_datetime(self): |
---|
2235 | n/a | |
---|
2236 | n/a | class C(self.theclass): |
---|
2237 | n/a | theAnswer = 42 |
---|
2238 | n/a | |
---|
2239 | n/a | def __new__(cls, *args, **kws): |
---|
2240 | n/a | temp = kws.copy() |
---|
2241 | n/a | extra = temp.pop('extra') |
---|
2242 | n/a | result = self.theclass.__new__(cls, *args, **temp) |
---|
2243 | n/a | result.extra = extra |
---|
2244 | n/a | return result |
---|
2245 | n/a | |
---|
2246 | n/a | def newmeth(self, start): |
---|
2247 | n/a | return start + self.year + self.month + self.second |
---|
2248 | n/a | |
---|
2249 | n/a | args = 2003, 4, 14, 12, 13, 41 |
---|
2250 | n/a | |
---|
2251 | n/a | dt1 = self.theclass(*args) |
---|
2252 | n/a | dt2 = C(*args, **{'extra': 7}) |
---|
2253 | n/a | |
---|
2254 | n/a | self.assertEqual(dt2.__class__, C) |
---|
2255 | n/a | self.assertEqual(dt2.theAnswer, 42) |
---|
2256 | n/a | self.assertEqual(dt2.extra, 7) |
---|
2257 | n/a | self.assertEqual(dt1.toordinal(), dt2.toordinal()) |
---|
2258 | n/a | self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month + |
---|
2259 | n/a | dt1.second - 7) |
---|
2260 | n/a | |
---|
2261 | n/a | class TestSubclassDateTime(TestDateTime): |
---|
2262 | n/a | theclass = SubclassDatetime |
---|
2263 | n/a | # Override tests not designed for subclass |
---|
2264 | n/a | @unittest.skip('not appropriate for subclasses') |
---|
2265 | n/a | def test_roundtrip(self): |
---|
2266 | n/a | pass |
---|
2267 | n/a | |
---|
2268 | n/a | class SubclassTime(time): |
---|
2269 | n/a | sub_var = 1 |
---|
2270 | n/a | |
---|
2271 | n/a | class TestTime(HarmlessMixedComparison, unittest.TestCase): |
---|
2272 | n/a | |
---|
2273 | n/a | theclass = time |
---|
2274 | n/a | |
---|
2275 | n/a | def test_basic_attributes(self): |
---|
2276 | n/a | t = self.theclass(12, 0) |
---|
2277 | n/a | self.assertEqual(t.hour, 12) |
---|
2278 | n/a | self.assertEqual(t.minute, 0) |
---|
2279 | n/a | self.assertEqual(t.second, 0) |
---|
2280 | n/a | self.assertEqual(t.microsecond, 0) |
---|
2281 | n/a | |
---|
2282 | n/a | def test_basic_attributes_nonzero(self): |
---|
2283 | n/a | # Make sure all attributes are non-zero so bugs in |
---|
2284 | n/a | # bit-shifting access show up. |
---|
2285 | n/a | t = self.theclass(12, 59, 59, 8000) |
---|
2286 | n/a | self.assertEqual(t.hour, 12) |
---|
2287 | n/a | self.assertEqual(t.minute, 59) |
---|
2288 | n/a | self.assertEqual(t.second, 59) |
---|
2289 | n/a | self.assertEqual(t.microsecond, 8000) |
---|
2290 | n/a | |
---|
2291 | n/a | def test_roundtrip(self): |
---|
2292 | n/a | t = self.theclass(1, 2, 3, 4) |
---|
2293 | n/a | |
---|
2294 | n/a | # Verify t -> string -> time identity. |
---|
2295 | n/a | s = repr(t) |
---|
2296 | n/a | self.assertTrue(s.startswith('datetime.')) |
---|
2297 | n/a | s = s[9:] |
---|
2298 | n/a | t2 = eval(s) |
---|
2299 | n/a | self.assertEqual(t, t2) |
---|
2300 | n/a | |
---|
2301 | n/a | # Verify identity via reconstructing from pieces. |
---|
2302 | n/a | t2 = self.theclass(t.hour, t.minute, t.second, |
---|
2303 | n/a | t.microsecond) |
---|
2304 | n/a | self.assertEqual(t, t2) |
---|
2305 | n/a | |
---|
2306 | n/a | def test_comparing(self): |
---|
2307 | n/a | args = [1, 2, 3, 4] |
---|
2308 | n/a | t1 = self.theclass(*args) |
---|
2309 | n/a | t2 = self.theclass(*args) |
---|
2310 | n/a | self.assertEqual(t1, t2) |
---|
2311 | n/a | self.assertTrue(t1 <= t2) |
---|
2312 | n/a | self.assertTrue(t1 >= t2) |
---|
2313 | n/a | self.assertFalse(t1 != t2) |
---|
2314 | n/a | self.assertFalse(t1 < t2) |
---|
2315 | n/a | self.assertFalse(t1 > t2) |
---|
2316 | n/a | |
---|
2317 | n/a | for i in range(len(args)): |
---|
2318 | n/a | newargs = args[:] |
---|
2319 | n/a | newargs[i] = args[i] + 1 |
---|
2320 | n/a | t2 = self.theclass(*newargs) # this is larger than t1 |
---|
2321 | n/a | self.assertTrue(t1 < t2) |
---|
2322 | n/a | self.assertTrue(t2 > t1) |
---|
2323 | n/a | self.assertTrue(t1 <= t2) |
---|
2324 | n/a | self.assertTrue(t2 >= t1) |
---|
2325 | n/a | self.assertTrue(t1 != t2) |
---|
2326 | n/a | self.assertTrue(t2 != t1) |
---|
2327 | n/a | self.assertFalse(t1 == t2) |
---|
2328 | n/a | self.assertFalse(t2 == t1) |
---|
2329 | n/a | self.assertFalse(t1 > t2) |
---|
2330 | n/a | self.assertFalse(t2 < t1) |
---|
2331 | n/a | self.assertFalse(t1 >= t2) |
---|
2332 | n/a | self.assertFalse(t2 <= t1) |
---|
2333 | n/a | |
---|
2334 | n/a | for badarg in OTHERSTUFF: |
---|
2335 | n/a | self.assertEqual(t1 == badarg, False) |
---|
2336 | n/a | self.assertEqual(t1 != badarg, True) |
---|
2337 | n/a | self.assertEqual(badarg == t1, False) |
---|
2338 | n/a | self.assertEqual(badarg != t1, True) |
---|
2339 | n/a | |
---|
2340 | n/a | self.assertRaises(TypeError, lambda: t1 <= badarg) |
---|
2341 | n/a | self.assertRaises(TypeError, lambda: t1 < badarg) |
---|
2342 | n/a | self.assertRaises(TypeError, lambda: t1 > badarg) |
---|
2343 | n/a | self.assertRaises(TypeError, lambda: t1 >= badarg) |
---|
2344 | n/a | self.assertRaises(TypeError, lambda: badarg <= t1) |
---|
2345 | n/a | self.assertRaises(TypeError, lambda: badarg < t1) |
---|
2346 | n/a | self.assertRaises(TypeError, lambda: badarg > t1) |
---|
2347 | n/a | self.assertRaises(TypeError, lambda: badarg >= t1) |
---|
2348 | n/a | |
---|
2349 | n/a | def test_bad_constructor_arguments(self): |
---|
2350 | n/a | # bad hours |
---|
2351 | n/a | self.theclass(0, 0) # no exception |
---|
2352 | n/a | self.theclass(23, 0) # no exception |
---|
2353 | n/a | self.assertRaises(ValueError, self.theclass, -1, 0) |
---|
2354 | n/a | self.assertRaises(ValueError, self.theclass, 24, 0) |
---|
2355 | n/a | # bad minutes |
---|
2356 | n/a | self.theclass(23, 0) # no exception |
---|
2357 | n/a | self.theclass(23, 59) # no exception |
---|
2358 | n/a | self.assertRaises(ValueError, self.theclass, 23, -1) |
---|
2359 | n/a | self.assertRaises(ValueError, self.theclass, 23, 60) |
---|
2360 | n/a | # bad seconds |
---|
2361 | n/a | self.theclass(23, 59, 0) # no exception |
---|
2362 | n/a | self.theclass(23, 59, 59) # no exception |
---|
2363 | n/a | self.assertRaises(ValueError, self.theclass, 23, 59, -1) |
---|
2364 | n/a | self.assertRaises(ValueError, self.theclass, 23, 59, 60) |
---|
2365 | n/a | # bad microseconds |
---|
2366 | n/a | self.theclass(23, 59, 59, 0) # no exception |
---|
2367 | n/a | self.theclass(23, 59, 59, 999999) # no exception |
---|
2368 | n/a | self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1) |
---|
2369 | n/a | self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000) |
---|
2370 | n/a | |
---|
2371 | n/a | def test_hash_equality(self): |
---|
2372 | n/a | d = self.theclass(23, 30, 17) |
---|
2373 | n/a | e = self.theclass(23, 30, 17) |
---|
2374 | n/a | self.assertEqual(d, e) |
---|
2375 | n/a | self.assertEqual(hash(d), hash(e)) |
---|
2376 | n/a | |
---|
2377 | n/a | dic = {d: 1} |
---|
2378 | n/a | dic[e] = 2 |
---|
2379 | n/a | self.assertEqual(len(dic), 1) |
---|
2380 | n/a | self.assertEqual(dic[d], 2) |
---|
2381 | n/a | self.assertEqual(dic[e], 2) |
---|
2382 | n/a | |
---|
2383 | n/a | d = self.theclass(0, 5, 17) |
---|
2384 | n/a | e = self.theclass(0, 5, 17) |
---|
2385 | n/a | self.assertEqual(d, e) |
---|
2386 | n/a | self.assertEqual(hash(d), hash(e)) |
---|
2387 | n/a | |
---|
2388 | n/a | dic = {d: 1} |
---|
2389 | n/a | dic[e] = 2 |
---|
2390 | n/a | self.assertEqual(len(dic), 1) |
---|
2391 | n/a | self.assertEqual(dic[d], 2) |
---|
2392 | n/a | self.assertEqual(dic[e], 2) |
---|
2393 | n/a | |
---|
2394 | n/a | def test_isoformat(self): |
---|
2395 | n/a | t = self.theclass(4, 5, 1, 123) |
---|
2396 | n/a | self.assertEqual(t.isoformat(), "04:05:01.000123") |
---|
2397 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2398 | n/a | |
---|
2399 | n/a | t = self.theclass() |
---|
2400 | n/a | self.assertEqual(t.isoformat(), "00:00:00") |
---|
2401 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2402 | n/a | |
---|
2403 | n/a | t = self.theclass(microsecond=1) |
---|
2404 | n/a | self.assertEqual(t.isoformat(), "00:00:00.000001") |
---|
2405 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2406 | n/a | |
---|
2407 | n/a | t = self.theclass(microsecond=10) |
---|
2408 | n/a | self.assertEqual(t.isoformat(), "00:00:00.000010") |
---|
2409 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2410 | n/a | |
---|
2411 | n/a | t = self.theclass(microsecond=100) |
---|
2412 | n/a | self.assertEqual(t.isoformat(), "00:00:00.000100") |
---|
2413 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2414 | n/a | |
---|
2415 | n/a | t = self.theclass(microsecond=1000) |
---|
2416 | n/a | self.assertEqual(t.isoformat(), "00:00:00.001000") |
---|
2417 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2418 | n/a | |
---|
2419 | n/a | t = self.theclass(microsecond=10000) |
---|
2420 | n/a | self.assertEqual(t.isoformat(), "00:00:00.010000") |
---|
2421 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2422 | n/a | |
---|
2423 | n/a | t = self.theclass(microsecond=100000) |
---|
2424 | n/a | self.assertEqual(t.isoformat(), "00:00:00.100000") |
---|
2425 | n/a | self.assertEqual(t.isoformat(), str(t)) |
---|
2426 | n/a | |
---|
2427 | n/a | t = self.theclass(hour=12, minute=34, second=56, microsecond=123456) |
---|
2428 | n/a | self.assertEqual(t.isoformat(timespec='hours'), "12") |
---|
2429 | n/a | self.assertEqual(t.isoformat(timespec='minutes'), "12:34") |
---|
2430 | n/a | self.assertEqual(t.isoformat(timespec='seconds'), "12:34:56") |
---|
2431 | n/a | self.assertEqual(t.isoformat(timespec='milliseconds'), "12:34:56.123") |
---|
2432 | n/a | self.assertEqual(t.isoformat(timespec='microseconds'), "12:34:56.123456") |
---|
2433 | n/a | self.assertEqual(t.isoformat(timespec='auto'), "12:34:56.123456") |
---|
2434 | n/a | self.assertRaises(ValueError, t.isoformat, timespec='monkey') |
---|
2435 | n/a | |
---|
2436 | n/a | t = self.theclass(hour=12, minute=34, second=56, microsecond=999500) |
---|
2437 | n/a | self.assertEqual(t.isoformat(timespec='milliseconds'), "12:34:56.999") |
---|
2438 | n/a | |
---|
2439 | n/a | t = self.theclass(hour=12, minute=34, second=56, microsecond=0) |
---|
2440 | n/a | self.assertEqual(t.isoformat(timespec='milliseconds'), "12:34:56.000") |
---|
2441 | n/a | self.assertEqual(t.isoformat(timespec='microseconds'), "12:34:56.000000") |
---|
2442 | n/a | self.assertEqual(t.isoformat(timespec='auto'), "12:34:56") |
---|
2443 | n/a | |
---|
2444 | n/a | def test_1653736(self): |
---|
2445 | n/a | # verify it doesn't accept extra keyword arguments |
---|
2446 | n/a | t = self.theclass(second=1) |
---|
2447 | n/a | self.assertRaises(TypeError, t.isoformat, foo=3) |
---|
2448 | n/a | |
---|
2449 | n/a | def test_strftime(self): |
---|
2450 | n/a | t = self.theclass(1, 2, 3, 4) |
---|
2451 | n/a | self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004") |
---|
2452 | n/a | # A naive object replaces %z and %Z with empty strings. |
---|
2453 | n/a | self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''") |
---|
2454 | n/a | |
---|
2455 | n/a | def test_format(self): |
---|
2456 | n/a | t = self.theclass(1, 2, 3, 4) |
---|
2457 | n/a | self.assertEqual(t.__format__(''), str(t)) |
---|
2458 | n/a | |
---|
2459 | n/a | with self.assertRaisesRegex(TypeError, 'must be str, not int'): |
---|
2460 | n/a | t.__format__(123) |
---|
2461 | n/a | |
---|
2462 | n/a | # check that a derived class's __str__() gets called |
---|
2463 | n/a | class A(self.theclass): |
---|
2464 | n/a | def __str__(self): |
---|
2465 | n/a | return 'A' |
---|
2466 | n/a | a = A(1, 2, 3, 4) |
---|
2467 | n/a | self.assertEqual(a.__format__(''), 'A') |
---|
2468 | n/a | |
---|
2469 | n/a | # check that a derived class's strftime gets called |
---|
2470 | n/a | class B(self.theclass): |
---|
2471 | n/a | def strftime(self, format_spec): |
---|
2472 | n/a | return 'B' |
---|
2473 | n/a | b = B(1, 2, 3, 4) |
---|
2474 | n/a | self.assertEqual(b.__format__(''), str(t)) |
---|
2475 | n/a | |
---|
2476 | n/a | for fmt in ['%H %M %S', |
---|
2477 | n/a | ]: |
---|
2478 | n/a | self.assertEqual(t.__format__(fmt), t.strftime(fmt)) |
---|
2479 | n/a | self.assertEqual(a.__format__(fmt), t.strftime(fmt)) |
---|
2480 | n/a | self.assertEqual(b.__format__(fmt), 'B') |
---|
2481 | n/a | |
---|
2482 | n/a | def test_str(self): |
---|
2483 | n/a | self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004") |
---|
2484 | n/a | self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000") |
---|
2485 | n/a | self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000") |
---|
2486 | n/a | self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03") |
---|
2487 | n/a | self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00") |
---|
2488 | n/a | |
---|
2489 | n/a | def test_repr(self): |
---|
2490 | n/a | name = 'datetime.' + self.theclass.__name__ |
---|
2491 | n/a | self.assertEqual(repr(self.theclass(1, 2, 3, 4)), |
---|
2492 | n/a | "%s(1, 2, 3, 4)" % name) |
---|
2493 | n/a | self.assertEqual(repr(self.theclass(10, 2, 3, 4000)), |
---|
2494 | n/a | "%s(10, 2, 3, 4000)" % name) |
---|
2495 | n/a | self.assertEqual(repr(self.theclass(0, 2, 3, 400000)), |
---|
2496 | n/a | "%s(0, 2, 3, 400000)" % name) |
---|
2497 | n/a | self.assertEqual(repr(self.theclass(12, 2, 3, 0)), |
---|
2498 | n/a | "%s(12, 2, 3)" % name) |
---|
2499 | n/a | self.assertEqual(repr(self.theclass(23, 15, 0, 0)), |
---|
2500 | n/a | "%s(23, 15)" % name) |
---|
2501 | n/a | |
---|
2502 | n/a | def test_resolution_info(self): |
---|
2503 | n/a | self.assertIsInstance(self.theclass.min, self.theclass) |
---|
2504 | n/a | self.assertIsInstance(self.theclass.max, self.theclass) |
---|
2505 | n/a | self.assertIsInstance(self.theclass.resolution, timedelta) |
---|
2506 | n/a | self.assertTrue(self.theclass.max > self.theclass.min) |
---|
2507 | n/a | |
---|
2508 | n/a | def test_pickling(self): |
---|
2509 | n/a | args = 20, 59, 16, 64**2 |
---|
2510 | n/a | orig = self.theclass(*args) |
---|
2511 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
2512 | n/a | green = pickler.dumps(orig, proto) |
---|
2513 | n/a | derived = unpickler.loads(green) |
---|
2514 | n/a | self.assertEqual(orig, derived) |
---|
2515 | n/a | self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) |
---|
2516 | n/a | |
---|
2517 | n/a | def test_pickling_subclass_time(self): |
---|
2518 | n/a | args = 20, 59, 16, 64**2 |
---|
2519 | n/a | orig = SubclassTime(*args) |
---|
2520 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
2521 | n/a | green = pickler.dumps(orig, proto) |
---|
2522 | n/a | derived = unpickler.loads(green) |
---|
2523 | n/a | self.assertEqual(orig, derived) |
---|
2524 | n/a | |
---|
2525 | n/a | def test_bool(self): |
---|
2526 | n/a | # time is always True. |
---|
2527 | n/a | cls = self.theclass |
---|
2528 | n/a | self.assertTrue(cls(1)) |
---|
2529 | n/a | self.assertTrue(cls(0, 1)) |
---|
2530 | n/a | self.assertTrue(cls(0, 0, 1)) |
---|
2531 | n/a | self.assertTrue(cls(0, 0, 0, 1)) |
---|
2532 | n/a | self.assertTrue(cls(0)) |
---|
2533 | n/a | self.assertTrue(cls()) |
---|
2534 | n/a | |
---|
2535 | n/a | def test_replace(self): |
---|
2536 | n/a | cls = self.theclass |
---|
2537 | n/a | args = [1, 2, 3, 4] |
---|
2538 | n/a | base = cls(*args) |
---|
2539 | n/a | self.assertEqual(base, base.replace()) |
---|
2540 | n/a | |
---|
2541 | n/a | i = 0 |
---|
2542 | n/a | for name, newval in (("hour", 5), |
---|
2543 | n/a | ("minute", 6), |
---|
2544 | n/a | ("second", 7), |
---|
2545 | n/a | ("microsecond", 8)): |
---|
2546 | n/a | newargs = args[:] |
---|
2547 | n/a | newargs[i] = newval |
---|
2548 | n/a | expected = cls(*newargs) |
---|
2549 | n/a | got = base.replace(**{name: newval}) |
---|
2550 | n/a | self.assertEqual(expected, got) |
---|
2551 | n/a | i += 1 |
---|
2552 | n/a | |
---|
2553 | n/a | # Out of bounds. |
---|
2554 | n/a | base = cls(1) |
---|
2555 | n/a | self.assertRaises(ValueError, base.replace, hour=24) |
---|
2556 | n/a | self.assertRaises(ValueError, base.replace, minute=-1) |
---|
2557 | n/a | self.assertRaises(ValueError, base.replace, second=100) |
---|
2558 | n/a | self.assertRaises(ValueError, base.replace, microsecond=1000000) |
---|
2559 | n/a | |
---|
2560 | n/a | def test_subclass_time(self): |
---|
2561 | n/a | |
---|
2562 | n/a | class C(self.theclass): |
---|
2563 | n/a | theAnswer = 42 |
---|
2564 | n/a | |
---|
2565 | n/a | def __new__(cls, *args, **kws): |
---|
2566 | n/a | temp = kws.copy() |
---|
2567 | n/a | extra = temp.pop('extra') |
---|
2568 | n/a | result = self.theclass.__new__(cls, *args, **temp) |
---|
2569 | n/a | result.extra = extra |
---|
2570 | n/a | return result |
---|
2571 | n/a | |
---|
2572 | n/a | def newmeth(self, start): |
---|
2573 | n/a | return start + self.hour + self.second |
---|
2574 | n/a | |
---|
2575 | n/a | args = 4, 5, 6 |
---|
2576 | n/a | |
---|
2577 | n/a | dt1 = self.theclass(*args) |
---|
2578 | n/a | dt2 = C(*args, **{'extra': 7}) |
---|
2579 | n/a | |
---|
2580 | n/a | self.assertEqual(dt2.__class__, C) |
---|
2581 | n/a | self.assertEqual(dt2.theAnswer, 42) |
---|
2582 | n/a | self.assertEqual(dt2.extra, 7) |
---|
2583 | n/a | self.assertEqual(dt1.isoformat(), dt2.isoformat()) |
---|
2584 | n/a | self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7) |
---|
2585 | n/a | |
---|
2586 | n/a | def test_backdoor_resistance(self): |
---|
2587 | n/a | # see TestDate.test_backdoor_resistance(). |
---|
2588 | n/a | base = '2:59.0' |
---|
2589 | n/a | for hour_byte in ' ', '9', chr(24), '\xff': |
---|
2590 | n/a | self.assertRaises(TypeError, self.theclass, |
---|
2591 | n/a | hour_byte + base[1:]) |
---|
2592 | n/a | # Good bytes, but bad tzinfo: |
---|
2593 | n/a | with self.assertRaisesRegex(TypeError, '^bad tzinfo state arg$'): |
---|
2594 | n/a | self.theclass(bytes([1] * len(base)), 'EST') |
---|
2595 | n/a | |
---|
2596 | n/a | # A mixin for classes with a tzinfo= argument. Subclasses must define |
---|
2597 | n/a | # theclass as a class attribute, and theclass(1, 1, 1, tzinfo=whatever) |
---|
2598 | n/a | # must be legit (which is true for time and datetime). |
---|
2599 | n/a | class TZInfoBase: |
---|
2600 | n/a | |
---|
2601 | n/a | def test_argument_passing(self): |
---|
2602 | n/a | cls = self.theclass |
---|
2603 | n/a | # A datetime passes itself on, a time passes None. |
---|
2604 | n/a | class introspective(tzinfo): |
---|
2605 | n/a | def tzname(self, dt): return dt and "real" or "none" |
---|
2606 | n/a | def utcoffset(self, dt): |
---|
2607 | n/a | return timedelta(minutes = dt and 42 or -42) |
---|
2608 | n/a | dst = utcoffset |
---|
2609 | n/a | |
---|
2610 | n/a | obj = cls(1, 2, 3, tzinfo=introspective()) |
---|
2611 | n/a | |
---|
2612 | n/a | expected = cls is time and "none" or "real" |
---|
2613 | n/a | self.assertEqual(obj.tzname(), expected) |
---|
2614 | n/a | |
---|
2615 | n/a | expected = timedelta(minutes=(cls is time and -42 or 42)) |
---|
2616 | n/a | self.assertEqual(obj.utcoffset(), expected) |
---|
2617 | n/a | self.assertEqual(obj.dst(), expected) |
---|
2618 | n/a | |
---|
2619 | n/a | def test_bad_tzinfo_classes(self): |
---|
2620 | n/a | cls = self.theclass |
---|
2621 | n/a | self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12) |
---|
2622 | n/a | |
---|
2623 | n/a | class NiceTry(object): |
---|
2624 | n/a | def __init__(self): pass |
---|
2625 | n/a | def utcoffset(self, dt): pass |
---|
2626 | n/a | self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry) |
---|
2627 | n/a | |
---|
2628 | n/a | class BetterTry(tzinfo): |
---|
2629 | n/a | def __init__(self): pass |
---|
2630 | n/a | def utcoffset(self, dt): pass |
---|
2631 | n/a | b = BetterTry() |
---|
2632 | n/a | t = cls(1, 1, 1, tzinfo=b) |
---|
2633 | n/a | self.assertIs(t.tzinfo, b) |
---|
2634 | n/a | |
---|
2635 | n/a | def test_utc_offset_out_of_bounds(self): |
---|
2636 | n/a | class Edgy(tzinfo): |
---|
2637 | n/a | def __init__(self, offset): |
---|
2638 | n/a | self.offset = timedelta(minutes=offset) |
---|
2639 | n/a | def utcoffset(self, dt): |
---|
2640 | n/a | return self.offset |
---|
2641 | n/a | |
---|
2642 | n/a | cls = self.theclass |
---|
2643 | n/a | for offset, legit in ((-1440, False), |
---|
2644 | n/a | (-1439, True), |
---|
2645 | n/a | (1439, True), |
---|
2646 | n/a | (1440, False)): |
---|
2647 | n/a | if cls is time: |
---|
2648 | n/a | t = cls(1, 2, 3, tzinfo=Edgy(offset)) |
---|
2649 | n/a | elif cls is datetime: |
---|
2650 | n/a | t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset)) |
---|
2651 | n/a | else: |
---|
2652 | n/a | assert 0, "impossible" |
---|
2653 | n/a | if legit: |
---|
2654 | n/a | aofs = abs(offset) |
---|
2655 | n/a | h, m = divmod(aofs, 60) |
---|
2656 | n/a | tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m) |
---|
2657 | n/a | if isinstance(t, datetime): |
---|
2658 | n/a | t = t.timetz() |
---|
2659 | n/a | self.assertEqual(str(t), "01:02:03" + tag) |
---|
2660 | n/a | else: |
---|
2661 | n/a | self.assertRaises(ValueError, str, t) |
---|
2662 | n/a | |
---|
2663 | n/a | def test_tzinfo_classes(self): |
---|
2664 | n/a | cls = self.theclass |
---|
2665 | n/a | class C1(tzinfo): |
---|
2666 | n/a | def utcoffset(self, dt): return None |
---|
2667 | n/a | def dst(self, dt): return None |
---|
2668 | n/a | def tzname(self, dt): return None |
---|
2669 | n/a | for t in (cls(1, 1, 1), |
---|
2670 | n/a | cls(1, 1, 1, tzinfo=None), |
---|
2671 | n/a | cls(1, 1, 1, tzinfo=C1())): |
---|
2672 | n/a | self.assertIsNone(t.utcoffset()) |
---|
2673 | n/a | self.assertIsNone(t.dst()) |
---|
2674 | n/a | self.assertIsNone(t.tzname()) |
---|
2675 | n/a | |
---|
2676 | n/a | class C3(tzinfo): |
---|
2677 | n/a | def utcoffset(self, dt): return timedelta(minutes=-1439) |
---|
2678 | n/a | def dst(self, dt): return timedelta(minutes=1439) |
---|
2679 | n/a | def tzname(self, dt): return "aname" |
---|
2680 | n/a | t = cls(1, 1, 1, tzinfo=C3()) |
---|
2681 | n/a | self.assertEqual(t.utcoffset(), timedelta(minutes=-1439)) |
---|
2682 | n/a | self.assertEqual(t.dst(), timedelta(minutes=1439)) |
---|
2683 | n/a | self.assertEqual(t.tzname(), "aname") |
---|
2684 | n/a | |
---|
2685 | n/a | # Wrong types. |
---|
2686 | n/a | class C4(tzinfo): |
---|
2687 | n/a | def utcoffset(self, dt): return "aname" |
---|
2688 | n/a | def dst(self, dt): return 7 |
---|
2689 | n/a | def tzname(self, dt): return 0 |
---|
2690 | n/a | t = cls(1, 1, 1, tzinfo=C4()) |
---|
2691 | n/a | self.assertRaises(TypeError, t.utcoffset) |
---|
2692 | n/a | self.assertRaises(TypeError, t.dst) |
---|
2693 | n/a | self.assertRaises(TypeError, t.tzname) |
---|
2694 | n/a | |
---|
2695 | n/a | # Offset out of range. |
---|
2696 | n/a | class C6(tzinfo): |
---|
2697 | n/a | def utcoffset(self, dt): return timedelta(hours=-24) |
---|
2698 | n/a | def dst(self, dt): return timedelta(hours=24) |
---|
2699 | n/a | t = cls(1, 1, 1, tzinfo=C6()) |
---|
2700 | n/a | self.assertRaises(ValueError, t.utcoffset) |
---|
2701 | n/a | self.assertRaises(ValueError, t.dst) |
---|
2702 | n/a | |
---|
2703 | n/a | # Not a whole number of seconds. |
---|
2704 | n/a | class C7(tzinfo): |
---|
2705 | n/a | def utcoffset(self, dt): return timedelta(microseconds=61) |
---|
2706 | n/a | def dst(self, dt): return timedelta(microseconds=-81) |
---|
2707 | n/a | t = cls(1, 1, 1, tzinfo=C7()) |
---|
2708 | n/a | self.assertRaises(ValueError, t.utcoffset) |
---|
2709 | n/a | self.assertRaises(ValueError, t.dst) |
---|
2710 | n/a | |
---|
2711 | n/a | def test_aware_compare(self): |
---|
2712 | n/a | cls = self.theclass |
---|
2713 | n/a | |
---|
2714 | n/a | # Ensure that utcoffset() gets ignored if the comparands have |
---|
2715 | n/a | # the same tzinfo member. |
---|
2716 | n/a | class OperandDependentOffset(tzinfo): |
---|
2717 | n/a | def utcoffset(self, t): |
---|
2718 | n/a | if t.minute < 10: |
---|
2719 | n/a | # d0 and d1 equal after adjustment |
---|
2720 | n/a | return timedelta(minutes=t.minute) |
---|
2721 | n/a | else: |
---|
2722 | n/a | # d2 off in the weeds |
---|
2723 | n/a | return timedelta(minutes=59) |
---|
2724 | n/a | |
---|
2725 | n/a | base = cls(8, 9, 10, tzinfo=OperandDependentOffset()) |
---|
2726 | n/a | d0 = base.replace(minute=3) |
---|
2727 | n/a | d1 = base.replace(minute=9) |
---|
2728 | n/a | d2 = base.replace(minute=11) |
---|
2729 | n/a | for x in d0, d1, d2: |
---|
2730 | n/a | for y in d0, d1, d2: |
---|
2731 | n/a | for op in lt, le, gt, ge, eq, ne: |
---|
2732 | n/a | got = op(x, y) |
---|
2733 | n/a | expected = op(x.minute, y.minute) |
---|
2734 | n/a | self.assertEqual(got, expected) |
---|
2735 | n/a | |
---|
2736 | n/a | # However, if they're different members, uctoffset is not ignored. |
---|
2737 | n/a | # Note that a time can't actually have an operand-depedent offset, |
---|
2738 | n/a | # though (and time.utcoffset() passes None to tzinfo.utcoffset()), |
---|
2739 | n/a | # so skip this test for time. |
---|
2740 | n/a | if cls is not time: |
---|
2741 | n/a | d0 = base.replace(minute=3, tzinfo=OperandDependentOffset()) |
---|
2742 | n/a | d1 = base.replace(minute=9, tzinfo=OperandDependentOffset()) |
---|
2743 | n/a | d2 = base.replace(minute=11, tzinfo=OperandDependentOffset()) |
---|
2744 | n/a | for x in d0, d1, d2: |
---|
2745 | n/a | for y in d0, d1, d2: |
---|
2746 | n/a | got = (x > y) - (x < y) |
---|
2747 | n/a | if (x is d0 or x is d1) and (y is d0 or y is d1): |
---|
2748 | n/a | expected = 0 |
---|
2749 | n/a | elif x is y is d2: |
---|
2750 | n/a | expected = 0 |
---|
2751 | n/a | elif x is d2: |
---|
2752 | n/a | expected = -1 |
---|
2753 | n/a | else: |
---|
2754 | n/a | assert y is d2 |
---|
2755 | n/a | expected = 1 |
---|
2756 | n/a | self.assertEqual(got, expected) |
---|
2757 | n/a | |
---|
2758 | n/a | |
---|
2759 | n/a | # Testing time objects with a non-None tzinfo. |
---|
2760 | n/a | class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase): |
---|
2761 | n/a | theclass = time |
---|
2762 | n/a | |
---|
2763 | n/a | def test_empty(self): |
---|
2764 | n/a | t = self.theclass() |
---|
2765 | n/a | self.assertEqual(t.hour, 0) |
---|
2766 | n/a | self.assertEqual(t.minute, 0) |
---|
2767 | n/a | self.assertEqual(t.second, 0) |
---|
2768 | n/a | self.assertEqual(t.microsecond, 0) |
---|
2769 | n/a | self.assertIsNone(t.tzinfo) |
---|
2770 | n/a | |
---|
2771 | n/a | def test_zones(self): |
---|
2772 | n/a | est = FixedOffset(-300, "EST", 1) |
---|
2773 | n/a | utc = FixedOffset(0, "UTC", -2) |
---|
2774 | n/a | met = FixedOffset(60, "MET", 3) |
---|
2775 | n/a | t1 = time( 7, 47, tzinfo=est) |
---|
2776 | n/a | t2 = time(12, 47, tzinfo=utc) |
---|
2777 | n/a | t3 = time(13, 47, tzinfo=met) |
---|
2778 | n/a | t4 = time(microsecond=40) |
---|
2779 | n/a | t5 = time(microsecond=40, tzinfo=utc) |
---|
2780 | n/a | |
---|
2781 | n/a | self.assertEqual(t1.tzinfo, est) |
---|
2782 | n/a | self.assertEqual(t2.tzinfo, utc) |
---|
2783 | n/a | self.assertEqual(t3.tzinfo, met) |
---|
2784 | n/a | self.assertIsNone(t4.tzinfo) |
---|
2785 | n/a | self.assertEqual(t5.tzinfo, utc) |
---|
2786 | n/a | |
---|
2787 | n/a | self.assertEqual(t1.utcoffset(), timedelta(minutes=-300)) |
---|
2788 | n/a | self.assertEqual(t2.utcoffset(), timedelta(minutes=0)) |
---|
2789 | n/a | self.assertEqual(t3.utcoffset(), timedelta(minutes=60)) |
---|
2790 | n/a | self.assertIsNone(t4.utcoffset()) |
---|
2791 | n/a | self.assertRaises(TypeError, t1.utcoffset, "no args") |
---|
2792 | n/a | |
---|
2793 | n/a | self.assertEqual(t1.tzname(), "EST") |
---|
2794 | n/a | self.assertEqual(t2.tzname(), "UTC") |
---|
2795 | n/a | self.assertEqual(t3.tzname(), "MET") |
---|
2796 | n/a | self.assertIsNone(t4.tzname()) |
---|
2797 | n/a | self.assertRaises(TypeError, t1.tzname, "no args") |
---|
2798 | n/a | |
---|
2799 | n/a | self.assertEqual(t1.dst(), timedelta(minutes=1)) |
---|
2800 | n/a | self.assertEqual(t2.dst(), timedelta(minutes=-2)) |
---|
2801 | n/a | self.assertEqual(t3.dst(), timedelta(minutes=3)) |
---|
2802 | n/a | self.assertIsNone(t4.dst()) |
---|
2803 | n/a | self.assertRaises(TypeError, t1.dst, "no args") |
---|
2804 | n/a | |
---|
2805 | n/a | self.assertEqual(hash(t1), hash(t2)) |
---|
2806 | n/a | self.assertEqual(hash(t1), hash(t3)) |
---|
2807 | n/a | self.assertEqual(hash(t2), hash(t3)) |
---|
2808 | n/a | |
---|
2809 | n/a | self.assertEqual(t1, t2) |
---|
2810 | n/a | self.assertEqual(t1, t3) |
---|
2811 | n/a | self.assertEqual(t2, t3) |
---|
2812 | n/a | self.assertNotEqual(t4, t5) # mixed tz-aware & naive |
---|
2813 | n/a | self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive |
---|
2814 | n/a | self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive |
---|
2815 | n/a | |
---|
2816 | n/a | self.assertEqual(str(t1), "07:47:00-05:00") |
---|
2817 | n/a | self.assertEqual(str(t2), "12:47:00+00:00") |
---|
2818 | n/a | self.assertEqual(str(t3), "13:47:00+01:00") |
---|
2819 | n/a | self.assertEqual(str(t4), "00:00:00.000040") |
---|
2820 | n/a | self.assertEqual(str(t5), "00:00:00.000040+00:00") |
---|
2821 | n/a | |
---|
2822 | n/a | self.assertEqual(t1.isoformat(), "07:47:00-05:00") |
---|
2823 | n/a | self.assertEqual(t2.isoformat(), "12:47:00+00:00") |
---|
2824 | n/a | self.assertEqual(t3.isoformat(), "13:47:00+01:00") |
---|
2825 | n/a | self.assertEqual(t4.isoformat(), "00:00:00.000040") |
---|
2826 | n/a | self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00") |
---|
2827 | n/a | |
---|
2828 | n/a | d = 'datetime.time' |
---|
2829 | n/a | self.assertEqual(repr(t1), d + "(7, 47, tzinfo=est)") |
---|
2830 | n/a | self.assertEqual(repr(t2), d + "(12, 47, tzinfo=utc)") |
---|
2831 | n/a | self.assertEqual(repr(t3), d + "(13, 47, tzinfo=met)") |
---|
2832 | n/a | self.assertEqual(repr(t4), d + "(0, 0, 0, 40)") |
---|
2833 | n/a | self.assertEqual(repr(t5), d + "(0, 0, 0, 40, tzinfo=utc)") |
---|
2834 | n/a | |
---|
2835 | n/a | self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"), |
---|
2836 | n/a | "07:47:00 %Z=EST %z=-0500") |
---|
2837 | n/a | self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") |
---|
2838 | n/a | self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100") |
---|
2839 | n/a | |
---|
2840 | n/a | yuck = FixedOffset(-1439, "%z %Z %%z%%Z") |
---|
2841 | n/a | t1 = time(23, 59, tzinfo=yuck) |
---|
2842 | n/a | self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"), |
---|
2843 | n/a | "23:59 %Z='%z %Z %%z%%Z' %z='-2359'") |
---|
2844 | n/a | |
---|
2845 | n/a | # Check that an invalid tzname result raises an exception. |
---|
2846 | n/a | class Badtzname(tzinfo): |
---|
2847 | n/a | tz = 42 |
---|
2848 | n/a | def tzname(self, dt): return self.tz |
---|
2849 | n/a | t = time(2, 3, 4, tzinfo=Badtzname()) |
---|
2850 | n/a | self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04") |
---|
2851 | n/a | self.assertRaises(TypeError, t.strftime, "%Z") |
---|
2852 | n/a | |
---|
2853 | n/a | # Issue #6697: |
---|
2854 | n/a | if '_Fast' in str(self): |
---|
2855 | n/a | Badtzname.tz = '\ud800' |
---|
2856 | n/a | self.assertRaises(ValueError, t.strftime, "%Z") |
---|
2857 | n/a | |
---|
2858 | n/a | def test_hash_edge_cases(self): |
---|
2859 | n/a | # Offsets that overflow a basic time. |
---|
2860 | n/a | t1 = self.theclass(0, 1, 2, 3, tzinfo=FixedOffset(1439, "")) |
---|
2861 | n/a | t2 = self.theclass(0, 0, 2, 3, tzinfo=FixedOffset(1438, "")) |
---|
2862 | n/a | self.assertEqual(hash(t1), hash(t2)) |
---|
2863 | n/a | |
---|
2864 | n/a | t1 = self.theclass(23, 58, 6, 100, tzinfo=FixedOffset(-1000, "")) |
---|
2865 | n/a | t2 = self.theclass(23, 48, 6, 100, tzinfo=FixedOffset(-1010, "")) |
---|
2866 | n/a | self.assertEqual(hash(t1), hash(t2)) |
---|
2867 | n/a | |
---|
2868 | n/a | def test_pickling(self): |
---|
2869 | n/a | # Try one without a tzinfo. |
---|
2870 | n/a | args = 20, 59, 16, 64**2 |
---|
2871 | n/a | orig = self.theclass(*args) |
---|
2872 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
2873 | n/a | green = pickler.dumps(orig, proto) |
---|
2874 | n/a | derived = unpickler.loads(green) |
---|
2875 | n/a | self.assertEqual(orig, derived) |
---|
2876 | n/a | self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) |
---|
2877 | n/a | |
---|
2878 | n/a | # Try one with a tzinfo. |
---|
2879 | n/a | tinfo = PicklableFixedOffset(-300, 'cookie') |
---|
2880 | n/a | orig = self.theclass(5, 6, 7, tzinfo=tinfo) |
---|
2881 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
2882 | n/a | green = pickler.dumps(orig, proto) |
---|
2883 | n/a | derived = unpickler.loads(green) |
---|
2884 | n/a | self.assertEqual(orig, derived) |
---|
2885 | n/a | self.assertIsInstance(derived.tzinfo, PicklableFixedOffset) |
---|
2886 | n/a | self.assertEqual(derived.utcoffset(), timedelta(minutes=-300)) |
---|
2887 | n/a | self.assertEqual(derived.tzname(), 'cookie') |
---|
2888 | n/a | self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) |
---|
2889 | n/a | |
---|
2890 | n/a | def test_more_bool(self): |
---|
2891 | n/a | # time is always True. |
---|
2892 | n/a | cls = self.theclass |
---|
2893 | n/a | |
---|
2894 | n/a | t = cls(0, tzinfo=FixedOffset(-300, "")) |
---|
2895 | n/a | self.assertTrue(t) |
---|
2896 | n/a | |
---|
2897 | n/a | t = cls(5, tzinfo=FixedOffset(-300, "")) |
---|
2898 | n/a | self.assertTrue(t) |
---|
2899 | n/a | |
---|
2900 | n/a | t = cls(5, tzinfo=FixedOffset(300, "")) |
---|
2901 | n/a | self.assertTrue(t) |
---|
2902 | n/a | |
---|
2903 | n/a | t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, "")) |
---|
2904 | n/a | self.assertTrue(t) |
---|
2905 | n/a | |
---|
2906 | n/a | def test_replace(self): |
---|
2907 | n/a | cls = self.theclass |
---|
2908 | n/a | z100 = FixedOffset(100, "+100") |
---|
2909 | n/a | zm200 = FixedOffset(timedelta(minutes=-200), "-200") |
---|
2910 | n/a | args = [1, 2, 3, 4, z100] |
---|
2911 | n/a | base = cls(*args) |
---|
2912 | n/a | self.assertEqual(base, base.replace()) |
---|
2913 | n/a | |
---|
2914 | n/a | i = 0 |
---|
2915 | n/a | for name, newval in (("hour", 5), |
---|
2916 | n/a | ("minute", 6), |
---|
2917 | n/a | ("second", 7), |
---|
2918 | n/a | ("microsecond", 8), |
---|
2919 | n/a | ("tzinfo", zm200)): |
---|
2920 | n/a | newargs = args[:] |
---|
2921 | n/a | newargs[i] = newval |
---|
2922 | n/a | expected = cls(*newargs) |
---|
2923 | n/a | got = base.replace(**{name: newval}) |
---|
2924 | n/a | self.assertEqual(expected, got) |
---|
2925 | n/a | i += 1 |
---|
2926 | n/a | |
---|
2927 | n/a | # Ensure we can get rid of a tzinfo. |
---|
2928 | n/a | self.assertEqual(base.tzname(), "+100") |
---|
2929 | n/a | base2 = base.replace(tzinfo=None) |
---|
2930 | n/a | self.assertIsNone(base2.tzinfo) |
---|
2931 | n/a | self.assertIsNone(base2.tzname()) |
---|
2932 | n/a | |
---|
2933 | n/a | # Ensure we can add one. |
---|
2934 | n/a | base3 = base2.replace(tzinfo=z100) |
---|
2935 | n/a | self.assertEqual(base, base3) |
---|
2936 | n/a | self.assertIs(base.tzinfo, base3.tzinfo) |
---|
2937 | n/a | |
---|
2938 | n/a | # Out of bounds. |
---|
2939 | n/a | base = cls(1) |
---|
2940 | n/a | self.assertRaises(ValueError, base.replace, hour=24) |
---|
2941 | n/a | self.assertRaises(ValueError, base.replace, minute=-1) |
---|
2942 | n/a | self.assertRaises(ValueError, base.replace, second=100) |
---|
2943 | n/a | self.assertRaises(ValueError, base.replace, microsecond=1000000) |
---|
2944 | n/a | |
---|
2945 | n/a | def test_mixed_compare(self): |
---|
2946 | n/a | t1 = time(1, 2, 3) |
---|
2947 | n/a | t2 = time(1, 2, 3) |
---|
2948 | n/a | self.assertEqual(t1, t2) |
---|
2949 | n/a | t2 = t2.replace(tzinfo=None) |
---|
2950 | n/a | self.assertEqual(t1, t2) |
---|
2951 | n/a | t2 = t2.replace(tzinfo=FixedOffset(None, "")) |
---|
2952 | n/a | self.assertEqual(t1, t2) |
---|
2953 | n/a | t2 = t2.replace(tzinfo=FixedOffset(0, "")) |
---|
2954 | n/a | self.assertNotEqual(t1, t2) |
---|
2955 | n/a | |
---|
2956 | n/a | # In time w/ identical tzinfo objects, utcoffset is ignored. |
---|
2957 | n/a | class Varies(tzinfo): |
---|
2958 | n/a | def __init__(self): |
---|
2959 | n/a | self.offset = timedelta(minutes=22) |
---|
2960 | n/a | def utcoffset(self, t): |
---|
2961 | n/a | self.offset += timedelta(minutes=1) |
---|
2962 | n/a | return self.offset |
---|
2963 | n/a | |
---|
2964 | n/a | v = Varies() |
---|
2965 | n/a | t1 = t2.replace(tzinfo=v) |
---|
2966 | n/a | t2 = t2.replace(tzinfo=v) |
---|
2967 | n/a | self.assertEqual(t1.utcoffset(), timedelta(minutes=23)) |
---|
2968 | n/a | self.assertEqual(t2.utcoffset(), timedelta(minutes=24)) |
---|
2969 | n/a | self.assertEqual(t1, t2) |
---|
2970 | n/a | |
---|
2971 | n/a | # But if they're not identical, it isn't ignored. |
---|
2972 | n/a | t2 = t2.replace(tzinfo=Varies()) |
---|
2973 | n/a | self.assertTrue(t1 < t2) # t1's offset counter still going up |
---|
2974 | n/a | |
---|
2975 | n/a | def test_subclass_timetz(self): |
---|
2976 | n/a | |
---|
2977 | n/a | class C(self.theclass): |
---|
2978 | n/a | theAnswer = 42 |
---|
2979 | n/a | |
---|
2980 | n/a | def __new__(cls, *args, **kws): |
---|
2981 | n/a | temp = kws.copy() |
---|
2982 | n/a | extra = temp.pop('extra') |
---|
2983 | n/a | result = self.theclass.__new__(cls, *args, **temp) |
---|
2984 | n/a | result.extra = extra |
---|
2985 | n/a | return result |
---|
2986 | n/a | |
---|
2987 | n/a | def newmeth(self, start): |
---|
2988 | n/a | return start + self.hour + self.second |
---|
2989 | n/a | |
---|
2990 | n/a | args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1) |
---|
2991 | n/a | |
---|
2992 | n/a | dt1 = self.theclass(*args) |
---|
2993 | n/a | dt2 = C(*args, **{'extra': 7}) |
---|
2994 | n/a | |
---|
2995 | n/a | self.assertEqual(dt2.__class__, C) |
---|
2996 | n/a | self.assertEqual(dt2.theAnswer, 42) |
---|
2997 | n/a | self.assertEqual(dt2.extra, 7) |
---|
2998 | n/a | self.assertEqual(dt1.utcoffset(), dt2.utcoffset()) |
---|
2999 | n/a | self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7) |
---|
3000 | n/a | |
---|
3001 | n/a | |
---|
3002 | n/a | # Testing datetime objects with a non-None tzinfo. |
---|
3003 | n/a | |
---|
3004 | n/a | class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase): |
---|
3005 | n/a | theclass = datetime |
---|
3006 | n/a | |
---|
3007 | n/a | def test_trivial(self): |
---|
3008 | n/a | dt = self.theclass(1, 2, 3, 4, 5, 6, 7) |
---|
3009 | n/a | self.assertEqual(dt.year, 1) |
---|
3010 | n/a | self.assertEqual(dt.month, 2) |
---|
3011 | n/a | self.assertEqual(dt.day, 3) |
---|
3012 | n/a | self.assertEqual(dt.hour, 4) |
---|
3013 | n/a | self.assertEqual(dt.minute, 5) |
---|
3014 | n/a | self.assertEqual(dt.second, 6) |
---|
3015 | n/a | self.assertEqual(dt.microsecond, 7) |
---|
3016 | n/a | self.assertEqual(dt.tzinfo, None) |
---|
3017 | n/a | |
---|
3018 | n/a | def test_even_more_compare(self): |
---|
3019 | n/a | # The test_compare() and test_more_compare() inherited from TestDate |
---|
3020 | n/a | # and TestDateTime covered non-tzinfo cases. |
---|
3021 | n/a | |
---|
3022 | n/a | # Smallest possible after UTC adjustment. |
---|
3023 | n/a | t1 = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "")) |
---|
3024 | n/a | # Largest possible after UTC adjustment. |
---|
3025 | n/a | t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, |
---|
3026 | n/a | tzinfo=FixedOffset(-1439, "")) |
---|
3027 | n/a | |
---|
3028 | n/a | # Make sure those compare correctly, and w/o overflow. |
---|
3029 | n/a | self.assertTrue(t1 < t2) |
---|
3030 | n/a | self.assertTrue(t1 != t2) |
---|
3031 | n/a | self.assertTrue(t2 > t1) |
---|
3032 | n/a | |
---|
3033 | n/a | self.assertEqual(t1, t1) |
---|
3034 | n/a | self.assertEqual(t2, t2) |
---|
3035 | n/a | |
---|
3036 | n/a | # Equal afer adjustment. |
---|
3037 | n/a | t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, "")) |
---|
3038 | n/a | t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3*60+13+2, "")) |
---|
3039 | n/a | self.assertEqual(t1, t2) |
---|
3040 | n/a | |
---|
3041 | n/a | # Change t1 not to subtract a minute, and t1 should be larger. |
---|
3042 | n/a | t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, "")) |
---|
3043 | n/a | self.assertTrue(t1 > t2) |
---|
3044 | n/a | |
---|
3045 | n/a | # Change t1 to subtract 2 minutes, and t1 should be smaller. |
---|
3046 | n/a | t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, "")) |
---|
3047 | n/a | self.assertTrue(t1 < t2) |
---|
3048 | n/a | |
---|
3049 | n/a | # Back to the original t1, but make seconds resolve it. |
---|
3050 | n/a | t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), |
---|
3051 | n/a | second=1) |
---|
3052 | n/a | self.assertTrue(t1 > t2) |
---|
3053 | n/a | |
---|
3054 | n/a | # Likewise, but make microseconds resolve it. |
---|
3055 | n/a | t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""), |
---|
3056 | n/a | microsecond=1) |
---|
3057 | n/a | self.assertTrue(t1 > t2) |
---|
3058 | n/a | |
---|
3059 | n/a | # Make t2 naive and it should differ. |
---|
3060 | n/a | t2 = self.theclass.min |
---|
3061 | n/a | self.assertNotEqual(t1, t2) |
---|
3062 | n/a | self.assertEqual(t2, t2) |
---|
3063 | n/a | |
---|
3064 | n/a | # It's also naive if it has tzinfo but tzinfo.utcoffset() is None. |
---|
3065 | n/a | class Naive(tzinfo): |
---|
3066 | n/a | def utcoffset(self, dt): return None |
---|
3067 | n/a | t2 = self.theclass(5, 6, 7, tzinfo=Naive()) |
---|
3068 | n/a | self.assertNotEqual(t1, t2) |
---|
3069 | n/a | self.assertEqual(t2, t2) |
---|
3070 | n/a | |
---|
3071 | n/a | # OTOH, it's OK to compare two of these mixing the two ways of being |
---|
3072 | n/a | # naive. |
---|
3073 | n/a | t1 = self.theclass(5, 6, 7) |
---|
3074 | n/a | self.assertEqual(t1, t2) |
---|
3075 | n/a | |
---|
3076 | n/a | # Try a bogus uctoffset. |
---|
3077 | n/a | class Bogus(tzinfo): |
---|
3078 | n/a | def utcoffset(self, dt): |
---|
3079 | n/a | return timedelta(minutes=1440) # out of bounds |
---|
3080 | n/a | t1 = self.theclass(2, 2, 2, tzinfo=Bogus()) |
---|
3081 | n/a | t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, "")) |
---|
3082 | n/a | self.assertRaises(ValueError, lambda: t1 == t2) |
---|
3083 | n/a | |
---|
3084 | n/a | def test_pickling(self): |
---|
3085 | n/a | # Try one without a tzinfo. |
---|
3086 | n/a | args = 6, 7, 23, 20, 59, 1, 64**2 |
---|
3087 | n/a | orig = self.theclass(*args) |
---|
3088 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
3089 | n/a | green = pickler.dumps(orig, proto) |
---|
3090 | n/a | derived = unpickler.loads(green) |
---|
3091 | n/a | self.assertEqual(orig, derived) |
---|
3092 | n/a | self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) |
---|
3093 | n/a | |
---|
3094 | n/a | # Try one with a tzinfo. |
---|
3095 | n/a | tinfo = PicklableFixedOffset(-300, 'cookie') |
---|
3096 | n/a | orig = self.theclass(*args, **{'tzinfo': tinfo}) |
---|
3097 | n/a | derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0)) |
---|
3098 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
3099 | n/a | green = pickler.dumps(orig, proto) |
---|
3100 | n/a | derived = unpickler.loads(green) |
---|
3101 | n/a | self.assertEqual(orig, derived) |
---|
3102 | n/a | self.assertIsInstance(derived.tzinfo, PicklableFixedOffset) |
---|
3103 | n/a | self.assertEqual(derived.utcoffset(), timedelta(minutes=-300)) |
---|
3104 | n/a | self.assertEqual(derived.tzname(), 'cookie') |
---|
3105 | n/a | self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) |
---|
3106 | n/a | |
---|
3107 | n/a | def test_extreme_hashes(self): |
---|
3108 | n/a | # If an attempt is made to hash these via subtracting the offset |
---|
3109 | n/a | # then hashing a datetime object, OverflowError results. The |
---|
3110 | n/a | # Python implementation used to blow up here. |
---|
3111 | n/a | t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "")) |
---|
3112 | n/a | hash(t) |
---|
3113 | n/a | t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, |
---|
3114 | n/a | tzinfo=FixedOffset(-1439, "")) |
---|
3115 | n/a | hash(t) |
---|
3116 | n/a | |
---|
3117 | n/a | # OTOH, an OOB offset should blow up. |
---|
3118 | n/a | t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, "")) |
---|
3119 | n/a | self.assertRaises(ValueError, hash, t) |
---|
3120 | n/a | |
---|
3121 | n/a | def test_zones(self): |
---|
3122 | n/a | est = FixedOffset(-300, "EST") |
---|
3123 | n/a | utc = FixedOffset(0, "UTC") |
---|
3124 | n/a | met = FixedOffset(60, "MET") |
---|
3125 | n/a | t1 = datetime(2002, 3, 19, 7, 47, tzinfo=est) |
---|
3126 | n/a | t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc) |
---|
3127 | n/a | t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met) |
---|
3128 | n/a | self.assertEqual(t1.tzinfo, est) |
---|
3129 | n/a | self.assertEqual(t2.tzinfo, utc) |
---|
3130 | n/a | self.assertEqual(t3.tzinfo, met) |
---|
3131 | n/a | self.assertEqual(t1.utcoffset(), timedelta(minutes=-300)) |
---|
3132 | n/a | self.assertEqual(t2.utcoffset(), timedelta(minutes=0)) |
---|
3133 | n/a | self.assertEqual(t3.utcoffset(), timedelta(minutes=60)) |
---|
3134 | n/a | self.assertEqual(t1.tzname(), "EST") |
---|
3135 | n/a | self.assertEqual(t2.tzname(), "UTC") |
---|
3136 | n/a | self.assertEqual(t3.tzname(), "MET") |
---|
3137 | n/a | self.assertEqual(hash(t1), hash(t2)) |
---|
3138 | n/a | self.assertEqual(hash(t1), hash(t3)) |
---|
3139 | n/a | self.assertEqual(hash(t2), hash(t3)) |
---|
3140 | n/a | self.assertEqual(t1, t2) |
---|
3141 | n/a | self.assertEqual(t1, t3) |
---|
3142 | n/a | self.assertEqual(t2, t3) |
---|
3143 | n/a | self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00") |
---|
3144 | n/a | self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00") |
---|
3145 | n/a | self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00") |
---|
3146 | n/a | d = 'datetime.datetime(2002, 3, 19, ' |
---|
3147 | n/a | self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)") |
---|
3148 | n/a | self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)") |
---|
3149 | n/a | self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)") |
---|
3150 | n/a | |
---|
3151 | n/a | def test_combine(self): |
---|
3152 | n/a | met = FixedOffset(60, "MET") |
---|
3153 | n/a | d = date(2002, 3, 4) |
---|
3154 | n/a | tz = time(18, 45, 3, 1234, tzinfo=met) |
---|
3155 | n/a | dt = datetime.combine(d, tz) |
---|
3156 | n/a | self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234, |
---|
3157 | n/a | tzinfo=met)) |
---|
3158 | n/a | |
---|
3159 | n/a | def test_extract(self): |
---|
3160 | n/a | met = FixedOffset(60, "MET") |
---|
3161 | n/a | dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met) |
---|
3162 | n/a | self.assertEqual(dt.date(), date(2002, 3, 4)) |
---|
3163 | n/a | self.assertEqual(dt.time(), time(18, 45, 3, 1234)) |
---|
3164 | n/a | self.assertEqual(dt.timetz(), time(18, 45, 3, 1234, tzinfo=met)) |
---|
3165 | n/a | |
---|
3166 | n/a | def test_tz_aware_arithmetic(self): |
---|
3167 | n/a | import random |
---|
3168 | n/a | |
---|
3169 | n/a | now = self.theclass.now() |
---|
3170 | n/a | tz55 = FixedOffset(-330, "west 5:30") |
---|
3171 | n/a | timeaware = now.time().replace(tzinfo=tz55) |
---|
3172 | n/a | nowaware = self.theclass.combine(now.date(), timeaware) |
---|
3173 | n/a | self.assertIs(nowaware.tzinfo, tz55) |
---|
3174 | n/a | self.assertEqual(nowaware.timetz(), timeaware) |
---|
3175 | n/a | |
---|
3176 | n/a | # Can't mix aware and non-aware. |
---|
3177 | n/a | self.assertRaises(TypeError, lambda: now - nowaware) |
---|
3178 | n/a | self.assertRaises(TypeError, lambda: nowaware - now) |
---|
3179 | n/a | |
---|
3180 | n/a | # And adding datetime's doesn't make sense, aware or not. |
---|
3181 | n/a | self.assertRaises(TypeError, lambda: now + nowaware) |
---|
3182 | n/a | self.assertRaises(TypeError, lambda: nowaware + now) |
---|
3183 | n/a | self.assertRaises(TypeError, lambda: nowaware + nowaware) |
---|
3184 | n/a | |
---|
3185 | n/a | # Subtracting should yield 0. |
---|
3186 | n/a | self.assertEqual(now - now, timedelta(0)) |
---|
3187 | n/a | self.assertEqual(nowaware - nowaware, timedelta(0)) |
---|
3188 | n/a | |
---|
3189 | n/a | # Adding a delta should preserve tzinfo. |
---|
3190 | n/a | delta = timedelta(weeks=1, minutes=12, microseconds=5678) |
---|
3191 | n/a | nowawareplus = nowaware + delta |
---|
3192 | n/a | self.assertIs(nowaware.tzinfo, tz55) |
---|
3193 | n/a | nowawareplus2 = delta + nowaware |
---|
3194 | n/a | self.assertIs(nowawareplus2.tzinfo, tz55) |
---|
3195 | n/a | self.assertEqual(nowawareplus, nowawareplus2) |
---|
3196 | n/a | |
---|
3197 | n/a | # that - delta should be what we started with, and that - what we |
---|
3198 | n/a | # started with should be delta. |
---|
3199 | n/a | diff = nowawareplus - delta |
---|
3200 | n/a | self.assertIs(diff.tzinfo, tz55) |
---|
3201 | n/a | self.assertEqual(nowaware, diff) |
---|
3202 | n/a | self.assertRaises(TypeError, lambda: delta - nowawareplus) |
---|
3203 | n/a | self.assertEqual(nowawareplus - nowaware, delta) |
---|
3204 | n/a | |
---|
3205 | n/a | # Make up a random timezone. |
---|
3206 | n/a | tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone") |
---|
3207 | n/a | # Attach it to nowawareplus. |
---|
3208 | n/a | nowawareplus = nowawareplus.replace(tzinfo=tzr) |
---|
3209 | n/a | self.assertIs(nowawareplus.tzinfo, tzr) |
---|
3210 | n/a | # Make sure the difference takes the timezone adjustments into account. |
---|
3211 | n/a | got = nowaware - nowawareplus |
---|
3212 | n/a | # Expected: (nowaware base - nowaware offset) - |
---|
3213 | n/a | # (nowawareplus base - nowawareplus offset) = |
---|
3214 | n/a | # (nowaware base - nowawareplus base) + |
---|
3215 | n/a | # (nowawareplus offset - nowaware offset) = |
---|
3216 | n/a | # -delta + nowawareplus offset - nowaware offset |
---|
3217 | n/a | expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta |
---|
3218 | n/a | self.assertEqual(got, expected) |
---|
3219 | n/a | |
---|
3220 | n/a | # Try max possible difference. |
---|
3221 | n/a | min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min")) |
---|
3222 | n/a | max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, |
---|
3223 | n/a | tzinfo=FixedOffset(-1439, "max")) |
---|
3224 | n/a | maxdiff = max - min |
---|
3225 | n/a | self.assertEqual(maxdiff, self.theclass.max - self.theclass.min + |
---|
3226 | n/a | timedelta(minutes=2*1439)) |
---|
3227 | n/a | # Different tzinfo, but the same offset |
---|
3228 | n/a | tza = timezone(HOUR, 'A') |
---|
3229 | n/a | tzb = timezone(HOUR, 'B') |
---|
3230 | n/a | delta = min.replace(tzinfo=tza) - max.replace(tzinfo=tzb) |
---|
3231 | n/a | self.assertEqual(delta, self.theclass.min - self.theclass.max) |
---|
3232 | n/a | |
---|
3233 | n/a | def test_tzinfo_now(self): |
---|
3234 | n/a | meth = self.theclass.now |
---|
3235 | n/a | # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). |
---|
3236 | n/a | base = meth() |
---|
3237 | n/a | # Try with and without naming the keyword. |
---|
3238 | n/a | off42 = FixedOffset(42, "42") |
---|
3239 | n/a | another = meth(off42) |
---|
3240 | n/a | again = meth(tz=off42) |
---|
3241 | n/a | self.assertIs(another.tzinfo, again.tzinfo) |
---|
3242 | n/a | self.assertEqual(another.utcoffset(), timedelta(minutes=42)) |
---|
3243 | n/a | # Bad argument with and w/o naming the keyword. |
---|
3244 | n/a | self.assertRaises(TypeError, meth, 16) |
---|
3245 | n/a | self.assertRaises(TypeError, meth, tzinfo=16) |
---|
3246 | n/a | # Bad keyword name. |
---|
3247 | n/a | self.assertRaises(TypeError, meth, tinfo=off42) |
---|
3248 | n/a | # Too many args. |
---|
3249 | n/a | self.assertRaises(TypeError, meth, off42, off42) |
---|
3250 | n/a | |
---|
3251 | n/a | # We don't know which time zone we're in, and don't have a tzinfo |
---|
3252 | n/a | # class to represent it, so seeing whether a tz argument actually |
---|
3253 | n/a | # does a conversion is tricky. |
---|
3254 | n/a | utc = FixedOffset(0, "utc", 0) |
---|
3255 | n/a | for weirdtz in [FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0), |
---|
3256 | n/a | timezone(timedelta(hours=15, minutes=58), "weirdtz"),]: |
---|
3257 | n/a | for dummy in range(3): |
---|
3258 | n/a | now = datetime.now(weirdtz) |
---|
3259 | n/a | self.assertIs(now.tzinfo, weirdtz) |
---|
3260 | n/a | utcnow = datetime.utcnow().replace(tzinfo=utc) |
---|
3261 | n/a | now2 = utcnow.astimezone(weirdtz) |
---|
3262 | n/a | if abs(now - now2) < timedelta(seconds=30): |
---|
3263 | n/a | break |
---|
3264 | n/a | # Else the code is broken, or more than 30 seconds passed between |
---|
3265 | n/a | # calls; assuming the latter, just try again. |
---|
3266 | n/a | else: |
---|
3267 | n/a | # Three strikes and we're out. |
---|
3268 | n/a | self.fail("utcnow(), now(tz), or astimezone() may be broken") |
---|
3269 | n/a | |
---|
3270 | n/a | def test_tzinfo_fromtimestamp(self): |
---|
3271 | n/a | import time |
---|
3272 | n/a | meth = self.theclass.fromtimestamp |
---|
3273 | n/a | ts = time.time() |
---|
3274 | n/a | # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). |
---|
3275 | n/a | base = meth(ts) |
---|
3276 | n/a | # Try with and without naming the keyword. |
---|
3277 | n/a | off42 = FixedOffset(42, "42") |
---|
3278 | n/a | another = meth(ts, off42) |
---|
3279 | n/a | again = meth(ts, tz=off42) |
---|
3280 | n/a | self.assertIs(another.tzinfo, again.tzinfo) |
---|
3281 | n/a | self.assertEqual(another.utcoffset(), timedelta(minutes=42)) |
---|
3282 | n/a | # Bad argument with and w/o naming the keyword. |
---|
3283 | n/a | self.assertRaises(TypeError, meth, ts, 16) |
---|
3284 | n/a | self.assertRaises(TypeError, meth, ts, tzinfo=16) |
---|
3285 | n/a | # Bad keyword name. |
---|
3286 | n/a | self.assertRaises(TypeError, meth, ts, tinfo=off42) |
---|
3287 | n/a | # Too many args. |
---|
3288 | n/a | self.assertRaises(TypeError, meth, ts, off42, off42) |
---|
3289 | n/a | # Too few args. |
---|
3290 | n/a | self.assertRaises(TypeError, meth) |
---|
3291 | n/a | |
---|
3292 | n/a | # Try to make sure tz= actually does some conversion. |
---|
3293 | n/a | timestamp = 1000000000 |
---|
3294 | n/a | utcdatetime = datetime.utcfromtimestamp(timestamp) |
---|
3295 | n/a | # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take. |
---|
3296 | n/a | # But on some flavor of Mac, it's nowhere near that. So we can't have |
---|
3297 | n/a | # any idea here what time that actually is, we can only test that |
---|
3298 | n/a | # relative changes match. |
---|
3299 | n/a | utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero |
---|
3300 | n/a | tz = FixedOffset(utcoffset, "tz", 0) |
---|
3301 | n/a | expected = utcdatetime + utcoffset |
---|
3302 | n/a | got = datetime.fromtimestamp(timestamp, tz) |
---|
3303 | n/a | self.assertEqual(expected, got.replace(tzinfo=None)) |
---|
3304 | n/a | |
---|
3305 | n/a | def test_tzinfo_utcnow(self): |
---|
3306 | n/a | meth = self.theclass.utcnow |
---|
3307 | n/a | # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). |
---|
3308 | n/a | base = meth() |
---|
3309 | n/a | # Try with and without naming the keyword; for whatever reason, |
---|
3310 | n/a | # utcnow() doesn't accept a tzinfo argument. |
---|
3311 | n/a | off42 = FixedOffset(42, "42") |
---|
3312 | n/a | self.assertRaises(TypeError, meth, off42) |
---|
3313 | n/a | self.assertRaises(TypeError, meth, tzinfo=off42) |
---|
3314 | n/a | |
---|
3315 | n/a | def test_tzinfo_utcfromtimestamp(self): |
---|
3316 | n/a | import time |
---|
3317 | n/a | meth = self.theclass.utcfromtimestamp |
---|
3318 | n/a | ts = time.time() |
---|
3319 | n/a | # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). |
---|
3320 | n/a | base = meth(ts) |
---|
3321 | n/a | # Try with and without naming the keyword; for whatever reason, |
---|
3322 | n/a | # utcfromtimestamp() doesn't accept a tzinfo argument. |
---|
3323 | n/a | off42 = FixedOffset(42, "42") |
---|
3324 | n/a | self.assertRaises(TypeError, meth, ts, off42) |
---|
3325 | n/a | self.assertRaises(TypeError, meth, ts, tzinfo=off42) |
---|
3326 | n/a | |
---|
3327 | n/a | def test_tzinfo_timetuple(self): |
---|
3328 | n/a | # TestDateTime tested most of this. datetime adds a twist to the |
---|
3329 | n/a | # DST flag. |
---|
3330 | n/a | class DST(tzinfo): |
---|
3331 | n/a | def __init__(self, dstvalue): |
---|
3332 | n/a | if isinstance(dstvalue, int): |
---|
3333 | n/a | dstvalue = timedelta(minutes=dstvalue) |
---|
3334 | n/a | self.dstvalue = dstvalue |
---|
3335 | n/a | def dst(self, dt): |
---|
3336 | n/a | return self.dstvalue |
---|
3337 | n/a | |
---|
3338 | n/a | cls = self.theclass |
---|
3339 | n/a | for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1): |
---|
3340 | n/a | d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue)) |
---|
3341 | n/a | t = d.timetuple() |
---|
3342 | n/a | self.assertEqual(1, t.tm_year) |
---|
3343 | n/a | self.assertEqual(1, t.tm_mon) |
---|
3344 | n/a | self.assertEqual(1, t.tm_mday) |
---|
3345 | n/a | self.assertEqual(10, t.tm_hour) |
---|
3346 | n/a | self.assertEqual(20, t.tm_min) |
---|
3347 | n/a | self.assertEqual(30, t.tm_sec) |
---|
3348 | n/a | self.assertEqual(0, t.tm_wday) |
---|
3349 | n/a | self.assertEqual(1, t.tm_yday) |
---|
3350 | n/a | self.assertEqual(flag, t.tm_isdst) |
---|
3351 | n/a | |
---|
3352 | n/a | # dst() returns wrong type. |
---|
3353 | n/a | self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple) |
---|
3354 | n/a | |
---|
3355 | n/a | # dst() at the edge. |
---|
3356 | n/a | self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1) |
---|
3357 | n/a | self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1) |
---|
3358 | n/a | |
---|
3359 | n/a | # dst() out of range. |
---|
3360 | n/a | self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple) |
---|
3361 | n/a | self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple) |
---|
3362 | n/a | |
---|
3363 | n/a | def test_utctimetuple(self): |
---|
3364 | n/a | class DST(tzinfo): |
---|
3365 | n/a | def __init__(self, dstvalue=0): |
---|
3366 | n/a | if isinstance(dstvalue, int): |
---|
3367 | n/a | dstvalue = timedelta(minutes=dstvalue) |
---|
3368 | n/a | self.dstvalue = dstvalue |
---|
3369 | n/a | def dst(self, dt): |
---|
3370 | n/a | return self.dstvalue |
---|
3371 | n/a | |
---|
3372 | n/a | cls = self.theclass |
---|
3373 | n/a | # This can't work: DST didn't implement utcoffset. |
---|
3374 | n/a | self.assertRaises(NotImplementedError, |
---|
3375 | n/a | cls(1, 1, 1, tzinfo=DST(0)).utcoffset) |
---|
3376 | n/a | |
---|
3377 | n/a | class UOFS(DST): |
---|
3378 | n/a | def __init__(self, uofs, dofs=None): |
---|
3379 | n/a | DST.__init__(self, dofs) |
---|
3380 | n/a | self.uofs = timedelta(minutes=uofs) |
---|
3381 | n/a | def utcoffset(self, dt): |
---|
3382 | n/a | return self.uofs |
---|
3383 | n/a | |
---|
3384 | n/a | for dstvalue in -33, 33, 0, None: |
---|
3385 | n/a | d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=UOFS(-53, dstvalue)) |
---|
3386 | n/a | t = d.utctimetuple() |
---|
3387 | n/a | self.assertEqual(d.year, t.tm_year) |
---|
3388 | n/a | self.assertEqual(d.month, t.tm_mon) |
---|
3389 | n/a | self.assertEqual(d.day, t.tm_mday) |
---|
3390 | n/a | self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm |
---|
3391 | n/a | self.assertEqual(13, t.tm_min) |
---|
3392 | n/a | self.assertEqual(d.second, t.tm_sec) |
---|
3393 | n/a | self.assertEqual(d.weekday(), t.tm_wday) |
---|
3394 | n/a | self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1, |
---|
3395 | n/a | t.tm_yday) |
---|
3396 | n/a | # Ensure tm_isdst is 0 regardless of what dst() says: DST |
---|
3397 | n/a | # is never in effect for a UTC time. |
---|
3398 | n/a | self.assertEqual(0, t.tm_isdst) |
---|
3399 | n/a | |
---|
3400 | n/a | # For naive datetime, utctimetuple == timetuple except for isdst |
---|
3401 | n/a | d = cls(1, 2, 3, 10, 20, 30, 40) |
---|
3402 | n/a | t = d.utctimetuple() |
---|
3403 | n/a | self.assertEqual(t[:-1], d.timetuple()[:-1]) |
---|
3404 | n/a | self.assertEqual(0, t.tm_isdst) |
---|
3405 | n/a | # Same if utcoffset is None |
---|
3406 | n/a | class NOFS(DST): |
---|
3407 | n/a | def utcoffset(self, dt): |
---|
3408 | n/a | return None |
---|
3409 | n/a | d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=NOFS()) |
---|
3410 | n/a | t = d.utctimetuple() |
---|
3411 | n/a | self.assertEqual(t[:-1], d.timetuple()[:-1]) |
---|
3412 | n/a | self.assertEqual(0, t.tm_isdst) |
---|
3413 | n/a | # Check that bad tzinfo is detected |
---|
3414 | n/a | class BOFS(DST): |
---|
3415 | n/a | def utcoffset(self, dt): |
---|
3416 | n/a | return "EST" |
---|
3417 | n/a | d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=BOFS()) |
---|
3418 | n/a | self.assertRaises(TypeError, d.utctimetuple) |
---|
3419 | n/a | |
---|
3420 | n/a | # Check that utctimetuple() is the same as |
---|
3421 | n/a | # astimezone(utc).timetuple() |
---|
3422 | n/a | d = cls(2010, 11, 13, 14, 15, 16, 171819) |
---|
3423 | n/a | for tz in [timezone.min, timezone.utc, timezone.max]: |
---|
3424 | n/a | dtz = d.replace(tzinfo=tz) |
---|
3425 | n/a | self.assertEqual(dtz.utctimetuple()[:-1], |
---|
3426 | n/a | dtz.astimezone(timezone.utc).timetuple()[:-1]) |
---|
3427 | n/a | # At the edges, UTC adjustment can produce years out-of-range |
---|
3428 | n/a | # for a datetime object. Ensure that an OverflowError is |
---|
3429 | n/a | # raised. |
---|
3430 | n/a | tiny = cls(MINYEAR, 1, 1, 0, 0, 37, tzinfo=UOFS(1439)) |
---|
3431 | n/a | # That goes back 1 minute less than a full day. |
---|
3432 | n/a | self.assertRaises(OverflowError, tiny.utctimetuple) |
---|
3433 | n/a | |
---|
3434 | n/a | huge = cls(MAXYEAR, 12, 31, 23, 59, 37, 999999, tzinfo=UOFS(-1439)) |
---|
3435 | n/a | # That goes forward 1 minute less than a full day. |
---|
3436 | n/a | self.assertRaises(OverflowError, huge.utctimetuple) |
---|
3437 | n/a | # More overflow cases |
---|
3438 | n/a | tiny = cls.min.replace(tzinfo=timezone(MINUTE)) |
---|
3439 | n/a | self.assertRaises(OverflowError, tiny.utctimetuple) |
---|
3440 | n/a | huge = cls.max.replace(tzinfo=timezone(-MINUTE)) |
---|
3441 | n/a | self.assertRaises(OverflowError, huge.utctimetuple) |
---|
3442 | n/a | |
---|
3443 | n/a | def test_tzinfo_isoformat(self): |
---|
3444 | n/a | zero = FixedOffset(0, "+00:00") |
---|
3445 | n/a | plus = FixedOffset(220, "+03:40") |
---|
3446 | n/a | minus = FixedOffset(-231, "-03:51") |
---|
3447 | n/a | unknown = FixedOffset(None, "") |
---|
3448 | n/a | |
---|
3449 | n/a | cls = self.theclass |
---|
3450 | n/a | datestr = '0001-02-03' |
---|
3451 | n/a | for ofs in None, zero, plus, minus, unknown: |
---|
3452 | n/a | for us in 0, 987001: |
---|
3453 | n/a | d = cls(1, 2, 3, 4, 5, 59, us, tzinfo=ofs) |
---|
3454 | n/a | timestr = '04:05:59' + (us and '.987001' or '') |
---|
3455 | n/a | ofsstr = ofs is not None and d.tzname() or '' |
---|
3456 | n/a | tailstr = timestr + ofsstr |
---|
3457 | n/a | iso = d.isoformat() |
---|
3458 | n/a | self.assertEqual(iso, datestr + 'T' + tailstr) |
---|
3459 | n/a | self.assertEqual(iso, d.isoformat('T')) |
---|
3460 | n/a | self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr) |
---|
3461 | n/a | self.assertEqual(d.isoformat('\u1234'), datestr + '\u1234' + tailstr) |
---|
3462 | n/a | self.assertEqual(str(d), datestr + ' ' + tailstr) |
---|
3463 | n/a | |
---|
3464 | n/a | def test_replace(self): |
---|
3465 | n/a | cls = self.theclass |
---|
3466 | n/a | z100 = FixedOffset(100, "+100") |
---|
3467 | n/a | zm200 = FixedOffset(timedelta(minutes=-200), "-200") |
---|
3468 | n/a | args = [1, 2, 3, 4, 5, 6, 7, z100] |
---|
3469 | n/a | base = cls(*args) |
---|
3470 | n/a | self.assertEqual(base, base.replace()) |
---|
3471 | n/a | |
---|
3472 | n/a | i = 0 |
---|
3473 | n/a | for name, newval in (("year", 2), |
---|
3474 | n/a | ("month", 3), |
---|
3475 | n/a | ("day", 4), |
---|
3476 | n/a | ("hour", 5), |
---|
3477 | n/a | ("minute", 6), |
---|
3478 | n/a | ("second", 7), |
---|
3479 | n/a | ("microsecond", 8), |
---|
3480 | n/a | ("tzinfo", zm200)): |
---|
3481 | n/a | newargs = args[:] |
---|
3482 | n/a | newargs[i] = newval |
---|
3483 | n/a | expected = cls(*newargs) |
---|
3484 | n/a | got = base.replace(**{name: newval}) |
---|
3485 | n/a | self.assertEqual(expected, got) |
---|
3486 | n/a | i += 1 |
---|
3487 | n/a | |
---|
3488 | n/a | # Ensure we can get rid of a tzinfo. |
---|
3489 | n/a | self.assertEqual(base.tzname(), "+100") |
---|
3490 | n/a | base2 = base.replace(tzinfo=None) |
---|
3491 | n/a | self.assertIsNone(base2.tzinfo) |
---|
3492 | n/a | self.assertIsNone(base2.tzname()) |
---|
3493 | n/a | |
---|
3494 | n/a | # Ensure we can add one. |
---|
3495 | n/a | base3 = base2.replace(tzinfo=z100) |
---|
3496 | n/a | self.assertEqual(base, base3) |
---|
3497 | n/a | self.assertIs(base.tzinfo, base3.tzinfo) |
---|
3498 | n/a | |
---|
3499 | n/a | # Out of bounds. |
---|
3500 | n/a | base = cls(2000, 2, 29) |
---|
3501 | n/a | self.assertRaises(ValueError, base.replace, year=2001) |
---|
3502 | n/a | |
---|
3503 | n/a | def test_more_astimezone(self): |
---|
3504 | n/a | # The inherited test_astimezone covered some trivial and error cases. |
---|
3505 | n/a | fnone = FixedOffset(None, "None") |
---|
3506 | n/a | f44m = FixedOffset(44, "44") |
---|
3507 | n/a | fm5h = FixedOffset(-timedelta(hours=5), "m300") |
---|
3508 | n/a | |
---|
3509 | n/a | dt = self.theclass.now(tz=f44m) |
---|
3510 | n/a | self.assertIs(dt.tzinfo, f44m) |
---|
3511 | n/a | # Replacing with degenerate tzinfo raises an exception. |
---|
3512 | n/a | self.assertRaises(ValueError, dt.astimezone, fnone) |
---|
3513 | n/a | # Replacing with same tzinfo makes no change. |
---|
3514 | n/a | x = dt.astimezone(dt.tzinfo) |
---|
3515 | n/a | self.assertIs(x.tzinfo, f44m) |
---|
3516 | n/a | self.assertEqual(x.date(), dt.date()) |
---|
3517 | n/a | self.assertEqual(x.time(), dt.time()) |
---|
3518 | n/a | |
---|
3519 | n/a | # Replacing with different tzinfo does adjust. |
---|
3520 | n/a | got = dt.astimezone(fm5h) |
---|
3521 | n/a | self.assertIs(got.tzinfo, fm5h) |
---|
3522 | n/a | self.assertEqual(got.utcoffset(), timedelta(hours=-5)) |
---|
3523 | n/a | expected = dt - dt.utcoffset() # in effect, convert to UTC |
---|
3524 | n/a | expected += fm5h.utcoffset(dt) # and from there to local time |
---|
3525 | n/a | expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo |
---|
3526 | n/a | self.assertEqual(got.date(), expected.date()) |
---|
3527 | n/a | self.assertEqual(got.time(), expected.time()) |
---|
3528 | n/a | self.assertEqual(got.timetz(), expected.timetz()) |
---|
3529 | n/a | self.assertIs(got.tzinfo, expected.tzinfo) |
---|
3530 | n/a | self.assertEqual(got, expected) |
---|
3531 | n/a | |
---|
3532 | n/a | @support.run_with_tz('UTC') |
---|
3533 | n/a | def test_astimezone_default_utc(self): |
---|
3534 | n/a | dt = self.theclass.now(timezone.utc) |
---|
3535 | n/a | self.assertEqual(dt.astimezone(None), dt) |
---|
3536 | n/a | self.assertEqual(dt.astimezone(), dt) |
---|
3537 | n/a | |
---|
3538 | n/a | # Note that offset in TZ variable has the opposite sign to that |
---|
3539 | n/a | # produced by %z directive. |
---|
3540 | n/a | @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') |
---|
3541 | n/a | def test_astimezone_default_eastern(self): |
---|
3542 | n/a | dt = self.theclass(2012, 11, 4, 6, 30, tzinfo=timezone.utc) |
---|
3543 | n/a | local = dt.astimezone() |
---|
3544 | n/a | self.assertEqual(dt, local) |
---|
3545 | n/a | self.assertEqual(local.strftime("%z %Z"), "-0500 EST") |
---|
3546 | n/a | dt = self.theclass(2012, 11, 4, 5, 30, tzinfo=timezone.utc) |
---|
3547 | n/a | local = dt.astimezone() |
---|
3548 | n/a | self.assertEqual(dt, local) |
---|
3549 | n/a | self.assertEqual(local.strftime("%z %Z"), "-0400 EDT") |
---|
3550 | n/a | |
---|
3551 | n/a | @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') |
---|
3552 | n/a | def test_astimezone_default_near_fold(self): |
---|
3553 | n/a | # Issue #26616. |
---|
3554 | n/a | u = datetime(2015, 11, 1, 5, tzinfo=timezone.utc) |
---|
3555 | n/a | t = u.astimezone() |
---|
3556 | n/a | s = t.astimezone() |
---|
3557 | n/a | self.assertEqual(t.tzinfo, s.tzinfo) |
---|
3558 | n/a | |
---|
3559 | n/a | def test_aware_subtract(self): |
---|
3560 | n/a | cls = self.theclass |
---|
3561 | n/a | |
---|
3562 | n/a | # Ensure that utcoffset() is ignored when the operands have the |
---|
3563 | n/a | # same tzinfo member. |
---|
3564 | n/a | class OperandDependentOffset(tzinfo): |
---|
3565 | n/a | def utcoffset(self, t): |
---|
3566 | n/a | if t.minute < 10: |
---|
3567 | n/a | # d0 and d1 equal after adjustment |
---|
3568 | n/a | return timedelta(minutes=t.minute) |
---|
3569 | n/a | else: |
---|
3570 | n/a | # d2 off in the weeds |
---|
3571 | n/a | return timedelta(minutes=59) |
---|
3572 | n/a | |
---|
3573 | n/a | base = cls(8, 9, 10, 11, 12, 13, 14, tzinfo=OperandDependentOffset()) |
---|
3574 | n/a | d0 = base.replace(minute=3) |
---|
3575 | n/a | d1 = base.replace(minute=9) |
---|
3576 | n/a | d2 = base.replace(minute=11) |
---|
3577 | n/a | for x in d0, d1, d2: |
---|
3578 | n/a | for y in d0, d1, d2: |
---|
3579 | n/a | got = x - y |
---|
3580 | n/a | expected = timedelta(minutes=x.minute - y.minute) |
---|
3581 | n/a | self.assertEqual(got, expected) |
---|
3582 | n/a | |
---|
3583 | n/a | # OTOH, if the tzinfo members are distinct, utcoffsets aren't |
---|
3584 | n/a | # ignored. |
---|
3585 | n/a | base = cls(8, 9, 10, 11, 12, 13, 14) |
---|
3586 | n/a | d0 = base.replace(minute=3, tzinfo=OperandDependentOffset()) |
---|
3587 | n/a | d1 = base.replace(minute=9, tzinfo=OperandDependentOffset()) |
---|
3588 | n/a | d2 = base.replace(minute=11, tzinfo=OperandDependentOffset()) |
---|
3589 | n/a | for x in d0, d1, d2: |
---|
3590 | n/a | for y in d0, d1, d2: |
---|
3591 | n/a | got = x - y |
---|
3592 | n/a | if (x is d0 or x is d1) and (y is d0 or y is d1): |
---|
3593 | n/a | expected = timedelta(0) |
---|
3594 | n/a | elif x is y is d2: |
---|
3595 | n/a | expected = timedelta(0) |
---|
3596 | n/a | elif x is d2: |
---|
3597 | n/a | expected = timedelta(minutes=(11-59)-0) |
---|
3598 | n/a | else: |
---|
3599 | n/a | assert y is d2 |
---|
3600 | n/a | expected = timedelta(minutes=0-(11-59)) |
---|
3601 | n/a | self.assertEqual(got, expected) |
---|
3602 | n/a | |
---|
3603 | n/a | def test_mixed_compare(self): |
---|
3604 | n/a | t1 = datetime(1, 2, 3, 4, 5, 6, 7) |
---|
3605 | n/a | t2 = datetime(1, 2, 3, 4, 5, 6, 7) |
---|
3606 | n/a | self.assertEqual(t1, t2) |
---|
3607 | n/a | t2 = t2.replace(tzinfo=None) |
---|
3608 | n/a | self.assertEqual(t1, t2) |
---|
3609 | n/a | t2 = t2.replace(tzinfo=FixedOffset(None, "")) |
---|
3610 | n/a | self.assertEqual(t1, t2) |
---|
3611 | n/a | t2 = t2.replace(tzinfo=FixedOffset(0, "")) |
---|
3612 | n/a | self.assertNotEqual(t1, t2) |
---|
3613 | n/a | |
---|
3614 | n/a | # In datetime w/ identical tzinfo objects, utcoffset is ignored. |
---|
3615 | n/a | class Varies(tzinfo): |
---|
3616 | n/a | def __init__(self): |
---|
3617 | n/a | self.offset = timedelta(minutes=22) |
---|
3618 | n/a | def utcoffset(self, t): |
---|
3619 | n/a | self.offset += timedelta(minutes=1) |
---|
3620 | n/a | return self.offset |
---|
3621 | n/a | |
---|
3622 | n/a | v = Varies() |
---|
3623 | n/a | t1 = t2.replace(tzinfo=v) |
---|
3624 | n/a | t2 = t2.replace(tzinfo=v) |
---|
3625 | n/a | self.assertEqual(t1.utcoffset(), timedelta(minutes=23)) |
---|
3626 | n/a | self.assertEqual(t2.utcoffset(), timedelta(minutes=24)) |
---|
3627 | n/a | self.assertEqual(t1, t2) |
---|
3628 | n/a | |
---|
3629 | n/a | # But if they're not identical, it isn't ignored. |
---|
3630 | n/a | t2 = t2.replace(tzinfo=Varies()) |
---|
3631 | n/a | self.assertTrue(t1 < t2) # t1's offset counter still going up |
---|
3632 | n/a | |
---|
3633 | n/a | def test_subclass_datetimetz(self): |
---|
3634 | n/a | |
---|
3635 | n/a | class C(self.theclass): |
---|
3636 | n/a | theAnswer = 42 |
---|
3637 | n/a | |
---|
3638 | n/a | def __new__(cls, *args, **kws): |
---|
3639 | n/a | temp = kws.copy() |
---|
3640 | n/a | extra = temp.pop('extra') |
---|
3641 | n/a | result = self.theclass.__new__(cls, *args, **temp) |
---|
3642 | n/a | result.extra = extra |
---|
3643 | n/a | return result |
---|
3644 | n/a | |
---|
3645 | n/a | def newmeth(self, start): |
---|
3646 | n/a | return start + self.hour + self.year |
---|
3647 | n/a | |
---|
3648 | n/a | args = 2002, 12, 31, 4, 5, 6, 500, FixedOffset(-300, "EST", 1) |
---|
3649 | n/a | |
---|
3650 | n/a | dt1 = self.theclass(*args) |
---|
3651 | n/a | dt2 = C(*args, **{'extra': 7}) |
---|
3652 | n/a | |
---|
3653 | n/a | self.assertEqual(dt2.__class__, C) |
---|
3654 | n/a | self.assertEqual(dt2.theAnswer, 42) |
---|
3655 | n/a | self.assertEqual(dt2.extra, 7) |
---|
3656 | n/a | self.assertEqual(dt1.utcoffset(), dt2.utcoffset()) |
---|
3657 | n/a | self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.year - 7) |
---|
3658 | n/a | |
---|
3659 | n/a | # Pain to set up DST-aware tzinfo classes. |
---|
3660 | n/a | |
---|
3661 | n/a | def first_sunday_on_or_after(dt): |
---|
3662 | n/a | days_to_go = 6 - dt.weekday() |
---|
3663 | n/a | if days_to_go: |
---|
3664 | n/a | dt += timedelta(days_to_go) |
---|
3665 | n/a | return dt |
---|
3666 | n/a | |
---|
3667 | n/a | ZERO = timedelta(0) |
---|
3668 | n/a | MINUTE = timedelta(minutes=1) |
---|
3669 | n/a | HOUR = timedelta(hours=1) |
---|
3670 | n/a | DAY = timedelta(days=1) |
---|
3671 | n/a | # In the US, DST starts at 2am (standard time) on the first Sunday in April. |
---|
3672 | n/a | DSTSTART = datetime(1, 4, 1, 2) |
---|
3673 | n/a | # and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct, |
---|
3674 | n/a | # which is the first Sunday on or after Oct 25. Because we view 1:MM as |
---|
3675 | n/a | # being standard time on that day, there is no spelling in local time of |
---|
3676 | n/a | # the last hour of DST (that's 1:MM DST, but 1:MM is taken as standard time). |
---|
3677 | n/a | DSTEND = datetime(1, 10, 25, 1) |
---|
3678 | n/a | |
---|
3679 | n/a | class USTimeZone(tzinfo): |
---|
3680 | n/a | |
---|
3681 | n/a | def __init__(self, hours, reprname, stdname, dstname): |
---|
3682 | n/a | self.stdoffset = timedelta(hours=hours) |
---|
3683 | n/a | self.reprname = reprname |
---|
3684 | n/a | self.stdname = stdname |
---|
3685 | n/a | self.dstname = dstname |
---|
3686 | n/a | |
---|
3687 | n/a | def __repr__(self): |
---|
3688 | n/a | return self.reprname |
---|
3689 | n/a | |
---|
3690 | n/a | def tzname(self, dt): |
---|
3691 | n/a | if self.dst(dt): |
---|
3692 | n/a | return self.dstname |
---|
3693 | n/a | else: |
---|
3694 | n/a | return self.stdname |
---|
3695 | n/a | |
---|
3696 | n/a | def utcoffset(self, dt): |
---|
3697 | n/a | return self.stdoffset + self.dst(dt) |
---|
3698 | n/a | |
---|
3699 | n/a | def dst(self, dt): |
---|
3700 | n/a | if dt is None or dt.tzinfo is None: |
---|
3701 | n/a | # An exception instead may be sensible here, in one or more of |
---|
3702 | n/a | # the cases. |
---|
3703 | n/a | return ZERO |
---|
3704 | n/a | assert dt.tzinfo is self |
---|
3705 | n/a | |
---|
3706 | n/a | # Find first Sunday in April. |
---|
3707 | n/a | start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year)) |
---|
3708 | n/a | assert start.weekday() == 6 and start.month == 4 and start.day <= 7 |
---|
3709 | n/a | |
---|
3710 | n/a | # Find last Sunday in October. |
---|
3711 | n/a | end = first_sunday_on_or_after(DSTEND.replace(year=dt.year)) |
---|
3712 | n/a | assert end.weekday() == 6 and end.month == 10 and end.day >= 25 |
---|
3713 | n/a | |
---|
3714 | n/a | # Can't compare naive to aware objects, so strip the timezone from |
---|
3715 | n/a | # dt first. |
---|
3716 | n/a | if start <= dt.replace(tzinfo=None) < end: |
---|
3717 | n/a | return HOUR |
---|
3718 | n/a | else: |
---|
3719 | n/a | return ZERO |
---|
3720 | n/a | |
---|
3721 | n/a | Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") |
---|
3722 | n/a | Central = USTimeZone(-6, "Central", "CST", "CDT") |
---|
3723 | n/a | Mountain = USTimeZone(-7, "Mountain", "MST", "MDT") |
---|
3724 | n/a | Pacific = USTimeZone(-8, "Pacific", "PST", "PDT") |
---|
3725 | n/a | utc_real = FixedOffset(0, "UTC", 0) |
---|
3726 | n/a | # For better test coverage, we want another flavor of UTC that's west of |
---|
3727 | n/a | # the Eastern and Pacific timezones. |
---|
3728 | n/a | utc_fake = FixedOffset(-12*60, "UTCfake", 0) |
---|
3729 | n/a | |
---|
3730 | n/a | class TestTimezoneConversions(unittest.TestCase): |
---|
3731 | n/a | # The DST switch times for 2002, in std time. |
---|
3732 | n/a | dston = datetime(2002, 4, 7, 2) |
---|
3733 | n/a | dstoff = datetime(2002, 10, 27, 1) |
---|
3734 | n/a | |
---|
3735 | n/a | theclass = datetime |
---|
3736 | n/a | |
---|
3737 | n/a | # Check a time that's inside DST. |
---|
3738 | n/a | def checkinside(self, dt, tz, utc, dston, dstoff): |
---|
3739 | n/a | self.assertEqual(dt.dst(), HOUR) |
---|
3740 | n/a | |
---|
3741 | n/a | # Conversion to our own timezone is always an identity. |
---|
3742 | n/a | self.assertEqual(dt.astimezone(tz), dt) |
---|
3743 | n/a | |
---|
3744 | n/a | asutc = dt.astimezone(utc) |
---|
3745 | n/a | there_and_back = asutc.astimezone(tz) |
---|
3746 | n/a | |
---|
3747 | n/a | # Conversion to UTC and back isn't always an identity here, |
---|
3748 | n/a | # because there are redundant spellings (in local time) of |
---|
3749 | n/a | # UTC time when DST begins: the clock jumps from 1:59:59 |
---|
3750 | n/a | # to 3:00:00, and a local time of 2:MM:SS doesn't really |
---|
3751 | n/a | # make sense then. The classes above treat 2:MM:SS as |
---|
3752 | n/a | # daylight time then (it's "after 2am"), really an alias |
---|
3753 | n/a | # for 1:MM:SS standard time. The latter form is what |
---|
3754 | n/a | # conversion back from UTC produces. |
---|
3755 | n/a | if dt.date() == dston.date() and dt.hour == 2: |
---|
3756 | n/a | # We're in the redundant hour, and coming back from |
---|
3757 | n/a | # UTC gives the 1:MM:SS standard-time spelling. |
---|
3758 | n/a | self.assertEqual(there_and_back + HOUR, dt) |
---|
3759 | n/a | # Although during was considered to be in daylight |
---|
3760 | n/a | # time, there_and_back is not. |
---|
3761 | n/a | self.assertEqual(there_and_back.dst(), ZERO) |
---|
3762 | n/a | # They're the same times in UTC. |
---|
3763 | n/a | self.assertEqual(there_and_back.astimezone(utc), |
---|
3764 | n/a | dt.astimezone(utc)) |
---|
3765 | n/a | else: |
---|
3766 | n/a | # We're not in the redundant hour. |
---|
3767 | n/a | self.assertEqual(dt, there_and_back) |
---|
3768 | n/a | |
---|
3769 | n/a | # Because we have a redundant spelling when DST begins, there is |
---|
3770 | n/a | # (unfortunately) an hour when DST ends that can't be spelled at all in |
---|
3771 | n/a | # local time. When DST ends, the clock jumps from 1:59 back to 1:00 |
---|
3772 | n/a | # again. The hour 1:MM DST has no spelling then: 1:MM is taken to be |
---|
3773 | n/a | # standard time. 1:MM DST == 0:MM EST, but 0:MM is taken to be |
---|
3774 | n/a | # daylight time. The hour 1:MM daylight == 0:MM standard can't be |
---|
3775 | n/a | # expressed in local time. Nevertheless, we want conversion back |
---|
3776 | n/a | # from UTC to mimic the local clock's "repeat an hour" behavior. |
---|
3777 | n/a | nexthour_utc = asutc + HOUR |
---|
3778 | n/a | nexthour_tz = nexthour_utc.astimezone(tz) |
---|
3779 | n/a | if dt.date() == dstoff.date() and dt.hour == 0: |
---|
3780 | n/a | # We're in the hour before the last DST hour. The last DST hour |
---|
3781 | n/a | # is ineffable. We want the conversion back to repeat 1:MM. |
---|
3782 | n/a | self.assertEqual(nexthour_tz, dt.replace(hour=1)) |
---|
3783 | n/a | nexthour_utc += HOUR |
---|
3784 | n/a | nexthour_tz = nexthour_utc.astimezone(tz) |
---|
3785 | n/a | self.assertEqual(nexthour_tz, dt.replace(hour=1)) |
---|
3786 | n/a | else: |
---|
3787 | n/a | self.assertEqual(nexthour_tz - dt, HOUR) |
---|
3788 | n/a | |
---|
3789 | n/a | # Check a time that's outside DST. |
---|
3790 | n/a | def checkoutside(self, dt, tz, utc): |
---|
3791 | n/a | self.assertEqual(dt.dst(), ZERO) |
---|
3792 | n/a | |
---|
3793 | n/a | # Conversion to our own timezone is always an identity. |
---|
3794 | n/a | self.assertEqual(dt.astimezone(tz), dt) |
---|
3795 | n/a | |
---|
3796 | n/a | # Converting to UTC and back is an identity too. |
---|
3797 | n/a | asutc = dt.astimezone(utc) |
---|
3798 | n/a | there_and_back = asutc.astimezone(tz) |
---|
3799 | n/a | self.assertEqual(dt, there_and_back) |
---|
3800 | n/a | |
---|
3801 | n/a | def convert_between_tz_and_utc(self, tz, utc): |
---|
3802 | n/a | dston = self.dston.replace(tzinfo=tz) |
---|
3803 | n/a | # Because 1:MM on the day DST ends is taken as being standard time, |
---|
3804 | n/a | # there is no spelling in tz for the last hour of daylight time. |
---|
3805 | n/a | # For purposes of the test, the last hour of DST is 0:MM, which is |
---|
3806 | n/a | # taken as being daylight time (and 1:MM is taken as being standard |
---|
3807 | n/a | # time). |
---|
3808 | n/a | dstoff = self.dstoff.replace(tzinfo=tz) |
---|
3809 | n/a | for delta in (timedelta(weeks=13), |
---|
3810 | n/a | DAY, |
---|
3811 | n/a | HOUR, |
---|
3812 | n/a | timedelta(minutes=1), |
---|
3813 | n/a | timedelta(microseconds=1)): |
---|
3814 | n/a | |
---|
3815 | n/a | self.checkinside(dston, tz, utc, dston, dstoff) |
---|
3816 | n/a | for during in dston + delta, dstoff - delta: |
---|
3817 | n/a | self.checkinside(during, tz, utc, dston, dstoff) |
---|
3818 | n/a | |
---|
3819 | n/a | self.checkoutside(dstoff, tz, utc) |
---|
3820 | n/a | for outside in dston - delta, dstoff + delta: |
---|
3821 | n/a | self.checkoutside(outside, tz, utc) |
---|
3822 | n/a | |
---|
3823 | n/a | def test_easy(self): |
---|
3824 | n/a | # Despite the name of this test, the endcases are excruciating. |
---|
3825 | n/a | self.convert_between_tz_and_utc(Eastern, utc_real) |
---|
3826 | n/a | self.convert_between_tz_and_utc(Pacific, utc_real) |
---|
3827 | n/a | self.convert_between_tz_and_utc(Eastern, utc_fake) |
---|
3828 | n/a | self.convert_between_tz_and_utc(Pacific, utc_fake) |
---|
3829 | n/a | # The next is really dancing near the edge. It works because |
---|
3830 | n/a | # Pacific and Eastern are far enough apart that their "problem |
---|
3831 | n/a | # hours" don't overlap. |
---|
3832 | n/a | self.convert_between_tz_and_utc(Eastern, Pacific) |
---|
3833 | n/a | self.convert_between_tz_and_utc(Pacific, Eastern) |
---|
3834 | n/a | # OTOH, these fail! Don't enable them. The difficulty is that |
---|
3835 | n/a | # the edge case tests assume that every hour is representable in |
---|
3836 | n/a | # the "utc" class. This is always true for a fixed-offset tzinfo |
---|
3837 | n/a | # class (lke utc_real and utc_fake), but not for Eastern or Central. |
---|
3838 | n/a | # For these adjacent DST-aware time zones, the range of time offsets |
---|
3839 | n/a | # tested ends up creating hours in the one that aren't representable |
---|
3840 | n/a | # in the other. For the same reason, we would see failures in the |
---|
3841 | n/a | # Eastern vs Pacific tests too if we added 3*HOUR to the list of |
---|
3842 | n/a | # offset deltas in convert_between_tz_and_utc(). |
---|
3843 | n/a | # |
---|
3844 | n/a | # self.convert_between_tz_and_utc(Eastern, Central) # can't work |
---|
3845 | n/a | # self.convert_between_tz_and_utc(Central, Eastern) # can't work |
---|
3846 | n/a | |
---|
3847 | n/a | def test_tricky(self): |
---|
3848 | n/a | # 22:00 on day before daylight starts. |
---|
3849 | n/a | fourback = self.dston - timedelta(hours=4) |
---|
3850 | n/a | ninewest = FixedOffset(-9*60, "-0900", 0) |
---|
3851 | n/a | fourback = fourback.replace(tzinfo=ninewest) |
---|
3852 | n/a | # 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST. Since it's "after |
---|
3853 | n/a | # 2", we should get the 3 spelling. |
---|
3854 | n/a | # If we plug 22:00 the day before into Eastern, it "looks like std |
---|
3855 | n/a | # time", so its offset is returned as -5, and -5 - -9 = 4. Adding 4 |
---|
3856 | n/a | # to 22:00 lands on 2:00, which makes no sense in local time (the |
---|
3857 | n/a | # local clock jumps from 1 to 3). The point here is to make sure we |
---|
3858 | n/a | # get the 3 spelling. |
---|
3859 | n/a | expected = self.dston.replace(hour=3) |
---|
3860 | n/a | got = fourback.astimezone(Eastern).replace(tzinfo=None) |
---|
3861 | n/a | self.assertEqual(expected, got) |
---|
3862 | n/a | |
---|
3863 | n/a | # Similar, but map to 6:00 UTC == 1:00 EST == 2:00 DST. In that |
---|
3864 | n/a | # case we want the 1:00 spelling. |
---|
3865 | n/a | sixutc = self.dston.replace(hour=6, tzinfo=utc_real) |
---|
3866 | n/a | # Now 6:00 "looks like daylight", so the offset wrt Eastern is -4, |
---|
3867 | n/a | # and adding -4-0 == -4 gives the 2:00 spelling. We want the 1:00 EST |
---|
3868 | n/a | # spelling. |
---|
3869 | n/a | expected = self.dston.replace(hour=1) |
---|
3870 | n/a | got = sixutc.astimezone(Eastern).replace(tzinfo=None) |
---|
3871 | n/a | self.assertEqual(expected, got) |
---|
3872 | n/a | |
---|
3873 | n/a | # Now on the day DST ends, we want "repeat an hour" behavior. |
---|
3874 | n/a | # UTC 4:MM 5:MM 6:MM 7:MM checking these |
---|
3875 | n/a | # EST 23:MM 0:MM 1:MM 2:MM |
---|
3876 | n/a | # EDT 0:MM 1:MM 2:MM 3:MM |
---|
3877 | n/a | # wall 0:MM 1:MM 1:MM 2:MM against these |
---|
3878 | n/a | for utc in utc_real, utc_fake: |
---|
3879 | n/a | for tz in Eastern, Pacific: |
---|
3880 | n/a | first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM |
---|
3881 | n/a | # Convert that to UTC. |
---|
3882 | n/a | first_std_hour -= tz.utcoffset(None) |
---|
3883 | n/a | # Adjust for possibly fake UTC. |
---|
3884 | n/a | asutc = first_std_hour + utc.utcoffset(None) |
---|
3885 | n/a | # First UTC hour to convert; this is 4:00 when utc=utc_real & |
---|
3886 | n/a | # tz=Eastern. |
---|
3887 | n/a | asutcbase = asutc.replace(tzinfo=utc) |
---|
3888 | n/a | for tzhour in (0, 1, 1, 2): |
---|
3889 | n/a | expectedbase = self.dstoff.replace(hour=tzhour) |
---|
3890 | n/a | for minute in 0, 30, 59: |
---|
3891 | n/a | expected = expectedbase.replace(minute=minute) |
---|
3892 | n/a | asutc = asutcbase.replace(minute=minute) |
---|
3893 | n/a | astz = asutc.astimezone(tz) |
---|
3894 | n/a | self.assertEqual(astz.replace(tzinfo=None), expected) |
---|
3895 | n/a | asutcbase += HOUR |
---|
3896 | n/a | |
---|
3897 | n/a | |
---|
3898 | n/a | def test_bogus_dst(self): |
---|
3899 | n/a | class ok(tzinfo): |
---|
3900 | n/a | def utcoffset(self, dt): return HOUR |
---|
3901 | n/a | def dst(self, dt): return HOUR |
---|
3902 | n/a | |
---|
3903 | n/a | now = self.theclass.now().replace(tzinfo=utc_real) |
---|
3904 | n/a | # Doesn't blow up. |
---|
3905 | n/a | now.astimezone(ok()) |
---|
3906 | n/a | |
---|
3907 | n/a | # Does blow up. |
---|
3908 | n/a | class notok(ok): |
---|
3909 | n/a | def dst(self, dt): return None |
---|
3910 | n/a | self.assertRaises(ValueError, now.astimezone, notok()) |
---|
3911 | n/a | |
---|
3912 | n/a | # Sometimes blow up. In the following, tzinfo.dst() |
---|
3913 | n/a | # implementation may return None or not None depending on |
---|
3914 | n/a | # whether DST is assumed to be in effect. In this situation, |
---|
3915 | n/a | # a ValueError should be raised by astimezone(). |
---|
3916 | n/a | class tricky_notok(ok): |
---|
3917 | n/a | def dst(self, dt): |
---|
3918 | n/a | if dt.year == 2000: |
---|
3919 | n/a | return None |
---|
3920 | n/a | else: |
---|
3921 | n/a | return 10*HOUR |
---|
3922 | n/a | dt = self.theclass(2001, 1, 1).replace(tzinfo=utc_real) |
---|
3923 | n/a | self.assertRaises(ValueError, dt.astimezone, tricky_notok()) |
---|
3924 | n/a | |
---|
3925 | n/a | def test_fromutc(self): |
---|
3926 | n/a | self.assertRaises(TypeError, Eastern.fromutc) # not enough args |
---|
3927 | n/a | now = datetime.utcnow().replace(tzinfo=utc_real) |
---|
3928 | n/a | self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo |
---|
3929 | n/a | now = now.replace(tzinfo=Eastern) # insert correct tzinfo |
---|
3930 | n/a | enow = Eastern.fromutc(now) # doesn't blow up |
---|
3931 | n/a | self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member |
---|
3932 | n/a | self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args |
---|
3933 | n/a | self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type |
---|
3934 | n/a | |
---|
3935 | n/a | # Always converts UTC to standard time. |
---|
3936 | n/a | class FauxUSTimeZone(USTimeZone): |
---|
3937 | n/a | def fromutc(self, dt): |
---|
3938 | n/a | return dt + self.stdoffset |
---|
3939 | n/a | FEastern = FauxUSTimeZone(-5, "FEastern", "FEST", "FEDT") |
---|
3940 | n/a | |
---|
3941 | n/a | # UTC 4:MM 5:MM 6:MM 7:MM 8:MM 9:MM |
---|
3942 | n/a | # EST 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM |
---|
3943 | n/a | # EDT 0:MM 1:MM 2:MM 3:MM 4:MM 5:MM |
---|
3944 | n/a | |
---|
3945 | n/a | # Check around DST start. |
---|
3946 | n/a | start = self.dston.replace(hour=4, tzinfo=Eastern) |
---|
3947 | n/a | fstart = start.replace(tzinfo=FEastern) |
---|
3948 | n/a | for wall in 23, 0, 1, 3, 4, 5: |
---|
3949 | n/a | expected = start.replace(hour=wall) |
---|
3950 | n/a | if wall == 23: |
---|
3951 | n/a | expected -= timedelta(days=1) |
---|
3952 | n/a | got = Eastern.fromutc(start) |
---|
3953 | n/a | self.assertEqual(expected, got) |
---|
3954 | n/a | |
---|
3955 | n/a | expected = fstart + FEastern.stdoffset |
---|
3956 | n/a | got = FEastern.fromutc(fstart) |
---|
3957 | n/a | self.assertEqual(expected, got) |
---|
3958 | n/a | |
---|
3959 | n/a | # Ensure astimezone() calls fromutc() too. |
---|
3960 | n/a | got = fstart.replace(tzinfo=utc_real).astimezone(FEastern) |
---|
3961 | n/a | self.assertEqual(expected, got) |
---|
3962 | n/a | |
---|
3963 | n/a | start += HOUR |
---|
3964 | n/a | fstart += HOUR |
---|
3965 | n/a | |
---|
3966 | n/a | # Check around DST end. |
---|
3967 | n/a | start = self.dstoff.replace(hour=4, tzinfo=Eastern) |
---|
3968 | n/a | fstart = start.replace(tzinfo=FEastern) |
---|
3969 | n/a | for wall in 0, 1, 1, 2, 3, 4: |
---|
3970 | n/a | expected = start.replace(hour=wall) |
---|
3971 | n/a | got = Eastern.fromutc(start) |
---|
3972 | n/a | self.assertEqual(expected, got) |
---|
3973 | n/a | |
---|
3974 | n/a | expected = fstart + FEastern.stdoffset |
---|
3975 | n/a | got = FEastern.fromutc(fstart) |
---|
3976 | n/a | self.assertEqual(expected, got) |
---|
3977 | n/a | |
---|
3978 | n/a | # Ensure astimezone() calls fromutc() too. |
---|
3979 | n/a | got = fstart.replace(tzinfo=utc_real).astimezone(FEastern) |
---|
3980 | n/a | self.assertEqual(expected, got) |
---|
3981 | n/a | |
---|
3982 | n/a | start += HOUR |
---|
3983 | n/a | fstart += HOUR |
---|
3984 | n/a | |
---|
3985 | n/a | |
---|
3986 | n/a | ############################################################################# |
---|
3987 | n/a | # oddballs |
---|
3988 | n/a | |
---|
3989 | n/a | class Oddballs(unittest.TestCase): |
---|
3990 | n/a | |
---|
3991 | n/a | def test_bug_1028306(self): |
---|
3992 | n/a | # Trying to compare a date to a datetime should act like a mixed- |
---|
3993 | n/a | # type comparison, despite that datetime is a subclass of date. |
---|
3994 | n/a | as_date = date.today() |
---|
3995 | n/a | as_datetime = datetime.combine(as_date, time()) |
---|
3996 | n/a | self.assertTrue(as_date != as_datetime) |
---|
3997 | n/a | self.assertTrue(as_datetime != as_date) |
---|
3998 | n/a | self.assertFalse(as_date == as_datetime) |
---|
3999 | n/a | self.assertFalse(as_datetime == as_date) |
---|
4000 | n/a | self.assertRaises(TypeError, lambda: as_date < as_datetime) |
---|
4001 | n/a | self.assertRaises(TypeError, lambda: as_datetime < as_date) |
---|
4002 | n/a | self.assertRaises(TypeError, lambda: as_date <= as_datetime) |
---|
4003 | n/a | self.assertRaises(TypeError, lambda: as_datetime <= as_date) |
---|
4004 | n/a | self.assertRaises(TypeError, lambda: as_date > as_datetime) |
---|
4005 | n/a | self.assertRaises(TypeError, lambda: as_datetime > as_date) |
---|
4006 | n/a | self.assertRaises(TypeError, lambda: as_date >= as_datetime) |
---|
4007 | n/a | self.assertRaises(TypeError, lambda: as_datetime >= as_date) |
---|
4008 | n/a | |
---|
4009 | n/a | # Nevertheless, comparison should work with the base-class (date) |
---|
4010 | n/a | # projection if use of a date method is forced. |
---|
4011 | n/a | self.assertEqual(as_date.__eq__(as_datetime), True) |
---|
4012 | n/a | different_day = (as_date.day + 1) % 20 + 1 |
---|
4013 | n/a | as_different = as_datetime.replace(day= different_day) |
---|
4014 | n/a | self.assertEqual(as_date.__eq__(as_different), False) |
---|
4015 | n/a | |
---|
4016 | n/a | # And date should compare with other subclasses of date. If a |
---|
4017 | n/a | # subclass wants to stop this, it's up to the subclass to do so. |
---|
4018 | n/a | date_sc = SubclassDate(as_date.year, as_date.month, as_date.day) |
---|
4019 | n/a | self.assertEqual(as_date, date_sc) |
---|
4020 | n/a | self.assertEqual(date_sc, as_date) |
---|
4021 | n/a | |
---|
4022 | n/a | # Ditto for datetimes. |
---|
4023 | n/a | datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month, |
---|
4024 | n/a | as_date.day, 0, 0, 0) |
---|
4025 | n/a | self.assertEqual(as_datetime, datetime_sc) |
---|
4026 | n/a | self.assertEqual(datetime_sc, as_datetime) |
---|
4027 | n/a | |
---|
4028 | n/a | def test_extra_attributes(self): |
---|
4029 | n/a | for x in [date.today(), |
---|
4030 | n/a | time(), |
---|
4031 | n/a | datetime.utcnow(), |
---|
4032 | n/a | timedelta(), |
---|
4033 | n/a | tzinfo(), |
---|
4034 | n/a | timezone(timedelta())]: |
---|
4035 | n/a | with self.assertRaises(AttributeError): |
---|
4036 | n/a | x.abc = 1 |
---|
4037 | n/a | |
---|
4038 | n/a | def test_check_arg_types(self): |
---|
4039 | n/a | class Number: |
---|
4040 | n/a | def __init__(self, value): |
---|
4041 | n/a | self.value = value |
---|
4042 | n/a | def __int__(self): |
---|
4043 | n/a | return self.value |
---|
4044 | n/a | |
---|
4045 | n/a | for xx in [decimal.Decimal(10), |
---|
4046 | n/a | decimal.Decimal('10.9'), |
---|
4047 | n/a | Number(10)]: |
---|
4048 | n/a | self.assertEqual(datetime(10, 10, 10, 10, 10, 10, 10), |
---|
4049 | n/a | datetime(xx, xx, xx, xx, xx, xx, xx)) |
---|
4050 | n/a | |
---|
4051 | n/a | with self.assertRaisesRegex(TypeError, '^an integer is required ' |
---|
4052 | n/a | r'\(got type str\)$'): |
---|
4053 | n/a | datetime(10, 10, '10') |
---|
4054 | n/a | |
---|
4055 | n/a | f10 = Number(10.9) |
---|
4056 | n/a | with self.assertRaisesRegex(TypeError, '^__int__ returned non-int ' |
---|
4057 | n/a | r'\(type float\)$'): |
---|
4058 | n/a | datetime(10, 10, f10) |
---|
4059 | n/a | |
---|
4060 | n/a | class Float(float): |
---|
4061 | n/a | pass |
---|
4062 | n/a | s10 = Float(10.9) |
---|
4063 | n/a | with self.assertRaisesRegex(TypeError, '^integer argument expected, ' |
---|
4064 | n/a | 'got float$'): |
---|
4065 | n/a | datetime(10, 10, s10) |
---|
4066 | n/a | |
---|
4067 | n/a | with self.assertRaises(TypeError): |
---|
4068 | n/a | datetime(10., 10, 10) |
---|
4069 | n/a | with self.assertRaises(TypeError): |
---|
4070 | n/a | datetime(10, 10., 10) |
---|
4071 | n/a | with self.assertRaises(TypeError): |
---|
4072 | n/a | datetime(10, 10, 10.) |
---|
4073 | n/a | with self.assertRaises(TypeError): |
---|
4074 | n/a | datetime(10, 10, 10, 10.) |
---|
4075 | n/a | with self.assertRaises(TypeError): |
---|
4076 | n/a | datetime(10, 10, 10, 10, 10.) |
---|
4077 | n/a | with self.assertRaises(TypeError): |
---|
4078 | n/a | datetime(10, 10, 10, 10, 10, 10.) |
---|
4079 | n/a | with self.assertRaises(TypeError): |
---|
4080 | n/a | datetime(10, 10, 10, 10, 10, 10, 10.) |
---|
4081 | n/a | |
---|
4082 | n/a | ############################################################################# |
---|
4083 | n/a | # Local Time Disambiguation |
---|
4084 | n/a | |
---|
4085 | n/a | # An experimental reimplementation of fromutc that respects the "fold" flag. |
---|
4086 | n/a | |
---|
4087 | n/a | class tzinfo2(tzinfo): |
---|
4088 | n/a | |
---|
4089 | n/a | def fromutc(self, dt): |
---|
4090 | n/a | "datetime in UTC -> datetime in local time." |
---|
4091 | n/a | |
---|
4092 | n/a | if not isinstance(dt, datetime): |
---|
4093 | n/a | raise TypeError("fromutc() requires a datetime argument") |
---|
4094 | n/a | if dt.tzinfo is not self: |
---|
4095 | n/a | raise ValueError("dt.tzinfo is not self") |
---|
4096 | n/a | # Returned value satisfies |
---|
4097 | n/a | # dt + ldt.utcoffset() = ldt |
---|
4098 | n/a | off0 = dt.replace(fold=0).utcoffset() |
---|
4099 | n/a | off1 = dt.replace(fold=1).utcoffset() |
---|
4100 | n/a | if off0 is None or off1 is None or dt.dst() is None: |
---|
4101 | n/a | raise ValueError |
---|
4102 | n/a | if off0 == off1: |
---|
4103 | n/a | ldt = dt + off0 |
---|
4104 | n/a | off1 = ldt.utcoffset() |
---|
4105 | n/a | if off0 == off1: |
---|
4106 | n/a | return ldt |
---|
4107 | n/a | # Now, we discovered both possible offsets, so |
---|
4108 | n/a | # we can just try four possible solutions: |
---|
4109 | n/a | for off in [off0, off1]: |
---|
4110 | n/a | ldt = dt + off |
---|
4111 | n/a | if ldt.utcoffset() == off: |
---|
4112 | n/a | return ldt |
---|
4113 | n/a | ldt = ldt.replace(fold=1) |
---|
4114 | n/a | if ldt.utcoffset() == off: |
---|
4115 | n/a | return ldt |
---|
4116 | n/a | |
---|
4117 | n/a | raise ValueError("No suitable local time found") |
---|
4118 | n/a | |
---|
4119 | n/a | # Reimplementing simplified US timezones to respect the "fold" flag: |
---|
4120 | n/a | |
---|
4121 | n/a | class USTimeZone2(tzinfo2): |
---|
4122 | n/a | |
---|
4123 | n/a | def __init__(self, hours, reprname, stdname, dstname): |
---|
4124 | n/a | self.stdoffset = timedelta(hours=hours) |
---|
4125 | n/a | self.reprname = reprname |
---|
4126 | n/a | self.stdname = stdname |
---|
4127 | n/a | self.dstname = dstname |
---|
4128 | n/a | |
---|
4129 | n/a | def __repr__(self): |
---|
4130 | n/a | return self.reprname |
---|
4131 | n/a | |
---|
4132 | n/a | def tzname(self, dt): |
---|
4133 | n/a | if self.dst(dt): |
---|
4134 | n/a | return self.dstname |
---|
4135 | n/a | else: |
---|
4136 | n/a | return self.stdname |
---|
4137 | n/a | |
---|
4138 | n/a | def utcoffset(self, dt): |
---|
4139 | n/a | return self.stdoffset + self.dst(dt) |
---|
4140 | n/a | |
---|
4141 | n/a | def dst(self, dt): |
---|
4142 | n/a | if dt is None or dt.tzinfo is None: |
---|
4143 | n/a | # An exception instead may be sensible here, in one or more of |
---|
4144 | n/a | # the cases. |
---|
4145 | n/a | return ZERO |
---|
4146 | n/a | assert dt.tzinfo is self |
---|
4147 | n/a | |
---|
4148 | n/a | # Find first Sunday in April. |
---|
4149 | n/a | start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year)) |
---|
4150 | n/a | assert start.weekday() == 6 and start.month == 4 and start.day <= 7 |
---|
4151 | n/a | |
---|
4152 | n/a | # Find last Sunday in October. |
---|
4153 | n/a | end = first_sunday_on_or_after(DSTEND.replace(year=dt.year)) |
---|
4154 | n/a | assert end.weekday() == 6 and end.month == 10 and end.day >= 25 |
---|
4155 | n/a | |
---|
4156 | n/a | # Can't compare naive to aware objects, so strip the timezone from |
---|
4157 | n/a | # dt first. |
---|
4158 | n/a | dt = dt.replace(tzinfo=None) |
---|
4159 | n/a | if start + HOUR <= dt < end: |
---|
4160 | n/a | # DST is in effect. |
---|
4161 | n/a | return HOUR |
---|
4162 | n/a | elif end <= dt < end + HOUR: |
---|
4163 | n/a | # Fold (an ambiguous hour): use dt.fold to disambiguate. |
---|
4164 | n/a | return ZERO if dt.fold else HOUR |
---|
4165 | n/a | elif start <= dt < start + HOUR: |
---|
4166 | n/a | # Gap (a non-existent hour): reverse the fold rule. |
---|
4167 | n/a | return HOUR if dt.fold else ZERO |
---|
4168 | n/a | else: |
---|
4169 | n/a | # DST is off. |
---|
4170 | n/a | return ZERO |
---|
4171 | n/a | |
---|
4172 | n/a | Eastern2 = USTimeZone2(-5, "Eastern2", "EST", "EDT") |
---|
4173 | n/a | Central2 = USTimeZone2(-6, "Central2", "CST", "CDT") |
---|
4174 | n/a | Mountain2 = USTimeZone2(-7, "Mountain2", "MST", "MDT") |
---|
4175 | n/a | Pacific2 = USTimeZone2(-8, "Pacific2", "PST", "PDT") |
---|
4176 | n/a | |
---|
4177 | n/a | # Europe_Vilnius_1941 tzinfo implementation reproduces the following |
---|
4178 | n/a | # 1941 transition from Olson's tzdist: |
---|
4179 | n/a | # |
---|
4180 | n/a | # Zone NAME GMTOFF RULES FORMAT [UNTIL] |
---|
4181 | n/a | # ZoneEurope/Vilnius 1:00 - CET 1940 Aug 3 |
---|
4182 | n/a | # 3:00 - MSK 1941 Jun 24 |
---|
4183 | n/a | # 1:00 C-Eur CE%sT 1944 Aug |
---|
4184 | n/a | # |
---|
4185 | n/a | # $ zdump -v Europe/Vilnius | grep 1941 |
---|
4186 | n/a | # Europe/Vilnius Mon Jun 23 20:59:59 1941 UTC = Mon Jun 23 23:59:59 1941 MSK isdst=0 gmtoff=10800 |
---|
4187 | n/a | # Europe/Vilnius Mon Jun 23 21:00:00 1941 UTC = Mon Jun 23 23:00:00 1941 CEST isdst=1 gmtoff=7200 |
---|
4188 | n/a | |
---|
4189 | n/a | class Europe_Vilnius_1941(tzinfo): |
---|
4190 | n/a | def _utc_fold(self): |
---|
4191 | n/a | return [datetime(1941, 6, 23, 21, tzinfo=self), # Mon Jun 23 21:00:00 1941 UTC |
---|
4192 | n/a | datetime(1941, 6, 23, 22, tzinfo=self)] # Mon Jun 23 22:00:00 1941 UTC |
---|
4193 | n/a | |
---|
4194 | n/a | def _loc_fold(self): |
---|
4195 | n/a | return [datetime(1941, 6, 23, 23, tzinfo=self), # Mon Jun 23 23:00:00 1941 MSK / CEST |
---|
4196 | n/a | datetime(1941, 6, 24, 0, tzinfo=self)] # Mon Jun 24 00:00:00 1941 CEST |
---|
4197 | n/a | |
---|
4198 | n/a | def utcoffset(self, dt): |
---|
4199 | n/a | fold_start, fold_stop = self._loc_fold() |
---|
4200 | n/a | if dt < fold_start: |
---|
4201 | n/a | return 3 * HOUR |
---|
4202 | n/a | if dt < fold_stop: |
---|
4203 | n/a | return (2 if dt.fold else 3) * HOUR |
---|
4204 | n/a | # if dt >= fold_stop |
---|
4205 | n/a | return 2 * HOUR |
---|
4206 | n/a | |
---|
4207 | n/a | def dst(self, dt): |
---|
4208 | n/a | fold_start, fold_stop = self._loc_fold() |
---|
4209 | n/a | if dt < fold_start: |
---|
4210 | n/a | return 0 * HOUR |
---|
4211 | n/a | if dt < fold_stop: |
---|
4212 | n/a | return (1 if dt.fold else 0) * HOUR |
---|
4213 | n/a | # if dt >= fold_stop |
---|
4214 | n/a | return 1 * HOUR |
---|
4215 | n/a | |
---|
4216 | n/a | def tzname(self, dt): |
---|
4217 | n/a | fold_start, fold_stop = self._loc_fold() |
---|
4218 | n/a | if dt < fold_start: |
---|
4219 | n/a | return 'MSK' |
---|
4220 | n/a | if dt < fold_stop: |
---|
4221 | n/a | return ('MSK', 'CEST')[dt.fold] |
---|
4222 | n/a | # if dt >= fold_stop |
---|
4223 | n/a | return 'CEST' |
---|
4224 | n/a | |
---|
4225 | n/a | def fromutc(self, dt): |
---|
4226 | n/a | assert dt.fold == 0 |
---|
4227 | n/a | assert dt.tzinfo is self |
---|
4228 | n/a | if dt.year != 1941: |
---|
4229 | n/a | raise NotImplementedError |
---|
4230 | n/a | fold_start, fold_stop = self._utc_fold() |
---|
4231 | n/a | if dt < fold_start: |
---|
4232 | n/a | return dt + 3 * HOUR |
---|
4233 | n/a | if dt < fold_stop: |
---|
4234 | n/a | return (dt + 2 * HOUR).replace(fold=1) |
---|
4235 | n/a | # if dt >= fold_stop |
---|
4236 | n/a | return dt + 2 * HOUR |
---|
4237 | n/a | |
---|
4238 | n/a | |
---|
4239 | n/a | class TestLocalTimeDisambiguation(unittest.TestCase): |
---|
4240 | n/a | |
---|
4241 | n/a | def test_vilnius_1941_fromutc(self): |
---|
4242 | n/a | Vilnius = Europe_Vilnius_1941() |
---|
4243 | n/a | |
---|
4244 | n/a | gdt = datetime(1941, 6, 23, 20, 59, 59, tzinfo=timezone.utc) |
---|
4245 | n/a | ldt = gdt.astimezone(Vilnius) |
---|
4246 | n/a | self.assertEqual(ldt.strftime("%c %Z%z"), |
---|
4247 | n/a | 'Mon Jun 23 23:59:59 1941 MSK+0300') |
---|
4248 | n/a | self.assertEqual(ldt.fold, 0) |
---|
4249 | n/a | self.assertFalse(ldt.dst()) |
---|
4250 | n/a | |
---|
4251 | n/a | gdt = datetime(1941, 6, 23, 21, tzinfo=timezone.utc) |
---|
4252 | n/a | ldt = gdt.astimezone(Vilnius) |
---|
4253 | n/a | self.assertEqual(ldt.strftime("%c %Z%z"), |
---|
4254 | n/a | 'Mon Jun 23 23:00:00 1941 CEST+0200') |
---|
4255 | n/a | self.assertEqual(ldt.fold, 1) |
---|
4256 | n/a | self.assertTrue(ldt.dst()) |
---|
4257 | n/a | |
---|
4258 | n/a | gdt = datetime(1941, 6, 23, 22, tzinfo=timezone.utc) |
---|
4259 | n/a | ldt = gdt.astimezone(Vilnius) |
---|
4260 | n/a | self.assertEqual(ldt.strftime("%c %Z%z"), |
---|
4261 | n/a | 'Tue Jun 24 00:00:00 1941 CEST+0200') |
---|
4262 | n/a | self.assertEqual(ldt.fold, 0) |
---|
4263 | n/a | self.assertTrue(ldt.dst()) |
---|
4264 | n/a | |
---|
4265 | n/a | def test_vilnius_1941_toutc(self): |
---|
4266 | n/a | Vilnius = Europe_Vilnius_1941() |
---|
4267 | n/a | |
---|
4268 | n/a | ldt = datetime(1941, 6, 23, 22, 59, 59, tzinfo=Vilnius) |
---|
4269 | n/a | gdt = ldt.astimezone(timezone.utc) |
---|
4270 | n/a | self.assertEqual(gdt.strftime("%c %Z"), |
---|
4271 | n/a | 'Mon Jun 23 19:59:59 1941 UTC') |
---|
4272 | n/a | |
---|
4273 | n/a | ldt = datetime(1941, 6, 23, 23, 59, 59, tzinfo=Vilnius) |
---|
4274 | n/a | gdt = ldt.astimezone(timezone.utc) |
---|
4275 | n/a | self.assertEqual(gdt.strftime("%c %Z"), |
---|
4276 | n/a | 'Mon Jun 23 20:59:59 1941 UTC') |
---|
4277 | n/a | |
---|
4278 | n/a | ldt = datetime(1941, 6, 23, 23, 59, 59, tzinfo=Vilnius, fold=1) |
---|
4279 | n/a | gdt = ldt.astimezone(timezone.utc) |
---|
4280 | n/a | self.assertEqual(gdt.strftime("%c %Z"), |
---|
4281 | n/a | 'Mon Jun 23 21:59:59 1941 UTC') |
---|
4282 | n/a | |
---|
4283 | n/a | ldt = datetime(1941, 6, 24, 0, tzinfo=Vilnius) |
---|
4284 | n/a | gdt = ldt.astimezone(timezone.utc) |
---|
4285 | n/a | self.assertEqual(gdt.strftime("%c %Z"), |
---|
4286 | n/a | 'Mon Jun 23 22:00:00 1941 UTC') |
---|
4287 | n/a | |
---|
4288 | n/a | |
---|
4289 | n/a | def test_constructors(self): |
---|
4290 | n/a | t = time(0, fold=1) |
---|
4291 | n/a | dt = datetime(1, 1, 1, fold=1) |
---|
4292 | n/a | self.assertEqual(t.fold, 1) |
---|
4293 | n/a | self.assertEqual(dt.fold, 1) |
---|
4294 | n/a | with self.assertRaises(TypeError): |
---|
4295 | n/a | time(0, 0, 0, 0, None, 0) |
---|
4296 | n/a | |
---|
4297 | n/a | def test_member(self): |
---|
4298 | n/a | dt = datetime(1, 1, 1, fold=1) |
---|
4299 | n/a | t = dt.time() |
---|
4300 | n/a | self.assertEqual(t.fold, 1) |
---|
4301 | n/a | t = dt.timetz() |
---|
4302 | n/a | self.assertEqual(t.fold, 1) |
---|
4303 | n/a | |
---|
4304 | n/a | def test_replace(self): |
---|
4305 | n/a | t = time(0) |
---|
4306 | n/a | dt = datetime(1, 1, 1) |
---|
4307 | n/a | self.assertEqual(t.replace(fold=1).fold, 1) |
---|
4308 | n/a | self.assertEqual(dt.replace(fold=1).fold, 1) |
---|
4309 | n/a | self.assertEqual(t.replace(fold=0).fold, 0) |
---|
4310 | n/a | self.assertEqual(dt.replace(fold=0).fold, 0) |
---|
4311 | n/a | # Check that replacement of other fields does not change "fold". |
---|
4312 | n/a | t = t.replace(fold=1, tzinfo=Eastern) |
---|
4313 | n/a | dt = dt.replace(fold=1, tzinfo=Eastern) |
---|
4314 | n/a | self.assertEqual(t.replace(tzinfo=None).fold, 1) |
---|
4315 | n/a | self.assertEqual(dt.replace(tzinfo=None).fold, 1) |
---|
4316 | n/a | # Check that fold is a keyword-only argument |
---|
4317 | n/a | with self.assertRaises(TypeError): |
---|
4318 | n/a | t.replace(1, 1, 1, None, 1) |
---|
4319 | n/a | with self.assertRaises(TypeError): |
---|
4320 | n/a | dt.replace(1, 1, 1, 1, 1, 1, 1, None, 1) |
---|
4321 | n/a | |
---|
4322 | n/a | def test_comparison(self): |
---|
4323 | n/a | t = time(0) |
---|
4324 | n/a | dt = datetime(1, 1, 1) |
---|
4325 | n/a | self.assertEqual(t, t.replace(fold=1)) |
---|
4326 | n/a | self.assertEqual(dt, dt.replace(fold=1)) |
---|
4327 | n/a | |
---|
4328 | n/a | def test_hash(self): |
---|
4329 | n/a | t = time(0) |
---|
4330 | n/a | dt = datetime(1, 1, 1) |
---|
4331 | n/a | self.assertEqual(hash(t), hash(t.replace(fold=1))) |
---|
4332 | n/a | self.assertEqual(hash(dt), hash(dt.replace(fold=1))) |
---|
4333 | n/a | |
---|
4334 | n/a | @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') |
---|
4335 | n/a | def test_fromtimestamp(self): |
---|
4336 | n/a | s = 1414906200 |
---|
4337 | n/a | dt0 = datetime.fromtimestamp(s) |
---|
4338 | n/a | dt1 = datetime.fromtimestamp(s + 3600) |
---|
4339 | n/a | self.assertEqual(dt0.fold, 0) |
---|
4340 | n/a | self.assertEqual(dt1.fold, 1) |
---|
4341 | n/a | |
---|
4342 | n/a | @support.run_with_tz('Australia/Lord_Howe') |
---|
4343 | n/a | def test_fromtimestamp_lord_howe(self): |
---|
4344 | n/a | tm = _time.localtime(1.4e9) |
---|
4345 | n/a | if _time.strftime('%Z%z', tm) != 'LHST+1030': |
---|
4346 | n/a | self.skipTest('Australia/Lord_Howe timezone is not supported on this platform') |
---|
4347 | n/a | # $ TZ=Australia/Lord_Howe date -r 1428158700 |
---|
4348 | n/a | # Sun Apr 5 01:45:00 LHDT 2015 |
---|
4349 | n/a | # $ TZ=Australia/Lord_Howe date -r 1428160500 |
---|
4350 | n/a | # Sun Apr 5 01:45:00 LHST 2015 |
---|
4351 | n/a | s = 1428158700 |
---|
4352 | n/a | t0 = datetime.fromtimestamp(s) |
---|
4353 | n/a | t1 = datetime.fromtimestamp(s + 1800) |
---|
4354 | n/a | self.assertEqual(t0, t1) |
---|
4355 | n/a | self.assertEqual(t0.fold, 0) |
---|
4356 | n/a | self.assertEqual(t1.fold, 1) |
---|
4357 | n/a | |
---|
4358 | n/a | |
---|
4359 | n/a | @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') |
---|
4360 | n/a | def test_timestamp(self): |
---|
4361 | n/a | dt0 = datetime(2014, 11, 2, 1, 30) |
---|
4362 | n/a | dt1 = dt0.replace(fold=1) |
---|
4363 | n/a | self.assertEqual(dt0.timestamp() + 3600, |
---|
4364 | n/a | dt1.timestamp()) |
---|
4365 | n/a | |
---|
4366 | n/a | @support.run_with_tz('Australia/Lord_Howe') |
---|
4367 | n/a | def test_timestamp_lord_howe(self): |
---|
4368 | n/a | tm = _time.localtime(1.4e9) |
---|
4369 | n/a | if _time.strftime('%Z%z', tm) != 'LHST+1030': |
---|
4370 | n/a | self.skipTest('Australia/Lord_Howe timezone is not supported on this platform') |
---|
4371 | n/a | t = datetime(2015, 4, 5, 1, 45) |
---|
4372 | n/a | s0 = t.replace(fold=0).timestamp() |
---|
4373 | n/a | s1 = t.replace(fold=1).timestamp() |
---|
4374 | n/a | self.assertEqual(s0 + 1800, s1) |
---|
4375 | n/a | |
---|
4376 | n/a | |
---|
4377 | n/a | @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') |
---|
4378 | n/a | def test_astimezone(self): |
---|
4379 | n/a | dt0 = datetime(2014, 11, 2, 1, 30) |
---|
4380 | n/a | dt1 = dt0.replace(fold=1) |
---|
4381 | n/a | # Convert both naive instances to aware. |
---|
4382 | n/a | adt0 = dt0.astimezone() |
---|
4383 | n/a | adt1 = dt1.astimezone() |
---|
4384 | n/a | # Check that the first instance in DST zone and the second in STD |
---|
4385 | n/a | self.assertEqual(adt0.tzname(), 'EDT') |
---|
4386 | n/a | self.assertEqual(adt1.tzname(), 'EST') |
---|
4387 | n/a | self.assertEqual(adt0 + HOUR, adt1) |
---|
4388 | n/a | # Aware instances with fixed offset tzinfo's always have fold=0 |
---|
4389 | n/a | self.assertEqual(adt0.fold, 0) |
---|
4390 | n/a | self.assertEqual(adt1.fold, 0) |
---|
4391 | n/a | |
---|
4392 | n/a | |
---|
4393 | n/a | def test_pickle_fold(self): |
---|
4394 | n/a | t = time(fold=1) |
---|
4395 | n/a | dt = datetime(1, 1, 1, fold=1) |
---|
4396 | n/a | for pickler, unpickler, proto in pickle_choices: |
---|
4397 | n/a | for x in [t, dt]: |
---|
4398 | n/a | s = pickler.dumps(x, proto) |
---|
4399 | n/a | y = unpickler.loads(s) |
---|
4400 | n/a | self.assertEqual(x, y) |
---|
4401 | n/a | self.assertEqual((0 if proto < 4 else x.fold), y.fold) |
---|
4402 | n/a | |
---|
4403 | n/a | def test_repr(self): |
---|
4404 | n/a | t = time(fold=1) |
---|
4405 | n/a | dt = datetime(1, 1, 1, fold=1) |
---|
4406 | n/a | self.assertEqual(repr(t), 'datetime.time(0, 0, fold=1)') |
---|
4407 | n/a | self.assertEqual(repr(dt), |
---|
4408 | n/a | 'datetime.datetime(1, 1, 1, 0, 0, fold=1)') |
---|
4409 | n/a | |
---|
4410 | n/a | def test_dst(self): |
---|
4411 | n/a | # Let's first establish that things work in regular times. |
---|
4412 | n/a | dt_summer = datetime(2002, 10, 27, 1, tzinfo=Eastern2) - timedelta.resolution |
---|
4413 | n/a | dt_winter = datetime(2002, 10, 27, 2, tzinfo=Eastern2) |
---|
4414 | n/a | self.assertEqual(dt_summer.dst(), HOUR) |
---|
4415 | n/a | self.assertEqual(dt_winter.dst(), ZERO) |
---|
4416 | n/a | # The disambiguation flag is ignored |
---|
4417 | n/a | self.assertEqual(dt_summer.replace(fold=1).dst(), HOUR) |
---|
4418 | n/a | self.assertEqual(dt_winter.replace(fold=1).dst(), ZERO) |
---|
4419 | n/a | |
---|
4420 | n/a | # Pick local time in the fold. |
---|
4421 | n/a | for minute in [0, 30, 59]: |
---|
4422 | n/a | dt = datetime(2002, 10, 27, 1, minute, tzinfo=Eastern2) |
---|
4423 | n/a | # With fold=0 (the default) it is in DST. |
---|
4424 | n/a | self.assertEqual(dt.dst(), HOUR) |
---|
4425 | n/a | # With fold=1 it is in STD. |
---|
4426 | n/a | self.assertEqual(dt.replace(fold=1).dst(), ZERO) |
---|
4427 | n/a | |
---|
4428 | n/a | # Pick local time in the gap. |
---|
4429 | n/a | for minute in [0, 30, 59]: |
---|
4430 | n/a | dt = datetime(2002, 4, 7, 2, minute, tzinfo=Eastern2) |
---|
4431 | n/a | # With fold=0 (the default) it is in STD. |
---|
4432 | n/a | self.assertEqual(dt.dst(), ZERO) |
---|
4433 | n/a | # With fold=1 it is in DST. |
---|
4434 | n/a | self.assertEqual(dt.replace(fold=1).dst(), HOUR) |
---|
4435 | n/a | |
---|
4436 | n/a | |
---|
4437 | n/a | def test_utcoffset(self): |
---|
4438 | n/a | # Let's first establish that things work in regular times. |
---|
4439 | n/a | dt_summer = datetime(2002, 10, 27, 1, tzinfo=Eastern2) - timedelta.resolution |
---|
4440 | n/a | dt_winter = datetime(2002, 10, 27, 2, tzinfo=Eastern2) |
---|
4441 | n/a | self.assertEqual(dt_summer.utcoffset(), -4 * HOUR) |
---|
4442 | n/a | self.assertEqual(dt_winter.utcoffset(), -5 * HOUR) |
---|
4443 | n/a | # The disambiguation flag is ignored |
---|
4444 | n/a | self.assertEqual(dt_summer.replace(fold=1).utcoffset(), -4 * HOUR) |
---|
4445 | n/a | self.assertEqual(dt_winter.replace(fold=1).utcoffset(), -5 * HOUR) |
---|
4446 | n/a | |
---|
4447 | n/a | def test_fromutc(self): |
---|
4448 | n/a | # Let's first establish that things work in regular times. |
---|
4449 | n/a | u_summer = datetime(2002, 10, 27, 6, tzinfo=Eastern2) - timedelta.resolution |
---|
4450 | n/a | u_winter = datetime(2002, 10, 27, 7, tzinfo=Eastern2) |
---|
4451 | n/a | t_summer = Eastern2.fromutc(u_summer) |
---|
4452 | n/a | t_winter = Eastern2.fromutc(u_winter) |
---|
4453 | n/a | self.assertEqual(t_summer, u_summer - 4 * HOUR) |
---|
4454 | n/a | self.assertEqual(t_winter, u_winter - 5 * HOUR) |
---|
4455 | n/a | self.assertEqual(t_summer.fold, 0) |
---|
4456 | n/a | self.assertEqual(t_winter.fold, 0) |
---|
4457 | n/a | |
---|
4458 | n/a | # What happens in the fall-back fold? |
---|
4459 | n/a | u = datetime(2002, 10, 27, 5, 30, tzinfo=Eastern2) |
---|
4460 | n/a | t0 = Eastern2.fromutc(u) |
---|
4461 | n/a | u += HOUR |
---|
4462 | n/a | t1 = Eastern2.fromutc(u) |
---|
4463 | n/a | self.assertEqual(t0, t1) |
---|
4464 | n/a | self.assertEqual(t0.fold, 0) |
---|
4465 | n/a | self.assertEqual(t1.fold, 1) |
---|
4466 | n/a | # The tricky part is when u is in the local fold: |
---|
4467 | n/a | u = datetime(2002, 10, 27, 1, 30, tzinfo=Eastern2) |
---|
4468 | n/a | t = Eastern2.fromutc(u) |
---|
4469 | n/a | self.assertEqual((t.day, t.hour), (26, 21)) |
---|
4470 | n/a | # .. or gets into the local fold after a standard time adjustment |
---|
4471 | n/a | u = datetime(2002, 10, 27, 6, 30, tzinfo=Eastern2) |
---|
4472 | n/a | t = Eastern2.fromutc(u) |
---|
4473 | n/a | self.assertEqual((t.day, t.hour), (27, 1)) |
---|
4474 | n/a | |
---|
4475 | n/a | # What happens in the spring-forward gap? |
---|
4476 | n/a | u = datetime(2002, 4, 7, 2, 0, tzinfo=Eastern2) |
---|
4477 | n/a | t = Eastern2.fromutc(u) |
---|
4478 | n/a | self.assertEqual((t.day, t.hour), (6, 21)) |
---|
4479 | n/a | |
---|
4480 | n/a | def test_mixed_compare_regular(self): |
---|
4481 | n/a | t = datetime(2000, 1, 1, tzinfo=Eastern2) |
---|
4482 | n/a | self.assertEqual(t, t.astimezone(timezone.utc)) |
---|
4483 | n/a | t = datetime(2000, 6, 1, tzinfo=Eastern2) |
---|
4484 | n/a | self.assertEqual(t, t.astimezone(timezone.utc)) |
---|
4485 | n/a | |
---|
4486 | n/a | def test_mixed_compare_fold(self): |
---|
4487 | n/a | t_fold = datetime(2002, 10, 27, 1, 45, tzinfo=Eastern2) |
---|
4488 | n/a | t_fold_utc = t_fold.astimezone(timezone.utc) |
---|
4489 | n/a | self.assertNotEqual(t_fold, t_fold_utc) |
---|
4490 | n/a | |
---|
4491 | n/a | def test_mixed_compare_gap(self): |
---|
4492 | n/a | t_gap = datetime(2002, 4, 7, 2, 45, tzinfo=Eastern2) |
---|
4493 | n/a | t_gap_utc = t_gap.astimezone(timezone.utc) |
---|
4494 | n/a | self.assertNotEqual(t_gap, t_gap_utc) |
---|
4495 | n/a | |
---|
4496 | n/a | def test_hash_aware(self): |
---|
4497 | n/a | t = datetime(2000, 1, 1, tzinfo=Eastern2) |
---|
4498 | n/a | self.assertEqual(hash(t), hash(t.replace(fold=1))) |
---|
4499 | n/a | t_fold = datetime(2002, 10, 27, 1, 45, tzinfo=Eastern2) |
---|
4500 | n/a | t_gap = datetime(2002, 4, 7, 2, 45, tzinfo=Eastern2) |
---|
4501 | n/a | self.assertEqual(hash(t_fold), hash(t_fold.replace(fold=1))) |
---|
4502 | n/a | self.assertEqual(hash(t_gap), hash(t_gap.replace(fold=1))) |
---|
4503 | n/a | |
---|
4504 | n/a | SEC = timedelta(0, 1) |
---|
4505 | n/a | |
---|
4506 | n/a | def pairs(iterable): |
---|
4507 | n/a | a, b = itertools.tee(iterable) |
---|
4508 | n/a | next(b, None) |
---|
4509 | n/a | return zip(a, b) |
---|
4510 | n/a | |
---|
4511 | n/a | class ZoneInfo(tzinfo): |
---|
4512 | n/a | zoneroot = '/usr/share/zoneinfo' |
---|
4513 | n/a | def __init__(self, ut, ti): |
---|
4514 | n/a | """ |
---|
4515 | n/a | |
---|
4516 | n/a | :param ut: array |
---|
4517 | n/a | Array of transition point timestamps |
---|
4518 | n/a | :param ti: list |
---|
4519 | n/a | A list of (offset, isdst, abbr) tuples |
---|
4520 | n/a | :return: None |
---|
4521 | n/a | """ |
---|
4522 | n/a | self.ut = ut |
---|
4523 | n/a | self.ti = ti |
---|
4524 | n/a | self.lt = self.invert(ut, ti) |
---|
4525 | n/a | |
---|
4526 | n/a | @staticmethod |
---|
4527 | n/a | def invert(ut, ti): |
---|
4528 | n/a | lt = (array('q', ut), array('q', ut)) |
---|
4529 | n/a | if ut: |
---|
4530 | n/a | offset = ti[0][0] // SEC |
---|
4531 | n/a | lt[0][0] += offset |
---|
4532 | n/a | lt[1][0] += offset |
---|
4533 | n/a | for i in range(1, len(ut)): |
---|
4534 | n/a | lt[0][i] += ti[i-1][0] // SEC |
---|
4535 | n/a | lt[1][i] += ti[i][0] // SEC |
---|
4536 | n/a | return lt |
---|
4537 | n/a | |
---|
4538 | n/a | @classmethod |
---|
4539 | n/a | def fromfile(cls, fileobj): |
---|
4540 | n/a | if fileobj.read(4).decode() != "TZif": |
---|
4541 | n/a | raise ValueError("not a zoneinfo file") |
---|
4542 | n/a | fileobj.seek(32) |
---|
4543 | n/a | counts = array('i') |
---|
4544 | n/a | counts.fromfile(fileobj, 3) |
---|
4545 | n/a | if sys.byteorder != 'big': |
---|
4546 | n/a | counts.byteswap() |
---|
4547 | n/a | |
---|
4548 | n/a | ut = array('i') |
---|
4549 | n/a | ut.fromfile(fileobj, counts[0]) |
---|
4550 | n/a | if sys.byteorder != 'big': |
---|
4551 | n/a | ut.byteswap() |
---|
4552 | n/a | |
---|
4553 | n/a | type_indices = array('B') |
---|
4554 | n/a | type_indices.fromfile(fileobj, counts[0]) |
---|
4555 | n/a | |
---|
4556 | n/a | ttis = [] |
---|
4557 | n/a | for i in range(counts[1]): |
---|
4558 | n/a | ttis.append(struct.unpack(">lbb", fileobj.read(6))) |
---|
4559 | n/a | |
---|
4560 | n/a | abbrs = fileobj.read(counts[2]) |
---|
4561 | n/a | |
---|
4562 | n/a | # Convert ttis |
---|
4563 | n/a | for i, (gmtoff, isdst, abbrind) in enumerate(ttis): |
---|
4564 | n/a | abbr = abbrs[abbrind:abbrs.find(0, abbrind)].decode() |
---|
4565 | n/a | ttis[i] = (timedelta(0, gmtoff), isdst, abbr) |
---|
4566 | n/a | |
---|
4567 | n/a | ti = [None] * len(ut) |
---|
4568 | n/a | for i, idx in enumerate(type_indices): |
---|
4569 | n/a | ti[i] = ttis[idx] |
---|
4570 | n/a | |
---|
4571 | n/a | self = cls(ut, ti) |
---|
4572 | n/a | |
---|
4573 | n/a | return self |
---|
4574 | n/a | |
---|
4575 | n/a | @classmethod |
---|
4576 | n/a | def fromname(cls, name): |
---|
4577 | n/a | path = os.path.join(cls.zoneroot, name) |
---|
4578 | n/a | with open(path, 'rb') as f: |
---|
4579 | n/a | return cls.fromfile(f) |
---|
4580 | n/a | |
---|
4581 | n/a | EPOCHORDINAL = date(1970, 1, 1).toordinal() |
---|
4582 | n/a | |
---|
4583 | n/a | def fromutc(self, dt): |
---|
4584 | n/a | """datetime in UTC -> datetime in local time.""" |
---|
4585 | n/a | |
---|
4586 | n/a | if not isinstance(dt, datetime): |
---|
4587 | n/a | raise TypeError("fromutc() requires a datetime argument") |
---|
4588 | n/a | if dt.tzinfo is not self: |
---|
4589 | n/a | raise ValueError("dt.tzinfo is not self") |
---|
4590 | n/a | |
---|
4591 | n/a | timestamp = ((dt.toordinal() - self.EPOCHORDINAL) * 86400 |
---|
4592 | n/a | + dt.hour * 3600 |
---|
4593 | n/a | + dt.minute * 60 |
---|
4594 | n/a | + dt.second) |
---|
4595 | n/a | |
---|
4596 | n/a | if timestamp < self.ut[1]: |
---|
4597 | n/a | tti = self.ti[0] |
---|
4598 | n/a | fold = 0 |
---|
4599 | n/a | else: |
---|
4600 | n/a | idx = bisect.bisect_right(self.ut, timestamp) |
---|
4601 | n/a | assert self.ut[idx-1] <= timestamp |
---|
4602 | n/a | assert idx == len(self.ut) or timestamp < self.ut[idx] |
---|
4603 | n/a | tti_prev, tti = self.ti[idx-2:idx] |
---|
4604 | n/a | # Detect fold |
---|
4605 | n/a | shift = tti_prev[0] - tti[0] |
---|
4606 | n/a | fold = (shift > timedelta(0, timestamp - self.ut[idx-1])) |
---|
4607 | n/a | dt += tti[0] |
---|
4608 | n/a | if fold: |
---|
4609 | n/a | return dt.replace(fold=1) |
---|
4610 | n/a | else: |
---|
4611 | n/a | return dt |
---|
4612 | n/a | |
---|
4613 | n/a | def _find_ti(self, dt, i): |
---|
4614 | n/a | timestamp = ((dt.toordinal() - self.EPOCHORDINAL) * 86400 |
---|
4615 | n/a | + dt.hour * 3600 |
---|
4616 | n/a | + dt.minute * 60 |
---|
4617 | n/a | + dt.second) |
---|
4618 | n/a | lt = self.lt[dt.fold] |
---|
4619 | n/a | idx = bisect.bisect_right(lt, timestamp) |
---|
4620 | n/a | |
---|
4621 | n/a | return self.ti[max(0, idx - 1)][i] |
---|
4622 | n/a | |
---|
4623 | n/a | def utcoffset(self, dt): |
---|
4624 | n/a | return self._find_ti(dt, 0) |
---|
4625 | n/a | |
---|
4626 | n/a | def dst(self, dt): |
---|
4627 | n/a | isdst = self._find_ti(dt, 1) |
---|
4628 | n/a | # XXX: We cannot accurately determine the "save" value, |
---|
4629 | n/a | # so let's return 1h whenever DST is in effect. Since |
---|
4630 | n/a | # we don't use dst() in fromutc(), it is unlikely that |
---|
4631 | n/a | # it will be needed for anything more than bool(dst()). |
---|
4632 | n/a | return ZERO if isdst else HOUR |
---|
4633 | n/a | |
---|
4634 | n/a | def tzname(self, dt): |
---|
4635 | n/a | return self._find_ti(dt, 2) |
---|
4636 | n/a | |
---|
4637 | n/a | @classmethod |
---|
4638 | n/a | def zonenames(cls, zonedir=None): |
---|
4639 | n/a | if zonedir is None: |
---|
4640 | n/a | zonedir = cls.zoneroot |
---|
4641 | n/a | zone_tab = os.path.join(zonedir, 'zone.tab') |
---|
4642 | n/a | try: |
---|
4643 | n/a | f = open(zone_tab) |
---|
4644 | n/a | except OSError: |
---|
4645 | n/a | return |
---|
4646 | n/a | with f: |
---|
4647 | n/a | for line in f: |
---|
4648 | n/a | line = line.strip() |
---|
4649 | n/a | if line and not line.startswith('#'): |
---|
4650 | n/a | yield line.split()[2] |
---|
4651 | n/a | |
---|
4652 | n/a | @classmethod |
---|
4653 | n/a | def stats(cls, start_year=1): |
---|
4654 | n/a | count = gap_count = fold_count = zeros_count = 0 |
---|
4655 | n/a | min_gap = min_fold = timedelta.max |
---|
4656 | n/a | max_gap = max_fold = ZERO |
---|
4657 | n/a | min_gap_datetime = max_gap_datetime = datetime.min |
---|
4658 | n/a | min_gap_zone = max_gap_zone = None |
---|
4659 | n/a | min_fold_datetime = max_fold_datetime = datetime.min |
---|
4660 | n/a | min_fold_zone = max_fold_zone = None |
---|
4661 | n/a | stats_since = datetime(start_year, 1, 1) # Starting from 1970 eliminates a lot of noise |
---|
4662 | n/a | for zonename in cls.zonenames(): |
---|
4663 | n/a | count += 1 |
---|
4664 | n/a | tz = cls.fromname(zonename) |
---|
4665 | n/a | for dt, shift in tz.transitions(): |
---|
4666 | n/a | if dt < stats_since: |
---|
4667 | n/a | continue |
---|
4668 | n/a | if shift > ZERO: |
---|
4669 | n/a | gap_count += 1 |
---|
4670 | n/a | if (shift, dt) > (max_gap, max_gap_datetime): |
---|
4671 | n/a | max_gap = shift |
---|
4672 | n/a | max_gap_zone = zonename |
---|
4673 | n/a | max_gap_datetime = dt |
---|
4674 | n/a | if (shift, datetime.max - dt) < (min_gap, datetime.max - min_gap_datetime): |
---|
4675 | n/a | min_gap = shift |
---|
4676 | n/a | min_gap_zone = zonename |
---|
4677 | n/a | min_gap_datetime = dt |
---|
4678 | n/a | elif shift < ZERO: |
---|
4679 | n/a | fold_count += 1 |
---|
4680 | n/a | shift = -shift |
---|
4681 | n/a | if (shift, dt) > (max_fold, max_fold_datetime): |
---|
4682 | n/a | max_fold = shift |
---|
4683 | n/a | max_fold_zone = zonename |
---|
4684 | n/a | max_fold_datetime = dt |
---|
4685 | n/a | if (shift, datetime.max - dt) < (min_fold, datetime.max - min_fold_datetime): |
---|
4686 | n/a | min_fold = shift |
---|
4687 | n/a | min_fold_zone = zonename |
---|
4688 | n/a | min_fold_datetime = dt |
---|
4689 | n/a | else: |
---|
4690 | n/a | zeros_count += 1 |
---|
4691 | n/a | trans_counts = (gap_count, fold_count, zeros_count) |
---|
4692 | n/a | print("Number of zones: %5d" % count) |
---|
4693 | n/a | print("Number of transitions: %5d = %d (gaps) + %d (folds) + %d (zeros)" % |
---|
4694 | n/a | ((sum(trans_counts),) + trans_counts)) |
---|
4695 | n/a | print("Min gap: %16s at %s in %s" % (min_gap, min_gap_datetime, min_gap_zone)) |
---|
4696 | n/a | print("Max gap: %16s at %s in %s" % (max_gap, max_gap_datetime, max_gap_zone)) |
---|
4697 | n/a | print("Min fold: %16s at %s in %s" % (min_fold, min_fold_datetime, min_fold_zone)) |
---|
4698 | n/a | print("Max fold: %16s at %s in %s" % (max_fold, max_fold_datetime, max_fold_zone)) |
---|
4699 | n/a | |
---|
4700 | n/a | |
---|
4701 | n/a | def transitions(self): |
---|
4702 | n/a | for (_, prev_ti), (t, ti) in pairs(zip(self.ut, self.ti)): |
---|
4703 | n/a | shift = ti[0] - prev_ti[0] |
---|
4704 | n/a | yield datetime.utcfromtimestamp(t), shift |
---|
4705 | n/a | |
---|
4706 | n/a | def nondst_folds(self): |
---|
4707 | n/a | """Find all folds with the same value of isdst on both sides of the transition.""" |
---|
4708 | n/a | for (_, prev_ti), (t, ti) in pairs(zip(self.ut, self.ti)): |
---|
4709 | n/a | shift = ti[0] - prev_ti[0] |
---|
4710 | n/a | if shift < ZERO and ti[1] == prev_ti[1]: |
---|
4711 | n/a | yield datetime.utcfromtimestamp(t), -shift, prev_ti[2], ti[2] |
---|
4712 | n/a | |
---|
4713 | n/a | @classmethod |
---|
4714 | n/a | def print_all_nondst_folds(cls, same_abbr=False, start_year=1): |
---|
4715 | n/a | count = 0 |
---|
4716 | n/a | for zonename in cls.zonenames(): |
---|
4717 | n/a | tz = cls.fromname(zonename) |
---|
4718 | n/a | for dt, shift, prev_abbr, abbr in tz.nondst_folds(): |
---|
4719 | n/a | if dt.year < start_year or same_abbr and prev_abbr != abbr: |
---|
4720 | n/a | continue |
---|
4721 | n/a | count += 1 |
---|
4722 | n/a | print("%3d) %-30s %s %10s %5s -> %s" % |
---|
4723 | n/a | (count, zonename, dt, shift, prev_abbr, abbr)) |
---|
4724 | n/a | |
---|
4725 | n/a | def folds(self): |
---|
4726 | n/a | for t, shift in self.transitions(): |
---|
4727 | n/a | if shift < ZERO: |
---|
4728 | n/a | yield t, -shift |
---|
4729 | n/a | |
---|
4730 | n/a | def gaps(self): |
---|
4731 | n/a | for t, shift in self.transitions(): |
---|
4732 | n/a | if shift > ZERO: |
---|
4733 | n/a | yield t, shift |
---|
4734 | n/a | |
---|
4735 | n/a | def zeros(self): |
---|
4736 | n/a | for t, shift in self.transitions(): |
---|
4737 | n/a | if not shift: |
---|
4738 | n/a | yield t |
---|
4739 | n/a | |
---|
4740 | n/a | |
---|
4741 | n/a | class ZoneInfoTest(unittest.TestCase): |
---|
4742 | n/a | zonename = 'America/New_York' |
---|
4743 | n/a | |
---|
4744 | n/a | def setUp(self): |
---|
4745 | n/a | if sys.platform == "win32": |
---|
4746 | n/a | self.skipTest("Skipping zoneinfo tests on Windows") |
---|
4747 | n/a | try: |
---|
4748 | n/a | self.tz = ZoneInfo.fromname(self.zonename) |
---|
4749 | n/a | except FileNotFoundError as err: |
---|
4750 | n/a | self.skipTest("Skipping %s: %s" % (self.zonename, err)) |
---|
4751 | n/a | |
---|
4752 | n/a | def assertEquivDatetimes(self, a, b): |
---|
4753 | n/a | self.assertEqual((a.replace(tzinfo=None), a.fold, id(a.tzinfo)), |
---|
4754 | n/a | (b.replace(tzinfo=None), b.fold, id(b.tzinfo))) |
---|
4755 | n/a | |
---|
4756 | n/a | def test_folds(self): |
---|
4757 | n/a | tz = self.tz |
---|
4758 | n/a | for dt, shift in tz.folds(): |
---|
4759 | n/a | for x in [0 * shift, 0.5 * shift, shift - timedelta.resolution]: |
---|
4760 | n/a | udt = dt + x |
---|
4761 | n/a | ldt = tz.fromutc(udt.replace(tzinfo=tz)) |
---|
4762 | n/a | self.assertEqual(ldt.fold, 1) |
---|
4763 | n/a | adt = udt.replace(tzinfo=timezone.utc).astimezone(tz) |
---|
4764 | n/a | self.assertEquivDatetimes(adt, ldt) |
---|
4765 | n/a | utcoffset = ldt.utcoffset() |
---|
4766 | n/a | self.assertEqual(ldt.replace(tzinfo=None), udt + utcoffset) |
---|
4767 | n/a | # Round trip |
---|
4768 | n/a | self.assertEquivDatetimes(ldt.astimezone(timezone.utc), |
---|
4769 | n/a | udt.replace(tzinfo=timezone.utc)) |
---|
4770 | n/a | |
---|
4771 | n/a | |
---|
4772 | n/a | for x in [-timedelta.resolution, shift]: |
---|
4773 | n/a | udt = dt + x |
---|
4774 | n/a | udt = udt.replace(tzinfo=tz) |
---|
4775 | n/a | ldt = tz.fromutc(udt) |
---|
4776 | n/a | self.assertEqual(ldt.fold, 0) |
---|
4777 | n/a | |
---|
4778 | n/a | def test_gaps(self): |
---|
4779 | n/a | tz = self.tz |
---|
4780 | n/a | for dt, shift in tz.gaps(): |
---|
4781 | n/a | for x in [0 * shift, 0.5 * shift, shift - timedelta.resolution]: |
---|
4782 | n/a | udt = dt + x |
---|
4783 | n/a | udt = udt.replace(tzinfo=tz) |
---|
4784 | n/a | ldt = tz.fromutc(udt) |
---|
4785 | n/a | self.assertEqual(ldt.fold, 0) |
---|
4786 | n/a | adt = udt.replace(tzinfo=timezone.utc).astimezone(tz) |
---|
4787 | n/a | self.assertEquivDatetimes(adt, ldt) |
---|
4788 | n/a | utcoffset = ldt.utcoffset() |
---|
4789 | n/a | self.assertEqual(ldt.replace(tzinfo=None), udt.replace(tzinfo=None) + utcoffset) |
---|
4790 | n/a | # Create a local time inside the gap |
---|
4791 | n/a | ldt = tz.fromutc(dt.replace(tzinfo=tz)) - shift + x |
---|
4792 | n/a | self.assertLess(ldt.replace(fold=1).utcoffset(), |
---|
4793 | n/a | ldt.replace(fold=0).utcoffset(), |
---|
4794 | n/a | "At %s." % ldt) |
---|
4795 | n/a | |
---|
4796 | n/a | for x in [-timedelta.resolution, shift]: |
---|
4797 | n/a | udt = dt + x |
---|
4798 | n/a | ldt = tz.fromutc(udt.replace(tzinfo=tz)) |
---|
4799 | n/a | self.assertEqual(ldt.fold, 0) |
---|
4800 | n/a | |
---|
4801 | n/a | def test_system_transitions(self): |
---|
4802 | n/a | if ('Riyadh8' in self.zonename or |
---|
4803 | n/a | # From tzdata NEWS file: |
---|
4804 | n/a | # The files solar87, solar88, and solar89 are no longer distributed. |
---|
4805 | n/a | # They were a negative experiment - that is, a demonstration that |
---|
4806 | n/a | # tz data can represent solar time only with some difficulty and error. |
---|
4807 | n/a | # Their presence in the distribution caused confusion, as Riyadh |
---|
4808 | n/a | # civil time was generally not solar time in those years. |
---|
4809 | n/a | self.zonename.startswith('right/')): |
---|
4810 | n/a | self.skipTest("Skipping %s" % self.zonename) |
---|
4811 | n/a | tz = self.tz |
---|
4812 | n/a | TZ = os.environ.get('TZ') |
---|
4813 | n/a | os.environ['TZ'] = self.zonename |
---|
4814 | n/a | try: |
---|
4815 | n/a | _time.tzset() |
---|
4816 | n/a | for udt, shift in tz.transitions(): |
---|
4817 | n/a | if udt.year >= 2037: |
---|
4818 | n/a | # System support for times around the end of 32-bit time_t |
---|
4819 | n/a | # and later is flaky on many systems. |
---|
4820 | n/a | break |
---|
4821 | n/a | s0 = (udt - datetime(1970, 1, 1)) // SEC |
---|
4822 | n/a | ss = shift // SEC # shift seconds |
---|
4823 | n/a | for x in [-40 * 3600, -20*3600, -1, 0, |
---|
4824 | n/a | ss - 1, ss + 20 * 3600, ss + 40 * 3600]: |
---|
4825 | n/a | s = s0 + x |
---|
4826 | n/a | sdt = datetime.fromtimestamp(s) |
---|
4827 | n/a | tzdt = datetime.fromtimestamp(s, tz).replace(tzinfo=None) |
---|
4828 | n/a | self.assertEquivDatetimes(sdt, tzdt) |
---|
4829 | n/a | s1 = sdt.timestamp() |
---|
4830 | n/a | self.assertEqual(s, s1) |
---|
4831 | n/a | if ss > 0: # gap |
---|
4832 | n/a | # Create local time inside the gap |
---|
4833 | n/a | dt = datetime.fromtimestamp(s0) - shift / 2 |
---|
4834 | n/a | ts0 = dt.timestamp() |
---|
4835 | n/a | ts1 = dt.replace(fold=1).timestamp() |
---|
4836 | n/a | self.assertEqual(ts0, s0 + ss / 2) |
---|
4837 | n/a | self.assertEqual(ts1, s0 - ss / 2) |
---|
4838 | n/a | finally: |
---|
4839 | n/a | if TZ is None: |
---|
4840 | n/a | del os.environ['TZ'] |
---|
4841 | n/a | else: |
---|
4842 | n/a | os.environ['TZ'] = TZ |
---|
4843 | n/a | _time.tzset() |
---|
4844 | n/a | |
---|
4845 | n/a | |
---|
4846 | n/a | class ZoneInfoCompleteTest(unittest.TestSuite): |
---|
4847 | n/a | def __init__(self): |
---|
4848 | n/a | tests = [] |
---|
4849 | n/a | if is_resource_enabled('tzdata'): |
---|
4850 | n/a | for name in ZoneInfo.zonenames(): |
---|
4851 | n/a | Test = type('ZoneInfoTest[%s]' % name, (ZoneInfoTest,), {}) |
---|
4852 | n/a | Test.zonename = name |
---|
4853 | n/a | for method in dir(Test): |
---|
4854 | n/a | if method.startswith('test_'): |
---|
4855 | n/a | tests.append(Test(method)) |
---|
4856 | n/a | super().__init__(tests) |
---|
4857 | n/a | |
---|
4858 | n/a | # Iran had a sub-minute UTC offset before 1946. |
---|
4859 | n/a | class IranTest(ZoneInfoTest): |
---|
4860 | n/a | zonename = 'Asia/Tehran' |
---|
4861 | n/a | |
---|
4862 | n/a | def load_tests(loader, standard_tests, pattern): |
---|
4863 | n/a | standard_tests.addTest(ZoneInfoCompleteTest()) |
---|
4864 | n/a | return standard_tests |
---|
4865 | n/a | |
---|
4866 | n/a | |
---|
4867 | n/a | if __name__ == "__main__": |
---|
4868 | n/a | unittest.main() |
---|