test_builtin.py 54.8 KB
Newer Older
1
# Python test set -- built-in functions
Guido van Rossum's avatar
Guido van Rossum committed
2

3 4
import ast
import builtins
Benjamin Peterson's avatar
Benjamin Peterson committed
5 6
import collections
import io
7
import locale
8
import os
9 10
import pickle
import platform
Benjamin Peterson's avatar
Benjamin Peterson committed
11
import random
12
import sys
13
import traceback
14 15 16
import types
import unittest
import warnings
17
from operator import neg
18
from test.support import TESTFN, unlink,  run_unittest, check_warnings
19
try:
20
    import pty, signal
21
except ImportError:
22
    pty = signal = None
Guido van Rossum's avatar
Guido van Rossum committed
23 24


25
class Squares:
Guido van Rossum's avatar
Guido van Rossum committed
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
    def __init__(self, max):
        self.max = max
        self.sofar = []

    def __len__(self): return len(self.sofar)

    def __getitem__(self, i):
        if not 0 <= i < self.max: raise IndexError
        n = len(self.sofar)
        while n <= i:
            self.sofar.append(n*n)
            n += 1
        return self.sofar[i]

class StrSquares:

    def __init__(self, max):
        self.max = max
        self.sofar = []

    def __len__(self):
        return len(self.sofar)

    def __getitem__(self, i):
        if not 0 <= i < self.max:
            raise IndexError
        n = len(self.sofar)
        while n <= i:
            self.sofar.append(str(n*n))
            n += 1
        return self.sofar[i]

class BitBucket:
    def write(self, line):
        pass

