Debian Codegraph @

lib-python/3/test/test_builtin.py

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