blob: ead8d704d570dd1251c20e554ce2e524fb0b78f0 [file] [log] [blame]
Tim Peters0bf60bd2003-01-08 20:40:01 +00001"""Test date/time type.
2
3See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases
4"""
Tim Peters2a799bf2002-12-16 20:18:38 +00005
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import os
Guido van Rossum177e41a2003-01-30 22:06:23 +00007import pickle
Tim Peters2a799bf2002-12-16 20:18:38 +00008import unittest
9
Mark Dickinsona56c4672009-01-27 18:17:45 +000010from operator import lt, le, gt, ge, eq, ne
11
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
Tim Peters2a799bf2002-12-16 20:18:38 +000013
14from datetime import MINYEAR, MAXYEAR
15from datetime import timedelta
16from datetime import tzinfo
Tim Peters0bf60bd2003-01-08 20:40:01 +000017from datetime import time
18from datetime import date, datetime
19
Guido van Rossumbe6fe542007-07-19 23:55:34 +000020pickle_choices = [(pickle, pickle, proto) for proto in range(3)]
21assert len(pickle_choices) == 3
Guido van Rossum177e41a2003-01-30 22:06:23 +000022
Tim Peters68124bb2003-02-08 03:46:31 +000023# An arbitrary collection of objects of non-datetime types, for testing
24# mixed-type comparisons.
Guido van Rossume2a383d2007-01-15 16:59:06 +000025OTHERSTUFF = (10, 10, 34.5, "abc", {}, [], ())
Tim Peters0bf60bd2003-01-08 20:40:01 +000026
Tim Peters2a799bf2002-12-16 20:18:38 +000027
28#############################################################################
29# module tests
30
31class TestModule(unittest.TestCase):
32
33 def test_constants(self):
34 import datetime
35 self.assertEqual(datetime.MINYEAR, 1)
36 self.assertEqual(datetime.MAXYEAR, 9999)
37
38#############################################################################
39# tzinfo tests
40
41class FixedOffset(tzinfo):
42 def __init__(self, offset, name, dstoffset=42):
Tim Peters397301e2003-01-02 21:28:08 +000043 if isinstance(offset, int):
44 offset = timedelta(minutes=offset)
45 if isinstance(dstoffset, int):
46 dstoffset = timedelta(minutes=dstoffset)
Tim Peters2a799bf2002-12-16 20:18:38 +000047 self.__offset = offset
48 self.__name = name
49 self.__dstoffset = dstoffset
50 def __repr__(self):
51 return self.__name.lower()
52 def utcoffset(self, dt):
53 return self.__offset
54 def tzname(self, dt):
55 return self.__name
56 def dst(self, dt):
57 return self.__dstoffset
58
Tim Petersfb8472c2002-12-21 05:04:42 +000059class PicklableFixedOffset(FixedOffset):
60 def __init__(self, offset=None, name=None, dstoffset=None):
61 FixedOffset.__init__(self, offset, name, dstoffset)
62
Tim Peters2a799bf2002-12-16 20:18:38 +000063class TestTZInfo(unittest.TestCase):
64
65 def test_non_abstractness(self):
66 # In order to allow subclasses to get pickled, the C implementation
67 # wasn't able to get away with having __init__ raise
68 # NotImplementedError.
69 useless = tzinfo()
70 dt = datetime.max
71 self.assertRaises(NotImplementedError, useless.tzname, dt)
72 self.assertRaises(NotImplementedError, useless.utcoffset, dt)
73 self.assertRaises(NotImplementedError, useless.dst, dt)
74
75 def test_subclass_must_override(self):
76 class NotEnough(tzinfo):
77 def __init__(self, offset, name):
78 self.__offset = offset
79 self.__name = name
Georg Brandlab91fde2009-08-13 08:51:18 +000080 self.assertTrue(issubclass(NotEnough, tzinfo))
Tim Peters2a799bf2002-12-16 20:18:38 +000081 ne = NotEnough(3, "NotByALongShot")
Georg Brandlab91fde2009-08-13 08:51:18 +000082 self.assertTrue(isinstance(ne, tzinfo))
Tim Peters2a799bf2002-12-16 20:18:38 +000083
84 dt = datetime.now()
85 self.assertRaises(NotImplementedError, ne.tzname, dt)
86 self.assertRaises(NotImplementedError, ne.utcoffset, dt)
87 self.assertRaises(NotImplementedError, ne.dst, dt)
88
89 def test_normal(self):
90 fo = FixedOffset(3, "Three")
Georg Brandlab91fde2009-08-13 08:51:18 +000091 self.assertTrue(isinstance(fo, tzinfo))
Tim Peters2a799bf2002-12-16 20:18:38 +000092 for dt in datetime.now(), None:
Tim Peters397301e2003-01-02 21:28:08 +000093 self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
Tim Peters2a799bf2002-12-16 20:18:38 +000094 self.assertEqual(fo.tzname(dt), "Three")
Tim Peters397301e2003-01-02 21:28:08 +000095 self.assertEqual(fo.dst(dt), timedelta(minutes=42))
Tim Peters2a799bf2002-12-16 20:18:38 +000096
97 def test_pickling_base(self):
Tim Peters2a799bf2002-12-16 20:18:38 +000098 # There's no point to pickling tzinfo objects on their own (they
99 # carry no data), but they need to be picklable anyway else
100 # concrete subclasses can't be pickled.
101 orig = tzinfo.__new__(tzinfo)
Georg Brandlab91fde2009-08-13 08:51:18 +0000102 self.assertTrue(type(orig) is tzinfo)
Guido van Rossum177e41a2003-01-30 22:06:23 +0000103 for pickler, unpickler, proto in pickle_choices:
Tim Petersf2715e02003-02-19 02:35:07 +0000104 green = pickler.dumps(orig, proto)
105 derived = unpickler.loads(green)
Georg Brandlab91fde2009-08-13 08:51:18 +0000106 self.assertTrue(type(derived) is tzinfo)
Tim Peters2a799bf2002-12-16 20:18:38 +0000107
108 def test_pickling_subclass(self):
Tim Peters2a799bf2002-12-16 20:18:38 +0000109 # Make sure we can pickle/unpickle an instance of a subclass.
Tim Peters397301e2003-01-02 21:28:08 +0000110 offset = timedelta(minutes=-300)
111 orig = PicklableFixedOffset(offset, 'cookie')
Georg Brandlab91fde2009-08-13 08:51:18 +0000112 self.assertTrue(isinstance(orig, tzinfo))
113 self.assertTrue(type(orig) is PicklableFixedOffset)
Tim Peters397301e2003-01-02 21:28:08 +0000114 self.assertEqual(orig.utcoffset(None), offset)
Tim Peters2a799bf2002-12-16 20:18:38 +0000115 self.assertEqual(orig.tzname(None), 'cookie')
Guido van Rossum177e41a2003-01-30 22:06:23 +0000116 for pickler, unpickler, proto in pickle_choices:
Tim Petersf2715e02003-02-19 02:35:07 +0000117 green = pickler.dumps(orig, proto)
118 derived = unpickler.loads(green)
Georg Brandlab91fde2009-08-13 08:51:18 +0000119 self.assertTrue(isinstance(derived, tzinfo))
120 self.assertTrue(type(derived) is PicklableFixedOffset)
Tim Petersf2715e02003-02-19 02:35:07 +0000121 self.assertEqual(derived.utcoffset(None), offset)
122 self.assertEqual(derived.tzname(None), 'cookie')
Tim Peters2a799bf2002-12-16 20:18:38 +0000123
124#############################################################################
Tim Peters07534a62003-02-07 22:50:28 +0000125# Base clase for testing a particular aspect of timedelta, time, date and
126# datetime comparisons.
127
Guido van Rossumd8faa362007-04-27 19:54:29 +0000128class HarmlessMixedComparison:
Tim Peters07534a62003-02-07 22:50:28 +0000129 # Test that __eq__ and __ne__ don't complain for mixed-type comparisons.
130
131 # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a
132 # legit constructor.
133
134 def test_harmless_mixed_comparison(self):
135 me = self.theclass(1, 1, 1)
136
Georg Brandlab91fde2009-08-13 08:51:18 +0000137 self.assertFalse(me == ())
138 self.assertTrue(me != ())
139 self.assertFalse(() == me)
140 self.assertTrue(() != me)
Tim Peters07534a62003-02-07 22:50:28 +0000141
Georg Brandlab91fde2009-08-13 08:51:18 +0000142 self.assertTrue(me in [1, 20, [], me])
143 self.assertFalse(me not in [1, 20, [], me])
Tim Peters07534a62003-02-07 22:50:28 +0000144
Georg Brandlab91fde2009-08-13 08:51:18 +0000145 self.assertTrue([] in [me, 1, 20, []])
146 self.assertFalse([] not in [me, 1, 20, []])
Tim Peters07534a62003-02-07 22:50:28 +0000147
148 def test_harmful_mixed_comparison(self):
149 me = self.theclass(1, 1, 1)
150
151 self.assertRaises(TypeError, lambda: me < ())
152 self.assertRaises(TypeError, lambda: me <= ())
153 self.assertRaises(TypeError, lambda: me > ())
154 self.assertRaises(TypeError, lambda: me >= ())
155
156 self.assertRaises(TypeError, lambda: () < me)
157 self.assertRaises(TypeError, lambda: () <= me)
158 self.assertRaises(TypeError, lambda: () > me)
159 self.assertRaises(TypeError, lambda: () >= me)
160
Tim Peters07534a62003-02-07 22:50:28 +0000161#############################################################################
Tim Peters2a799bf2002-12-16 20:18:38 +0000162# timedelta tests
163
Guido van Rossumd8faa362007-04-27 19:54:29 +0000164class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
Tim Peters07534a62003-02-07 22:50:28 +0000165
166 theclass = timedelta
Tim Peters2a799bf2002-12-16 20:18:38 +0000167
168 def test_constructor(self):
169 eq = self.assertEqual
170 td = timedelta
171
172 # Check keyword args to constructor
173 eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0,
174 milliseconds=0, microseconds=0))
175 eq(td(1), td(days=1))
176 eq(td(0, 1), td(seconds=1))
177 eq(td(0, 0, 1), td(microseconds=1))
178 eq(td(weeks=1), td(days=7))
179 eq(td(days=1), td(hours=24))
180 eq(td(hours=1), td(minutes=60))
181 eq(td(minutes=1), td(seconds=60))
182 eq(td(seconds=1), td(milliseconds=1000))
183 eq(td(milliseconds=1), td(microseconds=1000))
184
185 # Check float args to constructor
186 eq(td(weeks=1.0/7), td(days=1))
187 eq(td(days=1.0/24), td(hours=1))
188 eq(td(hours=1.0/60), td(minutes=1))
189 eq(td(minutes=1.0/60), td(seconds=1))
190 eq(td(seconds=0.001), td(milliseconds=1))
191 eq(td(milliseconds=0.001), td(microseconds=1))
192
193 def test_computations(self):
194 eq = self.assertEqual
195 td = timedelta
196
197 a = td(7) # One week
198 b = td(0, 60) # One minute
199 c = td(0, 0, 1000) # One millisecond
200 eq(a+b+c, td(7, 60, 1000))
201 eq(a-b, td(6, 24*3600 - 60))
202 eq(-a, td(-7))
203 eq(+a, td(7))
204 eq(-b, td(-1, 24*3600 - 60))
205 eq(-c, td(-1, 24*3600 - 1, 999000))
206 eq(abs(a), a)
207 eq(abs(-a), a)
208 eq(td(6, 24*3600), a)
209 eq(td(0, 0, 60*1000000), b)
210 eq(a*10, td(70))
211 eq(a*10, 10*a)
Guido van Rossume2a383d2007-01-15 16:59:06 +0000212 eq(a*10, 10*a)
Tim Peters2a799bf2002-12-16 20:18:38 +0000213 eq(b*10, td(0, 600))
214 eq(10*b, td(0, 600))
Guido van Rossume2a383d2007-01-15 16:59:06 +0000215 eq(b*10, td(0, 600))
Tim Peters2a799bf2002-12-16 20:18:38 +0000216 eq(c*10, td(0, 0, 10000))
217 eq(10*c, td(0, 0, 10000))
Guido van Rossume2a383d2007-01-15 16:59:06 +0000218 eq(c*10, td(0, 0, 10000))
Tim Peters2a799bf2002-12-16 20:18:38 +0000219 eq(a*-1, -a)
220 eq(b*-2, -b-b)
221 eq(c*-2, -c+-c)
222 eq(b*(60*24), (b*60)*24)
223 eq(b*(60*24), (60*b)*24)
224 eq(c*1000, td(0, 1))
225 eq(1000*c, td(0, 1))
226 eq(a//7, td(1))
227 eq(b//10, td(0, 6))
228 eq(c//1000, td(0, 0, 1))
229 eq(a//10, td(0, 7*24*360))
230 eq(a//3600000, td(0, 0, 7*24*1000))
231
232 def test_disallowed_computations(self):
233 a = timedelta(42)
234
235 # Add/sub ints, longs, floats should be illegal
Guido van Rossume2a383d2007-01-15 16:59:06 +0000236 for i in 1, 1, 1.0:
Tim Peters2a799bf2002-12-16 20:18:38 +0000237 self.assertRaises(TypeError, lambda: a+i)
238 self.assertRaises(TypeError, lambda: a-i)
239 self.assertRaises(TypeError, lambda: i+a)
240 self.assertRaises(TypeError, lambda: i-a)
241
242 # Mul/div by float isn't supported.
243 x = 2.3
244 self.assertRaises(TypeError, lambda: a*x)
245 self.assertRaises(TypeError, lambda: x*a)
246 self.assertRaises(TypeError, lambda: a/x)
247 self.assertRaises(TypeError, lambda: x/a)
248 self.assertRaises(TypeError, lambda: a // x)
249 self.assertRaises(TypeError, lambda: x // a)
250
Benjamin Petersonf10a79a2008-10-11 00:49:57 +0000251 # Division of int by timedelta doesn't make sense.
Tim Peters2a799bf2002-12-16 20:18:38 +0000252 # Division by zero doesn't make sense.
Guido van Rossume2a383d2007-01-15 16:59:06 +0000253 for zero in 0, 0:
Tim Peters2a799bf2002-12-16 20:18:38 +0000254 self.assertRaises(TypeError, lambda: zero // a)
255 self.assertRaises(ZeroDivisionError, lambda: a // zero)
256
257 def test_basic_attributes(self):
258 days, seconds, us = 1, 7, 31
259 td = timedelta(days, seconds, us)
260 self.assertEqual(td.days, days)
261 self.assertEqual(td.seconds, seconds)
262 self.assertEqual(td.microseconds, us)
263
264 def test_carries(self):
265 t1 = timedelta(days=100,
266 weeks=-7,
267 hours=-24*(100-49),
268 minutes=-3,
269 seconds=12,
270 microseconds=(3*60 - 12) * 1e6 + 1)
271 t2 = timedelta(microseconds=1)
272 self.assertEqual(t1, t2)
273
274 def test_hash_equality(self):
275 t1 = timedelta(days=100,
276 weeks=-7,
277 hours=-24*(100-49),
278 minutes=-3,
279 seconds=12,
280 microseconds=(3*60 - 12) * 1000000)
281 t2 = timedelta()
282 self.assertEqual(hash(t1), hash(t2))
283
284 t1 += timedelta(weeks=7)
285 t2 += timedelta(days=7*7)
286 self.assertEqual(t1, t2)
287 self.assertEqual(hash(t1), hash(t2))
288
289 d = {t1: 1}
290 d[t2] = 2
291 self.assertEqual(len(d), 1)
292 self.assertEqual(d[t1], 2)
293
294 def test_pickling(self):
Tim Peters2a799bf2002-12-16 20:18:38 +0000295 args = 12, 34, 56
296 orig = timedelta(*args)
Guido van Rossum177e41a2003-01-30 22:06:23 +0000297 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +0000298 green = pickler.dumps(orig, proto)
299 derived = unpickler.loads(green)
300 self.assertEqual(orig, derived)
Tim Peters2a799bf2002-12-16 20:18:38 +0000301
302 def test_compare(self):
303 t1 = timedelta(2, 3, 4)
304 t2 = timedelta(2, 3, 4)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000305 self.assertEqual(t1, t2)
Georg Brandlab91fde2009-08-13 08:51:18 +0000306 self.assertTrue(t1 <= t2)
307 self.assertTrue(t1 >= t2)
308 self.assertTrue(not t1 != t2)
309 self.assertTrue(not t1 < t2)
310 self.assertTrue(not t1 > t2)
Tim Peters2a799bf2002-12-16 20:18:38 +0000311
312 for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
313 t2 = timedelta(*args) # this is larger than t1
Georg Brandlab91fde2009-08-13 08:51:18 +0000314 self.assertTrue(t1 < t2)
315 self.assertTrue(t2 > t1)
316 self.assertTrue(t1 <= t2)
317 self.assertTrue(t2 >= t1)
318 self.assertTrue(t1 != t2)
319 self.assertTrue(t2 != t1)
320 self.assertTrue(not t1 == t2)
321 self.assertTrue(not t2 == t1)
322 self.assertTrue(not t1 > t2)
323 self.assertTrue(not t2 < t1)
324 self.assertTrue(not t1 >= t2)
325 self.assertTrue(not t2 <= t1)
Tim Peters2a799bf2002-12-16 20:18:38 +0000326
Tim Peters68124bb2003-02-08 03:46:31 +0000327 for badarg in OTHERSTUFF:
Tim Peters07534a62003-02-07 22:50:28 +0000328 self.assertEqual(t1 == badarg, False)
329 self.assertEqual(t1 != badarg, True)
330 self.assertEqual(badarg == t1, False)
331 self.assertEqual(badarg != t1, True)
332
Tim Peters2a799bf2002-12-16 20:18:38 +0000333 self.assertRaises(TypeError, lambda: t1 <= badarg)
334 self.assertRaises(TypeError, lambda: t1 < badarg)
335 self.assertRaises(TypeError, lambda: t1 > badarg)
336 self.assertRaises(TypeError, lambda: t1 >= badarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000337 self.assertRaises(TypeError, lambda: badarg <= t1)
338 self.assertRaises(TypeError, lambda: badarg < t1)
339 self.assertRaises(TypeError, lambda: badarg > t1)
340 self.assertRaises(TypeError, lambda: badarg >= t1)
341
342 def test_str(self):
343 td = timedelta
344 eq = self.assertEqual
345
346 eq(str(td(1)), "1 day, 0:00:00")
347 eq(str(td(-1)), "-1 day, 0:00:00")
348 eq(str(td(2)), "2 days, 0:00:00")
349 eq(str(td(-2)), "-2 days, 0:00:00")
350
351 eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59")
352 eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04")
353 eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)),
354 "-210 days, 23:12:34")
355
356 eq(str(td(milliseconds=1)), "0:00:00.001000")
357 eq(str(td(microseconds=3)), "0:00:00.000003")
358
359 eq(str(td(days=999999999, hours=23, minutes=59, seconds=59,
360 microseconds=999999)),
361 "999999999 days, 23:59:59.999999")
362
363 def test_roundtrip(self):
364 for td in (timedelta(days=999999999, hours=23, minutes=59,
365 seconds=59, microseconds=999999),
366 timedelta(days=-999999999),
367 timedelta(days=1, seconds=2, microseconds=3)):
368
369 # Verify td -> string -> td identity.
370 s = repr(td)
Georg Brandlab91fde2009-08-13 08:51:18 +0000371 self.assertTrue(s.startswith('datetime.'))
Tim Peters2a799bf2002-12-16 20:18:38 +0000372 s = s[9:]
373 td2 = eval(s)
374 self.assertEqual(td, td2)
375
376 # Verify identity via reconstructing from pieces.
377 td2 = timedelta(td.days, td.seconds, td.microseconds)
378 self.assertEqual(td, td2)
379
380 def test_resolution_info(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000381 self.assertTrue(isinstance(timedelta.min, timedelta))
382 self.assertTrue(isinstance(timedelta.max, timedelta))
383 self.assertTrue(isinstance(timedelta.resolution, timedelta))
384 self.assertTrue(timedelta.max > timedelta.min)
Tim Peters2a799bf2002-12-16 20:18:38 +0000385 self.assertEqual(timedelta.min, timedelta(-999999999))
386 self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
387 self.assertEqual(timedelta.resolution, timedelta(0, 0, 1))
388
389 def test_overflow(self):
390 tiny = timedelta.resolution
391
392 td = timedelta.min + tiny
393 td -= tiny # no problem
394 self.assertRaises(OverflowError, td.__sub__, tiny)
395 self.assertRaises(OverflowError, td.__add__, -tiny)
396
397 td = timedelta.max - tiny
398 td += tiny # no problem
399 self.assertRaises(OverflowError, td.__add__, tiny)
400 self.assertRaises(OverflowError, td.__sub__, -tiny)
401
402 self.assertRaises(OverflowError, lambda: -timedelta.max)
403
404 def test_microsecond_rounding(self):
405 td = timedelta
406 eq = self.assertEqual
407
408 # Single-field rounding.
409 eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0
410 eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0
411 eq(td(milliseconds=0.6/1000), td(microseconds=1))
412 eq(td(milliseconds=-0.6/1000), td(microseconds=-1))
413
414 # Rounding due to contributions from more than one field.
415 us_per_hour = 3600e6
416 us_per_day = us_per_hour * 24
417 eq(td(days=.4/us_per_day), td(0))
418 eq(td(hours=.2/us_per_hour), td(0))
419 eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1))
420
421 eq(td(days=-.4/us_per_day), td(0))
422 eq(td(hours=-.2/us_per_hour), td(0))
423 eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1))
424
425 def test_massive_normalization(self):
426 td = timedelta(microseconds=-1)
427 self.assertEqual((td.days, td.seconds, td.microseconds),
428 (-1, 24*3600-1, 999999))
429
430 def test_bool(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000431 self.assertTrue(timedelta(1))
432 self.assertTrue(timedelta(0, 1))
433 self.assertTrue(timedelta(0, 0, 1))
434 self.assertTrue(timedelta(microseconds=1))
435 self.assertTrue(not timedelta(0))
Tim Peters2a799bf2002-12-16 20:18:38 +0000436
Tim Petersb0c854d2003-05-17 15:57:00 +0000437 def test_subclass_timedelta(self):
438
439 class T(timedelta):
Guido van Rossum5a8a0372005-01-16 00:25:31 +0000440 @staticmethod
Tim Petersb0c854d2003-05-17 15:57:00 +0000441 def from_td(td):
442 return T(td.days, td.seconds, td.microseconds)
Tim Petersb0c854d2003-05-17 15:57:00 +0000443
444 def as_hours(self):
445 sum = (self.days * 24 +
446 self.seconds / 3600.0 +
447 self.microseconds / 3600e6)
448 return round(sum)
449
450 t1 = T(days=1)
Georg Brandlab91fde2009-08-13 08:51:18 +0000451 self.assertTrue(type(t1) is T)
Tim Petersb0c854d2003-05-17 15:57:00 +0000452 self.assertEqual(t1.as_hours(), 24)
453
454 t2 = T(days=-1, seconds=-3600)
Georg Brandlab91fde2009-08-13 08:51:18 +0000455 self.assertTrue(type(t2) is T)
Tim Petersb0c854d2003-05-17 15:57:00 +0000456 self.assertEqual(t2.as_hours(), -25)
457
458 t3 = t1 + t2
Georg Brandlab91fde2009-08-13 08:51:18 +0000459 self.assertTrue(type(t3) is timedelta)
Tim Petersb0c854d2003-05-17 15:57:00 +0000460 t4 = T.from_td(t3)
Georg Brandlab91fde2009-08-13 08:51:18 +0000461 self.assertTrue(type(t4) is T)
Tim Petersb0c854d2003-05-17 15:57:00 +0000462 self.assertEqual(t3.days, t4.days)
463 self.assertEqual(t3.seconds, t4.seconds)
464 self.assertEqual(t3.microseconds, t4.microseconds)
465 self.assertEqual(str(t3), str(t4))
466 self.assertEqual(t4.as_hours(), -1)
467
Tim Peters2a799bf2002-12-16 20:18:38 +0000468#############################################################################
469# date tests
470
471class TestDateOnly(unittest.TestCase):
472 # Tests here won't pass if also run on datetime objects, so don't
473 # subclass this to test datetimes too.
474
475 def test_delta_non_days_ignored(self):
476 dt = date(2000, 1, 2)
477 delta = timedelta(days=1, hours=2, minutes=3, seconds=4,
478 microseconds=5)
479 days = timedelta(delta.days)
480 self.assertEqual(days, timedelta(1))
481
482 dt2 = dt + delta
483 self.assertEqual(dt2, dt + days)
484
485 dt2 = delta + dt
486 self.assertEqual(dt2, dt + days)
487
488 dt2 = dt - delta
489 self.assertEqual(dt2, dt - days)
490
491 delta = -delta
492 days = timedelta(delta.days)
493 self.assertEqual(days, timedelta(-2))
494
495 dt2 = dt + delta
496 self.assertEqual(dt2, dt + days)
497
498 dt2 = delta + dt
499 self.assertEqual(dt2, dt + days)
500
501 dt2 = dt - delta
502 self.assertEqual(dt2, dt - days)
503
Tim Peters604c0132004-06-07 23:04:33 +0000504class SubclassDate(date):
505 sub_var = 1
506
Guido van Rossumd8faa362007-04-27 19:54:29 +0000507class TestDate(HarmlessMixedComparison, unittest.TestCase):
Tim Peters2a799bf2002-12-16 20:18:38 +0000508 # Tests here should pass for both dates and datetimes, except for a
509 # few tests that TestDateTime overrides.
510
511 theclass = date
512
513 def test_basic_attributes(self):
514 dt = self.theclass(2002, 3, 1)
515 self.assertEqual(dt.year, 2002)
516 self.assertEqual(dt.month, 3)
517 self.assertEqual(dt.day, 1)
518
519 def test_roundtrip(self):
520 for dt in (self.theclass(1, 2, 3),
521 self.theclass.today()):
522 # Verify dt -> string -> date identity.
523 s = repr(dt)
Georg Brandlab91fde2009-08-13 08:51:18 +0000524 self.assertTrue(s.startswith('datetime.'))
Tim Peters2a799bf2002-12-16 20:18:38 +0000525 s = s[9:]
526 dt2 = eval(s)
527 self.assertEqual(dt, dt2)
528
529 # Verify identity via reconstructing from pieces.
530 dt2 = self.theclass(dt.year, dt.month, dt.day)
531 self.assertEqual(dt, dt2)
532
533 def test_ordinal_conversions(self):
534 # Check some fixed values.
535 for y, m, d, n in [(1, 1, 1, 1), # calendar origin
536 (1, 12, 31, 365),
537 (2, 1, 1, 366),
538 # first example from "Calendrical Calculations"
539 (1945, 11, 12, 710347)]:
540 d = self.theclass(y, m, d)
541 self.assertEqual(n, d.toordinal())
542 fromord = self.theclass.fromordinal(n)
543 self.assertEqual(d, fromord)
544 if hasattr(fromord, "hour"):
Tim Petersf2715e02003-02-19 02:35:07 +0000545 # if we're checking something fancier than a date, verify
546 # the extra fields have been zeroed out
Tim Peters2a799bf2002-12-16 20:18:38 +0000547 self.assertEqual(fromord.hour, 0)
548 self.assertEqual(fromord.minute, 0)
549 self.assertEqual(fromord.second, 0)
550 self.assertEqual(fromord.microsecond, 0)
551
Tim Peters0bf60bd2003-01-08 20:40:01 +0000552 # Check first and last days of year spottily across the whole
553 # range of years supported.
Guido van Rossum805365e2007-05-07 22:24:25 +0000554 for year in range(MINYEAR, MAXYEAR+1, 7):
Tim Peters2a799bf2002-12-16 20:18:38 +0000555 # Verify (year, 1, 1) -> ordinal -> y, m, d is identity.
556 d = self.theclass(year, 1, 1)
557 n = d.toordinal()
558 d2 = self.theclass.fromordinal(n)
559 self.assertEqual(d, d2)
Tim Peters0bf60bd2003-01-08 20:40:01 +0000560 # Verify that moving back a day gets to the end of year-1.
561 if year > 1:
562 d = self.theclass.fromordinal(n-1)
563 d2 = self.theclass(year-1, 12, 31)
564 self.assertEqual(d, d2)
565 self.assertEqual(d2.toordinal(), n-1)
Tim Peters2a799bf2002-12-16 20:18:38 +0000566
567 # Test every day in a leap-year and a non-leap year.
568 dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
569 for year, isleap in (2000, True), (2002, False):
570 n = self.theclass(year, 1, 1).toordinal()
571 for month, maxday in zip(range(1, 13), dim):
572 if month == 2 and isleap:
573 maxday += 1
574 for day in range(1, maxday+1):
575 d = self.theclass(year, month, day)
576 self.assertEqual(d.toordinal(), n)
577 self.assertEqual(d, self.theclass.fromordinal(n))
578 n += 1
579
580 def test_extreme_ordinals(self):
581 a = self.theclass.min
582 a = self.theclass(a.year, a.month, a.day) # get rid of time parts
583 aord = a.toordinal()
584 b = a.fromordinal(aord)
585 self.assertEqual(a, b)
586
587 self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1))
588
589 b = a + timedelta(days=1)
590 self.assertEqual(b.toordinal(), aord + 1)
591 self.assertEqual(b, self.theclass.fromordinal(aord + 1))
592
593 a = self.theclass.max
594 a = self.theclass(a.year, a.month, a.day) # get rid of time parts
595 aord = a.toordinal()
596 b = a.fromordinal(aord)
597 self.assertEqual(a, b)
598
599 self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1))
600
601 b = a - timedelta(days=1)
602 self.assertEqual(b.toordinal(), aord - 1)
603 self.assertEqual(b, self.theclass.fromordinal(aord - 1))
604
605 def test_bad_constructor_arguments(self):
606 # bad years
607 self.theclass(MINYEAR, 1, 1) # no exception
608 self.theclass(MAXYEAR, 1, 1) # no exception
609 self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
610 self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
611 # bad months
612 self.theclass(2000, 1, 1) # no exception
613 self.theclass(2000, 12, 1) # no exception
614 self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
615 self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
616 # bad days
617 self.theclass(2000, 2, 29) # no exception
618 self.theclass(2004, 2, 29) # no exception
619 self.theclass(2400, 2, 29) # no exception
620 self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
621 self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
622 self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
623 self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
624 self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
625 self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
626
627 def test_hash_equality(self):
628 d = self.theclass(2000, 12, 31)
629 # same thing
630 e = self.theclass(2000, 12, 31)
631 self.assertEqual(d, e)
632 self.assertEqual(hash(d), hash(e))
633
634 dic = {d: 1}
635 dic[e] = 2
636 self.assertEqual(len(dic), 1)
637 self.assertEqual(dic[d], 2)
638 self.assertEqual(dic[e], 2)
639
640 d = self.theclass(2001, 1, 1)
641 # same thing
642 e = self.theclass(2001, 1, 1)
643 self.assertEqual(d, e)
644 self.assertEqual(hash(d), hash(e))
645
646 dic = {d: 1}
647 dic[e] = 2
648 self.assertEqual(len(dic), 1)
649 self.assertEqual(dic[d], 2)
650 self.assertEqual(dic[e], 2)
651
652 def test_computations(self):
653 a = self.theclass(2002, 1, 31)
654 b = self.theclass(1956, 1, 31)
655
656 diff = a-b
657 self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
658 self.assertEqual(diff.seconds, 0)
659 self.assertEqual(diff.microseconds, 0)
660
661 day = timedelta(1)
662 week = timedelta(7)
663 a = self.theclass(2002, 3, 2)
664 self.assertEqual(a + day, self.theclass(2002, 3, 3))
665 self.assertEqual(day + a, self.theclass(2002, 3, 3))
666 self.assertEqual(a - day, self.theclass(2002, 3, 1))
667 self.assertEqual(-day + a, self.theclass(2002, 3, 1))
668 self.assertEqual(a + week, self.theclass(2002, 3, 9))
669 self.assertEqual(a - week, self.theclass(2002, 2, 23))
670 self.assertEqual(a + 52*week, self.theclass(2003, 3, 1))
671 self.assertEqual(a - 52*week, self.theclass(2001, 3, 3))
672 self.assertEqual((a + week) - a, week)
673 self.assertEqual((a + day) - a, day)
674 self.assertEqual((a - week) - a, -week)
675 self.assertEqual((a - day) - a, -day)
676 self.assertEqual(a - (a + week), -week)
677 self.assertEqual(a - (a + day), -day)
678 self.assertEqual(a - (a - week), week)
679 self.assertEqual(a - (a - day), day)
680
681 # Add/sub ints, longs, floats should be illegal
Guido van Rossume2a383d2007-01-15 16:59:06 +0000682 for i in 1, 1, 1.0:
Tim Peters2a799bf2002-12-16 20:18:38 +0000683 self.assertRaises(TypeError, lambda: a+i)
684 self.assertRaises(TypeError, lambda: a-i)
685 self.assertRaises(TypeError, lambda: i+a)
686 self.assertRaises(TypeError, lambda: i-a)
687
688 # delta - date is senseless.
689 self.assertRaises(TypeError, lambda: day - a)
690 # mixing date and (delta or date) via * or // is senseless
691 self.assertRaises(TypeError, lambda: day * a)
692 self.assertRaises(TypeError, lambda: a * day)
693 self.assertRaises(TypeError, lambda: day // a)
694 self.assertRaises(TypeError, lambda: a // day)
695 self.assertRaises(TypeError, lambda: a * a)
696 self.assertRaises(TypeError, lambda: a // a)
697 # date + date is senseless
698 self.assertRaises(TypeError, lambda: a + a)
699
700 def test_overflow(self):
701 tiny = self.theclass.resolution
702
Alexander Belopolsky3efc2fd2010-05-27 22:03:53 +0000703 for delta in [tiny, timedelta(1), timedelta(2)]:
704 dt = self.theclass.min + delta
705 dt -= delta # no problem
706 self.assertRaises(OverflowError, dt.__sub__, delta)
707 self.assertRaises(OverflowError, dt.__add__, -delta)
Tim Peters2a799bf2002-12-16 20:18:38 +0000708
Alexander Belopolsky3efc2fd2010-05-27 22:03:53 +0000709 dt = self.theclass.max - delta
710 dt += delta # no problem
711 self.assertRaises(OverflowError, dt.__add__, delta)
712 self.assertRaises(OverflowError, dt.__sub__, -delta)
Tim Peters2a799bf2002-12-16 20:18:38 +0000713
714 def test_fromtimestamp(self):
715 import time
716
717 # Try an arbitrary fixed value.
718 year, month, day = 1999, 9, 19
719 ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
720 d = self.theclass.fromtimestamp(ts)
721 self.assertEqual(d.year, year)
722 self.assertEqual(d.month, month)
723 self.assertEqual(d.day, day)
724
Tim Peters1b6f7a92004-06-20 02:50:16 +0000725 def test_insane_fromtimestamp(self):
726 # It's possible that some platform maps time_t to double,
727 # and that this test will fail there. This test should
728 # exempt such platforms (provided they return reasonable
729 # results!).
730 for insane in -1e200, 1e200:
731 self.assertRaises(ValueError, self.theclass.fromtimestamp,
732 insane)
733
Tim Peters2a799bf2002-12-16 20:18:38 +0000734 def test_today(self):
735 import time
736
737 # We claim that today() is like fromtimestamp(time.time()), so
738 # prove it.
739 for dummy in range(3):
740 today = self.theclass.today()
741 ts = time.time()
742 todayagain = self.theclass.fromtimestamp(ts)
743 if today == todayagain:
744 break
745 # There are several legit reasons that could fail:
746 # 1. It recently became midnight, between the today() and the
747 # time() calls.
748 # 2. The platform time() has such fine resolution that we'll
749 # never get the same value twice.
750 # 3. The platform time() has poor resolution, and we just
751 # happened to call today() right before a resolution quantum
752 # boundary.
753 # 4. The system clock got fiddled between calls.
754 # In any case, wait a little while and try again.
755 time.sleep(0.1)
756
757 # It worked or it didn't. If it didn't, assume it's reason #2, and
758 # let the test pass if they're within half a second of each other.
Georg Brandlab91fde2009-08-13 08:51:18 +0000759 self.assertTrue(today == todayagain or
Tim Peters2a799bf2002-12-16 20:18:38 +0000760 abs(todayagain - today) < timedelta(seconds=0.5))
761
762 def test_weekday(self):
763 for i in range(7):
764 # March 4, 2002 is a Monday
765 self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i)
766 self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1)
767 # January 2, 1956 is a Monday
768 self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i)
769 self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1)
770
771 def test_isocalendar(self):
772 # Check examples from
773 # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
774 for i in range(7):
775 d = self.theclass(2003, 12, 22+i)
776 self.assertEqual(d.isocalendar(), (2003, 52, i+1))
777 d = self.theclass(2003, 12, 29) + timedelta(i)
778 self.assertEqual(d.isocalendar(), (2004, 1, i+1))
779 d = self.theclass(2004, 1, 5+i)
780 self.assertEqual(d.isocalendar(), (2004, 2, i+1))
781 d = self.theclass(2009, 12, 21+i)
782 self.assertEqual(d.isocalendar(), (2009, 52, i+1))
783 d = self.theclass(2009, 12, 28) + timedelta(i)
784 self.assertEqual(d.isocalendar(), (2009, 53, i+1))
785 d = self.theclass(2010, 1, 4+i)
786 self.assertEqual(d.isocalendar(), (2010, 1, i+1))
787
788 def test_iso_long_years(self):
789 # Calculate long ISO years and compare to table from
790 # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
791 ISO_LONG_YEARS_TABLE = """
792 4 32 60 88
793 9 37 65 93
794 15 43 71 99
795 20 48 76
796 26 54 82
797
798 105 133 161 189
799 111 139 167 195
800 116 144 172
801 122 150 178
802 128 156 184
803
804 201 229 257 285
805 207 235 263 291
806 212 240 268 296
807 218 246 274
808 224 252 280
809
810 303 331 359 387
811 308 336 364 392
812 314 342 370 398
813 320 348 376
814 325 353 381
815 """
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000816 iso_long_years = sorted(map(int, ISO_LONG_YEARS_TABLE.split()))
Tim Peters2a799bf2002-12-16 20:18:38 +0000817 L = []
818 for i in range(400):
819 d = self.theclass(2000+i, 12, 31)
820 d1 = self.theclass(1600+i, 12, 31)
821 self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:])
822 if d.isocalendar()[1] == 53:
823 L.append(i)
824 self.assertEqual(L, iso_long_years)
825
826 def test_isoformat(self):
827 t = self.theclass(2, 3, 2)
828 self.assertEqual(t.isoformat(), "0002-03-02")
829
830 def test_ctime(self):
831 t = self.theclass(2002, 3, 2)
832 self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002")
833
834 def test_strftime(self):
835 t = self.theclass(2005, 3, 2)
836 self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05")
Raymond Hettingerf69d9f62003-06-27 08:14:17 +0000837 self.assertEqual(t.strftime(""), "") # SF bug #761337
Thomas Wouters89f507f2006-12-13 04:49:30 +0000838 self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784
Tim Peters2a799bf2002-12-16 20:18:38 +0000839
840 self.assertRaises(TypeError, t.strftime) # needs an arg
841 self.assertRaises(TypeError, t.strftime, "one", "two") # too many args
842 self.assertRaises(TypeError, t.strftime, 42) # arg wrong type
843
Georg Brandlf78e02b2008-06-10 17:40:04 +0000844 # test that unicode input is allowed (issue 2782)
845 self.assertEqual(t.strftime("%m"), "03")
846
Tim Peters2a799bf2002-12-16 20:18:38 +0000847 # A naive object replaces %z and %Z w/ empty strings.
848 self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
849
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000850 #make sure that invalid format specifiers are handled correctly
851 #self.assertRaises(ValueError, t.strftime, "%e")
852 #self.assertRaises(ValueError, t.strftime, "%")
853 #self.assertRaises(ValueError, t.strftime, "%#")
854
855 #oh well, some systems just ignore those invalid ones.
856 #at least, excercise them to make sure that no crashes
857 #are generated
858 for f in ["%e", "%", "%#"]:
859 try:
860 t.strftime(f)
861 except ValueError:
862 pass
863
864 #check that this standard extension works
865 t.strftime("%f")
866
Georg Brandlf78e02b2008-06-10 17:40:04 +0000867
Eric Smith1ba31142007-09-11 18:06:02 +0000868 def test_format(self):
869 dt = self.theclass(2007, 9, 10)
Eric Smith8fd3eba2008-02-17 19:48:00 +0000870 self.assertEqual(dt.__format__(''), str(dt))
Eric Smith1ba31142007-09-11 18:06:02 +0000871
872 # check that a derived class's __str__() gets called
873 class A(self.theclass):
874 def __str__(self):
875 return 'A'
876 a = A(2007, 9, 10)
Eric Smith8fd3eba2008-02-17 19:48:00 +0000877 self.assertEqual(a.__format__(''), 'A')
Eric Smith1ba31142007-09-11 18:06:02 +0000878
879 # check that a derived class's strftime gets called
880 class B(self.theclass):
881 def strftime(self, format_spec):
882 return 'B'
883 b = B(2007, 9, 10)
Eric Smith8fd3eba2008-02-17 19:48:00 +0000884 self.assertEqual(b.__format__(''), str(dt))
Eric Smith1ba31142007-09-11 18:06:02 +0000885
886 for fmt in ["m:%m d:%d y:%y",
887 "m:%m d:%d y:%y H:%H M:%M S:%S",
888 "%z %Z",
889 ]:
Eric Smith8fd3eba2008-02-17 19:48:00 +0000890 self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
891 self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
892 self.assertEqual(b.__format__(fmt), 'B')
Eric Smith1ba31142007-09-11 18:06:02 +0000893
Tim Peters2a799bf2002-12-16 20:18:38 +0000894 def test_resolution_info(self):
Georg Brandlab91fde2009-08-13 08:51:18 +0000895 self.assertTrue(isinstance(self.theclass.min, self.theclass))
896 self.assertTrue(isinstance(self.theclass.max, self.theclass))
897 self.assertTrue(isinstance(self.theclass.resolution, timedelta))
898 self.assertTrue(self.theclass.max > self.theclass.min)
Tim Peters2a799bf2002-12-16 20:18:38 +0000899
900 def test_extreme_timedelta(self):
901 big = self.theclass.max - self.theclass.min
902 # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
903 n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
904 # n == 315537897599999999 ~= 2**58.13
905 justasbig = timedelta(0, 0, n)
906 self.assertEqual(big, justasbig)
907 self.assertEqual(self.theclass.min + big, self.theclass.max)
908 self.assertEqual(self.theclass.max - big, self.theclass.min)
909
910 def test_timetuple(self):
911 for i in range(7):
912 # January 2, 1956 is a Monday (0)
913 d = self.theclass(1956, 1, 2+i)
914 t = d.timetuple()
915 self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1))
916 # February 1, 1956 is a Wednesday (2)
917 d = self.theclass(1956, 2, 1+i)
918 t = d.timetuple()
919 self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1))
920 # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day
921 # of the year.
922 d = self.theclass(1956, 3, 1+i)
923 t = d.timetuple()
924 self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1))
925 self.assertEqual(t.tm_year, 1956)
926 self.assertEqual(t.tm_mon, 3)
927 self.assertEqual(t.tm_mday, 1+i)
928 self.assertEqual(t.tm_hour, 0)
929 self.assertEqual(t.tm_min, 0)
930 self.assertEqual(t.tm_sec, 0)
931 self.assertEqual(t.tm_wday, (3+i)%7)
932 self.assertEqual(t.tm_yday, 61+i)
933 self.assertEqual(t.tm_isdst, -1)
934
935 def test_pickling(self):
Tim Peters2a799bf2002-12-16 20:18:38 +0000936 args = 6, 7, 23
937 orig = self.theclass(*args)
Guido van Rossum177e41a2003-01-30 22:06:23 +0000938 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +0000939 green = pickler.dumps(orig, proto)
940 derived = unpickler.loads(green)
941 self.assertEqual(orig, derived)
Tim Peters2a799bf2002-12-16 20:18:38 +0000942
943 def test_compare(self):
944 t1 = self.theclass(2, 3, 4)
945 t2 = self.theclass(2, 3, 4)
Guido van Rossume61fd5b2007-07-11 12:20:59 +0000946 self.assertEqual(t1, t2)
Georg Brandlab91fde2009-08-13 08:51:18 +0000947 self.assertTrue(t1 <= t2)
948 self.assertTrue(t1 >= t2)
949 self.assertTrue(not t1 != t2)
950 self.assertTrue(not t1 < t2)
951 self.assertTrue(not t1 > t2)
Tim Peters2a799bf2002-12-16 20:18:38 +0000952
953 for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
954 t2 = self.theclass(*args) # this is larger than t1
Georg Brandlab91fde2009-08-13 08:51:18 +0000955 self.assertTrue(t1 < t2)
956 self.assertTrue(t2 > t1)
957 self.assertTrue(t1 <= t2)
958 self.assertTrue(t2 >= t1)
959 self.assertTrue(t1 != t2)
960 self.assertTrue(t2 != t1)
961 self.assertTrue(not t1 == t2)
962 self.assertTrue(not t2 == t1)
963 self.assertTrue(not t1 > t2)
964 self.assertTrue(not t2 < t1)
965 self.assertTrue(not t1 >= t2)
966 self.assertTrue(not t2 <= t1)
Tim Peters2a799bf2002-12-16 20:18:38 +0000967
Tim Peters68124bb2003-02-08 03:46:31 +0000968 for badarg in OTHERSTUFF:
Tim Peters07534a62003-02-07 22:50:28 +0000969 self.assertEqual(t1 == badarg, False)
970 self.assertEqual(t1 != badarg, True)
971 self.assertEqual(badarg == t1, False)
972 self.assertEqual(badarg != t1, True)
973
Tim Peters2a799bf2002-12-16 20:18:38 +0000974 self.assertRaises(TypeError, lambda: t1 < badarg)
975 self.assertRaises(TypeError, lambda: t1 > badarg)
976 self.assertRaises(TypeError, lambda: t1 >= badarg)
Tim Peters2a799bf2002-12-16 20:18:38 +0000977 self.assertRaises(TypeError, lambda: badarg <= t1)
978 self.assertRaises(TypeError, lambda: badarg < t1)
979 self.assertRaises(TypeError, lambda: badarg > t1)
980 self.assertRaises(TypeError, lambda: badarg >= t1)
981
Tim Peters8d81a012003-01-24 22:36:34 +0000982 def test_mixed_compare(self):
983 our = self.theclass(2000, 4, 5)
Guido van Rossum19960592006-08-24 17:29:38 +0000984
985 # Our class can be compared for equality to other classes
986 self.assertEqual(our == 1, False)
987 self.assertEqual(1 == our, False)
988 self.assertEqual(our != 1, True)
989 self.assertEqual(1 != our, True)
990
991 # But the ordering is undefined
992 self.assertRaises(TypeError, lambda: our < 1)
993 self.assertRaises(TypeError, lambda: 1 < our)
Tim Peters8d81a012003-01-24 22:36:34 +0000994
Guido van Rossum19960592006-08-24 17:29:38 +0000995 # Repeat those tests with a different class
Tim Peters8d81a012003-01-24 22:36:34 +0000996
Guido van Rossum19960592006-08-24 17:29:38 +0000997 class SomeClass:
998 pass
999
1000 their = SomeClass()
1001 self.assertEqual(our == their, False)
1002 self.assertEqual(their == our, False)
1003 self.assertEqual(our != their, True)
1004 self.assertEqual(their != our, True)
1005 self.assertRaises(TypeError, lambda: our < their)
1006 self.assertRaises(TypeError, lambda: their < our)
Tim Peters8d81a012003-01-24 22:36:34 +00001007
Guido van Rossum19960592006-08-24 17:29:38 +00001008 # However, if the other class explicitly defines ordering
1009 # relative to our class, it is allowed to do so
Tim Peters8d81a012003-01-24 22:36:34 +00001010
Guido van Rossum19960592006-08-24 17:29:38 +00001011 class LargerThanAnything:
1012 def __lt__(self, other):
1013 return False
1014 def __le__(self, other):
1015 return isinstance(other, LargerThanAnything)
1016 def __eq__(self, other):
1017 return isinstance(other, LargerThanAnything)
1018 def __ne__(self, other):
1019 return not isinstance(other, LargerThanAnything)
1020 def __gt__(self, other):
1021 return not isinstance(other, LargerThanAnything)
1022 def __ge__(self, other):
1023 return True
1024
1025 their = LargerThanAnything()
1026 self.assertEqual(our == their, False)
1027 self.assertEqual(their == our, False)
1028 self.assertEqual(our != their, True)
1029 self.assertEqual(their != our, True)
1030 self.assertEqual(our < their, True)
1031 self.assertEqual(their < our, False)
Tim Peters8d81a012003-01-24 22:36:34 +00001032
Tim Peters2a799bf2002-12-16 20:18:38 +00001033 def test_bool(self):
1034 # All dates are considered true.
Georg Brandlab91fde2009-08-13 08:51:18 +00001035 self.assertTrue(self.theclass.min)
1036 self.assertTrue(self.theclass.max)
Tim Peters2a799bf2002-12-16 20:18:38 +00001037
Guido van Rossum04110fb2007-08-24 16:32:05 +00001038 def test_strftime_out_of_range(self):
Tim Petersd6844152002-12-22 20:58:42 +00001039 # For nasty technical reasons, we can't handle years before 1900.
1040 cls = self.theclass
1041 self.assertEqual(cls(1900, 1, 1).strftime("%Y"), "1900")
1042 for y in 1, 49, 51, 99, 100, 1000, 1899:
1043 self.assertRaises(ValueError, cls(y, 1, 1).strftime, "%Y")
Tim Peters12bf3392002-12-24 05:41:27 +00001044
1045 def test_replace(self):
1046 cls = self.theclass
1047 args = [1, 2, 3]
1048 base = cls(*args)
1049 self.assertEqual(base, base.replace())
1050
1051 i = 0
1052 for name, newval in (("year", 2),
1053 ("month", 3),
1054 ("day", 4)):
1055 newargs = args[:]
1056 newargs[i] = newval
1057 expected = cls(*newargs)
1058 got = base.replace(**{name: newval})
1059 self.assertEqual(expected, got)
1060 i += 1
1061
1062 # Out of bounds.
1063 base = cls(2000, 2, 29)
1064 self.assertRaises(ValueError, base.replace, year=2001)
1065
Tim Petersa98924a2003-05-17 05:55:19 +00001066 def test_subclass_date(self):
1067
1068 class C(self.theclass):
1069 theAnswer = 42
1070
1071 def __new__(cls, *args, **kws):
1072 temp = kws.copy()
1073 extra = temp.pop('extra')
1074 result = self.theclass.__new__(cls, *args, **temp)
1075 result.extra = extra
1076 return result
1077
1078 def newmeth(self, start):
1079 return start + self.year + self.month
1080
1081 args = 2003, 4, 14
1082
1083 dt1 = self.theclass(*args)
1084 dt2 = C(*args, **{'extra': 7})
1085
1086 self.assertEqual(dt2.__class__, C)
1087 self.assertEqual(dt2.theAnswer, 42)
1088 self.assertEqual(dt2.extra, 7)
1089 self.assertEqual(dt1.toordinal(), dt2.toordinal())
1090 self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month - 7)
1091
Tim Peters604c0132004-06-07 23:04:33 +00001092 def test_pickling_subclass_date(self):
1093
1094 args = 6, 7, 23
1095 orig = SubclassDate(*args)
1096 for pickler, unpickler, proto in pickle_choices:
1097 green = pickler.dumps(orig, proto)
1098 derived = unpickler.loads(green)
1099 self.assertEqual(orig, derived)
1100
Tim Peters3f606292004-03-21 23:38:41 +00001101 def test_backdoor_resistance(self):
Guido van Rossum254348e2007-11-21 19:29:53 +00001102 # For fast unpickling, the constructor accepts a pickle byte string.
Tim Peters3f606292004-03-21 23:38:41 +00001103 # This is a low-overhead backdoor. A user can (by intent or
1104 # mistake) pass a string directly, which (if it's the right length)
1105 # will get treated like a pickle, and bypass the normal sanity
1106 # checks in the constructor. This can create insane objects.
1107 # The constructor doesn't want to burn the time to validate all
1108 # fields, but does check the month field. This stops, e.g.,
1109 # datetime.datetime('1995-03-25') from yielding an insane object.
Guido van Rossum254348e2007-11-21 19:29:53 +00001110 base = b'1995-03-25'
Tim Peters3f606292004-03-21 23:38:41 +00001111 if not issubclass(self.theclass, datetime):
1112 base = base[:4]
Guido van Rossum254348e2007-11-21 19:29:53 +00001113 for month_byte in b'9', b'\0', b'\r', b'\xff':
Tim Peters3f606292004-03-21 23:38:41 +00001114 self.assertRaises(TypeError, self.theclass,
1115 base[:2] + month_byte + base[3:])
1116 for ord_byte in range(1, 13):
1117 # This shouldn't blow up because of the month byte alone. If
1118 # the implementation changes to do more-careful checking, it may
1119 # blow up because other fields are insane.
Guido van Rossum254348e2007-11-21 19:29:53 +00001120 self.theclass(base[:2] + bytes([ord_byte]) + base[3:])
Tim Peterseb1a4962003-05-17 02:25:20 +00001121
Tim Peters2a799bf2002-12-16 20:18:38 +00001122#############################################################################
1123# datetime tests
1124
Tim Peters604c0132004-06-07 23:04:33 +00001125class SubclassDatetime(datetime):
1126 sub_var = 1
1127
Tim Peters2a799bf2002-12-16 20:18:38 +00001128class TestDateTime(TestDate):
1129
1130 theclass = datetime
1131
1132 def test_basic_attributes(self):
1133 dt = self.theclass(2002, 3, 1, 12, 0)
1134 self.assertEqual(dt.year, 2002)
1135 self.assertEqual(dt.month, 3)
1136 self.assertEqual(dt.day, 1)
1137 self.assertEqual(dt.hour, 12)
1138 self.assertEqual(dt.minute, 0)
1139 self.assertEqual(dt.second, 0)
1140 self.assertEqual(dt.microsecond, 0)
1141
1142 def test_basic_attributes_nonzero(self):
1143 # Make sure all attributes are non-zero so bugs in
1144 # bit-shifting access show up.
1145 dt = self.theclass(2002, 3, 1, 12, 59, 59, 8000)
1146 self.assertEqual(dt.year, 2002)
1147 self.assertEqual(dt.month, 3)
1148 self.assertEqual(dt.day, 1)
1149 self.assertEqual(dt.hour, 12)
1150 self.assertEqual(dt.minute, 59)
1151 self.assertEqual(dt.second, 59)
1152 self.assertEqual(dt.microsecond, 8000)
1153
1154 def test_roundtrip(self):
1155 for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
1156 self.theclass.now()):
1157 # Verify dt -> string -> datetime identity.
1158 s = repr(dt)
Georg Brandlab91fde2009-08-13 08:51:18 +00001159 self.assertTrue(s.startswith('datetime.'))
Tim Peters2a799bf2002-12-16 20:18:38 +00001160 s = s[9:]
1161 dt2 = eval(s)
1162 self.assertEqual(dt, dt2)
1163
1164 # Verify identity via reconstructing from pieces.
1165 dt2 = self.theclass(dt.year, dt.month, dt.day,
1166 dt.hour, dt.minute, dt.second,
1167 dt.microsecond)
1168 self.assertEqual(dt, dt2)
1169
1170 def test_isoformat(self):
1171 t = self.theclass(2, 3, 2, 4, 5, 1, 123)
1172 self.assertEqual(t.isoformat(), "0002-03-02T04:05:01.000123")
1173 self.assertEqual(t.isoformat('T'), "0002-03-02T04:05:01.000123")
1174 self.assertEqual(t.isoformat(' '), "0002-03-02 04:05:01.000123")
1175 # str is ISO format with the separator forced to a blank.
1176 self.assertEqual(str(t), "0002-03-02 04:05:01.000123")
1177
1178 t = self.theclass(2, 3, 2)
1179 self.assertEqual(t.isoformat(), "0002-03-02T00:00:00")
1180 self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00")
1181 self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00")
1182 # str is ISO format with the separator forced to a blank.
1183 self.assertEqual(str(t), "0002-03-02 00:00:00")
1184
Eric Smith1ba31142007-09-11 18:06:02 +00001185 def test_format(self):
1186 dt = self.theclass(2007, 9, 10, 4, 5, 1, 123)
Eric Smith8fd3eba2008-02-17 19:48:00 +00001187 self.assertEqual(dt.__format__(''), str(dt))
Eric Smith1ba31142007-09-11 18:06:02 +00001188
1189 # check that a derived class's __str__() gets called
1190 class A(self.theclass):
1191 def __str__(self):
1192 return 'A'
1193 a = A(2007, 9, 10, 4, 5, 1, 123)
Eric Smith8fd3eba2008-02-17 19:48:00 +00001194 self.assertEqual(a.__format__(''), 'A')
Eric Smith1ba31142007-09-11 18:06:02 +00001195
1196 # check that a derived class's strftime gets called
1197 class B(self.theclass):
1198 def strftime(self, format_spec):
1199 return 'B'
1200 b = B(2007, 9, 10, 4, 5, 1, 123)
Eric Smith8fd3eba2008-02-17 19:48:00 +00001201 self.assertEqual(b.__format__(''), str(dt))
Eric Smith1ba31142007-09-11 18:06:02 +00001202
1203 for fmt in ["m:%m d:%d y:%y",
1204 "m:%m d:%d y:%y H:%H M:%M S:%S",
1205 "%z %Z",
1206 ]:
Eric Smith8fd3eba2008-02-17 19:48:00 +00001207 self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
1208 self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
1209 self.assertEqual(b.__format__(fmt), 'B')
Eric Smith1ba31142007-09-11 18:06:02 +00001210
Tim Peters2a799bf2002-12-16 20:18:38 +00001211 def test_more_ctime(self):
1212 # Test fields that TestDate doesn't touch.
1213 import time
1214
1215 t = self.theclass(2002, 3, 2, 18, 3, 5, 123)
1216 self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002")
1217 # Oops! The next line fails on Win2K under MSVC 6, so it's commented
1218 # out. The difference is that t.ctime() produces " 2" for the day,
1219 # but platform ctime() produces "02" for the day. According to
1220 # C99, t.ctime() is correct here.
1221 # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
1222
1223 # So test a case where that difference doesn't matter.
1224 t = self.theclass(2002, 3, 22, 18, 3, 5, 123)
1225 self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
1226
1227 def test_tz_independent_comparing(self):
1228 dt1 = self.theclass(2002, 3, 1, 9, 0, 0)
1229 dt2 = self.theclass(2002, 3, 1, 10, 0, 0)
1230 dt3 = self.theclass(2002, 3, 1, 9, 0, 0)
1231 self.assertEqual(dt1, dt3)
Georg Brandlab91fde2009-08-13 08:51:18 +00001232 self.assertTrue(dt2 > dt3)
Tim Peters2a799bf2002-12-16 20:18:38 +00001233
1234 # Make sure comparison doesn't forget microseconds, and isn't done
1235 # via comparing a float timestamp (an IEEE double doesn't have enough
1236 # precision to span microsecond resolution across years 1 thru 9999,
1237 # so comparing via timestamp necessarily calls some distinct values
1238 # equal).
1239 dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998)
1240 us = timedelta(microseconds=1)
1241 dt2 = dt1 + us
1242 self.assertEqual(dt2 - dt1, us)
Georg Brandlab91fde2009-08-13 08:51:18 +00001243 self.assertTrue(dt1 < dt2)
Tim Peters2a799bf2002-12-16 20:18:38 +00001244
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001245 def test_strftime_with_bad_tzname_replace(self):
1246 # verify ok if tzinfo.tzname().replace() returns a non-string
1247 class MyTzInfo(FixedOffset):
1248 def tzname(self, dt):
1249 class MyStr(str):
1250 def replace(self, *args):
1251 return None
1252 return MyStr('name')
1253 t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name'))
1254 self.assertRaises(TypeError, t.strftime, '%Z')
1255
Tim Peters2a799bf2002-12-16 20:18:38 +00001256 def test_bad_constructor_arguments(self):
1257 # bad years
1258 self.theclass(MINYEAR, 1, 1) # no exception
1259 self.theclass(MAXYEAR, 1, 1) # no exception
1260 self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
1261 self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
1262 # bad months
1263 self.theclass(2000, 1, 1) # no exception
1264 self.theclass(2000, 12, 1) # no exception
1265 self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
1266 self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
1267 # bad days
1268 self.theclass(2000, 2, 29) # no exception
1269 self.theclass(2004, 2, 29) # no exception
1270 self.theclass(2400, 2, 29) # no exception
1271 self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
1272 self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
1273 self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
1274 self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
1275 self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
1276 self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
1277 # bad hours
1278 self.theclass(2000, 1, 31, 0) # no exception
1279 self.theclass(2000, 1, 31, 23) # no exception
1280 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1)
1281 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24)
1282 # bad minutes
1283 self.theclass(2000, 1, 31, 23, 0) # no exception
1284 self.theclass(2000, 1, 31, 23, 59) # no exception
1285 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1)
1286 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60)
1287 # bad seconds
1288 self.theclass(2000, 1, 31, 23, 59, 0) # no exception
1289 self.theclass(2000, 1, 31, 23, 59, 59) # no exception
1290 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1)
1291 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60)
1292 # bad microseconds
1293 self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception
1294 self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception
1295 self.assertRaises(ValueError, self.theclass,
1296 2000, 1, 31, 23, 59, 59, -1)
1297 self.assertRaises(ValueError, self.theclass,
1298 2000, 1, 31, 23, 59, 59,
1299 1000000)
1300
1301 def test_hash_equality(self):
1302 d = self.theclass(2000, 12, 31, 23, 30, 17)
1303 e = self.theclass(2000, 12, 31, 23, 30, 17)
1304 self.assertEqual(d, e)
1305 self.assertEqual(hash(d), hash(e))
1306
1307 dic = {d: 1}
1308 dic[e] = 2
1309 self.assertEqual(len(dic), 1)
1310 self.assertEqual(dic[d], 2)
1311 self.assertEqual(dic[e], 2)
1312
1313 d = self.theclass(2001, 1, 1, 0, 5, 17)
1314 e = self.theclass(2001, 1, 1, 0, 5, 17)
1315 self.assertEqual(d, e)
1316 self.assertEqual(hash(d), hash(e))
1317
1318 dic = {d: 1}
1319 dic[e] = 2
1320 self.assertEqual(len(dic), 1)
1321 self.assertEqual(dic[d], 2)
1322 self.assertEqual(dic[e], 2)
1323
1324 def test_computations(self):
1325 a = self.theclass(2002, 1, 31)
1326 b = self.theclass(1956, 1, 31)
1327 diff = a-b
1328 self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
1329 self.assertEqual(diff.seconds, 0)
1330 self.assertEqual(diff.microseconds, 0)
1331 a = self.theclass(2002, 3, 2, 17, 6)
1332 millisec = timedelta(0, 0, 1000)
1333 hour = timedelta(0, 3600)
1334 day = timedelta(1)
1335 week = timedelta(7)
1336 self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6))
1337 self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6))
1338 self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6))
1339 self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6))
1340 self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6))
1341 self.assertEqual(a - hour, a + -hour)
1342 self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6))
1343 self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6))
1344 self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6))
1345 self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6))
1346 self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6))
1347 self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6))
1348 self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6))
1349 self.assertEqual((a + week) - a, week)
1350 self.assertEqual((a + day) - a, day)
1351 self.assertEqual((a + hour) - a, hour)
1352 self.assertEqual((a + millisec) - a, millisec)
1353 self.assertEqual((a - week) - a, -week)
1354 self.assertEqual((a - day) - a, -day)
1355 self.assertEqual((a - hour) - a, -hour)
1356 self.assertEqual((a - millisec) - a, -millisec)
1357 self.assertEqual(a - (a + week), -week)
1358 self.assertEqual(a - (a + day), -day)
1359 self.assertEqual(a - (a + hour), -hour)
1360 self.assertEqual(a - (a + millisec), -millisec)
1361 self.assertEqual(a - (a - week), week)
1362 self.assertEqual(a - (a - day), day)
1363 self.assertEqual(a - (a - hour), hour)
1364 self.assertEqual(a - (a - millisec), millisec)
1365 self.assertEqual(a + (week + day + hour + millisec),
1366 self.theclass(2002, 3, 10, 18, 6, 0, 1000))
1367 self.assertEqual(a + (week + day + hour + millisec),
1368 (((a + week) + day) + hour) + millisec)
1369 self.assertEqual(a - (week + day + hour + millisec),
1370 self.theclass(2002, 2, 22, 16, 5, 59, 999000))
1371 self.assertEqual(a - (week + day + hour + millisec),
1372 (((a - week) - day) - hour) - millisec)
1373 # Add/sub ints, longs, floats should be illegal
Guido van Rossume2a383d2007-01-15 16:59:06 +00001374 for i in 1, 1, 1.0:
Tim Peters2a799bf2002-12-16 20:18:38 +00001375 self.assertRaises(TypeError, lambda: a+i)
1376 self.assertRaises(TypeError, lambda: a-i)
1377 self.assertRaises(TypeError, lambda: i+a)
1378 self.assertRaises(TypeError, lambda: i-a)
1379
1380 # delta - datetime is senseless.
1381 self.assertRaises(TypeError, lambda: day - a)
1382 # mixing datetime and (delta or datetime) via * or // is senseless
1383 self.assertRaises(TypeError, lambda: day * a)
1384 self.assertRaises(TypeError, lambda: a * day)
1385 self.assertRaises(TypeError, lambda: day // a)
1386 self.assertRaises(TypeError, lambda: a // day)
1387 self.assertRaises(TypeError, lambda: a * a)
1388 self.assertRaises(TypeError, lambda: a // a)
1389 # datetime + datetime is senseless
1390 self.assertRaises(TypeError, lambda: a + a)
1391
1392 def test_pickling(self):
Tim Peters2a799bf2002-12-16 20:18:38 +00001393 args = 6, 7, 23, 20, 59, 1, 64**2
1394 orig = self.theclass(*args)
Guido van Rossum177e41a2003-01-30 22:06:23 +00001395 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +00001396 green = pickler.dumps(orig, proto)
1397 derived = unpickler.loads(green)
1398 self.assertEqual(orig, derived)
Tim Peters2a799bf2002-12-16 20:18:38 +00001399
Guido van Rossum275666f2003-02-07 21:49:01 +00001400 def test_more_pickling(self):
1401 a = self.theclass(2003, 2, 7, 16, 48, 37, 444116)
1402 s = pickle.dumps(a)
1403 b = pickle.loads(s)
1404 self.assertEqual(b.year, 2003)
1405 self.assertEqual(b.month, 2)
1406 self.assertEqual(b.day, 7)
1407
Tim Peters604c0132004-06-07 23:04:33 +00001408 def test_pickling_subclass_datetime(self):
1409 args = 6, 7, 23, 20, 59, 1, 64**2
1410 orig = SubclassDatetime(*args)
1411 for pickler, unpickler, proto in pickle_choices:
1412 green = pickler.dumps(orig, proto)
1413 derived = unpickler.loads(green)
1414 self.assertEqual(orig, derived)
1415
Tim Peters2a799bf2002-12-16 20:18:38 +00001416 def test_more_compare(self):
1417 # The test_compare() inherited from TestDate covers the error cases.
1418 # We just want to test lexicographic ordering on the members datetime
1419 # has that date lacks.
1420 args = [2000, 11, 29, 20, 58, 16, 999998]
1421 t1 = self.theclass(*args)
1422 t2 = self.theclass(*args)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001423 self.assertEqual(t1, t2)
Georg Brandlab91fde2009-08-13 08:51:18 +00001424 self.assertTrue(t1 <= t2)
1425 self.assertTrue(t1 >= t2)
1426 self.assertTrue(not t1 != t2)
1427 self.assertTrue(not t1 < t2)
1428 self.assertTrue(not t1 > t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00001429
1430 for i in range(len(args)):
1431 newargs = args[:]
1432 newargs[i] = args[i] + 1
1433 t2 = self.theclass(*newargs) # this is larger than t1
Georg Brandlab91fde2009-08-13 08:51:18 +00001434 self.assertTrue(t1 < t2)
1435 self.assertTrue(t2 > t1)
1436 self.assertTrue(t1 <= t2)
1437 self.assertTrue(t2 >= t1)
1438 self.assertTrue(t1 != t2)
1439 self.assertTrue(t2 != t1)
1440 self.assertTrue(not t1 == t2)
1441 self.assertTrue(not t2 == t1)
1442 self.assertTrue(not t1 > t2)
1443 self.assertTrue(not t2 < t1)
1444 self.assertTrue(not t1 >= t2)
1445 self.assertTrue(not t2 <= t1)
Tim Peters2a799bf2002-12-16 20:18:38 +00001446
1447
1448 # A helper for timestamp constructor tests.
1449 def verify_field_equality(self, expected, got):
1450 self.assertEqual(expected.tm_year, got.year)
1451 self.assertEqual(expected.tm_mon, got.month)
1452 self.assertEqual(expected.tm_mday, got.day)
1453 self.assertEqual(expected.tm_hour, got.hour)
1454 self.assertEqual(expected.tm_min, got.minute)
1455 self.assertEqual(expected.tm_sec, got.second)
1456
1457 def test_fromtimestamp(self):
1458 import time
1459
1460 ts = time.time()
1461 expected = time.localtime(ts)
1462 got = self.theclass.fromtimestamp(ts)
1463 self.verify_field_equality(expected, got)
1464
1465 def test_utcfromtimestamp(self):
1466 import time
1467
1468 ts = time.time()
1469 expected = time.gmtime(ts)
1470 got = self.theclass.utcfromtimestamp(ts)
1471 self.verify_field_equality(expected, got)
1472
Thomas Wouters477c8d52006-05-27 19:21:47 +00001473 def test_microsecond_rounding(self):
1474 # Test whether fromtimestamp "rounds up" floats that are less
1475 # than one microsecond smaller than an integer.
1476 self.assertEquals(self.theclass.fromtimestamp(0.9999999),
1477 self.theclass.fromtimestamp(1))
1478
Tim Peters1b6f7a92004-06-20 02:50:16 +00001479 def test_insane_fromtimestamp(self):
1480 # It's possible that some platform maps time_t to double,
1481 # and that this test will fail there. This test should
1482 # exempt such platforms (provided they return reasonable
1483 # results!).
1484 for insane in -1e200, 1e200:
1485 self.assertRaises(ValueError, self.theclass.fromtimestamp,
1486 insane)
1487
1488 def test_insane_utcfromtimestamp(self):
1489 # It's possible that some platform maps time_t to double,
1490 # and that this test will fail there. This test should
1491 # exempt such platforms (provided they return reasonable
1492 # results!).
1493 for insane in -1e200, 1e200:
1494 self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
1495 insane)
1496
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497 def test_negative_float_fromtimestamp(self):
1498 # Windows doesn't accept negative timestamps
1499 if os.name == "nt":
1500 return
1501 # The result is tz-dependent; at least test that this doesn't
1502 # fail (like it did before bug 1646728 was fixed).
1503 self.theclass.fromtimestamp(-1.05)
1504
1505 def test_negative_float_utcfromtimestamp(self):
1506 # Windows doesn't accept negative timestamps
1507 if os.name == "nt":
1508 return
1509 d = self.theclass.utcfromtimestamp(-1.05)
1510 self.assertEquals(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
1511
Tim Peters2a799bf2002-12-16 20:18:38 +00001512 def test_utcnow(self):
1513 import time
1514
1515 # Call it a success if utcnow() and utcfromtimestamp() are within
1516 # a second of each other.
1517 tolerance = timedelta(seconds=1)
1518 for dummy in range(3):
1519 from_now = self.theclass.utcnow()
1520 from_timestamp = self.theclass.utcfromtimestamp(time.time())
1521 if abs(from_timestamp - from_now) <= tolerance:
1522 break
1523 # Else try again a few times.
Georg Brandlab91fde2009-08-13 08:51:18 +00001524 self.assertTrue(abs(from_timestamp - from_now) <= tolerance)
Tim Peters2a799bf2002-12-16 20:18:38 +00001525
Skip Montanaro0af3ade2005-01-13 04:12:31 +00001526 def test_strptime(self):
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001527 import _strptime
Skip Montanaro0af3ade2005-01-13 04:12:31 +00001528
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001529 string = '2004-12-01 13:02:47.197'
1530 format = '%Y-%m-%d %H:%M:%S.%f'
1531 result, frac = _strptime._strptime(string, format)
1532 expected = self.theclass(*(result[0:6]+(frac,)))
Skip Montanaro0af3ade2005-01-13 04:12:31 +00001533 got = self.theclass.strptime(string, format)
1534 self.assertEqual(expected, got)
1535
Tim Peters2a799bf2002-12-16 20:18:38 +00001536 def test_more_timetuple(self):
1537 # This tests fields beyond those tested by the TestDate.test_timetuple.
1538 t = self.theclass(2004, 12, 31, 6, 22, 33)
1539 self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1))
1540 self.assertEqual(t.timetuple(),
1541 (t.year, t.month, t.day,
1542 t.hour, t.minute, t.second,
1543 t.weekday(),
1544 t.toordinal() - date(t.year, 1, 1).toordinal() + 1,
1545 -1))
1546 tt = t.timetuple()
1547 self.assertEqual(tt.tm_year, t.year)
1548 self.assertEqual(tt.tm_mon, t.month)
1549 self.assertEqual(tt.tm_mday, t.day)
1550 self.assertEqual(tt.tm_hour, t.hour)
1551 self.assertEqual(tt.tm_min, t.minute)
1552 self.assertEqual(tt.tm_sec, t.second)
1553 self.assertEqual(tt.tm_wday, t.weekday())
1554 self.assertEqual(tt.tm_yday, t.toordinal() -
1555 date(t.year, 1, 1).toordinal() + 1)
1556 self.assertEqual(tt.tm_isdst, -1)
1557
1558 def test_more_strftime(self):
1559 # This tests fields beyond those tested by the TestDate.test_strftime.
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001560 t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
1561 self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"),
1562 "12 31 04 000047 33 22 06 366")
Tim Peters2a799bf2002-12-16 20:18:38 +00001563
1564 def test_extract(self):
1565 dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
1566 self.assertEqual(dt.date(), date(2002, 3, 4))
1567 self.assertEqual(dt.time(), time(18, 45, 3, 1234))
1568
1569 def test_combine(self):
1570 d = date(2002, 3, 4)
1571 t = time(18, 45, 3, 1234)
1572 expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
1573 combine = self.theclass.combine
1574 dt = combine(d, t)
1575 self.assertEqual(dt, expected)
1576
1577 dt = combine(time=t, date=d)
1578 self.assertEqual(dt, expected)
1579
1580 self.assertEqual(d, dt.date())
1581 self.assertEqual(t, dt.time())
1582 self.assertEqual(dt, combine(dt.date(), dt.time()))
1583
1584 self.assertRaises(TypeError, combine) # need an arg
1585 self.assertRaises(TypeError, combine, d) # need two args
1586 self.assertRaises(TypeError, combine, t, d) # args reversed
1587 self.assertRaises(TypeError, combine, d, t, 1) # too many args
1588 self.assertRaises(TypeError, combine, "date", "time") # wrong types
1589
Tim Peters12bf3392002-12-24 05:41:27 +00001590 def test_replace(self):
1591 cls = self.theclass
1592 args = [1, 2, 3, 4, 5, 6, 7]
1593 base = cls(*args)
1594 self.assertEqual(base, base.replace())
1595
1596 i = 0
1597 for name, newval in (("year", 2),
1598 ("month", 3),
1599 ("day", 4),
1600 ("hour", 5),
1601 ("minute", 6),
1602 ("second", 7),
1603 ("microsecond", 8)):
1604 newargs = args[:]
1605 newargs[i] = newval
1606 expected = cls(*newargs)
1607 got = base.replace(**{name: newval})
1608 self.assertEqual(expected, got)
1609 i += 1
1610
1611 # Out of bounds.
1612 base = cls(2000, 2, 29)
1613 self.assertRaises(ValueError, base.replace, year=2001)
1614
Tim Peters80475bb2002-12-25 07:40:55 +00001615 def test_astimezone(self):
Tim Peters52dcce22003-01-23 16:36:11 +00001616 # Pretty boring! The TZ test is more interesting here. astimezone()
1617 # simply can't be applied to a naive object.
Tim Peters80475bb2002-12-25 07:40:55 +00001618 dt = self.theclass.now()
1619 f = FixedOffset(44, "")
Tim Peters80475bb2002-12-25 07:40:55 +00001620 self.assertRaises(TypeError, dt.astimezone) # not enough args
1621 self.assertRaises(TypeError, dt.astimezone, f, f) # too many args
1622 self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type
Tim Peters52dcce22003-01-23 16:36:11 +00001623 self.assertRaises(ValueError, dt.astimezone, f) # naive
1624 self.assertRaises(ValueError, dt.astimezone, tz=f) # naive
Tim Peters80475bb2002-12-25 07:40:55 +00001625
Tim Peters52dcce22003-01-23 16:36:11 +00001626 class Bogus(tzinfo):
1627 def utcoffset(self, dt): return None
1628 def dst(self, dt): return timedelta(0)
1629 bog = Bogus()
1630 self.assertRaises(ValueError, dt.astimezone, bog) # naive
1631
1632 class AlsoBogus(tzinfo):
1633 def utcoffset(self, dt): return timedelta(0)
1634 def dst(self, dt): return None
1635 alsobog = AlsoBogus()
1636 self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive
Tim Peters12bf3392002-12-24 05:41:27 +00001637
Tim Petersa98924a2003-05-17 05:55:19 +00001638 def test_subclass_datetime(self):
1639
1640 class C(self.theclass):
1641 theAnswer = 42
1642
1643 def __new__(cls, *args, **kws):
1644 temp = kws.copy()
1645 extra = temp.pop('extra')
1646 result = self.theclass.__new__(cls, *args, **temp)
1647 result.extra = extra
1648 return result
1649
1650 def newmeth(self, start):
1651 return start + self.year + self.month + self.second
1652
1653 args = 2003, 4, 14, 12, 13, 41
1654
1655 dt1 = self.theclass(*args)
1656 dt2 = C(*args, **{'extra': 7})
1657
1658 self.assertEqual(dt2.__class__, C)
1659 self.assertEqual(dt2.theAnswer, 42)
1660 self.assertEqual(dt2.extra, 7)
1661 self.assertEqual(dt1.toordinal(), dt2.toordinal())
1662 self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month +
1663 dt1.second - 7)
1664
Tim Peters604c0132004-06-07 23:04:33 +00001665class SubclassTime(time):
1666 sub_var = 1
1667
Guido van Rossumd8faa362007-04-27 19:54:29 +00001668class TestTime(HarmlessMixedComparison, unittest.TestCase):
Tim Peters2a799bf2002-12-16 20:18:38 +00001669
1670 theclass = time
1671
1672 def test_basic_attributes(self):
1673 t = self.theclass(12, 0)
1674 self.assertEqual(t.hour, 12)
1675 self.assertEqual(t.minute, 0)
1676 self.assertEqual(t.second, 0)
1677 self.assertEqual(t.microsecond, 0)
1678
1679 def test_basic_attributes_nonzero(self):
1680 # Make sure all attributes are non-zero so bugs in
1681 # bit-shifting access show up.
1682 t = self.theclass(12, 59, 59, 8000)
1683 self.assertEqual(t.hour, 12)
1684 self.assertEqual(t.minute, 59)
1685 self.assertEqual(t.second, 59)
1686 self.assertEqual(t.microsecond, 8000)
1687
1688 def test_roundtrip(self):
1689 t = self.theclass(1, 2, 3, 4)
1690
1691 # Verify t -> string -> time identity.
1692 s = repr(t)
Georg Brandlab91fde2009-08-13 08:51:18 +00001693 self.assertTrue(s.startswith('datetime.'))
Tim Peters2a799bf2002-12-16 20:18:38 +00001694 s = s[9:]
1695 t2 = eval(s)
1696 self.assertEqual(t, t2)
1697
1698 # Verify identity via reconstructing from pieces.
1699 t2 = self.theclass(t.hour, t.minute, t.second,
1700 t.microsecond)
1701 self.assertEqual(t, t2)
1702
1703 def test_comparing(self):
1704 args = [1, 2, 3, 4]
1705 t1 = self.theclass(*args)
1706 t2 = self.theclass(*args)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001707 self.assertEqual(t1, t2)
Georg Brandlab91fde2009-08-13 08:51:18 +00001708 self.assertTrue(t1 <= t2)
1709 self.assertTrue(t1 >= t2)
1710 self.assertTrue(not t1 != t2)
1711 self.assertTrue(not t1 < t2)
1712 self.assertTrue(not t1 > t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00001713
1714 for i in range(len(args)):
1715 newargs = args[:]
1716 newargs[i] = args[i] + 1
1717 t2 = self.theclass(*newargs) # this is larger than t1
Georg Brandlab91fde2009-08-13 08:51:18 +00001718 self.assertTrue(t1 < t2)
1719 self.assertTrue(t2 > t1)
1720 self.assertTrue(t1 <= t2)
1721 self.assertTrue(t2 >= t1)
1722 self.assertTrue(t1 != t2)
1723 self.assertTrue(t2 != t1)
1724 self.assertTrue(not t1 == t2)
1725 self.assertTrue(not t2 == t1)
1726 self.assertTrue(not t1 > t2)
1727 self.assertTrue(not t2 < t1)
1728 self.assertTrue(not t1 >= t2)
1729 self.assertTrue(not t2 <= t1)
Tim Peters2a799bf2002-12-16 20:18:38 +00001730
Tim Peters68124bb2003-02-08 03:46:31 +00001731 for badarg in OTHERSTUFF:
Tim Peters07534a62003-02-07 22:50:28 +00001732 self.assertEqual(t1 == badarg, False)
1733 self.assertEqual(t1 != badarg, True)
1734 self.assertEqual(badarg == t1, False)
1735 self.assertEqual(badarg != t1, True)
1736
Tim Peters2a799bf2002-12-16 20:18:38 +00001737 self.assertRaises(TypeError, lambda: t1 <= badarg)
1738 self.assertRaises(TypeError, lambda: t1 < badarg)
1739 self.assertRaises(TypeError, lambda: t1 > badarg)
1740 self.assertRaises(TypeError, lambda: t1 >= badarg)
Tim Peters2a799bf2002-12-16 20:18:38 +00001741 self.assertRaises(TypeError, lambda: badarg <= t1)
1742 self.assertRaises(TypeError, lambda: badarg < t1)
1743 self.assertRaises(TypeError, lambda: badarg > t1)
1744 self.assertRaises(TypeError, lambda: badarg >= t1)
1745
1746 def test_bad_constructor_arguments(self):
1747 # bad hours
1748 self.theclass(0, 0) # no exception
1749 self.theclass(23, 0) # no exception
1750 self.assertRaises(ValueError, self.theclass, -1, 0)
1751 self.assertRaises(ValueError, self.theclass, 24, 0)
1752 # bad minutes
1753 self.theclass(23, 0) # no exception
1754 self.theclass(23, 59) # no exception
1755 self.assertRaises(ValueError, self.theclass, 23, -1)
1756 self.assertRaises(ValueError, self.theclass, 23, 60)
1757 # bad seconds
1758 self.theclass(23, 59, 0) # no exception
1759 self.theclass(23, 59, 59) # no exception
1760 self.assertRaises(ValueError, self.theclass, 23, 59, -1)
1761 self.assertRaises(ValueError, self.theclass, 23, 59, 60)
1762 # bad microseconds
1763 self.theclass(23, 59, 59, 0) # no exception
1764 self.theclass(23, 59, 59, 999999) # no exception
1765 self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1)
1766 self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000)
1767
1768 def test_hash_equality(self):
1769 d = self.theclass(23, 30, 17)
1770 e = self.theclass(23, 30, 17)
1771 self.assertEqual(d, e)
1772 self.assertEqual(hash(d), hash(e))
1773
1774 dic = {d: 1}
1775 dic[e] = 2
1776 self.assertEqual(len(dic), 1)
1777 self.assertEqual(dic[d], 2)
1778 self.assertEqual(dic[e], 2)
1779
1780 d = self.theclass(0, 5, 17)
1781 e = self.theclass(0, 5, 17)
1782 self.assertEqual(d, e)
1783 self.assertEqual(hash(d), hash(e))
1784
1785 dic = {d: 1}
1786 dic[e] = 2
1787 self.assertEqual(len(dic), 1)
1788 self.assertEqual(dic[d], 2)
1789 self.assertEqual(dic[e], 2)
1790
1791 def test_isoformat(self):
1792 t = self.theclass(4, 5, 1, 123)
1793 self.assertEqual(t.isoformat(), "04:05:01.000123")
1794 self.assertEqual(t.isoformat(), str(t))
1795
1796 t = self.theclass()
1797 self.assertEqual(t.isoformat(), "00:00:00")
1798 self.assertEqual(t.isoformat(), str(t))
1799
1800 t = self.theclass(microsecond=1)
1801 self.assertEqual(t.isoformat(), "00:00:00.000001")
1802 self.assertEqual(t.isoformat(), str(t))
1803
1804 t = self.theclass(microsecond=10)
1805 self.assertEqual(t.isoformat(), "00:00:00.000010")
1806 self.assertEqual(t.isoformat(), str(t))
1807
1808 t = self.theclass(microsecond=100)
1809 self.assertEqual(t.isoformat(), "00:00:00.000100")
1810 self.assertEqual(t.isoformat(), str(t))
1811
1812 t = self.theclass(microsecond=1000)
1813 self.assertEqual(t.isoformat(), "00:00:00.001000")
1814 self.assertEqual(t.isoformat(), str(t))
1815
1816 t = self.theclass(microsecond=10000)
1817 self.assertEqual(t.isoformat(), "00:00:00.010000")
1818 self.assertEqual(t.isoformat(), str(t))
1819
1820 t = self.theclass(microsecond=100000)
1821 self.assertEqual(t.isoformat(), "00:00:00.100000")
1822 self.assertEqual(t.isoformat(), str(t))
1823
Thomas Wouterscf297e42007-02-23 15:07:44 +00001824 def test_1653736(self):
1825 # verify it doesn't accept extra keyword arguments
1826 t = self.theclass(second=1)
1827 self.assertRaises(TypeError, t.isoformat, foo=3)
1828
Tim Peters2a799bf2002-12-16 20:18:38 +00001829 def test_strftime(self):
1830 t = self.theclass(1, 2, 3, 4)
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001831 self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004")
Tim Peters2a799bf2002-12-16 20:18:38 +00001832 # A naive object replaces %z and %Z with empty strings.
1833 self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
1834
Eric Smith1ba31142007-09-11 18:06:02 +00001835 def test_format(self):
1836 t = self.theclass(1, 2, 3, 4)
Eric Smith8fd3eba2008-02-17 19:48:00 +00001837 self.assertEqual(t.__format__(''), str(t))
Eric Smith1ba31142007-09-11 18:06:02 +00001838
1839 # check that a derived class's __str__() gets called
1840 class A(self.theclass):
1841 def __str__(self):
1842 return 'A'
1843 a = A(1, 2, 3, 4)
Eric Smith8fd3eba2008-02-17 19:48:00 +00001844 self.assertEqual(a.__format__(''), 'A')
Eric Smith1ba31142007-09-11 18:06:02 +00001845
1846 # check that a derived class's strftime gets called
1847 class B(self.theclass):
1848 def strftime(self, format_spec):
1849 return 'B'
1850 b = B(1, 2, 3, 4)
Eric Smith8fd3eba2008-02-17 19:48:00 +00001851 self.assertEqual(b.__format__(''), str(t))
Eric Smith1ba31142007-09-11 18:06:02 +00001852
1853 for fmt in ['%H %M %S',
1854 ]:
Eric Smith8fd3eba2008-02-17 19:48:00 +00001855 self.assertEqual(t.__format__(fmt), t.strftime(fmt))
1856 self.assertEqual(a.__format__(fmt), t.strftime(fmt))
1857 self.assertEqual(b.__format__(fmt), 'B')
Eric Smith1ba31142007-09-11 18:06:02 +00001858
Tim Peters2a799bf2002-12-16 20:18:38 +00001859 def test_str(self):
1860 self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004")
1861 self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000")
1862 self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000")
1863 self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03")
1864 self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00")
1865
1866 def test_repr(self):
1867 name = 'datetime.' + self.theclass.__name__
1868 self.assertEqual(repr(self.theclass(1, 2, 3, 4)),
1869 "%s(1, 2, 3, 4)" % name)
1870 self.assertEqual(repr(self.theclass(10, 2, 3, 4000)),
1871 "%s(10, 2, 3, 4000)" % name)
1872 self.assertEqual(repr(self.theclass(0, 2, 3, 400000)),
1873 "%s(0, 2, 3, 400000)" % name)
1874 self.assertEqual(repr(self.theclass(12, 2, 3, 0)),
1875 "%s(12, 2, 3)" % name)
1876 self.assertEqual(repr(self.theclass(23, 15, 0, 0)),
1877 "%s(23, 15)" % name)
1878
1879 def test_resolution_info(self):
Georg Brandlab91fde2009-08-13 08:51:18 +00001880 self.assertTrue(isinstance(self.theclass.min, self.theclass))
1881 self.assertTrue(isinstance(self.theclass.max, self.theclass))
1882 self.assertTrue(isinstance(self.theclass.resolution, timedelta))
1883 self.assertTrue(self.theclass.max > self.theclass.min)
Tim Peters2a799bf2002-12-16 20:18:38 +00001884
1885 def test_pickling(self):
Tim Peters2a799bf2002-12-16 20:18:38 +00001886 args = 20, 59, 16, 64**2
1887 orig = self.theclass(*args)
Guido van Rossum177e41a2003-01-30 22:06:23 +00001888 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +00001889 green = pickler.dumps(orig, proto)
1890 derived = unpickler.loads(green)
1891 self.assertEqual(orig, derived)
Tim Peters2a799bf2002-12-16 20:18:38 +00001892
Tim Peters604c0132004-06-07 23:04:33 +00001893 def test_pickling_subclass_time(self):
1894 args = 20, 59, 16, 64**2
1895 orig = SubclassTime(*args)
1896 for pickler, unpickler, proto in pickle_choices:
1897 green = pickler.dumps(orig, proto)
1898 derived = unpickler.loads(green)
1899 self.assertEqual(orig, derived)
1900
Tim Peters2a799bf2002-12-16 20:18:38 +00001901 def test_bool(self):
1902 cls = self.theclass
Georg Brandlab91fde2009-08-13 08:51:18 +00001903 self.assertTrue(cls(1))
1904 self.assertTrue(cls(0, 1))
1905 self.assertTrue(cls(0, 0, 1))
1906 self.assertTrue(cls(0, 0, 0, 1))
1907 self.assertTrue(not cls(0))
1908 self.assertTrue(not cls())
Tim Peters2a799bf2002-12-16 20:18:38 +00001909
Tim Peters12bf3392002-12-24 05:41:27 +00001910 def test_replace(self):
1911 cls = self.theclass
1912 args = [1, 2, 3, 4]
1913 base = cls(*args)
1914 self.assertEqual(base, base.replace())
1915
1916 i = 0
1917 for name, newval in (("hour", 5),
1918 ("minute", 6),
1919 ("second", 7),
1920 ("microsecond", 8)):
1921 newargs = args[:]
1922 newargs[i] = newval
1923 expected = cls(*newargs)
1924 got = base.replace(**{name: newval})
1925 self.assertEqual(expected, got)
1926 i += 1
1927
1928 # Out of bounds.
1929 base = cls(1)
1930 self.assertRaises(ValueError, base.replace, hour=24)
1931 self.assertRaises(ValueError, base.replace, minute=-1)
1932 self.assertRaises(ValueError, base.replace, second=100)
1933 self.assertRaises(ValueError, base.replace, microsecond=1000000)
1934
Tim Petersa98924a2003-05-17 05:55:19 +00001935 def test_subclass_time(self):
1936
1937 class C(self.theclass):
1938 theAnswer = 42
1939
1940 def __new__(cls, *args, **kws):
1941 temp = kws.copy()
1942 extra = temp.pop('extra')
1943 result = self.theclass.__new__(cls, *args, **temp)
1944 result.extra = extra
1945 return result
1946
1947 def newmeth(self, start):
1948 return start + self.hour + self.second
1949
1950 args = 4, 5, 6
1951
1952 dt1 = self.theclass(*args)
1953 dt2 = C(*args, **{'extra': 7})
1954
1955 self.assertEqual(dt2.__class__, C)
1956 self.assertEqual(dt2.theAnswer, 42)
1957 self.assertEqual(dt2.extra, 7)
1958 self.assertEqual(dt1.isoformat(), dt2.isoformat())
1959 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
1960
Armin Rigof4afb212005-11-07 07:15:48 +00001961 def test_backdoor_resistance(self):
1962 # see TestDate.test_backdoor_resistance().
1963 base = '2:59.0'
1964 for hour_byte in ' ', '9', chr(24), '\xff':
1965 self.assertRaises(TypeError, self.theclass,
1966 hour_byte + base[1:])
1967
Tim Peters855fe882002-12-22 03:43:39 +00001968# A mixin for classes with a tzinfo= argument. Subclasses must define
1969# theclass as a class atribute, and theclass(1, 1, 1, tzinfo=whatever)
Tim Peters0bf60bd2003-01-08 20:40:01 +00001970# must be legit (which is true for time and datetime).
Guido van Rossumd8faa362007-04-27 19:54:29 +00001971class TZInfoBase:
Tim Peters2a799bf2002-12-16 20:18:38 +00001972
Tim Petersbad8ff02002-12-30 20:52:32 +00001973 def test_argument_passing(self):
1974 cls = self.theclass
Tim Peters0bf60bd2003-01-08 20:40:01 +00001975 # A datetime passes itself on, a time passes None.
Tim Petersbad8ff02002-12-30 20:52:32 +00001976 class introspective(tzinfo):
1977 def tzname(self, dt): return dt and "real" or "none"
Tim Peters397301e2003-01-02 21:28:08 +00001978 def utcoffset(self, dt):
1979 return timedelta(minutes = dt and 42 or -42)
Tim Petersbad8ff02002-12-30 20:52:32 +00001980 dst = utcoffset
1981
1982 obj = cls(1, 2, 3, tzinfo=introspective())
1983
Tim Peters0bf60bd2003-01-08 20:40:01 +00001984 expected = cls is time and "none" or "real"
Tim Petersbad8ff02002-12-30 20:52:32 +00001985 self.assertEqual(obj.tzname(), expected)
1986
Tim Peters0bf60bd2003-01-08 20:40:01 +00001987 expected = timedelta(minutes=(cls is time and -42 or 42))
Tim Petersbad8ff02002-12-30 20:52:32 +00001988 self.assertEqual(obj.utcoffset(), expected)
1989 self.assertEqual(obj.dst(), expected)
1990
Tim Peters855fe882002-12-22 03:43:39 +00001991 def test_bad_tzinfo_classes(self):
1992 cls = self.theclass
1993 self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12)
Tim Peters2a799bf2002-12-16 20:18:38 +00001994
Tim Peters855fe882002-12-22 03:43:39 +00001995 class NiceTry(object):
1996 def __init__(self): pass
1997 def utcoffset(self, dt): pass
1998 self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry)
1999
2000 class BetterTry(tzinfo):
2001 def __init__(self): pass
2002 def utcoffset(self, dt): pass
2003 b = BetterTry()
2004 t = cls(1, 1, 1, tzinfo=b)
Georg Brandlab91fde2009-08-13 08:51:18 +00002005 self.assertTrue(t.tzinfo is b)
Tim Peters855fe882002-12-22 03:43:39 +00002006
2007 def test_utc_offset_out_of_bounds(self):
2008 class Edgy(tzinfo):
2009 def __init__(self, offset):
Tim Peters397301e2003-01-02 21:28:08 +00002010 self.offset = timedelta(minutes=offset)
Tim Peters855fe882002-12-22 03:43:39 +00002011 def utcoffset(self, dt):
2012 return self.offset
2013
2014 cls = self.theclass
2015 for offset, legit in ((-1440, False),
2016 (-1439, True),
2017 (1439, True),
2018 (1440, False)):
Tim Peters0bf60bd2003-01-08 20:40:01 +00002019 if cls is time:
Tim Peters855fe882002-12-22 03:43:39 +00002020 t = cls(1, 2, 3, tzinfo=Edgy(offset))
Tim Peters0bf60bd2003-01-08 20:40:01 +00002021 elif cls is datetime:
Tim Peters855fe882002-12-22 03:43:39 +00002022 t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset))
Tim Peters0bf60bd2003-01-08 20:40:01 +00002023 else:
2024 assert 0, "impossible"
Tim Peters855fe882002-12-22 03:43:39 +00002025 if legit:
2026 aofs = abs(offset)
2027 h, m = divmod(aofs, 60)
2028 tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m)
Tim Peters0bf60bd2003-01-08 20:40:01 +00002029 if isinstance(t, datetime):
Tim Peters855fe882002-12-22 03:43:39 +00002030 t = t.timetz()
2031 self.assertEqual(str(t), "01:02:03" + tag)
2032 else:
2033 self.assertRaises(ValueError, str, t)
2034
2035 def test_tzinfo_classes(self):
2036 cls = self.theclass
2037 class C1(tzinfo):
2038 def utcoffset(self, dt): return None
2039 def dst(self, dt): return None
2040 def tzname(self, dt): return None
2041 for t in (cls(1, 1, 1),
2042 cls(1, 1, 1, tzinfo=None),
2043 cls(1, 1, 1, tzinfo=C1())):
Georg Brandlab91fde2009-08-13 08:51:18 +00002044 self.assertTrue(t.utcoffset() is None)
2045 self.assertTrue(t.dst() is None)
2046 self.assertTrue(t.tzname() is None)
Tim Peters855fe882002-12-22 03:43:39 +00002047
Tim Peters855fe882002-12-22 03:43:39 +00002048 class C3(tzinfo):
2049 def utcoffset(self, dt): return timedelta(minutes=-1439)
2050 def dst(self, dt): return timedelta(minutes=1439)
2051 def tzname(self, dt): return "aname"
Tim Peters397301e2003-01-02 21:28:08 +00002052 t = cls(1, 1, 1, tzinfo=C3())
2053 self.assertEqual(t.utcoffset(), timedelta(minutes=-1439))
2054 self.assertEqual(t.dst(), timedelta(minutes=1439))
2055 self.assertEqual(t.tzname(), "aname")
Tim Peters855fe882002-12-22 03:43:39 +00002056
2057 # Wrong types.
2058 class C4(tzinfo):
2059 def utcoffset(self, dt): return "aname"
Tim Peters397301e2003-01-02 21:28:08 +00002060 def dst(self, dt): return 7
Tim Peters855fe882002-12-22 03:43:39 +00002061 def tzname(self, dt): return 0
2062 t = cls(1, 1, 1, tzinfo=C4())
2063 self.assertRaises(TypeError, t.utcoffset)
2064 self.assertRaises(TypeError, t.dst)
2065 self.assertRaises(TypeError, t.tzname)
2066
2067 # Offset out of range.
Tim Peters855fe882002-12-22 03:43:39 +00002068 class C6(tzinfo):
2069 def utcoffset(self, dt): return timedelta(hours=-24)
2070 def dst(self, dt): return timedelta(hours=24)
Tim Peters397301e2003-01-02 21:28:08 +00002071 t = cls(1, 1, 1, tzinfo=C6())
2072 self.assertRaises(ValueError, t.utcoffset)
2073 self.assertRaises(ValueError, t.dst)
Tim Peters855fe882002-12-22 03:43:39 +00002074
2075 # Not a whole number of minutes.
2076 class C7(tzinfo):
2077 def utcoffset(self, dt): return timedelta(seconds=61)
2078 def dst(self, dt): return timedelta(microseconds=-81)
2079 t = cls(1, 1, 1, tzinfo=C7())
2080 self.assertRaises(ValueError, t.utcoffset)
2081 self.assertRaises(ValueError, t.dst)
2082
Tim Peters4c0db782002-12-26 05:01:19 +00002083 def test_aware_compare(self):
2084 cls = self.theclass
2085
Tim Peters60c76e42002-12-27 00:41:11 +00002086 # Ensure that utcoffset() gets ignored if the comparands have
2087 # the same tzinfo member.
Tim Peters4c0db782002-12-26 05:01:19 +00002088 class OperandDependentOffset(tzinfo):
2089 def utcoffset(self, t):
2090 if t.minute < 10:
Tim Peters397301e2003-01-02 21:28:08 +00002091 # d0 and d1 equal after adjustment
2092 return timedelta(minutes=t.minute)
Tim Peters4c0db782002-12-26 05:01:19 +00002093 else:
Tim Peters397301e2003-01-02 21:28:08 +00002094 # d2 off in the weeds
2095 return timedelta(minutes=59)
Tim Peters4c0db782002-12-26 05:01:19 +00002096
2097 base = cls(8, 9, 10, tzinfo=OperandDependentOffset())
2098 d0 = base.replace(minute=3)
2099 d1 = base.replace(minute=9)
2100 d2 = base.replace(minute=11)
2101 for x in d0, d1, d2:
2102 for y in d0, d1, d2:
Mark Dickinsona56c4672009-01-27 18:17:45 +00002103 for op in lt, le, gt, ge, eq, ne:
2104 got = op(x, y)
2105 expected = op(x.minute, y.minute)
2106 self.assertEqual(got, expected)
Tim Peters60c76e42002-12-27 00:41:11 +00002107
2108 # However, if they're different members, uctoffset is not ignored.
Tim Peters0bf60bd2003-01-08 20:40:01 +00002109 # Note that a time can't actually have an operand-depedent offset,
2110 # though (and time.utcoffset() passes None to tzinfo.utcoffset()),
2111 # so skip this test for time.
2112 if cls is not time:
Tim Petersbad8ff02002-12-30 20:52:32 +00002113 d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
2114 d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
2115 d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
2116 for x in d0, d1, d2:
2117 for y in d0, d1, d2:
Mark Dickinsona56c4672009-01-27 18:17:45 +00002118 got = (x > y) - (x < y)
Tim Petersbad8ff02002-12-30 20:52:32 +00002119 if (x is d0 or x is d1) and (y is d0 or y is d1):
2120 expected = 0
2121 elif x is y is d2:
2122 expected = 0
2123 elif x is d2:
2124 expected = -1
2125 else:
2126 assert y is d2
2127 expected = 1
2128 self.assertEqual(got, expected)
Tim Peters4c0db782002-12-26 05:01:19 +00002129
Tim Peters855fe882002-12-22 03:43:39 +00002130
Tim Peters0bf60bd2003-01-08 20:40:01 +00002131# Testing time objects with a non-None tzinfo.
Guido van Rossumd8faa362007-04-27 19:54:29 +00002132class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
Tim Peters0bf60bd2003-01-08 20:40:01 +00002133 theclass = time
Tim Peters2a799bf2002-12-16 20:18:38 +00002134
2135 def test_empty(self):
2136 t = self.theclass()
2137 self.assertEqual(t.hour, 0)
2138 self.assertEqual(t.minute, 0)
2139 self.assertEqual(t.second, 0)
2140 self.assertEqual(t.microsecond, 0)
Georg Brandlab91fde2009-08-13 08:51:18 +00002141 self.assertTrue(t.tzinfo is None)
Tim Peters2a799bf2002-12-16 20:18:38 +00002142
Tim Peters2a799bf2002-12-16 20:18:38 +00002143 def test_zones(self):
2144 est = FixedOffset(-300, "EST", 1)
2145 utc = FixedOffset(0, "UTC", -2)
2146 met = FixedOffset(60, "MET", 3)
Tim Peters0bf60bd2003-01-08 20:40:01 +00002147 t1 = time( 7, 47, tzinfo=est)
2148 t2 = time(12, 47, tzinfo=utc)
2149 t3 = time(13, 47, tzinfo=met)
2150 t4 = time(microsecond=40)
2151 t5 = time(microsecond=40, tzinfo=utc)
Tim Peters2a799bf2002-12-16 20:18:38 +00002152
2153 self.assertEqual(t1.tzinfo, est)
2154 self.assertEqual(t2.tzinfo, utc)
2155 self.assertEqual(t3.tzinfo, met)
Georg Brandlab91fde2009-08-13 08:51:18 +00002156 self.assertTrue(t4.tzinfo is None)
Tim Peters2a799bf2002-12-16 20:18:38 +00002157 self.assertEqual(t5.tzinfo, utc)
2158
Tim Peters855fe882002-12-22 03:43:39 +00002159 self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
2160 self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
2161 self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
Georg Brandlab91fde2009-08-13 08:51:18 +00002162 self.assertTrue(t4.utcoffset() is None)
Tim Peters2a799bf2002-12-16 20:18:38 +00002163 self.assertRaises(TypeError, t1.utcoffset, "no args")
2164
2165 self.assertEqual(t1.tzname(), "EST")
2166 self.assertEqual(t2.tzname(), "UTC")
2167 self.assertEqual(t3.tzname(), "MET")
Georg Brandlab91fde2009-08-13 08:51:18 +00002168 self.assertTrue(t4.tzname() is None)
Tim Peters2a799bf2002-12-16 20:18:38 +00002169 self.assertRaises(TypeError, t1.tzname, "no args")
2170
Tim Peters855fe882002-12-22 03:43:39 +00002171 self.assertEqual(t1.dst(), timedelta(minutes=1))
2172 self.assertEqual(t2.dst(), timedelta(minutes=-2))
2173 self.assertEqual(t3.dst(), timedelta(minutes=3))
Georg Brandlab91fde2009-08-13 08:51:18 +00002174 self.assertTrue(t4.dst() is None)
Tim Peters2a799bf2002-12-16 20:18:38 +00002175 self.assertRaises(TypeError, t1.dst, "no args")
2176
2177 self.assertEqual(hash(t1), hash(t2))
2178 self.assertEqual(hash(t1), hash(t3))
2179 self.assertEqual(hash(t2), hash(t3))
2180
2181 self.assertEqual(t1, t2)
2182 self.assertEqual(t1, t3)
2183 self.assertEqual(t2, t3)
2184 self.assertRaises(TypeError, lambda: t4 == t5) # mixed tz-aware & naive
2185 self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive
2186 self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive
2187
2188 self.assertEqual(str(t1), "07:47:00-05:00")
2189 self.assertEqual(str(t2), "12:47:00+00:00")
2190 self.assertEqual(str(t3), "13:47:00+01:00")
2191 self.assertEqual(str(t4), "00:00:00.000040")
2192 self.assertEqual(str(t5), "00:00:00.000040+00:00")
2193
2194 self.assertEqual(t1.isoformat(), "07:47:00-05:00")
2195 self.assertEqual(t2.isoformat(), "12:47:00+00:00")
2196 self.assertEqual(t3.isoformat(), "13:47:00+01:00")
2197 self.assertEqual(t4.isoformat(), "00:00:00.000040")
2198 self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00")
2199
Tim Peters0bf60bd2003-01-08 20:40:01 +00002200 d = 'datetime.time'
Tim Peters2a799bf2002-12-16 20:18:38 +00002201 self.assertEqual(repr(t1), d + "(7, 47, tzinfo=est)")
2202 self.assertEqual(repr(t2), d + "(12, 47, tzinfo=utc)")
2203 self.assertEqual(repr(t3), d + "(13, 47, tzinfo=met)")
2204 self.assertEqual(repr(t4), d + "(0, 0, 0, 40)")
2205 self.assertEqual(repr(t5), d + "(0, 0, 0, 40, tzinfo=utc)")
2206
2207 self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"),
2208 "07:47:00 %Z=EST %z=-0500")
2209 self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000")
2210 self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100")
2211
2212 yuck = FixedOffset(-1439, "%z %Z %%z%%Z")
Tim Peters0bf60bd2003-01-08 20:40:01 +00002213 t1 = time(23, 59, tzinfo=yuck)
Tim Peters2a799bf2002-12-16 20:18:38 +00002214 self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"),
2215 "23:59 %Z='%z %Z %%z%%Z' %z='-2359'")
2216
Tim Petersb92bb712002-12-21 17:44:07 +00002217 # Check that an invalid tzname result raises an exception.
2218 class Badtzname(tzinfo):
2219 def tzname(self, dt): return 42
Tim Peters0bf60bd2003-01-08 20:40:01 +00002220 t = time(2, 3, 4, tzinfo=Badtzname())
Tim Petersb92bb712002-12-21 17:44:07 +00002221 self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04")
2222 self.assertRaises(TypeError, t.strftime, "%Z")
Tim Peters2a799bf2002-12-16 20:18:38 +00002223
2224 def test_hash_edge_cases(self):
2225 # Offsets that overflow a basic time.
2226 t1 = self.theclass(0, 1, 2, 3, tzinfo=FixedOffset(1439, ""))
2227 t2 = self.theclass(0, 0, 2, 3, tzinfo=FixedOffset(1438, ""))
2228 self.assertEqual(hash(t1), hash(t2))
2229
2230 t1 = self.theclass(23, 58, 6, 100, tzinfo=FixedOffset(-1000, ""))
2231 t2 = self.theclass(23, 48, 6, 100, tzinfo=FixedOffset(-1010, ""))
2232 self.assertEqual(hash(t1), hash(t2))
2233
Tim Peters2a799bf2002-12-16 20:18:38 +00002234 def test_pickling(self):
Tim Peters2a799bf2002-12-16 20:18:38 +00002235 # Try one without a tzinfo.
2236 args = 20, 59, 16, 64**2
2237 orig = self.theclass(*args)
Guido van Rossum177e41a2003-01-30 22:06:23 +00002238 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +00002239 green = pickler.dumps(orig, proto)
2240 derived = unpickler.loads(green)
2241 self.assertEqual(orig, derived)
Tim Peters2a799bf2002-12-16 20:18:38 +00002242
2243 # Try one with a tzinfo.
Tim Petersfb8472c2002-12-21 05:04:42 +00002244 tinfo = PicklableFixedOffset(-300, 'cookie')
Tim Peters2a799bf2002-12-16 20:18:38 +00002245 orig = self.theclass(5, 6, 7, tzinfo=tinfo)
Guido van Rossum177e41a2003-01-30 22:06:23 +00002246 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +00002247 green = pickler.dumps(orig, proto)
2248 derived = unpickler.loads(green)
2249 self.assertEqual(orig, derived)
Georg Brandlab91fde2009-08-13 08:51:18 +00002250 self.assertTrue(isinstance(derived.tzinfo, PicklableFixedOffset))
Tim Peters96940c92003-01-31 21:55:33 +00002251 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
2252 self.assertEqual(derived.tzname(), 'cookie')
Tim Peters2a799bf2002-12-16 20:18:38 +00002253
2254 def test_more_bool(self):
2255 # Test cases with non-None tzinfo.
2256 cls = self.theclass
2257
2258 t = cls(0, tzinfo=FixedOffset(-300, ""))
Georg Brandlab91fde2009-08-13 08:51:18 +00002259 self.assertTrue(t)
Tim Peters2a799bf2002-12-16 20:18:38 +00002260
2261 t = cls(5, tzinfo=FixedOffset(-300, ""))
Georg Brandlab91fde2009-08-13 08:51:18 +00002262 self.assertTrue(t)
Tim Peters2a799bf2002-12-16 20:18:38 +00002263
2264 t = cls(5, tzinfo=FixedOffset(300, ""))
Georg Brandlab91fde2009-08-13 08:51:18 +00002265 self.assertTrue(not t)
Tim Peters2a799bf2002-12-16 20:18:38 +00002266
2267 t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, ""))
Georg Brandlab91fde2009-08-13 08:51:18 +00002268 self.assertTrue(not t)
Tim Peters2a799bf2002-12-16 20:18:38 +00002269
2270 # Mostly ensuring this doesn't overflow internally.
2271 t = cls(0, tzinfo=FixedOffset(23*60 + 59, ""))
Georg Brandlab91fde2009-08-13 08:51:18 +00002272 self.assertTrue(t)
Tim Peters2a799bf2002-12-16 20:18:38 +00002273
2274 # But this should yield a value error -- the utcoffset is bogus.
2275 t = cls(0, tzinfo=FixedOffset(24*60, ""))
2276 self.assertRaises(ValueError, lambda: bool(t))
2277
2278 # Likewise.
2279 t = cls(0, tzinfo=FixedOffset(-24*60, ""))
2280 self.assertRaises(ValueError, lambda: bool(t))
2281
Tim Peters12bf3392002-12-24 05:41:27 +00002282 def test_replace(self):
2283 cls = self.theclass
2284 z100 = FixedOffset(100, "+100")
2285 zm200 = FixedOffset(timedelta(minutes=-200), "-200")
2286 args = [1, 2, 3, 4, z100]
2287 base = cls(*args)
2288 self.assertEqual(base, base.replace())
2289
2290 i = 0
2291 for name, newval in (("hour", 5),
2292 ("minute", 6),
2293 ("second", 7),
2294 ("microsecond", 8),
2295 ("tzinfo", zm200)):
2296 newargs = args[:]
2297 newargs[i] = newval
2298 expected = cls(*newargs)
2299 got = base.replace(**{name: newval})
2300 self.assertEqual(expected, got)
2301 i += 1
2302
2303 # Ensure we can get rid of a tzinfo.
2304 self.assertEqual(base.tzname(), "+100")
2305 base2 = base.replace(tzinfo=None)
Georg Brandlab91fde2009-08-13 08:51:18 +00002306 self.assertTrue(base2.tzinfo is None)
2307 self.assertTrue(base2.tzname() is None)
Tim Peters12bf3392002-12-24 05:41:27 +00002308
2309 # Ensure we can add one.
2310 base3 = base2.replace(tzinfo=z100)
2311 self.assertEqual(base, base3)
Georg Brandlab91fde2009-08-13 08:51:18 +00002312 self.assertTrue(base.tzinfo is base3.tzinfo)
Tim Peters12bf3392002-12-24 05:41:27 +00002313
2314 # Out of bounds.
2315 base = cls(1)
2316 self.assertRaises(ValueError, base.replace, hour=24)
2317 self.assertRaises(ValueError, base.replace, minute=-1)
2318 self.assertRaises(ValueError, base.replace, second=100)
2319 self.assertRaises(ValueError, base.replace, microsecond=1000000)
2320
Tim Peters60c76e42002-12-27 00:41:11 +00002321 def test_mixed_compare(self):
2322 t1 = time(1, 2, 3)
Tim Peters0bf60bd2003-01-08 20:40:01 +00002323 t2 = time(1, 2, 3)
Tim Peters60c76e42002-12-27 00:41:11 +00002324 self.assertEqual(t1, t2)
2325 t2 = t2.replace(tzinfo=None)
2326 self.assertEqual(t1, t2)
2327 t2 = t2.replace(tzinfo=FixedOffset(None, ""))
2328 self.assertEqual(t1, t2)
Tim Peters68124bb2003-02-08 03:46:31 +00002329 t2 = t2.replace(tzinfo=FixedOffset(0, ""))
2330 self.assertRaises(TypeError, lambda: t1 == t2)
Tim Peters60c76e42002-12-27 00:41:11 +00002331
Tim Peters0bf60bd2003-01-08 20:40:01 +00002332 # In time w/ identical tzinfo objects, utcoffset is ignored.
Tim Peters60c76e42002-12-27 00:41:11 +00002333 class Varies(tzinfo):
2334 def __init__(self):
Tim Peters397301e2003-01-02 21:28:08 +00002335 self.offset = timedelta(minutes=22)
Tim Peters60c76e42002-12-27 00:41:11 +00002336 def utcoffset(self, t):
Tim Peters397301e2003-01-02 21:28:08 +00002337 self.offset += timedelta(minutes=1)
Tim Peters60c76e42002-12-27 00:41:11 +00002338 return self.offset
2339
2340 v = Varies()
2341 t1 = t2.replace(tzinfo=v)
2342 t2 = t2.replace(tzinfo=v)
2343 self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
2344 self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
2345 self.assertEqual(t1, t2)
2346
2347 # But if they're not identical, it isn't ignored.
2348 t2 = t2.replace(tzinfo=Varies())
Georg Brandlab91fde2009-08-13 08:51:18 +00002349 self.assertTrue(t1 < t2) # t1's offset counter still going up
Tim Peters60c76e42002-12-27 00:41:11 +00002350
Tim Petersa98924a2003-05-17 05:55:19 +00002351 def test_subclass_timetz(self):
2352
2353 class C(self.theclass):
2354 theAnswer = 42
2355
2356 def __new__(cls, *args, **kws):
2357 temp = kws.copy()
2358 extra = temp.pop('extra')
2359 result = self.theclass.__new__(cls, *args, **temp)
2360 result.extra = extra
2361 return result
2362
2363 def newmeth(self, start):
2364 return start + self.hour + self.second
2365
2366 args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
2367
2368 dt1 = self.theclass(*args)
2369 dt2 = C(*args, **{'extra': 7})
2370
2371 self.assertEqual(dt2.__class__, C)
2372 self.assertEqual(dt2.theAnswer, 42)
2373 self.assertEqual(dt2.extra, 7)
2374 self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
2375 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
2376
Tim Peters4c0db782002-12-26 05:01:19 +00002377
Tim Peters0bf60bd2003-01-08 20:40:01 +00002378# Testing datetime objects with a non-None tzinfo.
2379
Guido van Rossumd8faa362007-04-27 19:54:29 +00002380class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
Tim Peters0bf60bd2003-01-08 20:40:01 +00002381 theclass = datetime
Tim Peters2a799bf2002-12-16 20:18:38 +00002382
2383 def test_trivial(self):
2384 dt = self.theclass(1, 2, 3, 4, 5, 6, 7)
2385 self.assertEqual(dt.year, 1)
2386 self.assertEqual(dt.month, 2)
2387 self.assertEqual(dt.day, 3)
2388 self.assertEqual(dt.hour, 4)
2389 self.assertEqual(dt.minute, 5)
2390 self.assertEqual(dt.second, 6)
2391 self.assertEqual(dt.microsecond, 7)
2392 self.assertEqual(dt.tzinfo, None)
2393
2394 def test_even_more_compare(self):
2395 # The test_compare() and test_more_compare() inherited from TestDate
2396 # and TestDateTime covered non-tzinfo cases.
2397
2398 # Smallest possible after UTC adjustment.
2399 t1 = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
2400 # Largest possible after UTC adjustment.
2401 t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
2402 tzinfo=FixedOffset(-1439, ""))
2403
2404 # Make sure those compare correctly, and w/o overflow.
Georg Brandlab91fde2009-08-13 08:51:18 +00002405 self.assertTrue(t1 < t2)
2406 self.assertTrue(t1 != t2)
2407 self.assertTrue(t2 > t1)
Tim Peters2a799bf2002-12-16 20:18:38 +00002408
Guido van Rossume61fd5b2007-07-11 12:20:59 +00002409 self.assertEqual(t1, t1)
2410 self.assertEqual(t2, t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00002411
2412 # Equal afer adjustment.
2413 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""))
2414 t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3*60+13+2, ""))
2415 self.assertEqual(t1, t2)
2416
2417 # Change t1 not to subtract a minute, and t1 should be larger.
2418 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, ""))
Georg Brandlab91fde2009-08-13 08:51:18 +00002419 self.assertTrue(t1 > t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00002420
2421 # Change t1 to subtract 2 minutes, and t1 should be smaller.
2422 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, ""))
Georg Brandlab91fde2009-08-13 08:51:18 +00002423 self.assertTrue(t1 < t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00002424
2425 # Back to the original t1, but make seconds resolve it.
2426 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
2427 second=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00002428 self.assertTrue(t1 > t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00002429
2430 # Likewise, but make microseconds resolve it.
2431 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
2432 microsecond=1)
Georg Brandlab91fde2009-08-13 08:51:18 +00002433 self.assertTrue(t1 > t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00002434
2435 # Make t2 naive and it should fail.
2436 t2 = self.theclass.min
2437 self.assertRaises(TypeError, lambda: t1 == t2)
2438 self.assertEqual(t2, t2)
2439
2440 # It's also naive if it has tzinfo but tzinfo.utcoffset() is None.
2441 class Naive(tzinfo):
2442 def utcoffset(self, dt): return None
2443 t2 = self.theclass(5, 6, 7, tzinfo=Naive())
2444 self.assertRaises(TypeError, lambda: t1 == t2)
2445 self.assertEqual(t2, t2)
2446
2447 # OTOH, it's OK to compare two of these mixing the two ways of being
2448 # naive.
2449 t1 = self.theclass(5, 6, 7)
2450 self.assertEqual(t1, t2)
2451
2452 # Try a bogus uctoffset.
2453 class Bogus(tzinfo):
Tim Peters397301e2003-01-02 21:28:08 +00002454 def utcoffset(self, dt):
2455 return timedelta(minutes=1440) # out of bounds
Tim Peters2a799bf2002-12-16 20:18:38 +00002456 t1 = self.theclass(2, 2, 2, tzinfo=Bogus())
2457 t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, ""))
Tim Peters60c76e42002-12-27 00:41:11 +00002458 self.assertRaises(ValueError, lambda: t1 == t2)
Tim Peters2a799bf2002-12-16 20:18:38 +00002459
Tim Peters2a799bf2002-12-16 20:18:38 +00002460 def test_pickling(self):
Tim Peters2a799bf2002-12-16 20:18:38 +00002461 # Try one without a tzinfo.
2462 args = 6, 7, 23, 20, 59, 1, 64**2
2463 orig = self.theclass(*args)
Guido van Rossum177e41a2003-01-30 22:06:23 +00002464 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +00002465 green = pickler.dumps(orig, proto)
2466 derived = unpickler.loads(green)
2467 self.assertEqual(orig, derived)
Tim Peters2a799bf2002-12-16 20:18:38 +00002468
2469 # Try one with a tzinfo.
Tim Petersfb8472c2002-12-21 05:04:42 +00002470 tinfo = PicklableFixedOffset(-300, 'cookie')
Tim Peters2a799bf2002-12-16 20:18:38 +00002471 orig = self.theclass(*args, **{'tzinfo': tinfo})
Tim Petersa9bc1682003-01-11 03:39:11 +00002472 derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0))
Guido van Rossum177e41a2003-01-30 22:06:23 +00002473 for pickler, unpickler, proto in pickle_choices:
Tim Peters96940c92003-01-31 21:55:33 +00002474 green = pickler.dumps(orig, proto)
2475 derived = unpickler.loads(green)
2476 self.assertEqual(orig, derived)
Georg Brandlab91fde2009-08-13 08:51:18 +00002477 self.assertTrue(isinstance(derived.tzinfo,
Tim Peters96940c92003-01-31 21:55:33 +00002478 PicklableFixedOffset))
2479 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
2480 self.assertEqual(derived.tzname(), 'cookie')
Tim Peters2a799bf2002-12-16 20:18:38 +00002481
2482 def test_extreme_hashes(self):
2483 # If an attempt is made to hash these via subtracting the offset
2484 # then hashing a datetime object, OverflowError results. The
2485 # Python implementation used to blow up here.
2486 t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
2487 hash(t)
2488 t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
2489 tzinfo=FixedOffset(-1439, ""))
2490 hash(t)
2491
2492 # OTOH, an OOB offset should blow up.
2493 t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, ""))
2494 self.assertRaises(ValueError, hash, t)
2495
2496 def test_zones(self):
2497 est = FixedOffset(-300, "EST")
2498 utc = FixedOffset(0, "UTC")
2499 met = FixedOffset(60, "MET")
Tim Peters0bf60bd2003-01-08 20:40:01 +00002500 t1 = datetime(2002, 3, 19, 7, 47, tzinfo=est)
2501 t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc)
2502 t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met)
Tim Peters2a799bf2002-12-16 20:18:38 +00002503 self.assertEqual(t1.tzinfo, est)
2504 self.assertEqual(t2.tzinfo, utc)
2505 self.assertEqual(t3.tzinfo, met)
Tim Peters855fe882002-12-22 03:43:39 +00002506 self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
2507 self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
2508 self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
Tim Peters2a799bf2002-12-16 20:18:38 +00002509 self.assertEqual(t1.tzname(), "EST")
2510 self.assertEqual(t2.tzname(), "UTC")
2511 self.assertEqual(t3.tzname(), "MET")
2512 self.assertEqual(hash(t1), hash(t2))
2513 self.assertEqual(hash(t1), hash(t3))
2514 self.assertEqual(hash(t2), hash(t3))
2515 self.assertEqual(t1, t2)
2516 self.assertEqual(t1, t3)
2517 self.assertEqual(t2, t3)
2518 self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00")
2519 self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00")
2520 self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00")
Tim Peters0bf60bd2003-01-08 20:40:01 +00002521 d = 'datetime.datetime(2002, 3, 19, '
Tim Peters2a799bf2002-12-16 20:18:38 +00002522 self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)")
2523 self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)")
2524 self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)")
2525
2526 def test_combine(self):
2527 met = FixedOffset(60, "MET")
2528 d = date(2002, 3, 4)
Tim Peters0bf60bd2003-01-08 20:40:01 +00002529 tz = time(18, 45, 3, 1234, tzinfo=met)
2530 dt = datetime.combine(d, tz)
2531 self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234,
Tim Peters2a799bf2002-12-16 20:18:38 +00002532 tzinfo=met))
2533
2534 def test_extract(self):
2535 met = FixedOffset(60, "MET")
2536 dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met)
2537 self.assertEqual(dt.date(), date(2002, 3, 4))
2538 self.assertEqual(dt.time(), time(18, 45, 3, 1234))
Tim Peters0bf60bd2003-01-08 20:40:01 +00002539 self.assertEqual(dt.timetz(), time(18, 45, 3, 1234, tzinfo=met))
Tim Peters2a799bf2002-12-16 20:18:38 +00002540
2541 def test_tz_aware_arithmetic(self):
2542 import random
2543
2544 now = self.theclass.now()
2545 tz55 = FixedOffset(-330, "west 5:30")
Tim Peters0bf60bd2003-01-08 20:40:01 +00002546 timeaware = now.time().replace(tzinfo=tz55)
Tim Peters2a799bf2002-12-16 20:18:38 +00002547 nowaware = self.theclass.combine(now.date(), timeaware)
Georg Brandlab91fde2009-08-13 08:51:18 +00002548 self.assertTrue(nowaware.tzinfo is tz55)
Tim Peters2a799bf2002-12-16 20:18:38 +00002549 self.assertEqual(nowaware.timetz(), timeaware)
2550
2551 # Can't mix aware and non-aware.
2552 self.assertRaises(TypeError, lambda: now - nowaware)
2553 self.assertRaises(TypeError, lambda: nowaware - now)
2554
Tim Peters0bf60bd2003-01-08 20:40:01 +00002555 # And adding datetime's doesn't make sense, aware or not.
Tim Peters2a799bf2002-12-16 20:18:38 +00002556 self.assertRaises(TypeError, lambda: now + nowaware)
2557 self.assertRaises(TypeError, lambda: nowaware + now)
2558 self.assertRaises(TypeError, lambda: nowaware + nowaware)
2559
2560 # Subtracting should yield 0.
2561 self.assertEqual(now - now, timedelta(0))
2562 self.assertEqual(nowaware - nowaware, timedelta(0))
2563
2564 # Adding a delta should preserve tzinfo.
2565 delta = timedelta(weeks=1, minutes=12, microseconds=5678)
2566 nowawareplus = nowaware + delta
Georg Brandlab91fde2009-08-13 08:51:18 +00002567 self.assertTrue(nowaware.tzinfo is tz55)
Tim Peters2a799bf2002-12-16 20:18:38 +00002568 nowawareplus2 = delta + nowaware
Georg Brandlab91fde2009-08-13 08:51:18 +00002569 self.assertTrue(nowawareplus2.tzinfo is tz55)
Tim Peters2a799bf2002-12-16 20:18:38 +00002570 self.assertEqual(nowawareplus, nowawareplus2)
2571
2572 # that - delta should be what we started with, and that - what we
2573 # started with should be delta.
2574 diff = nowawareplus - delta
Georg Brandlab91fde2009-08-13 08:51:18 +00002575 self.assertTrue(diff.tzinfo is tz55)
Tim Peters2a799bf2002-12-16 20:18:38 +00002576 self.assertEqual(nowaware, diff)
2577 self.assertRaises(TypeError, lambda: delta - nowawareplus)
2578 self.assertEqual(nowawareplus - nowaware, delta)
2579
2580 # Make up a random timezone.
2581 tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
Tim Peters4c0db782002-12-26 05:01:19 +00002582 # Attach it to nowawareplus.
2583 nowawareplus = nowawareplus.replace(tzinfo=tzr)
Georg Brandlab91fde2009-08-13 08:51:18 +00002584 self.assertTrue(nowawareplus.tzinfo is tzr)
Tim Peters2a799bf2002-12-16 20:18:38 +00002585 # Make sure the difference takes the timezone adjustments into account.
2586 got = nowaware - nowawareplus
2587 # Expected: (nowaware base - nowaware offset) -
2588 # (nowawareplus base - nowawareplus offset) =
2589 # (nowaware base - nowawareplus base) +
2590 # (nowawareplus offset - nowaware offset) =
2591 # -delta + nowawareplus offset - nowaware offset
Tim Peters855fe882002-12-22 03:43:39 +00002592 expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
Tim Peters2a799bf2002-12-16 20:18:38 +00002593 self.assertEqual(got, expected)
2594
2595 # Try max possible difference.
2596 min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
2597 max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
2598 tzinfo=FixedOffset(-1439, "max"))
2599 maxdiff = max - min
2600 self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
2601 timedelta(minutes=2*1439))
2602
2603 def test_tzinfo_now(self):
2604 meth = self.theclass.now
2605 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2606 base = meth()
2607 # Try with and without naming the keyword.
2608 off42 = FixedOffset(42, "42")
2609 another = meth(off42)
Tim Peters10cadce2003-01-23 19:58:02 +00002610 again = meth(tz=off42)
Georg Brandlab91fde2009-08-13 08:51:18 +00002611 self.assertTrue(another.tzinfo is again.tzinfo)
Tim Peters855fe882002-12-22 03:43:39 +00002612 self.assertEqual(another.utcoffset(), timedelta(minutes=42))
Tim Peters2a799bf2002-12-16 20:18:38 +00002613 # Bad argument with and w/o naming the keyword.
2614 self.assertRaises(TypeError, meth, 16)
2615 self.assertRaises(TypeError, meth, tzinfo=16)
2616 # Bad keyword name.
2617 self.assertRaises(TypeError, meth, tinfo=off42)
2618 # Too many args.
2619 self.assertRaises(TypeError, meth, off42, off42)
2620
Tim Peters10cadce2003-01-23 19:58:02 +00002621 # We don't know which time zone we're in, and don't have a tzinfo
2622 # class to represent it, so seeing whether a tz argument actually
2623 # does a conversion is tricky.
2624 weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
2625 utc = FixedOffset(0, "utc", 0)
2626 for dummy in range(3):
2627 now = datetime.now(weirdtz)
Georg Brandlab91fde2009-08-13 08:51:18 +00002628 self.assertTrue(now.tzinfo is weirdtz)
Tim Peters10cadce2003-01-23 19:58:02 +00002629 utcnow = datetime.utcnow().replace(tzinfo=utc)
2630 now2 = utcnow.astimezone(weirdtz)
2631 if abs(now - now2) < timedelta(seconds=30):
2632 break
2633 # Else the code is broken, or more than 30 seconds passed between
2634 # calls; assuming the latter, just try again.
2635 else:
2636 # Three strikes and we're out.
2637 self.fail("utcnow(), now(tz), or astimezone() may be broken")
2638
Tim Peters2a799bf2002-12-16 20:18:38 +00002639 def test_tzinfo_fromtimestamp(self):
2640 import time
2641 meth = self.theclass.fromtimestamp
2642 ts = time.time()
2643 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2644 base = meth(ts)
2645 # Try with and without naming the keyword.
2646 off42 = FixedOffset(42, "42")
2647 another = meth(ts, off42)
Tim Peters2a44a8d2003-01-23 20:53:10 +00002648 again = meth(ts, tz=off42)
Georg Brandlab91fde2009-08-13 08:51:18 +00002649 self.assertTrue(another.tzinfo is again.tzinfo)
Tim Peters855fe882002-12-22 03:43:39 +00002650 self.assertEqual(another.utcoffset(), timedelta(minutes=42))
Tim Peters2a799bf2002-12-16 20:18:38 +00002651 # Bad argument with and w/o naming the keyword.
2652 self.assertRaises(TypeError, meth, ts, 16)
2653 self.assertRaises(TypeError, meth, ts, tzinfo=16)
2654 # Bad keyword name.
2655 self.assertRaises(TypeError, meth, ts, tinfo=off42)
2656 # Too many args.
2657 self.assertRaises(TypeError, meth, ts, off42, off42)
2658 # Too few args.
2659 self.assertRaises(TypeError, meth)
2660
Tim Peters2a44a8d2003-01-23 20:53:10 +00002661 # Try to make sure tz= actually does some conversion.
Tim Peters84407612003-02-06 16:42:14 +00002662 timestamp = 1000000000
2663 utcdatetime = datetime.utcfromtimestamp(timestamp)
2664 # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
2665 # But on some flavor of Mac, it's nowhere near that. So we can't have
2666 # any idea here what time that actually is, we can only test that
2667 # relative changes match.
2668 utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
2669 tz = FixedOffset(utcoffset, "tz", 0)
2670 expected = utcdatetime + utcoffset
2671 got = datetime.fromtimestamp(timestamp, tz)
2672 self.assertEqual(expected, got.replace(tzinfo=None))
Tim Peters2a44a8d2003-01-23 20:53:10 +00002673
Tim Peters2a799bf2002-12-16 20:18:38 +00002674 def test_tzinfo_utcnow(self):
2675 meth = self.theclass.utcnow
2676 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2677 base = meth()
2678 # Try with and without naming the keyword; for whatever reason,
2679 # utcnow() doesn't accept a tzinfo argument.
2680 off42 = FixedOffset(42, "42")
2681 self.assertRaises(TypeError, meth, off42)
2682 self.assertRaises(TypeError, meth, tzinfo=off42)
2683
2684 def test_tzinfo_utcfromtimestamp(self):
2685 import time
2686 meth = self.theclass.utcfromtimestamp
2687 ts = time.time()
2688 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2689 base = meth(ts)
2690 # Try with and without naming the keyword; for whatever reason,
2691 # utcfromtimestamp() doesn't accept a tzinfo argument.
2692 off42 = FixedOffset(42, "42")
2693 self.assertRaises(TypeError, meth, ts, off42)
2694 self.assertRaises(TypeError, meth, ts, tzinfo=off42)
2695
2696 def test_tzinfo_timetuple(self):
Tim Peters0bf60bd2003-01-08 20:40:01 +00002697 # TestDateTime tested most of this. datetime adds a twist to the
Tim Peters2a799bf2002-12-16 20:18:38 +00002698 # DST flag.
2699 class DST(tzinfo):
2700 def __init__(self, dstvalue):
Tim Peters397301e2003-01-02 21:28:08 +00002701 if isinstance(dstvalue, int):
2702 dstvalue = timedelta(minutes=dstvalue)
Tim Peters2a799bf2002-12-16 20:18:38 +00002703 self.dstvalue = dstvalue
2704 def dst(self, dt):
2705 return self.dstvalue
2706
2707 cls = self.theclass
2708 for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1):
2709 d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue))
2710 t = d.timetuple()
2711 self.assertEqual(1, t.tm_year)
2712 self.assertEqual(1, t.tm_mon)
2713 self.assertEqual(1, t.tm_mday)
2714 self.assertEqual(10, t.tm_hour)
2715 self.assertEqual(20, t.tm_min)
2716 self.assertEqual(30, t.tm_sec)
2717 self.assertEqual(0, t.tm_wday)
2718 self.assertEqual(1, t.tm_yday)
2719 self.assertEqual(flag, t.tm_isdst)
2720
2721 # dst() returns wrong type.
2722 self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple)
2723
2724 # dst() at the edge.
2725 self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1)
2726 self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1)
2727
2728 # dst() out of range.
2729 self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple)
2730 self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple)
2731
2732 def test_utctimetuple(self):
2733 class DST(tzinfo):
2734 def __init__(self, dstvalue):
Tim Peters397301e2003-01-02 21:28:08 +00002735 if isinstance(dstvalue, int):
2736 dstvalue = timedelta(minutes=dstvalue)
Tim Peters2a799bf2002-12-16 20:18:38 +00002737 self.dstvalue = dstvalue
2738 def dst(self, dt):
2739 return self.dstvalue
2740
2741 cls = self.theclass
2742 # This can't work: DST didn't implement utcoffset.
2743 self.assertRaises(NotImplementedError,
2744 cls(1, 1, 1, tzinfo=DST(0)).utcoffset)
2745
2746 class UOFS(DST):
2747 def __init__(self, uofs, dofs=None):
2748 DST.__init__(self, dofs)
Tim Peters397301e2003-01-02 21:28:08 +00002749 self.uofs = timedelta(minutes=uofs)
Tim Peters2a799bf2002-12-16 20:18:38 +00002750 def utcoffset(self, dt):
2751 return self.uofs
2752
2753 # Ensure tm_isdst is 0 regardless of what dst() says: DST is never
2754 # in effect for a UTC time.
2755 for dstvalue in -33, 33, 0, None:
2756 d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=UOFS(-53, dstvalue))
2757 t = d.utctimetuple()
2758 self.assertEqual(d.year, t.tm_year)
2759 self.assertEqual(d.month, t.tm_mon)
2760 self.assertEqual(d.day, t.tm_mday)
2761 self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm
2762 self.assertEqual(13, t.tm_min)
2763 self.assertEqual(d.second, t.tm_sec)
2764 self.assertEqual(d.weekday(), t.tm_wday)
2765 self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1,
2766 t.tm_yday)
2767 self.assertEqual(0, t.tm_isdst)
2768
2769 # At the edges, UTC adjustment can normalize into years out-of-range
2770 # for a datetime object. Ensure that a correct timetuple is
2771 # created anyway.
2772 tiny = cls(MINYEAR, 1, 1, 0, 0, 37, tzinfo=UOFS(1439))
2773 # That goes back 1 minute less than a full day.
2774 t = tiny.utctimetuple()
2775 self.assertEqual(t.tm_year, MINYEAR-1)
2776 self.assertEqual(t.tm_mon, 12)
2777 self.assertEqual(t.tm_mday, 31)
2778 self.assertEqual(t.tm_hour, 0)
2779 self.assertEqual(t.tm_min, 1)
2780 self.assertEqual(t.tm_sec, 37)
2781 self.assertEqual(t.tm_yday, 366) # "year 0" is a leap year
2782 self.assertEqual(t.tm_isdst, 0)
2783
2784 huge = cls(MAXYEAR, 12, 31, 23, 59, 37, 999999, tzinfo=UOFS(-1439))
2785 # That goes forward 1 minute less than a full day.
2786 t = huge.utctimetuple()
2787 self.assertEqual(t.tm_year, MAXYEAR+1)
2788 self.assertEqual(t.tm_mon, 1)
2789 self.assertEqual(t.tm_mday, 1)
2790 self.assertEqual(t.tm_hour, 23)
2791 self.assertEqual(t.tm_min, 58)
2792 self.assertEqual(t.tm_sec, 37)
2793 self.assertEqual(t.tm_yday, 1)
2794 self.assertEqual(t.tm_isdst, 0)
2795
2796 def test_tzinfo_isoformat(self):
2797 zero = FixedOffset(0, "+00:00")
2798 plus = FixedOffset(220, "+03:40")
2799 minus = FixedOffset(-231, "-03:51")
2800 unknown = FixedOffset(None, "")
2801
2802 cls = self.theclass
2803 datestr = '0001-02-03'
2804 for ofs in None, zero, plus, minus, unknown:
Tim Peters6578dc92002-12-24 18:31:27 +00002805 for us in 0, 987001:
Tim Peters2a799bf2002-12-16 20:18:38 +00002806 d = cls(1, 2, 3, 4, 5, 59, us, tzinfo=ofs)
2807 timestr = '04:05:59' + (us and '.987001' or '')
2808 ofsstr = ofs is not None and d.tzname() or ''
2809 tailstr = timestr + ofsstr
2810 iso = d.isoformat()
2811 self.assertEqual(iso, datestr + 'T' + tailstr)
2812 self.assertEqual(iso, d.isoformat('T'))
2813 self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr)
Walter Dörwaldbc1f8862007-06-20 11:02:38 +00002814 self.assertEqual(d.isoformat('\u1234'), datestr + '\u1234' + tailstr)
Tim Peters2a799bf2002-12-16 20:18:38 +00002815 self.assertEqual(str(d), datestr + ' ' + tailstr)
2816
Tim Peters12bf3392002-12-24 05:41:27 +00002817 def test_replace(self):
2818 cls = self.theclass
2819 z100 = FixedOffset(100, "+100")
2820 zm200 = FixedOffset(timedelta(minutes=-200), "-200")
2821 args = [1, 2, 3, 4, 5, 6, 7, z100]
2822 base = cls(*args)
2823 self.assertEqual(base, base.replace())
2824
2825 i = 0
2826 for name, newval in (("year", 2),
2827 ("month", 3),
2828 ("day", 4),
2829 ("hour", 5),
2830 ("minute", 6),
2831 ("second", 7),
2832 ("microsecond", 8),
2833 ("tzinfo", zm200)):
2834 newargs = args[:]
2835 newargs[i] = newval
2836 expected = cls(*newargs)
2837 got = base.replace(**{name: newval})
2838 self.assertEqual(expected, got)
2839 i += 1
2840
2841 # Ensure we can get rid of a tzinfo.
2842 self.assertEqual(base.tzname(), "+100")
2843 base2 = base.replace(tzinfo=None)
Georg Brandlab91fde2009-08-13 08:51:18 +00002844 self.assertTrue(base2.tzinfo is None)
2845 self.assertTrue(base2.tzname() is None)
Tim Peters12bf3392002-12-24 05:41:27 +00002846
2847 # Ensure we can add one.
2848 base3 = base2.replace(tzinfo=z100)
2849 self.assertEqual(base, base3)
Georg Brandlab91fde2009-08-13 08:51:18 +00002850 self.assertTrue(base.tzinfo is base3.tzinfo)
Tim Peters12bf3392002-12-24 05:41:27 +00002851
2852 # Out of bounds.
2853 base = cls(2000, 2, 29)
2854 self.assertRaises(ValueError, base.replace, year=2001)
Tim Peters2a799bf2002-12-16 20:18:38 +00002855
Tim Peters80475bb2002-12-25 07:40:55 +00002856 def test_more_astimezone(self):
2857 # The inherited test_astimezone covered some trivial and error cases.
2858 fnone = FixedOffset(None, "None")
2859 f44m = FixedOffset(44, "44")
2860 fm5h = FixedOffset(-timedelta(hours=5), "m300")
2861
Tim Peters10cadce2003-01-23 19:58:02 +00002862 dt = self.theclass.now(tz=f44m)
Georg Brandlab91fde2009-08-13 08:51:18 +00002863 self.assertTrue(dt.tzinfo is f44m)
Tim Peters52dcce22003-01-23 16:36:11 +00002864 # Replacing with degenerate tzinfo raises an exception.
2865 self.assertRaises(ValueError, dt.astimezone, fnone)
2866 # Ditto with None tz.
2867 self.assertRaises(TypeError, dt.astimezone, None)
2868 # Replacing with same tzinfo makes no change.
Tim Peters80475bb2002-12-25 07:40:55 +00002869 x = dt.astimezone(dt.tzinfo)
Georg Brandlab91fde2009-08-13 08:51:18 +00002870 self.assertTrue(x.tzinfo is f44m)
Tim Peters80475bb2002-12-25 07:40:55 +00002871 self.assertEqual(x.date(), dt.date())
2872 self.assertEqual(x.time(), dt.time())
2873
2874 # Replacing with different tzinfo does adjust.
2875 got = dt.astimezone(fm5h)
Georg Brandlab91fde2009-08-13 08:51:18 +00002876 self.assertTrue(got.tzinfo is fm5h)
Tim Peters80475bb2002-12-25 07:40:55 +00002877 self.assertEqual(got.utcoffset(), timedelta(hours=-5))
2878 expected = dt - dt.utcoffset() # in effect, convert to UTC
2879 expected += fm5h.utcoffset(dt) # and from there to local time
2880 expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo
2881 self.assertEqual(got.date(), expected.date())
2882 self.assertEqual(got.time(), expected.time())
2883 self.assertEqual(got.timetz(), expected.timetz())
Georg Brandlab91fde2009-08-13 08:51:18 +00002884 self.assertTrue(got.tzinfo is expected.tzinfo)
Tim Peters80475bb2002-12-25 07:40:55 +00002885 self.assertEqual(got, expected)
2886
Tim Peters4c0db782002-12-26 05:01:19 +00002887 def test_aware_subtract(self):
2888 cls = self.theclass
2889
Tim Peters60c76e42002-12-27 00:41:11 +00002890 # Ensure that utcoffset() is ignored when the operands have the
2891 # same tzinfo member.
Tim Peters4c0db782002-12-26 05:01:19 +00002892 class OperandDependentOffset(tzinfo):
2893 def utcoffset(self, t):
2894 if t.minute < 10:
Tim Peters397301e2003-01-02 21:28:08 +00002895 # d0 and d1 equal after adjustment
2896 return timedelta(minutes=t.minute)
Tim Peters4c0db782002-12-26 05:01:19 +00002897 else:
Tim Peters397301e2003-01-02 21:28:08 +00002898 # d2 off in the weeds
2899 return timedelta(minutes=59)
Tim Peters4c0db782002-12-26 05:01:19 +00002900
2901 base = cls(8, 9, 10, 11, 12, 13, 14, tzinfo=OperandDependentOffset())
2902 d0 = base.replace(minute=3)
2903 d1 = base.replace(minute=9)
2904 d2 = base.replace(minute=11)
2905 for x in d0, d1, d2:
2906 for y in d0, d1, d2:
2907 got = x - y
Tim Peters60c76e42002-12-27 00:41:11 +00002908 expected = timedelta(minutes=x.minute - y.minute)
2909 self.assertEqual(got, expected)
2910
2911 # OTOH, if the tzinfo members are distinct, utcoffsets aren't
2912 # ignored.
2913 base = cls(8, 9, 10, 11, 12, 13, 14)
2914 d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
2915 d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
2916 d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
2917 for x in d0, d1, d2:
2918 for y in d0, d1, d2:
2919 got = x - y
Tim Peters4c0db782002-12-26 05:01:19 +00002920 if (x is d0 or x is d1) and (y is d0 or y is d1):
2921 expected = timedelta(0)
2922 elif x is y is d2:
2923 expected = timedelta(0)
2924 elif x is d2:
2925 expected = timedelta(minutes=(11-59)-0)
2926 else:
2927 assert y is d2
2928 expected = timedelta(minutes=0-(11-59))
2929 self.assertEqual(got, expected)
2930
Tim Peters60c76e42002-12-27 00:41:11 +00002931 def test_mixed_compare(self):
2932 t1 = datetime(1, 2, 3, 4, 5, 6, 7)
Tim Peters0bf60bd2003-01-08 20:40:01 +00002933 t2 = datetime(1, 2, 3, 4, 5, 6, 7)
Tim Peters60c76e42002-12-27 00:41:11 +00002934 self.assertEqual(t1, t2)
2935 t2 = t2.replace(tzinfo=None)
2936 self.assertEqual(t1, t2)
2937 t2 = t2.replace(tzinfo=FixedOffset(None, ""))
2938 self.assertEqual(t1, t2)
Tim Peters68124bb2003-02-08 03:46:31 +00002939 t2 = t2.replace(tzinfo=FixedOffset(0, ""))
2940 self.assertRaises(TypeError, lambda: t1 == t2)
Tim Peters60c76e42002-12-27 00:41:11 +00002941
Tim Peters0bf60bd2003-01-08 20:40:01 +00002942 # In datetime w/ identical tzinfo objects, utcoffset is ignored.
Tim Peters60c76e42002-12-27 00:41:11 +00002943 class Varies(tzinfo):
2944 def __init__(self):
Tim Peters397301e2003-01-02 21:28:08 +00002945 self.offset = timedelta(minutes=22)
Tim Peters60c76e42002-12-27 00:41:11 +00002946 def utcoffset(self, t):
Tim Peters397301e2003-01-02 21:28:08 +00002947 self.offset += timedelta(minutes=1)
Tim Peters60c76e42002-12-27 00:41:11 +00002948 return self.offset
2949
2950 v = Varies()
2951 t1 = t2.replace(tzinfo=v)
2952 t2 = t2.replace(tzinfo=v)
2953 self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
2954 self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
2955 self.assertEqual(t1, t2)
2956
2957 # But if they're not identical, it isn't ignored.
2958 t2 = t2.replace(tzinfo=Varies())
Georg Brandlab91fde2009-08-13 08:51:18 +00002959 self.assertTrue(t1 < t2) # t1's offset counter still going up
Tim Peters80475bb2002-12-25 07:40:55 +00002960
Tim Petersa98924a2003-05-17 05:55:19 +00002961 def test_subclass_datetimetz(self):
2962
2963 class C(self.theclass):
2964 theAnswer = 42
2965
2966 def __new__(cls, *args, **kws):
2967 temp = kws.copy()
2968 extra = temp.pop('extra')
2969 result = self.theclass.__new__(cls, *args, **temp)
2970 result.extra = extra
2971 return result
2972
2973 def newmeth(self, start):
2974 return start + self.hour + self.year
2975
2976 args = 2002, 12, 31, 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
2977
2978 dt1 = self.theclass(*args)
2979 dt2 = C(*args, **{'extra': 7})
2980
2981 self.assertEqual(dt2.__class__, C)
2982 self.assertEqual(dt2.theAnswer, 42)
2983 self.assertEqual(dt2.extra, 7)
2984 self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
2985 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.year - 7)
2986
Tim Peters621818b2002-12-29 23:44:49 +00002987# Pain to set up DST-aware tzinfo classes.
2988
2989def first_sunday_on_or_after(dt):
2990 days_to_go = 6 - dt.weekday()
2991 if days_to_go:
2992 dt += timedelta(days_to_go)
2993 return dt
2994
2995ZERO = timedelta(0)
2996HOUR = timedelta(hours=1)
2997DAY = timedelta(days=1)
2998# In the US, DST starts at 2am (standard time) on the first Sunday in April.
2999DSTSTART = datetime(1, 4, 1, 2)
3000# and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct,
Tim Peters327098a2003-01-20 22:54:38 +00003001# which is the first Sunday on or after Oct 25. Because we view 1:MM as
3002# being standard time on that day, there is no spelling in local time of
3003# the last hour of DST (that's 1:MM DST, but 1:MM is taken as standard time).
3004DSTEND = datetime(1, 10, 25, 1)
Tim Peters621818b2002-12-29 23:44:49 +00003005
3006class USTimeZone(tzinfo):
3007
3008 def __init__(self, hours, reprname, stdname, dstname):
3009 self.stdoffset = timedelta(hours=hours)
3010 self.reprname = reprname
3011 self.stdname = stdname
3012 self.dstname = dstname
3013
3014 def __repr__(self):
3015 return self.reprname
3016
3017 def tzname(self, dt):
3018 if self.dst(dt):
3019 return self.dstname
3020 else:
3021 return self.stdname
3022
3023 def utcoffset(self, dt):
3024 return self.stdoffset + self.dst(dt)
3025
3026 def dst(self, dt):
Tim Petersbad8ff02002-12-30 20:52:32 +00003027 if dt is None or dt.tzinfo is None:
Tim Peters621818b2002-12-29 23:44:49 +00003028 # An exception instead may be sensible here, in one or more of
3029 # the cases.
3030 return ZERO
Tim Peters521fc152002-12-31 17:36:56 +00003031 assert dt.tzinfo is self
Tim Peters621818b2002-12-29 23:44:49 +00003032
3033 # Find first Sunday in April.
3034 start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
3035 assert start.weekday() == 6 and start.month == 4 and start.day <= 7
3036
3037 # Find last Sunday in October.
3038 end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
3039 assert end.weekday() == 6 and end.month == 10 and end.day >= 25
3040
Tim Peters621818b2002-12-29 23:44:49 +00003041 # Can't compare naive to aware objects, so strip the timezone from
3042 # dt first.
Tim Peters52dcce22003-01-23 16:36:11 +00003043 if start <= dt.replace(tzinfo=None) < end:
Tim Peters621818b2002-12-29 23:44:49 +00003044 return HOUR
3045 else:
3046 return ZERO
3047
Tim Peters521fc152002-12-31 17:36:56 +00003048Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
3049Central = USTimeZone(-6, "Central", "CST", "CDT")
3050Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
3051Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
Tim Peters1024bf82002-12-30 17:09:40 +00003052utc_real = FixedOffset(0, "UTC", 0)
3053# For better test coverage, we want another flavor of UTC that's west of
3054# the Eastern and Pacific timezones.
Tim Petersadf64202003-01-04 06:03:15 +00003055utc_fake = FixedOffset(-12*60, "UTCfake", 0)
Tim Peters621818b2002-12-29 23:44:49 +00003056
3057class TestTimezoneConversions(unittest.TestCase):
Tim Peters327098a2003-01-20 22:54:38 +00003058 # The DST switch times for 2002, in std time.
Tim Peters0bf60bd2003-01-08 20:40:01 +00003059 dston = datetime(2002, 4, 7, 2)
Tim Peters327098a2003-01-20 22:54:38 +00003060 dstoff = datetime(2002, 10, 27, 1)
Tim Peters621818b2002-12-29 23:44:49 +00003061
Tim Peters0bf60bd2003-01-08 20:40:01 +00003062 theclass = datetime
Tim Peters710fb152003-01-02 19:35:54 +00003063
Tim Peters521fc152002-12-31 17:36:56 +00003064 # Check a time that's inside DST.
3065 def checkinside(self, dt, tz, utc, dston, dstoff):
3066 self.assertEqual(dt.dst(), HOUR)
3067
3068 # Conversion to our own timezone is always an identity.
3069 self.assertEqual(dt.astimezone(tz), dt)
Tim Peters521fc152002-12-31 17:36:56 +00003070
3071 asutc = dt.astimezone(utc)
3072 there_and_back = asutc.astimezone(tz)
3073
3074 # Conversion to UTC and back isn't always an identity here,
3075 # because there are redundant spellings (in local time) of
3076 # UTC time when DST begins: the clock jumps from 1:59:59
3077 # to 3:00:00, and a local time of 2:MM:SS doesn't really
3078 # make sense then. The classes above treat 2:MM:SS as
3079 # daylight time then (it's "after 2am"), really an alias
3080 # for 1:MM:SS standard time. The latter form is what
3081 # conversion back from UTC produces.
3082 if dt.date() == dston.date() and dt.hour == 2:
3083 # We're in the redundant hour, and coming back from
3084 # UTC gives the 1:MM:SS standard-time spelling.
3085 self.assertEqual(there_and_back + HOUR, dt)
3086 # Although during was considered to be in daylight
3087 # time, there_and_back is not.
3088 self.assertEqual(there_and_back.dst(), ZERO)
3089 # They're the same times in UTC.
3090 self.assertEqual(there_and_back.astimezone(utc),
3091 dt.astimezone(utc))
3092 else:
3093 # We're not in the redundant hour.
3094 self.assertEqual(dt, there_and_back)
3095
Tim Peters327098a2003-01-20 22:54:38 +00003096 # Because we have a redundant spelling when DST begins, there is
3097 # (unforunately) an hour when DST ends that can't be spelled at all in
3098 # local time. When DST ends, the clock jumps from 1:59 back to 1:00
3099 # again. The hour 1:MM DST has no spelling then: 1:MM is taken to be
3100 # standard time. 1:MM DST == 0:MM EST, but 0:MM is taken to be
3101 # daylight time. The hour 1:MM daylight == 0:MM standard can't be
3102 # expressed in local time. Nevertheless, we want conversion back
3103 # from UTC to mimic the local clock's "repeat an hour" behavior.
Tim Peters521fc152002-12-31 17:36:56 +00003104 nexthour_utc = asutc + HOUR
Tim Petersadf64202003-01-04 06:03:15 +00003105 nexthour_tz = nexthour_utc.astimezone(tz)
Tim Peters327098a2003-01-20 22:54:38 +00003106 if dt.date() == dstoff.date() and dt.hour == 0:
3107 # We're in the hour before the last DST hour. The last DST hour
Tim Petersadf64202003-01-04 06:03:15 +00003108 # is ineffable. We want the conversion back to repeat 1:MM.
Tim Peters327098a2003-01-20 22:54:38 +00003109 self.assertEqual(nexthour_tz, dt.replace(hour=1))
3110 nexthour_utc += HOUR
3111 nexthour_tz = nexthour_utc.astimezone(tz)
3112 self.assertEqual(nexthour_tz, dt.replace(hour=1))
Tim Peters521fc152002-12-31 17:36:56 +00003113 else:
Tim Peters327098a2003-01-20 22:54:38 +00003114 self.assertEqual(nexthour_tz - dt, HOUR)
Tim Peters521fc152002-12-31 17:36:56 +00003115
3116 # Check a time that's outside DST.
3117 def checkoutside(self, dt, tz, utc):
3118 self.assertEqual(dt.dst(), ZERO)
3119
3120 # Conversion to our own timezone is always an identity.
3121 self.assertEqual(dt.astimezone(tz), dt)
Tim Peters52dcce22003-01-23 16:36:11 +00003122
3123 # Converting to UTC and back is an identity too.
3124 asutc = dt.astimezone(utc)
3125 there_and_back = asutc.astimezone(tz)
3126 self.assertEqual(dt, there_and_back)
Tim Peters521fc152002-12-31 17:36:56 +00003127
Tim Peters1024bf82002-12-30 17:09:40 +00003128 def convert_between_tz_and_utc(self, tz, utc):
3129 dston = self.dston.replace(tzinfo=tz)
Tim Peters327098a2003-01-20 22:54:38 +00003130 # Because 1:MM on the day DST ends is taken as being standard time,
3131 # there is no spelling in tz for the last hour of daylight time.
3132 # For purposes of the test, the last hour of DST is 0:MM, which is
3133 # taken as being daylight time (and 1:MM is taken as being standard
3134 # time).
Tim Peters1024bf82002-12-30 17:09:40 +00003135 dstoff = self.dstoff.replace(tzinfo=tz)
3136 for delta in (timedelta(weeks=13),
3137 DAY,
3138 HOUR,
3139 timedelta(minutes=1),
3140 timedelta(microseconds=1)):
3141
Tim Peters521fc152002-12-31 17:36:56 +00003142 self.checkinside(dston, tz, utc, dston, dstoff)
3143 for during in dston + delta, dstoff - delta:
3144 self.checkinside(during, tz, utc, dston, dstoff)
Tim Peters31cc3152002-12-30 17:37:30 +00003145
Tim Peters521fc152002-12-31 17:36:56 +00003146 self.checkoutside(dstoff, tz, utc)
3147 for outside in dston - delta, dstoff + delta:
3148 self.checkoutside(outside, tz, utc)
Tim Peters31cc3152002-12-30 17:37:30 +00003149
Tim Peters621818b2002-12-29 23:44:49 +00003150 def test_easy(self):
3151 # Despite the name of this test, the endcases are excruciating.
Tim Peters1024bf82002-12-30 17:09:40 +00003152 self.convert_between_tz_and_utc(Eastern, utc_real)
3153 self.convert_between_tz_and_utc(Pacific, utc_real)
3154 self.convert_between_tz_and_utc(Eastern, utc_fake)
3155 self.convert_between_tz_and_utc(Pacific, utc_fake)
3156 # The next is really dancing near the edge. It works because
3157 # Pacific and Eastern are far enough apart that their "problem
3158 # hours" don't overlap.
3159 self.convert_between_tz_and_utc(Eastern, Pacific)
3160 self.convert_between_tz_and_utc(Pacific, Eastern)
Tim Peters36087ed2003-01-01 04:18:51 +00003161 # OTOH, these fail! Don't enable them. The difficulty is that
3162 # the edge case tests assume that every hour is representable in
3163 # the "utc" class. This is always true for a fixed-offset tzinfo
3164 # class (lke utc_real and utc_fake), but not for Eastern or Central.
3165 # For these adjacent DST-aware time zones, the range of time offsets
3166 # tested ends up creating hours in the one that aren't representable
3167 # in the other. For the same reason, we would see failures in the
3168 # Eastern vs Pacific tests too if we added 3*HOUR to the list of
3169 # offset deltas in convert_between_tz_and_utc().
3170 #
3171 # self.convert_between_tz_and_utc(Eastern, Central) # can't work
3172 # self.convert_between_tz_and_utc(Central, Eastern) # can't work
Tim Peters621818b2002-12-29 23:44:49 +00003173
Tim Petersf3615152003-01-01 21:51:37 +00003174 def test_tricky(self):
3175 # 22:00 on day before daylight starts.
3176 fourback = self.dston - timedelta(hours=4)
3177 ninewest = FixedOffset(-9*60, "-0900", 0)
Tim Peters52dcce22003-01-23 16:36:11 +00003178 fourback = fourback.replace(tzinfo=ninewest)
Tim Petersf3615152003-01-01 21:51:37 +00003179 # 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST. Since it's "after
3180 # 2", we should get the 3 spelling.
3181 # If we plug 22:00 the day before into Eastern, it "looks like std
3182 # time", so its offset is returned as -5, and -5 - -9 = 4. Adding 4
3183 # to 22:00 lands on 2:00, which makes no sense in local time (the
3184 # local clock jumps from 1 to 3). The point here is to make sure we
3185 # get the 3 spelling.
3186 expected = self.dston.replace(hour=3)
Tim Peters52dcce22003-01-23 16:36:11 +00003187 got = fourback.astimezone(Eastern).replace(tzinfo=None)
Tim Petersf3615152003-01-01 21:51:37 +00003188 self.assertEqual(expected, got)
3189
3190 # Similar, but map to 6:00 UTC == 1:00 EST == 2:00 DST. In that
3191 # case we want the 1:00 spelling.
Tim Peters52dcce22003-01-23 16:36:11 +00003192 sixutc = self.dston.replace(hour=6, tzinfo=utc_real)
Tim Petersf3615152003-01-01 21:51:37 +00003193 # Now 6:00 "looks like daylight", so the offset wrt Eastern is -4,
3194 # and adding -4-0 == -4 gives the 2:00 spelling. We want the 1:00 EST
3195 # spelling.
3196 expected = self.dston.replace(hour=1)
Tim Peters52dcce22003-01-23 16:36:11 +00003197 got = sixutc.astimezone(Eastern).replace(tzinfo=None)
Tim Petersf3615152003-01-01 21:51:37 +00003198 self.assertEqual(expected, got)
Tim Peters621818b2002-12-29 23:44:49 +00003199
Tim Petersadf64202003-01-04 06:03:15 +00003200 # Now on the day DST ends, we want "repeat an hour" behavior.
3201 # UTC 4:MM 5:MM 6:MM 7:MM checking these
3202 # EST 23:MM 0:MM 1:MM 2:MM
3203 # EDT 0:MM 1:MM 2:MM 3:MM
3204 # wall 0:MM 1:MM 1:MM 2:MM against these
3205 for utc in utc_real, utc_fake:
3206 for tz in Eastern, Pacific:
Tim Peters327098a2003-01-20 22:54:38 +00003207 first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM
Tim Petersadf64202003-01-04 06:03:15 +00003208 # Convert that to UTC.
3209 first_std_hour -= tz.utcoffset(None)
3210 # Adjust for possibly fake UTC.
3211 asutc = first_std_hour + utc.utcoffset(None)
3212 # First UTC hour to convert; this is 4:00 when utc=utc_real &
3213 # tz=Eastern.
3214 asutcbase = asutc.replace(tzinfo=utc)
3215 for tzhour in (0, 1, 1, 2):
3216 expectedbase = self.dstoff.replace(hour=tzhour)
3217 for minute in 0, 30, 59:
3218 expected = expectedbase.replace(minute=minute)
3219 asutc = asutcbase.replace(minute=minute)
3220 astz = asutc.astimezone(tz)
3221 self.assertEqual(astz.replace(tzinfo=None), expected)
3222 asutcbase += HOUR
3223
3224
Tim Peters710fb152003-01-02 19:35:54 +00003225 def test_bogus_dst(self):
3226 class ok(tzinfo):
3227 def utcoffset(self, dt): return HOUR
3228 def dst(self, dt): return HOUR
3229
3230 now = self.theclass.now().replace(tzinfo=utc_real)
3231 # Doesn't blow up.
3232 now.astimezone(ok())
3233
3234 # Does blow up.
3235 class notok(ok):
3236 def dst(self, dt): return None
3237 self.assertRaises(ValueError, now.astimezone, notok())
3238
Tim Peters52dcce22003-01-23 16:36:11 +00003239 def test_fromutc(self):
3240 self.assertRaises(TypeError, Eastern.fromutc) # not enough args
3241 now = datetime.utcnow().replace(tzinfo=utc_real)
3242 self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo
3243 now = now.replace(tzinfo=Eastern) # insert correct tzinfo
3244 enow = Eastern.fromutc(now) # doesn't blow up
3245 self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member
3246 self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args
3247 self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type
3248
3249 # Always converts UTC to standard time.
3250 class FauxUSTimeZone(USTimeZone):
3251 def fromutc(self, dt):
3252 return dt + self.stdoffset
3253 FEastern = FauxUSTimeZone(-5, "FEastern", "FEST", "FEDT")
3254
3255 # UTC 4:MM 5:MM 6:MM 7:MM 8:MM 9:MM
3256 # EST 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
3257 # EDT 0:MM 1:MM 2:MM 3:MM 4:MM 5:MM
3258
3259 # Check around DST start.
3260 start = self.dston.replace(hour=4, tzinfo=Eastern)
3261 fstart = start.replace(tzinfo=FEastern)
3262 for wall in 23, 0, 1, 3, 4, 5:
3263 expected = start.replace(hour=wall)
3264 if wall == 23:
3265 expected -= timedelta(days=1)
3266 got = Eastern.fromutc(start)
3267 self.assertEqual(expected, got)
3268
3269 expected = fstart + FEastern.stdoffset
3270 got = FEastern.fromutc(fstart)
3271 self.assertEqual(expected, got)
3272
3273 # Ensure astimezone() calls fromutc() too.
3274 got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
3275 self.assertEqual(expected, got)
3276
3277 start += HOUR
3278 fstart += HOUR
3279
3280 # Check around DST end.
3281 start = self.dstoff.replace(hour=4, tzinfo=Eastern)
3282 fstart = start.replace(tzinfo=FEastern)
3283 for wall in 0, 1, 1, 2, 3, 4:
3284 expected = start.replace(hour=wall)
3285 got = Eastern.fromutc(start)
3286 self.assertEqual(expected, got)
3287
3288 expected = fstart + FEastern.stdoffset
3289 got = FEastern.fromutc(fstart)
3290 self.assertEqual(expected, got)
3291
3292 # Ensure astimezone() calls fromutc() too.
3293 got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
3294 self.assertEqual(expected, got)
3295
3296 start += HOUR
3297 fstart += HOUR
3298
Tim Peters710fb152003-01-02 19:35:54 +00003299
Tim Peters528ca532004-09-16 01:30:50 +00003300#############################################################################
3301# oddballs
3302
3303class Oddballs(unittest.TestCase):
3304
3305 def test_bug_1028306(self):
3306 # Trying to compare a date to a datetime should act like a mixed-
3307 # type comparison, despite that datetime is a subclass of date.
3308 as_date = date.today()
3309 as_datetime = datetime.combine(as_date, time())
Georg Brandlab91fde2009-08-13 08:51:18 +00003310 self.assertTrue(as_date != as_datetime)
3311 self.assertTrue(as_datetime != as_date)
3312 self.assertTrue(not as_date == as_datetime)
3313 self.assertTrue(not as_datetime == as_date)
Tim Peters528ca532004-09-16 01:30:50 +00003314 self.assertRaises(TypeError, lambda: as_date < as_datetime)
3315 self.assertRaises(TypeError, lambda: as_datetime < as_date)
3316 self.assertRaises(TypeError, lambda: as_date <= as_datetime)
3317 self.assertRaises(TypeError, lambda: as_datetime <= as_date)
3318 self.assertRaises(TypeError, lambda: as_date > as_datetime)
3319 self.assertRaises(TypeError, lambda: as_datetime > as_date)
3320 self.assertRaises(TypeError, lambda: as_date >= as_datetime)
3321 self.assertRaises(TypeError, lambda: as_datetime >= as_date)
3322
3323 # Neverthelss, comparison should work with the base-class (date)
3324 # projection if use of a date method is forced.
Guido van Rossum19960592006-08-24 17:29:38 +00003325 self.assertEqual(as_date.__eq__(as_datetime), True)
Tim Peters528ca532004-09-16 01:30:50 +00003326 different_day = (as_date.day + 1) % 20 + 1
Guido van Rossum19960592006-08-24 17:29:38 +00003327 as_different = as_datetime.replace(day= different_day)
3328 self.assertEqual(as_date.__eq__(as_different), False)
Tim Peters528ca532004-09-16 01:30:50 +00003329
3330 # And date should compare with other subclasses of date. If a
3331 # subclass wants to stop this, it's up to the subclass to do so.
3332 date_sc = SubclassDate(as_date.year, as_date.month, as_date.day)
3333 self.assertEqual(as_date, date_sc)
3334 self.assertEqual(date_sc, as_date)
3335
3336 # Ditto for datetimes.
3337 datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month,
3338 as_date.day, 0, 0, 0)
3339 self.assertEqual(as_datetime, datetime_sc)
3340 self.assertEqual(datetime_sc, as_datetime)
3341
Tim Peters2a799bf2002-12-16 20:18:38 +00003342def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003343 support.run_unittest(__name__)
Tim Peters2a799bf2002-12-16 20:18:38 +00003344
3345if __name__ == "__main__":
3346 test_main()