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