Debian Codegraph @

Lib/test/test_builtin.py

raw
1 # Python test set -- built-in functions
2
3 import ast
4 import builtins
5 import collections
6 import contextlib
7 import decimal
8 import fractions
9 import gc
10 import io
11 import locale
12 import math
13 import os
14 import pickle
15 import platform
16 import random
17 import re
18 import sys
19 import traceback
20 import types
21 import typing
22 import unittest
23 import warnings
24 from contextlib import ExitStack
25 from functools import partial
26 from inspect import CO_COROUTINE
27 from itertools import product
28 from textwrap import dedent
29 from types import AsyncGeneratorType, FunctionType, CellType
30 from operator import neg
31 from test import support
32 from test.support import cpython_only, swap_attr
33 from test.support import async_yield, run_yielding_async_fn
34 from test.support.import_helper import import_module
35 from test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)
36 from test.support.script_helper import assert_python_ok
37 from test.support.testcase import ComplexesAreIdenticalMixin
38 from test.support.warnings_helper import check_warnings
39 from test.support import requires_IEEE_754
40 from unittest.mock import MagicMock, patch
41 try:
42 import pty, signal
43 except ImportError:
44 pty = signal = None
45
46
47 # Detect evidence of double-rounding: sum() does not always
48 # get improved accuracy on machines that suffer from double rounding.
49 x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
50 HAVE_DOUBLE_ROUNDING = (x + y == 1e16 + 4)
51
52 # used as proof of globals being used
53 A_GLOBAL_VALUE = 123
54
55 class Squares:
56
57 def __init__(self, max):
58 self.max = max
59 self.sofar = []
60
61 def __len__(self): return len(self.sofar)
62
63 def __getitem__(self, i):
64 if not 0 <= i < self.max: raise IndexError
65 n = len(self.sofar)
66 while n <= i:
67 self.sofar.append(n*n)
68 n += 1
69 return self.sofar[i]
70
71 class StrSquares:
72
73 def __init__(self, max):
74 self.max = max
75 self.sofar = []
76
77 def __len__(self):
78 return len(self.sofar)
79
80 def __getitem__(self, i):
81 if not 0 <= i < self.max:
82 raise IndexError
83 n = len(self.sofar)
84 while n <= i:
85 self.sofar.append(str(n*n))
86 n += 1
87 return self.sofar[i]
88
89 class BitBucket:
90 def write(self, line):
91 pass
92
93 test_conv_no_sign = [
94 ('0', 0),
95 ('1', 1),
96 ('9', 9),
97 ('10', 10),
98 ('99', 99),
99 ('100', 100),
100 ('314', 314),
101 (' 314', 314),
102 ('314 ', 314),
103 (' \t\t 314 \t\t ', 314),
104 (repr(sys.maxsize), sys.maxsize),
105 (' 1x', ValueError),
106 (' 1 ', 1),
107 (' 1\02 ', ValueError),
108 ('', ValueError),
109 (' ', ValueError),
110 (' \t\t ', ValueError),
111 (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
112 (chr(0x200), ValueError),
113 ]
114
115 test_conv_sign = [
116 ('0', 0),
117 ('1', 1),
118 ('9', 9),
119 ('10', 10),
120 ('99', 99),
121 ('100', 100),
122 ('314', 314),
123 (' 314', ValueError),
124 ('314 ', 314),
125 (' \t\t 314 \t\t ', ValueError),
126 (repr(sys.maxsize), sys.maxsize),
127 (' 1x', ValueError),
128 (' 1 ', ValueError),
129 (' 1\02 ', ValueError),
130 ('', ValueError),
131 (' ', ValueError),
132 (' \t\t ', ValueError),
133 (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
134 (chr(0x200), ValueError),
135 ]
136
137 class TestFailingBool:
138 def __bool__(self):
139 raise RuntimeError
140
141 class TestFailingIter:
142 def __iter__(self):
143 raise RuntimeError
144
145 def filter_char(arg):
146 return ord(arg) > ord("d")
147
148 def map_char(arg):
149 return chr(ord(arg)+1)
150
151 def pack(*args):
152 return args
153
154 class BuiltinTest(ComplexesAreIdenticalMixin, unittest.TestCase):
155 # Helper to check picklability
156 def check_iter_pickle(self, it, seq, proto):
157 itorg = it
158 d = pickle.dumps(it, proto)
159 it = pickle.loads(d)
160 self.assertEqual(type(itorg), type(it))
161 self.assertEqual(list(it), seq)
162
163 #test the iterator after dropping one from it
164 it = pickle.loads(d)
165 try:
166 next(it)
167 except StopIteration:
168 return
169 d = pickle.dumps(it, proto)
170 it = pickle.loads(d)
171 self.assertEqual(list(it), seq[1:])
172
173 def test_import(self):
174 __import__('sys')
175 __import__('time')
176 __import__('string')
177 __import__(name='sys')
178 __import__(name='time', level=0)
179 self.assertRaises(ModuleNotFoundError, __import__, 'spamspam')
180 self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
181 self.assertRaises(ValueError, __import__, '')
182 self.assertRaises(TypeError, __import__, 'sys', name='sys')
183 # Relative import outside of a package with no __package__ or __spec__ (bpo-37409).
184 with self.assertWarns(ImportWarning):
185 self.assertRaises(ImportError, __import__, '',
186 {'__package__': None, '__spec__': None, '__name__': '__main__'},
187 locals={}, fromlist=('foo',), level=1)
188 # embedded null character
189 self.assertRaises(ModuleNotFoundError, __import__, 'string\x00')
190
191 def test_abs(self):
192 # int
193 self.assertEqual(abs(0), 0)
194 self.assertEqual(abs(1234), 1234)
195 self.assertEqual(abs(-1234), 1234)
196 self.assertTrue(abs(-sys.maxsize-1) > 0)
197 # float
198 self.assertEqual(abs(0.0), 0.0)
199 self.assertEqual(abs(3.14), 3.14)
200 self.assertEqual(abs(-3.14), 3.14)
201 # str
202 self.assertRaises(TypeError, abs, 'a')
203 # bool
204 self.assertEqual(abs(True), 1)
205 self.assertEqual(abs(False), 0)
206 # other
207 self.assertRaises(TypeError, abs)
208 self.assertRaises(TypeError, abs, None)
209 class AbsClass(object):
210 def __abs__(self):
211 return -5
212 self.assertEqual(abs(AbsClass()), -5)
213
214 def test_all(self):
215 self.assertEqual(all([2, 4, 6]), True)
216 self.assertEqual(all([2, None, 6]), False)
217 self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
218 self.assertRaises(RuntimeError, all, TestFailingIter())
219 self.assertRaises(TypeError, all, 10) # Non-iterable
220 self.assertRaises(TypeError, all) # No args
221 self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args
222 self.assertEqual(all([]), True) # Empty iterator
223 self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
224 S = [50, 60]
225 self.assertEqual(all(x > 42 for x in S), True)
226 S = [50, 40, 60]
227 self.assertEqual(all(x > 42 for x in S), False)
228 S = [50, 40, 60, TestFailingBool()]
229 self.assertEqual(all(x > 42 for x in S), False)
230
231 def test_any(self):
232 self.assertEqual(any([None, None, None]), False)
233 self.assertEqual(any([None, 4, None]), True)
234 self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
235 self.assertRaises(RuntimeError, any, TestFailingIter())
236 self.assertRaises(TypeError, any, 10) # Non-iterable
237 self.assertRaises(TypeError, any) # No args
238 self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args
239 self.assertEqual(any([]), False) # Empty iterator
240 self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
241 S = [40, 60, 30]
242 self.assertEqual(any(x > 42 for x in S), True)
243 S = [40, 60, 30, TestFailingBool()]
244 self.assertEqual(any(x > 42 for x in S), True)
245 S = [10, 20, 30]
246 self.assertEqual(any(x > 42 for x in S), False)
247
248 def test_all_any_tuple_optimization(self):
249 def f_all():
250 return all(x-2 for x in [1,2,3])
251
252 def f_any():
253 return any(x-1 for x in [1,2,3])
254
255 def f_tuple():
256 return tuple(2*x for x in [1,2,3])
257
258 funcs = [f_all, f_any, f_tuple]
259
260 for f in funcs:
261 # check that generator code object is not duplicated
262 code_objs = [c for c in f.__code__.co_consts if isinstance(c, type(f.__code__))]
263 self.assertEqual(len(code_objs), 1)
264
265
266 # check the overriding the builtins works
267
268 global all, any, tuple
269 saved = all, any, tuple
270 try:
271 all = lambda x : "all"
272 any = lambda x : "any"
273 tuple = lambda x : "tuple"
274
275 overridden_outputs = [f() for f in funcs]
276 finally:
277 all, any, tuple = saved
278
279 self.assertEqual(overridden_outputs, ['all', 'any', 'tuple'])
280
281 # Now repeat, overriding the builtins module as well
282 saved = all, any, tuple
283 try:
284 builtins.all = all = lambda x : "all"
285 builtins.any = any = lambda x : "any"
286 builtins.tuple = tuple = lambda x : "tuple"
287
288 overridden_outputs = [f() for f in funcs]
289 finally:
290 all, any, tuple = saved
291 builtins.all, builtins.any, builtins.tuple = saved
292
293 self.assertEqual(overridden_outputs, ['all', 'any', 'tuple'])
294
295
296 def test_builtin_call_async_genexpr_no_crash(self):
297 async def f_all():
298 return all(await 2 for _ in [])
299
300 async def f_any():
301 return any(await 2 for _ in [])
302
303 async def f_tuple():
304 return tuple(await 2 for _ in [])
305
306 async def f_list():
307 return list(await 2 for _ in [])
308
309 async def f_set():
310 return set(await 2 for _ in [])
311
312 for f in (f_all, f_any, f_tuple, f_list, f_set):
313 with self.subTest(func=f.__name__):
314 with self.assertRaises(TypeError):
315 run_yielding_async_fn(f)
316
317 def test_ascii(self):
318 self.assertEqual(ascii(''), '\'\'')
319 self.assertEqual(ascii(0), '0')
320 self.assertEqual(ascii(()), '()')
321 self.assertEqual(ascii([]), '[]')
322 self.assertEqual(ascii({}), '{}')
323 a = []
324 a.append(a)
325 self.assertEqual(ascii(a), '[[...]]')
326 a = {}
327 a[0] = a
328 self.assertEqual(ascii(a), '{0: {...}}')
329 # Advanced checks for unicode strings
330 def _check_uni(s):
331 self.assertEqual(ascii(s), repr(s))
332 _check_uni("'")
333 _check_uni('"')
334 _check_uni('"\'')
335 _check_uni('\0')
336 _check_uni('\r\n\t .')
337 # Unprintable non-ASCII characters
338 _check_uni('\x85')
339 _check_uni('\u1fff')
340 _check_uni('\U00012fff')
341 # Lone surrogates
342 _check_uni('\ud800')
343 _check_uni('\udfff')
344 # Issue #9804: surrogates should be joined even for printable
345 # wide characters (UCS-2 builds).
346 self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
347 # All together
348 s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
349 self.assertEqual(ascii(s),
350 r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")
351
352 def test_neg(self):
353 x = -sys.maxsize-1
354 self.assertTrue(isinstance(x, int))
355 self.assertEqual(-x, sys.maxsize+1)
356
357 def test_callable(self):
358 self.assertTrue(callable(len))
359 self.assertFalse(callable("a"))
360 self.assertTrue(callable(callable))
361 self.assertTrue(callable(lambda x, y: x + y))
362 self.assertFalse(callable(__builtins__))
363 def f(): pass
364 self.assertTrue(callable(f))
365
366 class C1:
367 def meth(self): pass
368 self.assertTrue(callable(C1))
369 c = C1()
370 self.assertTrue(callable(c.meth))
371 self.assertFalse(callable(c))
372
373 # __call__ is looked up on the class, not the instance
374 c.__call__ = None
375 self.assertFalse(callable(c))
376 c.__call__ = lambda self: 0
377 self.assertFalse(callable(c))
378 del c.__call__
379 self.assertFalse(callable(c))
380
381 class C2(object):
382 def __call__(self): pass
383 c2 = C2()
384 self.assertTrue(callable(c2))
385 c2.__call__ = None
386 self.assertTrue(callable(c2))
387 class C3(C2): pass
388 c3 = C3()
389 self.assertTrue(callable(c3))
390
391 def test_chr(self):
392 self.assertEqual(chr(0), '\0')
393 self.assertEqual(chr(32), ' ')
394 self.assertEqual(chr(65), 'A')
395 self.assertEqual(chr(97), 'a')
396 self.assertEqual(chr(0xff), '\xff')
397 self.assertRaises(TypeError, chr)
398 self.assertRaises(TypeError, chr, 65.0)
399 self.assertEqual(chr(0x0000FFFF), "\U0000FFFF")
400 self.assertEqual(chr(0x00010000), "\U00010000")
401 self.assertEqual(chr(0x00010001), "\U00010001")
402 self.assertEqual(chr(0x000FFFFE), "\U000FFFFE")
403 self.assertEqual(chr(0x000FFFFF), "\U000FFFFF")
404 self.assertEqual(chr(0x00100000), "\U00100000")
405 self.assertEqual(chr(0x00100001), "\U00100001")
406 self.assertEqual(chr(0x0010FFFE), "\U0010FFFE")
407 self.assertEqual(chr(0x0010FFFF), "\U0010FFFF")
408 self.assertRaises(ValueError, chr, -1)
409 self.assertRaises(ValueError, chr, 0x00110000)
410 self.assertRaises(ValueError, chr, 1<<24)
411 self.assertRaises(ValueError, chr, 2**32-1)
412 self.assertRaises(ValueError, chr, -2**32)
413 self.assertRaises(ValueError, chr, 2**1000)
414 self.assertRaises(ValueError, chr, -2**1000)
415
416 def test_cmp(self):
417 self.assertNotHasAttr(builtins, "cmp")
418
419 def test_compile(self):
420 compile('print(1)\n', '', 'exec')
421 bom = b'\xef\xbb\xbf'
422 compile(bom + b'print(1)\n', '', 'exec')
423 compile(source='pass', filename='?', mode='exec')
424 compile(dont_inherit=False, filename='tmp', source='0', mode='eval')
425 compile('pass', '?', dont_inherit=True, mode='exec')
426 compile(memoryview(b"text"), "name", "exec")
427 self.assertRaises(TypeError, compile)
428 self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
429 self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
430 self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
431 mode='eval', source='0', filename='tmp')
432 compile('print("\xe5")\n', '', 'exec')
433 self.assertRaises(SyntaxError, compile, chr(0), 'f', 'exec')
434 self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
435
436 # test the optimize argument
437
438 codestr = '''def f():
439 """doc"""
440 debug_enabled = False
441 if __debug__:
442 debug_enabled = True
443 try:
444 assert False
445 except AssertionError:
446 return (True, f.__doc__, debug_enabled, __debug__)
447 else:
448 return (False, f.__doc__, debug_enabled, __debug__)
449 '''
450 def f(): """doc"""
451 values = [(-1, __debug__, f.__doc__, __debug__, __debug__),
452 (0, True, 'doc', True, True),
453 (1, False, 'doc', False, False),
454 (2, False, None, False, False)]
455 for optval, *expected in values:
456 with self.subTest(optval=optval):
457 # test both direct compilation and compilation via AST
458 codeobjs = []
459 codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
460 tree = ast.parse(codestr, optimize=optval)
461 codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
462 for code in codeobjs:
463 ns = {}
464 exec(code, ns)
465 rv = ns['f']()
466 self.assertEqual(rv, tuple(expected))
467
468 def test_compile_top_level_await_no_coro(self):
469 """Make sure top level non-await codes get the correct coroutine flags"""
470 modes = ('single', 'exec')
471 code_samples = [
472 '''def f():pass\n''',
473 '''[x for x in l]''',
474 '''{x for x in l}''',
475 '''(x for x in l)''',
476 '''{x:x for x in l}''',
477 ]
478 for mode, code_sample in product(modes, code_samples):
479 source = dedent(code_sample)
480 co = compile(source,
481 '?',
482 mode,
483 flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
484
485 self.assertNotEqual(co.co_flags & CO_COROUTINE, CO_COROUTINE,
486 msg=f"source={source} mode={mode}")
487
488
489 def test_compile_top_level_await(self):
490 """Test whether code with top level await can be compiled.
491
492 Make sure it compiles only with the PyCF_ALLOW_TOP_LEVEL_AWAIT flag
493 set, and make sure the generated code object has the CO_COROUTINE flag
494 set in order to execute it with `await eval(.....)` instead of exec,
495 or via a FunctionType.
496 """
497
498 # helper function just to check we can run top=level async-for
499 async def arange(n):
500 for i in range(n):
501 yield i
502
503 class Lock:
504 async def __aenter__(self):
505 return self
506
507 async def __aexit__(self, *exc_info):
508 pass
509
510 async def sleep(delay, result=None):
511 assert delay == 0
512 await async_yield(None)
513 return result
514
515 modes = ('single', 'exec')
516 optimizations = (-1, 0, 1, 2)
517 code_samples = [
518 '''a = await sleep(0, result=1)''',
519 '''async for i in arange(1):
520 a = 1''',
521 '''async with Lock() as l:
522 a = 1''',
523 '''a = [x async for x in arange(2)][1]''',
524 '''a = 1 in {x async for x in arange(2)}''',
525 '''a = {x:1 async for x in arange(1)}[0]''',
526 '''a = [x async for x in arange(2) async for x in arange(2)][1]''',
527 '''a = [x async for x in (x async for x in arange(5))][1]''',
528 '''a, = [1 for x in {x async for x in arange(1)}]''',
529 '''a = [await sleep(0, x) async for x in arange(2)][1]''',
530 # gh-121637: Make sure we correctly handle the case where the
531 # async code is optimized away
532 '''assert not await sleep(0); a = 1''',
533 '''assert [x async for x in arange(1)]; a = 1''',
534 '''assert {x async for x in arange(1)}; a = 1''',
535 '''assert {x: x async for x in arange(1)}; a = 1''',
536 '''
537 if (a := 1) and __debug__:
538 async with Lock() as l:
539 pass
540 ''',
541 '''
542 if (a := 1) and __debug__:
543 async for x in arange(2):
544 pass
545 ''',
546 ]
547 for mode, code_sample, optimize in product(modes, code_samples, optimizations):
548 with self.subTest(mode=mode, code_sample=code_sample, optimize=optimize):
549 source = dedent(code_sample)
550 with self.assertRaises(
551 SyntaxError, msg=f"source={source} mode={mode}"):
552 compile(source, '?', mode, optimize=optimize)
553
554 co = compile(source,
555 '?',
556 mode,
557 flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT,
558 optimize=optimize)
559
560 self.assertEqual(co.co_flags & CO_COROUTINE, CO_COROUTINE,
561 msg=f"source={source} mode={mode}")
562
563 # test we can create and advance a function type
564 globals_ = {'Lock': Lock, 'a': 0, 'arange': arange, 'sleep': sleep}
565 run_yielding_async_fn(FunctionType(co, globals_))
566 self.assertEqual(globals_['a'], 1)
567
568 # test we can await-eval,
569 globals_ = {'Lock': Lock, 'a': 0, 'arange': arange, 'sleep': sleep}
570 run_yielding_async_fn(lambda: eval(co, globals_))
571 self.assertEqual(globals_['a'], 1)
572
573 def test_compile_top_level_await_invalid_cases(self):
574 # helper function just to check we can run top=level async-for
575 async def arange(n):
576 for i in range(n):
577 yield i
578
579 class Lock:
580 async def __aenter__(self):
581 return self
582
583 async def __aexit__(self, *exc_info):
584 pass
585
586 modes = ('single', 'exec')
587 code_samples = [
588 '''def f(): await arange(10)\n''',
589 '''def f(): [x async for x in arange(10)]\n''',
590 '''def f(): [await x async for x in arange(10)]\n''',
591 '''def f():
592 async for i in arange(1):
593 a = 1
594 ''',
595 '''def f():
596 async with Lock() as l:
597 a = 1
598 '''
599 ]
600 for mode, code_sample in product(modes, code_samples):
601 source = dedent(code_sample)
602 with self.assertRaises(
603 SyntaxError, msg=f"source={source} mode={mode}"):
604 compile(source, '?', mode)
605
606 with self.assertRaises(
607 SyntaxError, msg=f"source={source} mode={mode}"):
608 co = compile(source,
609 '?',
610 mode,
611 flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
612
613 def test_compile_async_generator(self):
614 """
615 With the PyCF_ALLOW_TOP_LEVEL_AWAIT flag added in 3.8, we want to
616 make sure AsyncGenerators are still properly not marked with the
617 CO_COROUTINE flag.
618 """
619 code = dedent("""async def ticker():
620 for i in range(10):
621 yield i
622 await sleep(0)""")
623
624 co = compile(code, '?', 'exec', flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT)
625 glob = {}
626 exec(co, glob)
627 self.assertEqual(type(glob['ticker']()), AsyncGeneratorType)
628
629 def test_compile_ast(self):
630 args = ("a*__debug__", "f.py", "exec")
631 raw = compile(*args, flags = ast.PyCF_ONLY_AST).body[0]
632 opt1 = compile(*args, flags = ast.PyCF_OPTIMIZED_AST).body[0]
633 opt2 = compile(ast.parse(args[0]), *args[1:], flags = ast.PyCF_OPTIMIZED_AST).body[0]
634
635 for tree in (raw, opt1, opt2):
636 self.assertIsInstance(tree.value, ast.BinOp)
637 self.assertIsInstance(tree.value.op, ast.Mult)
638 self.assertIsInstance(tree.value.left, ast.Name)
639 self.assertEqual(tree.value.left.id, 'a')
640
641 raw_right = raw.value.right
642 self.assertIsInstance(raw_right, ast.Name)
643 self.assertEqual(raw_right.id, "__debug__")
644
645 for opt in [opt1, opt2]:
646 opt_right = opt.value.right
647 self.assertIsInstance(opt_right, ast.Constant)
648 self.assertEqual(opt_right.value, __debug__)
649
650 def test_delattr(self):
651 sys.spam = 1
652 delattr(sys, 'spam')
653 self.assertRaises(TypeError, delattr)
654 self.assertRaises(TypeError, delattr, sys)
655 msg = r"^attribute name must be string, not 'int'$"
656 self.assertRaisesRegex(TypeError, msg, delattr, sys, 1)
657
658 def test_dir(self):
659 # dir(wrong number of arguments)
660 self.assertRaises(TypeError, dir, 42, 42)
661
662 # dir() - local scope
663 local_var = 1
664 self.assertIn('local_var', dir())
665
666 # dir(module)
667 self.assertIn('exit', dir(sys))
668
669 # dir(module_with_invalid__dict__)
670 class Foo(types.ModuleType):
671 __dict__ = 8
672 f = Foo("foo")
673 self.assertRaises(TypeError, dir, f)
674
675 # dir(type)
676 self.assertIn("strip", dir(str))
677 self.assertNotIn("__mro__", dir(str))
678
679 # dir(obj)
680 class Foo(object):
681 def __init__(self):
682 self.x = 7
683 self.y = 8
684 self.z = 9
685 f = Foo()
686 self.assertIn("y", dir(f))
687
688 # dir(obj_no__dict__)
689 class Foo(object):
690 __slots__ = []
691 f = Foo()
692 self.assertIn("__repr__", dir(f))
693
694 # dir(obj_no__class__with__dict__)
695 # (an ugly trick to cause getattr(f, "__class__") to fail)
696 class Foo(object):
697 __slots__ = ["__class__", "__dict__"]
698 def __init__(self):
699 self.bar = "wow"
700 f = Foo()
701 self.assertNotIn("__repr__", dir(f))
702 self.assertIn("bar", dir(f))
703
704 # dir(obj_using __dir__)
705 class Foo(object):
706 def __dir__(self):
707 return ["kan", "ga", "roo"]
708 f = Foo()
709 self.assertTrue(dir(f) == ["ga", "kan", "roo"])
710
711 # dir(obj__dir__tuple)
712 class Foo(object):
713 def __dir__(self):
714 return ("b", "c", "a")
715 res = dir(Foo())
716 self.assertIsInstance(res, list)
717 self.assertTrue(res == ["a", "b", "c"])
718
719 # dir(obj__dir__iterable)
720 class Foo(object):
721 def __dir__(self):
722 return {"b", "c", "a"}
723 res = dir(Foo())
724 self.assertIsInstance(res, list)
725 self.assertEqual(sorted(res), ["a", "b", "c"])
726
727 # dir(obj__dir__not_sequence)
728 class Foo(object):
729 def __dir__(self):
730 return 7
731 f = Foo()
732 self.assertRaises(TypeError, dir, f)
733
734 # dir(traceback)
735 try:
736 raise IndexError
737 except IndexError as e:
738 self.assertEqual(len(dir(e.__traceback__)), 4)
739
740 # test that object has a __dir__()
741 self.assertEqual(sorted([].__dir__()), dir([]))
742
743 def test___ne__(self):
744 self.assertFalse(None.__ne__(None))
745 self.assertIs(None.__ne__(0), NotImplemented)
746 self.assertIs(None.__ne__("abc"), NotImplemented)
747
748 def test_divmod(self):
749 self.assertEqual(divmod(12, 7), (1, 5))
750 self.assertEqual(divmod(-12, 7), (-2, 2))
751 self.assertEqual(divmod(12, -7), (-2, -2))
752 self.assertEqual(divmod(-12, -7), (1, -5))
753
754 self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
755
756 for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),
757 (-3.25, 1.0, (-4.0, 0.75)),
758 (3.25, -1.0, (-4.0, -0.75)),
759 (-3.25, -1.0, (3.0, -0.25))]:
760 result = divmod(num, denom)
761 self.assertAlmostEqual(result[0], exp_result[0])
762 self.assertAlmostEqual(result[1], exp_result[1])
763
764 self.assertRaises(TypeError, divmod)
765 self.assertRaisesRegex(
766 ZeroDivisionError,
767 "division by zero",
768 divmod, 1, 0,
769 )
770 self.assertRaisesRegex(
771 ZeroDivisionError,
772 "division by zero",
773 divmod, 0.0, 0,
774 )
775
776 def test_eval(self):
777 self.assertEqual(eval('1+1'), 2)
778 self.assertEqual(eval(' 1+1\n'), 2)
779 globals = {'a': 1, 'b': 2}
780 locals = {'b': 200, 'c': 300}
781 self.assertEqual(eval('a', globals) , 1)
782 self.assertEqual(eval('a', globals, locals), 1)
783 self.assertEqual(eval('b', globals, locals), 200)
784 self.assertEqual(eval('c', globals, locals), 300)
785 globals = {'a': 1, 'b': 2}
786 locals = {'b': 200, 'c': 300}
787 bom = b'\xef\xbb\xbf'
788 self.assertEqual(eval(bom + b'a', globals, locals), 1)
789 self.assertEqual(eval('"\xe5"', globals), "\xe5")
790 self.assertRaises(TypeError, eval)
791 self.assertRaises(TypeError, eval, ())
792 self.assertRaises(SyntaxError, eval, bom[:2] + b'a')
793
794 class X:
795 def __getitem__(self, key):
796 raise ValueError
797 self.assertRaises(ValueError, eval, "foo", {}, X())
798
799 def test_eval_kwargs(self):
800 data = {"A_GLOBAL_VALUE": 456}
801 self.assertEqual(eval("globals()['A_GLOBAL_VALUE']", globals=data), 456)
802 self.assertEqual(eval("globals()['A_GLOBAL_VALUE']", locals=data), 123)
803
804 def test_general_eval(self):
805 # Tests that general mappings can be used for the locals argument
806
807 class M:
808 "Test mapping interface versus possible calls from eval()."
809 def __getitem__(self, key):
810 if key == 'a':
811 return 12
812 raise KeyError
813 def keys(self):
814 return list('xyz')
815
816 m = M()
817 g = globals()
818 self.assertEqual(eval('a', g, m), 12)
819 self.assertRaises(NameError, eval, 'b', g, m)
820 self.assertEqual(eval('dir()', g, m), list('xyz'))
821 self.assertEqual(eval('globals()', g, m), g)
822 self.assertEqual(eval('locals()', g, m), m)
823 self.assertRaises(TypeError, eval, 'a', m)
824 class A:
825 "Non-mapping"
826 pass
827 m = A()
828 self.assertRaises(TypeError, eval, 'a', g, m)
829
830 # Verify that dict subclasses work as well
831 class D(dict):
832 def __getitem__(self, key):
833 if key == 'a':
834 return 12
835 return dict.__getitem__(self, key)
836 def keys(self):
837 return list('xyz')
838
839 d = D()
840 self.assertEqual(eval('a', g, d), 12)
841 self.assertRaises(NameError, eval, 'b', g, d)
842 self.assertEqual(eval('dir()', g, d), list('xyz'))
843 self.assertEqual(eval('globals()', g, d), g)
844 self.assertEqual(eval('locals()', g, d), d)
845
846 # Verify locals stores (used by list comps)
847 eval('[locals() for i in (2,3)]', g, d)
848 eval('[locals() for i in (2,3)]', g, collections.UserDict())
849
850 class SpreadSheet:
851 "Sample application showing nested, calculated lookups."
852 _cells = {}
853 def __setitem__(self, key, formula):
854 self._cells[key] = formula
855 def __getitem__(self, key):
856 return eval(self._cells[key], globals(), self)
857
858 ss = SpreadSheet()
859 ss['a1'] = '5'
860 ss['a2'] = 'a1*6'
861 ss['a3'] = 'a2*7'
862 self.assertEqual(ss['a3'], 210)
863
864 # Verify that dir() catches a non-list returned by eval
865 # SF bug #1004669
866 class C:
867 def __getitem__(self, item):
868 raise KeyError(item)
869 def keys(self):
870 return 1 # used to be 'a' but that's no longer an error
871 self.assertRaises(TypeError, eval, 'dir()', globals(), C())
872
873 def test_exec(self):
874 g = {}
875 exec('z = 1', g)
876 if '__builtins__' in g:
877 del g['__builtins__']
878 self.assertEqual(g, {'z': 1})
879
880 exec('z = 1+1', g)
881 if '__builtins__' in g:
882 del g['__builtins__']
883 self.assertEqual(g, {'z': 2})
884 g = {}
885 l = {}
886
887 with check_warnings():
888 warnings.filterwarnings("ignore", "global statement",
889 module="<string>")
890 exec('global a; a = 1; b = 2', g, l)
891 if '__builtins__' in g:
892 del g['__builtins__']
893 if '__builtins__' in l:
894 del l['__builtins__']
895 self.assertEqual((g, l), ({'a': 1}, {'b': 2}))
896
897 def test_exec_kwargs(self):
898 g = {}
899 exec('global z\nz = 1', globals=g)
900 if '__builtins__' in g:
901 del g['__builtins__']
902 self.assertEqual(g, {'z': 1})
903
904 # if we only set locals, the global assignment will not
905 # reach this locals dictionary
906 g = {}
907 exec('global z\nz = 1', locals=g)
908 self.assertEqual(g, {})
909
910 def test_exec_globals(self):
911 code = compile("print('Hello World!')", "", "exec")
912 # no builtin function
913 self.assertRaisesRegex(NameError, "name 'print' is not defined",
914 exec, code, {'__builtins__': {}})
915 # __builtins__ must be a mapping type
916 self.assertRaises(TypeError,
917 exec, code, {'__builtins__': 123})
918
919 def test_exec_globals_frozen(self):
920 class frozendict_error(Exception):
921 pass
922
923 class frozendict(dict):
924 def __setitem__(self, key, value):
925 raise frozendict_error("frozendict is readonly")
926
927 # read-only builtins
928 if isinstance(__builtins__, types.ModuleType):
929 frozen_builtins = frozendict(__builtins__.__dict__)
930 else:
931 frozen_builtins = frozendict(__builtins__)
932 code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec")
933 self.assertRaises(frozendict_error,
934 exec, code, {'__builtins__': frozen_builtins})
935
936 # no __build_class__ function
937 code = compile("class A: pass", "", "exec")
938 self.assertRaisesRegex(NameError, "__build_class__ not found",
939 exec, code, {'__builtins__': {}})
940 # __build_class__ in a custom __builtins__
941 exec(code, {'__builtins__': frozen_builtins})
942 self.assertRaisesRegex(NameError, "__build_class__ not found",
943 exec, code, {'__builtins__': frozendict()})
944
945 # read-only globals
946 namespace = frozendict({})
947 code = compile("x=1", "test", "exec")
948 self.assertRaises(frozendict_error,
949 exec, code, namespace)
950
951 def test_exec_globals_error_on_get(self):
952 # custom `globals` or `builtins` can raise errors on item access
953 class setonlyerror(Exception):
954 pass
955
956 class setonlydict(dict):
957 def __getitem__(self, key):
958 raise setonlyerror
959
960 # globals' `__getitem__` raises
961 code = compile("globalname", "test", "exec")
962 self.assertRaises(setonlyerror,
963 exec, code, setonlydict({'globalname': 1}))
964
965 # builtins' `__getitem__` raises
966 code = compile("superglobal", "test", "exec")
967 self.assertRaises(setonlyerror, exec, code,
968 {'__builtins__': setonlydict({'superglobal': 1})})
969
970 def test_exec_globals_dict_subclass(self):
971 class customdict(dict): # this one should not do anything fancy
972 pass
973
974 code = compile("superglobal", "test", "exec")
975 # works correctly
976 exec(code, {'__builtins__': customdict({'superglobal': 1})})
977 # custom builtins dict subclass is missing key
978 self.assertRaisesRegex(NameError, "name 'superglobal' is not defined",
979 exec, code, {'__builtins__': customdict()})
980
981 def test_eval_builtins_mapping(self):
982 code = compile("superglobal", "test", "eval")
983 # works correctly
984 ns = {'__builtins__': types.MappingProxyType({'superglobal': 1})}
985 self.assertEqual(eval(code, ns), 1)
986 # custom builtins mapping is missing key
987 ns = {'__builtins__': types.MappingProxyType({})}
988 self.assertRaisesRegex(NameError, "name 'superglobal' is not defined",
989 eval, code, ns)
990
991 def test_exec_builtins_mapping_import(self):
992 code = compile("import foo.bar", "test", "exec")
993 ns = {'__builtins__': types.MappingProxyType({})}
994 self.assertRaisesRegex(ImportError, "__import__ not found", exec, code, ns)
995 ns = {'__builtins__': types.MappingProxyType({'__import__': lambda *args: args})}
996 exec(code, ns)
997 self.assertEqual(ns['foo'], ('foo.bar', ns, ns, None, 0))
998
999 def test_eval_builtins_mapping_reduce(self):
1000 # list_iterator.__reduce__() calls _PyEval_GetBuiltin("iter")
1001 code = compile("x.__reduce__()", "test", "eval")
1002 ns = {'__builtins__': types.MappingProxyType({}), 'x': iter([1, 2])}
1003 self.assertRaisesRegex(AttributeError, "iter", eval, code, ns)
1004 ns = {'__builtins__': types.MappingProxyType({'iter': iter}), 'x': iter([1, 2])}
1005 self.assertEqual(eval(code, ns), (iter, ([1, 2],), 0))
1006
1007 def test_exec_redirected(self):
1008 savestdout = sys.stdout
1009 sys.stdout = None # Whatever that cannot flush()
1010 try:
1011 # Used to raise SystemError('error return without exception set')
1012 exec('a')
1013 except NameError:
1014 pass
1015 finally:
1016 sys.stdout = savestdout
1017
1018 def test_exec_closure(self):
1019 def function_without_closures():
1020 return 3 * 5
1021
1022 result = 0
1023 def make_closure_functions():
1024 a = 2
1025 b = 3
1026 c = 5
1027 def three_freevars():
1028 nonlocal result
1029 nonlocal a
1030 nonlocal b
1031 result = a*b
1032 def four_freevars():
1033 nonlocal result
1034 nonlocal a
1035 nonlocal b
1036 nonlocal c
1037 result = a*b*c
1038 return three_freevars, four_freevars
1039 three_freevars, four_freevars = make_closure_functions()
1040
1041 # "smoke" test
1042 result = 0
1043 exec(three_freevars.__code__,
1044 three_freevars.__globals__,
1045 closure=three_freevars.__closure__)
1046 self.assertEqual(result, 6)
1047
1048 # should also work with a manually created closure
1049 result = 0
1050 my_closure = (CellType(35), CellType(72), three_freevars.__closure__[2])
1051 exec(three_freevars.__code__,
1052 three_freevars.__globals__,
1053 closure=my_closure)
1054 self.assertEqual(result, 2520)
1055
1056 # should fail: closure isn't allowed
1057 # for functions without free vars
1058 self.assertRaises(TypeError,
1059 exec,
1060 function_without_closures.__code__,
1061 function_without_closures.__globals__,
1062 closure=my_closure)
1063
1064 # should fail: closure required but wasn't specified
1065 self.assertRaises(TypeError,
1066 exec,
1067 three_freevars.__code__,
1068 three_freevars.__globals__,
1069 closure=None)
1070
1071 # should fail: closure of wrong length
1072 self.assertRaises(TypeError,
1073 exec,
1074 three_freevars.__code__,
1075 three_freevars.__globals__,
1076 closure=four_freevars.__closure__)
1077
1078 # should fail: closure using a list instead of a tuple
1079 my_closure = list(my_closure)
1080 self.assertRaises(TypeError,
1081 exec,
1082 three_freevars.__code__,
1083 three_freevars.__globals__,
1084 closure=my_closure)
1085 my_closure = tuple(my_closure)
1086
1087 # should fail: anything passed to closure= isn't allowed
1088 # when the source is a string
1089 self.assertRaises(TypeError,
1090 exec,
1091 "pass",
1092 closure=int)
1093
1094 # should fail: correct closure= argument isn't allowed
1095 # when the source is a string
1096 self.assertRaises(TypeError,
1097 exec,
1098 "pass",
1099 closure=my_closure)
1100
1101 # should fail: closure tuple with one non-cell-var
1102 my_closure = list(my_closure)
1103 my_closure[0] = int
1104 my_closure = tuple(my_closure)
1105 self.assertRaises(TypeError,
1106 exec,
1107 three_freevars.__code__,
1108 three_freevars.__globals__,
1109 closure=my_closure)
1110
1111
1112 def test_filter(self):
1113 self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
1114 self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
1115 self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
1116 self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
1117 self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
1118 def identity(item):
1119 return 1
1120 filter(identity, Squares(5))
1121 self.assertRaises(TypeError, filter)
1122 class BadSeq(object):
1123 def __getitem__(self, index):
1124 if index<4:
1125 return 42
1126 raise ValueError
1127 self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
1128 def badfunc():
1129 pass
1130 self.assertRaises(TypeError, list, filter(badfunc, range(5)))
1131
1132 # test bltinmodule.c::filtertuple()
1133 self.assertEqual(list(filter(None, (1, 2))), [1, 2])
1134 self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
1135 self.assertRaises(TypeError, list, filter(42, (1, 2)))
1136
1137 def test_filter_pickle(self):
1138 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1139 f1 = filter(filter_char, "abcdeabcde")
1140 f2 = filter(filter_char, "abcdeabcde")
1141 self.check_iter_pickle(f1, list(f2), proto)
1142
1143 @support.skip_wasi_stack_overflow()
1144 @support.skip_emscripten_stack_overflow()
1145 @support.requires_resource('cpu')
1146 def test_filter_dealloc(self):
1147 # Tests recursive deallocation of nested filter objects using the
1148 # thrashcan mechanism. See gh-102356 for more details.
1149 max_iters = 1000000
1150 i = filter(bool, range(max_iters))
1151 for _ in range(max_iters):
1152 i = filter(bool, i)
1153 del i
1154 gc.collect()
1155
1156 def test_getattr(self):
1157 self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
1158 self.assertRaises(TypeError, getattr)
1159 self.assertRaises(TypeError, getattr, sys)
1160 msg = r"^attribute name must be string, not 'int'$"
1161 self.assertRaisesRegex(TypeError, msg, getattr, sys, 1)
1162 self.assertRaisesRegex(TypeError, msg, getattr, sys, 1, 'spam')
1163 self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
1164 # unicode surrogates are not encodable to the default encoding (utf8)
1165 self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
1166
1167 def test_hasattr(self):
1168 self.assertTrue(hasattr(sys, 'stdout'))
1169 self.assertRaises(TypeError, hasattr)
1170 self.assertRaises(TypeError, hasattr, sys)
1171 msg = r"^attribute name must be string, not 'int'$"
1172 self.assertRaisesRegex(TypeError, msg, hasattr, sys, 1)
1173 self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
1174
1175 # Check that hasattr propagates all exceptions outside of
1176 # AttributeError.
1177 class A:
1178 def __getattr__(self, what):
1179 raise SystemExit
1180 self.assertRaises(SystemExit, hasattr, A(), "b")
1181 class B:
1182 def __getattr__(self, what):
1183 raise ValueError
1184 self.assertRaises(ValueError, hasattr, B(), "b")
1185
1186 def test_hash(self):
1187 hash(None)
1188 self.assertEqual(hash(1), hash(1))
1189 self.assertEqual(hash(1), hash(1.0))
1190 hash('spam')
1191 self.assertEqual(hash('spam'), hash(b'spam'))
1192 hash((0,1,2,3))
1193 def f(): pass
1194 hash(f)
1195 self.assertRaises(TypeError, hash, [])
1196 self.assertRaises(TypeError, hash, {})
1197 # Bug 1536021: Allow hash to return long objects
1198 class X:
1199 def __hash__(self):
1200 return 2**100
1201 self.assertEqual(type(hash(X())), int)
1202 class Z(int):
1203 def __hash__(self):
1204 return self
1205 self.assertEqual(hash(Z(42)), hash(42))
1206
1207 def test_invalid_hash_typeerror(self):
1208 # GH-140406: The returned object from __hash__() would leak if it
1209 # wasn't an integer.
1210 class A:
1211 def __hash__(self):
1212 return 1.0
1213
1214 with self.assertRaises(TypeError):
1215 hash(A())
1216
1217 def test_hex(self):
1218 self.assertEqual(hex(16), '0x10')
1219 self.assertEqual(hex(-16), '-0x10')
1220 self.assertRaises(TypeError, hex, {})
1221
1222 def test_id(self):
1223 id(None)
1224 id(1)
1225 id(1.0)
1226 id('spam')
1227 id((0,1,2,3))
1228 id([0,1,2,3])
1229 id({'spam': 1, 'eggs': 2, 'ham': 3})
1230
1231 # Test input() later, alphabetized as if it were raw_input
1232
1233 def test_iter(self):
1234 self.assertRaises(TypeError, iter)
1235 self.assertRaises(TypeError, iter, 42, 42)
1236 lists = [("1", "2"), ["1", "2"], "12"]
1237 for l in lists:
1238 i = iter(l)
1239 self.assertEqual(next(i), '1')
1240 self.assertEqual(next(i), '2')
1241 self.assertRaises(StopIteration, next, i)
1242
1243 def test_isinstance(self):
1244 class C:
1245 pass
1246 class D(C):
1247 pass
1248 class E:
1249 pass
1250 c = C()
1251 d = D()
1252 e = E()
1253 self.assertTrue(isinstance(c, C))
1254 self.assertTrue(isinstance(d, C))
1255 self.assertTrue(not isinstance(e, C))
1256 self.assertTrue(not isinstance(c, D))
1257 self.assertTrue(not isinstance('foo', E))
1258 self.assertRaises(TypeError, isinstance, E, 'foo')
1259 self.assertRaises(TypeError, isinstance)
1260
1261 def test_issubclass(self):
1262 class C:
1263 pass
1264 class D(C):
1265 pass
1266 class E:
1267 pass
1268 c = C()
1269 d = D()
1270 e = E()
1271 self.assertTrue(issubclass(D, C))
1272 self.assertTrue(issubclass(C, C))
1273 self.assertTrue(not issubclass(C, D))
1274 self.assertRaises(TypeError, issubclass, 'foo', E)
1275 self.assertRaises(TypeError, issubclass, E, 'foo')
1276 self.assertRaises(TypeError, issubclass)
1277
1278 def test_len(self):
1279 self.assertEqual(len('123'), 3)
1280 self.assertEqual(len(()), 0)
1281 self.assertEqual(len((1, 2, 3, 4)), 4)
1282 self.assertEqual(len([1, 2, 3, 4]), 4)
1283 self.assertEqual(len({}), 0)
1284 self.assertEqual(len({'a':1, 'b': 2}), 2)
1285 class BadSeq:
1286 def __len__(self):
1287 raise ValueError
1288 self.assertRaises(ValueError, len, BadSeq())
1289 class InvalidLen:
1290 def __len__(self):
1291 return None
1292 self.assertRaises(TypeError, len, InvalidLen())
1293 class FloatLen:
1294 def __len__(self):
1295 return 4.5
1296 self.assertRaises(TypeError, len, FloatLen())
1297 class NegativeLen:
1298 def __len__(self):
1299 return -10
1300 self.assertRaises(ValueError, len, NegativeLen())
1301 class HugeLen:
1302 def __len__(self):
1303 return sys.maxsize + 1
1304 self.assertRaises(OverflowError, len, HugeLen())
1305 class HugeNegativeLen:
1306 def __len__(self):
1307 return -sys.maxsize-10
1308 self.assertRaises(ValueError, len, HugeNegativeLen())
1309 class NoLenMethod(object): pass
1310 self.assertRaises(TypeError, len, NoLenMethod())
1311
1312 def test_map(self):
1313 self.assertEqual(
1314 list(map(lambda x: x*x, range(1,4))),
1315 [1, 4, 9]
1316 )
1317 try:
1318 from math import sqrt
1319 except ImportError:
1320 def sqrt(x):
1321 return pow(x, 0.5)
1322 self.assertEqual(
1323 list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
1324 [[4.0, 2.0], [9.0, 3.0]]
1325 )
1326 self.assertEqual(
1327 list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
1328 [10, 4, 6]
1329 )
1330
1331 def plus(*v):
1332 accu = 0
1333 for i in v: accu = accu + i
1334 return accu
1335 self.assertEqual(
1336 list(map(plus, [1, 3, 7])),
1337 [1, 3, 7]
1338 )
1339 self.assertEqual(
1340 list(map(plus, [1, 3, 7], [4, 9, 2])),
1341 [1+4, 3+9, 7+2]
1342 )
1343 self.assertEqual(
1344 list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
1345 [1+4+1, 3+9+1, 7+2+0]
1346 )
1347 self.assertEqual(
1348 list(map(int, Squares(10))),
1349 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
1350 )
1351 def Max(a, b):
1352 if a is None:
1353 return b
1354 if b is None:
1355 return a
1356 return max(a, b)
1357 self.assertEqual(
1358 list(map(Max, Squares(3), Squares(2))),
1359 [0, 1]
1360 )
1361 self.assertRaises(TypeError, map)
1362 self.assertRaises(TypeError, map, lambda x: x, 42)
1363 class BadSeq:
1364 def __iter__(self):
1365 raise ValueError
1366 yield None
1367 self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
1368 def badfunc(x):
1369 raise RuntimeError
1370 self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
1371
1372 def test_map_pickle(self):
1373 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1374 m1 = map(map_char, "Is this the real life?")
1375 m2 = map(map_char, "Is this the real life?")
1376 self.check_iter_pickle(m1, list(m2), proto)
1377
1378 # strict map tests based on strict zip tests
1379
1380 def test_map_pickle_strict(self):
1381 a = (1, 2, 3)
1382 b = (4, 5, 6)
1383 t = [(1, 4), (2, 5), (3, 6)]
1384 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1385 m1 = map(pack, a, b, strict=True)
1386 self.check_iter_pickle(m1, t, proto)
1387
1388 def test_map_pickle_strict_fail(self):
1389 a = (1, 2, 3)
1390 b = (4, 5, 6, 7)
1391 t = [(1, 4), (2, 5), (3, 6)]
1392 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1393 m1 = map(pack, a, b, strict=True)
1394 m2 = pickle.loads(pickle.dumps(m1, proto))
1395 self.assertEqual(self.iter_error(m1, ValueError), t)
1396 self.assertEqual(self.iter_error(m2, ValueError), t)
1397
1398 def test_map_strict(self):
1399 self.assertEqual(tuple(map(pack, (1, 2, 3), 'abc', strict=True)),
1400 ((1, 'a'), (2, 'b'), (3, 'c')))
1401 self.assertRaises(ValueError, tuple,
1402 map(pack, (1, 2, 3, 4), 'abc', strict=True))
1403 self.assertRaises(ValueError, tuple,
1404 map(pack, (1, 2), 'abc', strict=True))
1405 self.assertRaises(ValueError, tuple,
1406 map(pack, (1, 2), (1, 2), 'abc', strict=True))
1407
1408 # gh-140517: Testing refleaks with mortal objects.
1409 t1 = (None, object())
1410 t2 = (object(), object())
1411 t3 = (object(),)
1412
1413 self.assertRaises(ValueError, tuple,
1414 map(pack, t1, 'a', strict=True))
1415 self.assertRaises(ValueError, tuple,
1416 map(pack, t1, t2, 'a', strict=True))
1417 self.assertRaises(ValueError, tuple,
1418 map(pack, t1, t2, t3, strict=True))
1419 self.assertRaises(ValueError, tuple,
1420 map(pack, 'a', t1, strict=True))
1421 self.assertRaises(ValueError, tuple,
1422 map(pack, 'a', t2, t3, strict=True))
1423
1424 def test_map_strict_iterators(self):
1425 x = iter(range(5))
1426 y = [0]
1427 z = iter(range(5))
1428 self.assertRaises(ValueError, list,
1429 (map(pack, x, y, z, strict=True)))
1430 self.assertEqual(next(x), 2)
1431 self.assertEqual(next(z), 1)
1432
1433 def test_map_strict_error_handling(self):
1434
1435 class Error(Exception):
1436 pass
1437
1438 class Iter:
1439 def __init__(self, size):
1440 self.size = size
1441 def __iter__(self):
1442 return self
1443 def __next__(self):
1444 self.size -= 1
1445 if self.size < 0:
1446 raise Error
1447 return self.size
1448
1449 l1 = self.iter_error(map(pack, "AB", Iter(1), strict=True), Error)
1450 self.assertEqual(l1, [("A", 0)])
1451 l2 = self.iter_error(map(pack, "AB", Iter(2), "A", strict=True), ValueError)
1452 self.assertEqual(l2, [("A", 1, "A")])
1453 l3 = self.iter_error(map(pack, "AB", Iter(2), "ABC", strict=True), Error)
1454 self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
1455 l4 = self.iter_error(map(pack, "AB", Iter(3), strict=True), ValueError)
1456 self.assertEqual(l4, [("A", 2), ("B", 1)])
1457 l5 = self.iter_error(map(pack, Iter(1), "AB", strict=True), Error)
1458 self.assertEqual(l5, [(0, "A")])
1459 l6 = self.iter_error(map(pack, Iter(2), "A", strict=True), ValueError)
1460 self.assertEqual(l6, [(1, "A")])
1461 l7 = self.iter_error(map(pack, Iter(2), "ABC", strict=True), Error)
1462 self.assertEqual(l7, [(1, "A"), (0, "B")])
1463 l8 = self.iter_error(map(pack, Iter(3), "AB", strict=True), ValueError)
1464 self.assertEqual(l8, [(2, "A"), (1, "B")])
1465
1466 def test_map_strict_error_handling_stopiteration(self):
1467
1468 class Iter:
1469 def __init__(self, size):
1470 self.size = size
1471 def __iter__(self):
1472 return self
1473 def __next__(self):
1474 self.size -= 1
1475 if self.size < 0:
1476 raise StopIteration
1477 return self.size
1478
1479 l1 = self.iter_error(map(pack, "AB", Iter(1), strict=True), ValueError)
1480 self.assertEqual(l1, [("A", 0)])
1481 l2 = self.iter_error(map(pack, "AB", Iter(2), "A", strict=True), ValueError)
1482 self.assertEqual(l2, [("A", 1, "A")])
1483 l3 = self.iter_error(map(pack, "AB", Iter(2), "ABC", strict=True), ValueError)
1484 self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
1485 l4 = self.iter_error(map(pack, "AB", Iter(3), strict=True), ValueError)
1486 self.assertEqual(l4, [("A", 2), ("B", 1)])
1487 l5 = self.iter_error(map(pack, Iter(1), "AB", strict=True), ValueError)
1488 self.assertEqual(l5, [(0, "A")])
1489 l6 = self.iter_error(map(pack, Iter(2), "A", strict=True), ValueError)
1490 self.assertEqual(l6, [(1, "A")])
1491 l7 = self.iter_error(map(pack, Iter(2), "ABC", strict=True), ValueError)
1492 self.assertEqual(l7, [(1, "A"), (0, "B")])
1493 l8 = self.iter_error(map(pack, Iter(3), "AB", strict=True), ValueError)
1494 self.assertEqual(l8, [(2, "A"), (1, "B")])
1495
1496 def test_max(self):
1497 self.assertEqual(max('123123'), '3')
1498 self.assertEqual(max(1, 2, 3), 3)
1499 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
1500 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
1501
1502 self.assertEqual(max(1, 2, 3.0), 3.0)
1503 self.assertEqual(max(1, 2.0, 3), 3)
1504 self.assertEqual(max(1.0, 2, 3), 3)
1505
1506 with self.assertRaisesRegex(
1507 TypeError,
1508 'max expected at least 1 argument, got 0'
1509 ):
1510 max()
1511
1512 self.assertRaises(TypeError, max, 42)
1513 with self.assertRaisesRegex(
1514 ValueError,
1515 r'max\(\) iterable argument is empty'
1516 ):
1517 max(())
1518 class BadSeq:
1519 def __getitem__(self, index):
1520 raise ValueError
1521 self.assertRaises(ValueError, max, BadSeq())
1522
1523 for stmt in (
1524 "max(key=int)", # no args
1525 "max(default=None)",
1526 "max(1, 2, default=None)", # require container for default
1527 "max(default=None, key=int)",
1528 "max(1, key=int)", # single arg not iterable
1529 "max(1, 2, keystone=int)", # wrong keyword
1530 "max(1, 2, key=int, abc=int)", # two many keywords
1531 "max(1, 2, key=1)", # keyfunc is not callable
1532 ):
1533 try:
1534 exec(stmt, globals())
1535 except TypeError:
1536 pass
1537 else:
1538 self.fail(stmt)
1539
1540 self.assertEqual(max((1,), key=neg), 1) # one elem iterable
1541 self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
1542 self.assertEqual(max(1, 2, key=neg), 1) # two elems
1543
1544 self.assertEqual(max((), default=None), None) # zero elem iterable
1545 self.assertEqual(max((1,), default=None), 1) # one elem iterable
1546 self.assertEqual(max((1,2), default=None), 2) # two elem iterable
1547
1548 self.assertEqual(max((), default=1, key=neg), 1)
1549 self.assertEqual(max((1, 2), default=3, key=neg), 1)
1550
1551 self.assertEqual(max((1, 2), key=None), 2)
1552
1553 data = [random.randrange(200) for i in range(100)]
1554 keys = dict((elem, random.randrange(50)) for elem in data)
1555 f = keys.__getitem__
1556 self.assertEqual(max(data, key=f),
1557 sorted(reversed(data), key=f)[-1])
1558
1559 def test_min(self):
1560 self.assertEqual(min('123123'), '1')
1561 self.assertEqual(min(1, 2, 3), 1)
1562 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
1563 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
1564
1565 self.assertEqual(min(1, 2, 3.0), 1)
1566 self.assertEqual(min(1, 2.0, 3), 1)
1567 self.assertEqual(min(1.0, 2, 3), 1.0)
1568
1569 with self.assertRaisesRegex(
1570 TypeError,
1571 'min expected at least 1 argument, got 0'
1572 ):
1573 min()
1574
1575 self.assertRaises(TypeError, min, 42)
1576 with self.assertRaisesRegex(
1577 ValueError,
1578 r'min\(\) iterable argument is empty'
1579 ):
1580 min(())
1581 class BadSeq:
1582 def __getitem__(self, index):
1583 raise ValueError
1584 self.assertRaises(ValueError, min, BadSeq())
1585
1586 for stmt in (
1587 "min(key=int)", # no args
1588 "min(default=None)",
1589 "min(1, 2, default=None)", # require container for default
1590 "min(default=None, key=int)",
1591 "min(1, key=int)", # single arg not iterable
1592 "min(1, 2, keystone=int)", # wrong keyword
1593 "min(1, 2, key=int, abc=int)", # two many keywords
1594 "min(1, 2, key=1)", # keyfunc is not callable
1595 ):
1596 try:
1597 exec(stmt, globals())
1598 except TypeError:
1599 pass
1600 else:
1601 self.fail(stmt)
1602
1603 self.assertEqual(min((1,), key=neg), 1) # one elem iterable
1604 self.assertEqual(min((1,2), key=neg), 2) # two elem iterable
1605 self.assertEqual(min(1, 2, key=neg), 2) # two elems
1606
1607 self.assertEqual(min((), default=None), None) # zero elem iterable
1608 self.assertEqual(min((1,), default=None), 1) # one elem iterable
1609 self.assertEqual(min((1,2), default=None), 1) # two elem iterable
1610
1611 self.assertEqual(min((), default=1, key=neg), 1)
1612 self.assertEqual(min((1, 2), default=1, key=neg), 2)
1613
1614 self.assertEqual(min((1, 2), key=None), 1)
1615
1616 data = [random.randrange(200) for i in range(100)]
1617 keys = dict((elem, random.randrange(50)) for elem in data)
1618 f = keys.__getitem__
1619 self.assertEqual(min(data, key=f),
1620 sorted(data, key=f)[0])
1621
1622 def test_next(self):
1623 it = iter(range(2))
1624 self.assertEqual(next(it), 0)
1625 self.assertEqual(next(it), 1)
1626 self.assertRaises(StopIteration, next, it)
1627 self.assertRaises(StopIteration, next, it)
1628 self.assertEqual(next(it, 42), 42)
1629
1630 class Iter(object):
1631 def __iter__(self):
1632 return self
1633 def __next__(self):
1634 raise StopIteration
1635
1636 it = iter(Iter())
1637 self.assertEqual(next(it, 42), 42)
1638 self.assertRaises(StopIteration, next, it)
1639
1640 def gen():
1641 yield 1
1642 return
1643
1644 it = gen()
1645 self.assertEqual(next(it), 1)
1646 self.assertRaises(StopIteration, next, it)
1647 self.assertEqual(next(it, 42), 42)
1648
1649 def test_oct(self):
1650 self.assertEqual(oct(100), '0o144')
1651 self.assertEqual(oct(-100), '-0o144')
1652 self.assertRaises(TypeError, oct, ())
1653
1654 def write_testfile(self):
1655 # NB the first 4 lines are also used to test input, below
1656 fp = open(TESTFN, 'w', encoding="utf-8")
1657 self.addCleanup(unlink, TESTFN)
1658 with fp:
1659 fp.write('1+1\n')
1660 fp.write('The quick brown fox jumps over the lazy dog')
1661 fp.write('.\n')
1662 fp.write('Dear John\n')
1663 fp.write('XXX'*100)
1664 fp.write('YYY'*100)
1665
1666 def test_open(self):
1667 self.write_testfile()
1668 fp = open(TESTFN, encoding="utf-8")
1669 with fp:
1670 self.assertEqual(fp.readline(4), '1+1\n')
1671 self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
1672 self.assertEqual(fp.readline(4), 'Dear')
1673 self.assertEqual(fp.readline(100), ' John\n')
1674 self.assertEqual(fp.read(300), 'XXX'*100)
1675 self.assertEqual(fp.read(1000), 'YYY'*100)
1676
1677 # embedded null bytes and characters
1678 self.assertRaises(ValueError, open, 'a\x00b')
1679 self.assertRaises(ValueError, open, b'a\x00b')
1680
1681 @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled")
1682 def test_open_default_encoding(self):
1683 with EnvironmentVarGuard() as env:
1684 # try to get a user preferred encoding different than the current
1685 # locale encoding to check that open() uses the current locale
1686 # encoding and not the user preferred encoding
1687 env.unset('LC_ALL', 'LANG', 'LC_CTYPE')
1688
1689 self.write_testfile()
1690 current_locale_encoding = locale.getencoding()
1691 with warnings.catch_warnings():
1692 warnings.simplefilter("ignore", EncodingWarning)
1693 fp = open(TESTFN, 'w')
1694 with fp:
1695 self.assertEqual(fp.encoding, current_locale_encoding)
1696
1697 @support.requires_subprocess()
1698 def test_open_non_inheritable(self):
1699 fileobj = open(__file__, encoding="utf-8")
1700 with fileobj:
1701 self.assertFalse(os.get_inheritable(fileobj.fileno()))
1702
1703 def test_ord(self):
1704 self.assertEqual(ord(' '), 32)
1705 self.assertEqual(ord('A'), 65)
1706 self.assertEqual(ord('a'), 97)
1707 self.assertEqual(ord('\x80'), 128)
1708 self.assertEqual(ord('\xff'), 255)
1709
1710 self.assertEqual(ord(b' '), 32)
1711 self.assertEqual(ord(b'A'), 65)
1712 self.assertEqual(ord(b'a'), 97)
1713 self.assertEqual(ord(b'\x80'), 128)
1714 self.assertEqual(ord(b'\xff'), 255)
1715
1716 self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
1717 self.assertRaises(TypeError, ord, 42)
1718
1719 self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)
1720 self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF)
1721 self.assertEqual(ord("\U00010000"), 0x00010000)
1722 self.assertEqual(ord("\U00010001"), 0x00010001)
1723 self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE)
1724 self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF)
1725 self.assertEqual(ord("\U00100000"), 0x00100000)
1726 self.assertEqual(ord("\U00100001"), 0x00100001)
1727 self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE)
1728 self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF)
1729
1730 def test_pow(self):
1731 self.assertEqual(pow(0,0), 1)
1732 self.assertEqual(pow(0,1), 0)
1733 self.assertEqual(pow(1,0), 1)
1734 self.assertEqual(pow(1,1), 1)
1735
1736 self.assertEqual(pow(2,0), 1)
1737 self.assertEqual(pow(2,10), 1024)
1738 self.assertEqual(pow(2,20), 1024*1024)
1739 self.assertEqual(pow(2,30), 1024*1024*1024)
1740
1741 self.assertEqual(pow(-2,0), 1)
1742 self.assertEqual(pow(-2,1), -2)
1743 self.assertEqual(pow(-2,2), 4)
1744 self.assertEqual(pow(-2,3), -8)
1745
1746 self.assertAlmostEqual(pow(0.,0), 1.)
1747 self.assertAlmostEqual(pow(0.,1), 0.)
1748 self.assertAlmostEqual(pow(1.,0), 1.)
1749 self.assertAlmostEqual(pow(1.,1), 1.)
1750
1751 self.assertAlmostEqual(pow(2.,0), 1.)
1752 self.assertAlmostEqual(pow(2.,10), 1024.)
1753 self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
1754 self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
1755
1756 self.assertAlmostEqual(pow(-2.,0), 1.)
1757 self.assertAlmostEqual(pow(-2.,1), -2.)
1758 self.assertAlmostEqual(pow(-2.,2), 4.)
1759 self.assertAlmostEqual(pow(-2.,3), -8.)
1760
1761 for x in 2, 2.0:
1762 for y in 10, 10.0:
1763 for z in 1000, 1000.0:
1764 if isinstance(x, float) or \
1765 isinstance(y, float) or \
1766 isinstance(z, float):
1767 self.assertRaises(TypeError, pow, x, y, z)
1768 else:
1769 self.assertAlmostEqual(pow(x, y, z), 24.0)
1770
1771 self.assertAlmostEqual(pow(-1, 0.5), 1j)
1772 self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)
1773
1774 # See test_pow for additional tests for three-argument pow.
1775 self.assertEqual(pow(-1, -2, 3), 1)
1776 self.assertRaises(ValueError, pow, 1, 2, 0)
1777
1778 self.assertRaises(TypeError, pow)
1779
1780 # Test passing in arguments as keywords.
1781 self.assertEqual(pow(0, exp=0), 1)
1782 self.assertEqual(pow(base=2, exp=4), 16)
1783 self.assertEqual(pow(base=5, exp=2, mod=14), 11)
1784 twopow = partial(pow, base=2)
1785 self.assertEqual(twopow(exp=5), 32)
1786 fifth_power = partial(pow, exp=5)
1787 self.assertEqual(fifth_power(2), 32)
1788 mod10 = partial(pow, mod=10)
1789 self.assertEqual(mod10(2, 6), 4)
1790 self.assertEqual(mod10(exp=6, base=2), 4)
1791
1792 def test_input(self):
1793 self.write_testfile()
1794 fp = open(TESTFN, encoding="utf-8")
1795 savestdin = sys.stdin
1796 savestdout = sys.stdout # Eats the echo
1797 try:
1798 sys.stdin = fp
1799 sys.stdout = BitBucket()
1800 self.assertEqual(input(), "1+1")
1801 self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
1802 self.assertEqual(input('testing\n'), 'Dear John')
1803
1804 # SF 1535165: don't segfault on closed stdin
1805 # sys.stdout must be a regular file for triggering
1806 sys.stdout = savestdout
1807 sys.stdin.close()
1808 self.assertRaises(ValueError, input)
1809
1810 sys.stdout = BitBucket()
1811 sys.stdin = io.StringIO("NULL\0")
1812 self.assertRaises(TypeError, input, 42, 42)
1813 sys.stdin = io.StringIO(" 'whitespace'")
1814 self.assertEqual(input(), " 'whitespace'")
1815 sys.stdin = io.StringIO()
1816 self.assertRaises(EOFError, input)
1817
1818 del sys.stdout
1819 self.assertRaises(RuntimeError, input, 'prompt')
1820 del sys.stdin
1821 self.assertRaises(RuntimeError, input, 'prompt')
1822 finally:
1823 sys.stdin = savestdin
1824 sys.stdout = savestdout
1825 fp.close()
1826
1827 def test_input_gh130163(self):
1828 class X(io.StringIO):
1829 def __getattribute__(self, name):
1830 nonlocal patch
1831 if patch:
1832 patch = False
1833 sys.stdout = X()
1834 sys.stderr = X()
1835 sys.stdin = X('input\n')
1836 support.gc_collect()
1837 return io.StringIO.__getattribute__(self, name)
1838
1839 with (support.swap_attr(sys, 'stdout', None),
1840 support.swap_attr(sys, 'stderr', None),
1841 support.swap_attr(sys, 'stdin', None)):
1842 patch = False
1843 # the only references:
1844 sys.stdout = X()
1845 sys.stderr = X()
1846 sys.stdin = X('input\n')
1847 patch = True
1848 input() # should not crash
1849
1850 # test_int(): see test_int.py for tests of built-in function int().
1851
1852 def test_repr(self):
1853 self.assertEqual(repr(''), '\'\'')
1854 self.assertEqual(repr(0), '0')
1855 self.assertEqual(repr(()), '()')
1856 self.assertEqual(repr([]), '[]')
1857 self.assertEqual(repr({}), '{}')
1858 a = []
1859 a.append(a)
1860 self.assertEqual(repr(a), '[[...]]')
1861 a = {}
1862 a[0] = a
1863 self.assertEqual(repr(a), '{0: {...}}')
1864
1865 def test_repr_blocked(self):
1866 class C:
1867 __repr__ = None
1868 self.assertRaises(TypeError, repr, C())
1869
1870 def test_round(self):
1871 self.assertEqual(round(0.0), 0.0)
1872 self.assertEqual(type(round(0.0)), int)
1873 self.assertEqual(round(1.0), 1.0)
1874 self.assertEqual(round(10.0), 10.0)
1875 self.assertEqual(round(1000000000.0), 1000000000.0)
1876 self.assertEqual(round(1e20), 1e20)
1877
1878 self.assertEqual(round(-1.0), -1.0)
1879 self.assertEqual(round(-10.0), -10.0)
1880 self.assertEqual(round(-1000000000.0), -1000000000.0)
1881 self.assertEqual(round(-1e20), -1e20)
1882
1883 self.assertEqual(round(0.1), 0.0)
1884 self.assertEqual(round(1.1), 1.0)
1885 self.assertEqual(round(10.1), 10.0)
1886 self.assertEqual(round(1000000000.1), 1000000000.0)
1887
1888 self.assertEqual(round(-1.1), -1.0)
1889 self.assertEqual(round(-10.1), -10.0)
1890 self.assertEqual(round(-1000000000.1), -1000000000.0)
1891
1892 self.assertEqual(round(0.9), 1.0)
1893 self.assertEqual(round(9.9), 10.0)
1894 self.assertEqual(round(999999999.9), 1000000000.0)
1895
1896 self.assertEqual(round(-0.9), -1.0)
1897 self.assertEqual(round(-9.9), -10.0)
1898 self.assertEqual(round(-999999999.9), -1000000000.0)
1899
1900 self.assertEqual(round(-8.0, -1), -10.0)
1901 self.assertEqual(type(round(-8.0, -1)), float)
1902
1903 self.assertEqual(type(round(-8.0, 0)), float)
1904 self.assertEqual(type(round(-8.0, 1)), float)
1905
1906 # Check even / odd rounding behaviour
1907 self.assertEqual(round(5.5), 6)
1908 self.assertEqual(round(6.5), 6)
1909 self.assertEqual(round(-5.5), -6)
1910 self.assertEqual(round(-6.5), -6)
1911
1912 # Check behavior on ints
1913 self.assertEqual(round(0), 0)
1914 self.assertEqual(round(8), 8)
1915 self.assertEqual(round(-8), -8)
1916 self.assertEqual(type(round(0)), int)
1917 self.assertEqual(type(round(-8, -1)), int)
1918 self.assertEqual(type(round(-8, 0)), int)
1919 self.assertEqual(type(round(-8, 1)), int)
1920
1921 # test new kwargs
1922 self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
1923
1924 self.assertRaises(TypeError, round)
1925
1926 # test generic rounding delegation for reals
1927 class TestRound:
1928 def __round__(self):
1929 return 23
1930
1931 class TestNoRound:
1932 pass
1933
1934 self.assertEqual(round(TestRound()), 23)
1935
1936 self.assertRaises(TypeError, round, 1, 2, 3)
1937 self.assertRaises(TypeError, round, TestNoRound())
1938
1939 t = TestNoRound()
1940 t.__round__ = lambda *args: args
1941 self.assertRaises(TypeError, round, t)
1942 self.assertRaises(TypeError, round, t, 0)
1943
1944 # Some versions of glibc for alpha have a bug that affects
1945 # float -> integer rounding (floor, ceil, rint, round) for
1946 # values in the range [2**52, 2**53). See:
1947 #
1948 # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
1949 #
1950 # We skip this test on Linux/alpha if it would fail.
1951 linux_alpha = (platform.system().startswith('Linux') and
1952 platform.machine().startswith('alpha'))
1953 system_round_bug = round(5e15+1) != 5e15+1
1954 @unittest.skipIf(linux_alpha and system_round_bug,
1955 "test will fail; failure is probably due to a "
1956 "buggy system round function")
1957 def test_round_large(self):
1958 # Issue #1869: integral floats should remain unchanged
1959 self.assertEqual(round(5e15-1), 5e15-1)
1960 self.assertEqual(round(5e15), 5e15)
1961 self.assertEqual(round(5e15+1), 5e15+1)
1962 self.assertEqual(round(5e15+2), 5e15+2)
1963 self.assertEqual(round(5e15+3), 5e15+3)
1964
1965 def test_bug_27936(self):
1966 # Verify that ndigits=None means the same as passing in no argument
1967 for x in [1234,
1968 1234.56,
1969 decimal.Decimal('1234.56'),
1970 fractions.Fraction(123456, 100)]:
1971 self.assertEqual(round(x, None), round(x))
1972 self.assertEqual(type(round(x, None)), type(round(x)))
1973
1974 def test_setattr(self):
1975 setattr(sys, 'spam', 1)
1976 try:
1977 self.assertEqual(sys.spam, 1)
1978 finally:
1979 del sys.spam
1980 self.assertRaises(TypeError, setattr)
1981 self.assertRaises(TypeError, setattr, sys)
1982 self.assertRaises(TypeError, setattr, sys, 'spam')
1983 msg = r"^attribute name must be string, not 'int'$"
1984 self.assertRaisesRegex(TypeError, msg, setattr, sys, 1, 'spam')
1985
1986 # test_str(): see test_str.py and test_bytes.py for str() tests.
1987
1988 def test_sum(self):
1989 self.assertEqual(sum([]), 0)
1990 self.assertEqual(sum(list(range(2,8))), 27)
1991 self.assertEqual(sum(iter(list(range(2,8)))), 27)
1992 self.assertEqual(sum(Squares(10)), 285)
1993 self.assertEqual(sum(iter(Squares(10))), 285)
1994 self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
1995
1996 self.assertEqual(sum(range(10), 1000), 1045)
1997 self.assertEqual(sum(range(10), start=1000), 1045)
1998 self.assertEqual(sum(range(10), 2**31-5), 2**31+40)
1999 self.assertEqual(sum(range(10), 2**63-5), 2**63+40)
2000
2001 self.assertEqual(sum(i % 2 != 0 for i in range(10)), 5)
2002 self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**31-3),
2003 2**31+2)
2004 self.assertEqual(sum((i % 2 != 0 for i in range(10)), 2**63-3),
2005 2**63+2)
2006 self.assertIs(sum([], False), False)
2007
2008 self.assertEqual(sum(i / 2 for i in range(10)), 22.5)
2009 self.assertEqual(sum((i / 2 for i in range(10)), 1000), 1022.5)
2010 self.assertEqual(sum((i / 2 for i in range(10)), 1000.25), 1022.75)
2011 self.assertEqual(sum([0.5, 1]), 1.5)
2012 self.assertEqual(sum([1, 0.5]), 1.5)
2013 self.assertEqual(repr(sum([-0.0])), '0.0')
2014 self.assertEqual(repr(sum([-0.0], -0.0)), '-0.0')
2015 self.assertEqual(repr(sum([], -0.0)), '-0.0')
2016 self.assertTrue(math.isinf(sum([float("inf"), float("inf")])))
2017 self.assertTrue(math.isinf(sum([1e308, 1e308])))
2018
2019 self.assertRaises(TypeError, sum)
2020 self.assertRaises(TypeError, sum, 42)
2021 self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
2022 self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
2023 self.assertRaises(TypeError, sum, [b'a', b'c'], b'')
2024 values = [bytearray(b'a'), bytearray(b'b')]
2025 self.assertRaises(TypeError, sum, values, bytearray(b''))
2026 self.assertRaises(TypeError, sum, [[1], [2], [3]])
2027 self.assertRaises(TypeError, sum, [{2:3}])
2028 self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
2029 self.assertRaises(TypeError, sum, [], '')
2030 self.assertRaises(TypeError, sum, [], b'')
2031 self.assertRaises(TypeError, sum, [], bytearray())
2032 self.assertRaises(OverflowError, sum, [1.0, 10**1000])
2033 self.assertRaises(OverflowError, sum, [1j, 10**1000])
2034
2035 class BadSeq:
2036 def __getitem__(self, index):
2037 raise ValueError
2038 self.assertRaises(ValueError, sum, BadSeq())
2039
2040 empty = []
2041 sum(([x] for x in range(10)), empty)
2042 self.assertEqual(empty, [])
2043
2044 xs = [complex(random.random() - .5, random.random() - .5)
2045 for _ in range(10000)]
2046 self.assertEqual(sum(xs), complex(sum(z.real for z in xs),
2047 sum(z.imag for z in xs)))
2048
2049 # test that sum() of complex and real numbers doesn't
2050 # smash sign of imaginary 0
2051 self.assertComplexesAreIdentical(sum([complex(1, -0.0), 1]),
2052 complex(2, -0.0))
2053 self.assertComplexesAreIdentical(sum([1, complex(1, -0.0)]),
2054 complex(2, -0.0))
2055 self.assertComplexesAreIdentical(sum([complex(1, -0.0), 1.0]),
2056 complex(2, -0.0))
2057 self.assertComplexesAreIdentical(sum([1.0, complex(1, -0.0)]),
2058 complex(2, -0.0))
2059
2060 @requires_IEEE_754
2061 @unittest.skipIf(HAVE_DOUBLE_ROUNDING,
2062 "sum accuracy not guaranteed on machines with double rounding")
2063 @support.cpython_only # Other implementations may choose a different algorithm
2064 def test_sum_accuracy(self):
2065 self.assertEqual(sum([0.1] * 10), 1.0)
2066 self.assertEqual(sum([1.0, 10E100, 1.0, -10E100]), 2.0)
2067 self.assertEqual(sum([1.0, 10E100, 1.0, -10E100, 2j]), 2+2j)
2068 self.assertEqual(sum([2+1j, 10E100j, 1j, -10E100j]), 2+2j)
2069 self.assertEqual(sum([1j, 1, 10E100j, 1j, 1.0, -10E100j]), 2+2j)
2070 self.assertEqual(sum([2j, 1., 10E100, 1., -10E100]), 2+2j)
2071 self.assertEqual(sum([1.0, 10**100, 1.0, -10**100]), 2.0)
2072 self.assertEqual(sum([2j, 1.0, 10**100, 1.0, -10**100]), 2+2j)
2073 self.assertEqual(sum([0.1j]*10 + [fractions.Fraction(1, 10)]), 0.1+1j)
2074
2075 def test_type(self):
2076 self.assertEqual(type(''), type('123'))
2077 self.assertNotEqual(type(''), type(()))
2078
2079 # We don't want self in vars(), so these are static methods
2080
2081 @staticmethod
2082 def get_vars_f0():
2083 return vars()
2084
2085 @staticmethod
2086 def get_vars_f2():
2087 BuiltinTest.get_vars_f0()
2088 a = 1
2089 b = 2
2090 return vars()
2091
2092 class C_get_vars(object):
2093 def getDict(self):
2094 return {'a':2}
2095 __dict__ = property(fget=getDict)
2096
2097 def test_vars(self):
2098 self.assertEqual(set(vars()), set(dir()))
2099 self.assertEqual(set(vars(sys)), set(dir(sys)))
2100 self.assertEqual(self.get_vars_f0(), {})
2101 self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
2102 self.assertRaises(TypeError, vars, 42, 42)
2103 self.assertRaises(TypeError, vars, 42)
2104 self.assertEqual(vars(self.C_get_vars()), {'a':2})
2105
2106 def iter_error(self, iterable, error):
2107 """Collect `iterable` into a list, catching an expected `error`."""
2108 items = []
2109 with self.assertRaises(error):
2110 for item in iterable:
2111 items.append(item)
2112 return items
2113
2114 def test_zip(self):
2115 a = (1, 2, 3)
2116 b = (4, 5, 6)
2117 t = [(1, 4), (2, 5), (3, 6)]
2118 self.assertEqual(list(zip(a, b)), t)
2119 b = [4, 5, 6]
2120 self.assertEqual(list(zip(a, b)), t)
2121 b = (4, 5, 6, 7)
2122 self.assertEqual(list(zip(a, b)), t)
2123 class I:
2124 def __getitem__(self, i):
2125 if i < 0 or i > 2: raise IndexError
2126 return i + 4
2127 self.assertEqual(list(zip(a, I())), t)
2128 self.assertEqual(list(zip()), [])
2129 self.assertEqual(list(zip(*[])), [])
2130 self.assertRaises(TypeError, zip, None)
2131 class G:
2132 pass
2133 self.assertRaises(TypeError, zip, a, G())
2134 self.assertRaises(RuntimeError, zip, a, TestFailingIter())
2135
2136 # Make sure zip doesn't try to allocate a billion elements for the
2137 # result list when one of its arguments doesn't say how long it is.
2138 # A MemoryError is the most likely failure mode.
2139 class SequenceWithoutALength:
2140 def __getitem__(self, i):
2141 if i == 5:
2142 raise IndexError
2143 else:
2144 return i
2145 self.assertEqual(
2146 list(zip(SequenceWithoutALength(), range(2**30))),
2147 list(enumerate(range(5)))
2148 )
2149
2150 class BadSeq:
2151 def __getitem__(self, i):
2152 if i == 5:
2153 raise ValueError
2154 else:
2155 return i
2156 self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))
2157
2158 def test_zip_pickle(self):
2159 a = (1, 2, 3)
2160 b = (4, 5, 6)
2161 t = [(1, 4), (2, 5), (3, 6)]
2162 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2163 z1 = zip(a, b)
2164 self.check_iter_pickle(z1, t, proto)
2165
2166 def test_zip_pickle_strict(self):
2167 a = (1, 2, 3)
2168 b = (4, 5, 6)
2169 t = [(1, 4), (2, 5), (3, 6)]
2170 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2171 z1 = zip(a, b, strict=True)
2172 self.check_iter_pickle(z1, t, proto)
2173
2174 def test_zip_pickle_strict_fail(self):
2175 a = (1, 2, 3)
2176 b = (4, 5, 6, 7)
2177 t = [(1, 4), (2, 5), (3, 6)]
2178 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2179 z1 = zip(a, b, strict=True)
2180 z2 = pickle.loads(pickle.dumps(z1, proto))
2181 self.assertEqual(self.iter_error(z1, ValueError), t)
2182 self.assertEqual(self.iter_error(z2, ValueError), t)
2183
2184 def test_zip_bad_iterable(self):
2185 exception = TypeError()
2186
2187 class BadIterable:
2188 def __iter__(self):
2189 raise exception
2190
2191 with self.assertRaises(TypeError) as cm:
2192 zip(BadIterable())
2193
2194 self.assertIs(cm.exception, exception)
2195
2196 def test_zip_strict(self):
2197 self.assertEqual(tuple(zip((1, 2, 3), 'abc', strict=True)),
2198 ((1, 'a'), (2, 'b'), (3, 'c')))
2199 self.assertRaises(ValueError, tuple,
2200 zip((1, 2, 3, 4), 'abc', strict=True))
2201 self.assertRaises(ValueError, tuple,
2202 zip((1, 2), 'abc', strict=True))
2203 self.assertRaises(ValueError, tuple,
2204 zip((1, 2), (1, 2), 'abc', strict=True))
2205
2206 def test_zip_strict_iterators(self):
2207 x = iter(range(5))
2208 y = [0]
2209 z = iter(range(5))
2210 self.assertRaises(ValueError, list,
2211 (zip(x, y, z, strict=True)))
2212 self.assertEqual(next(x), 2)
2213 self.assertEqual(next(z), 1)
2214
2215 def test_zip_strict_error_handling(self):
2216
2217 class Error(Exception):
2218 pass
2219
2220 class Iter:
2221 def __init__(self, size):
2222 self.size = size
2223 def __iter__(self):
2224 return self
2225 def __next__(self):
2226 self.size -= 1
2227 if self.size < 0:
2228 raise Error
2229 return self.size
2230
2231 l1 = self.iter_error(zip("AB", Iter(1), strict=True), Error)
2232 self.assertEqual(l1, [("A", 0)])
2233 l2 = self.iter_error(zip("AB", Iter(2), "A", strict=True), ValueError)
2234 self.assertEqual(l2, [("A", 1, "A")])
2235 l3 = self.iter_error(zip("AB", Iter(2), "ABC", strict=True), Error)
2236 self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
2237 l4 = self.iter_error(zip("AB", Iter(3), strict=True), ValueError)
2238 self.assertEqual(l4, [("A", 2), ("B", 1)])
2239 l5 = self.iter_error(zip(Iter(1), "AB", strict=True), Error)
2240 self.assertEqual(l5, [(0, "A")])
2241 l6 = self.iter_error(zip(Iter(2), "A", strict=True), ValueError)
2242 self.assertEqual(l6, [(1, "A")])
2243 l7 = self.iter_error(zip(Iter(2), "ABC", strict=True), Error)
2244 self.assertEqual(l7, [(1, "A"), (0, "B")])
2245 l8 = self.iter_error(zip(Iter(3), "AB", strict=True), ValueError)
2246 self.assertEqual(l8, [(2, "A"), (1, "B")])
2247
2248 def test_zip_strict_error_handling_stopiteration(self):
2249
2250 class Iter:
2251 def __init__(self, size):
2252 self.size = size
2253 def __iter__(self):
2254 return self
2255 def __next__(self):
2256 self.size -= 1
2257 if self.size < 0:
2258 raise StopIteration
2259 return self.size
2260
2261 l1 = self.iter_error(zip("AB", Iter(1), strict=True), ValueError)
2262 self.assertEqual(l1, [("A", 0)])
2263 l2 = self.iter_error(zip("AB", Iter(2), "A", strict=True), ValueError)
2264 self.assertEqual(l2, [("A", 1, "A")])
2265 l3 = self.iter_error(zip("AB", Iter(2), "ABC", strict=True), ValueError)
2266 self.assertEqual(l3, [("A", 1, "A"), ("B", 0, "B")])
2267 l4 = self.iter_error(zip("AB", Iter(3), strict=True), ValueError)
2268 self.assertEqual(l4, [("A", 2), ("B", 1)])
2269 l5 = self.iter_error(zip(Iter(1), "AB", strict=True), ValueError)
2270 self.assertEqual(l5, [(0, "A")])
2271 l6 = self.iter_error(zip(Iter(2), "A", strict=True), ValueError)
2272 self.assertEqual(l6, [(1, "A")])
2273 l7 = self.iter_error(zip(Iter(2), "ABC", strict=True), ValueError)
2274 self.assertEqual(l7, [(1, "A"), (0, "B")])
2275 l8 = self.iter_error(zip(Iter(3), "AB", strict=True), ValueError)
2276 self.assertEqual(l8, [(2, "A"), (1, "B")])
2277
2278 @support.cpython_only
2279 def test_zip_result_gc(self):
2280 # bpo-42536: zip's tuple-reuse speed trick breaks the GC's assumptions
2281 # about what can be untracked. Make sure we re-track result tuples
2282 # whenever we reuse them.
2283 it = zip([[]])
2284 gc.collect()
2285 # That GC collection probably untracked the recycled internal result
2286 # tuple, which is initialized to (None,). Make sure it's re-tracked when
2287 # it's mutated and returned from __next__:
2288 self.assertTrue(gc.is_tracked(next(it)))
2289
2290 def test_format(self):
2291 # Test the basic machinery of the format() builtin. Don't test
2292 # the specifics of the various formatters
2293 self.assertEqual(format(3, ''), '3')
2294
2295 # Returns some classes to use for various tests. There's
2296 # an old-style version, and a new-style version
2297 def classes_new():
2298 class A(object):
2299 def __init__(self, x):
2300 self.x = x
2301 def __format__(self, format_spec):
2302 return str(self.x) + format_spec
2303 class DerivedFromA(A):
2304 pass
2305
2306 class Simple(object): pass
2307 class DerivedFromSimple(Simple):
2308 def __init__(self, x):
2309 self.x = x
2310 def __format__(self, format_spec):
2311 return str(self.x) + format_spec
2312 class DerivedFromSimple2(DerivedFromSimple): pass
2313 return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
2314
2315 def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
2316 self.assertEqual(format(A(3), 'spec'), '3spec')
2317 self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
2318 self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
2319 self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
2320 '10abcdef')
2321
2322 class_test(*classes_new())
2323
2324 def empty_format_spec(value):
2325 # test that:
2326 # format(x, '') == str(x)
2327 # format(x) == str(x)
2328 self.assertEqual(format(value, ""), str(value))
2329 self.assertEqual(format(value), str(value))
2330
2331 # for builtin types, format(x, "") == str(x)
2332 empty_format_spec(17**13)
2333 empty_format_spec(1.0)
2334 empty_format_spec(3.1415e104)
2335 empty_format_spec(-3.1415e104)
2336 empty_format_spec(3.1415e-104)
2337 empty_format_spec(-3.1415e-104)
2338 empty_format_spec(object)
2339 empty_format_spec(None)
2340
2341 # TypeError because self.__format__ returns the wrong type
2342 class BadFormatResult:
2343 def __format__(self, format_spec):
2344 return 1.0
2345 self.assertRaises(TypeError, format, BadFormatResult(), "")
2346
2347 # TypeError because format_spec is not unicode or str
2348 self.assertRaises(TypeError, format, object(), 4)
2349 self.assertRaises(TypeError, format, object(), object())
2350
2351 # tests for object.__format__ really belong elsewhere, but
2352 # there's no good place to put them
2353 x = object().__format__('')
2354 self.assertStartsWith(x, '<object object at')
2355
2356 # first argument to object.__format__ must be string
2357 self.assertRaises(TypeError, object().__format__, 3)
2358 self.assertRaises(TypeError, object().__format__, object())
2359 self.assertRaises(TypeError, object().__format__, None)
2360
2361 # --------------------------------------------------------------------
2362 # Issue #7994: object.__format__ with a non-empty format string is
2363 # disallowed
2364 class A:
2365 def __format__(self, fmt_str):
2366 return format('', fmt_str)
2367
2368 self.assertEqual(format(A()), '')
2369 self.assertEqual(format(A(), ''), '')
2370 self.assertEqual(format(A(), 's'), '')
2371
2372 class B:
2373 pass
2374
2375 class C(object):
2376 pass
2377
2378 for cls in [object, B, C]:
2379 obj = cls()
2380 self.assertEqual(format(obj), str(obj))
2381 self.assertEqual(format(obj, ''), str(obj))
2382 with self.assertRaisesRegex(TypeError,
2383 r'\b%s\b' % re.escape(cls.__name__)):
2384 format(obj, 's')
2385 # --------------------------------------------------------------------
2386
2387 # make sure we can take a subclass of str as a format spec
2388 class DerivedFromStr(str): pass
2389 self.assertEqual(format(0, DerivedFromStr('10')), ' 0')
2390
2391 def test_bin(self):
2392 self.assertEqual(bin(0), '0b0')
2393 self.assertEqual(bin(1), '0b1')
2394 self.assertEqual(bin(-1), '-0b1')
2395 self.assertEqual(bin(2**65), '0b1' + '0' * 65)
2396 self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
2397 self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
2398 self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
2399
2400 def test_bytearray_translate(self):
2401 x = bytearray(b"abc")
2402 self.assertRaises(ValueError, x.translate, b"1", 1)
2403 self.assertRaises(TypeError, x.translate, b"1"*256, 1)
2404
2405 def test_bytearray_extend_error(self):
2406 array = bytearray()
2407 bad_iter = map(int, "X")
2408 self.assertRaises(ValueError, array.extend, bad_iter)
2409
2410 def test_bytearray_join_with_misbehaving_iterator(self):
2411 # Issue #112625
2412 array = bytearray(b',')
2413 def iterator():
2414 array.clear()
2415 yield b'A'
2416 yield b'B'
2417 self.assertRaises(BufferError, array.join, iterator())
2418
2419 def test_bytearray_join_with_custom_iterator(self):
2420 # Issue #112625
2421 array = bytearray(b',')
2422 def iterator():
2423 yield b'A'
2424 yield b'B'
2425 self.assertEqual(bytearray(b'A,B'), array.join(iterator()))
2426
2427 def test_construct_singletons(self):
2428 for const in None, Ellipsis, NotImplemented:
2429 tp = type(const)
2430 self.assertIs(tp(), const)
2431 self.assertRaises(TypeError, tp, 1, 2)
2432 self.assertRaises(TypeError, tp, a=1, b=2)
2433
2434 def test_bool_notimplemented(self):
2435 # GH-79893: NotImplemented is a sentinel value that should never
2436 # be evaluated in a boolean context (virtually all such use cases
2437 # are a result of accidental misuse implementing rich comparison
2438 # operations in terms of one another).
2439 msg = "NotImplemented should not be used in a boolean context"
2440 self.assertRaisesRegex(TypeError, msg, bool, NotImplemented)
2441 with self.assertRaisesRegex(TypeError, msg):
2442 if NotImplemented:
2443 pass
2444 with self.assertRaisesRegex(TypeError, msg):
2445 not NotImplemented
2446
2447 def test_singleton_attribute_access(self):
2448 for singleton in (NotImplemented, Ellipsis):
2449 with self.subTest(singleton):
2450 self.assertIs(type(singleton), singleton.__class__)
2451 self.assertIs(type(singleton).__class__, type)
2452
2453 # Missing instance attributes:
2454 with self.assertRaises(AttributeError):
2455 singleton.prop = 1
2456 with self.assertRaises(AttributeError):
2457 singleton.prop
2458
2459 # Missing class attributes:
2460 with self.assertRaises(TypeError):
2461 type(singleton).prop = 1
2462 with self.assertRaises(AttributeError):
2463 type(singleton).prop
2464
2465
2466 class TestBreakpoint(unittest.TestCase):
2467 def setUp(self):
2468 # These tests require a clean slate environment. For example, if the
2469 # test suite is run with $PYTHONBREAKPOINT set to something else, it
2470 # will mess up these tests. Similarly for sys.breakpointhook.
2471 # Cleaning the slate here means you can't use breakpoint() to debug
2472 # these tests, but I think that's okay. Just use pdb.set_trace() if
2473 # you must.
2474 self.resources = ExitStack()
2475 self.addCleanup(self.resources.close)
2476 self.env = self.resources.enter_context(EnvironmentVarGuard())
2477 del self.env['PYTHONBREAKPOINT']
2478 self.resources.enter_context(
2479 swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))
2480
2481 def test_breakpoint(self):
2482 with patch('pdb.set_trace') as mock:
2483 breakpoint()
2484 mock.assert_called_once()
2485
2486 def test_breakpoint_with_breakpointhook_set(self):
2487 my_breakpointhook = MagicMock()
2488 sys.breakpointhook = my_breakpointhook
2489 breakpoint()
2490 my_breakpointhook.assert_called_once_with()
2491
2492 def test_breakpoint_with_breakpointhook_reset(self):
2493 my_breakpointhook = MagicMock()
2494 sys.breakpointhook = my_breakpointhook
2495 breakpoint()
2496 my_breakpointhook.assert_called_once_with()
2497 # Reset the hook and it will not be called again.
2498 sys.breakpointhook = sys.__breakpointhook__
2499 with patch('pdb.set_trace') as mock:
2500 breakpoint()
2501 mock.assert_called_once_with()
2502 my_breakpointhook.assert_called_once_with()
2503
2504 def test_breakpoint_with_args_and_keywords(self):
2505 my_breakpointhook = MagicMock()
2506 sys.breakpointhook = my_breakpointhook
2507 breakpoint(1, 2, 3, four=4, five=5)
2508 my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)
2509
2510 def test_breakpoint_with_passthru_error(self):
2511 def my_breakpointhook():
2512 pass
2513 sys.breakpointhook = my_breakpointhook
2514 self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)
2515
2516 @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2517 def test_envar_good_path_builtin(self):
2518 self.env['PYTHONBREAKPOINT'] = 'int'
2519 with patch('builtins.int') as mock:
2520 breakpoint('7')
2521 mock.assert_called_once_with('7')
2522
2523 @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2524 def test_envar_good_path_other(self):
2525 self.env['PYTHONBREAKPOINT'] = 'sys.exit'
2526 with patch('sys.exit') as mock:
2527 breakpoint()
2528 mock.assert_called_once_with()
2529
2530 @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2531 def test_envar_good_path_noop_0(self):
2532 self.env['PYTHONBREAKPOINT'] = '0'
2533 with patch('pdb.set_trace') as mock:
2534 breakpoint()
2535 mock.assert_not_called()
2536
2537 def test_envar_good_path_empty_string(self):
2538 # PYTHONBREAKPOINT='' is the same as it not being set.
2539 self.env['PYTHONBREAKPOINT'] = ''
2540 with patch('pdb.set_trace') as mock:
2541 breakpoint()
2542 mock.assert_called_once_with()
2543
2544 @unittest.skipIf(sys.flags.ignore_environment, '-E was given')
2545 def test_envar_unimportable(self):
2546 for envar in (
2547 '.', '..', '.foo', 'foo.', '.int', 'int.',
2548 '.foo.bar', '..foo.bar', '/./',
2549 'nosuchbuiltin',
2550 'nosuchmodule.nosuchcallable',
2551 ):
2552 with self.subTest(envar=envar):
2553 self.env['PYTHONBREAKPOINT'] = envar
2554 mock = self.resources.enter_context(patch('pdb.set_trace'))
2555 w = self.resources.enter_context(check_warnings(quiet=True))
2556 breakpoint()
2557 self.assertEqual(
2558 str(w.message),
2559 f'Ignoring unimportable $PYTHONBREAKPOINT: "{envar}"')
2560 self.assertEqual(w.category, RuntimeWarning)
2561 mock.assert_not_called()
2562
2563 def test_envar_ignored_when_hook_is_set(self):
2564 self.env['PYTHONBREAKPOINT'] = 'sys.exit'
2565 with patch('sys.exit') as mock:
2566 sys.breakpointhook = int
2567 breakpoint()
2568 mock.assert_not_called()
2569
2570 def test_runtime_error_when_hook_is_lost(self):
2571 del sys.breakpointhook
2572 with self.assertRaises(RuntimeError):
2573 breakpoint()
2574
2575
2576 @unittest.skipUnless(pty, "the pty and signal modules must be available")
2577 class PtyTests(unittest.TestCase):
2578 """Tests that use a pseudo terminal to guarantee stdin and stdout are
2579 terminals in the test environment"""
2580
2581 @staticmethod
2582 def handle_sighup(signum, frame):
2583 # bpo-40140: if the process is the session leader, os.close(fd)
2584 # of "pid, fd = pty.fork()" can raise SIGHUP signal:
2585 # just ignore the signal.
2586 pass
2587
2588 def run_child(self, child, terminal_input):
2589 old_sighup = signal.signal(signal.SIGHUP, self.handle_sighup)
2590 try:
2591 return self._run_child(child, terminal_input)
2592 finally:
2593 signal.signal(signal.SIGHUP, old_sighup)
2594
2595 def _run_child(self, child, terminal_input):
2596 r, w = os.pipe() # Pipe test results from child back to parent
2597 try:
2598 pid, fd = pty.fork()
2599 except (OSError, AttributeError) as e:
2600 os.close(r)
2601 os.close(w)
2602 self.skipTest("pty.fork() raised {}".format(e))
2603 raise
2604
2605 if pid == 0:
2606 # Child
2607 try:
2608 os.close(r)
2609 with open(w, "w") as wpipe:
2610 child(wpipe)
2611 except:
2612 traceback.print_exc()
2613 finally:
2614 # We don't want to return to unittest...
2615 os._exit(0)
2616
2617 # Parent
2618 os.close(w)
2619 os.write(fd, terminal_input)
2620
2621 # Get results from the pipe
2622 with open(r, encoding="utf-8") as rpipe:
2623 lines = []
2624 while True:
2625 line = rpipe.readline().strip()
2626 if line == "":
2627 # The other end was closed => the child exited
2628 break
2629 lines.append(line)
2630
2631 # Check the result was got and corresponds to the user's terminal input
2632 if len(lines) != 2:
2633 # Something went wrong, try to get at stderr
2634 # Beware of Linux raising EIO when the slave is closed
2635 child_output = bytearray()
2636 while True:
2637 try:
2638 chunk = os.read(fd, 3000)
2639 except OSError: # Assume EIO
2640 break
2641 if not chunk:
2642 break
2643 child_output.extend(chunk)
2644 os.close(fd)
2645 child_output = child_output.decode("ascii", "ignore")
2646 self.fail("got %d lines in pipe but expected 2, child output was:\n%s"
2647 % (len(lines), child_output))
2648
2649 # bpo-40155: Close the PTY before waiting for the child process
2650 # completion, otherwise the child process hangs on AIX.
2651 os.close(fd)
2652
2653 support.wait_process(pid, exitcode=0)
2654
2655 return lines
2656
2657 def check_input_tty(self, prompt, terminal_input, stdio_encoding=None, *,
2658 expected=None,
2659 stdin_errors='surrogateescape',
2660 stdout_errors='replace'):
2661 if not sys.stdin.isatty() or not sys.stdout.isatty():
2662 self.skipTest("stdin and stdout must be ttys")
2663 def child(wpipe):
2664 # Check the error handlers are accounted for
2665 if stdio_encoding:
2666 sys.stdin = io.TextIOWrapper(sys.stdin.detach(),
2667 encoding=stdio_encoding,
2668 errors=stdin_errors)
2669 sys.stdout = io.TextIOWrapper(sys.stdout.detach(),
2670 encoding=stdio_encoding,
2671 errors=stdout_errors)
2672 print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe)
2673 try:
2674 print(ascii(input(prompt)), file=wpipe)
2675 except BaseException as e:
2676 print(ascii(f'{e.__class__.__name__}: {e!s}'), file=wpipe)
2677 with self.detach_readline():
2678 lines = self.run_child(child, terminal_input + b"\r\n")
2679 # Check we did exercise the GNU readline path
2680 self.assertIn(lines[0], {'tty = True', 'tty = False'})
2681 if lines[0] != 'tty = True':
2682 self.skipTest("standard IO in should have been a tty")
2683 input_result = eval(lines[1]) # ascii() -> eval() roundtrip
2684 if expected is None:
2685 if stdio_encoding:
2686 expected = terminal_input.decode(stdio_encoding, 'surrogateescape')
2687 else:
2688 expected = terminal_input.decode(sys.stdin.encoding) # what else?
2689 self.assertEqual(input_result, expected)
2690
2691 @contextlib.contextmanager
2692 def detach_readline(self):
2693 # bpo-13886: When the readline module is loaded, PyOS_Readline() uses
2694 # the readline implementation. In some cases, the Python readline
2695 # callback rlhandler() is called by readline with a string without
2696 # non-ASCII characters.
2697 # Unlink readline temporarily from PyOS_Readline() for those tests,
2698 # since test_builtin is not intended to test
2699 # the readline module, but the builtins module.
2700 if "readline" in sys.modules:
2701 c = import_module("ctypes")
2702 fp_api = "PyOS_ReadlineFunctionPointer"
2703 prev_value = c.c_void_p.in_dll(c.pythonapi, fp_api).value
2704 c.c_void_p.in_dll(c.pythonapi, fp_api).value = None
2705 try:
2706 yield
2707 finally:
2708 c.c_void_p.in_dll(c.pythonapi, fp_api).value = prev_value
2709 else:
2710 yield
2711
2712 def test_input_tty(self):
2713 # Test input() functionality when wired to a tty
2714 self.check_input_tty("prompt", b"quux")
2715
2716 def test_input_tty_non_ascii(self):
2717 # Check stdin/stdout encoding is used when invoking PyOS_Readline()
2718 self.check_input_tty("prompté", b"quux\xc3\xa9", "utf-8")
2719
2720 def test_input_tty_non_ascii_unicode_errors(self):
2721 # Check stdin/stdout error handler is used when invoking PyOS_Readline()
2722 self.check_input_tty("prompté", b"quux\xe9", "ascii")
2723
2724 def test_input_tty_null_in_prompt(self):
2725 self.check_input_tty("prompt\0", b"",
2726 expected='ValueError: input: prompt string cannot contain '
2727 'null characters')
2728
2729 def test_input_tty_nonencodable_prompt(self):
2730 self.check_input_tty("prompté", b"quux", "ascii", stdout_errors='strict',
2731 expected="UnicodeEncodeError: 'ascii' codec can't encode "
2732 "character '\\xe9' in position 6: ordinal not in "
2733 "range(128)")
2734
2735 def test_input_tty_nondecodable_input(self):
2736 self.check_input_tty("prompt", b"quux\xe9", "ascii", stdin_errors='strict',
2737 expected="UnicodeDecodeError: 'ascii' codec can't decode "
2738 "byte 0xe9 in position 4: ordinal not in "
2739 "range(128)")
2740
2741 def test_input_no_stdout_fileno(self):
2742 # Issue #24402: If stdin is the original terminal but stdout.fileno()
2743 # fails, do not use the original stdout file descriptor
2744 def child(wpipe):
2745 print("stdin.isatty():", sys.stdin.isatty(), file=wpipe)
2746 sys.stdout = io.StringIO() # Does not support fileno()
2747 input("prompt")
2748 print("captured:", ascii(sys.stdout.getvalue()), file=wpipe)
2749 lines = self.run_child(child, b"quux\r")
2750 expected = (
2751 "stdin.isatty(): True",
2752 "captured: 'prompt'",
2753 )
2754 self.assertSequenceEqual(lines, expected)
2755
2756 class TestSorted(unittest.TestCase):
2757
2758 def test_basic(self):
2759 data = list(range(100))
2760 copy = data[:]
2761 random.shuffle(copy)
2762 self.assertEqual(data, sorted(copy))
2763 self.assertNotEqual(data, copy)
2764
2765 data.reverse()
2766 random.shuffle(copy)
2767 self.assertEqual(data, sorted(copy, key=lambda x: -x))
2768 self.assertNotEqual(data, copy)
2769 random.shuffle(copy)
2770 self.assertEqual(data, sorted(copy, reverse=True))
2771 self.assertNotEqual(data, copy)
2772
2773 def test_bad_arguments(self):
2774 # Issue #29327: The first argument is positional-only.
2775 sorted([])
2776 with self.assertRaises(TypeError):
2777 sorted(iterable=[])
2778 # Other arguments are keyword-only
2779 sorted([], key=None)
2780 with self.assertRaises(TypeError):
2781 sorted([], None)
2782
2783 def test_inputtypes(self):
2784 s = 'abracadabra'
2785 types = [list, tuple, str]
2786 for T in types:
2787 self.assertEqual(sorted(s), sorted(T(s)))
2788
2789 s = ''.join(set(s)) # unique letters only
2790 types = [str, set, frozenset, list, tuple, dict.fromkeys]
2791 for T in types:
2792 self.assertEqual(sorted(s), sorted(T(s)))
2793
2794 def test_baddecorator(self):
2795 data = 'The quick Brown fox Jumped over The lazy Dog'.split()
2796 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
2797
2798
2799 class ShutdownTest(unittest.TestCase):
2800
2801 def test_cleanup(self):
2802 # Issue #19255: builtins are still available at shutdown
2803 code = """if 1:
2804 import builtins
2805 import sys
2806
2807 class C:
2808 def __del__(self):
2809 print("before")
2810 # Check that builtins still exist
2811 len(())
2812 print("after")
2813
2814 c = C()
2815 # Make this module survive until builtins and sys are cleaned
2816 builtins.here = sys.modules[__name__]
2817 sys.here = sys.modules[__name__]
2818 # Create a reference loop so that this module needs to go
2819 # through a GC phase.
2820 here = sys.modules[__name__]
2821 """
2822 # Issue #20599: Force ASCII encoding to get a codec implemented in C,
2823 # otherwise the codec may be unloaded before C.__del__() is called, and
2824 # so print("before") fails because the codec cannot be used to encode
2825 # "before" to sys.stdout.encoding. For example, on Windows,
2826 # sys.stdout.encoding is the OEM code page and these code pages are
2827 # implemented in Python
2828 rc, out, err = assert_python_ok("-c", code,
2829 PYTHONIOENCODING="ascii")
2830 self.assertEqual(["before", "after"], out.decode().splitlines())
2831
2832
2833 @cpython_only
2834 class ImmortalTests(unittest.TestCase):
2835
2836 if sys.maxsize < (1 << 32):
2837 IMMORTAL_REFCOUNT_MINIMUM = 1 << 30
2838 else:
2839 IMMORTAL_REFCOUNT_MINIMUM = 1 << 31
2840
2841 IMMORTALS = (None, True, False, Ellipsis, NotImplemented, *range(-5, 257))
2842
2843 def assert_immortal(self, immortal):
2844 with self.subTest(immortal):
2845 self.assertGreater(sys.getrefcount(immortal), self.IMMORTAL_REFCOUNT_MINIMUM)
2846
2847 def test_immortals(self):
2848 for immortal in self.IMMORTALS:
2849 self.assert_immortal(immortal)
2850
2851 def test_list_repeat_respect_immortality(self):
2852 refs = list(self.IMMORTALS) * 42
2853 for immortal in self.IMMORTALS:
2854 self.assert_immortal(immortal)
2855
2856 def test_tuple_repeat_respect_immortality(self):
2857 refs = tuple(self.IMMORTALS) * 42
2858 for immortal in self.IMMORTALS:
2859 self.assert_immortal(immortal)
2860
2861
2862 class TestType(unittest.TestCase):
2863 def test_new_type(self):
2864 A = type('A', (), {})
2865 self.assertEqual(A.__name__, 'A')
2866 self.assertEqual(A.__qualname__, 'A')
2867 self.assertEqual(A.__module__, __name__)
2868 self.assertEqual(A.__bases__, (object,))
2869 self.assertIs(A.__base__, object)
2870 self.assertNotIn('__firstlineno__', A.__dict__)
2871 x = A()
2872 self.assertIs(type(x), A)
2873 self.assertIs(x.__class__, A)
2874
2875 class B:
2876 def ham(self):
2877 return 'ham%d' % self
2878 C = type('C', (B, int), {'spam': lambda self: 'spam%s' % self})
2879 self.assertEqual(C.__name__, 'C')
2880 self.assertEqual(C.__qualname__, 'C')
2881 self.assertEqual(C.__module__, __name__)
2882 self.assertEqual(C.__bases__, (B, int))
2883 self.assertIs(C.__base__, int)
2884 self.assertIn('spam', C.__dict__)
2885 self.assertNotIn('ham', C.__dict__)
2886 x = C(42)
2887 self.assertEqual(x, 42)
2888 self.assertIs(type(x), C)
2889 self.assertIs(x.__class__, C)
2890 self.assertEqual(x.ham(), 'ham42')
2891 self.assertEqual(x.spam(), 'spam42')
2892 self.assertEqual(x.to_bytes(2, 'little'), b'\x2a\x00')
2893
2894 def test_type_nokwargs(self):
2895 with self.assertRaises(TypeError):
2896 type('a', (), {}, x=5)
2897 with self.assertRaises(TypeError):
2898 type('a', (), dict={})
2899
2900 def test_type_name(self):
2901 for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
2902 with self.subTest(name=name):
2903 A = type(name, (), {})
2904 self.assertEqual(A.__name__, name)
2905 self.assertEqual(A.__qualname__, name)
2906 self.assertEqual(A.__module__, __name__)
2907 with self.assertRaises(ValueError):
2908 type('A\x00B', (), {})
2909 with self.assertRaises(UnicodeEncodeError):
2910 type('A\udcdcB', (), {})
2911 with self.assertRaises(TypeError):
2912 type(b'A', (), {})
2913
2914 C = type('C', (), {})
2915 for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '':
2916 with self.subTest(name=name):
2917 C.__name__ = name
2918 self.assertEqual(C.__name__, name)
2919 self.assertEqual(C.__qualname__, 'C')
2920 self.assertEqual(C.__module__, __name__)
2921
2922 A = type('C', (), {})
2923 with self.assertRaises(ValueError):
2924 A.__name__ = 'A\x00B'
2925 self.assertEqual(A.__name__, 'C')
2926 with self.assertRaises(UnicodeEncodeError):
2927 A.__name__ = 'A\udcdcB'
2928 self.assertEqual(A.__name__, 'C')
2929 with self.assertRaises(TypeError):
2930 A.__name__ = b'A'
2931 self.assertEqual(A.__name__, 'C')
2932
2933 def test_type_qualname(self):
2934 A = type('A', (), {'__qualname__': 'B.C'})
2935 self.assertEqual(A.__name__, 'A')
2936 self.assertEqual(A.__qualname__, 'B.C')
2937 self.assertEqual(A.__module__, __name__)
2938 with self.assertRaises(TypeError):
2939 type('A', (), {'__qualname__': b'B'})
2940 self.assertEqual(A.__qualname__, 'B.C')
2941
2942 A.__qualname__ = 'D.E'
2943 self.assertEqual(A.__name__, 'A')
2944 self.assertEqual(A.__qualname__, 'D.E')
2945 with self.assertRaises(TypeError):
2946 A.__qualname__ = b'B'
2947 self.assertEqual(A.__qualname__, 'D.E')
2948
2949 def test_type_firstlineno(self):
2950 A = type('A', (), {'__firstlineno__': 42})
2951 self.assertEqual(A.__name__, 'A')
2952 self.assertEqual(A.__module__, __name__)
2953 self.assertEqual(A.__dict__['__firstlineno__'], 42)
2954 A.__module__ = 'testmodule'
2955 self.assertEqual(A.__module__, 'testmodule')
2956 self.assertNotIn('__firstlineno__', A.__dict__)
2957 A.__firstlineno__ = 43
2958 self.assertEqual(A.__dict__['__firstlineno__'], 43)
2959
2960 def test_type_typeparams(self):
2961 class A[T]:
2962 pass
2963 T, = A.__type_params__
2964 self.assertIsInstance(T, typing.TypeVar)
2965 A.__type_params__ = "whatever"
2966 self.assertEqual(A.__type_params__, "whatever")
2967 with self.assertRaises(TypeError):
2968 del A.__type_params__
2969 self.assertEqual(A.__type_params__, "whatever")
2970
2971 def test_type_doc(self):
2972 for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', b'x', 42, None:
2973 A = type('A', (), {'__doc__': doc})
2974 self.assertEqual(A.__doc__, doc)
2975 with self.assertRaises(UnicodeEncodeError):
2976 type('A', (), {'__doc__': 'x\udcdcy'})
2977
2978 A = type('A', (), {})
2979 self.assertEqual(A.__doc__, None)
2980 for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', 'x\udcdcy', b'x', 42, None:
2981 A.__doc__ = doc
2982 self.assertEqual(A.__doc__, doc)
2983
2984 def test_bad_args(self):
2985 with self.assertRaises(TypeError):
2986 type()
2987 with self.assertRaises(TypeError):
2988 type('A', ())
2989 with self.assertRaises(TypeError):
2990 type('A', (), {}, ())
2991 with self.assertRaises(TypeError):
2992 type('A', (), dict={})
2993 with self.assertRaises(TypeError):
2994 type('A', [], {})
2995 with self.assertRaises(TypeError):
2996 type('A', (), types.MappingProxyType({}))
2997 with self.assertRaises(TypeError):
2998 type('A', (None,), {})
2999 with self.assertRaises(TypeError):
3000 type('A', (bool,), {})
3001 with self.assertRaises(TypeError):
3002 type('A', (int, str), {})
3003
3004 def test_bad_slots(self):
3005 with self.assertRaises(TypeError):
3006 type('A', (), {'__slots__': b'x'})
3007 with self.assertRaises(TypeError):
3008 type('A', (int,), {'__slots__': 'x'})
3009 with self.assertRaises(TypeError):
3010 type('A', (), {'__slots__': ''})
3011 with self.assertRaises(TypeError):
3012 type('A', (), {'__slots__': '42'})
3013 with self.assertRaises(TypeError):
3014 type('A', (), {'__slots__': 'x\x00y'})
3015 with self.assertRaises(ValueError):
3016 type('A', (), {'__slots__': 'x', 'x': 0})
3017 with self.assertRaises(TypeError):
3018 type('A', (), {'__slots__': ('__dict__', '__dict__')})
3019 with self.assertRaises(TypeError):
3020 type('A', (), {'__slots__': ('__weakref__', '__weakref__')})
3021
3022 class B:
3023 pass
3024 with self.assertRaises(TypeError):
3025 type('A', (B,), {'__slots__': '__dict__'})
3026 with self.assertRaises(TypeError):
3027 type('A', (B,), {'__slots__': '__weakref__'})
3028
3029 def test_namespace_order(self):
3030 # bpo-34320: namespace should preserve order
3031 od = collections.OrderedDict([('a', 1), ('b', 2)])
3032 od.move_to_end('a')
3033 expected = list(od.items())
3034
3035 C = type('C', (), od)
3036 self.assertEqual(list(C.__dict__.items())[:2], [('b', 2), ('a', 1)])
3037
3038
3039 def load_tests(loader, tests, pattern):
3040 from doctest import DocTestSuite
3041 if sys.float_repr_style == 'short':
3042 tests.addTest(DocTestSuite(builtins))
3043 return tests
3044
3045 if __name__ == "__main__":
3046 unittest.main()