63
test_conv_no_sign = [
64 65 66 67 68 69 70 71 72 73
        ('0', 0),
        ('1', 1),
        ('9', 9),
        ('10', 10),
        ('99', 99),
        ('100', 100),
        ('314', 314),
        (' 314', 314),
        ('314 ', 314),
        ('  \t\t  314  \t\t  ', 314),
74
        (repr(sys.maxsize), sys.maxsize),
75 76 77 78 79
        ('  1x', ValueError),
        ('  1  ', 1),
        ('  1\02  ', ValueError),
        ('', ValueError),
        (' ', ValueError),
80
        ('  \t\t  ', ValueError),
81
        (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
82
        (chr(0x200), ValueError),
83 84
]

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
test_conv_sign = [
        ('0', 0),
        ('1', 1),
        ('9', 9),
        ('10', 10),
        ('99', 99),
        ('100', 100),
        ('314', 314),
        (' 314', ValueError),
        ('314 ', 314),
        ('  \t\t  314  \t\t  ', ValueError),
        (repr(sys.maxsize), sys.maxsize),
        ('  1x', ValueError),
        ('  1  ', ValueError),
        ('  1\02  ', ValueError),
        ('', ValueError),
        (' ', ValueError),
        ('  \t\t  ', ValueError),
        (str(b'\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
        (chr(0x200), ValueError),
]

107
class TestFailingBool:
108
    def __bool__(self):
109 110 111 112 113 114
        raise RuntimeError

class TestFailingIter:
    def __iter__(self):
        raise RuntimeError

115 116 117 118 119 120
def filter_char(arg):
    return ord(arg) > ord("d")

def map_char(arg):
    return chr(ord(arg)+1)

121
class BuiltinTest(unittest.TestCase):
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    # Helper to check picklability
    def check_iter_pickle(self, it, seq):
        itorg = it
        d = pickle.dumps(it)
        it = pickle.loads(d)
        self.assertEqual(type(itorg), type(it))
        self.assertEqual(list(it), seq)

        #test the iterator after dropping one from it
        it = pickle.loads(d)
        try:
            next(it)
        except StopIteration:
            return
        d = pickle.dumps(it)
        it = pickle.loads(d)
        self.assertEqual(list(it), seq[1:])
139 140 141 142 143

    def test_import(self):
        __import__('sys')
        __import__('time')
        __import__('string')
144 145
        __import__(name='sys')
        __import__(name='time', level=0)
146 147
        self.assertRaises(ImportError, __import__, 'spamspam')
        self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
148
        self.assertRaises(ValueError, __import__, '')
149
        self.assertRaises(TypeError, __import__, 'sys', name='sys')
150 151 152 153 154 155

    def test_abs(self):
        # int
        self.assertEqual(abs(0), 0)
        self.assertEqual(abs(1234), 1234)
        self.assertEqual(abs(-1234), 1234)
156
        self.assertTrue(abs(-sys.maxsize-1) > 0)
157 158 159 160 161 162
        # float
        self.assertEqual(abs(0.0), 0.0)
        self.assertEqual(abs(3.14), 3.14)
        self.assertEqual(abs(-3.14), 3.14)
        # str
        self.assertRaises(TypeError, abs, 'a')
163 164 165 166 167 168 169 170 171 172
        # bool
        self.assertEqual(abs(True), 1)
        self.assertEqual(abs(False), 0)
        # other
        self.assertRaises(TypeError, abs)
        self.assertRaises(TypeError, abs, None)
        class AbsClass(object):
            def __abs__(self):
                return -5
        self.assertEqual(abs(AbsClass()), -5)
173

174 175 176 177 178 179 180 181 182
    def test_all(self):
        self.assertEqual(all([2, 4, 6]), True)
        self.assertEqual(all([2, None, 6]), False)
        self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
        self.assertRaises(RuntimeError, all, TestFailingIter())
        self.assertRaises(TypeError, all, 10)               # Non-iterable
        self.assertRaises(TypeError, all)                   # No args
        self.assertRaises(TypeError, all, [2, 4, 6], [])    # Too many args
        self.assertEqual(all([]), True)                     # Empty iterator
183
        self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
184 185 186 187 188 189 190 191 192
        S = [50, 60]
        self.assertEqual(all(x > 42 for x in S), True)
        S = [50, 40, 60]
        self.assertEqual(all(x > 42 for x in S), False)

    def test_any(self):
        self.assertEqual(any([None, None, None]), False)
        self.assertEqual(any([None, 4, None]), True)
        self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
193
        self.assertRaises(RuntimeError, any, TestFailingIter())
194 195 196 197
        self.assertRaises(TypeError, any, 10)               # Non-iterable
        self.assertRaises(TypeError, any)                   # No args
        self.assertRaises(TypeError, any, [2, 4, 6], [])    # Too many args
        self.assertEqual(any([]), False)                    # Empty iterator
198
        self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
199 200 201 202 203
        S = [40, 60, 30]
        self.assertEqual(any(x > 42 for x in S), True)
        S = [10, 20, 30]
        self.assertEqual(any(x > 42 for x in S), False)

204 205 206 207 208 209 210 211 212 213 214 215
    def test_ascii(self):
        self.assertEqual(ascii(''), '\'\'')
        self.assertEqual(ascii(0), '0')
        self.assertEqual(ascii(()), '()')
        self.assertEqual(ascii([]), '[]')
        self.assertEqual(ascii({}), '{}')
        a = []
        a.append(a)
        self.assertEqual(ascii(a), '[[...]]')
        a = {}
        a[0] = a
        self.assertEqual(ascii(a), '{0: {...}}')
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        # Advanced checks for unicode strings
        def _check_uni(s):
            self.assertEqual(ascii(s), repr(s))
        _check_uni("'")
        _check_uni('"')
        _check_uni('"\'')
        _check_uni('\0')
        _check_uni('\r\n\t .')
        # Unprintable non-ASCII characters
        _check_uni('\x85')
        _check_uni('\u1fff')
        _check_uni('\U00012fff')
        # Lone surrogates
        _check_uni('\ud800')
        _check_uni('\udfff')
        # Issue #9804: surrogates should be joined even for printable
        # wide characters (UCS-2 builds).
        self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'")
        # All together
        s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx."
        self.assertEqual(ascii(s),
            r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""")
238

239
    def test_neg(self):
240
        x = -sys.maxsize-1
241
        self.assertTrue(isinstance(x, int))
242
        self.assertEqual(-x, sys.maxsize+1)
243

244
    def test_callable(self):
245 246 247 248 249
        self.assertTrue(callable(len))
        self.assertFalse(callable("a"))
        self.assertTrue(callable(callable))
        self.assertTrue(callable(lambda x, y: x + y))
        self.assertFalse(callable(__builtins__))
250
        def f(): pass
251 252 253
        self.assertTrue(callable(f))

        class C1:
254
            def meth(self): pass
255 256 257 258 259 260 261 262 263 264 265 266 267 268
        self.assertTrue(callable(C1))
        c = C1()
        self.assertTrue(callable(c.meth))
        self.assertFalse(callable(c))

        # __call__ is looked up on the class, not the instance
        c.__call__ = None
        self.assertFalse(callable(c))
        c.__call__ = lambda self: 0
        self.assertFalse(callable(c))
        del c.__call__
        self.assertFalse(callable(c))

        class C2(object):
269
            def __call__(self): pass
270 271 272 273 274 275 276
        c2 = C2()
        self.assertTrue(callable(c2))
        c2.__call__ = None
        self.assertTrue(callable(c2))
        class C3(C2): pass
        c3 = C3()
        self.assertTrue(callable(c3))
277 278 279 280 281 282

    def test_chr(self):
        self.assertEqual(chr(32), ' ')
        self.assertEqual(chr(65), 'A')
        self.assertEqual(chr(97), 'a')
        self.assertEqual(chr(0xff), '\xff')
283
        self.assertRaises(ValueError, chr, 1<<24)
284
        self.assertEqual(chr(sys.maxunicode),
285
                         str('\\U0010ffff'.encode("ascii"), 'unicode-escape'))
286
        self.assertRaises(TypeError, chr)
287 288 289 290 291 292 293 294 295 296 297
        self.assertEqual(chr(0x0000FFFF), "\U0000FFFF")
        self.assertEqual(chr(0x00010000), "\U00010000")
        self.assertEqual(chr(0x00010001), "\U00010001")
        self.assertEqual(chr(0x000FFFFE), "\U000FFFFE")
        self.assertEqual(chr(0x000FFFFF), "\U000FFFFF")
        self.assertEqual(chr(0x00100000), "\U00100000")
        self.assertEqual(chr(0x00100001), "\U00100001")
        self.assertEqual(chr(0x0010FFFE), "\U0010FFFE")
        self.assertEqual(chr(0x0010FFFF), "\U0010FFFF")
        self.assertRaises(ValueError, chr, -1)
        self.assertRaises(ValueError, chr, 0x00110000)
298
        self.assertRaises((OverflowError, ValueError), chr, 2**32)
299 300

    def test_cmp(self):
301
        self.assertTrue(not hasattr(builtins, "cmp"))
302 303

    def test_compile(self):
304
        compile('print(1)\n', '', 'exec')
305 306
        bom = b'\xef\xbb\xbf'
        compile(bom + b'print(1)\n', '', 'exec')
307 308 309
        compile(source='pass', filename='?', mode='exec')
        compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
        compile('pass', '?', dont_inherit=1, mode='exec')
310
        compile(memoryview(b"text"), "name", "exec")
311
        self.assertRaises(TypeError, compile)
312 313
        self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode')
        self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff)
314
        self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
315 316
        self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
                          mode='eval', source='0', filename='tmp')
317 318 319
        compile('print("\xe5")\n', '', 'exec')
        self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
        self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
320

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        # test the optimize argument

        codestr = '''def f():
        """doc"""
        try:
            assert False
        except AssertionError:
            return (True, f.__doc__)
        else:
            return (False, f.__doc__)
        '''
        def f(): """doc"""
        values = [(-1, __debug__, f.__doc__),
                  (0, True, 'doc'),
                  (1, False, 'doc'),
                  (2, False, None)]
        for optval, debugval, docstring in values:
            # test both direct compilation and compilation via AST
            codeobjs = []
            codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
            tree = ast.parse(codestr)
            codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
            for code in codeobjs:
                ns = {}
                exec(code, ns)
                rv = ns['f']()
                self.assertEqual(rv, (debugval, docstring))

349 350 351 352 353 354
    def test_delattr(self):
        sys.spam = 1
        delattr(sys, 'spam')
        self.assertRaises(TypeError, delattr)

    def test_dir(self):
355
        # dir(wrong number of arguments)
356 357
        self.assertRaises(TypeError, dir, 42, 42)

358 359
        # dir() - local scope
        local_var = 1
360
        self.assertIn('local_var', dir())
361 362

        # dir(module)
363
        self.assertIn('exit', dir(sys))
364 365 366 367 368 369 370 371

        # dir(module_with_invalid__dict__)
        class Foo(types.ModuleType):
            __dict__ = 8
        f = Foo("foo")
        self.assertRaises(TypeError, dir, f)

        # dir(type)
372 373
        self.assertIn("strip", dir(str))
        self.assertNotIn("__mro__", dir(str))
374 375 376 377 378 379 380 381

        # dir(obj)
        class Foo(object):
            def __init__(self):
                self.x = 7
                self.y = 8
                self.z = 9
        f = Foo()
382
        self.assertIn("y", dir(f))
383 384 385 386 387

        # dir(obj_no__dict__)
        class Foo(object):
            __slots__ = []
        f = Foo()
388
        self.assertIn("__repr__", dir(f))
389 390 391 392 393 394 395 396

        # dir(obj_no__class__with__dict__)
        # (an ugly trick to cause getattr(f, "__class__") to fail)
        class Foo(object):
            __slots__ = ["__class__", "__dict__"]
            def __init__(self):
                self.bar = "wow"
        f = Foo()
397 398
        self.assertNotIn("__repr__", dir(f))
        self.assertIn("bar", dir(f))
399 400 401 402 403 404

        # dir(obj_using __dir__)
        class Foo(object):
            def __dir__(self):
                return ["kan", "ga", "roo"]
        f = Foo()
405
        self.assertTrue(dir(f) == ["ga", "kan", "roo"])
406

407 408 409 410 411 412 413 414 415
        # dir(obj__dir__tuple)
        class Foo(object):
            def __dir__(self):
                return ("b", "c", "a")
        res = dir(Foo())
        self.assertIsInstance(res, list)
        self.assertTrue(res == ["a", "b", "c"])

        # dir(obj__dir__not_sequence)
416 417 418 419 420 421
        class Foo(object):
            def __dir__(self):
                return 7
        f = Foo()
        self.assertRaises(TypeError, dir, f)

422 423 424 425 426 427
        # dir(traceback)
        try:
            raise IndexError
        except:
            self.assertEqual(len(dir(sys.exc_info()[2])), 4)

428 429
        # test that object has a __dir__()
        self.assertEqual(sorted([].__dir__()), dir([]))
430

431 432 433 434 435 436
    def test_divmod(self):
        self.assertEqual(divmod(12, 7), (1, 5))
        self.assertEqual(divmod(-12, 7), (-2, 2))
        self.assertEqual(divmod(12, -7), (-2, -2))
        self.assertEqual(divmod(-12, -7), (1, -5))

437
        self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
438

439 440 441 442 443 444 445
        for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),
                                        (-3.25, 1.0, (-4.0, 0.75)),
                                        (3.25, -1.0, (-4.0, -0.75)),
                                        (-3.25, -1.0, (3.0, -0.25))]:
            result = divmod(num, denom)
            self.assertAlmostEqual(result[0], exp_result[0])
            self.assertAlmostEqual(result[1], exp_result[1])
446 447 448 449 450 451 452 453 454 455 456 457 458 459

        self.assertRaises(TypeError, divmod)

    def test_eval(self):
        self.assertEqual(eval('1+1'), 2)
        self.assertEqual(eval(' 1+1\n'), 2)
        globals = {'a': 1, 'b': 2}
        locals = {'b': 200, 'c': 300}
        self.assertEqual(eval('a', globals) , 1)
        self.assertEqual(eval('a', globals, locals), 1)
        self.assertEqual(eval('b', globals, locals), 200)
        self.assertEqual(eval('c', globals, locals), 300)
        globals = {'a': 1, 'b': 2}
        locals = {'b': 200, 'c': 300}
460 461
        bom = b'\xef\xbb\xbf'
        self.assertEqual(eval(bom + b'a', globals, locals), 1)
462
        self.assertEqual(eval('"\xe5"', globals), "\xe5")
463 464
        self.assertRaises(TypeError, eval)
        self.assertRaises(TypeError, eval, ())
465
        self.assertRaises(SyntaxError, eval, bom[:2] + b'a')
466

467 468 469 470 471
        class X:
            def __getitem__(self, key):
                raise ValueError
        self.assertRaises(ValueError, eval, "foo", {}, X())

472 473 474 475 476 477 478 479 480
    def test_general_eval(self):
        # Tests that general mappings can be used for the locals argument

        class M:
            "Test mapping interface versus possible calls from eval()."
            def __getitem__(self, key):
                if key == 'a':
                    return 12
                raise KeyError
481 482
            def keys(self):
                return list('xyz')
483 484 485 486 487 488 489 490

        m = M()
        g = globals()
        self.assertEqual(eval('a', g, m), 12)
        self.assertRaises(NameError, eval, 'b', g, m)
        self.assertEqual(eval('dir()', g, m), list('xyz'))
        self.assertEqual(eval('globals()', g, m), g)
        self.assertEqual(eval('locals()', g, m), m)
491
        self.assertRaises(TypeError, eval, 'a', m)
492 493 494 495 496
        class A:
            "Non-mapping"
            pass
        m = A()
        self.assertRaises(TypeError, eval, 'a', g, m)
497 498 499 500 501 502 503

        # Verify that dict subclasses work as well
        class D(dict):
            def __getitem__(self, key):
                if key == 'a':
                    return 12
                return dict.__getitem__(self, key)
504 505
            def keys(self):
                return list('xyz')
506 507 508 509 510 511 512 513 514 515

        d = D()
        self.assertEqual(eval('a', g, d), 12)
        self.assertRaises(NameError, eval, 'b', g, d)
        self.assertEqual(eval('dir()', g, d), list('xyz'))
        self.assertEqual(eval('globals()', g, d), g)
        self.assertEqual(eval('locals()', g, d), d)

        # Verify locals stores (used by list comps)
        eval('[locals() for i in (2,3)]', g, d)
516
        eval('[locals() for i in (2,3)]', g, collections.UserDict())
517 518 519 520 521 522

        class SpreadSheet:
            "Sample application showing nested, calculated lookups."
            _cells = {}
            def __setitem__(self, key, formula):
                self._cells[key] = formula
523
            def __getitem__(self, key):
524 525 526 527 528 529 530 531
                return eval(self._cells[key], globals(), self)

        ss = SpreadSheet()
        ss['a1'] = '5'
        ss['a2'] = 'a1*6'
        ss['a3'] = 'a2*7'
        self.assertEqual(ss['a3'], 210)

532 533 534 535 536
        # Verify that dir() catches a non-list returned by eval
        # SF bug #1004669
        class C:
            def __getitem__(self, item):
                raise KeyError(item)
537 538
            def keys(self):
                return 1 # used to be 'a' but that's no longer an error
539 540
        self.assertRaises(TypeError, eval, 'dir()', globals(), C())

541 542 543 544 545 546 547
    def test_exec(self):
        g = {}
        exec('z = 1', g)
        if '__builtins__' in g:
            del g['__builtins__']
        self.assertEqual(g, {'z': 1})

548
        exec('z = 1+1', g)
549 550 551 552 553 554
        if '__builtins__' in g:
            del g['__builtins__']
        self.assertEqual(g, {'z': 2})
        g = {}
        l = {}

555 556 557 558
        with check_warnings():
            warnings.filterwarnings("ignore", "global statement",
                    module="<string>")
            exec('global a; a = 1; b = 2', g, l)
559 560 561 562 563 564
        if '__builtins__' in g:
            del g['__builtins__']
        if '__builtins__' in l:
            del l['__builtins__']
        self.assertEqual((g, l), ({'a': 1}, {'b': 2}))

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    def test_exec_globals(self):
        code = compile("print('Hello World!')", "", "exec")
        # no builtin function
        self.assertRaisesRegex(NameError, "name 'print' is not defined",
                               exec, code, {'__builtins__': {}})
        # __builtins__ must be a mapping type
        self.assertRaises(TypeError,
                          exec, code, {'__builtins__': 123})

        # no __build_class__ function
        code = compile("class A: pass", "", "exec")
        self.assertRaisesRegex(NameError, "__build_class__ not found",
                               exec, code, {'__builtins__': {}})

        class frozendict_error(Exception):
            pass

        class frozendict(dict):
            def __setitem__(self, key, value):
                raise frozendict_error("frozendict is readonly")

        # read-only builtins
587 588 589 590
        if isinstance(__builtins__, types.ModuleType):
            frozen_builtins = frozendict(__builtins__.__dict__)
        else:
            frozen_builtins = frozendict(__builtins__)
591 592 593 594 595 596 597 598 599 600
        code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec")
        self.assertRaises(frozendict_error,
                          exec, code, {'__builtins__': frozen_builtins})

        # read-only globals
        namespace = frozendict({})
        code = compile("x=1", "test", "exec")
        self.assertRaises(frozendict_error,
                          exec, code, namespace)

601 602 603 604 605 606 607 608 609 610 611
    def test_exec_redirected(self):
        savestdout = sys.stdout
        sys.stdout = None # Whatever that cannot flush()
        try:
            # Used to raise SystemError('error return without exception set')
            exec('a')
        except NameError:
            pass
        finally:
            sys.stdout = savestdout

612
    def test_filter(self):
613 614 615 616 617
        self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))
        self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])
        self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])
        self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])
        self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])
618 619 620 621 622
        def identity(item):
            return 1
        filter(identity, Squares(5))
        self.assertRaises(TypeError, filter)
        class BadSeq(object):
Tim Peters's avatar
Tim Peters committed
623 624 625 626
            def __getitem__(self, index):
                if index<4:
                    return 42
                raise ValueError
627
        self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))
628 629
        def badfunc():
            pass
630
        self.assertRaises(TypeError, list, filter(badfunc, range(5)))
631

Walter Dörwald's avatar
Walter Dörwald committed
632
        # test bltinmodule.c::filtertuple()
633 634 635
        self.assertEqual(list(filter(None, (1, 2))), [1, 2])
        self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])
        self.assertRaises(TypeError, list, filter(42, (1, 2)))
636

637 638 639 640 641
    def test_filter_pickle(self):
        f1 = filter(filter_char, "abcdeabcde")
        f2 = filter(filter_char, "abcdeabcde")
        self.check_iter_pickle(f1, list(f2))

642
    def test_getattr(self):
643
        self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
644 645 646
        self.assertRaises(TypeError, getattr, sys, 1)
        self.assertRaises(TypeError, getattr, sys, 1, "foo")
        self.assertRaises(TypeError, getattr)
647
        self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))
648 649
        # unicode surrogates are not encodable to the default encoding (utf8)
        self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E")
650 651

    def test_hasattr(self):
652
        self.assertTrue(hasattr(sys, 'stdout'))
653 654
        self.assertRaises(TypeError, hasattr, sys, 1)
        self.assertRaises(TypeError, hasattr)
655
        self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
656

657 658
        # Check that hasattr propagates all exceptions outside of
        # AttributeError.
659 660
        class A:
            def __getattr__(self, what):
661 662
                raise SystemExit
        self.assertRaises(SystemExit, hasattr, A(), "b")
663 664
        class B:
            def __getattr__(self, what):
665 666
                raise ValueError
        self.assertRaises(ValueError, hasattr, B(), "b")
667

668 669
    def test_hash(self):
        hash(None)
670
        self.assertEqual(hash(1), hash(1))
671 672
        self.assertEqual(hash(1), hash(1.0))
        hash('spam')
673
        self.assertEqual(hash('spam'), hash(b'spam'))
674 675 676 677
        hash((0,1,2,3))
        def f(): pass
        self.assertRaises(TypeError, hash, [])
        self.assertRaises(TypeError, hash, {})
678 679 680 681
        # Bug 1536021: Allow hash to return long objects
        class X:
            def __hash__(self):
                return 2**100
682
        self.assertEqual(type(hash(X())), int)
683
        class Z(int):
684 685
            def __hash__(self):
                return self
686
        self.assertEqual(hash(Z(42)), hash(42))
687 688

    def test_hex(self):
689 690
        self.assertEqual(hex(16), '0x10')
        self.assertEqual(hex(-16), '-0x10')
691 692 693 694 695 696 697 698 699 700 701
        self.assertRaises(TypeError, hex, {})

    def test_id(self):
        id(None)
        id(1)
        id(1.0)
        id('spam')
        id((0,1,2,3))
        id([0,1,2,3])
        id({'spam': 1, 'eggs': 2, 'ham': 3})

702 703
    # Test input() later, alphabetized as if it were raw_input

704 705 706 707 708 709
    def test_iter(self):
        self.assertRaises(TypeError, iter)
        self.assertRaises(TypeError, iter, 42, 42)
        lists = [("1", "2"), ["1", "2"], "12"]
        for l in lists:
            i = iter(l)
710 711 712
            self.assertEqual(next(i), '1')
            self.assertEqual(next(i), '2')
            self.assertRaises(StopIteration, next, i)
713 714 715 716 717 718 719 720 721 722 723

    def test_isinstance(self):
        class C:
            pass
        class D(C):
            pass
        class E:
            pass
        c = C()
        d = D()
        e = E()
724 725 726 727 728
        self.assertTrue(isinstance(c, C))
        self.assertTrue(isinstance(d, C))
        self.assertTrue(not isinstance(e, C))
        self.assertTrue(not isinstance(c, D))
        self.assertTrue(not isinstance('foo', E))
729 730 731 732 733 734 735 736 737 738 739 740 741
        self.assertRaises(TypeError, isinstance, E, 'foo')
        self.assertRaises(TypeError, isinstance)

    def test_issubclass(self):
        class C:
            pass
        class D(C):
            pass
        class E:
            pass
        c = C()
        d = D()
        e = E()
742 743 744
        self.assertTrue(issubclass(D, C))
        self.assertTrue(issubclass(C, C))
        self.assertTrue(not issubclass(C, D))
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
        self.assertRaises(TypeError, issubclass, 'foo', E)
        self.assertRaises(TypeError, issubclass, E, 'foo')
        self.assertRaises(TypeError, issubclass)

    def test_len(self):
        self.assertEqual(len('123'), 3)
        self.assertEqual(len(()), 0)
        self.assertEqual(len((1, 2, 3, 4)), 4)
        self.assertEqual(len([1, 2, 3, 4]), 4)
        self.assertEqual(len({}), 0)
        self.assertEqual(len({'a':1, 'b': 2}), 2)
        class BadSeq:
            def __len__(self):
                raise ValueError
        self.assertRaises(ValueError, len, BadSeq())
760 761 762 763 764 765 766 767 768 769 770 771
        class InvalidLen:
            def __len__(self):
                return None
        self.assertRaises(TypeError, len, InvalidLen())
        class FloatLen:
            def __len__(self):
                return 4.5
        self.assertRaises(TypeError, len, FloatLen())
        class HugeLen:
            def __len__(self):
                return sys.maxsize + 1
        self.assertRaises(OverflowError, len, HugeLen())
772 773
        class NoLenMethod(object): pass
        self.assertRaises(TypeError, len, NoLenMethod())
774 775 776

    def test_map(self):
        self.assertEqual(
777
            list(map(lambda x: x*x, range(1,4))),
778 779 780 781 782 783 784 785
            [1, 4, 9]
        )
        try:
            from math import sqrt
        except ImportError:
            def sqrt(x):
                return pow(x, 0.5)
        self.assertEqual(
786
            list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),
787 788 789
            [[4.0, 2.0], [9.0, 3.0]]
        )
        self.assertEqual(
790
            list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),
791 792 793 794 795 796 797 798
            [10, 4, 6]
        )

        def plus(*v):
            accu = 0
            for i in v: accu = accu + i
            return accu
        self.assertEqual(
799
            list(map(plus, [1, 3, 7])),
800 801 802
            [1, 3, 7]
        )
        self.assertEqual(
803
            list(map(plus, [1, 3, 7], [4, 9, 2])),
804 805 806
            [1+4, 3+9, 7+2]
        )
        self.assertEqual(
807
            list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),
808 809 810
            [1+4+1, 3+9+1, 7+2+0]
        )
        self.assertEqual(
811
            list(map(int, Squares(10))),
812 813
            [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
        )
814 815 816 817 818 819
        def Max(a, b):
            if a is None:
                return b
            if b is None:
                return a
            return max(a, b)
820
        self.assertEqual(
821 822
            list(map(Max, Squares(3), Squares(2))),
            [0, 1]
823 824 825 826
        )
        self.assertRaises(TypeError, map)
        self.assertRaises(TypeError, map, lambda x: x, 42)
        class BadSeq:
827
            def __iter__(self):
828
                raise ValueError
829 830
                yield None
        self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))
831 832
        def badfunc(x):
            raise RuntimeError
833
        self.assertRaises(RuntimeError, list, map(badfunc, range(5)))
834

835 836 837 838 839
    def test_map_pickle(self):
        m1 = map(map_char, "Is this the real life?")
        m2 = map(map_char, "Is this the real life?")
        self.check_iter_pickle(m1, list(m2))

840 841 842 843 844 845
    def test_max(self):
        self.assertEqual(max('123123'), '3')
        self.assertEqual(max(1, 2, 3), 3)
        self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
        self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)

846 847 848
        self.assertEqual(max(1, 2, 3.0), 3.0)
        self.assertEqual(max(1, 2.0, 3), 3)
        self.assertEqual(max(1.0, 2, 3), 3)
849

850 851 852 853 854 855 856
        for stmt in (
            "max(key=int)",                 # no args
            "max(1, key=int)",              # single arg not iterable
            "max(1, 2, keystone=int)",      # wrong keyword
            "max(1, 2, key=int, abc=int)",  # two many keywords
            "max(1, 2, key=1)",             # keyfunc is not callable
            ):
Tim Peters's avatar
Tim Peters committed
857
            try:
858
                exec(stmt, globals())
Tim Peters's avatar
Tim Peters committed
859 860 861 862
            except TypeError:
                pass
            else:
                self.fail(stmt)
863 864 865 866 867 868 869 870 871 872 873

        self.assertEqual(max((1,), key=neg), 1)     # one elem iterable
        self.assertEqual(max((1,2), key=neg), 1)    # two elem iterable
        self.assertEqual(max(1, 2, key=neg), 1)     # two elems

        data = [random.randrange(200) for i in range(100)]
        keys = dict((elem, random.randrange(50)) for elem in data)
        f = keys.__getitem__
        self.assertEqual(max(data, key=f),
                         sorted(reversed(data), key=f)[-1])

874 875 876 877 878 879
    def test_min(self):
        self.assertEqual(min('123123'), '1')
        self.assertEqual(min(1, 2, 3), 1)
        self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
        self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)

880 881 882
        self.assertEqual(min(1, 2, 3.0), 1)
        self.assertEqual(min(1, 2.0, 3), 1)
        self.assertEqual(min(1.0, 2, 3), 1.0)
883 884 885 886 887 888 889 890 891

        self.assertRaises(TypeError, min)
        self.assertRaises(TypeError, min, 42)
        self.assertRaises(ValueError, min, ())
        class BadSeq:
            def __getitem__(self, index):
                raise ValueError
        self.assertRaises(ValueError, min, BadSeq())

892 893 894 895 896 897 898
        for stmt in (
            "min(key=int)",                 # no args
            "min(1, key=int)",              # single arg not iterable
            "min(1, 2, keystone=int)",      # wrong keyword
            "min(1, 2, key=int, abc=int)",  # two many keywords
            "min(1, 2, key=1)",             # keyfunc is not callable
            ):
Tim Peters's avatar
Tim Peters committed
899
            try:
900
                exec(stmt, globals())
Tim Peters's avatar
Tim Peters committed
901 902 903 904
            except TypeError:
                pass
            else:
                self.fail(stmt)
905 906 907 908 909 910 911 912 913 914 915

        self.assertEqual(min((1,), key=neg), 1)     # one elem iterable
        self.assertEqual(min((1,2), key=neg), 2)    # two elem iterable
        self.assertEqual(min(1, 2, key=neg), 2)     # two elems

        data = [random.randrange(200) for i in range(100)]
        keys = dict((elem, random.randrange(50)) for elem in data)
        f = keys.__getitem__
        self.assertEqual(min(data, key=f),
                         sorted(data, key=f)[0])

916 917 918 919 920 921
    def test_next(self):
        it = iter(range(2))
        self.assertEqual(next(it), 0)
        self.assertEqual(next(it), 1)
        self.assertRaises(StopIteration, next, it)
        self.assertRaises(StopIteration, next, it)
922
        self.assertEqual(next(it, 42), 42)
923 924 925 926 927 928 929 930

        class Iter(object):
            def __iter__(self):
                return self
            def __next__(self):
                raise StopIteration

        it = iter(Iter())
931
        self.assertEqual(next(it, 42), 42)
932 933 934 935 936 937 938
        self.assertRaises(StopIteration, next, it)

        def gen():
            yield 1
            return

        it = gen()
939
        self.assertEqual(next(it), 1)
940
        self.assertRaises(StopIteration, next, it)
941
        self.assertEqual(next(it, 42), 42)
942

943
    def test_oct(self):
944 945
        self.assertEqual(oct(100), '0o144')
        self.assertEqual(oct(-100), '-0o144')
946 947 948
        self.assertRaises(TypeError, oct, ())

    def write_testfile(self):
949
        # NB the first 4 lines are also used to test input, below
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
        fp = open(TESTFN, 'w')
        try:
            fp.write('1+1\n')
            fp.write('The quick brown fox jumps over the lazy dog')
            fp.write('.\n')
            fp.write('Dear John\n')
            fp.write('XXX'*100)
            fp.write('YYY'*100)
        finally:
            fp.close()

    def test_open(self):
        self.write_testfile()
        fp = open(TESTFN, 'r')
        try:
            self.assertEqual(fp.readline(4), '1+1\n')
            self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
            self.assertEqual(fp.readline(4), 'Dear')
            self.assertEqual(fp.readline(100), ' John\n')
            self.assertEqual(fp.read(300), 'XXX'*100)
            self.assertEqual(fp.read(1000), 'YYY'*100)
        finally:
            fp.close()
973
            unlink(TESTFN)
974

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
    def test_open_default_encoding(self):
        old_environ = dict(os.environ)
        try:
            # try to get a user preferred encoding different than the current
            # locale encoding to check that open() uses the current locale
            # encoding and not the user preferred encoding
            for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):
                if key in os.environ:
                    del os.environ[key]

            self.write_testfile()
            current_locale_encoding = locale.getpreferredencoding(False)
            fp = open(TESTFN, 'w')
            try:
                self.assertEqual(fp.encoding, current_locale_encoding)
            finally:
                fp.close()
992
                unlink(TESTFN)
993 994 995 996
        finally:
            os.environ.clear()
            os.environ.update(old_environ)

997 998 999 1000
    def test_ord(self):
        self.assertEqual(ord(' '), 32)
        self.assertEqual(ord('A'), 65)
        self.assertEqual(ord('a'), 97)
1001 1002 1003 1004 1005 1006 1007 1008 1009
        self.assertEqual(ord('\x80'), 128)
        self.assertEqual(ord('\xff'), 255)

        self.assertEqual(ord(b' '), 32)
        self.assertEqual(ord(b'A'), 65)
        self.assertEqual(ord(b'a'), 97)
        self.assertEqual(ord(b'\x80'), 128)
        self.assertEqual(ord(b'\xff'), 255)

1010
        self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)
1011 1012
        self.assertRaises(TypeError, ord, 42)

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
        self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)
        self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF)
        self.assertEqual(ord("\U00010000"), 0x00010000)
        self.assertEqual(ord("\U00010001"), 0x00010001)
        self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE)
        self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF)
        self.assertEqual(ord("\U00100000"), 0x00100000)
        self.assertEqual(ord("\U00100001"), 0x00100001)
        self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE)
        self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF)

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    def test_pow(self):
        self.assertEqual(pow(0,0), 1)
        self.assertEqual(pow(0,1), 0)
        self.assertEqual(pow(1,0), 1)
        self.assertEqual(pow(1,1), 1)

        self.assertEqual(pow(2,0), 1)
        self.assertEqual(pow(2,10), 1024)
        self.assertEqual(pow(2,20), 1024*1024)
        self.assertEqual(pow(2,30), 1024*1024*1024)

        self.assertEqual(pow(-2,0), 1)
        self.assertEqual(pow(-2,1), -2)
        self.assertEqual(pow(-2,2), 4)
        self.assertEqual(pow(-2,3), -8)

        self.assertAlmostEqual(pow(0.,0), 1.)
        self.assertAlmostEqual(pow(0.,1), 0.)
        self.assertAlmostEqual(pow(1.,0), 1.)
        self.assertAlmostEqual(pow(1.,1), 1.)

        self.assertAlmostEqual(pow(2.,0), 1.)
        self.assertAlmostEqual(pow(2.,10), 1024.)
        self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
        self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)

        self.assertAlmostEqual(pow(-2.,0), 1.)
        self.assertAlmostEqual(pow(-2.,1), -2.)
        self.assertAlmostEqual(pow(-2.,2), 4.)
        self.assertAlmostEqual(pow(-2.,3), -8.)

1055 1056 1057
        for x in 2, 2.0:
            for y in 10, 10.0:
                for z in 1000, 1000.0:
1058 1059 1060 1061 1062 1063 1064
                    if isinstance(x, float) or \
                       isinstance(y, float) or \
                       isinstance(z, float):
                        self.assertRaises(TypeError, pow, x, y, z)
                    else:
                        self.assertAlmostEqual(pow(x, y, z), 24.0)

1065 1066 1067
        self.assertAlmostEqual(pow(-1, 0.5), 1j)
        self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)

1068 1069
        self.assertRaises(TypeError, pow, -1, -2, 3)
        self.assertRaises(ValueError, pow, 1, 2, 0)
1070 1071 1072

        self.assertRaises(TypeError, pow)

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    def test_input(self):
        self.write_testfile()
        fp = open(TESTFN, 'r')
        savestdin = sys.stdin
        savestdout = sys.stdout # Eats the echo
        try:
            sys.stdin = fp
            sys.stdout = BitBucket()
            self.assertEqual(input(), "1+1")
            self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')
            self.assertEqual(input('testing\n'), 'Dear John')

            # SF 1535165: don't segfault on closed stdin
            # sys.stdout must be a regular file for triggering
            sys.stdout = savestdout
            sys.stdin.close()
            self.assertRaises(ValueError, input)

            sys.stdout = BitBucket()
1092
            sys.stdin = io.StringIO("NULL\0")
1093
            self.assertRaises(TypeError, input, 42, 42)
1094
            sys.stdin = io.StringIO("    'whitespace'")
1095
            self.assertEqual(input(), "    'whitespace'")
1096
            sys.stdin = io.StringIO()
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
            self.assertRaises(EOFError, input)

            del sys.stdout
            self.assertRaises(RuntimeError, input, 'prompt')
            del sys.stdin
            self.assertRaises(RuntimeError, input, 'prompt')
        finally:
            sys.stdin = savestdin
            sys.stdout = savestdout
            fp.close()
            unlink(TESTFN)

1109
    @unittest.skipUnless(pty, "the pty and signal modules must be available")
1110
    def check_input_tty(self, prompt, terminal_input, stdio_encoding=None):
1111 1112
        if not sys.stdin.isatty() or not sys.stdout.isatty():
            self.skipTest("stdin and stdout must be ttys")
1113 1114 1115 1116 1117 1118 1119 1120 1121
        r, w = os.pipe()
        try:
            pid, fd = pty.fork()
        except (OSError, AttributeError) as e:
            os.close(r)
            os.close(w)
            self.skipTest("pty.fork() raised {}".format(e))
        if pid == 0:
            # Child
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
            try:
                # Make sure we don't get stuck if there's a problem
                signal.alarm(2)
                os.close(r)
                # Check the error handlers are accounted for
                if stdio_encoding:
                    sys.stdin = io.TextIOWrapper(sys.stdin.detach(),
                                                 encoding=stdio_encoding,
                                                 errors='surrogateescape')
                    sys.stdout = io.TextIOWrapper(sys.stdout.detach(),
                                                  encoding=stdio_encoding,
                                                  errors='replace')
                with open(w, "w") as wpipe:
1135 1136
                    print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe)
                    print(ascii(input(prompt)), file=wpipe)
1137 1138 1139 1140 1141
            except:
                traceback.print_exc()
            finally:
                # We don't want to return to unittest...
                os._exit(0)
1142 1143 1144 1145 1146 1147 1148 1149
        # Parent
        os.close(w)
        os.write(fd, terminal_input + b"\r\n")
        # Get results from the pipe
        with open(r, "r") as rpipe:
            lines = []
            while True:
                line = rpipe.readline().strip()
1150 1151
                if line == "":
                    # The other end was closed => the child exited
1152 1153
                    break
                lines.append(line)
1154 1155 1156 1157 1158 1159 1160
        # Check the result was got and corresponds to the user's terminal input
        if len(lines) != 2:
            # Something went wrong, try to get at stderr
            with open(fd, "r", encoding="ascii", errors="ignore") as child_output:
                self.fail("got %d lines in pipe but expected 2, child output was:\n%s"
                          % (len(lines), child_output.read()))
        os.close(fd)
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
        # Check we did exercise the GNU readline path
        self.assertIn(lines[0], {'tty = True', 'tty = False'})
        if lines[0] != 'tty = True':
            self.skipTest("standard IO in should have been a tty")
        input_result = eval(lines[1])   # ascii() -> eval() roundtrip
        if stdio_encoding:
            expected = terminal_input.decode(stdio_encoding, 'surrogateescape')
        else:
            expected = terminal_input.decode(sys.stdin.encoding)  # what else?
        self.assertEqual(input_result, expected)

    def test_input_tty(self):
        # Test input() functionality when wired to a tty (the code path
        # is different and invokes GNU readline if available).
        self.check_input_tty("prompt", b"quux")

    def test_input_tty_non_ascii(self):
        # Check stdin/stdout encoding is used when invoking GNU readline
        self.check_input_tty("prompté", b"quux\xe9", "utf-8")

    def test_input_tty_non_ascii_unicode_errors(self):
        # Check stdin/stdout error handler is used when invoking GNU readline
        self.check_input_tty("prompté", b"quux\xe9", "ascii")

1185 1186
    # test_int(): see test_int.py for tests of built-in function int().

1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
    def test_repr(self):
        self.assertEqual(repr(''), '\'\'')
        self.assertEqual(repr(0), '0')
        self.assertEqual(repr(()), '()')
        self.assertEqual(repr([]), '[]')
        self.assertEqual(repr({}), '{}')
        a = []
        a.append(a)
        self.assertEqual(repr(a), '[[...]]')
        a = {}
        a[0] = a
        self.assertEqual(repr(a), '{0: {...}}')

    def test_round(self):
        self.assertEqual(round(0.0), 0.0)
1202
        self.assertEqual(type(round(0.0)), int)
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
        self.assertEqual(round(1.0), 1.0)
        self.assertEqual(round(10.0), 10.0)
        self.assertEqual(round(1000000000.0), 1000000000.0)
        self.assertEqual(round(1e20), 1e20)

        self.assertEqual(round(-1.0), -1.0)
        self.assertEqual(round(-10.0), -10.0)
        self.assertEqual(round(-1000000000.0), -1000000000.0)
        self.assertEqual(round(-1e20), -1e20)

        self.assertEqual(round(0.1), 0.0)
        self.assertEqual(round(1.1), 1.0)
        self.assertEqual(round(10.1), 10.0)
        self.assertEqual(round(1000000000.1), 1000000000.0)

        self.assertEqual(round(-1.1), -1.0)
        self.assertEqual(round(-10.1), -10.0)
        self.assertEqual(round(-1000000000.1), -1000000000.0)

        self.assertEqual(round(0.9), 1.0)
        self.assertEqual(round(9.9), 10.0)
        self.assertEqual(round(999999999.9), 1000000000.0)

        self.assertEqual(round(-0.9), -1.0)
        self.assertEqual(round(-9.9), -10.0)
        self.assertEqual(round(-999999999.9), -1000000000.0)

        self.assertEqual(round(-8.0, -1), -10.0)
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
        self.assertEqual(type(round(-8.0, -1)), float)

        self.assertEqual(type(round(-8.0, 0)), float)
        self.assertEqual(type(round(-8.0, 1)), float)

        # Check even / odd rounding behaviour
        self.assertEqual(round(5.5), 6)
        self.assertEqual(round(6.5), 6)
        self.assertEqual(round(-5.5), -6)
        self.assertEqual(round(-6.5), -6)

        # Check behavior on ints
        self.assertEqual(round(0), 0)
        self.assertEqual(round(8), 8)
        self.assertEqual(round(-8), -8)
        self.assertEqual(type(round(0)), int)
1247 1248 1249
        self.assertEqual(type(round(-8, -1)), int)
        self.assertEqual(type(round(-8, 0)), int)
        self.assertEqual(type(round(-8, 1)), int)
1250

1251 1252 1253
        # test new kwargs
        self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)

1254 1255
        self.assertRaises(TypeError, round)

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
        # test generic rounding delegation for reals
        class TestRound:
            def __round__(self):
                return 23

        class TestNoRound:
            pass

        self.assertEqual(round(TestRound()), 23)

        self.assertRaises(TypeError, round, 1, 2, 3)
        self.assertRaises(TypeError, round, TestNoRound())

1269 1270 1271 1272 1273
        t = TestNoRound()
        t.__round__ = lambda *args: args
        self.assertRaises(TypeError, round, t)
        self.assertRaises(TypeError, round, t, 0)

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
    # Some versions of glibc for alpha have a bug that affects
    # float -> integer rounding (floor, ceil, rint, round) for
    # values in the range [2**52, 2**53).  See:
    #
    #   http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
    #
    # We skip this test on Linux/alpha if it would fail.
    linux_alpha = (platform.system().startswith('Linux') and
                   platform.machine().startswith('alpha'))
    system_round_bug = round(5e15+1) != 5e15+1
    @unittest.skipIf(linux_alpha and system_round_bug,
                     "test will fail;  failure is probably due to a "
                     "buggy system round function")
    def test_round_large(self):
        # Issue #1869: integral floats should remain unchanged
        self.assertEqual(round(5e15-1), 5e15-1)
        self.assertEqual(round(5e15), 5e15)
        self.assertEqual(round(5e15+1), 5e15+1)
        self.assertEqual(round(5e15+2), 5e15+2)
        self.assertEqual(round(5e15+3), 5e15+3)

1295
    def test_setattr(self):
Tim Peters's avatar
Tim Peters committed
1296 1297 1298 1299
        setattr(sys, 'spam', 1)
        self.assertEqual(sys.spam, 1)
        self.assertRaises(TypeError, setattr, sys, 1, 'spam')
        self.assertRaises(TypeError, setattr)
1300

1301
    # test_str(): see test_unicode.py and test_bytes.py for str() tests.
1302

1303 1304
    def test_sum(self):
        self.assertEqual(sum([]), 0)
1305 1306
        self.assertEqual(sum(list(range(2,8))), 27)
        self.assertEqual(sum(iter(list(range(2,8)))), 27)
1307 1308 1309 1310 1311 1312 1313 1314
        self.assertEqual(sum(Squares(10)), 285)
        self.assertEqual(sum(iter(Squares(10))), 285)
        self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])

        self.assertRaises(TypeError, sum)
        self.assertRaises(TypeError, sum, 42)
        self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
        self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
1315 1316 1317
        self.assertRaises(TypeError, sum, [b'a', b'c'], b'')
        values = [bytearray(b'a'), bytearray(b'b')]
        self.assertRaises(TypeError, sum, values, bytearray(b''))
1318 1319 1320 1321 1322 1323 1324 1325 1326
        self.assertRaises(TypeError, sum, [[1], [2], [3]])
        self.assertRaises(TypeError, sum, [{2:3}])
        self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})

        class BadSeq:
            def __getitem__(self, index):
                raise ValueError
        self.assertRaises(ValueError, sum, BadSeq())

1327 1328 1329 1330
        empty = []
        sum(([x] for x in range(10)), empty)
        self.assertEqual(empty, [])

1331 1332 1333 1334
    def test_type(self):
        self.assertEqual(type(''),  type('123'))
        self.assertNotEqual(type(''), type(()))

Guido van Rossum's avatar
Guido van Rossum committed
1335 1336 1337
    # We don't want self in vars(), so these are static methods

    @staticmethod
1338 1339 1340
    def get_vars_f0():
        return vars()

Guido van Rossum's avatar
Guido van Rossum committed
1341
    @staticmethod
1342 1343 1344 1345 1346 1347
    def get_vars_f2():
        BuiltinTest.get_vars_f0()
        a = 1
        b = 2
        return vars()

1348 1349 1350 1351 1352
    class C_get_vars(object):
        def getDict(self):
            return {'a':2}
        __dict__ = property(fget=getDict)

1353
    def test_vars(self):
1354 1355
        self.assertEqual(set(vars()), set(dir()))
        self.assertEqual(set(vars(sys)), set(dir(sys)))
1356 1357 1358 1359
        self.assertEqual(self.get_vars_f0(), {})
        self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
        self.assertRaises(TypeError, vars, 42, 42)
        self.assertRaises(TypeError, vars, 42)
1360
        self.assertEqual(vars(self.C_get_vars()), {'a':2})
1361 1362 1363 1364 1365

    def test_zip(self):
        a = (1, 2, 3)
        b = (4, 5, 6)
        t = [(1, 4), (2, 5), (3, 6)]
1366
        self.assertEqual(list(zip(a, b)), t)
1367
        b = [4, 5, 6]
1368
        self.assertEqual(list(zip(a, b)), t)
1369
        b = (4, 5, 6, 7)
1370
        self.assertEqual(list(zip(a, b)), t)
1371 1372 1373 1374
        class I:
            def __getitem__(self, i):
                if i < 0 or i > 2: raise IndexError
                return i + 4
1375 1376 1377
        self.assertEqual(list(zip(a, I())), t)
        self.assertEqual(list(zip()), [])
        self.assertEqual(list(zip(*[])), [])
1378 1379 1380 1381
        self.assertRaises(TypeError, zip, None)
        class G:
            pass
        self.assertRaises(TypeError, zip, a, G())
1382
        self.assertRaises(RuntimeError, zip, a, TestFailingIter())
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393

        # Make sure zip doesn't try to allocate a billion elements for the
        # result list when one of its arguments doesn't say how long it is.
        # A MemoryError is the most likely failure mode.
        class SequenceWithoutALength:
            def __getitem__(self, i):
                if i == 5:
                    raise IndexError
                else:
                    return i
        self.assertEqual(
1394
            list(zip(SequenceWithoutALength(), range(2**30))),
1395 1396 1397 1398 1399 1400 1401 1402 1403
            list(enumerate(range(5)))
        )

        class BadSeq:
            def __getitem__(self, i):
                if i == 5:
                    raise ValueError
                else:
                    return i
1404
        self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))
1405

1406 1407 1408 1409 1410 1411 1412
    def test_zip_pickle(self):
        a = (1, 2, 3)
        b = (4, 5, 6)
        t = [(1, 4), (2, 5), (3, 6)]
        z1 = zip(a, b)
        self.check_iter_pickle(z1, t)

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
    def test_format(self):
        # Test the basic machinery of the format() builtin.  Don't test
        #  the specifics of the various formatters
        self.assertEqual(format(3, ''), '3')

        # Returns some classes to use for various tests.  There's
        #  an old-style version, and a new-style version
        def classes_new():
            class A(object):
                def __init__(self, x):
                    self.x = x
                def __format__(self, format_spec):
                    return str(self.x) + format_spec
            class DerivedFromA(A):
                pass

            class Simple(object): pass
            class DerivedFromSimple(Simple):
                def __init__(self, x):
                    self.x = x
                def __format__(self, format_spec):
                    return str(self.x) + format_spec
            class DerivedFromSimple2(DerivedFromSimple): pass
            return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2

        def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
            self.assertEqual(format(A(3), 'spec'), '3spec')
            self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
            self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
            self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
                             '10abcdef')

        class_test(*classes_new())

        def empty_format_spec(value):
            # test that:
            #  format(x, '') == str(x)
            #  format(x) == str(x)
            self.assertEqual(format(value, ""), str(value))
            self.assertEqual(format(value), str(value))

        # for builtin types, format(x, "") == str(x)
        empty_format_spec(17**13)
        empty_format_spec(1.0)
        empty_format_spec(3.1415e104)
        empty_format_spec(-3.1415e104)
        empty_format_spec(3.1415e-104)
        empty_format_spec(-3.1415e-104)
        empty_format_spec(object)
        empty_format_spec(None)

        # TypeError because self.__format__ returns the wrong type
        class BadFormatResult:
            def __format__(self, format_spec):
                return 1.0
        self.assertRaises(TypeError, format, BadFormatResult(), "")

        # TypeError because format_spec is not unicode or str
        self.assertRaises(TypeError, format, object(), 4)
        self.assertRaises(TypeError, format, object(), object())

        # tests for object.__format__ really belong elsewhere, but
        #  there's no good place to put them
        x = object().__format__('')
        self.assertTrue(x.startswith('<object object at'))

        # first argument to object.__format__ must be string
        self.assertRaises(TypeError, object().__format__, 3)
        self.assertRaises(TypeError, object().__format__, object())
        self.assertRaises(TypeError, object().__format__, None)

        # --------------------------------------------------------------------
        # Issue #7994: object.__format__ with a non-empty format string is
1486
        #  deprecated
1487 1488 1489
        def test_deprecated_format_string(obj, fmt_str, should_raise):
            if should_raise:
                self.assertRaises(TypeError, format, obj, fmt_str)
1490
            else:
1491
                format(obj, fmt_str)
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516

        fmt_strs = ['', 's']

        class A:
            def __format__(self, fmt_str):
                return format('', fmt_str)

        for fmt_str in fmt_strs:
            test_deprecated_format_string(A(), fmt_str, False)

        class B:
            pass

        class C(object):
            pass

        for cls in [object, B, C]:
            for fmt_str in fmt_strs:
                test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0)
        # --------------------------------------------------------------------

        # make sure we can take a subclass of str as a format spec
        class DerivedFromStr(str): pass
        self.assertEqual(format(0, DerivedFromStr('10')), '         0')

Christian Heimes's avatar
Christian Heimes committed
1517 1518 1519 1520 1521 1522 1523 1524 1525
    def test_bin(self):
        self.assertEqual(bin(0), '0b0')
        self.assertEqual(bin(1), '0b1')
        self.assertEqual(bin(-1), '-0b1')
        self.assertEqual(bin(2**65), '0b1' + '0' * 65)
        self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
        self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
        self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)

1526 1527 1528 1529 1530
    def test_bytearray_translate(self):
        x = bytearray(b"abc")
        self.assertRaises(ValueError, x.translate, b"1", 1)
        self.assertRaises(TypeError, x.translate, b"1"*256, 1)

1531
    def test_construct_singletons(self):
1532
        for const in None, Ellipsis, NotImplemented:
1533 1534 1535 1536 1537
            tp = type(const)
            self.assertIs(tp(), const)
            self.assertRaises(TypeError, tp, 1, 2)
            self.assertRaises(TypeError, tp, a=1, b=2)

1538 1539 1540
class TestSorted(unittest.TestCase):

    def test_basic(self):
1541
        data = list(range(100))
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
        copy = data[:]
        random.shuffle(copy)
        self.assertEqual(data, sorted(copy))
        self.assertNotEqual(data, copy)

        data.reverse()
        random.shuffle(copy)
        self.assertEqual(data, sorted(copy, key=lambda x: -x))
        self.assertNotEqual(data, copy)
        random.shuffle(copy)
        self.assertEqual(data, sorted(copy, reverse=1))
        self.assertNotEqual(data, copy)

    def test_inputtypes(self):
        s = 'abracadabra'
1557
        types = [list, tuple, str]
1558
        for T in types:
1559 1560
            self.assertEqual(sorted(s), sorted(T(s)))

1561 1562
        s = ''.join(set(s))  # unique letters only
        types = [str, set, frozenset, list, tuple, dict.fromkeys]
1563
        for T in types:
1564 1565 1566 1567 1568 1569
            self.assertEqual(sorted(s), sorted(T(s)))

    def test_baddecorator(self):
        data = 'The quick Brown fox Jumped over The lazy Dog'.split()
        self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)

1570
def test_main(verbose=None):
1571
    test_classes = (BuiltinTest, TestSorted)
1572 1573 1574 1575 1576 1577 1578

    run_unittest(*test_classes)

    # verify reference counting
    if verbose and hasattr(sys, "gettotalrefcount"):
        import gc
        counts = [None] * 5
1579
        for i in range(len(counts)):
1580 1581 1582
            run_unittest(*test_classes)
            gc.collect()
            counts[i] = sys.gettotalrefcount()
1583
        print(counts)
1584

1585 1586

if __name__ == "__main__":
1587
    test_main(verbose=True)