Debian Codegraph @

cpython27/Lib/test/test_datetime.py

raw symbols SCIP
1 """Test date/time type.
2
3 See http://www.zope.org/Members/fdrake/DateTimeWiki/TestCases
4 """
5 from __future__ import division
6 import sys
7 import pickle
8 import cPickle
9 import unittest
10
11 from test import test_support
12
13 from datetime import MINYEAR, MAXYEAR
14 from datetime import timedelta
15 from datetime import tzinfo
16 from datetime import time
17 from datetime import date, datetime
18
19 pickle_choices = [(pickler, unpickler, proto)
20 for pickler in pickle, cPickle
21 for unpickler in pickle, cPickle
22 for proto in range(3)]
23 assert len(pickle_choices) == 2*2*3
24
25 # An arbitrary collection of objects of non-datetime types, for testing
26 # mixed-type comparisons.
27 OTHERSTUFF = (10, 10L, 34.5, "abc", {}, [], ())
28
29
30 #############################################################################
31 # module tests
32
33 class TestModule(unittest.TestCase):
34
35 def test_constants(self):
36 import datetime
37 self.assertEqual(datetime.MINYEAR, 1)
38 self.assertEqual(datetime.MAXYEAR, 9999)
39
40 #############################################################################
41 # tzinfo tests
42
43 class FixedOffset(tzinfo):
44 def __init__(self, offset, name, dstoffset=42):
45 if isinstance(offset, int):
46 offset = timedelta(minutes=offset)
47 if isinstance(dstoffset, int):
48 dstoffset = timedelta(minutes=dstoffset)
49 self.__offset = offset
50 self.__name = name
51 self.__dstoffset = dstoffset
52 def __repr__(self):
53 return self.__name.lower()
54 def utcoffset(self, dt):
55 return self.__offset
56 def tzname(self, dt):
57 return self.__name
58 def dst(self, dt):
59 return self.__dstoffset
60
61 class PicklableFixedOffset(FixedOffset):
62 def __init__(self, offset=None, name=None, dstoffset=None):
63 FixedOffset.__init__(self, offset, name, dstoffset)
64
65 class TestTZInfo(unittest.TestCase):
66
67 def test_non_abstractness(self):
68 # In order to allow subclasses to get pickled, the C implementation
69 # wasn't able to get away with having __init__ raise
70 # NotImplementedError.
71 useless = tzinfo()
72 dt = datetime.max
73 self.assertRaises(NotImplementedError, useless.tzname, dt)
74 self.assertRaises(NotImplementedError, useless.utcoffset, dt)
75 self.assertRaises(NotImplementedError, useless.dst, dt)
76
77 def test_subclass_must_override(self):
78 class NotEnough(tzinfo):
79 def __init__(self, offset, name):
80 self.__offset = offset
81 self.__name = name
82 self.assertTrue(issubclass(NotEnough, tzinfo))
83 ne = NotEnough(3, "NotByALongShot")
84 self.assertIsInstance(ne, tzinfo)
85
86 dt = datetime.now()
87 self.assertRaises(NotImplementedError, ne.tzname, dt)
88 self.assertRaises(NotImplementedError, ne.utcoffset, dt)
89 self.assertRaises(NotImplementedError, ne.dst, dt)
90
91 def test_normal(self):
92 fo = FixedOffset(3, "Three")
93 self.assertIsInstance(fo, tzinfo)
94 for dt in datetime.now(), None:
95 self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
96 self.assertEqual(fo.tzname(dt), "Three")
97 self.assertEqual(fo.dst(dt), timedelta(minutes=42))
98
99 def test_pickling_base(self):
100 # There's no point to pickling tzinfo objects on their own (they
101 # carry no data), but they need to be picklable anyway else
102 # concrete subclasses can't be pickled.
103 orig = tzinfo.__new__(tzinfo)
104 self.assertIs(type(orig), tzinfo)
105 for pickler, unpickler, proto in pickle_choices:
106 green = pickler.dumps(orig, proto)
107 derived = unpickler.loads(green)
108 self.assertIs(type(derived), tzinfo)
109
110 def test_pickling_subclass(self):
111 # Make sure we can pickle/unpickle an instance of a subclass.
112 offset = timedelta(minutes=-300)
113 orig = PicklableFixedOffset(offset, 'cookie')
114 self.assertIsInstance(orig, tzinfo)
115 self.assertTrue(type(orig) is PicklableFixedOffset)
116 self.assertEqual(orig.utcoffset(None), offset)
117 self.assertEqual(orig.tzname(None), 'cookie')
118 for pickler, unpickler, proto in pickle_choices:
119 green = pickler.dumps(orig, proto)
120 derived = unpickler.loads(green)
121 self.assertIsInstance(derived, tzinfo)
122 self.assertTrue(type(derived) is PicklableFixedOffset)
123 self.assertEqual(derived.utcoffset(None), offset)
124 self.assertEqual(derived.tzname(None), 'cookie')
125
126 #############################################################################
127 # Base class for testing a particular aspect of timedelta, time, date and
128 # datetime comparisons.
129
130 class HarmlessMixedComparison:
131 # Test that __eq__ and __ne__ don't complain for mixed-type comparisons.
132
133 # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a
134 # legit constructor.
135
136 def test_harmless_mixed_comparison(self):
137 me = self.theclass(1, 1, 1)
138
139 self.assertFalse(me == ())
140 self.assertTrue(me != ())
141 self.assertFalse(() == me)
142 self.assertTrue(() != me)
143
144 self.assertIn(me, [1, 20L, [], me])
145 self.assertIn([], [me, 1, 20L, []])
146
147 def test_harmful_mixed_comparison(self):
148 me = self.theclass(1, 1, 1)
149
150 self.assertRaises(TypeError, lambda: me < ())
151 self.assertRaises(TypeError, lambda: me <= ())
152 self.assertRaises(TypeError, lambda: me > ())
153 self.assertRaises(TypeError, lambda: me >= ())
154
155 self.assertRaises(TypeError, lambda: () < me)
156 self.assertRaises(TypeError, lambda: () <= me)
157 self.assertRaises(TypeError, lambda: () > me)
158 self.assertRaises(TypeError, lambda: () >= me)
159
160 self.assertRaises(TypeError, cmp, (), me)
161 self.assertRaises(TypeError, cmp, me, ())
162
163 #############################################################################
164 # timedelta tests
165
166 class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
167
168 theclass = timedelta
169
170 def test_constructor(self):
171 eq = self.assertEqual
172 td = timedelta
173
174 # Check keyword args to constructor
175 eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0,
176 milliseconds=0, microseconds=0))
177 eq(td(1), td(days=1))
178 eq(td(0, 1), td(seconds=1))
179 eq(td(0, 0, 1), td(microseconds=1))
180 eq(td(weeks=1), td(days=7))
181 eq(td(days=1), td(hours=24))
182 eq(td(hours=1), td(minutes=60))
183 eq(td(minutes=1), td(seconds=60))
184 eq(td(seconds=1), td(milliseconds=1000))
185 eq(td(milliseconds=1), td(microseconds=1000))
186
187 # Check float args to constructor
188 eq(td(weeks=1.0/7), td(days=1))
189 eq(td(days=1.0/24), td(hours=1))
190 eq(td(hours=1.0/60), td(minutes=1))
191 eq(td(minutes=1.0/60), td(seconds=1))
192 eq(td(seconds=0.001), td(milliseconds=1))
193 eq(td(milliseconds=0.001), td(microseconds=1))
194
195 def test_computations(self):
196 eq = self.assertEqual
197 td = timedelta
198
199 a = td(7) # One week
200 b = td(0, 60) # One minute
201 c = td(0, 0, 1000) # One millisecond
202 eq(a+b+c, td(7, 60, 1000))
203 eq(a-b, td(6, 24*3600 - 60))
204 eq(-a, td(-7))
205 eq(+a, td(7))
206 eq(-b, td(-1, 24*3600 - 60))
207 eq(-c, td(-1, 24*3600 - 1, 999000))
208 eq(abs(a), a)
209 eq(abs(-a), a)
210 eq(td(6, 24*3600), a)
211 eq(td(0, 0, 60*1000000), b)
212 eq(a*10, td(70))
213 eq(a*10, 10*a)
214 eq(a*10L, 10*a)
215 eq(b*10, td(0, 600))
216 eq(10*b, td(0, 600))
217 eq(b*10L, td(0, 600))
218 eq(c*10, td(0, 0, 10000))
219 eq(10*c, td(0, 0, 10000))
220 eq(c*10L, td(0, 0, 10000))
221 eq(a*-1, -a)
222 eq(b*-2, -b-b)
223 eq(c*-2, -c+-c)
224 eq(b*(60*24), (b*60)*24)
225 eq(b*(60*24), (60*b)*24)
226 eq(c*1000, td(0, 1))
227 eq(1000*c, td(0, 1))
228 eq(a//7, td(1))
229 eq(b//10, td(0, 6))
230 eq(c//1000, td(0, 0, 1))
231 eq(a//10, td(0, 7*24*360))
232 eq(a//3600000, td(0, 0, 7*24*1000))
233
234 # Issue #11576
235 eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998),
236 td(0, 0, 1))
237 eq(td(999999999, 1, 1) - td(999999999, 1, 0),
238 td(0, 0, 1))
239
240
241 def test_disallowed_computations(self):
242 a = timedelta(42)
243
244 # Add/sub ints, longs, floats should be illegal
245 for i in 1, 1L, 1.0:
246 self.assertRaises(TypeError, lambda: a+i)
247 self.assertRaises(TypeError, lambda: a-i)
248 self.assertRaises(TypeError, lambda: i+a)
249 self.assertRaises(TypeError, lambda: i-a)
250
251 # Mul/div by float isn't supported.
252 x = 2.3
253 self.assertRaises(TypeError, lambda: a*x)
254 self.assertRaises(TypeError, lambda: x*a)
255 self.assertRaises(TypeError, lambda: a/x)
256 self.assertRaises(TypeError, lambda: x/a)
257 self.assertRaises(TypeError, lambda: a // x)
258 self.assertRaises(TypeError, lambda: x // a)
259
260 # Division of int by timedelta doesn't make sense.
261 # Division by zero doesn't make sense.
262 for zero in 0, 0L:
263 self.assertRaises(TypeError, lambda: zero // a)
264 self.assertRaises(ZeroDivisionError, lambda: a // zero)
265
266 def test_basic_attributes(self):
267 days, seconds, us = 1, 7, 31
268 td = timedelta(days, seconds, us)
269 self.assertEqual(td.days, days)
270 self.assertEqual(td.seconds, seconds)
271 self.assertEqual(td.microseconds, us)
272
273 def test_total_seconds(self):
274 td = timedelta(days=365)
275 self.assertEqual(td.total_seconds(), 31536000.0)
276 for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]:
277 td = timedelta(seconds=total_seconds)
278 self.assertEqual(td.total_seconds(), total_seconds)
279 # Issue8644: Test that td.total_seconds() has the same
280 # accuracy as td / timedelta(seconds=1).
281 for ms in [-1, -2, -123]:
282 td = timedelta(microseconds=ms)
283 self.assertEqual(td.total_seconds(),
284 ((24*3600*td.days + td.seconds)*10**6
285 + td.microseconds)/10**6)
286
287 def test_carries(self):
288 t1 = timedelta(days=100,
289 weeks=-7,
290 hours=-24*(100-49),
291 minutes=-3,
292 seconds=12,
293 microseconds=(3*60 - 12) * 1e6 + 1)
294 t2 = timedelta(microseconds=1)
295 self.assertEqual(t1, t2)
296
297 def test_hash_equality(self):
298 t1 = timedelta(days=100,
299 weeks=-7,
300 hours=-24*(100-49),
301 minutes=-3,
302 seconds=12,
303 microseconds=(3*60 - 12) * 1000000)
304 t2 = timedelta()
305 self.assertEqual(hash(t1), hash(t2))
306
307 t1 += timedelta(weeks=7)
308 t2 += timedelta(days=7*7)
309 self.assertEqual(t1, t2)
310 self.assertEqual(hash(t1), hash(t2))
311
312 d = {t1: 1}
313 d[t2] = 2
314 self.assertEqual(len(d), 1)
315 self.assertEqual(d[t1], 2)
316
317 def test_pickling(self):
318 args = 12, 34, 56
319 orig = timedelta(*args)
320 for pickler, unpickler, proto in pickle_choices:
321 green = pickler.dumps(orig, proto)
322 derived = unpickler.loads(green)
323 self.assertEqual(orig, derived)
324
325 def test_compare(self):
326 t1 = timedelta(2, 3, 4)
327 t2 = timedelta(2, 3, 4)
328 self.assertTrue(t1 == t2)
329 self.assertTrue(t1 <= t2)
330 self.assertTrue(t1 >= t2)
331 self.assertFalse(t1 != t2)
332 self.assertFalse(t1 < t2)
333 self.assertFalse(t1 > t2)
334 self.assertEqual(cmp(t1, t2), 0)
335 self.assertEqual(cmp(t2, t1), 0)
336
337 for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
338 t2 = timedelta(*args) # this is larger than t1
339 self.assertTrue(t1 < t2)
340 self.assertTrue(t2 > t1)
341 self.assertTrue(t1 <= t2)
342 self.assertTrue(t2 >= t1)
343 self.assertTrue(t1 != t2)
344 self.assertTrue(t2 != t1)
345 self.assertFalse(t1 == t2)
346 self.assertFalse(t2 == t1)
347 self.assertFalse(t1 > t2)
348 self.assertFalse(t2 < t1)
349 self.assertFalse(t1 >= t2)
350 self.assertFalse(t2 <= t1)
351 self.assertEqual(cmp(t1, t2), -1)
352 self.assertEqual(cmp(t2, t1), 1)
353
354 for badarg in OTHERSTUFF:
355 self.assertEqual(t1 == badarg, False)
356 self.assertEqual(t1 != badarg, True)
357 self.assertEqual(badarg == t1, False)
358 self.assertEqual(badarg != t1, True)
359
360 self.assertRaises(TypeError, lambda: t1 <= badarg)
361 self.assertRaises(TypeError, lambda: t1 < badarg)
362 self.assertRaises(TypeError, lambda: t1 > badarg)
363 self.assertRaises(TypeError, lambda: t1 >= badarg)
364 self.assertRaises(TypeError, lambda: badarg <= t1)
365 self.assertRaises(TypeError, lambda: badarg < t1)
366 self.assertRaises(TypeError, lambda: badarg > t1)
367 self.assertRaises(TypeError, lambda: badarg >= t1)
368
369 def test_str(self):
370 td = timedelta
371 eq = self.assertEqual
372
373 eq(str(td(1)), "1 day, 0:00:00")
374 eq(str(td(-1)), "-1 day, 0:00:00")
375 eq(str(td(2)), "2 days, 0:00:00")
376 eq(str(td(-2)), "-2 days, 0:00:00")
377
378 eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59")
379 eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04")
380 eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)),
381 "-210 days, 23:12:34")
382
383 eq(str(td(milliseconds=1)), "0:00:00.001000")
384 eq(str(td(microseconds=3)), "0:00:00.000003")
385
386 eq(str(td(days=999999999, hours=23, minutes=59, seconds=59,
387 microseconds=999999)),
388 "999999999 days, 23:59:59.999999")
389
390 def test_roundtrip(self):
391 for td in (timedelta(days=999999999, hours=23, minutes=59,
392 seconds=59, microseconds=999999),
393 timedelta(days=-999999999),
394 timedelta(days=1, seconds=2, microseconds=3)):
395
396 # Verify td -> string -> td identity.
397 s = repr(td)
398 self.assertTrue(s.startswith('datetime.'))
399 s = s[9:]
400 td2 = eval(s)
401 self.assertEqual(td, td2)
402
403 # Verify identity via reconstructing from pieces.
404 td2 = timedelta(td.days, td.seconds, td.microseconds)
405 self.assertEqual(td, td2)
406
407 def test_resolution_info(self):
408 self.assertIsInstance(timedelta.min, timedelta)
409 self.assertIsInstance(timedelta.max, timedelta)
410 self.assertIsInstance(timedelta.resolution, timedelta)
411 self.assertTrue(timedelta.max > timedelta.min)
412 self.assertEqual(timedelta.min, timedelta(-999999999))
413 self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
414 self.assertEqual(timedelta.resolution, timedelta(0, 0, 1))
415
416 def test_overflow(self):
417 tiny = timedelta.resolution
418
419 td = timedelta.min + tiny
420 td -= tiny # no problem
421 self.assertRaises(OverflowError, td.__sub__, tiny)
422 self.assertRaises(OverflowError, td.__add__, -tiny)
423
424 td = timedelta.max - tiny
425 td += tiny # no problem
426 self.assertRaises(OverflowError, td.__add__, tiny)
427 self.assertRaises(OverflowError, td.__sub__, -tiny)
428
429 self.assertRaises(OverflowError, lambda: -timedelta.max)
430
431 def test_microsecond_rounding(self):
432 td = timedelta
433 eq = self.assertEqual
434
435 # Single-field rounding.
436 eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0
437 eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0
438 eq(td(milliseconds=0.6/1000), td(microseconds=1))
439 eq(td(milliseconds=-0.6/1000), td(microseconds=-1))
440
441 # Rounding due to contributions from more than one field.
442 us_per_hour = 3600e6
443 us_per_day = us_per_hour * 24
444 eq(td(days=.4/us_per_day), td(0))
445 eq(td(hours=.2/us_per_hour), td(0))
446 eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1))
447
448 eq(td(days=-.4/us_per_day), td(0))
449 eq(td(hours=-.2/us_per_hour), td(0))
450 eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1))
451
452 def test_massive_normalization(self):
453 td = timedelta(microseconds=-1)
454 self.assertEqual((td.days, td.seconds, td.microseconds),
455 (-1, 24*3600-1, 999999))
456
457 def test_bool(self):
458 self.assertTrue(timedelta(1))
459 self.assertTrue(timedelta(0, 1))
460 self.assertTrue(timedelta(0, 0, 1))
461 self.assertTrue(timedelta(microseconds=1))
462 self.assertFalse(timedelta(0))
463
464 def test_subclass_timedelta(self):
465
466 class T(timedelta):
467 @staticmethod
468 def from_td(td):
469 return T(td.days, td.seconds, td.microseconds)
470
471 def as_hours(self):
472 sum = (self.days * 24 +
473 self.seconds / 3600.0 +
474 self.microseconds / 3600e6)
475 return round(sum)
476
477 t1 = T(days=1)
478 self.assertIs(type(t1), T)
479 self.assertEqual(t1.as_hours(), 24)
480
481 t2 = T(days=-1, seconds=-3600)
482 self.assertIs(type(t2), T)
483 self.assertEqual(t2.as_hours(), -25)
484
485 t3 = t1 + t2
486 self.assertIs(type(t3), timedelta)
487 t4 = T.from_td(t3)
488 self.assertIs(type(t4), T)
489 self.assertEqual(t3.days, t4.days)
490 self.assertEqual(t3.seconds, t4.seconds)
491 self.assertEqual(t3.microseconds, t4.microseconds)
492 self.assertEqual(str(t3), str(t4))
493 self.assertEqual(t4.as_hours(), -1)
494
495 def test_issue31752(self):
496 # The interpreter shouldn't crash because divmod() returns negative
497 # remainder.
498 for inttype in (int, long):
499 class BadInt(inttype):
500 def __mul__(self, other):
501 return Prod()
502 def __rmul__(self, other):
503 return Prod()
504 def __floordiv__(self, other):
505 return Prod()
506 def __rfloordiv__(self, other):
507 return Prod()
508
509 class BadLong(long):
510 def __mul__(self, other):
511 return Prod()
512 def __rmul__(self, other):
513 return Prod()
514 def __floordiv__(self, other):
515 return Prod()
516 def __rfloordiv__(self, other):
517 return Prod()
518
519 class Prod:
520 def __add__(self, other):
521 return Sum()
522 def __radd__(self, other):
523 return Sum()
524
525 for inttype2 in (int, long):
526 class Sum(inttype2):
527 def __divmod__(self, other):
528 return divmodresult
529
530 for divmodresult in [None, (), (0, 1, 2), (0, -1)]:
531 # The following examples should not crash.
532 try:
533 timedelta(microseconds=BadInt(1))
534 except TypeError:
535 pass
536 try:
537 timedelta(hours=BadInt(1))
538 except TypeError:
539 pass
540 try:
541 timedelta(weeks=BadInt(1))
542 except (TypeError, ValueError):
543 pass
544 try:
545 timedelta(1) * BadInt(1)
546 except (TypeError, ValueError):
547 pass
548 try:
549 BadInt(1) * timedelta(1)
550 except TypeError:
551 pass
552 try:
553 timedelta(1) // BadInt(1)
554 except TypeError:
555 pass
556
557
558 #############################################################################
559 # date tests
560
561 class TestDateOnly(unittest.TestCase):
562 # Tests here won't pass if also run on datetime objects, so don't
563 # subclass this to test datetimes too.
564
565 def test_delta_non_days_ignored(self):
566 dt = date(2000, 1, 2)
567 delta = timedelta(days=1, hours=2, minutes=3, seconds=4,
568 microseconds=5)
569 days = timedelta(delta.days)
570 self.assertEqual(days, timedelta(1))
571
572 dt2 = dt + delta
573 self.assertEqual(dt2, dt + days)
574
575 dt2 = delta + dt
576 self.assertEqual(dt2, dt + days)
577
578 dt2 = dt - delta
579 self.assertEqual(dt2, dt - days)
580
581 delta = -delta
582 days = timedelta(delta.days)
583 self.assertEqual(days, timedelta(-2))
584
585 dt2 = dt + delta
586 self.assertEqual(dt2, dt + days)
587
588 dt2 = delta + dt
589 self.assertEqual(dt2, dt + days)
590
591 dt2 = dt - delta
592 self.assertEqual(dt2, dt - days)
593
594 class SubclassDate(date):
595 sub_var = 1
596
597 class TestDate(HarmlessMixedComparison, unittest.TestCase):
598 # Tests here should pass for both dates and datetimes, except for a
599 # few tests that TestDateTime overrides.
600
601 theclass = date
602
603 def test_basic_attributes(self):
604 dt = self.theclass(2002, 3, 1)
605 self.assertEqual(dt.year, 2002)
606 self.assertEqual(dt.month, 3)
607 self.assertEqual(dt.day, 1)
608
609 def test_roundtrip(self):
610 for dt in (self.theclass(1, 2, 3),
611 self.theclass.today()):
612 # Verify dt -> string -> date identity.
613 s = repr(dt)
614 self.assertTrue(s.startswith('datetime.'))
615 s = s[9:]
616 dt2 = eval(s)
617 self.assertEqual(dt, dt2)
618
619 # Verify identity via reconstructing from pieces.
620 dt2 = self.theclass(dt.year, dt.month, dt.day)
621 self.assertEqual(dt, dt2)
622
623 def test_ordinal_conversions(self):
624 # Check some fixed values.
625 for y, m, d, n in [(1, 1, 1, 1), # calendar origin
626 (1, 12, 31, 365),
627 (2, 1, 1, 366),
628 # first example from "Calendrical Calculations"
629 (1945, 11, 12, 710347)]:
630 d = self.theclass(y, m, d)
631 self.assertEqual(n, d.toordinal())
632 fromord = self.theclass.fromordinal(n)
633 self.assertEqual(d, fromord)
634 if hasattr(fromord, "hour"):
635 # if we're checking something fancier than a date, verify
636 # the extra fields have been zeroed out
637 self.assertEqual(fromord.hour, 0)
638 self.assertEqual(fromord.minute, 0)
639 self.assertEqual(fromord.second, 0)
640 self.assertEqual(fromord.microsecond, 0)
641
642 # Check first and last days of year spottily across the whole
643 # range of years supported.
644 for year in xrange(MINYEAR, MAXYEAR+1, 7):
645 # Verify (year, 1, 1) -> ordinal -> y, m, d is identity.
646 d = self.theclass(year, 1, 1)
647 n = d.toordinal()
648 d2 = self.theclass.fromordinal(n)
649 self.assertEqual(d, d2)
650 # Verify that moving back a day gets to the end of year-1.
651 if year > 1:
652 d = self.theclass.fromordinal(n-1)
653 d2 = self.theclass(year-1, 12, 31)
654 self.assertEqual(d, d2)
655 self.assertEqual(d2.toordinal(), n-1)
656
657 # Test every day in a leap-year and a non-leap year.
658 dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
659 for year, isleap in (2000, True), (2002, False):
660 n = self.theclass(year, 1, 1).toordinal()
661 for month, maxday in zip(range(1, 13), dim):
662 if month == 2 and isleap:
663 maxday += 1
664 for day in range(1, maxday+1):
665 d = self.theclass(year, month, day)
666 self.assertEqual(d.toordinal(), n)
667 self.assertEqual(d, self.theclass.fromordinal(n))
668 n += 1
669
670 def test_extreme_ordinals(self):
671 a = self.theclass.min
672 a = self.theclass(a.year, a.month, a.day) # get rid of time parts
673 aord = a.toordinal()
674 b = a.fromordinal(aord)
675 self.assertEqual(a, b)
676
677 self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1))
678
679 b = a + timedelta(days=1)
680 self.assertEqual(b.toordinal(), aord + 1)
681 self.assertEqual(b, self.theclass.fromordinal(aord + 1))
682
683 a = self.theclass.max
684 a = self.theclass(a.year, a.month, a.day) # get rid of time parts
685 aord = a.toordinal()
686 b = a.fromordinal(aord)
687 self.assertEqual(a, b)
688
689 self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1))
690
691 b = a - timedelta(days=1)
692 self.assertEqual(b.toordinal(), aord - 1)
693 self.assertEqual(b, self.theclass.fromordinal(aord - 1))
694
695 def test_bad_constructor_arguments(self):
696 # bad years
697 self.theclass(MINYEAR, 1, 1) # no exception
698 self.theclass(MAXYEAR, 1, 1) # no exception
699 self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
700 self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
701 # bad months
702 self.theclass(2000, 1, 1) # no exception
703 self.theclass(2000, 12, 1) # no exception
704 self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
705 self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
706 # bad days
707 self.theclass(2000, 2, 29) # no exception
708 self.theclass(2004, 2, 29) # no exception
709 self.theclass(2400, 2, 29) # no exception
710 self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
711 self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
712 self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
713 self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
714 self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
715 self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
716
717 def test_hash_equality(self):
718 d = self.theclass(2000, 12, 31)
719 # same thing
720 e = self.theclass(2000, 12, 31)
721 self.assertEqual(d, e)
722 self.assertEqual(hash(d), hash(e))
723
724 dic = {d: 1}
725 dic[e] = 2
726 self.assertEqual(len(dic), 1)
727 self.assertEqual(dic[d], 2)
728 self.assertEqual(dic[e], 2)
729
730 d = self.theclass(2001, 1, 1)
731 # same thing
732 e = self.theclass(2001, 1, 1)
733 self.assertEqual(d, e)
734 self.assertEqual(hash(d), hash(e))
735
736 dic = {d: 1}
737 dic[e] = 2
738 self.assertEqual(len(dic), 1)
739 self.assertEqual(dic[d], 2)
740 self.assertEqual(dic[e], 2)
741
742 def test_computations(self):
743 a = self.theclass(2002, 1, 31)
744 b = self.theclass(1956, 1, 31)
745
746 diff = a-b
747 self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
748 self.assertEqual(diff.seconds, 0)
749 self.assertEqual(diff.microseconds, 0)
750
751 day = timedelta(1)
752 week = timedelta(7)
753 a = self.theclass(2002, 3, 2)
754 self.assertEqual(a + day, self.theclass(2002, 3, 3))
755 self.assertEqual(day + a, self.theclass(2002, 3, 3))
756 self.assertEqual(a - day, self.theclass(2002, 3, 1))
757 self.assertEqual(-day + a, self.theclass(2002, 3, 1))
758 self.assertEqual(a + week, self.theclass(2002, 3, 9))
759 self.assertEqual(a - week, self.theclass(2002, 2, 23))
760 self.assertEqual(a + 52*week, self.theclass(2003, 3, 1))
761 self.assertEqual(a - 52*week, self.theclass(2001, 3, 3))
762 self.assertEqual((a + week) - a, week)
763 self.assertEqual((a + day) - a, day)
764 self.assertEqual((a - week) - a, -week)
765 self.assertEqual((a - day) - a, -day)
766 self.assertEqual(a - (a + week), -week)
767 self.assertEqual(a - (a + day), -day)
768 self.assertEqual(a - (a - week), week)
769 self.assertEqual(a - (a - day), day)
770
771 # Add/sub ints, longs, floats should be illegal
772 for i in 1, 1L, 1.0:
773 self.assertRaises(TypeError, lambda: a+i)
774 self.assertRaises(TypeError, lambda: a-i)
775 self.assertRaises(TypeError, lambda: i+a)
776 self.assertRaises(TypeError, lambda: i-a)
777
778 # delta - date is senseless.
779 self.assertRaises(TypeError, lambda: day - a)
780 # mixing date and (delta or date) via * or // is senseless
781 self.assertRaises(TypeError, lambda: day * a)
782 self.assertRaises(TypeError, lambda: a * day)
783 self.assertRaises(TypeError, lambda: day // a)
784 self.assertRaises(TypeError, lambda: a // day)
785 self.assertRaises(TypeError, lambda: a * a)
786 self.assertRaises(TypeError, lambda: a // a)
787 # date + date is senseless
788 self.assertRaises(TypeError, lambda: a + a)
789
790 def test_overflow(self):
791 tiny = self.theclass.resolution
792
793 for delta in [tiny, timedelta(1), timedelta(2)]:
794 dt = self.theclass.min + delta
795 dt -= delta # no problem
796 self.assertRaises(OverflowError, dt.__sub__, delta)
797 self.assertRaises(OverflowError, dt.__add__, -delta)
798
799 dt = self.theclass.max - delta
800 dt += delta # no problem
801 self.assertRaises(OverflowError, dt.__add__, delta)
802 self.assertRaises(OverflowError, dt.__sub__, -delta)
803
804 def test_fromtimestamp(self):
805 import time
806
807 # Try an arbitrary fixed value.
808 year, month, day = 1999, 9, 19
809 ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
810 d = self.theclass.fromtimestamp(ts)
811 self.assertEqual(d.year, year)
812 self.assertEqual(d.month, month)
813 self.assertEqual(d.day, day)
814
815 def test_insane_fromtimestamp(self):
816 # It's possible that some platform maps time_t to double,
817 # and that this test will fail there. This test should
818 # exempt such platforms (provided they return reasonable
819 # results!).
820 for insane in -1e200, 1e200:
821 self.assertRaises(ValueError, self.theclass.fromtimestamp,
822 insane)
823
824 def test_today(self):
825 import time
826
827 # We claim that today() is like fromtimestamp(time.time()), so
828 # prove it.
829 for dummy in range(3):
830 today = self.theclass.today()
831 ts = time.time()
832 todayagain = self.theclass.fromtimestamp(ts)
833 if today == todayagain:
834 break
835 # There are several legit reasons that could fail:
836 # 1. It recently became midnight, between the today() and the
837 # time() calls.
838 # 2. The platform time() has such fine resolution that we'll
839 # never get the same value twice.
840 # 3. The platform time() has poor resolution, and we just
841 # happened to call today() right before a resolution quantum
842 # boundary.
843 # 4. The system clock got fiddled between calls.
844 # In any case, wait a little while and try again.
845 time.sleep(0.1)
846
847 # It worked or it didn't. If it didn't, assume it's reason #2, and
848 # let the test pass if they're within half a second of each other.
849 if today != todayagain:
850 self.assertAlmostEqual(todayagain, today,
851 delta=timedelta(seconds=0.5))
852
853 def test_weekday(self):
854 for i in range(7):
855 # March 4, 2002 is a Monday
856 self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i)
857 self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1)
858 # January 2, 1956 is a Monday
859 self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i)
860 self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1)
861
862 def test_isocalendar(self):
863 # Check examples from
864 # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
865 for i in range(7):
866 d = self.theclass(2003, 12, 22+i)
867 self.assertEqual(d.isocalendar(), (2003, 52, i+1))
868 d = self.theclass(2003, 12, 29) + timedelta(i)
869 self.assertEqual(d.isocalendar(), (2004, 1, i+1))
870 d = self.theclass(2004, 1, 5+i)
871 self.assertEqual(d.isocalendar(), (2004, 2, i+1))
872 d = self.theclass(2009, 12, 21+i)
873 self.assertEqual(d.isocalendar(), (2009, 52, i+1))
874 d = self.theclass(2009, 12, 28) + timedelta(i)
875 self.assertEqual(d.isocalendar(), (2009, 53, i+1))
876 d = self.theclass(2010, 1, 4+i)
877 self.assertEqual(d.isocalendar(), (2010, 1, i+1))
878
879 def test_iso_long_years(self):
880 # Calculate long ISO years and compare to table from
881 # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
882 ISO_LONG_YEARS_TABLE = """
883 4 32 60 88
884 9 37 65 93
885 15 43 71 99
886 20 48 76
887 26 54 82
888
889 105 133 161 189
890 111 139 167 195
891 116 144 172
892 122 150 178
893 128 156 184
894
895 201 229 257 285
896 207 235 263 291
897 212 240 268 296
898 218 246 274
899 224 252 280
900
901 303 331 359 387
902 308 336 364 392
903 314 342 370 398
904 320 348 376
905 325 353 381
906 """
907 iso_long_years = map(int, ISO_LONG_YEARS_TABLE.split())
908 iso_long_years.sort()
909 L = []
910 for i in range(400):
911 d = self.theclass(2000+i, 12, 31)
912 d1 = self.theclass(1600+i, 12, 31)
913 self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:])
914 if d.isocalendar()[1] == 53:
915 L.append(i)
916 self.assertEqual(L, iso_long_years)
917
918 def test_isoformat(self):
919 t = self.theclass(2, 3, 2)
920 self.assertEqual(t.isoformat(), "0002-03-02")
921
922 def test_ctime(self):
923 t = self.theclass(2002, 3, 2)
924 self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002")
925
926 def test_strftime(self):
927 t = self.theclass(2005, 3, 2)
928 self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05")
929 self.assertEqual(t.strftime(""), "") # SF bug #761337
930 self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784
931
932 self.assertRaises(TypeError, t.strftime) # needs an arg
933 self.assertRaises(TypeError, t.strftime, "one", "two") # too many args
934 self.assertRaises(TypeError, t.strftime, 42) # arg wrong type
935
936 # test that unicode input is allowed (issue 2782)
937 self.assertEqual(t.strftime(u"%m"), "03")
938
939 # A naive object replaces %z and %Z w/ empty strings.
940 self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
941
942 #make sure that invalid format specifiers are handled correctly
943 #self.assertRaises(ValueError, t.strftime, "%e")
944 #self.assertRaises(ValueError, t.strftime, "%")
945 #self.assertRaises(ValueError, t.strftime, "%#")
946
947 #oh well, some systems just ignore those invalid ones.
948 #at least, exercise them to make sure that no crashes
949 #are generated
950 for f in ["%e", "%", "%#"]:
951 try:
952 t.strftime(f)
953 except ValueError:
954 pass
955
956 #check that this standard extension works
957 t.strftime("%f")
958
959
960 def test_format(self):
961 dt = self.theclass(2007, 9, 10)
962 self.assertEqual(dt.__format__(''), str(dt))
963
964 # check that a derived class's __str__() gets called
965 class A(self.theclass):
966 def __str__(self):
967 return 'A'
968 a = A(2007, 9, 10)
969 self.assertEqual(a.__format__(''), 'A')
970
971 # check that a derived class's strftime gets called
972 class B(self.theclass):
973 def strftime(self, format_spec):
974 return 'B'
975 b = B(2007, 9, 10)
976 self.assertEqual(b.__format__(''), str(dt))
977
978 for fmt in ["m:%m d:%d y:%y",
979 "m:%m d:%d y:%y H:%H M:%M S:%S",
980 "%z %Z",
981 ]:
982 self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
983 self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
984 self.assertEqual(b.__format__(fmt), 'B')
985
986 def test_resolution_info(self):
987 self.assertIsInstance(self.theclass.min, self.theclass)
988 self.assertIsInstance(self.theclass.max, self.theclass)
989 self.assertIsInstance(self.theclass.resolution, timedelta)
990 self.assertTrue(self.theclass.max > self.theclass.min)
991
992 def test_extreme_timedelta(self):
993 big = self.theclass.max - self.theclass.min
994 # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
995 n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
996 # n == 315537897599999999 ~= 2**58.13
997 justasbig = timedelta(0, 0, n)
998 self.assertEqual(big, justasbig)
999 self.assertEqual(self.theclass.min + big, self.theclass.max)
1000 self.assertEqual(self.theclass.max - big, self.theclass.min)
1001
1002 def test_timetuple(self):
1003 for i in range(7):
1004 # January 2, 1956 is a Monday (0)
1005 d = self.theclass(1956, 1, 2+i)
1006 t = d.timetuple()
1007 self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1))
1008 # February 1, 1956 is a Wednesday (2)
1009 d = self.theclass(1956, 2, 1+i)
1010 t = d.timetuple()
1011 self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1))
1012 # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day
1013 # of the year.
1014 d = self.theclass(1956, 3, 1+i)
1015 t = d.timetuple()
1016 self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1))
1017 self.assertEqual(t.tm_year, 1956)
1018 self.assertEqual(t.tm_mon, 3)
1019 self.assertEqual(t.tm_mday, 1+i)
1020 self.assertEqual(t.tm_hour, 0)
1021 self.assertEqual(t.tm_min, 0)
1022 self.assertEqual(t.tm_sec, 0)
1023 self.assertEqual(t.tm_wday, (3+i)%7)
1024 self.assertEqual(t.tm_yday, 61+i)
1025 self.assertEqual(t.tm_isdst, -1)
1026
1027 def test_pickling(self):
1028 args = 6, 7, 23
1029 orig = self.theclass(*args)
1030 for pickler, unpickler, proto in pickle_choices:
1031 green = pickler.dumps(orig, proto)
1032 derived = unpickler.loads(green)
1033 self.assertEqual(orig, derived)
1034
1035 def test_compare(self):
1036 t1 = self.theclass(2, 3, 4)
1037 t2 = self.theclass(2, 3, 4)
1038 self.assertTrue(t1 == t2)
1039 self.assertTrue(t1 <= t2)
1040 self.assertTrue(t1 >= t2)
1041 self.assertFalse(t1 != t2)
1042 self.assertFalse(t1 < t2)
1043 self.assertFalse(t1 > t2)
1044 self.assertEqual(cmp(t1, t2), 0)
1045 self.assertEqual(cmp(t2, t1), 0)
1046
1047 for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
1048 t2 = self.theclass(*args) # this is larger than t1
1049 self.assertTrue(t1 < t2)
1050 self.assertTrue(t2 > t1)
1051 self.assertTrue(t1 <= t2)
1052 self.assertTrue(t2 >= t1)
1053 self.assertTrue(t1 != t2)
1054 self.assertTrue(t2 != t1)
1055 self.assertFalse(t1 == t2)
1056 self.assertFalse(t2 == t1)
1057 self.assertFalse(t1 > t2)
1058 self.assertFalse(t2 < t1)
1059 self.assertFalse(t1 >= t2)
1060 self.assertFalse(t2 <= t1)
1061 self.assertEqual(cmp(t1, t2), -1)
1062 self.assertEqual(cmp(t2, t1), 1)
1063
1064 for badarg in OTHERSTUFF:
1065 self.assertEqual(t1 == badarg, False)
1066 self.assertEqual(t1 != badarg, True)
1067 self.assertEqual(badarg == t1, False)
1068 self.assertEqual(badarg != t1, True)
1069
1070 self.assertRaises(TypeError, lambda: t1 < badarg)
1071 self.assertRaises(TypeError, lambda: t1 > badarg)
1072 self.assertRaises(TypeError, lambda: t1 >= badarg)
1073 self.assertRaises(TypeError, lambda: badarg <= t1)
1074 self.assertRaises(TypeError, lambda: badarg < t1)
1075 self.assertRaises(TypeError, lambda: badarg > t1)
1076 self.assertRaises(TypeError, lambda: badarg >= t1)
1077
1078 def test_mixed_compare(self):
1079 our = self.theclass(2000, 4, 5)
1080 self.assertRaises(TypeError, cmp, our, 1)
1081 self.assertRaises(TypeError, cmp, 1, our)
1082
1083 class AnotherDateTimeClass(object):
1084 def __cmp__(self, other):
1085 # Return "equal" so calling this can't be confused with
1086 # compare-by-address (which never says "equal" for distinct
1087 # objects).
1088 return 0
1089 __hash__ = None # Silence Py3k warning
1090
1091 # This still errors, because date and datetime comparison raise
1092 # TypeError instead of NotImplemented when they don't know what to
1093 # do, in order to stop comparison from falling back to the default
1094 # compare-by-address.
1095 their = AnotherDateTimeClass()
1096 self.assertRaises(TypeError, cmp, our, their)
1097 # Oops: The next stab raises TypeError in the C implementation,
1098 # but not in the Python implementation of datetime. The difference
1099 # is due to that the Python implementation defines __cmp__ but
1100 # the C implementation defines tp_richcompare. This is more pain
1101 # to fix than it's worth, so commenting out the test.
1102 # self.assertEqual(cmp(their, our), 0)
1103
1104 # But date and datetime comparison return NotImplemented instead if the
1105 # other object has a timetuple attr. This gives the other object a
1106 # chance to do the comparison.
1107 class Comparable(AnotherDateTimeClass):
1108 def timetuple(self):
1109 return ()
1110
1111 their = Comparable()
1112 self.assertEqual(cmp(our, their), 0)
1113 self.assertEqual(cmp(their, our), 0)
1114 self.assertTrue(our == their)
1115 self.assertTrue(their == our)
1116
1117 def test_bool(self):
1118 # All dates are considered true.
1119 self.assertTrue(self.theclass.min)
1120 self.assertTrue(self.theclass.max)
1121
1122 def test_strftime_out_of_range(self):
1123 # For nasty technical reasons, we can't handle years before 1900.
1124 cls = self.theclass
1125 self.assertEqual(cls(1900, 1, 1).strftime("%Y"), "1900")
1126 for y in 1, 49, 51, 99, 100, 1000, 1899:
1127 self.assertRaises(ValueError, cls(y, 1, 1).strftime, "%Y")
1128
1129 def test_replace(self):
1130 cls = self.theclass
1131 args = [1, 2, 3]
1132 base = cls(*args)
1133 self.assertEqual(base, base.replace())
1134
1135 i = 0
1136 for name, newval in (("year", 2),
1137 ("month", 3),
1138 ("day", 4)):
1139 newargs = args[:]
1140 newargs[i] = newval
1141 expected = cls(*newargs)
1142 got = base.replace(**{name: newval})
1143 self.assertEqual(expected, got)
1144 i += 1
1145
1146 # Out of bounds.
1147 base = cls(2000, 2, 29)
1148 self.assertRaises(ValueError, base.replace, year=2001)
1149
1150 def test_subclass_date(self):
1151
1152 class C(self.theclass):
1153 theAnswer = 42
1154
1155 def __new__(cls, *args, **kws):
1156 temp = kws.copy()
1157 extra = temp.pop('extra')
1158 result = self.theclass.__new__(cls, *args, **temp)
1159 result.extra = extra
1160 return result
1161
1162 def newmeth(self, start):
1163 return start + self.year + self.month
1164
1165 args = 2003, 4, 14
1166
1167 dt1 = self.theclass(*args)
1168 dt2 = C(*args, **{'extra': 7})
1169
1170 self.assertEqual(dt2.__class__, C)
1171 self.assertEqual(dt2.theAnswer, 42)
1172 self.assertEqual(dt2.extra, 7)
1173 self.assertEqual(dt1.toordinal(), dt2.toordinal())
1174 self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month - 7)
1175
1176 def test_pickling_subclass_date(self):
1177
1178 args = 6, 7, 23
1179 orig = SubclassDate(*args)
1180 for pickler, unpickler, proto in pickle_choices:
1181 green = pickler.dumps(orig, proto)
1182 derived = unpickler.loads(green)
1183 self.assertEqual(orig, derived)
1184
1185 def test_backdoor_resistance(self):
1186 # For fast unpickling, the constructor accepts a pickle string.
1187 # This is a low-overhead backdoor. A user can (by intent or
1188 # mistake) pass a string directly, which (if it's the right length)
1189 # will get treated like a pickle, and bypass the normal sanity
1190 # checks in the constructor. This can create insane objects.
1191 # The constructor doesn't want to burn the time to validate all
1192 # fields, but does check the month field. This stops, e.g.,
1193 # datetime.datetime('1995-03-25') from yielding an insane object.
1194 base = '1995-03-25'
1195 if not issubclass(self.theclass, datetime):
1196 base = base[:4]
1197 for month_byte in '9', chr(0), chr(13), '\xff':
1198 self.assertRaises(TypeError, self.theclass,
1199 base[:2] + month_byte + base[3:])
1200 for ord_byte in range(1, 13):
1201 # This shouldn't blow up because of the month byte alone. If
1202 # the implementation changes to do more-careful checking, it may
1203 # blow up because other fields are insane.
1204 self.theclass(base[:2] + chr(ord_byte) + base[3:])
1205
1206 #############################################################################
1207 # datetime tests
1208
1209 class SubclassDatetime(datetime):
1210 sub_var = 1
1211
1212 class TestDateTime(TestDate):
1213
1214 theclass = datetime
1215
1216 def test_basic_attributes(self):
1217 dt = self.theclass(2002, 3, 1, 12, 0)
1218 self.assertEqual(dt.year, 2002)
1219 self.assertEqual(dt.month, 3)
1220 self.assertEqual(dt.day, 1)
1221 self.assertEqual(dt.hour, 12)
1222 self.assertEqual(dt.minute, 0)
1223 self.assertEqual(dt.second, 0)
1224 self.assertEqual(dt.microsecond, 0)
1225
1226 def test_basic_attributes_nonzero(self):
1227 # Make sure all attributes are non-zero so bugs in
1228 # bit-shifting access show up.
1229 dt = self.theclass(2002, 3, 1, 12, 59, 59, 8000)
1230 self.assertEqual(dt.year, 2002)
1231 self.assertEqual(dt.month, 3)
1232 self.assertEqual(dt.day, 1)
1233 self.assertEqual(dt.hour, 12)
1234 self.assertEqual(dt.minute, 59)
1235 self.assertEqual(dt.second, 59)
1236 self.assertEqual(dt.microsecond, 8000)
1237
1238 def test_roundtrip(self):
1239 for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
1240 self.theclass.now()):
1241 # Verify dt -> string -> datetime identity.
1242 s = repr(dt)
1243 self.assertTrue(s.startswith('datetime.'))
1244 s = s[9:]
1245 dt2 = eval(s)
1246 self.assertEqual(dt, dt2)
1247
1248 # Verify identity via reconstructing from pieces.
1249 dt2 = self.theclass(dt.year, dt.month, dt.day,
1250 dt.hour, dt.minute, dt.second,
1251 dt.microsecond)
1252 self.assertEqual(dt, dt2)
1253
1254 def test_isoformat(self):
1255 t = self.theclass(2, 3, 2, 4, 5, 1, 123)
1256 self.assertEqual(t.isoformat(), "0002-03-02T04:05:01.000123")
1257 self.assertEqual(t.isoformat('T'), "0002-03-02T04:05:01.000123")
1258 self.assertEqual(t.isoformat(' '), "0002-03-02 04:05:01.000123")
1259 self.assertEqual(t.isoformat('\x00'), "0002-03-02\x0004:05:01.000123")
1260 # str is ISO format with the separator forced to a blank.
1261 self.assertEqual(str(t), "0002-03-02 04:05:01.000123")
1262
1263 t = self.theclass(2, 3, 2)
1264 self.assertEqual(t.isoformat(), "0002-03-02T00:00:00")
1265 self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00")
1266 self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00")
1267 # str is ISO format with the separator forced to a blank.
1268 self.assertEqual(str(t), "0002-03-02 00:00:00")
1269
1270 def test_format(self):
1271 dt = self.theclass(2007, 9, 10, 4, 5, 1, 123)
1272 self.assertEqual(dt.__format__(''), str(dt))
1273
1274 # check that a derived class's __str__() gets called
1275 class A(self.theclass):
1276 def __str__(self):
1277 return 'A'
1278 a = A(2007, 9, 10, 4, 5, 1, 123)
1279 self.assertEqual(a.__format__(''), 'A')
1280
1281 # check that a derived class's strftime gets called
1282 class B(self.theclass):
1283 def strftime(self, format_spec):
1284 return 'B'
1285 b = B(2007, 9, 10, 4, 5, 1, 123)
1286 self.assertEqual(b.__format__(''), str(dt))
1287
1288 for fmt in ["m:%m d:%d y:%y",
1289 "m:%m d:%d y:%y H:%H M:%M S:%S",
1290 "%z %Z",
1291 ]:
1292 self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
1293 self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
1294 self.assertEqual(b.__format__(fmt), 'B')
1295
1296 def test_more_ctime(self):
1297 # Test fields that TestDate doesn't touch.
1298 import time
1299
1300 t = self.theclass(2002, 3, 2, 18, 3, 5, 123)
1301 self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002")
1302 # Oops! The next line fails on Win2K under MSVC 6, so it's commented
1303 # out. The difference is that t.ctime() produces " 2" for the day,
1304 # but platform ctime() produces "02" for the day. According to
1305 # C99, t.ctime() is correct here.
1306 # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
1307
1308 # So test a case where that difference doesn't matter.
1309 t = self.theclass(2002, 3, 22, 18, 3, 5, 123)
1310 self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
1311
1312 def test_tz_independent_comparing(self):
1313 dt1 = self.theclass(2002, 3, 1, 9, 0, 0)
1314 dt2 = self.theclass(2002, 3, 1, 10, 0, 0)
1315 dt3 = self.theclass(2002, 3, 1, 9, 0, 0)
1316 self.assertEqual(dt1, dt3)
1317 self.assertTrue(dt2 > dt3)
1318
1319 # Make sure comparison doesn't forget microseconds, and isn't done
1320 # via comparing a float timestamp (an IEEE double doesn't have enough
1321 # precision to span microsecond resolution across years 1 thru 9999,
1322 # so comparing via timestamp necessarily calls some distinct values
1323 # equal).
1324 dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998)
1325 us = timedelta(microseconds=1)
1326 dt2 = dt1 + us
1327 self.assertEqual(dt2 - dt1, us)
1328 self.assertTrue(dt1 < dt2)
1329
1330 def test_strftime_with_bad_tzname_replace(self):
1331 # verify ok if tzinfo.tzname().replace() returns a non-string
1332 class MyTzInfo(FixedOffset):
1333 def tzname(self, dt):
1334 class MyStr(str):
1335 def replace(self, *args):
1336 return None
1337 return MyStr('name')
1338 t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name'))
1339 self.assertRaises(TypeError, t.strftime, '%Z')
1340
1341 def test_bad_constructor_arguments(self):
1342 # bad years
1343 self.theclass(MINYEAR, 1, 1) # no exception
1344 self.theclass(MAXYEAR, 1, 1) # no exception
1345 self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
1346 self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
1347 # bad months
1348 self.theclass(2000, 1, 1) # no exception
1349 self.theclass(2000, 12, 1) # no exception
1350 self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
1351 self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
1352 # bad days
1353 self.theclass(2000, 2, 29) # no exception
1354 self.theclass(2004, 2, 29) # no exception
1355 self.theclass(2400, 2, 29) # no exception
1356 self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
1357 self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
1358 self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
1359 self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
1360 self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
1361 self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
1362 # bad hours
1363 self.theclass(2000, 1, 31, 0) # no exception
1364 self.theclass(2000, 1, 31, 23) # no exception
1365 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1)
1366 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24)
1367 # bad minutes
1368 self.theclass(2000, 1, 31, 23, 0) # no exception
1369 self.theclass(2000, 1, 31, 23, 59) # no exception
1370 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1)
1371 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60)
1372 # bad seconds
1373 self.theclass(2000, 1, 31, 23, 59, 0) # no exception
1374 self.theclass(2000, 1, 31, 23, 59, 59) # no exception
1375 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1)
1376 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60)
1377 # bad microseconds
1378 self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception
1379 self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception
1380 self.assertRaises(ValueError, self.theclass,
1381 2000, 1, 31, 23, 59, 59, -1)
1382 self.assertRaises(ValueError, self.theclass,
1383 2000, 1, 31, 23, 59, 59,
1384 1000000)
1385
1386 def test_hash_equality(self):
1387 d = self.theclass(2000, 12, 31, 23, 30, 17)
1388 e = self.theclass(2000, 12, 31, 23, 30, 17)
1389 self.assertEqual(d, e)
1390 self.assertEqual(hash(d), hash(e))
1391
1392 dic = {d: 1}
1393 dic[e] = 2
1394 self.assertEqual(len(dic), 1)
1395 self.assertEqual(dic[d], 2)
1396 self.assertEqual(dic[e], 2)
1397
1398 d = self.theclass(2001, 1, 1, 0, 5, 17)
1399 e = self.theclass(2001, 1, 1, 0, 5, 17)
1400 self.assertEqual(d, e)
1401 self.assertEqual(hash(d), hash(e))
1402
1403 dic = {d: 1}
1404 dic[e] = 2
1405 self.assertEqual(len(dic), 1)
1406 self.assertEqual(dic[d], 2)
1407 self.assertEqual(dic[e], 2)
1408
1409 def test_computations(self):
1410 a = self.theclass(2002, 1, 31)
1411 b = self.theclass(1956, 1, 31)
1412 diff = a-b
1413 self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
1414 self.assertEqual(diff.seconds, 0)
1415 self.assertEqual(diff.microseconds, 0)
1416 a = self.theclass(2002, 3, 2, 17, 6)
1417 millisec = timedelta(0, 0, 1000)
1418 hour = timedelta(0, 3600)
1419 day = timedelta(1)
1420 week = timedelta(7)
1421 self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6))
1422 self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6))
1423 self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6))
1424 self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6))
1425 self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6))
1426 self.assertEqual(a - hour, a + -hour)
1427 self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6))
1428 self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6))
1429 self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6))
1430 self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6))
1431 self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6))
1432 self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6))
1433 self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6))
1434 self.assertEqual((a + week) - a, week)
1435 self.assertEqual((a + day) - a, day)
1436 self.assertEqual((a + hour) - a, hour)
1437 self.assertEqual((a + millisec) - a, millisec)
1438 self.assertEqual((a - week) - a, -week)
1439 self.assertEqual((a - day) - a, -day)
1440 self.assertEqual((a - hour) - a, -hour)
1441 self.assertEqual((a - millisec) - a, -millisec)
1442 self.assertEqual(a - (a + week), -week)
1443 self.assertEqual(a - (a + day), -day)
1444 self.assertEqual(a - (a + hour), -hour)
1445 self.assertEqual(a - (a + millisec), -millisec)
1446 self.assertEqual(a - (a - week), week)
1447 self.assertEqual(a - (a - day), day)
1448 self.assertEqual(a - (a - hour), hour)
1449 self.assertEqual(a - (a - millisec), millisec)
1450 self.assertEqual(a + (week + day + hour + millisec),
1451 self.theclass(2002, 3, 10, 18, 6, 0, 1000))
1452 self.assertEqual(a + (week + day + hour + millisec),
1453 (((a + week) + day) + hour) + millisec)
1454 self.assertEqual(a - (week + day + hour + millisec),
1455 self.theclass(2002, 2, 22, 16, 5, 59, 999000))
1456 self.assertEqual(a - (week + day + hour + millisec),
1457 (((a - week) - day) - hour) - millisec)
1458 # Add/sub ints, longs, floats should be illegal
1459 for i in 1, 1L, 1.0:
1460 self.assertRaises(TypeError, lambda: a+i)
1461 self.assertRaises(TypeError, lambda: a-i)
1462 self.assertRaises(TypeError, lambda: i+a)
1463 self.assertRaises(TypeError, lambda: i-a)
1464
1465 # delta - datetime is senseless.
1466 self.assertRaises(TypeError, lambda: day - a)
1467 # mixing datetime and (delta or datetime) via * or // is senseless
1468 self.assertRaises(TypeError, lambda: day * a)
1469 self.assertRaises(TypeError, lambda: a * day)
1470 self.assertRaises(TypeError, lambda: day // a)
1471 self.assertRaises(TypeError, lambda: a // day)
1472 self.assertRaises(TypeError, lambda: a * a)
1473 self.assertRaises(TypeError, lambda: a // a)
1474 # datetime + datetime is senseless
1475 self.assertRaises(TypeError, lambda: a + a)
1476
1477 def test_pickling(self):
1478 args = 6, 7, 23, 20, 59, 1, 64**2
1479 orig = self.theclass(*args)
1480 for pickler, unpickler, proto in pickle_choices:
1481 green = pickler.dumps(orig, proto)
1482 derived = unpickler.loads(green)
1483 self.assertEqual(orig, derived)
1484
1485 def test_more_pickling(self):
1486 a = self.theclass(2003, 2, 7, 16, 48, 37, 444116)
1487 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1488 s = pickle.dumps(a, proto)
1489 b = pickle.loads(s)
1490 self.assertEqual(b.year, 2003)
1491 self.assertEqual(b.month, 2)
1492 self.assertEqual(b.day, 7)
1493
1494 def test_pickling_subclass_datetime(self):
1495 args = 6, 7, 23, 20, 59, 1, 64**2
1496 orig = SubclassDatetime(*args)
1497 for pickler, unpickler, proto in pickle_choices:
1498 green = pickler.dumps(orig, proto)
1499 derived = unpickler.loads(green)
1500 self.assertEqual(orig, derived)
1501
1502 def test_more_compare(self):
1503 # The test_compare() inherited from TestDate covers the error cases.
1504 # We just want to test lexicographic ordering on the members datetime
1505 # has that date lacks.
1506 args = [2000, 11, 29, 20, 58, 16, 999998]
1507 t1 = self.theclass(*args)
1508 t2 = self.theclass(*args)
1509 self.assertTrue(t1 == t2)
1510 self.assertTrue(t1 <= t2)
1511 self.assertTrue(t1 >= t2)
1512 self.assertFalse(t1 != t2)
1513 self.assertFalse(t1 < t2)
1514 self.assertFalse(t1 > t2)
1515 self.assertEqual(cmp(t1, t2), 0)
1516 self.assertEqual(cmp(t2, t1), 0)
1517
1518 for i in range(len(args)):
1519 newargs = args[:]
1520 newargs[i] = args[i] + 1
1521 t2 = self.theclass(*newargs) # this is larger than t1
1522 self.assertTrue(t1 < t2)
1523 self.assertTrue(t2 > t1)
1524 self.assertTrue(t1 <= t2)
1525 self.assertTrue(t2 >= t1)
1526 self.assertTrue(t1 != t2)
1527 self.assertTrue(t2 != t1)
1528 self.assertFalse(t1 == t2)
1529 self.assertFalse(t2 == t1)
1530 self.assertFalse(t1 > t2)
1531 self.assertFalse(t2 < t1)
1532 self.assertFalse(t1 >= t2)
1533 self.assertFalse(t2 <= t1)
1534 self.assertEqual(cmp(t1, t2), -1)
1535 self.assertEqual(cmp(t2, t1), 1)
1536
1537
1538 # A helper for timestamp constructor tests.
1539 def verify_field_equality(self, expected, got):
1540 self.assertEqual(expected.tm_year, got.year)
1541 self.assertEqual(expected.tm_mon, got.month)
1542 self.assertEqual(expected.tm_mday, got.day)
1543 self.assertEqual(expected.tm_hour, got.hour)
1544 self.assertEqual(expected.tm_min, got.minute)
1545 self.assertEqual(expected.tm_sec, got.second)
1546
1547 def test_fromtimestamp(self):
1548 import time
1549
1550 ts = time.time()
1551 expected = time.localtime(ts)
1552 got = self.theclass.fromtimestamp(ts)
1553 self.verify_field_equality(expected, got)
1554
1555 def test_utcfromtimestamp(self):
1556 import time
1557
1558 ts = time.time()
1559 expected = time.gmtime(ts)
1560 got = self.theclass.utcfromtimestamp(ts)
1561 self.verify_field_equality(expected, got)
1562
1563 def test_microsecond_rounding(self):
1564 # Test whether fromtimestamp "rounds up" floats that are less
1565 # than one microsecond smaller than an integer.
1566 self.assertEqual(self.theclass.fromtimestamp(0.9999999),
1567 self.theclass.fromtimestamp(1))
1568
1569 def test_insane_fromtimestamp(self):
1570 # It's possible that some platform maps time_t to double,
1571 # and that this test will fail there. This test should
1572 # exempt such platforms (provided they return reasonable
1573 # results!).
1574 for insane in -1e200, 1e200:
1575 self.assertRaises(ValueError, self.theclass.fromtimestamp,
1576 insane)
1577
1578 def test_insane_utcfromtimestamp(self):
1579 # It's possible that some platform maps time_t to double,
1580 # and that this test will fail there. This test should
1581 # exempt such platforms (provided they return reasonable
1582 # results!).
1583 for insane in -1e200, 1e200:
1584 self.assertRaises(ValueError, self.theclass.utcfromtimestamp,
1585 insane)
1586 @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
1587 def test_negative_float_fromtimestamp(self):
1588 # The result is tz-dependent; at least test that this doesn't
1589 # fail (like it did before bug 1646728 was fixed).
1590 self.theclass.fromtimestamp(-1.05)
1591
1592 @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
1593 def test_negative_float_utcfromtimestamp(self):
1594 d = self.theclass.utcfromtimestamp(-1.05)
1595 self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
1596
1597 def test_utcnow(self):
1598 import time
1599
1600 # Call it a success if utcnow() and utcfromtimestamp() are within
1601 # a second of each other.
1602 tolerance = timedelta(seconds=1)
1603 for dummy in range(3):
1604 from_now = self.theclass.utcnow()
1605 from_timestamp = self.theclass.utcfromtimestamp(time.time())
1606 if abs(from_timestamp - from_now) <= tolerance:
1607 break
1608 # Else try again a few times.
1609 self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
1610
1611 def test_strptime(self):
1612 import _strptime
1613
1614 string = '2004-12-01 13:02:47.197'
1615 format = '%Y-%m-%d %H:%M:%S.%f'
1616 result, frac = _strptime._strptime(string, format)
1617 expected = self.theclass(*(result[0:6]+(frac,)))
1618 got = self.theclass.strptime(string, format)
1619 self.assertEqual(expected, got)
1620
1621 def test_more_timetuple(self):
1622 # This tests fields beyond those tested by the TestDate.test_timetuple.
1623 t = self.theclass(2004, 12, 31, 6, 22, 33)
1624 self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1))
1625 self.assertEqual(t.timetuple(),
1626 (t.year, t.month, t.day,
1627 t.hour, t.minute, t.second,
1628 t.weekday(),
1629 t.toordinal() - date(t.year, 1, 1).toordinal() + 1,
1630 -1))
1631 tt = t.timetuple()
1632 self.assertEqual(tt.tm_year, t.year)
1633 self.assertEqual(tt.tm_mon, t.month)
1634 self.assertEqual(tt.tm_mday, t.day)
1635 self.assertEqual(tt.tm_hour, t.hour)
1636 self.assertEqual(tt.tm_min, t.minute)
1637 self.assertEqual(tt.tm_sec, t.second)
1638 self.assertEqual(tt.tm_wday, t.weekday())
1639 self.assertEqual(tt.tm_yday, t.toordinal() -
1640 date(t.year, 1, 1).toordinal() + 1)
1641 self.assertEqual(tt.tm_isdst, -1)
1642
1643 def test_more_strftime(self):
1644 # This tests fields beyond those tested by the TestDate.test_strftime.
1645 t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
1646 self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"),
1647 "12 31 04 000047 33 22 06 366")
1648
1649 def test_extract(self):
1650 dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
1651 self.assertEqual(dt.date(), date(2002, 3, 4))
1652 self.assertEqual(dt.time(), time(18, 45, 3, 1234))
1653
1654 def test_combine(self):
1655 d = date(2002, 3, 4)
1656 t = time(18, 45, 3, 1234)
1657 expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
1658 combine = self.theclass.combine
1659 dt = combine(d, t)
1660 self.assertEqual(dt, expected)
1661
1662 dt = combine(time=t, date=d)
1663 self.assertEqual(dt, expected)
1664
1665 self.assertEqual(d, dt.date())
1666 self.assertEqual(t, dt.time())
1667 self.assertEqual(dt, combine(dt.date(), dt.time()))
1668
1669 self.assertRaises(TypeError, combine) # need an arg
1670 self.assertRaises(TypeError, combine, d) # need two args
1671 self.assertRaises(TypeError, combine, t, d) # args reversed
1672 self.assertRaises(TypeError, combine, d, t, 1) # too many args
1673 self.assertRaises(TypeError, combine, "date", "time") # wrong types
1674
1675 def test_replace(self):
1676 cls = self.theclass
1677 args = [1, 2, 3, 4, 5, 6, 7]
1678 base = cls(*args)
1679 self.assertEqual(base, base.replace())
1680
1681 i = 0
1682 for name, newval in (("year", 2),
1683 ("month", 3),
1684 ("day", 4),
1685 ("hour", 5),
1686 ("minute", 6),
1687 ("second", 7),
1688 ("microsecond", 8)):
1689 newargs = args[:]
1690 newargs[i] = newval
1691 expected = cls(*newargs)
1692 got = base.replace(**{name: newval})
1693 self.assertEqual(expected, got)
1694 i += 1
1695
1696 # Out of bounds.
1697 base = cls(2000, 2, 29)
1698 self.assertRaises(ValueError, base.replace, year=2001)
1699
1700 def test_astimezone(self):
1701 # Pretty boring! The TZ test is more interesting here. astimezone()
1702 # simply can't be applied to a naive object.
1703 dt = self.theclass.now()
1704 f = FixedOffset(44, "")
1705 self.assertRaises(TypeError, dt.astimezone) # not enough args
1706 self.assertRaises(TypeError, dt.astimezone, f, f) # too many args
1707 self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type
1708 self.assertRaises(ValueError, dt.astimezone, f) # naive
1709 self.assertRaises(ValueError, dt.astimezone, tz=f) # naive
1710
1711 class Bogus(tzinfo):
1712 def utcoffset(self, dt): return None
1713 def dst(self, dt): return timedelta(0)
1714 bog = Bogus()
1715 self.assertRaises(ValueError, dt.astimezone, bog) # naive
1716
1717 class AlsoBogus(tzinfo):
1718 def utcoffset(self, dt): return timedelta(0)
1719 def dst(self, dt): return None
1720 alsobog = AlsoBogus()
1721 self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive
1722
1723 def test_subclass_datetime(self):
1724
1725 class C(self.theclass):
1726 theAnswer = 42
1727
1728 def __new__(cls, *args, **kws):
1729 temp = kws.copy()
1730 extra = temp.pop('extra')
1731 result = self.theclass.__new__(cls, *args, **temp)
1732 result.extra = extra
1733 return result
1734
1735 def newmeth(self, start):
1736 return start + self.year + self.month + self.second
1737
1738 args = 2003, 4, 14, 12, 13, 41
1739
1740 dt1 = self.theclass(*args)
1741 dt2 = C(*args, **{'extra': 7})
1742
1743 self.assertEqual(dt2.__class__, C)
1744 self.assertEqual(dt2.theAnswer, 42)
1745 self.assertEqual(dt2.extra, 7)
1746 self.assertEqual(dt1.toordinal(), dt2.toordinal())
1747 self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month +
1748 dt1.second - 7)
1749
1750 class SubclassTime(time):
1751 sub_var = 1
1752
1753 class TestTime(HarmlessMixedComparison, unittest.TestCase):
1754
1755 theclass = time
1756
1757 def test_basic_attributes(self):
1758 t = self.theclass(12, 0)
1759 self.assertEqual(t.hour, 12)
1760 self.assertEqual(t.minute, 0)
1761 self.assertEqual(t.second, 0)
1762 self.assertEqual(t.microsecond, 0)
1763
1764 def test_basic_attributes_nonzero(self):
1765 # Make sure all attributes are non-zero so bugs in
1766 # bit-shifting access show up.
1767 t = self.theclass(12, 59, 59, 8000)
1768 self.assertEqual(t.hour, 12)
1769 self.assertEqual(t.minute, 59)
1770 self.assertEqual(t.second, 59)
1771 self.assertEqual(t.microsecond, 8000)
1772
1773 def test_roundtrip(self):
1774 t = self.theclass(1, 2, 3, 4)
1775
1776 # Verify t -> string -> time identity.
1777 s = repr(t)
1778 self.assertTrue(s.startswith('datetime.'))
1779 s = s[9:]
1780 t2 = eval(s)
1781 self.assertEqual(t, t2)
1782
1783 # Verify identity via reconstructing from pieces.
1784 t2 = self.theclass(t.hour, t.minute, t.second,
1785 t.microsecond)
1786 self.assertEqual(t, t2)
1787
1788 def test_comparing(self):
1789 args = [1, 2, 3, 4]
1790 t1 = self.theclass(*args)
1791 t2 = self.theclass(*args)
1792 self.assertTrue(t1 == t2)
1793 self.assertTrue(t1 <= t2)
1794 self.assertTrue(t1 >= t2)
1795 self.assertFalse(t1 != t2)
1796 self.assertFalse(t1 < t2)
1797 self.assertFalse(t1 > t2)
1798 self.assertEqual(cmp(t1, t2), 0)
1799 self.assertEqual(cmp(t2, t1), 0)
1800
1801 for i in range(len(args)):
1802 newargs = args[:]
1803 newargs[i] = args[i] + 1
1804 t2 = self.theclass(*newargs) # this is larger than t1
1805 self.assertTrue(t1 < t2)
1806 self.assertTrue(t2 > t1)
1807 self.assertTrue(t1 <= t2)
1808 self.assertTrue(t2 >= t1)
1809 self.assertTrue(t1 != t2)
1810 self.assertTrue(t2 != t1)
1811 self.assertFalse(t1 == t2)
1812 self.assertFalse(t2 == t1)
1813 self.assertFalse(t1 > t2)
1814 self.assertFalse(t2 < t1)
1815 self.assertFalse(t1 >= t2)
1816 self.assertFalse(t2 <= t1)
1817 self.assertEqual(cmp(t1, t2), -1)
1818 self.assertEqual(cmp(t2, t1), 1)
1819
1820 for badarg in OTHERSTUFF:
1821 self.assertEqual(t1 == badarg, False)
1822 self.assertEqual(t1 != badarg, True)
1823 self.assertEqual(badarg == t1, False)
1824 self.assertEqual(badarg != t1, True)
1825
1826 self.assertRaises(TypeError, lambda: t1 <= badarg)
1827 self.assertRaises(TypeError, lambda: t1 < badarg)
1828 self.assertRaises(TypeError, lambda: t1 > badarg)
1829 self.assertRaises(TypeError, lambda: t1 >= badarg)
1830 self.assertRaises(TypeError, lambda: badarg <= t1)
1831 self.assertRaises(TypeError, lambda: badarg < t1)
1832 self.assertRaises(TypeError, lambda: badarg > t1)
1833 self.assertRaises(TypeError, lambda: badarg >= t1)
1834
1835 def test_bad_constructor_arguments(self):
1836 # bad hours
1837 self.theclass(0, 0) # no exception
1838 self.theclass(23, 0) # no exception
1839 self.assertRaises(ValueError, self.theclass, -1, 0)
1840 self.assertRaises(ValueError, self.theclass, 24, 0)
1841 # bad minutes
1842 self.theclass(23, 0) # no exception
1843 self.theclass(23, 59) # no exception
1844 self.assertRaises(ValueError, self.theclass, 23, -1)
1845 self.assertRaises(ValueError, self.theclass, 23, 60)
1846 # bad seconds
1847 self.theclass(23, 59, 0) # no exception
1848 self.theclass(23, 59, 59) # no exception
1849 self.assertRaises(ValueError, self.theclass, 23, 59, -1)
1850 self.assertRaises(ValueError, self.theclass, 23, 59, 60)
1851 # bad microseconds
1852 self.theclass(23, 59, 59, 0) # no exception
1853 self.theclass(23, 59, 59, 999999) # no exception
1854 self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1)
1855 self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000)
1856
1857 def test_hash_equality(self):
1858 d = self.theclass(23, 30, 17)
1859 e = self.theclass(23, 30, 17)
1860 self.assertEqual(d, e)
1861 self.assertEqual(hash(d), hash(e))
1862
1863 dic = {d: 1}
1864 dic[e] = 2
1865 self.assertEqual(len(dic), 1)
1866 self.assertEqual(dic[d], 2)
1867 self.assertEqual(dic[e], 2)
1868
1869 d = self.theclass(0, 5, 17)
1870 e = self.theclass(0, 5, 17)
1871 self.assertEqual(d, e)
1872 self.assertEqual(hash(d), hash(e))
1873
1874 dic = {d: 1}
1875 dic[e] = 2
1876 self.assertEqual(len(dic), 1)
1877 self.assertEqual(dic[d], 2)
1878 self.assertEqual(dic[e], 2)
1879
1880 def test_isoformat(self):
1881 t = self.theclass(4, 5, 1, 123)
1882 self.assertEqual(t.isoformat(), "04:05:01.000123")
1883 self.assertEqual(t.isoformat(), str(t))
1884
1885 t = self.theclass()
1886 self.assertEqual(t.isoformat(), "00:00:00")
1887 self.assertEqual(t.isoformat(), str(t))
1888
1889 t = self.theclass(microsecond=1)
1890 self.assertEqual(t.isoformat(), "00:00:00.000001")
1891 self.assertEqual(t.isoformat(), str(t))
1892
1893 t = self.theclass(microsecond=10)
1894 self.assertEqual(t.isoformat(), "00:00:00.000010")
1895 self.assertEqual(t.isoformat(), str(t))
1896
1897 t = self.theclass(microsecond=100)
1898 self.assertEqual(t.isoformat(), "00:00:00.000100")
1899 self.assertEqual(t.isoformat(), str(t))
1900
1901 t = self.theclass(microsecond=1000)
1902 self.assertEqual(t.isoformat(), "00:00:00.001000")
1903 self.assertEqual(t.isoformat(), str(t))
1904
1905 t = self.theclass(microsecond=10000)
1906 self.assertEqual(t.isoformat(), "00:00:00.010000")
1907 self.assertEqual(t.isoformat(), str(t))
1908
1909 t = self.theclass(microsecond=100000)
1910 self.assertEqual(t.isoformat(), "00:00:00.100000")
1911 self.assertEqual(t.isoformat(), str(t))
1912
1913 def test_1653736(self):
1914 # verify it doesn't accept extra keyword arguments
1915 t = self.theclass(second=1)
1916 self.assertRaises(TypeError, t.isoformat, foo=3)
1917
1918 def test_strftime(self):
1919 t = self.theclass(1, 2, 3, 4)
1920 self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004")
1921 # A naive object replaces %z and %Z with empty strings.
1922 self.assertEqual(t.strftime("'%z' '%Z'"), "'' ''")
1923
1924 def test_format(self):
1925 t = self.theclass(1, 2, 3, 4)
1926 self.assertEqual(t.__format__(''), str(t))
1927
1928 # check that a derived class's __str__() gets called
1929 class A(self.theclass):
1930 def __str__(self):
1931 return 'A'
1932 a = A(1, 2, 3, 4)
1933 self.assertEqual(a.__format__(''), 'A')
1934
1935 # check that a derived class's strftime gets called
1936 class B(self.theclass):
1937 def strftime(self, format_spec):
1938 return 'B'
1939 b = B(1, 2, 3, 4)
1940 self.assertEqual(b.__format__(''), str(t))
1941
1942 for fmt in ['%H %M %S',
1943 ]:
1944 self.assertEqual(t.__format__(fmt), t.strftime(fmt))
1945 self.assertEqual(a.__format__(fmt), t.strftime(fmt))
1946 self.assertEqual(b.__format__(fmt), 'B')
1947
1948 def test_str(self):
1949 self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004")
1950 self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000")
1951 self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000")
1952 self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03")
1953 self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00")
1954
1955 def test_repr(self):
1956 name = 'datetime.' + self.theclass.__name__
1957 self.assertEqual(repr(self.theclass(1, 2, 3, 4)),
1958 "%s(1, 2, 3, 4)" % name)
1959 self.assertEqual(repr(self.theclass(10, 2, 3, 4000)),
1960 "%s(10, 2, 3, 4000)" % name)
1961 self.assertEqual(repr(self.theclass(0, 2, 3, 400000)),
1962 "%s(0, 2, 3, 400000)" % name)
1963 self.assertEqual(repr(self.theclass(12, 2, 3, 0)),
1964 "%s(12, 2, 3)" % name)
1965 self.assertEqual(repr(self.theclass(23, 15, 0, 0)),
1966 "%s(23, 15)" % name)
1967
1968 def test_resolution_info(self):
1969 self.assertIsInstance(self.theclass.min, self.theclass)
1970 self.assertIsInstance(self.theclass.max, self.theclass)
1971 self.assertIsInstance(self.theclass.resolution, timedelta)
1972 self.assertTrue(self.theclass.max > self.theclass.min)
1973
1974 def test_pickling(self):
1975 args = 20, 59, 16, 64**2
1976 orig = self.theclass(*args)
1977 for pickler, unpickler, proto in pickle_choices:
1978 green = pickler.dumps(orig, proto)
1979 derived = unpickler.loads(green)
1980 self.assertEqual(orig, derived)
1981
1982 def test_pickling_subclass_time(self):
1983 args = 20, 59, 16, 64**2
1984 orig = SubclassTime(*args)
1985 for pickler, unpickler, proto in pickle_choices:
1986 green = pickler.dumps(orig, proto)
1987 derived = unpickler.loads(green)
1988 self.assertEqual(orig, derived)
1989
1990 def test_bool(self):
1991 cls = self.theclass
1992 self.assertTrue(cls(1))
1993 self.assertTrue(cls(0, 1))
1994 self.assertTrue(cls(0, 0, 1))
1995 self.assertTrue(cls(0, 0, 0, 1))
1996 self.assertFalse(cls(0))
1997 self.assertFalse(cls())
1998
1999 def test_replace(self):
2000 cls = self.theclass
2001 args = [1, 2, 3, 4]
2002 base = cls(*args)
2003 self.assertEqual(base, base.replace())
2004
2005 i = 0
2006 for name, newval in (("hour", 5),
2007 ("minute", 6),
2008 ("second", 7),
2009 ("microsecond", 8)):
2010 newargs = args[:]
2011 newargs[i] = newval
2012 expected = cls(*newargs)
2013 got = base.replace(**{name: newval})
2014 self.assertEqual(expected, got)
2015 i += 1
2016
2017 # Out of bounds.
2018 base = cls(1)
2019 self.assertRaises(ValueError, base.replace, hour=24)
2020 self.assertRaises(ValueError, base.replace, minute=-1)
2021 self.assertRaises(ValueError, base.replace, second=100)
2022 self.assertRaises(ValueError, base.replace, microsecond=1000000)
2023
2024 def test_subclass_time(self):
2025
2026 class C(self.theclass):
2027 theAnswer = 42
2028
2029 def __new__(cls, *args, **kws):
2030 temp = kws.copy()
2031 extra = temp.pop('extra')
2032 result = self.theclass.__new__(cls, *args, **temp)
2033 result.extra = extra
2034 return result
2035
2036 def newmeth(self, start):
2037 return start + self.hour + self.second
2038
2039 args = 4, 5, 6
2040
2041 dt1 = self.theclass(*args)
2042 dt2 = C(*args, **{'extra': 7})
2043
2044 self.assertEqual(dt2.__class__, C)
2045 self.assertEqual(dt2.theAnswer, 42)
2046 self.assertEqual(dt2.extra, 7)
2047 self.assertEqual(dt1.isoformat(), dt2.isoformat())
2048 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
2049
2050 def test_backdoor_resistance(self):
2051 # see TestDate.test_backdoor_resistance().
2052 base = '2:59.0'
2053 for hour_byte in ' ', '9', chr(24), '\xff':
2054 self.assertRaises(TypeError, self.theclass,
2055 hour_byte + base[1:])
2056
2057 # A mixin for classes with a tzinfo= argument. Subclasses must define
2058 # theclass as a class attribute, and theclass(1, 1, 1, tzinfo=whatever)
2059 # must be legit (which is true for time and datetime).
2060 class TZInfoBase:
2061
2062 def test_argument_passing(self):
2063 cls = self.theclass
2064 # A datetime passes itself on, a time passes None.
2065 class introspective(tzinfo):
2066 def tzname(self, dt): return dt and "real" or "none"
2067 def utcoffset(self, dt):
2068 return timedelta(minutes = dt and 42 or -42)
2069 dst = utcoffset
2070
2071 obj = cls(1, 2, 3, tzinfo=introspective())
2072
2073 expected = cls is time and "none" or "real"
2074 self.assertEqual(obj.tzname(), expected)
2075
2076 expected = timedelta(minutes=(cls is time and -42 or 42))
2077 self.assertEqual(obj.utcoffset(), expected)
2078 self.assertEqual(obj.dst(), expected)
2079
2080 def test_bad_tzinfo_classes(self):
2081 cls = self.theclass
2082 self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12)
2083
2084 class NiceTry(object):
2085 def __init__(self): pass
2086 def utcoffset(self, dt): pass
2087 self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry)
2088
2089 class BetterTry(tzinfo):
2090 def __init__(self): pass
2091 def utcoffset(self, dt): pass
2092 b = BetterTry()
2093 t = cls(1, 1, 1, tzinfo=b)
2094 self.assertIs(t.tzinfo, b)
2095
2096 def test_utc_offset_out_of_bounds(self):
2097 class Edgy(tzinfo):
2098 def __init__(self, offset):
2099 self.offset = timedelta(minutes=offset)
2100 def utcoffset(self, dt):
2101 return self.offset
2102
2103 cls = self.theclass
2104 for offset, legit in ((-1440, False),
2105 (-1439, True),
2106 (1439, True),
2107 (1440, False)):
2108 if cls is time:
2109 t = cls(1, 2, 3, tzinfo=Edgy(offset))
2110 elif cls is datetime:
2111 t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset))
2112 else:
2113 assert 0, "impossible"
2114 if legit:
2115 aofs = abs(offset)
2116 h, m = divmod(aofs, 60)
2117 tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m)
2118 if isinstance(t, datetime):
2119 t = t.timetz()
2120 self.assertEqual(str(t), "01:02:03" + tag)
2121 else:
2122 self.assertRaises(ValueError, str, t)
2123
2124 def test_tzinfo_classes(self):
2125 cls = self.theclass
2126 class C1(tzinfo):
2127 def utcoffset(self, dt): return None
2128 def dst(self, dt): return None
2129 def tzname(self, dt): return None
2130 for t in (cls(1, 1, 1),
2131 cls(1, 1, 1, tzinfo=None),
2132 cls(1, 1, 1, tzinfo=C1())):
2133 self.assertIsNone(t.utcoffset())
2134 self.assertIsNone(t.dst())
2135 self.assertIsNone(t.tzname())
2136
2137 class C3(tzinfo):
2138 def utcoffset(self, dt): return timedelta(minutes=-1439)
2139 def dst(self, dt): return timedelta(minutes=1439)
2140 def tzname(self, dt): return "aname"
2141 t = cls(1, 1, 1, tzinfo=C3())
2142 self.assertEqual(t.utcoffset(), timedelta(minutes=-1439))
2143 self.assertEqual(t.dst(), timedelta(minutes=1439))
2144 self.assertEqual(t.tzname(), "aname")
2145
2146 # Wrong types.
2147 class C4(tzinfo):
2148 def utcoffset(self, dt): return "aname"
2149 def dst(self, dt): return 7
2150 def tzname(self, dt): return 0
2151 t = cls(1, 1, 1, tzinfo=C4())
2152 self.assertRaises(TypeError, t.utcoffset)
2153 self.assertRaises(TypeError, t.dst)
2154 self.assertRaises(TypeError, t.tzname)
2155
2156 # Offset out of range.
2157 class C6(tzinfo):
2158 def utcoffset(self, dt): return timedelta(hours=-24)
2159 def dst(self, dt): return timedelta(hours=24)
2160 t = cls(1, 1, 1, tzinfo=C6())
2161 self.assertRaises(ValueError, t.utcoffset)
2162 self.assertRaises(ValueError, t.dst)
2163
2164 # Not a whole number of minutes.
2165 class C7(tzinfo):
2166 def utcoffset(self, dt): return timedelta(seconds=61)
2167 def dst(self, dt): return timedelta(microseconds=-81)
2168 t = cls(1, 1, 1, tzinfo=C7())
2169 self.assertRaises(ValueError, t.utcoffset)
2170 self.assertRaises(ValueError, t.dst)
2171
2172 def test_aware_compare(self):
2173 cls = self.theclass
2174
2175 # Ensure that utcoffset() gets ignored if the comparands have
2176 # the same tzinfo member.
2177 class OperandDependentOffset(tzinfo):
2178 def utcoffset(self, t):
2179 if t.minute < 10:
2180 # d0 and d1 equal after adjustment
2181 return timedelta(minutes=t.minute)
2182 else:
2183 # d2 off in the weeds
2184 return timedelta(minutes=59)
2185
2186 base = cls(8, 9, 10, tzinfo=OperandDependentOffset())
2187 d0 = base.replace(minute=3)
2188 d1 = base.replace(minute=9)
2189 d2 = base.replace(minute=11)
2190 for x in d0, d1, d2:
2191 for y in d0, d1, d2:
2192 got = cmp(x, y)
2193 expected = cmp(x.minute, y.minute)
2194 self.assertEqual(got, expected)
2195
2196 # However, if they're different members, uctoffset is not ignored.
2197 # Note that a time can't actually have an operand-depedent offset,
2198 # though (and time.utcoffset() passes None to tzinfo.utcoffset()),
2199 # so skip this test for time.
2200 if cls is not time:
2201 d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
2202 d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
2203 d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
2204 for x in d0, d1, d2:
2205 for y in d0, d1, d2:
2206 got = cmp(x, y)
2207 if (x is d0 or x is d1) and (y is d0 or y is d1):
2208 expected = 0
2209 elif x is y is d2:
2210 expected = 0
2211 elif x is d2:
2212 expected = -1
2213 else:
2214 assert y is d2
2215 expected = 1
2216 self.assertEqual(got, expected)
2217
2218
2219 # Testing time objects with a non-None tzinfo.
2220 class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
2221 theclass = time
2222
2223 def test_empty(self):
2224 t = self.theclass()
2225 self.assertEqual(t.hour, 0)
2226 self.assertEqual(t.minute, 0)
2227 self.assertEqual(t.second, 0)
2228 self.assertEqual(t.microsecond, 0)
2229 self.assertIsNone(t.tzinfo)
2230
2231 def test_zones(self):
2232 est = FixedOffset(-300, "EST", 1)
2233 utc = FixedOffset(0, "UTC", -2)
2234 met = FixedOffset(60, "MET", 3)
2235 t1 = time( 7, 47, tzinfo=est)
2236 t2 = time(12, 47, tzinfo=utc)
2237 t3 = time(13, 47, tzinfo=met)
2238 t4 = time(microsecond=40)
2239 t5 = time(microsecond=40, tzinfo=utc)
2240
2241 self.assertEqual(t1.tzinfo, est)
2242 self.assertEqual(t2.tzinfo, utc)
2243 self.assertEqual(t3.tzinfo, met)
2244 self.assertIsNone(t4.tzinfo)
2245 self.assertEqual(t5.tzinfo, utc)
2246
2247 self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
2248 self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
2249 self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
2250 self.assertIsNone(t4.utcoffset())
2251 self.assertRaises(TypeError, t1.utcoffset, "no args")
2252
2253 self.assertEqual(t1.tzname(), "EST")
2254 self.assertEqual(t2.tzname(), "UTC")
2255 self.assertEqual(t3.tzname(), "MET")
2256 self.assertIsNone(t4.tzname())
2257 self.assertRaises(TypeError, t1.tzname, "no args")
2258
2259 self.assertEqual(t1.dst(), timedelta(minutes=1))
2260 self.assertEqual(t2.dst(), timedelta(minutes=-2))
2261 self.assertEqual(t3.dst(), timedelta(minutes=3))
2262 self.assertIsNone(t4.dst())
2263 self.assertRaises(TypeError, t1.dst, "no args")
2264
2265 self.assertEqual(hash(t1), hash(t2))
2266 self.assertEqual(hash(t1), hash(t3))
2267 self.assertEqual(hash(t2), hash(t3))
2268
2269 self.assertEqual(t1, t2)
2270 self.assertEqual(t1, t3)
2271 self.assertEqual(t2, t3)
2272 self.assertRaises(TypeError, lambda: t4 == t5) # mixed tz-aware & naive
2273 self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive
2274 self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive
2275
2276 self.assertEqual(str(t1), "07:47:00-05:00")
2277 self.assertEqual(str(t2), "12:47:00+00:00")
2278 self.assertEqual(str(t3), "13:47:00+01:00")
2279 self.assertEqual(str(t4), "00:00:00.000040")
2280 self.assertEqual(str(t5), "00:00:00.000040+00:00")
2281
2282 self.assertEqual(t1.isoformat(), "07:47:00-05:00")
2283 self.assertEqual(t2.isoformat(), "12:47:00+00:00")
2284 self.assertEqual(t3.isoformat(), "13:47:00+01:00")
2285 self.assertEqual(t4.isoformat(), "00:00:00.000040")
2286 self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00")
2287
2288 d = 'datetime.time'
2289 self.assertEqual(repr(t1), d + "(7, 47, tzinfo=est)")
2290 self.assertEqual(repr(t2), d + "(12, 47, tzinfo=utc)")
2291 self.assertEqual(repr(t3), d + "(13, 47, tzinfo=met)")
2292 self.assertEqual(repr(t4), d + "(0, 0, 0, 40)")
2293 self.assertEqual(repr(t5), d + "(0, 0, 0, 40, tzinfo=utc)")
2294
2295 self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"),
2296 "07:47:00 %Z=EST %z=-0500")
2297 self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000")
2298 self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100")
2299
2300 yuck = FixedOffset(-1439, "%z %Z %%z%%Z")
2301 t1 = time(23, 59, tzinfo=yuck)
2302 self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"),
2303 "23:59 %Z='%z %Z %%z%%Z' %z='-2359'")
2304
2305 # Check that an invalid tzname result raises an exception.
2306 class Badtzname(tzinfo):
2307 def tzname(self, dt): return 42
2308 t = time(2, 3, 4, tzinfo=Badtzname())
2309 self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04")
2310 self.assertRaises(TypeError, t.strftime, "%Z")
2311
2312 def test_hash_edge_cases(self):
2313 # Offsets that overflow a basic time.
2314 t1 = self.theclass(0, 1, 2, 3, tzinfo=FixedOffset(1439, ""))
2315 t2 = self.theclass(0, 0, 2, 3, tzinfo=FixedOffset(1438, ""))
2316 self.assertEqual(hash(t1), hash(t2))
2317
2318 t1 = self.theclass(23, 58, 6, 100, tzinfo=FixedOffset(-1000, ""))
2319 t2 = self.theclass(23, 48, 6, 100, tzinfo=FixedOffset(-1010, ""))
2320 self.assertEqual(hash(t1), hash(t2))
2321
2322 def test_pickling(self):
2323 # Try one without a tzinfo.
2324 args = 20, 59, 16, 64**2
2325 orig = self.theclass(*args)
2326 for pickler, unpickler, proto in pickle_choices:
2327 green = pickler.dumps(orig, proto)
2328 derived = unpickler.loads(green)
2329 self.assertEqual(orig, derived)
2330
2331 # Try one with a tzinfo.
2332 tinfo = PicklableFixedOffset(-300, 'cookie')
2333 orig = self.theclass(5, 6, 7, tzinfo=tinfo)
2334 for pickler, unpickler, proto in pickle_choices:
2335 green = pickler.dumps(orig, proto)
2336 derived = unpickler.loads(green)
2337 self.assertEqual(orig, derived)
2338 self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
2339 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
2340 self.assertEqual(derived.tzname(), 'cookie')
2341
2342 def test_more_bool(self):
2343 # Test cases with non-None tzinfo.
2344 cls = self.theclass
2345
2346 t = cls(0, tzinfo=FixedOffset(-300, ""))
2347 self.assertTrue(t)
2348
2349 t = cls(5, tzinfo=FixedOffset(-300, ""))
2350 self.assertTrue(t)
2351
2352 t = cls(5, tzinfo=FixedOffset(300, ""))
2353 self.assertFalse(t)
2354
2355 t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, ""))
2356 self.assertFalse(t)
2357
2358 # Mostly ensuring this doesn't overflow internally.
2359 t = cls(0, tzinfo=FixedOffset(23*60 + 59, ""))
2360 self.assertTrue(t)
2361
2362 # But this should yield a value error -- the utcoffset is bogus.
2363 t = cls(0, tzinfo=FixedOffset(24*60, ""))
2364 self.assertRaises(ValueError, lambda: bool(t))
2365
2366 # Likewise.
2367 t = cls(0, tzinfo=FixedOffset(-24*60, ""))
2368 self.assertRaises(ValueError, lambda: bool(t))
2369
2370 def test_replace(self):
2371 cls = self.theclass
2372 z100 = FixedOffset(100, "+100")
2373 zm200 = FixedOffset(timedelta(minutes=-200), "-200")
2374 args = [1, 2, 3, 4, z100]
2375 base = cls(*args)
2376 self.assertEqual(base, base.replace())
2377
2378 i = 0
2379 for name, newval in (("hour", 5),
2380 ("minute", 6),
2381 ("second", 7),
2382 ("microsecond", 8),
2383 ("tzinfo", zm200)):
2384 newargs = args[:]
2385 newargs[i] = newval
2386 expected = cls(*newargs)
2387 got = base.replace(**{name: newval})
2388 self.assertEqual(expected, got)
2389 i += 1
2390
2391 # Ensure we can get rid of a tzinfo.
2392 self.assertEqual(base.tzname(), "+100")
2393 base2 = base.replace(tzinfo=None)
2394 self.assertIsNone(base2.tzinfo)
2395 self.assertIsNone(base2.tzname())
2396
2397 # Ensure we can add one.
2398 base3 = base2.replace(tzinfo=z100)
2399 self.assertEqual(base, base3)
2400 self.assertIs(base.tzinfo, base3.tzinfo)
2401
2402 # Out of bounds.
2403 base = cls(1)
2404 self.assertRaises(ValueError, base.replace, hour=24)
2405 self.assertRaises(ValueError, base.replace, minute=-1)
2406 self.assertRaises(ValueError, base.replace, second=100)
2407 self.assertRaises(ValueError, base.replace, microsecond=1000000)
2408
2409 def test_mixed_compare(self):
2410 t1 = time(1, 2, 3)
2411 t2 = time(1, 2, 3)
2412 self.assertEqual(t1, t2)
2413 t2 = t2.replace(tzinfo=None)
2414 self.assertEqual(t1, t2)
2415 t2 = t2.replace(tzinfo=FixedOffset(None, ""))
2416 self.assertEqual(t1, t2)
2417 t2 = t2.replace(tzinfo=FixedOffset(0, ""))
2418 self.assertRaises(TypeError, lambda: t1 == t2)
2419
2420 # In time w/ identical tzinfo objects, utcoffset is ignored.
2421 class Varies(tzinfo):
2422 def __init__(self):
2423 self.offset = timedelta(minutes=22)
2424 def utcoffset(self, t):
2425 self.offset += timedelta(minutes=1)
2426 return self.offset
2427
2428 v = Varies()
2429 t1 = t2.replace(tzinfo=v)
2430 t2 = t2.replace(tzinfo=v)
2431 self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
2432 self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
2433 self.assertEqual(t1, t2)
2434
2435 # But if they're not identical, it isn't ignored.
2436 t2 = t2.replace(tzinfo=Varies())
2437 self.assertTrue(t1 < t2) # t1's offset counter still going up
2438
2439 def test_subclass_timetz(self):
2440
2441 class C(self.theclass):
2442 theAnswer = 42
2443
2444 def __new__(cls, *args, **kws):
2445 temp = kws.copy()
2446 extra = temp.pop('extra')
2447 result = self.theclass.__new__(cls, *args, **temp)
2448 result.extra = extra
2449 return result
2450
2451 def newmeth(self, start):
2452 return start + self.hour + self.second
2453
2454 args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
2455
2456 dt1 = self.theclass(*args)
2457 dt2 = C(*args, **{'extra': 7})
2458
2459 self.assertEqual(dt2.__class__, C)
2460 self.assertEqual(dt2.theAnswer, 42)
2461 self.assertEqual(dt2.extra, 7)
2462 self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
2463 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
2464
2465
2466 # Testing datetime objects with a non-None tzinfo.
2467
2468 class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
2469 theclass = datetime
2470
2471 def test_trivial(self):
2472 dt = self.theclass(1, 2, 3, 4, 5, 6, 7)
2473 self.assertEqual(dt.year, 1)
2474 self.assertEqual(dt.month, 2)
2475 self.assertEqual(dt.day, 3)
2476 self.assertEqual(dt.hour, 4)
2477 self.assertEqual(dt.minute, 5)
2478 self.assertEqual(dt.second, 6)
2479 self.assertEqual(dt.microsecond, 7)
2480 self.assertEqual(dt.tzinfo, None)
2481
2482 def test_even_more_compare(self):
2483 # The test_compare() and test_more_compare() inherited from TestDate
2484 # and TestDateTime covered non-tzinfo cases.
2485
2486 # Smallest possible after UTC adjustment.
2487 t1 = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
2488 # Largest possible after UTC adjustment.
2489 t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
2490 tzinfo=FixedOffset(-1439, ""))
2491
2492 # Make sure those compare correctly, and w/o overflow.
2493 self.assertTrue(t1 < t2)
2494 self.assertTrue(t1 != t2)
2495 self.assertTrue(t2 > t1)
2496
2497 self.assertTrue(t1 == t1)
2498 self.assertTrue(t2 == t2)
2499
2500 # Equal afer adjustment.
2501 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""))
2502 t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3*60+13+2, ""))
2503 self.assertEqual(t1, t2)
2504
2505 # Change t1 not to subtract a minute, and t1 should be larger.
2506 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, ""))
2507 self.assertTrue(t1 > t2)
2508
2509 # Change t1 to subtract 2 minutes, and t1 should be smaller.
2510 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, ""))
2511 self.assertTrue(t1 < t2)
2512
2513 # Back to the original t1, but make seconds resolve it.
2514 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
2515 second=1)
2516 self.assertTrue(t1 > t2)
2517
2518 # Likewise, but make microseconds resolve it.
2519 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
2520 microsecond=1)
2521 self.assertTrue(t1 > t2)
2522
2523 # Make t2 naive and it should fail.
2524 t2 = self.theclass.min
2525 self.assertRaises(TypeError, lambda: t1 == t2)
2526 self.assertEqual(t2, t2)
2527
2528 # It's also naive if it has tzinfo but tzinfo.utcoffset() is None.
2529 class Naive(tzinfo):
2530 def utcoffset(self, dt): return None
2531 t2 = self.theclass(5, 6, 7, tzinfo=Naive())
2532 self.assertRaises(TypeError, lambda: t1 == t2)
2533 self.assertEqual(t2, t2)
2534
2535 # OTOH, it's OK to compare two of these mixing the two ways of being
2536 # naive.
2537 t1 = self.theclass(5, 6, 7)
2538 self.assertEqual(t1, t2)
2539
2540 # Try a bogus uctoffset.
2541 class Bogus(tzinfo):
2542 def utcoffset(self, dt):
2543 return timedelta(minutes=1440) # out of bounds
2544 t1 = self.theclass(2, 2, 2, tzinfo=Bogus())
2545 t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, ""))
2546 self.assertRaises(ValueError, lambda: t1 == t2)
2547
2548 def test_pickling(self):
2549 # Try one without a tzinfo.
2550 args = 6, 7, 23, 20, 59, 1, 64**2
2551 orig = self.theclass(*args)
2552 for pickler, unpickler, proto in pickle_choices:
2553 green = pickler.dumps(orig, proto)
2554 derived = unpickler.loads(green)
2555 self.assertEqual(orig, derived)
2556
2557 # Try one with a tzinfo.
2558 tinfo = PicklableFixedOffset(-300, 'cookie')
2559 orig = self.theclass(*args, **{'tzinfo': tinfo})
2560 derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0))
2561 for pickler, unpickler, proto in pickle_choices:
2562 green = pickler.dumps(orig, proto)
2563 derived = unpickler.loads(green)
2564 self.assertEqual(orig, derived)
2565 self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
2566 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
2567 self.assertEqual(derived.tzname(), 'cookie')
2568
2569 def test_extreme_hashes(self):
2570 # If an attempt is made to hash these via subtracting the offset
2571 # then hashing a datetime object, OverflowError results. The
2572 # Python implementation used to blow up here.
2573 t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
2574 hash(t)
2575 t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
2576 tzinfo=FixedOffset(-1439, ""))
2577 hash(t)
2578
2579 # OTOH, an OOB offset should blow up.
2580 t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, ""))
2581 self.assertRaises(ValueError, hash, t)
2582
2583 def test_zones(self):
2584 est = FixedOffset(-300, "EST")
2585 utc = FixedOffset(0, "UTC")
2586 met = FixedOffset(60, "MET")
2587 t1 = datetime(2002, 3, 19, 7, 47, tzinfo=est)
2588 t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc)
2589 t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met)
2590 self.assertEqual(t1.tzinfo, est)
2591 self.assertEqual(t2.tzinfo, utc)
2592 self.assertEqual(t3.tzinfo, met)
2593 self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
2594 self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
2595 self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
2596 self.assertEqual(t1.tzname(), "EST")
2597 self.assertEqual(t2.tzname(), "UTC")
2598 self.assertEqual(t3.tzname(), "MET")
2599 self.assertEqual(hash(t1), hash(t2))
2600 self.assertEqual(hash(t1), hash(t3))
2601 self.assertEqual(hash(t2), hash(t3))
2602 self.assertEqual(t1, t2)
2603 self.assertEqual(t1, t3)
2604 self.assertEqual(t2, t3)
2605 self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00")
2606 self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00")
2607 self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00")
2608 d = 'datetime.datetime(2002, 3, 19, '
2609 self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)")
2610 self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)")
2611 self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)")
2612
2613 def test_combine(self):
2614 met = FixedOffset(60, "MET")
2615 d = date(2002, 3, 4)
2616 tz = time(18, 45, 3, 1234, tzinfo=met)
2617 dt = datetime.combine(d, tz)
2618 self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234,
2619 tzinfo=met))
2620
2621 def test_extract(self):
2622 met = FixedOffset(60, "MET")
2623 dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met)
2624 self.assertEqual(dt.date(), date(2002, 3, 4))
2625 self.assertEqual(dt.time(), time(18, 45, 3, 1234))
2626 self.assertEqual(dt.timetz(), time(18, 45, 3, 1234, tzinfo=met))
2627
2628 def test_tz_aware_arithmetic(self):
2629 import random
2630
2631 now = self.theclass.now()
2632 tz55 = FixedOffset(-330, "west 5:30")
2633 timeaware = now.time().replace(tzinfo=tz55)
2634 nowaware = self.theclass.combine(now.date(), timeaware)
2635 self.assertIs(nowaware.tzinfo, tz55)
2636 self.assertEqual(nowaware.timetz(), timeaware)
2637
2638 # Can't mix aware and non-aware.
2639 self.assertRaises(TypeError, lambda: now - nowaware)
2640 self.assertRaises(TypeError, lambda: nowaware - now)
2641
2642 # And adding datetime's doesn't make sense, aware or not.
2643 self.assertRaises(TypeError, lambda: now + nowaware)
2644 self.assertRaises(TypeError, lambda: nowaware + now)
2645 self.assertRaises(TypeError, lambda: nowaware + nowaware)
2646
2647 # Subtracting should yield 0.
2648 self.assertEqual(now - now, timedelta(0))
2649 self.assertEqual(nowaware - nowaware, timedelta(0))
2650
2651 # Adding a delta should preserve tzinfo.
2652 delta = timedelta(weeks=1, minutes=12, microseconds=5678)
2653 nowawareplus = nowaware + delta
2654 self.assertIs(nowaware.tzinfo, tz55)
2655 nowawareplus2 = delta + nowaware
2656 self.assertIs(nowawareplus2.tzinfo, tz55)
2657 self.assertEqual(nowawareplus, nowawareplus2)
2658
2659 # that - delta should be what we started with, and that - what we
2660 # started with should be delta.
2661 diff = nowawareplus - delta
2662 self.assertIs(diff.tzinfo, tz55)
2663 self.assertEqual(nowaware, diff)
2664 self.assertRaises(TypeError, lambda: delta - nowawareplus)
2665 self.assertEqual(nowawareplus - nowaware, delta)
2666
2667 # Make up a random timezone.
2668 tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
2669 # Attach it to nowawareplus.
2670 nowawareplus = nowawareplus.replace(tzinfo=tzr)
2671 self.assertIs(nowawareplus.tzinfo, tzr)
2672 # Make sure the difference takes the timezone adjustments into account.
2673 got = nowaware - nowawareplus
2674 # Expected: (nowaware base - nowaware offset) -
2675 # (nowawareplus base - nowawareplus offset) =
2676 # (nowaware base - nowawareplus base) +
2677 # (nowawareplus offset - nowaware offset) =
2678 # -delta + nowawareplus offset - nowaware offset
2679 expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
2680 self.assertEqual(got, expected)
2681
2682 # Try max possible difference.
2683 min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
2684 max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
2685 tzinfo=FixedOffset(-1439, "max"))
2686 maxdiff = max - min
2687 self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
2688 timedelta(minutes=2*1439))
2689
2690 def test_tzinfo_now(self):
2691 meth = self.theclass.now
2692 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2693 base = meth()
2694 # Try with and without naming the keyword.
2695 off42 = FixedOffset(42, "42")
2696 another = meth(off42)
2697 again = meth(tz=off42)
2698 self.assertIs(another.tzinfo, again.tzinfo)
2699 self.assertEqual(another.utcoffset(), timedelta(minutes=42))
2700 # Bad argument with and w/o naming the keyword.
2701 self.assertRaises(TypeError, meth, 16)
2702 self.assertRaises(TypeError, meth, tzinfo=16)
2703 # Bad keyword name.
2704 self.assertRaises(TypeError, meth, tinfo=off42)
2705 # Too many args.
2706 self.assertRaises(TypeError, meth, off42, off42)
2707
2708 # We don't know which time zone we're in, and don't have a tzinfo
2709 # class to represent it, so seeing whether a tz argument actually
2710 # does a conversion is tricky.
2711 weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
2712 utc = FixedOffset(0, "utc", 0)
2713 for dummy in range(3):
2714 now = datetime.now(weirdtz)
2715 self.assertIs(now.tzinfo, weirdtz)
2716 utcnow = datetime.utcnow().replace(tzinfo=utc)
2717 now2 = utcnow.astimezone(weirdtz)
2718 if abs(now - now2) < timedelta(seconds=30):
2719 break
2720 # Else the code is broken, or more than 30 seconds passed between
2721 # calls; assuming the latter, just try again.
2722 else:
2723 # Three strikes and we're out.
2724 self.fail("utcnow(), now(tz), or astimezone() may be broken")
2725
2726 def test_tzinfo_fromtimestamp(self):
2727 import time
2728 meth = self.theclass.fromtimestamp
2729 ts = time.time()
2730 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2731 base = meth(ts)
2732 # Try with and without naming the keyword.
2733 off42 = FixedOffset(42, "42")
2734 another = meth(ts, off42)
2735 again = meth(ts, tz=off42)
2736 self.assertIs(another.tzinfo, again.tzinfo)
2737 self.assertEqual(another.utcoffset(), timedelta(minutes=42))
2738 # Bad argument with and w/o naming the keyword.
2739 self.assertRaises(TypeError, meth, ts, 16)
2740 self.assertRaises(TypeError, meth, ts, tzinfo=16)
2741 # Bad keyword name.
2742 self.assertRaises(TypeError, meth, ts, tinfo=off42)
2743 # Too many args.
2744 self.assertRaises(TypeError, meth, ts, off42, off42)
2745 # Too few args.
2746 self.assertRaises(TypeError, meth)
2747
2748 # Try to make sure tz= actually does some conversion.
2749 timestamp = 1000000000
2750 utcdatetime = datetime.utcfromtimestamp(timestamp)
2751 # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
2752 # But on some flavor of Mac, it's nowhere near that. So we can't have
2753 # any idea here what time that actually is, we can only test that
2754 # relative changes match.
2755 utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
2756 tz = FixedOffset(utcoffset, "tz", 0)
2757 expected = utcdatetime + utcoffset
2758 got = datetime.fromtimestamp(timestamp, tz)
2759 self.assertEqual(expected, got.replace(tzinfo=None))
2760
2761 def test_tzinfo_utcnow(self):
2762 meth = self.theclass.utcnow
2763 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2764 base = meth()
2765 # Try with and without naming the keyword; for whatever reason,
2766 # utcnow() doesn't accept a tzinfo argument.
2767 off42 = FixedOffset(42, "42")
2768 self.assertRaises(TypeError, meth, off42)
2769 self.assertRaises(TypeError, meth, tzinfo=off42)
2770
2771 def test_tzinfo_utcfromtimestamp(self):
2772 import time
2773 meth = self.theclass.utcfromtimestamp
2774 ts = time.time()
2775 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
2776 base = meth(ts)
2777 # Try with and without naming the keyword; for whatever reason,
2778 # utcfromtimestamp() doesn't accept a tzinfo argument.
2779 off42 = FixedOffset(42, "42")
2780 self.assertRaises(TypeError, meth, ts, off42)
2781 self.assertRaises(TypeError, meth, ts, tzinfo=off42)
2782
2783 def test_tzinfo_timetuple(self):
2784 # TestDateTime tested most of this. datetime adds a twist to the
2785 # DST flag.
2786 class DST(tzinfo):
2787 def __init__(self, dstvalue):
2788 if isinstance(dstvalue, int):
2789 dstvalue = timedelta(minutes=dstvalue)
2790 self.dstvalue = dstvalue
2791 def dst(self, dt):
2792 return self.dstvalue
2793
2794 cls = self.theclass
2795 for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1):
2796 d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue))
2797 t = d.timetuple()
2798 self.assertEqual(1, t.tm_year)
2799 self.assertEqual(1, t.tm_mon)
2800 self.assertEqual(1, t.tm_mday)
2801 self.assertEqual(10, t.tm_hour)
2802 self.assertEqual(20, t.tm_min)
2803 self.assertEqual(30, t.tm_sec)
2804 self.assertEqual(0, t.tm_wday)
2805 self.assertEqual(1, t.tm_yday)
2806 self.assertEqual(flag, t.tm_isdst)
2807
2808 # dst() returns wrong type.
2809 self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple)
2810
2811 # dst() at the edge.
2812 self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1)
2813 self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1)
2814
2815 # dst() out of range.
2816 self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple)
2817 self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple)
2818
2819 def test_utctimetuple(self):
2820 class DST(tzinfo):
2821 def __init__(self, dstvalue):
2822 if isinstance(dstvalue, int):
2823 dstvalue = timedelta(minutes=dstvalue)
2824 self.dstvalue = dstvalue
2825 def dst(self, dt):
2826 return self.dstvalue
2827
2828 cls = self.theclass
2829 # This can't work: DST didn't implement utcoffset.
2830 self.assertRaises(NotImplementedError,
2831 cls(1, 1, 1, tzinfo=DST(0)).utcoffset)
2832
2833 class UOFS(DST):
2834 def __init__(self, uofs, dofs=None):
2835 DST.__init__(self, dofs)
2836 self.uofs = timedelta(minutes=uofs)
2837 def utcoffset(self, dt):
2838 return self.uofs
2839
2840 # Ensure tm_isdst is 0 regardless of what dst() says: DST is never
2841 # in effect for a UTC time.
2842 for dstvalue in -33, 33, 0, None:
2843 d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=UOFS(-53, dstvalue))
2844 t = d.utctimetuple()
2845 self.assertEqual(d.year, t.tm_year)
2846 self.assertEqual(d.month, t.tm_mon)
2847 self.assertEqual(d.day, t.tm_mday)
2848 self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm
2849 self.assertEqual(13, t.tm_min)
2850 self.assertEqual(d.second, t.tm_sec)
2851 self.assertEqual(d.weekday(), t.tm_wday)
2852 self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1,
2853 t.tm_yday)
2854 self.assertEqual(0, t.tm_isdst)
2855
2856 # At the edges, UTC adjustment can normalize into years out-of-range
2857 # for a datetime object. Ensure that a correct timetuple is
2858 # created anyway.
2859 tiny = cls(MINYEAR, 1, 1, 0, 0, 37, tzinfo=UOFS(1439))
2860 # That goes back 1 minute less than a full day.
2861 t = tiny.utctimetuple()
2862 self.assertEqual(t.tm_year, MINYEAR-1)
2863 self.assertEqual(t.tm_mon, 12)
2864 self.assertEqual(t.tm_mday, 31)
2865 self.assertEqual(t.tm_hour, 0)
2866 self.assertEqual(t.tm_min, 1)
2867 self.assertEqual(t.tm_sec, 37)
2868 self.assertEqual(t.tm_yday, 366) # "year 0" is a leap year
2869 self.assertEqual(t.tm_isdst, 0)
2870
2871 huge = cls(MAXYEAR, 12, 31, 23, 59, 37, 999999, tzinfo=UOFS(-1439))
2872 # That goes forward 1 minute less than a full day.
2873 t = huge.utctimetuple()
2874 self.assertEqual(t.tm_year, MAXYEAR+1)
2875 self.assertEqual(t.tm_mon, 1)
2876 self.assertEqual(t.tm_mday, 1)
2877 self.assertEqual(t.tm_hour, 23)
2878 self.assertEqual(t.tm_min, 58)
2879 self.assertEqual(t.tm_sec, 37)
2880 self.assertEqual(t.tm_yday, 1)
2881 self.assertEqual(t.tm_isdst, 0)
2882
2883 def test_tzinfo_isoformat(self):
2884 zero = FixedOffset(0, "+00:00")
2885 plus = FixedOffset(220, "+03:40")
2886 minus = FixedOffset(-231, "-03:51")
2887 unknown = FixedOffset(None, "")
2888
2889 cls = self.theclass
2890 datestr = '0001-02-03'
2891 for ofs in None, zero, plus, minus, unknown:
2892 for us in 0, 987001:
2893 d = cls(1, 2, 3, 4, 5, 59, us, tzinfo=ofs)
2894 timestr = '04:05:59' + (us and '.987001' or '')
2895 ofsstr = ofs is not None and d.tzname() or ''
2896 tailstr = timestr + ofsstr
2897 iso = d.isoformat()
2898 self.assertEqual(iso, datestr + 'T' + tailstr)
2899 self.assertEqual(iso, d.isoformat('T'))
2900 self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr)
2901 self.assertEqual(str(d), datestr + ' ' + tailstr)
2902
2903 def test_replace(self):
2904 cls = self.theclass
2905 z100 = FixedOffset(100, "+100")
2906 zm200 = FixedOffset(timedelta(minutes=-200), "-200")
2907 args = [1, 2, 3, 4, 5, 6, 7, z100]
2908 base = cls(*args)
2909 self.assertEqual(base, base.replace())
2910
2911 i = 0
2912 for name, newval in (("year", 2),
2913 ("month", 3),
2914 ("day", 4),
2915 ("hour", 5),
2916 ("minute", 6),
2917 ("second", 7),
2918 ("microsecond", 8),
2919 ("tzinfo", zm200)):
2920 newargs = args[:]
2921 newargs[i] = newval
2922 expected = cls(*newargs)
2923 got = base.replace(**{name: newval})
2924 self.assertEqual(expected, got)
2925 i += 1
2926
2927 # Ensure we can get rid of a tzinfo.
2928 self.assertEqual(base.tzname(), "+100")
2929 base2 = base.replace(tzinfo=None)
2930 self.assertIsNone(base2.tzinfo)
2931 self.assertIsNone(base2.tzname())
2932
2933 # Ensure we can add one.
2934 base3 = base2.replace(tzinfo=z100)
2935 self.assertEqual(base, base3)
2936 self.assertIs(base.tzinfo, base3.tzinfo)
2937
2938 # Out of bounds.
2939 base = cls(2000, 2, 29)
2940 self.assertRaises(ValueError, base.replace, year=2001)
2941
2942 def test_more_astimezone(self):
2943 # The inherited test_astimezone covered some trivial and error cases.
2944 fnone = FixedOffset(None, "None")
2945 f44m = FixedOffset(44, "44")
2946 fm5h = FixedOffset(-timedelta(hours=5), "m300")
2947
2948 dt = self.theclass.now(tz=f44m)
2949 self.assertIs(dt.tzinfo, f44m)
2950 # Replacing with degenerate tzinfo raises an exception.
2951 self.assertRaises(ValueError, dt.astimezone, fnone)
2952 # Ditto with None tz.
2953 self.assertRaises(TypeError, dt.astimezone, None)
2954 # Replacing with same tzinfo makes no change.
2955 x = dt.astimezone(dt.tzinfo)
2956 self.assertIs(x.tzinfo, f44m)
2957 self.assertEqual(x.date(), dt.date())
2958 self.assertEqual(x.time(), dt.time())
2959
2960 # Replacing with different tzinfo does adjust.
2961 got = dt.astimezone(fm5h)
2962 self.assertIs(got.tzinfo, fm5h)
2963 self.assertEqual(got.utcoffset(), timedelta(hours=-5))
2964 expected = dt - dt.utcoffset() # in effect, convert to UTC
2965 expected += fm5h.utcoffset(dt) # and from there to local time
2966 expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo
2967 self.assertEqual(got.date(), expected.date())
2968 self.assertEqual(got.time(), expected.time())
2969 self.assertEqual(got.timetz(), expected.timetz())
2970 self.assertIs(got.tzinfo, expected.tzinfo)
2971 self.assertEqual(got, expected)
2972
2973 def test_aware_subtract(self):
2974 cls = self.theclass
2975
2976 # Ensure that utcoffset() is ignored when the operands have the
2977 # same tzinfo member.
2978 class OperandDependentOffset(tzinfo):
2979 def utcoffset(self, t):
2980 if t.minute < 10:
2981 # d0 and d1 equal after adjustment
2982 return timedelta(minutes=t.minute)
2983 else:
2984 # d2 off in the weeds
2985 return timedelta(minutes=59)
2986
2987 base = cls(8, 9, 10, 11, 12, 13, 14, tzinfo=OperandDependentOffset())
2988 d0 = base.replace(minute=3)
2989 d1 = base.replace(minute=9)
2990 d2 = base.replace(minute=11)
2991 for x in d0, d1, d2:
2992 for y in d0, d1, d2:
2993 got = x - y
2994 expected = timedelta(minutes=x.minute - y.minute)
2995 self.assertEqual(got, expected)
2996
2997 # OTOH, if the tzinfo members are distinct, utcoffsets aren't
2998 # ignored.
2999 base = cls(8, 9, 10, 11, 12, 13, 14)
3000 d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
3001 d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
3002 d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
3003 for x in d0, d1, d2:
3004 for y in d0, d1, d2:
3005 got = x - y
3006 if (x is d0 or x is d1) and (y is d0 or y is d1):
3007 expected = timedelta(0)
3008 elif x is y is d2:
3009 expected = timedelta(0)
3010 elif x is d2:
3011 expected = timedelta(minutes=(11-59)-0)
3012 else:
3013 assert y is d2
3014 expected = timedelta(minutes=0-(11-59))
3015 self.assertEqual(got, expected)
3016
3017 def test_mixed_compare(self):
3018 t1 = datetime(1, 2, 3, 4, 5, 6, 7)
3019 t2 = datetime(1, 2, 3, 4, 5, 6, 7)
3020 self.assertEqual(t1, t2)
3021 t2 = t2.replace(tzinfo=None)
3022 self.assertEqual(t1, t2)
3023 t2 = t2.replace(tzinfo=FixedOffset(None, ""))
3024 self.assertEqual(t1, t2)
3025 t2 = t2.replace(tzinfo=FixedOffset(0, ""))
3026 self.assertRaises(TypeError, lambda: t1 == t2)
3027
3028 # In datetime w/ identical tzinfo objects, utcoffset is ignored.
3029 class Varies(tzinfo):
3030 def __init__(self):
3031 self.offset = timedelta(minutes=22)
3032 def utcoffset(self, t):
3033 self.offset += timedelta(minutes=1)
3034 return self.offset
3035
3036 v = Varies()
3037 t1 = t2.replace(tzinfo=v)
3038 t2 = t2.replace(tzinfo=v)
3039 self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
3040 self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
3041 self.assertEqual(t1, t2)
3042
3043 # But if they're not identical, it isn't ignored.
3044 t2 = t2.replace(tzinfo=Varies())
3045 self.assertTrue(t1 < t2) # t1's offset counter still going up
3046
3047 def test_subclass_datetimetz(self):
3048
3049 class C(self.theclass):
3050 theAnswer = 42
3051
3052 def __new__(cls, *args, **kws):
3053 temp = kws.copy()
3054 extra = temp.pop('extra')
3055 result = self.theclass.__new__(cls, *args, **temp)
3056 result.extra = extra
3057 return result
3058
3059 def newmeth(self, start):
3060 return start + self.hour + self.year
3061
3062 args = 2002, 12, 31, 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
3063
3064 dt1 = self.theclass(*args)
3065 dt2 = C(*args, **{'extra': 7})
3066
3067 self.assertEqual(dt2.__class__, C)
3068 self.assertEqual(dt2.theAnswer, 42)
3069 self.assertEqual(dt2.extra, 7)
3070 self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
3071 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.year - 7)
3072
3073 # Pain to set up DST-aware tzinfo classes.
3074
3075 def first_sunday_on_or_after(dt):
3076 days_to_go = 6 - dt.weekday()
3077 if days_to_go:
3078 dt += timedelta(days_to_go)
3079 return dt
3080
3081 ZERO = timedelta(0)
3082 HOUR = timedelta(hours=1)
3083 DAY = timedelta(days=1)
3084 # In the US, DST starts at 2am (standard time) on the first Sunday in April.
3085 DSTSTART = datetime(1, 4, 1, 2)
3086 # and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct,
3087 # which is the first Sunday on or after Oct 25. Because we view 1:MM as
3088 # being standard time on that day, there is no spelling in local time of
3089 # the last hour of DST (that's 1:MM DST, but 1:MM is taken as standard time).
3090 DSTEND = datetime(1, 10, 25, 1)
3091
3092 class USTimeZone(tzinfo):
3093
3094 def __init__(self, hours, reprname, stdname, dstname):
3095 self.stdoffset = timedelta(hours=hours)
3096 self.reprname = reprname
3097 self.stdname = stdname
3098 self.dstname = dstname
3099
3100 def __repr__(self):
3101 return self.reprname
3102
3103 def tzname(self, dt):
3104 if self.dst(dt):
3105 return self.dstname
3106 else:
3107 return self.stdname
3108
3109 def utcoffset(self, dt):
3110 return self.stdoffset + self.dst(dt)
3111
3112 def dst(self, dt):
3113 if dt is None or dt.tzinfo is None:
3114 # An exception instead may be sensible here, in one or more of
3115 # the cases.
3116 return ZERO
3117 assert dt.tzinfo is self
3118
3119 # Find first Sunday in April.
3120 start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
3121 assert start.weekday() == 6 and start.month == 4 and start.day <= 7
3122
3123 # Find last Sunday in October.
3124 end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
3125 assert end.weekday() == 6 and end.month == 10 and end.day >= 25
3126
3127 # Can't compare naive to aware objects, so strip the timezone from
3128 # dt first.
3129 if start <= dt.replace(tzinfo=None) < end:
3130 return HOUR
3131 else:
3132 return ZERO
3133
3134 Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
3135 Central = USTimeZone(-6, "Central", "CST", "CDT")
3136 Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
3137 Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
3138 utc_real = FixedOffset(0, "UTC", 0)
3139 # For better test coverage, we want another flavor of UTC that's west of
3140 # the Eastern and Pacific timezones.
3141 utc_fake = FixedOffset(-12*60, "UTCfake", 0)
3142
3143 class TestTimezoneConversions(unittest.TestCase):
3144 # The DST switch times for 2002, in std time.
3145 dston = datetime(2002, 4, 7, 2)
3146 dstoff = datetime(2002, 10, 27, 1)
3147
3148 theclass = datetime
3149
3150 # Check a time that's inside DST.
3151 def checkinside(self, dt, tz, utc, dston, dstoff):
3152 self.assertEqual(dt.dst(), HOUR)
3153
3154 # Conversion to our own timezone is always an identity.
3155 self.assertEqual(dt.astimezone(tz), dt)
3156
3157 asutc = dt.astimezone(utc)
3158 there_and_back = asutc.astimezone(tz)
3159
3160 # Conversion to UTC and back isn't always an identity here,
3161 # because there are redundant spellings (in local time) of
3162 # UTC time when DST begins: the clock jumps from 1:59:59
3163 # to 3:00:00, and a local time of 2:MM:SS doesn't really
3164 # make sense then. The classes above treat 2:MM:SS as
3165 # daylight time then (it's "after 2am"), really an alias
3166 # for 1:MM:SS standard time. The latter form is what
3167 # conversion back from UTC produces.
3168 if dt.date() == dston.date() and dt.hour == 2:
3169 # We're in the redundant hour, and coming back from
3170 # UTC gives the 1:MM:SS standard-time spelling.
3171 self.assertEqual(there_and_back + HOUR, dt)
3172 # Although during was considered to be in daylight
3173 # time, there_and_back is not.
3174 self.assertEqual(there_and_back.dst(), ZERO)
3175 # They're the same times in UTC.
3176 self.assertEqual(there_and_back.astimezone(utc),
3177 dt.astimezone(utc))
3178 else:
3179 # We're not in the redundant hour.
3180 self.assertEqual(dt, there_and_back)
3181
3182 # Because we have a redundant spelling when DST begins, there is
3183 # (unfortunately) an hour when DST ends that can't be spelled at all in
3184 # local time. When DST ends, the clock jumps from 1:59 back to 1:00
3185 # again. The hour 1:MM DST has no spelling then: 1:MM is taken to be
3186 # standard time. 1:MM DST == 0:MM EST, but 0:MM is taken to be
3187 # daylight time. The hour 1:MM daylight == 0:MM standard can't be
3188 # expressed in local time. Nevertheless, we want conversion back
3189 # from UTC to mimic the local clock's "repeat an hour" behavior.
3190 nexthour_utc = asutc + HOUR
3191 nexthour_tz = nexthour_utc.astimezone(tz)
3192 if dt.date() == dstoff.date() and dt.hour == 0:
3193 # We're in the hour before the last DST hour. The last DST hour
3194 # is ineffable. We want the conversion back to repeat 1:MM.
3195 self.assertEqual(nexthour_tz, dt.replace(hour=1))
3196 nexthour_utc += HOUR
3197 nexthour_tz = nexthour_utc.astimezone(tz)
3198 self.assertEqual(nexthour_tz, dt.replace(hour=1))
3199 else:
3200 self.assertEqual(nexthour_tz - dt, HOUR)
3201
3202 # Check a time that's outside DST.
3203 def checkoutside(self, dt, tz, utc):
3204 self.assertEqual(dt.dst(), ZERO)
3205
3206 # Conversion to our own timezone is always an identity.
3207 self.assertEqual(dt.astimezone(tz), dt)
3208
3209 # Converting to UTC and back is an identity too.
3210 asutc = dt.astimezone(utc)
3211 there_and_back = asutc.astimezone(tz)
3212 self.assertEqual(dt, there_and_back)
3213
3214 def convert_between_tz_and_utc(self, tz, utc):
3215 dston = self.dston.replace(tzinfo=tz)
3216 # Because 1:MM on the day DST ends is taken as being standard time,
3217 # there is no spelling in tz for the last hour of daylight time.
3218 # For purposes of the test, the last hour of DST is 0:MM, which is
3219 # taken as being daylight time (and 1:MM is taken as being standard
3220 # time).
3221 dstoff = self.dstoff.replace(tzinfo=tz)
3222 for delta in (timedelta(weeks=13),
3223 DAY,
3224 HOUR,
3225 timedelta(minutes=1),
3226 timedelta(microseconds=1)):
3227
3228 self.checkinside(dston, tz, utc, dston, dstoff)
3229 for during in dston + delta, dstoff - delta:
3230 self.checkinside(during, tz, utc, dston, dstoff)
3231
3232 self.checkoutside(dstoff, tz, utc)
3233 for outside in dston - delta, dstoff + delta:
3234 self.checkoutside(outside, tz, utc)
3235
3236 def test_easy(self):
3237 # Despite the name of this test, the endcases are excruciating.
3238 self.convert_between_tz_and_utc(Eastern, utc_real)
3239 self.convert_between_tz_and_utc(Pacific, utc_real)
3240 self.convert_between_tz_and_utc(Eastern, utc_fake)
3241 self.convert_between_tz_and_utc(Pacific, utc_fake)
3242 # The next is really dancing near the edge. It works because
3243 # Pacific and Eastern are far enough apart that their "problem
3244 # hours" don't overlap.
3245 self.convert_between_tz_and_utc(Eastern, Pacific)
3246 self.convert_between_tz_and_utc(Pacific, Eastern)
3247 # OTOH, these fail! Don't enable them. The difficulty is that
3248 # the edge case tests assume that every hour is representable in
3249 # the "utc" class. This is always true for a fixed-offset tzinfo
3250 # class (lke utc_real and utc_fake), but not for Eastern or Central.
3251 # For these adjacent DST-aware time zones, the range of time offsets
3252 # tested ends up creating hours in the one that aren't representable
3253 # in the other. For the same reason, we would see failures in the
3254 # Eastern vs Pacific tests too if we added 3*HOUR to the list of
3255 # offset deltas in convert_between_tz_and_utc().
3256 #
3257 # self.convert_between_tz_and_utc(Eastern, Central) # can't work
3258 # self.convert_between_tz_and_utc(Central, Eastern) # can't work
3259
3260 def test_tricky(self):
3261 # 22:00 on day before daylight starts.
3262 fourback = self.dston - timedelta(hours=4)
3263 ninewest = FixedOffset(-9*60, "-0900", 0)
3264 fourback = fourback.replace(tzinfo=ninewest)
3265 # 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST. Since it's "after
3266 # 2", we should get the 3 spelling.
3267 # If we plug 22:00 the day before into Eastern, it "looks like std
3268 # time", so its offset is returned as -5, and -5 - -9 = 4. Adding 4
3269 # to 22:00 lands on 2:00, which makes no sense in local time (the
3270 # local clock jumps from 1 to 3). The point here is to make sure we
3271 # get the 3 spelling.
3272 expected = self.dston.replace(hour=3)
3273 got = fourback.astimezone(Eastern).replace(tzinfo=None)
3274 self.assertEqual(expected, got)
3275
3276 # Similar, but map to 6:00 UTC == 1:00 EST == 2:00 DST. In that
3277 # case we want the 1:00 spelling.
3278 sixutc = self.dston.replace(hour=6, tzinfo=utc_real)
3279 # Now 6:00 "looks like daylight", so the offset wrt Eastern is -4,
3280 # and adding -4-0 == -4 gives the 2:00 spelling. We want the 1:00 EST
3281 # spelling.
3282 expected = self.dston.replace(hour=1)
3283 got = sixutc.astimezone(Eastern).replace(tzinfo=None)
3284 self.assertEqual(expected, got)
3285
3286 # Now on the day DST ends, we want "repeat an hour" behavior.
3287 # UTC 4:MM 5:MM 6:MM 7:MM checking these
3288 # EST 23:MM 0:MM 1:MM 2:MM
3289 # EDT 0:MM 1:MM 2:MM 3:MM
3290 # wall 0:MM 1:MM 1:MM 2:MM against these
3291 for utc in utc_real, utc_fake:
3292 for tz in Eastern, Pacific:
3293 first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM
3294 # Convert that to UTC.
3295 first_std_hour -= tz.utcoffset(None)
3296 # Adjust for possibly fake UTC.
3297 asutc = first_std_hour + utc.utcoffset(None)
3298 # First UTC hour to convert; this is 4:00 when utc=utc_real &
3299 # tz=Eastern.
3300 asutcbase = asutc.replace(tzinfo=utc)
3301 for tzhour in (0, 1, 1, 2):
3302 expectedbase = self.dstoff.replace(hour=tzhour)
3303 for minute in 0, 30, 59:
3304 expected = expectedbase.replace(minute=minute)
3305 asutc = asutcbase.replace(minute=minute)
3306 astz = asutc.astimezone(tz)
3307 self.assertEqual(astz.replace(tzinfo=None), expected)
3308 asutcbase += HOUR
3309
3310
3311 def test_bogus_dst(self):
3312 class ok(tzinfo):
3313 def utcoffset(self, dt): return HOUR
3314 def dst(self, dt): return HOUR
3315
3316 now = self.theclass.now().replace(tzinfo=utc_real)
3317 # Doesn't blow up.
3318 now.astimezone(ok())
3319
3320 # Does blow up.
3321 class notok(ok):
3322 def dst(self, dt): return None
3323 self.assertRaises(ValueError, now.astimezone, notok())
3324
3325 def test_fromutc(self):
3326 self.assertRaises(TypeError, Eastern.fromutc) # not enough args
3327 now = datetime.utcnow().replace(tzinfo=utc_real)
3328 self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo
3329 now = now.replace(tzinfo=Eastern) # insert correct tzinfo
3330 enow = Eastern.fromutc(now) # doesn't blow up
3331 self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member
3332 self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args
3333 self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type
3334
3335 # Always converts UTC to standard time.
3336 class FauxUSTimeZone(USTimeZone):
3337 def fromutc(self, dt):
3338 return dt + self.stdoffset
3339 FEastern = FauxUSTimeZone(-5, "FEastern", "FEST", "FEDT")
3340
3341 # UTC 4:MM 5:MM 6:MM 7:MM 8:MM 9:MM
3342 # EST 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
3343 # EDT 0:MM 1:MM 2:MM 3:MM 4:MM 5:MM
3344
3345 # Check around DST start.
3346 start = self.dston.replace(hour=4, tzinfo=Eastern)
3347 fstart = start.replace(tzinfo=FEastern)
3348 for wall in 23, 0, 1, 3, 4, 5:
3349 expected = start.replace(hour=wall)
3350 if wall == 23:
3351 expected -= timedelta(days=1)
3352 got = Eastern.fromutc(start)
3353 self.assertEqual(expected, got)
3354
3355 expected = fstart + FEastern.stdoffset
3356 got = FEastern.fromutc(fstart)
3357 self.assertEqual(expected, got)
3358
3359 # Ensure astimezone() calls fromutc() too.
3360 got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
3361 self.assertEqual(expected, got)
3362
3363 start += HOUR
3364 fstart += HOUR
3365
3366 # Check around DST end.
3367 start = self.dstoff.replace(hour=4, tzinfo=Eastern)
3368 fstart = start.replace(tzinfo=FEastern)
3369 for wall in 0, 1, 1, 2, 3, 4:
3370 expected = start.replace(hour=wall)
3371 got = Eastern.fromutc(start)
3372 self.assertEqual(expected, got)
3373
3374 expected = fstart + FEastern.stdoffset
3375 got = FEastern.fromutc(fstart)
3376 self.assertEqual(expected, got)
3377
3378 # Ensure astimezone() calls fromutc() too.
3379 got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
3380 self.assertEqual(expected, got)
3381
3382 start += HOUR
3383 fstart += HOUR
3384
3385
3386 #############################################################################
3387 # oddballs
3388
3389 class Oddballs(unittest.TestCase):
3390
3391 def test_bug_1028306(self):
3392 # Trying to compare a date to a datetime should act like a mixed-
3393 # type comparison, despite that datetime is a subclass of date.
3394 as_date = date.today()
3395 as_datetime = datetime.combine(as_date, time())
3396 self.assertTrue(as_date != as_datetime)
3397 self.assertTrue(as_datetime != as_date)
3398 self.assertFalse(as_date == as_datetime)
3399 self.assertFalse(as_datetime == as_date)
3400 self.assertRaises(TypeError, lambda: as_date < as_datetime)
3401 self.assertRaises(TypeError, lambda: as_datetime < as_date)
3402 self.assertRaises(TypeError, lambda: as_date <= as_datetime)
3403 self.assertRaises(TypeError, lambda: as_datetime <= as_date)
3404 self.assertRaises(TypeError, lambda: as_date > as_datetime)
3405 self.assertRaises(TypeError, lambda: as_datetime > as_date)
3406 self.assertRaises(TypeError, lambda: as_date >= as_datetime)
3407 self.assertRaises(TypeError, lambda: as_datetime >= as_date)
3408
3409 # Nevertheless, comparison should work with the base-class (date)
3410 # projection if use of a date method is forced.
3411 self.assertTrue(as_date.__eq__(as_datetime))
3412 different_day = (as_date.day + 1) % 20 + 1
3413 self.assertFalse(as_date.__eq__(as_datetime.replace(day=different_day)))
3414
3415 # And date should compare with other subclasses of date. If a
3416 # subclass wants to stop this, it's up to the subclass to do so.
3417 date_sc = SubclassDate(as_date.year, as_date.month, as_date.day)
3418 self.assertEqual(as_date, date_sc)
3419 self.assertEqual(date_sc, as_date)
3420
3421 # Ditto for datetimes.
3422 datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month,
3423 as_date.day, 0, 0, 0)
3424 self.assertEqual(as_datetime, datetime_sc)
3425 self.assertEqual(datetime_sc, as_datetime)
3426
3427 def test_main():
3428 test_support.run_unittest(__name__)
3429
3430 if __name__ == "__main__":
3431 test_main()