Debian Codegraph @

pypy/module/time/test/apptest_time.py

raw symbols SCIP
1 # coding: utf-8
2
3 import pytest
4 import sys
5
6 # spaceconfig = {"usemodules": ["time", "struct", "binascii", "signal"]}
7
8 try:
9 import nt as posix
10 _WIN32 = True
11 except ImportError:
12 import posix
13 _WIN32 = False
14 os = posix
15 _MACOS = sys.platform == "darwin"
16
17
18 def test_attributes():
19 import time
20 assert isinstance(time.altzone, int)
21 assert isinstance(time.daylight, int)
22 assert isinstance(time.timezone, int)
23 assert isinstance(time.tzname, tuple)
24 assert isinstance(time.__doc__, str)
25 assert isinstance(time._STRUCT_TM_ITEMS, int)
26
27 def test_sleep():
28 import time
29 raises(TypeError, time.sleep, "foo")
30 time.sleep(0.12345)
31 raises(ValueError, time.sleep, -1.0)
32 raises((ValueError, OverflowError), time.sleep, float('nan'))
33 raises(OverflowError, time.sleep, float('inf'))
34
35 def test_time():
36 import time
37 t1 = time.time()
38 assert isinstance(t1, float)
39 assert t1 != 0.0 # 0.0 means failure
40 time.sleep(0.02)
41 t2 = time.time()
42 assert t1 != t2 # the resolution should be at least 0.01 secs
43
44 def test_time_ns():
45 import time
46 t1 = time.time_ns()
47 assert isinstance(t1, int)
48 assert t1 != 0 # 0 means failure
49 time.sleep(0.02)
50 t2 = time.time_ns()
51 assert t1 != t2 # the resolution should be at least 0.01 secs
52 assert abs(time.time() - time.time_ns() * 1e-9) < 0.1
53
54 def test_clock_realtime():
55 import time
56 if not hasattr(time, 'clock_gettime'):
57 skip("need time.clock_gettime()")
58 t1 = time.clock_gettime(time.CLOCK_REALTIME)
59 assert isinstance(t1, float)
60 time.sleep(time.clock_getres(time.CLOCK_REALTIME))
61 t2 = time.clock_gettime(time.CLOCK_REALTIME)
62 assert t1 != t2
63
64 def test_clock_realtime_ns():
65 import time
66 if not hasattr(time, 'clock_gettime_ns'):
67 skip("need time.clock_gettime_ns()")
68 t1 = time.clock_gettime_ns(time.CLOCK_REALTIME)
69 assert isinstance(t1, int)
70 time.sleep(time.clock_getres(time.CLOCK_REALTIME))
71 t2 = time.clock_gettime_ns(time.CLOCK_REALTIME)
72 assert t1 != t2
73 assert abs(time.clock_gettime(time.CLOCK_REALTIME) -
74 time.clock_gettime_ns(time.CLOCK_REALTIME) * 1e-9) < 0.1
75
76 def test_clock_monotonic():
77 import time
78 if not (hasattr(time, 'clock_gettime') and
79 hasattr(time, 'CLOCK_MONOTONIC')):
80 skip("need time.clock_gettime()/CLOCK_MONOTONIC")
81 t1 = time.clock_gettime(time.CLOCK_MONOTONIC)
82 assert isinstance(t1, float)
83 time.sleep(time.clock_getres(time.CLOCK_MONOTONIC))
84 t2 = time.clock_gettime(time.CLOCK_MONOTONIC)
85 assert t1 < t2
86
87 def test_clock_monotonic_ns():
88 import time
89 if not (hasattr(time, 'clock_gettime_ns') and
90 hasattr(time, 'CLOCK_MONOTONIC')):
91 skip("need time.clock_gettime()/CLOCK_MONOTONIC")
92 t1 = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
93 assert isinstance(t1, int)
94 time.sleep(time.clock_getres(time.CLOCK_MONOTONIC))
95 t2 = time.clock_gettime_ns(time.CLOCK_MONOTONIC)
96 assert t1 < t2
97 assert abs(time.clock_gettime(time.CLOCK_MONOTONIC) -
98 time.clock_gettime_ns(time.CLOCK_MONOTONIC) * 1e-9) < 0.1
99
100 def test_clock_gettime():
101 import time
102 clock_ids = ['CLOCK_REALTIME',
103 'CLOCK_REALTIME_COARSE',
104 'CLOCK_MONOTONIC',
105 'CLOCK_MONOTONIC_COARSE',
106 'CLOCK_MONOTONIC_RAW',
107 'CLOCK_BOOTTIME',
108 'CLOCK_PROCESS_CPUTIME_ID',
109 'CLOCK_THREAD_CPUTIME_ID',
110 'CLOCK_HIGHRES',
111 'CLOCK_PROF',
112 'CLOCK_UPTIME',]
113 for clock_id in clock_ids:
114 clock = getattr(time, clock_id, None)
115 if clock is None:
116 continue
117 t1 = time.clock_gettime(clock)
118 assert isinstance(t1, float)
119 time.sleep(time.clock_getres(clock))
120 t2 = time.clock_gettime(clock)
121 assert t1 < t2
122
123 def test_clock_gettime():
124 import time
125 clock_ids = ['CLOCK_REALTIME',
126 'CLOCK_REALTIME_COARSE',
127 'CLOCK_MONOTONIC',
128 'CLOCK_MONOTONIC_COARSE',
129 'CLOCK_MONOTONIC_RAW',
130 'CLOCK_BOOTTIME',
131 'CLOCK_PROCESS_CPUTIME_ID',
132 'CLOCK_THREAD_CPUTIME_ID',
133 'CLOCK_HIGHRES',
134 'CLOCK_PROF',
135 'CLOCK_UPTIME',]
136 for clock_id in clock_ids:
137 clock = getattr(time, clock_id, None)
138 if clock is None:
139 continue
140 t1 = time.clock_gettime_ns(clock)
141 assert isinstance(t1, int)
142 time.sleep(time.clock_getres(clock))
143 t2 = time.clock_gettime_ns(clock)
144 assert t1 < t2
145 assert abs(time.clock_gettime(clock) -
146 time.clock_gettime_ns(clock) * 1e-9) < 0.1
147
148 def test_ctime():
149 import time
150 raises(TypeError, time.ctime, "foo")
151 time.ctime(None)
152 time.ctime()
153 res = time.ctime(0)
154 assert isinstance(res, str)
155 time.ctime(time.time())
156 raises(OverflowError, time.ctime, 1E200)
157 raises(OverflowError, time.ctime, 10**900)
158 for year in [-100, 100, 1000, 2000, 10000]:
159 try:
160 testval = time.mktime((year, 1, 10) + (0,)*6)
161 except (ValueError, OverflowError):
162 # If mktime fails, ctime will fail too. This may happen
163 # on some platforms.
164 pass
165 else:
166 assert time.ctime(testval)[20:] == str(year)
167
168 def test_gmtime():
169 import time, sys
170 raises(TypeError, time.gmtime, "foo")
171 time.gmtime()
172 time.gmtime(None)
173 time.gmtime(0)
174 res = time.gmtime(time.time())
175 assert isinstance(res, time.struct_time)
176 assert res[-1] == 0 # DST is always zero in gmtime()
177 t0 = time.mktime(time.gmtime())
178 t1 = time.mktime(time.gmtime(None))
179 assert 0 <= (t1 - t0) < 1.2
180 t = time.time()
181 assert time.gmtime(t) == time.gmtime(t)
182 raises(OverflowError, time.gmtime, 2**64)
183 raises(OverflowError, time.gmtime, -2**64)
184 if sys.platform == 'win32':
185 # This is
186 # datetime.datetime.max.replace(tzinfo=datetime.timezone.utc).timestamp()) - 1
187 # and is checked in aiohttp
188 # see
189 # https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-localtime32-localtime64
190 raises(OSError, time.gmtime, 253402300799)
191
192 def test_localtime():
193 import time
194 raises(TypeError, time.localtime, "foo")
195 time.localtime()
196 time.localtime(None)
197 time.localtime(0)
198 res = time.localtime(time.time())
199 assert isinstance(res, time.struct_time)
200 t0 = time.mktime(time.localtime())
201 t1 = time.mktime(time.localtime(None))
202 assert 0 <= (t1 - t0) < 1.2
203 t = time.time()
204 assert time.localtime(t) == time.localtime(t)
205 if _WIN32:
206 raises(OSError, time.localtime, -1)
207 else:
208 time.localtime(-1)
209
210 def test_localtime_invalid():
211 from time import localtime
212 exc = raises(ValueError, localtime, float('nan'))
213 assert 'Invalid value' in str(exc.value)
214
215 def test_mktime():
216 import time
217 import sys
218 raises(TypeError, time.mktime, "foo")
219 raises(TypeError, time.mktime, None)
220 raises(TypeError, time.mktime, (1, 2))
221 raises(TypeError, time.mktime, (1, 2, 3, 4, 5, 6, 'f', 8, 9))
222 res = time.mktime(time.localtime())
223 assert isinstance(res, float)
224
225 ltime = time.localtime()
226 ltime = list(ltime)
227 ltime[0] = -1
228 if _WIN32 or _MACOS or sys.maxsize < 2**32:
229 raises(OverflowError, time.mktime, tuple(ltime))
230 else:
231 time.mktime(tuple(ltime)) # Does not crash anymore
232 ltime[0] = 100
233 if _WIN32 or _MACOS or sys.maxsize < 2**32:
234 raises(OverflowError, time.mktime, tuple(ltime))
235 else:
236 time.mktime(tuple(ltime)) # Does not crash anymore
237
238 t = time.time()
239 assert int(time.mktime(time.localtime(t))) == int(t)
240 assert int(time.mktime(time.gmtime(t))) - time.timezone == int(t)
241 ltime = time.localtime()
242 assert time.mktime(tuple(ltime)) == time.mktime(ltime)
243
244 res = time.mktime((2000, 1, 1, 0, 0, 0, -1, -1, -1))
245 assert time.ctime(res) == 'Sat Jan 1 00:00:00 2000'
246
247 def test_mktime_overflow():
248 import time
249 import sys
250 if _WIN32:
251 # on windows, mktime will convert to utc and the upper
252 # bound is 23:59:59 Dec 21, 3000. So in order to be sure
253 # to exceed the limit everywhere, add 2 years
254 MAX_YEAR = 3000
255 DELTA = 2
256 MIN_YEAR = 1971
257 elif sys.maxsize < 2**32:
258 # 32-bit Linux has a 32-bit time_t (range ~1902-2037)
259 MAX_YEAR = 2037
260 DELTA = 2
261 MIN_YEAR = 1902
262 else:
263 MAX_YEAR = (1 << 31) - 1
264 DELTA = 1
265 MIN_YEAR = -(1 << 31) + 1900
266 time.mktime((MAX_YEAR,) + (0,) * 8) # doesn't raise
267 with raises(OverflowError):
268 time.mktime((MAX_YEAR + DELTA,) + (0,) * 8)
269 if _MACOS:
270 raises(OverflowError, time.mktime, (MIN_YEAR,) + (0,) * 8)
271 else:
272 time.mktime((MIN_YEAR,) + (0,) * 8)
273 with raises(OverflowError):
274 time.mktime((MIN_YEAR - DELTA,) + (0,) * 8)
275
276 def test_asctime():
277 import time
278 time.asctime()
279 # raises(TypeError, time.asctime, None)
280 raises(TypeError, time.asctime, ())
281 raises(TypeError, time.asctime, (1,))
282 raises(TypeError, time.asctime, range(8))
283 raises(TypeError, time.asctime, (1, 2))
284 raises(TypeError, time.asctime, (1, 2, 3, 4, 5, 6, 'f', 8, 9))
285 raises(TypeError, time.asctime, "foo")
286 raises(ValueError, time.asctime, (1900, -1, 1, 0, 0, 0, 0, 1, -1))
287 res = time.asctime()
288 assert isinstance(res, str)
289 time.asctime(time.localtime())
290 t = time.time()
291 assert time.ctime(t) == time.asctime(time.localtime(t))
292 if time.timezone:
293 assert time.ctime(t) != time.asctime(time.gmtime(t))
294 ltime = time.localtime()
295 assert time.asctime(tuple(ltime)) == time.asctime(ltime)
296 try:
297 time.asctime((12345,) + (0,) * 8) # assert this doesn't crash
298 except ValueError:
299 pass # some OS (ie POSIXes besides Linux) reject year > 9999
300
301 def test_asctime_large_year():
302 import time
303 assert time.asctime((12345,) +
304 (0,) * 8) == 'Mon Jan 1 00:00:00 12345'
305 assert time.asctime((123456789,) +
306 (0,) * 8) == 'Mon Jan 1 00:00:00 123456789'
307 sizeof_int = 4
308 bigyear = (1 << 8 * sizeof_int - 1) - 1
309 asc = time.asctime((bigyear, 6, 1) + (0,)*6)
310 assert asc[-len(str(bigyear)):] == str(bigyear)
311 raises(OverflowError, time.asctime, (bigyear + 1,) + (0,)*8)
312 raises(OverflowError, time.asctime, (-bigyear - 2 + 1900,) + (0,)*8)
313
314 def test_struct_time():
315 import time
316 raises(TypeError, time.struct_time)
317 raises(TypeError, time.struct_time, "foo")
318 raises(TypeError, time.struct_time, (1, 2, 3))
319 tup = (1, 2, 3, 4, 5, 6, 7, 8, 9)
320 st_time = time.struct_time(tup)
321 assert str(st_time).startswith('time.struct_time(tm_year=1, ')
322 assert len(st_time) == len(tup)
323
324 def test_tzset():
325 import time
326 import os
327
328 if _WIN32:
329 skip("tzset available only under Unix")
330
331 # epoch time of midnight Dec 25th 2002. Never DST in northern
332 # hemisphere.
333 xmas2002 = 1040774400.0
334
335 # these formats are correct for 2002, and possibly future years
336 # this format is the 'standard' as documented at:
337 # http://www.opengroup.org/onlinepubs/007904975/basedefs/xbd_chap08.html
338 # They are also documented in the tzset(3) man page on most Unix
339 # systems.
340 eastern = 'EST+05EDT,M4.1.0,M10.5.0'
341 victoria = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
342 utc = 'UTC+0'
343
344 org_TZ = os.environ.get('TZ', None)
345 try:
346 # Make sure we can switch to UTC time and results are correct
347 # Note that unknown timezones default to UTC.
348 # Note that altzone is undefined in UTC, as there is no DST
349 os.environ['TZ'] = eastern
350 time.tzset()
351 os.environ['TZ'] = utc
352 time.tzset()
353 assert time.gmtime(xmas2002) == time.localtime(xmas2002)
354 assert time.daylight == 0
355 assert time.timezone == 0
356 assert time.localtime(xmas2002).tm_isdst == 0
357
358 # make sure we can switch to US/Eastern
359 os.environ['TZ'] = eastern
360 time.tzset()
361 assert time.gmtime(xmas2002) != time.localtime(xmas2002)
362 assert time.tzname == ('EST', 'EDT')
363 assert len(time.tzname) == 2
364 assert time.daylight == 1
365 assert time.timezone == 18000
366 assert time.altzone == 14400
367 assert time.localtime(xmas2002).tm_isdst == 0
368
369 # now go to the southern hemisphere.
370 os.environ['TZ'] = victoria
371 time.tzset()
372 assert time.gmtime(xmas2002) != time.localtime(xmas2002)
373 assert time.tzname[0] == 'AEST'
374 assert time.tzname[1] == 'AEDT'
375 assert len(time.tzname) == 2
376 assert time.daylight == 1
377 assert time.timezone == -36000
378 assert time.altzone == -39600
379 assert time.localtime(xmas2002).tm_isdst == 1
380 finally:
381 # repair TZ environment variable in case any other tests
382 # rely on it.
383 if org_TZ is not None:
384 os.environ['TZ'] = org_TZ
385 elif 'TZ' in os.environ:
386 del os.environ['TZ']
387 time.tzset()
388
389 def test_localtime_timezone():
390 import time
391 import os
392 if _WIN32:
393 skip("tzset available only under Unix")
394 if not (os.path.exists('/usr/share/zoneinfo/Europe/Kyiv') or
395 os.path.exists('/usr/lib/zoneinfo/Europe/Kyiv')):
396 skip("Kyiv timezone unavailable")
397 org_TZ = os.environ.get('TZ', None)
398 try:
399 os.environ['TZ'] = 'Europe/Kyiv'
400 time.tzset()
401 localtm = time.localtime(0)
402 assert localtm.tm_zone == "MSK"
403 assert localtm.tm_gmtoff == 10800
404 finally:
405 if org_TZ is not None:
406 os.environ['TZ'] = org_TZ
407 elif 'TZ' in os.environ:
408 del os.environ['TZ']
409 time.tzset()
410
411 def test_large_year_does_not_crash():
412 # may fail on windows but should not crash
413 import time
414 try:
415 time.strftime('%Y', (10000, 0, 0, 0, 0, 0, 0, 0, 0))
416 except ValueError:
417 pass
418
419 def test_strftime():
420 import time
421 import os, sys
422
423 t = time.time()
424 tt = time.gmtime(t)
425 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
426 'j', 'm', 'M', 'p', 'S',
427 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
428 format = ' %' + directive
429 time.strftime(format, tt)
430
431 raises(TypeError, time.strftime, ())
432 raises(TypeError, time.strftime, (1,))
433 raises(TypeError, time.strftime, range(8))
434
435 if _WIN32:
436 raises(ValueError, time.strftime, '%f')
437 # windows must have year stricly > 0
438 return
439 elif sys.platform == 'darwin' or 'bsd' in sys.platform:
440 # darwin strips % of unknown format codes
441 # http://bugs.python.org/issue9811
442 assert time.strftime('%f') == 'f'
443
444 # Darwin always use four digits for %Y, Linux uses as many as needed.
445 expected_year = '0000'
446 else:
447 assert time.strftime('%f') == '%f'
448 expected_year = '0'
449 with raises(ValueError):
450 time.strftime("%Y\0", tt)
451
452 expected_formatted_date = expected_year + ' 01 01 00 00 00 1 001'
453 assert time.strftime("%Y %m %d %H %M %S %w %j", (0,) * 9) == expected_formatted_date
454
455 def test_strftime_ext():
456 import time
457
458 tt = time.gmtime()
459 try:
460 result = time.strftime('%D', tt)
461 except ValueError:
462 pass
463 else:
464 assert result == time.strftime('%m/%d/%y', tt)
465
466 def test_strftime_bounds_checking():
467 import time
468 import os
469
470 # make sure that strftime() checks the bounds of the various parts
471 # of the time tuple.
472
473 # check year
474 time.strftime('', (1899, 1, 1, 0, 0, 0, 0, 1, -1))
475 if _WIN32:
476 with raises(ValueError):
477 time.strftime('', (0, 1, 1, 0, 0, 0, 0, 1, -1))
478 else:
479 time.strftime('', (0, 1, 1, 0, 0, 0, 0, 1, -1))
480
481 # check month
482 raises(ValueError, time.strftime, '', (1900, 13, 1, 0, 0, 0, 0, 1, -1))
483 # check day of month
484 raises(ValueError, time.strftime, '', (1900, 1, 32, 0, 0, 0, 0, 1, -1))
485 # check hour
486 raises(ValueError, time.strftime, '', (1900, 1, 1, -1, 0, 0, 0, 1, -1))
487 raises(ValueError, time.strftime, '', (1900, 1, 1, 24, 0, 0, 0, 1, -1))
488 # check minute
489 raises(ValueError, time.strftime, '', (1900, 1, 1, 0, -1, 0, 0, 1, -1))
490 raises(ValueError, time.strftime, '', (1900, 1, 1, 0, 60, 0, 0, 1, -1))
491 # check second
492 raises(ValueError, time.strftime, '', (1900, 1, 1, 0, 0, -1, 0, 1, -1))
493 # C99 only requires allowing for one leap second, but Python's docs say
494 # allow two leap seconds (0..61)
495 raises(ValueError, time.strftime, '', (1900, 1, 1, 0, 0, 62, 0, 1, -1))
496 # no check for upper-bound day of week;
497 # value forced into range by a "% 7" calculation.
498 # start check at -2 since gettmarg() increments value before taking
499 # modulo.
500 raises(ValueError, time.strftime, '', (1900, 1, 1, 0, 0, 0, -2, 1, -1))
501 # check day of the year
502 raises(ValueError, time.strftime, '', (1900, 1, 1, 0, 0, 0, 0, 367, -1))
503 # check daylight savings flag
504 time.strftime('', (1900, 1, 1, 0, 0, 0, 0, 1, -2))
505 time.strftime('', (1900, 1, 1, 0, 0, 0, 0, 1, 2))
506
507 @pytest.mark.skipif(sys.platform=="win32", reason='fails on win32')
508 def test_strftime_nonascii():
509 import time
510 import _locale
511 prev_loc = _locale.setlocale(_locale.LC_TIME)
512 try:
513 _locale.setlocale(_locale.LC_TIME, "fr_CH")
514 except _locale.Error:
515 skip("unsupported locale LC_TIME=fr_CH")
516 try:
517 s = time.strftime('%B.', time.localtime(192039127))
518 # I am unsure, but I think that this fails because decoding of
519 # the result isn't done in the fr_CH locale. There is no code
520 # to grab the LC_TIME locale specifically, which is the one
521 # used by strftime().
522 assert s == "f\xe9vrier."
523 finally:
524 _locale.setlocale(_locale.LC_TIME, prev_loc)
525
526 def test_strftime_surrogate():
527 import time
528 # maybe raises, maybe doesn't, but should not crash
529 try:
530 res = time.strftime(u'%y\ud800%m', time.localtime(192039127))
531 except UnicodeEncodeError:
532 pass
533 else:
534 expected = u'76\ud80002'
535 print(len(res), len(expected))
536 assert res == u'76\ud80002'
537
538 @pytest.mark.skipif(_WIN32, reason="fails to encode s")
539 def test_strftime_unicode():
540 import time
541 s = u"ððððððððððððððððððððððð꿀"
542 res = time.strftime(u"%D" + s, time.localtime(192039127))
543 assert res.endswith(s)
544
545 def test_strptime():
546 import time
547
548 t = time.time()
549 tt = time.gmtime(t)
550 assert isinstance(time.strptime("", ""), type(tt))
551
552 for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
553 'j', 'm', 'M', 'p', 'S',
554 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
555 format = ' %' + directive
556 # print(format)
557 time.strptime(time.strftime(format, tt), format)
558
559 def test_pickle():
560 import _pickle as pickle
561 import time
562 now = time.localtime()
563 new = pickle.loads(pickle.dumps(now))
564 assert new == now
565 assert type(new) is type(now)
566
567 def test_monotonic():
568 import time
569 t1 = time.monotonic()
570 assert isinstance(t1, float)
571 time.sleep(0.02)
572 t2 = time.monotonic()
573 assert t1 < t2
574
575 def test_monotonic_ns():
576 import time
577 t1 = time.monotonic_ns()
578 assert isinstance(t1, int)
579 time.sleep(0.02)
580 t2 = time.monotonic_ns()
581 assert t1 < t2
582 assert abs(time.monotonic() - time.monotonic_ns() * 1e-9) < 0.1
583
584 def test_perf_counter():
585 import time
586 assert isinstance(time.perf_counter(), float)
587
588 def test_perf_counter_ns():
589 import time
590 assert isinstance(time.perf_counter_ns(), int)
591 assert abs(time.perf_counter() - time.perf_counter_ns() * 1e-9) < 0.1
592
593 def test_process_time():
594 import time
595 t1 = time.process_time()
596 assert isinstance(t1, float)
597 time.sleep(0.1)
598 t2 = time.process_time()
599 # process_time() should not include time spent during sleep
600 assert (t2 - t1) < 0.05
601
602 def test_process_time_ns():
603 import time
604 t1 = time.process_time_ns()
605 assert isinstance(t1, int)
606 time.sleep(0.1)
607 t2 = time.process_time_ns()
608 # process_time_ns() should not include time spent during sleep
609 assert (t2 - t1) < 5 * 10**7
610 assert abs(time.process_time() - time.process_time_ns() * 1e-9) < 0.1
611
612 def test_thread_time():
613 import time
614 if not hasattr(time, 'thread_time'):
615 skip("need time.thread_time")
616 t1 = time.thread_time()
617 assert isinstance(t1, float)
618 time.sleep(0.1)
619 t2 = time.thread_time()
620 # thread_time_time() should not include time spent during sleep
621 assert (t2 - t1) < 0.05
622
623 def test_thread_time_ns():
624 import time
625 if not hasattr(time, 'thread_time_ns'):
626 skip("need time.thread_time_ns")
627 t1 = time.thread_time_ns()
628 assert isinstance(t1, int)
629 time.sleep(0.1)
630 t2 = time.thread_time_ns()
631 # process_thread_ns() should not include time spent during sleep
632 assert (t2 - t1) < 5 * 10**7
633 assert abs(time.thread_time() - time.thread_time_ns() * 1e-9) < 0.1
634
635 def test_get_clock_info():
636 import time
637 clocks = ['perf_counter', 'process_time', 'time']
638 if hasattr(time, 'monotonic'):
639 clocks.append('monotonic')
640 if hasattr(time, 'thread_time'):
641 clocks.append('thread_time')
642 for name in clocks:
643 info = time.get_clock_info(name)
644 assert isinstance(info.implementation, str)
645 assert info.implementation != ''
646 assert isinstance(info.monotonic, bool)
647 assert isinstance(info.resolution, float)
648 assert info.resolution > 0.0
649 assert info.resolution <= 1.0
650 assert isinstance(info.adjustable, bool)
651
652 def test_pep475_retry_sleep():
653 import time
654 import _signal as signal
655 if not hasattr(signal, 'SIGALRM'):
656 skip("SIGALRM available only under Unix")
657 signalled = []
658
659 def foo(*args):
660 signalled.append("ALARM")
661
662 signal.signal(signal.SIGALRM, foo)
663 try:
664 t1 = time.time()
665 signal.alarm(1)
666 time.sleep(3.0)
667 t2 = time.time()
668 finally:
669 signal.signal(signal.SIGALRM, signal.SIG_DFL)
670
671 assert signalled != []
672 assert t2 - t1 > 2.99
673
674 def test_tm_gmtoff_valid():
675 import time
676 local = time.localtime()
677 assert local.tm_gmtoff is not None
678 assert local.tm_zone is not None
679 local = time.gmtime()
680 assert local.tm_gmtoff is not None
681 assert local.tm_zone is not None
682
683 def test_match_args():
684 import time
685 assert time.struct_time.__match_args__ == ('tm_year', 'tm_mon', 'tm_mday', 'tm_hour', 'tm_min', 'tm_sec', 'tm_wday', 'tm_yday', 'tm_isdst')
686