Debian Codegraph @

Lib/test/test_builtin.py

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