1from test import support
2from test.support import warnings_helper
3import decimal
4import enum
5import locale
6import math
7import platform
8import sys
9import sysconfig
10import time
11import threading
12import unittest
13try:
14    import _testcapi
15except ImportError:
16    _testcapi = None
17
18from test.support import skip_if_buggy_ucrt_strfptime
19
20# Max year is only limited by the size of C int.
21SIZEOF_INT = sysconfig.get_config_var('SIZEOF_INT') or 4
22TIME_MAXYEAR = (1 << 8 * SIZEOF_INT - 1) - 1
23TIME_MINYEAR = -TIME_MAXYEAR - 1 + 1900
24
25SEC_TO_US = 10 ** 6
26US_TO_NS = 10 ** 3
27MS_TO_NS = 10 ** 6
28SEC_TO_NS = 10 ** 9
29NS_TO_SEC = 10 ** 9
30
31class _PyTime(enum.IntEnum):
32    # Round towards minus infinity (-inf)
33    ROUND_FLOOR = 0
34    # Round towards infinity (+inf)
35    ROUND_CEILING = 1
36    # Round to nearest with ties going to nearest even integer
37    ROUND_HALF_EVEN = 2
38    # Round away from zero
39    ROUND_UP = 3
40
41# _PyTime_t is int64_t
42_PyTime_MIN = -2 ** 63
43_PyTime_MAX = 2 ** 63 - 1
44
45# Rounding modes supported by PyTime
46ROUNDING_MODES = (
47    # (PyTime rounding method, decimal rounding method)
48    (_PyTime.ROUND_FLOOR, decimal.ROUND_FLOOR),
49    (_PyTime.ROUND_CEILING, decimal.ROUND_CEILING),
50    (_PyTime.ROUND_HALF_EVEN, decimal.ROUND_HALF_EVEN),
51    (_PyTime.ROUND_UP, decimal.ROUND_UP),
52)
53
54
55class TimeTestCase(unittest.TestCase):
56
57    def setUp(self):
58        self.t = time.time()
59
60    def test_data_attributes(self):
61        time.altzone
62        time.daylight
63        time.timezone
64        time.tzname
65
66    def test_time(self):
67        time.time()
68        info = time.get_clock_info('time')
69        self.assertFalse(info.monotonic)
70        self.assertTrue(info.adjustable)
71
72    def test_time_ns_type(self):
73        def check_ns(sec, ns):
74            self.assertIsInstance(ns, int)
75
76            sec_ns = int(sec * 1e9)
77            # tolerate a difference of 50 ms
78            self.assertLess((sec_ns - ns), 50 ** 6, (sec, ns))
79
80        check_ns(time.time(),
81                 time.time_ns())
82        check_ns(time.monotonic(),
83                 time.monotonic_ns())
84        check_ns(time.perf_counter(),
85                 time.perf_counter_ns())
86        check_ns(time.process_time(),
87                 time.process_time_ns())
88
89        if hasattr(time, 'thread_time'):
90            check_ns(time.thread_time(),
91                     time.thread_time_ns())
92
93        if hasattr(time, 'clock_gettime'):
94            check_ns(time.clock_gettime(time.CLOCK_REALTIME),
95                     time.clock_gettime_ns(time.CLOCK_REALTIME))
96
97    @unittest.skipUnless(hasattr(time, 'clock_gettime'),
98                         'need time.clock_gettime()')
99    def test_clock_realtime(self):
100        t = time.clock_gettime(time.CLOCK_REALTIME)
101        self.assertIsInstance(t, float)
102
103    @unittest.skipUnless(hasattr(time, 'clock_gettime'),
104                         'need time.clock_gettime()')
105    @unittest.skipUnless(hasattr(time, 'CLOCK_MONOTONIC'),
106                         'need time.CLOCK_MONOTONIC')
107    def test_clock_monotonic(self):
108        a = time.clock_gettime(time.CLOCK_MONOTONIC)
109        b = time.clock_gettime(time.CLOCK_MONOTONIC)
110        self.assertLessEqual(a, b)
111
112    @unittest.skipUnless(hasattr(time, 'pthread_getcpuclockid'),
113                         'need time.pthread_getcpuclockid()')
114    @unittest.skipUnless(hasattr(time, 'clock_gettime'),
115                         'need time.clock_gettime()')
116    def test_pthread_getcpuclockid(self):
117        clk_id = time.pthread_getcpuclockid(threading.get_ident())
118        self.assertTrue(type(clk_id) is int)
119        # when in 32-bit mode AIX only returns the predefined constant
120        if not platform.system() == "AIX":
121            self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
122        elif (sys.maxsize.bit_length() > 32):
123            self.assertNotEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
124        else:
125            self.assertEqual(clk_id, time.CLOCK_THREAD_CPUTIME_ID)
126        t1 = time.clock_gettime(clk_id)
127        t2 = time.clock_gettime(clk_id)
128        self.assertLessEqual(t1, t2)
129
130    @unittest.skipUnless(hasattr(time, 'clock_getres'),
131                         'need time.clock_getres()')
132    def test_clock_getres(self):
133        res = time.clock_getres(time.CLOCK_REALTIME)
134        self.assertGreater(res, 0.0)
135        self.assertLessEqual(res, 1.0)
136
137    @unittest.skipUnless(hasattr(time, 'clock_settime'),
138                         'need time.clock_settime()')
139    def test_clock_settime(self):
140        t = time.clock_gettime(time.CLOCK_REALTIME)
141        try:
142            time.clock_settime(time.CLOCK_REALTIME, t)
143        except PermissionError:
144            pass
145
146        if hasattr(time, 'CLOCK_MONOTONIC'):
147            self.assertRaises(OSError,
148                              time.clock_settime, time.CLOCK_MONOTONIC, 0)
149
150    def test_conversions(self):
151        self.assertEqual(time.ctime(self.t),
152                         time.asctime(time.localtime(self.t)))
153        self.assertEqual(int(time.mktime(time.localtime(self.t))),
154                         int(self.t))
155
156    def test_sleep(self):
157        self.assertRaises(ValueError, time.sleep, -2)
158        self.assertRaises(ValueError, time.sleep, -1)
159        time.sleep(1.2)
160
161    def test_strftime(self):
162        tt = time.gmtime(self.t)
163        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
164                          'j', 'm', 'M', 'p', 'S',
165                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
166            format = ' %' + directive
167            try:
168                time.strftime(format, tt)
169            except ValueError:
170                self.fail('conversion specifier: %r failed.' % format)
171
172        self.assertRaises(TypeError, time.strftime, b'%S', tt)
173        # embedded null character
174        self.assertRaises(ValueError, time.strftime, '%S\0', tt)
175
176    def _bounds_checking(self, func):
177        # Make sure that strftime() checks the bounds of the various parts
178        # of the time tuple (0 is valid for *all* values).
179
180        # The year field is tested by other test cases above
181
182        # Check month [1, 12] + zero support
183        func((1900, 0, 1, 0, 0, 0, 0, 1, -1))
184        func((1900, 12, 1, 0, 0, 0, 0, 1, -1))
185        self.assertRaises(ValueError, func,
186                            (1900, -1, 1, 0, 0, 0, 0, 1, -1))
187        self.assertRaises(ValueError, func,
188                            (1900, 13, 1, 0, 0, 0, 0, 1, -1))
189        # Check day of month [1, 31] + zero support
190        func((1900, 1, 0, 0, 0, 0, 0, 1, -1))
191        func((1900, 1, 31, 0, 0, 0, 0, 1, -1))
192        self.assertRaises(ValueError, func,
193                            (1900, 1, -1, 0, 0, 0, 0, 1, -1))
194        self.assertRaises(ValueError, func,
195                            (1900, 1, 32, 0, 0, 0, 0, 1, -1))
196        # Check hour [0, 23]
197        func((1900, 1, 1, 23, 0, 0, 0, 1, -1))
198        self.assertRaises(ValueError, func,
199                            (1900, 1, 1, -1, 0, 0, 0, 1, -1))
200        self.assertRaises(ValueError, func,
201                            (1900, 1, 1, 24, 0, 0, 0, 1, -1))
202        # Check minute [0, 59]
203        func((1900, 1, 1, 0, 59, 0, 0, 1, -1))
204        self.assertRaises(ValueError, func,
205                            (1900, 1, 1, 0, -1, 0, 0, 1, -1))
206        self.assertRaises(ValueError, func,
207                            (1900, 1, 1, 0, 60, 0, 0, 1, -1))
208        # Check second [0, 61]
209        self.assertRaises(ValueError, func,
210                            (1900, 1, 1, 0, 0, -1, 0, 1, -1))
211        # C99 only requires allowing for one leap second, but Python's docs say
212        # allow two leap seconds (0..61)
213        func((1900, 1, 1, 0, 0, 60, 0, 1, -1))
214        func((1900, 1, 1, 0, 0, 61, 0, 1, -1))
215        self.assertRaises(ValueError, func,
216                            (1900, 1, 1, 0, 0, 62, 0, 1, -1))
217        # No check for upper-bound day of week;
218        #  value forced into range by a ``% 7`` calculation.
219        # Start check at -2 since gettmarg() increments value before taking
220        #  modulo.
221        self.assertEqual(func((1900, 1, 1, 0, 0, 0, -1, 1, -1)),
222                         func((1900, 1, 1, 0, 0, 0, +6, 1, -1)))
223        self.assertRaises(ValueError, func,
224                            (1900, 1, 1, 0, 0, 0, -2, 1, -1))
225        # Check day of the year [1, 366] + zero support
226        func((1900, 1, 1, 0, 0, 0, 0, 0, -1))
227        func((1900, 1, 1, 0, 0, 0, 0, 366, -1))
228        self.assertRaises(ValueError, func,
229                            (1900, 1, 1, 0, 0, 0, 0, -1, -1))
230        self.assertRaises(ValueError, func,
231                            (1900, 1, 1, 0, 0, 0, 0, 367, -1))
232
233    def test_strftime_bounding_check(self):
234        self._bounds_checking(lambda tup: time.strftime('', tup))
235
236    def test_strftime_format_check(self):
237        # Test that strftime does not crash on invalid format strings
238        # that may trigger a buffer overread. When not triggered,
239        # strftime may succeed or raise ValueError depending on
240        # the platform.
241        for x in [ '', 'A', '%A', '%AA' ]:
242            for y in range(0x0, 0x10):
243                for z in [ '%', 'A%', 'AA%', '%A%', 'A%A%', '%#' ]:
244                    try:
245                        time.strftime(x * y + z)
246                    except ValueError:
247                        pass
248
249    def test_default_values_for_zero(self):
250        # Make sure that using all zeros uses the proper default
251        # values.  No test for daylight savings since strftime() does
252        # not change output based on its value and no test for year
253        # because systems vary in their support for year 0.
254        expected = "2000 01 01 00 00 00 1 001"
255        with warnings_helper.check_warnings():
256            result = time.strftime("%Y %m %d %H %M %S %w %j", (2000,)+(0,)*8)
257        self.assertEqual(expected, result)
258
259    @skip_if_buggy_ucrt_strfptime
260    def test_strptime(self):
261        # Should be able to go round-trip from strftime to strptime without
262        # raising an exception.
263        tt = time.gmtime(self.t)
264        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
265                          'j', 'm', 'M', 'p', 'S',
266                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
267            format = '%' + directive
268            strf_output = time.strftime(format, tt)
269            try:
270                time.strptime(strf_output, format)
271            except ValueError:
272                self.fail("conversion specifier %r failed with '%s' input." %
273                          (format, strf_output))
274
275    def test_strptime_bytes(self):
276        # Make sure only strings are accepted as arguments to strptime.
277        self.assertRaises(TypeError, time.strptime, b'2009', "%Y")
278        self.assertRaises(TypeError, time.strptime, '2009', b'%Y')
279
280    def test_strptime_exception_context(self):
281        # check that this doesn't chain exceptions needlessly (see #17572)
282        with self.assertRaises(ValueError) as e:
283            time.strptime('', '%D')
284        self.assertIs(e.exception.__suppress_context__, True)
285        # additional check for IndexError branch (issue #19545)
286        with self.assertRaises(ValueError) as e:
287            time.strptime('19', '%Y %')
288        self.assertIs(e.exception.__suppress_context__, True)
289
290    def test_asctime(self):
291        time.asctime(time.gmtime(self.t))
292
293        # Max year is only limited by the size of C int.
294        for bigyear in TIME_MAXYEAR, TIME_MINYEAR:
295            asc = time.asctime((bigyear, 6, 1) + (0,) * 6)
296            self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
297        self.assertRaises(OverflowError, time.asctime,
298                          (TIME_MAXYEAR + 1,) + (0,) * 8)
299        self.assertRaises(OverflowError, time.asctime,
300                          (TIME_MINYEAR - 1,) + (0,) * 8)
301        self.assertRaises(TypeError, time.asctime, 0)
302        self.assertRaises(TypeError, time.asctime, ())
303        self.assertRaises(TypeError, time.asctime, (0,) * 10)
304
305    def test_asctime_bounding_check(self):
306        self._bounds_checking(time.asctime)
307
308    def test_ctime(self):
309        t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
310        self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
311        t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
312        self.assertEqual(time.ctime(t), 'Sat Jan  1 00:00:00 2000')
313        for year in [-100, 100, 1000, 2000, 2050, 10000]:
314            try:
315                testval = time.mktime((year, 1, 10) + (0,)*6)
316            except (ValueError, OverflowError):
317                # If mktime fails, ctime will fail too.  This may happen
318                # on some platforms.
319                pass
320            else:
321                self.assertEqual(time.ctime(testval)[20:], str(year))
322
323    @unittest.skipUnless(hasattr(time, "tzset"),
324                         "time module has no attribute tzset")
325    def test_tzset(self):
326
327        from os import environ
328
329        # Epoch time of midnight Dec 25th 2002. Never DST in northern
330        # hemisphere.
331        xmas2002 = 1040774400.0
332
333        # These formats are correct for 2002, and possibly future years
334        # This format is the 'standard' as documented at:
335        # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
336        # They are also documented in the tzset(3) man page on most Unix
337        # systems.
338        eastern = 'EST+05EDT,M4.1.0,M10.5.0'
339        victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
340        utc='UTC+0'
341
342        org_TZ = environ.get('TZ',None)
343        try:
344            # Make sure we can switch to UTC time and results are correct
345            # Note that unknown timezones default to UTC.
346            # Note that altzone is undefined in UTC, as there is no DST
347            environ['TZ'] = eastern
348            time.tzset()
349            environ['TZ'] = utc
350            time.tzset()
351            self.assertEqual(
352                time.gmtime(xmas2002), time.localtime(xmas2002)
353                )
354            self.assertEqual(time.daylight, 0)
355            self.assertEqual(time.timezone, 0)
356            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
357
358            # Make sure we can switch to US/Eastern
359            environ['TZ'] = eastern
360            time.tzset()
361            self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
362            self.assertEqual(time.tzname, ('EST', 'EDT'))
363            self.assertEqual(len(time.tzname), 2)
364            self.assertEqual(time.daylight, 1)
365            self.assertEqual(time.timezone, 18000)
366            self.assertEqual(time.altzone, 14400)
367            self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
368            self.assertEqual(len(time.tzname), 2)
369
370            # Now go to the southern hemisphere.
371            environ['TZ'] = victoria
372            time.tzset()
373            self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
374
375            # Issue #11886: Australian Eastern Standard Time (UTC+10) is called
376            # "EST" (as Eastern Standard Time, UTC-5) instead of "AEST"
377            # (non-DST timezone), and "EDT" instead of "AEDT" (DST timezone),
378            # on some operating systems (e.g. FreeBSD), which is wrong. See for
379            # example this bug:
380            # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=93810
381            self.assertIn(time.tzname[0], ('AEST' 'EST'), time.tzname[0])
382            self.assertTrue(time.tzname[1] in ('AEDT', 'EDT'), str(time.tzname[1]))
383            self.assertEqual(len(time.tzname), 2)
384            self.assertEqual(time.daylight, 1)
385            self.assertEqual(time.timezone, -36000)
386            self.assertEqual(time.altzone, -39600)
387            self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
388
389        finally:
390            # Repair TZ environment variable in case any other tests
391            # rely on it.
392            if org_TZ is not None:
393                environ['TZ'] = org_TZ
394            elif 'TZ' in environ:
395                del environ['TZ']
396            time.tzset()
397
398    def test_insane_timestamps(self):
399        # It's possible that some platform maps time_t to double,
400        # and that this test will fail there.  This test should
401        # exempt such platforms (provided they return reasonable
402        # results!).
403        for func in time.ctime, time.gmtime, time.localtime:
404            for unreasonable in -1e200, 1e200:
405                self.assertRaises(OverflowError, func, unreasonable)
406
407    def test_ctime_without_arg(self):
408        # Not sure how to check the values, since the clock could tick
409        # at any time.  Make sure these are at least accepted and
410        # don't raise errors.
411        time.ctime()
412        time.ctime(None)
413
414    def test_gmtime_without_arg(self):
415        gt0 = time.gmtime()
416        gt1 = time.gmtime(None)
417        t0 = time.mktime(gt0)
418        t1 = time.mktime(gt1)
419        self.assertAlmostEqual(t1, t0, delta=0.2)
420
421    def test_localtime_without_arg(self):
422        lt0 = time.localtime()
423        lt1 = time.localtime(None)
424        t0 = time.mktime(lt0)
425        t1 = time.mktime(lt1)
426        self.assertAlmostEqual(t1, t0, delta=0.2)
427
428    def test_mktime(self):
429        # Issue #1726687
430        for t in (-2, -1, 0, 1):
431            try:
432                tt = time.localtime(t)
433            except (OverflowError, OSError):
434                pass
435            else:
436                self.assertEqual(time.mktime(tt), t)
437
438    # Issue #13309: passing extreme values to mktime() or localtime()
439    # borks the glibc's internal timezone data.
440    @unittest.skipUnless(platform.libc_ver()[0] != 'glibc',
441                         "disabled because of a bug in glibc. Issue #13309")
442    def test_mktime_error(self):
443        # It may not be possible to reliably make mktime return an error
444        # on all platforms.  This will make sure that no other exception
445        # than OverflowError is raised for an extreme value.
446        tt = time.gmtime(self.t)
447        tzname = time.strftime('%Z', tt)
448        self.assertNotEqual(tzname, 'LMT')
449        try:
450            time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
451        except OverflowError:
452            pass
453        self.assertEqual(time.strftime('%Z', tt), tzname)
454
455    def test_monotonic(self):
456        # monotonic() should not go backward
457        times = [time.monotonic() for n in range(100)]
458        t1 = times[0]
459        for t2 in times[1:]:
460            self.assertGreaterEqual(t2, t1, "times=%s" % times)
461            t1 = t2
462
463        # monotonic() includes time elapsed during a sleep
464        t1 = time.monotonic()
465        time.sleep(0.5)
466        t2 = time.monotonic()
467        dt = t2 - t1
468        self.assertGreater(t2, t1)
469        # bpo-20101: tolerate a difference of 50 ms because of bad timer
470        # resolution on Windows
471        self.assertTrue(0.450 <= dt)
472
473        # monotonic() is a monotonic but non adjustable clock
474        info = time.get_clock_info('monotonic')
475        self.assertTrue(info.monotonic)
476        self.assertFalse(info.adjustable)
477
478    def test_perf_counter(self):
479        time.perf_counter()
480
481    def test_process_time(self):
482        # process_time() should not include time spend during a sleep
483        start = time.process_time()
484        time.sleep(0.100)
485        stop = time.process_time()
486        # use 20 ms because process_time() has usually a resolution of 15 ms
487        # on Windows
488        self.assertLess(stop - start, 0.020)
489
490        info = time.get_clock_info('process_time')
491        self.assertTrue(info.monotonic)
492        self.assertFalse(info.adjustable)
493
494    def test_thread_time(self):
495        if not hasattr(time, 'thread_time'):
496            if sys.platform.startswith(('linux', 'win')):
497                self.fail("time.thread_time() should be available on %r"
498                          % (sys.platform,))
499            else:
500                self.skipTest("need time.thread_time")
501
502        # thread_time() should not include time spend during a sleep
503        start = time.thread_time()
504        time.sleep(0.100)
505        stop = time.thread_time()
506        # use 20 ms because thread_time() has usually a resolution of 15 ms
507        # on Windows
508        self.assertLess(stop - start, 0.020)
509
510        info = time.get_clock_info('thread_time')
511        self.assertTrue(info.monotonic)
512        self.assertFalse(info.adjustable)
513
514    @unittest.skipUnless(hasattr(time, 'clock_settime'),
515                         'need time.clock_settime')
516    def test_monotonic_settime(self):
517        t1 = time.monotonic()
518        realtime = time.clock_gettime(time.CLOCK_REALTIME)
519        # jump backward with an offset of 1 hour
520        try:
521            time.clock_settime(time.CLOCK_REALTIME, realtime - 3600)
522        except PermissionError as err:
523            self.skipTest(err)
524        t2 = time.monotonic()
525        time.clock_settime(time.CLOCK_REALTIME, realtime)
526        # monotonic must not be affected by system clock updates
527        self.assertGreaterEqual(t2, t1)
528
529    def test_localtime_failure(self):
530        # Issue #13847: check for localtime() failure
531        invalid_time_t = None
532        for time_t in (-1, 2**30, 2**33, 2**60):
533            try:
534                time.localtime(time_t)
535            except OverflowError:
536                self.skipTest("need 64-bit time_t")
537            except OSError:
538                invalid_time_t = time_t
539                break
540        if invalid_time_t is None:
541            self.skipTest("unable to find an invalid time_t value")
542
543        self.assertRaises(OSError, time.localtime, invalid_time_t)
544        self.assertRaises(OSError, time.ctime, invalid_time_t)
545
546        # Issue #26669: check for localtime() failure
547        self.assertRaises(ValueError, time.localtime, float("nan"))
548        self.assertRaises(ValueError, time.ctime, float("nan"))
549
550    def test_get_clock_info(self):
551        clocks = ['monotonic', 'perf_counter', 'process_time', 'time']
552
553        for name in clocks:
554            info = time.get_clock_info(name)
555
556            #self.assertIsInstance(info, dict)
557            self.assertIsInstance(info.implementation, str)
558            self.assertNotEqual(info.implementation, '')
559            self.assertIsInstance(info.monotonic, bool)
560            self.assertIsInstance(info.resolution, float)
561            # 0.0 < resolution <= 1.0
562            self.assertGreater(info.resolution, 0.0)
563            self.assertLessEqual(info.resolution, 1.0)
564            self.assertIsInstance(info.adjustable, bool)
565
566        self.assertRaises(ValueError, time.get_clock_info, 'xxx')
567
568
569class TestLocale(unittest.TestCase):
570    def setUp(self):
571        self.oldloc = locale.setlocale(locale.LC_ALL)
572
573    def tearDown(self):
574        locale.setlocale(locale.LC_ALL, self.oldloc)
575
576    def test_bug_3061(self):
577        try:
578            tmp = locale.setlocale(locale.LC_ALL, "fr_FR")
579        except locale.Error:
580            self.skipTest('could not set locale.LC_ALL to fr_FR')
581        # This should not cause an exception
582        time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
583
584
585class _TestAsctimeYear:
586    _format = '%d'
587
588    def yearstr(self, y):
589        return time.asctime((y,) + (0,) * 8).split()[-1]
590
591    def test_large_year(self):
592        # Check that it doesn't crash for year > 9999
593        self.assertEqual(self.yearstr(12345), '12345')
594        self.assertEqual(self.yearstr(123456789), '123456789')
595
596class _TestStrftimeYear:
597
598    # Issue 13305:  For years < 1000, the value is not always
599    # padded to 4 digits across platforms.  The C standard
600    # assumes year >= 1900, so it does not specify the number
601    # of digits.
602
603    if time.strftime('%Y', (1,) + (0,) * 8) == '0001':
604        _format = '%04d'
605    else:
606        _format = '%d'
607
608    def yearstr(self, y):
609        return time.strftime('%Y', (y,) + (0,) * 8)
610
611    def test_4dyear(self):
612        # Check that we can return the zero padded value.
613        if self._format == '%04d':
614            self.test_year('%04d')
615        else:
616            def year4d(y):
617                return time.strftime('%4Y', (y,) + (0,) * 8)
618            self.test_year('%04d', func=year4d)
619
620    def skip_if_not_supported(y):
621        msg = "strftime() is limited to [1; 9999] with Visual Studio"
622        # Check that it doesn't crash for year > 9999
623        try:
624            time.strftime('%Y', (y,) + (0,) * 8)
625        except ValueError:
626            cond = False
627        else:
628            cond = True
629        return unittest.skipUnless(cond, msg)
630
631    @skip_if_not_supported(10000)
632    def test_large_year(self):
633        return super().test_large_year()
634
635    @skip_if_not_supported(0)
636    def test_negative(self):
637        return super().test_negative()
638
639    del skip_if_not_supported
640
641
642class _Test4dYear:
643    _format = '%d'
644
645    def test_year(self, fmt=None, func=None):
646        fmt = fmt or self._format
647        func = func or self.yearstr
648        self.assertEqual(func(1),    fmt % 1)
649        self.assertEqual(func(68),   fmt % 68)
650        self.assertEqual(func(69),   fmt % 69)
651        self.assertEqual(func(99),   fmt % 99)
652        self.assertEqual(func(999),  fmt % 999)
653        self.assertEqual(func(9999), fmt % 9999)
654
655    def test_large_year(self):
656        self.assertEqual(self.yearstr(12345).lstrip('+'), '12345')
657        self.assertEqual(self.yearstr(123456789).lstrip('+'), '123456789')
658        self.assertEqual(self.yearstr(TIME_MAXYEAR).lstrip('+'), str(TIME_MAXYEAR))
659        self.assertRaises(OverflowError, self.yearstr, TIME_MAXYEAR + 1)
660
661    def test_negative(self):
662        self.assertEqual(self.yearstr(-1), self._format % -1)
663        self.assertEqual(self.yearstr(-1234), '-1234')
664        self.assertEqual(self.yearstr(-123456), '-123456')
665        self.assertEqual(self.yearstr(-123456789), str(-123456789))
666        self.assertEqual(self.yearstr(-1234567890), str(-1234567890))
667        self.assertEqual(self.yearstr(TIME_MINYEAR), str(TIME_MINYEAR))
668        # Modules/timemodule.c checks for underflow
669        self.assertRaises(OverflowError, self.yearstr, TIME_MINYEAR - 1)
670        with self.assertRaises(OverflowError):
671            self.yearstr(-TIME_MAXYEAR - 1)
672
673
674class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear, unittest.TestCase):
675    pass
676
677class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase):
678    pass
679
680
681class TestPytime(unittest.TestCase):
682    @skip_if_buggy_ucrt_strfptime
683    @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
684    def test_localtime_timezone(self):
685
686        # Get the localtime and examine it for the offset and zone.
687        lt = time.localtime()
688        self.assertTrue(hasattr(lt, "tm_gmtoff"))
689        self.assertTrue(hasattr(lt, "tm_zone"))
690
691        # See if the offset and zone are similar to the module
692        # attributes.
693        if lt.tm_gmtoff is None:
694            self.assertTrue(not hasattr(time, "timezone"))
695        else:
696            self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
697        if lt.tm_zone is None:
698            self.assertTrue(not hasattr(time, "tzname"))
699        else:
700            self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])
701
702        # Try and make UNIX times from the localtime and a 9-tuple
703        # created from the localtime. Test to see that the times are
704        # the same.
705        t = time.mktime(lt); t9 = time.mktime(lt[:9])
706        self.assertEqual(t, t9)
707
708        # Make localtimes from the UNIX times and compare them to
709        # the original localtime, thus making a round trip.
710        new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
711        self.assertEqual(new_lt, lt)
712        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
713        self.assertEqual(new_lt.tm_zone, lt.tm_zone)
714        self.assertEqual(new_lt9, lt)
715        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
716        self.assertEqual(new_lt9.tm_zone, lt.tm_zone)
717
718    @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
719    def test_strptime_timezone(self):
720        t = time.strptime("UTC", "%Z")
721        self.assertEqual(t.tm_zone, 'UTC')
722        t = time.strptime("+0500", "%z")
723        self.assertEqual(t.tm_gmtoff, 5 * 3600)
724
725    @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support")
726    def test_short_times(self):
727
728        import pickle
729
730        # Load a short time structure using pickle.
731        st = b"ctime\nstruct_time\np0\n((I2007\nI8\nI11\nI1\nI24\nI49\nI5\nI223\nI1\ntp1\n(dp2\ntp3\nRp4\n."
732        lt = pickle.loads(st)
733        self.assertIs(lt.tm_gmtoff, None)
734        self.assertIs(lt.tm_zone, None)
735
736
737@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
738class CPyTimeTestCase:
739    """
740    Base class to test the C _PyTime_t API.
741    """
742    OVERFLOW_SECONDS = None
743
744    def setUp(self):
745        from _testcapi import SIZEOF_TIME_T
746        bits = SIZEOF_TIME_T * 8 - 1
747        self.time_t_min = -2 ** bits
748        self.time_t_max = 2 ** bits - 1
749
750    def time_t_filter(self, seconds):
751        return (self.time_t_min <= seconds <= self.time_t_max)
752
753    def _rounding_values(self, use_float):
754        "Build timestamps used to test rounding."
755
756        units = [1, US_TO_NS, MS_TO_NS, SEC_TO_NS]
757        if use_float:
758            # picoseconds are only tested to pytime_converter accepting floats
759            units.append(1e-3)
760
761        values = (
762            # small values
763            1, 2, 5, 7, 123, 456, 1234,
764            # 10^k - 1
765            9,
766            99,
767            999,
768            9999,
769            99999,
770            999999,
771            # test half even rounding near 0.5, 1.5, 2.5, 3.5, 4.5
772            499, 500, 501,
773            1499, 1500, 1501,
774            2500,
775            3500,
776            4500,
777        )
778
779        ns_timestamps = [0]
780        for unit in units:
781            for value in values:
782                ns = value * unit
783                ns_timestamps.extend((-ns, ns))
784        for pow2 in (0, 5, 10, 15, 22, 23, 24, 30, 33):
785            ns = (2 ** pow2) * SEC_TO_NS
786            ns_timestamps.extend((
787                -ns-1, -ns, -ns+1,
788                ns-1, ns, ns+1
789            ))
790        for seconds in (_testcapi.INT_MIN, _testcapi.INT_MAX):
791            ns_timestamps.append(seconds * SEC_TO_NS)
792        if use_float:
793            # numbers with an exact representation in IEEE 754 (base 2)
794            for pow2 in (3, 7, 10, 15):
795                ns = 2.0 ** (-pow2)
796                ns_timestamps.extend((-ns, ns))
797
798        # seconds close to _PyTime_t type limit
799        ns = (2 ** 63 // SEC_TO_NS) * SEC_TO_NS
800        ns_timestamps.extend((-ns, ns))
801
802        return ns_timestamps
803
804    def _check_rounding(self, pytime_converter, expected_func,
805                        use_float, unit_to_sec, value_filter=None):
806
807        def convert_values(ns_timestamps):
808            if use_float:
809                unit_to_ns = SEC_TO_NS / float(unit_to_sec)
810                values = [ns / unit_to_ns for ns in ns_timestamps]
811            else:
812                unit_to_ns = SEC_TO_NS // unit_to_sec
813                values = [ns // unit_to_ns for ns in ns_timestamps]
814
815            if value_filter:
816                values = filter(value_filter, values)
817
818            # remove duplicates and sort
819            return sorted(set(values))
820
821        # test rounding
822        ns_timestamps = self._rounding_values(use_float)
823        valid_values = convert_values(ns_timestamps)
824        for time_rnd, decimal_rnd in ROUNDING_MODES :
825            with decimal.localcontext() as context:
826                context.rounding = decimal_rnd
827
828                for value in valid_values:
829                    debug_info = {'value': value, 'rounding': decimal_rnd}
830                    try:
831                        result = pytime_converter(value, time_rnd)
832                        expected = expected_func(value)
833                    except Exception:
834                        self.fail("Error on timestamp conversion: %s" % debug_info)
835                    self.assertEqual(result,
836                                     expected,
837                                     debug_info)
838
839        # test overflow
840        ns = self.OVERFLOW_SECONDS * SEC_TO_NS
841        ns_timestamps = (-ns, ns)
842        overflow_values = convert_values(ns_timestamps)
843        for time_rnd, _ in ROUNDING_MODES :
844            for value in overflow_values:
845                debug_info = {'value': value, 'rounding': time_rnd}
846                with self.assertRaises(OverflowError, msg=debug_info):
847                    pytime_converter(value, time_rnd)
848
849    def check_int_rounding(self, pytime_converter, expected_func,
850                           unit_to_sec=1, value_filter=None):
851        self._check_rounding(pytime_converter, expected_func,
852                             False, unit_to_sec, value_filter)
853
854    def check_float_rounding(self, pytime_converter, expected_func,
855                             unit_to_sec=1, value_filter=None):
856        self._check_rounding(pytime_converter, expected_func,
857                             True, unit_to_sec, value_filter)
858
859    def decimal_round(self, x):
860        d = decimal.Decimal(x)
861        d = d.quantize(1)
862        return int(d)
863
864
865class TestCPyTime(CPyTimeTestCase, unittest.TestCase):
866    """
867    Test the C _PyTime_t API.
868    """
869    # _PyTime_t is a 64-bit signed integer
870    OVERFLOW_SECONDS = math.ceil((2**63 + 1) / SEC_TO_NS)
871
872    def test_FromSeconds(self):
873        from _testcapi import PyTime_FromSeconds
874
875        # PyTime_FromSeconds() expects a C int, reject values out of range
876        def c_int_filter(secs):
877            return (_testcapi.INT_MIN <= secs <= _testcapi.INT_MAX)
878
879        self.check_int_rounding(lambda secs, rnd: PyTime_FromSeconds(secs),
880                                lambda secs: secs * SEC_TO_NS,
881                                value_filter=c_int_filter)
882
883        # test nan
884        for time_rnd, _ in ROUNDING_MODES:
885            with self.assertRaises(TypeError):
886                PyTime_FromSeconds(float('nan'))
887
888    def test_FromSecondsObject(self):
889        from _testcapi import PyTime_FromSecondsObject
890
891        self.check_int_rounding(
892            PyTime_FromSecondsObject,
893            lambda secs: secs * SEC_TO_NS)
894
895        self.check_float_rounding(
896            PyTime_FromSecondsObject,
897            lambda ns: self.decimal_round(ns * SEC_TO_NS))
898
899        # test nan
900        for time_rnd, _ in ROUNDING_MODES:
901            with self.assertRaises(ValueError):
902                PyTime_FromSecondsObject(float('nan'), time_rnd)
903
904    def test_AsSecondsDouble(self):
905        from _testcapi import PyTime_AsSecondsDouble
906
907        def float_converter(ns):
908            if abs(ns) % SEC_TO_NS == 0:
909                return float(ns // SEC_TO_NS)
910            else:
911                return float(ns) / SEC_TO_NS
912
913        self.check_int_rounding(lambda ns, rnd: PyTime_AsSecondsDouble(ns),
914                                float_converter,
915                                NS_TO_SEC)
916
917        # test nan
918        for time_rnd, _ in ROUNDING_MODES:
919            with self.assertRaises(TypeError):
920                PyTime_AsSecondsDouble(float('nan'))
921
922    def create_decimal_converter(self, denominator):
923        denom = decimal.Decimal(denominator)
924
925        def converter(value):
926            d = decimal.Decimal(value) / denom
927            return self.decimal_round(d)
928
929        return converter
930
931    def test_AsTimeval(self):
932        from _testcapi import PyTime_AsTimeval
933
934        us_converter = self.create_decimal_converter(US_TO_NS)
935
936        def timeval_converter(ns):
937            us = us_converter(ns)
938            return divmod(us, SEC_TO_US)
939
940        if sys.platform == 'win32':
941            from _testcapi import LONG_MIN, LONG_MAX
942
943            # On Windows, timeval.tv_sec type is a C long
944            def seconds_filter(secs):
945                return LONG_MIN <= secs <= LONG_MAX
946        else:
947            seconds_filter = self.time_t_filter
948
949        self.check_int_rounding(PyTime_AsTimeval,
950                                timeval_converter,
951                                NS_TO_SEC,
952                                value_filter=seconds_filter)
953
954    @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec'),
955                         'need _testcapi.PyTime_AsTimespec')
956    def test_AsTimespec(self):
957        from _testcapi import PyTime_AsTimespec
958
959        def timespec_converter(ns):
960            return divmod(ns, SEC_TO_NS)
961
962        self.check_int_rounding(lambda ns, rnd: PyTime_AsTimespec(ns),
963                                timespec_converter,
964                                NS_TO_SEC,
965                                value_filter=self.time_t_filter)
966
967    @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimeval_clamp'),
968                         'need _testcapi.PyTime_AsTimeval_clamp')
969    def test_AsTimeval_clamp(self):
970        from _testcapi import PyTime_AsTimeval_clamp
971
972        if sys.platform == 'win32':
973            from _testcapi import LONG_MIN, LONG_MAX
974            tv_sec_max = LONG_MAX
975            tv_sec_min = LONG_MIN
976        else:
977            tv_sec_max = self.time_t_max
978            tv_sec_min = self.time_t_min
979
980        for t in (_PyTime_MIN, _PyTime_MAX):
981            ts = PyTime_AsTimeval_clamp(t, _PyTime.ROUND_CEILING)
982            with decimal.localcontext() as context:
983                context.rounding = decimal.ROUND_CEILING
984                us = self.decimal_round(decimal.Decimal(t) / US_TO_NS)
985            tv_sec, tv_usec = divmod(us, SEC_TO_US)
986            if tv_sec_max < tv_sec:
987                tv_sec = tv_sec_max
988                tv_usec = 0
989            elif tv_sec < tv_sec_min:
990                tv_sec = tv_sec_min
991                tv_usec = 0
992            self.assertEqual(ts, (tv_sec, tv_usec))
993
994    @unittest.skipUnless(hasattr(_testcapi, 'PyTime_AsTimespec_clamp'),
995                         'need _testcapi.PyTime_AsTimespec_clamp')
996    def test_AsTimespec_clamp(self):
997        from _testcapi import PyTime_AsTimespec_clamp
998
999        for t in (_PyTime_MIN, _PyTime_MAX):
1000            ts = PyTime_AsTimespec_clamp(t)
1001            tv_sec, tv_nsec = divmod(t, NS_TO_SEC)
1002            if self.time_t_max < tv_sec:
1003                tv_sec = self.time_t_max
1004                tv_nsec = 0
1005            elif tv_sec < self.time_t_min:
1006                tv_sec = self.time_t_min
1007                tv_nsec = 0
1008            self.assertEqual(ts, (tv_sec, tv_nsec))
1009
1010    def test_AsMilliseconds(self):
1011        from _testcapi import PyTime_AsMilliseconds
1012
1013        self.check_int_rounding(PyTime_AsMilliseconds,
1014                                self.create_decimal_converter(MS_TO_NS),
1015                                NS_TO_SEC)
1016
1017    def test_AsMicroseconds(self):
1018        from _testcapi import PyTime_AsMicroseconds
1019
1020        self.check_int_rounding(PyTime_AsMicroseconds,
1021                                self.create_decimal_converter(US_TO_NS),
1022                                NS_TO_SEC)
1023
1024
1025class TestOldPyTime(CPyTimeTestCase, unittest.TestCase):
1026    """
1027    Test the old C _PyTime_t API: _PyTime_ObjectToXXX() functions.
1028    """
1029
1030    # time_t is a 32-bit or 64-bit signed integer
1031    OVERFLOW_SECONDS = 2 ** 64
1032
1033    def test_object_to_time_t(self):
1034        from _testcapi import pytime_object_to_time_t
1035
1036        self.check_int_rounding(pytime_object_to_time_t,
1037                                lambda secs: secs,
1038                                value_filter=self.time_t_filter)
1039
1040        self.check_float_rounding(pytime_object_to_time_t,
1041                                  self.decimal_round,
1042                                  value_filter=self.time_t_filter)
1043
1044    def create_converter(self, sec_to_unit):
1045        def converter(secs):
1046            floatpart, intpart = math.modf(secs)
1047            intpart = int(intpart)
1048            floatpart *= sec_to_unit
1049            floatpart = self.decimal_round(floatpart)
1050            if floatpart < 0:
1051                floatpart += sec_to_unit
1052                intpart -= 1
1053            elif floatpart >= sec_to_unit:
1054                floatpart -= sec_to_unit
1055                intpart += 1
1056            return (intpart, floatpart)
1057        return converter
1058
1059    def test_object_to_timeval(self):
1060        from _testcapi import pytime_object_to_timeval
1061
1062        self.check_int_rounding(pytime_object_to_timeval,
1063                                lambda secs: (secs, 0),
1064                                value_filter=self.time_t_filter)
1065
1066        self.check_float_rounding(pytime_object_to_timeval,
1067                                  self.create_converter(SEC_TO_US),
1068                                  value_filter=self.time_t_filter)
1069
1070         # test nan
1071        for time_rnd, _ in ROUNDING_MODES:
1072            with self.assertRaises(ValueError):
1073                pytime_object_to_timeval(float('nan'), time_rnd)
1074
1075    def test_object_to_timespec(self):
1076        from _testcapi import pytime_object_to_timespec
1077
1078        self.check_int_rounding(pytime_object_to_timespec,
1079                                lambda secs: (secs, 0),
1080                                value_filter=self.time_t_filter)
1081
1082        self.check_float_rounding(pytime_object_to_timespec,
1083                                  self.create_converter(SEC_TO_NS),
1084                                  value_filter=self.time_t_filter)
1085
1086        # test nan
1087        for time_rnd, _ in ROUNDING_MODES:
1088            with self.assertRaises(ValueError):
1089                pytime_object_to_timespec(float('nan'), time_rnd)
1090
1091@unittest.skipUnless(sys.platform == "darwin", "test weak linking on macOS")
1092class TestTimeWeaklinking(unittest.TestCase):
1093    # These test cases verify that weak linking support on macOS works
1094    # as expected. These cases only test new behaviour introduced by weak linking,
1095    # regular behaviour is tested by the normal test cases.
1096    #
1097    # See the section on Weak Linking in Mac/README.txt for more information.
1098    def test_clock_functions(self):
1099        import sysconfig
1100        import platform
1101
1102        config_vars = sysconfig.get_config_vars()
1103        var_name = "HAVE_CLOCK_GETTIME"
1104        if var_name not in config_vars or not config_vars[var_name]:
1105            raise unittest.SkipTest(f"{var_name} is not available")
1106
1107        mac_ver = tuple(int(x) for x in platform.mac_ver()[0].split("."))
1108
1109        clock_names = [
1110            "CLOCK_MONOTONIC", "clock_gettime", "clock_gettime_ns", "clock_settime",
1111            "clock_settime_ns", "clock_getres"]
1112
1113        if mac_ver >= (10, 12):
1114            for name in clock_names:
1115                self.assertTrue(hasattr(time, name), f"time.{name} is not available")
1116
1117        else:
1118            for name in clock_names:
1119                self.assertFalse(hasattr(time, name), f"time.{name} is available")
1120
1121
1122if __name__ == "__main__":
1123    unittest.main()
1124