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