move sections
[python/dscho.git] / Lib / test / test_builtin.py
blob69b6ae4196c1ac4df6c1421aea285e63d0e616bd
1 # Python test set -- built-in functions
3 import platform
4 import unittest
5 from test.test_support import fcmp, have_unicode, TESTFN, unlink, \
6 run_unittest, check_py3k_warnings
7 import warnings
8 from operator import neg
10 import sys, cStringIO, random, UserDict
12 # count the number of test runs.
13 # used to skip running test_execfile() multiple times
14 # and to create unique strings to intern in test_intern()
15 numruns = 0
17 class Squares:
19 def __init__(self, max):
20 self.max = max
21 self.sofar = []
23 def __len__(self): return len(self.sofar)
25 def __getitem__(self, i):
26 if not 0 <= i < self.max: raise IndexError
27 n = len(self.sofar)
28 while n <= i:
29 self.sofar.append(n*n)
30 n += 1
31 return self.sofar[i]
33 class StrSquares:
35 def __init__(self, max):
36 self.max = max
37 self.sofar = []
39 def __len__(self):
40 return len(self.sofar)
42 def __getitem__(self, i):
43 if not 0 <= i < self.max:
44 raise IndexError
45 n = len(self.sofar)
46 while n <= i:
47 self.sofar.append(str(n*n))
48 n += 1
49 return self.sofar[i]
51 class BitBucket:
52 def write(self, line):
53 pass
56 class TestFailingBool:
57 def __nonzero__(self):
58 raise RuntimeError
60 class TestFailingIter:
61 def __iter__(self):
62 raise RuntimeError
64 class BuiltinTest(unittest.TestCase):
66 def test_import(self):
67 __import__('sys')
68 __import__('time')
69 __import__('string')
70 __import__(name='sys')
71 __import__(name='time', level=0)
72 self.assertRaises(ImportError, __import__, 'spamspam')
73 self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
74 self.assertRaises(ValueError, __import__, '')
75 self.assertRaises(TypeError, __import__, 'sys', name='sys')
77 def test_abs(self):
78 # int
79 self.assertEqual(abs(0), 0)
80 self.assertEqual(abs(1234), 1234)
81 self.assertEqual(abs(-1234), 1234)
82 self.assertTrue(abs(-sys.maxint-1) > 0)
83 # float
84 self.assertEqual(abs(0.0), 0.0)
85 self.assertEqual(abs(3.14), 3.14)
86 self.assertEqual(abs(-3.14), 3.14)
87 # long
88 self.assertEqual(abs(0L), 0L)
89 self.assertEqual(abs(1234L), 1234L)
90 self.assertEqual(abs(-1234L), 1234L)
91 # str
92 self.assertRaises(TypeError, abs, 'a')
93 # bool
94 self.assertEqual(abs(True), 1)
95 self.assertEqual(abs(False), 0)
96 # other
97 self.assertRaises(TypeError, abs)
98 self.assertRaises(TypeError, abs, None)
99 class AbsClass(object):
100 def __abs__(self):
101 return -5
102 self.assertEqual(abs(AbsClass()), -5)
104 def test_all(self):
105 self.assertEqual(all([2, 4, 6]), True)
106 self.assertEqual(all([2, None, 6]), False)
107 self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
108 self.assertRaises(RuntimeError, all, TestFailingIter())
109 self.assertRaises(TypeError, all, 10) # Non-iterable
110 self.assertRaises(TypeError, all) # No args
111 self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args
112 self.assertEqual(all([]), True) # Empty iterator
113 S = [50, 60]
114 self.assertEqual(all(x > 42 for x in S), True)
115 S = [50, 40, 60]
116 self.assertEqual(all(x > 42 for x in S), False)
118 def test_any(self):
119 self.assertEqual(any([None, None, None]), False)
120 self.assertEqual(any([None, 4, None]), True)
121 self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
122 self.assertRaises(RuntimeError, all, TestFailingIter())
123 self.assertRaises(TypeError, any, 10) # Non-iterable
124 self.assertRaises(TypeError, any) # No args
125 self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args
126 self.assertEqual(any([]), False) # Empty iterator
127 S = [40, 60, 30]
128 self.assertEqual(any(x > 42 for x in S), True)
129 S = [10, 20, 30]
130 self.assertEqual(any(x > 42 for x in S), False)
132 def test_neg(self):
133 x = -sys.maxint-1
134 self.assertTrue(isinstance(x, int))
135 self.assertEqual(-x, sys.maxint+1)
137 def test_apply(self):
138 def f0(*args):
139 self.assertEqual(args, ())
140 def f1(a1):
141 self.assertEqual(a1, 1)
142 def f2(a1, a2):
143 self.assertEqual(a1, 1)
144 self.assertEqual(a2, 2)
145 def f3(a1, a2, a3):
146 self.assertEqual(a1, 1)
147 self.assertEqual(a2, 2)
148 self.assertEqual(a3, 3)
149 apply(f0, ())
150 apply(f1, (1,))
151 apply(f2, (1, 2))
152 apply(f3, (1, 2, 3))
154 # A PyCFunction that takes only positional parameters should allow an
155 # empty keyword dictionary to pass without a complaint, but raise a
156 # TypeError if the dictionary is non-empty.
157 apply(id, (1,), {})
158 self.assertRaises(TypeError, apply, id, (1,), {"foo": 1})
159 self.assertRaises(TypeError, apply)
160 self.assertRaises(TypeError, apply, id, 42)
161 self.assertRaises(TypeError, apply, id, (42,), 42)
163 def test_callable(self):
164 self.assertTrue(callable(len))
165 self.assertFalse(callable("a"))
166 self.assertTrue(callable(callable))
167 self.assertTrue(callable(lambda x, y: x + y))
168 self.assertFalse(callable(__builtins__))
169 def f(): pass
170 self.assertTrue(callable(f))
172 class Classic:
173 def meth(self): pass
174 self.assertTrue(callable(Classic))
175 c = Classic()
176 self.assertTrue(callable(c.meth))
177 self.assertFalse(callable(c))
179 class NewStyle(object):
180 def meth(self): pass
181 self.assertTrue(callable(NewStyle))
182 n = NewStyle()
183 self.assertTrue(callable(n.meth))
184 self.assertFalse(callable(n))
186 # Classic and new-style classes evaluate __call__() differently
187 c.__call__ = None
188 self.assertTrue(callable(c))
189 del c.__call__
190 self.assertFalse(callable(c))
191 n.__call__ = None
192 self.assertFalse(callable(n))
193 del n.__call__
194 self.assertFalse(callable(n))
196 class N2(object):
197 def __call__(self): pass
198 n2 = N2()
199 self.assertTrue(callable(n2))
200 class N3(N2): pass
201 n3 = N3()
202 self.assertTrue(callable(n3))
204 def test_chr(self):
205 self.assertEqual(chr(32), ' ')
206 self.assertEqual(chr(65), 'A')
207 self.assertEqual(chr(97), 'a')
208 self.assertEqual(chr(0xff), '\xff')
209 self.assertRaises(ValueError, chr, 256)
210 self.assertRaises(TypeError, chr)
212 def test_cmp(self):
213 self.assertEqual(cmp(-1, 1), -1)
214 self.assertEqual(cmp(1, -1), 1)
215 self.assertEqual(cmp(1, 1), 0)
216 # verify that circular objects are not handled
217 a = []; a.append(a)
218 b = []; b.append(b)
219 from UserList import UserList
220 c = UserList(); c.append(c)
221 self.assertRaises(RuntimeError, cmp, a, b)
222 self.assertRaises(RuntimeError, cmp, b, c)
223 self.assertRaises(RuntimeError, cmp, c, a)
224 self.assertRaises(RuntimeError, cmp, a, c)
225 # okay, now break the cycles
226 a.pop(); b.pop(); c.pop()
227 self.assertRaises(TypeError, cmp)
229 def test_coerce(self):
230 self.assertTrue(not fcmp(coerce(1, 1.1), (1.0, 1.1)))
231 self.assertEqual(coerce(1, 1L), (1L, 1L))
232 self.assertTrue(not fcmp(coerce(1L, 1.1), (1.0, 1.1)))
233 self.assertRaises(TypeError, coerce)
234 class BadNumber:
235 def __coerce__(self, other):
236 raise ValueError
237 self.assertRaises(ValueError, coerce, 42, BadNumber())
238 self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000))
240 def test_compile(self):
241 compile('print 1\n', '', 'exec')
242 bom = '\xef\xbb\xbf'
243 compile(bom + 'print 1\n', '', 'exec')
244 compile(source='pass', filename='?', mode='exec')
245 compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
246 compile('pass', '?', dont_inherit=1, mode='exec')
247 self.assertRaises(TypeError, compile)
248 self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
249 self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
250 self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
251 self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
252 mode='eval', source='0', filename='tmp')
253 if have_unicode:
254 compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
255 self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
256 self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
259 def test_delattr(self):
260 import sys
261 sys.spam = 1
262 delattr(sys, 'spam')
263 self.assertRaises(TypeError, delattr)
265 def test_dir(self):
266 # dir(wrong number of arguments)
267 self.assertRaises(TypeError, dir, 42, 42)
269 # dir() - local scope
270 local_var = 1
271 self.assertIn('local_var', dir())
273 # dir(module)
274 import sys
275 self.assertIn('exit', dir(sys))
277 # dir(module_with_invalid__dict__)
278 import types
279 class Foo(types.ModuleType):
280 __dict__ = 8
281 f = Foo("foo")
282 self.assertRaises(TypeError, dir, f)
284 # dir(type)
285 self.assertIn("strip", dir(str))
286 self.assertNotIn("__mro__", dir(str))
288 # dir(obj)
289 class Foo(object):
290 def __init__(self):
291 self.x = 7
292 self.y = 8
293 self.z = 9
294 f = Foo()
295 self.assertIn("y", dir(f))
297 # dir(obj_no__dict__)
298 class Foo(object):
299 __slots__ = []
300 f = Foo()
301 self.assertIn("__repr__", dir(f))
303 # dir(obj_no__class__with__dict__)
304 # (an ugly trick to cause getattr(f, "__class__") to fail)
305 class Foo(object):
306 __slots__ = ["__class__", "__dict__"]
307 def __init__(self):
308 self.bar = "wow"
309 f = Foo()
310 self.assertNotIn("__repr__", dir(f))
311 self.assertIn("bar", dir(f))
313 # dir(obj_using __dir__)
314 class Foo(object):
315 def __dir__(self):
316 return ["kan", "ga", "roo"]
317 f = Foo()
318 self.assertTrue(dir(f) == ["ga", "kan", "roo"])
320 # dir(obj__dir__not_list)
321 class Foo(object):
322 def __dir__(self):
323 return 7
324 f = Foo()
325 self.assertRaises(TypeError, dir, f)
327 def test_divmod(self):
328 self.assertEqual(divmod(12, 7), (1, 5))
329 self.assertEqual(divmod(-12, 7), (-2, 2))
330 self.assertEqual(divmod(12, -7), (-2, -2))
331 self.assertEqual(divmod(-12, -7), (1, -5))
333 self.assertEqual(divmod(12L, 7L), (1L, 5L))
334 self.assertEqual(divmod(-12L, 7L), (-2L, 2L))
335 self.assertEqual(divmod(12L, -7L), (-2L, -2L))
336 self.assertEqual(divmod(-12L, -7L), (1L, -5L))
338 self.assertEqual(divmod(12, 7L), (1, 5L))
339 self.assertEqual(divmod(-12, 7L), (-2, 2L))
340 self.assertEqual(divmod(12L, -7), (-2L, -2))
341 self.assertEqual(divmod(-12L, -7), (1L, -5))
343 self.assertEqual(divmod(-sys.maxint-1, -1),
344 (sys.maxint+1, 0))
346 self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
347 self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
348 self.assertTrue(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
349 self.assertTrue(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
351 self.assertRaises(TypeError, divmod)
353 def test_eval(self):
354 self.assertEqual(eval('1+1'), 2)
355 self.assertEqual(eval(' 1+1\n'), 2)
356 globals = {'a': 1, 'b': 2}
357 locals = {'b': 200, 'c': 300}
358 self.assertEqual(eval('a', globals) , 1)
359 self.assertEqual(eval('a', globals, locals), 1)
360 self.assertEqual(eval('b', globals, locals), 200)
361 self.assertEqual(eval('c', globals, locals), 300)
362 if have_unicode:
363 self.assertEqual(eval(unicode('1+1')), 2)
364 self.assertEqual(eval(unicode(' 1+1\n')), 2)
365 globals = {'a': 1, 'b': 2}
366 locals = {'b': 200, 'c': 300}
367 if have_unicode:
368 self.assertEqual(eval(unicode('a'), globals), 1)
369 self.assertEqual(eval(unicode('a'), globals, locals), 1)
370 self.assertEqual(eval(unicode('b'), globals, locals), 200)
371 self.assertEqual(eval(unicode('c'), globals, locals), 300)
372 bom = '\xef\xbb\xbf'
373 self.assertEqual(eval(bom + 'a', globals, locals), 1)
374 self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals),
375 unicode('\xc3\xa5', 'utf8'))
376 self.assertRaises(TypeError, eval)
377 self.assertRaises(TypeError, eval, ())
379 def test_general_eval(self):
380 # Tests that general mappings can be used for the locals argument
382 class M:
383 "Test mapping interface versus possible calls from eval()."
384 def __getitem__(self, key):
385 if key == 'a':
386 return 12
387 raise KeyError
388 def keys(self):
389 return list('xyz')
391 m = M()
392 g = globals()
393 self.assertEqual(eval('a', g, m), 12)
394 self.assertRaises(NameError, eval, 'b', g, m)
395 self.assertEqual(eval('dir()', g, m), list('xyz'))
396 self.assertEqual(eval('globals()', g, m), g)
397 self.assertEqual(eval('locals()', g, m), m)
398 self.assertRaises(TypeError, eval, 'a', m)
399 class A:
400 "Non-mapping"
401 pass
402 m = A()
403 self.assertRaises(TypeError, eval, 'a', g, m)
405 # Verify that dict subclasses work as well
406 class D(dict):
407 def __getitem__(self, key):
408 if key == 'a':
409 return 12
410 return dict.__getitem__(self, key)
411 def keys(self):
412 return list('xyz')
414 d = D()
415 self.assertEqual(eval('a', g, d), 12)
416 self.assertRaises(NameError, eval, 'b', g, d)
417 self.assertEqual(eval('dir()', g, d), list('xyz'))
418 self.assertEqual(eval('globals()', g, d), g)
419 self.assertEqual(eval('locals()', g, d), d)
421 # Verify locals stores (used by list comps)
422 eval('[locals() for i in (2,3)]', g, d)
423 eval('[locals() for i in (2,3)]', g, UserDict.UserDict())
425 class SpreadSheet:
426 "Sample application showing nested, calculated lookups."
427 _cells = {}
428 def __setitem__(self, key, formula):
429 self._cells[key] = formula
430 def __getitem__(self, key):
431 return eval(self._cells[key], globals(), self)
433 ss = SpreadSheet()
434 ss['a1'] = '5'
435 ss['a2'] = 'a1*6'
436 ss['a3'] = 'a2*7'
437 self.assertEqual(ss['a3'], 210)
439 # Verify that dir() catches a non-list returned by eval
440 # SF bug #1004669
441 class C:
442 def __getitem__(self, item):
443 raise KeyError(item)
444 def keys(self):
445 return 'a'
446 self.assertRaises(TypeError, eval, 'dir()', globals(), C())
448 # Done outside of the method test_z to get the correct scope
449 z = 0
450 f = open(TESTFN, 'w')
451 f.write('z = z+1\n')
452 f.write('z = z*2\n')
453 f.close()
454 with check_py3k_warnings(("execfile.. not supported in 3.x",
455 DeprecationWarning)):
456 execfile(TESTFN)
458 def test_execfile(self):
459 global numruns
460 if numruns:
461 return
462 numruns += 1
464 globals = {'a': 1, 'b': 2}
465 locals = {'b': 200, 'c': 300}
467 self.assertEqual(self.__class__.z, 2)
468 globals['z'] = 0
469 execfile(TESTFN, globals)
470 self.assertEqual(globals['z'], 2)
471 locals['z'] = 0
472 execfile(TESTFN, globals, locals)
473 self.assertEqual(locals['z'], 2)
475 class M:
476 "Test mapping interface versus possible calls from execfile()."
477 def __init__(self):
478 self.z = 10
479 def __getitem__(self, key):
480 if key == 'z':
481 return self.z
482 raise KeyError
483 def __setitem__(self, key, value):
484 if key == 'z':
485 self.z = value
486 return
487 raise KeyError
489 locals = M()
490 locals['z'] = 0
491 execfile(TESTFN, globals, locals)
492 self.assertEqual(locals['z'], 2)
494 unlink(TESTFN)
495 self.assertRaises(TypeError, execfile)
496 self.assertRaises(TypeError, execfile, TESTFN, {}, ())
497 import os
498 self.assertRaises(IOError, execfile, os.curdir)
499 self.assertRaises(IOError, execfile, "I_dont_exist")
501 def test_filter(self):
502 self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
503 self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
504 self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2])
505 self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
506 self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81])
507 def identity(item):
508 return 1
509 filter(identity, Squares(5))
510 self.assertRaises(TypeError, filter)
511 class BadSeq(object):
512 def __getitem__(self, index):
513 if index<4:
514 return 42
515 raise ValueError
516 self.assertRaises(ValueError, filter, lambda x: x, BadSeq())
517 def badfunc():
518 pass
519 self.assertRaises(TypeError, filter, badfunc, range(5))
521 # test bltinmodule.c::filtertuple()
522 self.assertEqual(filter(None, (1, 2)), (1, 2))
523 self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4))
524 self.assertRaises(TypeError, filter, 42, (1, 2))
526 # test bltinmodule.c::filterstring()
527 self.assertEqual(filter(None, "12"), "12")
528 self.assertEqual(filter(lambda x: x>="3", "1234"), "34")
529 self.assertRaises(TypeError, filter, 42, "12")
530 class badstr(str):
531 def __getitem__(self, index):
532 raise ValueError
533 self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234"))
535 class badstr2(str):
536 def __getitem__(self, index):
537 return 42
538 self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234"))
540 class weirdstr(str):
541 def __getitem__(self, index):
542 return weirdstr(2*str.__getitem__(self, index))
543 self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344")
545 class shiftstr(str):
546 def __getitem__(self, index):
547 return chr(ord(str.__getitem__(self, index))+1)
548 self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345")
550 if have_unicode:
551 # test bltinmodule.c::filterunicode()
552 self.assertEqual(filter(None, unicode("12")), unicode("12"))
553 self.assertEqual(filter(lambda x: x>="3", unicode("1234")), unicode("34"))
554 self.assertRaises(TypeError, filter, 42, unicode("12"))
555 self.assertRaises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234")))
557 class badunicode(unicode):
558 def __getitem__(self, index):
559 return 42
560 self.assertRaises(TypeError, filter, lambda x: x >=42, badunicode("1234"))
562 class weirdunicode(unicode):
563 def __getitem__(self, index):
564 return weirdunicode(2*unicode.__getitem__(self, index))
565 self.assertEqual(
566 filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344"))
568 class shiftunicode(unicode):
569 def __getitem__(self, index):
570 return unichr(ord(unicode.__getitem__(self, index))+1)
571 self.assertEqual(
572 filter(lambda x: x>=unicode("3"), shiftunicode("1234")),
573 unicode("345")
576 def test_filter_subclasses(self):
577 # test that filter() never returns tuple, str or unicode subclasses
578 # and that the result always goes through __getitem__
579 funcs = (None, bool, lambda x: True)
580 class tuple2(tuple):
581 def __getitem__(self, index):
582 return 2*tuple.__getitem__(self, index)
583 class str2(str):
584 def __getitem__(self, index):
585 return 2*str.__getitem__(self, index)
586 inputs = {
587 tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
588 str2: {"": "", "123": "112233"}
590 if have_unicode:
591 class unicode2(unicode):
592 def __getitem__(self, index):
593 return 2*unicode.__getitem__(self, index)
594 inputs[unicode2] = {
595 unicode(): unicode(),
596 unicode("123"): unicode("112233")
599 for (cls, inps) in inputs.iteritems():
600 for (inp, exp) in inps.iteritems():
601 # make sure the output goes through __getitem__
602 # even if func is None
603 self.assertEqual(
604 filter(funcs[0], cls(inp)),
605 filter(funcs[1], cls(inp))
607 for func in funcs:
608 outp = filter(func, cls(inp))
609 self.assertEqual(outp, exp)
610 self.assertTrue(not isinstance(outp, cls))
612 def test_getattr(self):
613 import sys
614 self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
615 self.assertRaises(TypeError, getattr, sys, 1)
616 self.assertRaises(TypeError, getattr, sys, 1, "foo")
617 self.assertRaises(TypeError, getattr)
618 if have_unicode:
619 self.assertRaises(UnicodeError, getattr, sys, unichr(sys.maxunicode))
621 def test_hasattr(self):
622 import sys
623 self.assertTrue(hasattr(sys, 'stdout'))
624 self.assertRaises(TypeError, hasattr, sys, 1)
625 self.assertRaises(TypeError, hasattr)
626 if have_unicode:
627 self.assertRaises(UnicodeError, hasattr, sys, unichr(sys.maxunicode))
629 # Check that hasattr allows SystemExit and KeyboardInterrupts by
630 class A:
631 def __getattr__(self, what):
632 raise KeyboardInterrupt
633 self.assertRaises(KeyboardInterrupt, hasattr, A(), "b")
634 class B:
635 def __getattr__(self, what):
636 raise SystemExit
637 self.assertRaises(SystemExit, hasattr, B(), "b")
639 def test_hash(self):
640 hash(None)
641 self.assertEqual(hash(1), hash(1L))
642 self.assertEqual(hash(1), hash(1.0))
643 hash('spam')
644 if have_unicode:
645 self.assertEqual(hash('spam'), hash(unicode('spam')))
646 hash((0,1,2,3))
647 def f(): pass
648 self.assertRaises(TypeError, hash, [])
649 self.assertRaises(TypeError, hash, {})
650 # Bug 1536021: Allow hash to return long objects
651 class X:
652 def __hash__(self):
653 return 2**100
654 self.assertEquals(type(hash(X())), int)
655 class Y(object):
656 def __hash__(self):
657 return 2**100
658 self.assertEquals(type(hash(Y())), int)
659 class Z(long):
660 def __hash__(self):
661 return self
662 self.assertEquals(hash(Z(42)), hash(42L))
664 def test_hex(self):
665 self.assertEqual(hex(16), '0x10')
666 self.assertEqual(hex(16L), '0x10L')
667 self.assertEqual(hex(-16), '-0x10')
668 self.assertEqual(hex(-16L), '-0x10L')
669 self.assertRaises(TypeError, hex, {})
671 def test_id(self):
672 id(None)
673 id(1)
674 id(1L)
675 id(1.0)
676 id('spam')
677 id((0,1,2,3))
678 id([0,1,2,3])
679 id({'spam': 1, 'eggs': 2, 'ham': 3})
681 # Test input() later, together with raw_input
683 def test_intern(self):
684 self.assertRaises(TypeError, intern)
685 # This fails if the test is run twice with a constant string,
686 # therefore append the run counter
687 s = "never interned before " + str(numruns)
688 self.assertTrue(intern(s) is s)
689 s2 = s.swapcase().swapcase()
690 self.assertTrue(intern(s2) is s)
692 # Subclasses of string can't be interned, because they
693 # provide too much opportunity for insane things to happen.
694 # We don't want them in the interned dict and if they aren't
695 # actually interned, we don't want to create the appearance
696 # that they are by allowing intern() to succeeed.
697 class S(str):
698 def __hash__(self):
699 return 123
701 self.assertRaises(TypeError, intern, S("abc"))
703 # It's still safe to pass these strings to routines that
704 # call intern internally, e.g. PyObject_SetAttr().
705 s = S("abc")
706 setattr(s, s, s)
707 self.assertEqual(getattr(s, s), s)
709 def test_iter(self):
710 self.assertRaises(TypeError, iter)
711 self.assertRaises(TypeError, iter, 42, 42)
712 lists = [("1", "2"), ["1", "2"], "12"]
713 if have_unicode:
714 lists.append(unicode("12"))
715 for l in lists:
716 i = iter(l)
717 self.assertEqual(i.next(), '1')
718 self.assertEqual(i.next(), '2')
719 self.assertRaises(StopIteration, i.next)
721 def test_isinstance(self):
722 class C:
723 pass
724 class D(C):
725 pass
726 class E:
727 pass
728 c = C()
729 d = D()
730 e = E()
731 self.assertTrue(isinstance(c, C))
732 self.assertTrue(isinstance(d, C))
733 self.assertTrue(not isinstance(e, C))
734 self.assertTrue(not isinstance(c, D))
735 self.assertTrue(not isinstance('foo', E))
736 self.assertRaises(TypeError, isinstance, E, 'foo')
737 self.assertRaises(TypeError, isinstance)
739 def test_issubclass(self):
740 class C:
741 pass
742 class D(C):
743 pass
744 class E:
745 pass
746 c = C()
747 d = D()
748 e = E()
749 self.assertTrue(issubclass(D, C))
750 self.assertTrue(issubclass(C, C))
751 self.assertTrue(not issubclass(C, D))
752 self.assertRaises(TypeError, issubclass, 'foo', E)
753 self.assertRaises(TypeError, issubclass, E, 'foo')
754 self.assertRaises(TypeError, issubclass)
756 def test_len(self):
757 self.assertEqual(len('123'), 3)
758 self.assertEqual(len(()), 0)
759 self.assertEqual(len((1, 2, 3, 4)), 4)
760 self.assertEqual(len([1, 2, 3, 4]), 4)
761 self.assertEqual(len({}), 0)
762 self.assertEqual(len({'a':1, 'b': 2}), 2)
763 class BadSeq:
764 def __len__(self):
765 raise ValueError
766 self.assertRaises(ValueError, len, BadSeq())
767 self.assertRaises(TypeError, len, 2)
768 class ClassicStyle: pass
769 class NewStyle(object): pass
770 self.assertRaises(AttributeError, len, ClassicStyle())
771 self.assertRaises(TypeError, len, NewStyle())
773 def test_map(self):
774 self.assertEqual(
775 map(None, 'hello world'),
776 ['h','e','l','l','o',' ','w','o','r','l','d']
778 self.assertEqual(
779 map(None, 'abcd', 'efg'),
780 [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
782 self.assertEqual(
783 map(None, range(10)),
784 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
786 self.assertEqual(
787 map(lambda x: x*x, range(1,4)),
788 [1, 4, 9]
790 try:
791 from math import sqrt
792 except ImportError:
793 def sqrt(x):
794 return pow(x, 0.5)
795 self.assertEqual(
796 map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]),
797 [[4.0, 2.0], [9.0, 3.0]]
799 self.assertEqual(
800 map(lambda x, y: x+y, [1,3,2], [9,1,4]),
801 [10, 4, 6]
804 def plus(*v):
805 accu = 0
806 for i in v: accu = accu + i
807 return accu
808 self.assertEqual(
809 map(plus, [1, 3, 7]),
810 [1, 3, 7]
812 self.assertEqual(
813 map(plus, [1, 3, 7], [4, 9, 2]),
814 [1+4, 3+9, 7+2]
816 self.assertEqual(
817 map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
818 [1+4+1, 3+9+1, 7+2+0]
820 self.assertEqual(
821 map(None, Squares(10)),
822 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
824 self.assertEqual(
825 map(int, Squares(10)),
826 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
828 self.assertEqual(
829 map(None, Squares(3), Squares(2)),
830 [(0,0), (1,1), (4,None)]
832 self.assertEqual(
833 map(max, Squares(3), Squares(2)),
834 [0, 1, 4]
836 self.assertRaises(TypeError, map)
837 self.assertRaises(TypeError, map, lambda x: x, 42)
838 self.assertEqual(map(None, [42]), [42])
839 class BadSeq:
840 def __getitem__(self, index):
841 raise ValueError
842 self.assertRaises(ValueError, map, lambda x: x, BadSeq())
843 def badfunc(x):
844 raise RuntimeError
845 self.assertRaises(RuntimeError, map, badfunc, range(5))
847 def test_max(self):
848 self.assertEqual(max('123123'), '3')
849 self.assertEqual(max(1, 2, 3), 3)
850 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
851 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
853 self.assertEqual(max(1, 2L, 3.0), 3.0)
854 self.assertEqual(max(1L, 2.0, 3), 3)
855 self.assertEqual(max(1.0, 2, 3L), 3L)
857 for stmt in (
858 "max(key=int)", # no args
859 "max(1, key=int)", # single arg not iterable
860 "max(1, 2, keystone=int)", # wrong keyword
861 "max(1, 2, key=int, abc=int)", # two many keywords
862 "max(1, 2, key=1)", # keyfunc is not callable
864 try:
865 exec(stmt) in globals()
866 except TypeError:
867 pass
868 else:
869 self.fail(stmt)
871 self.assertEqual(max((1,), key=neg), 1) # one elem iterable
872 self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
873 self.assertEqual(max(1, 2, key=neg), 1) # two elems
875 data = [random.randrange(200) for i in range(100)]
876 keys = dict((elem, random.randrange(50)) for elem in data)
877 f = keys.__getitem__
878 self.assertEqual(max(data, key=f),
879 sorted(reversed(data), key=f)[-1])
881 def test_min(self):
882 self.assertEqual(min('123123'), '1')
883 self.assertEqual(min(1, 2, 3), 1)
884 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
885 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
887 self.assertEqual(min(1, 2L, 3.0), 1)
888 self.assertEqual(min(1L, 2.0, 3), 1L)
889 self.assertEqual(min(1.0, 2, 3L), 1.0)
891 self.assertRaises(TypeError, min)
892 self.assertRaises(TypeError, min, 42)
893 self.assertRaises(ValueError, min, ())
894 class BadSeq:
895 def __getitem__(self, index):
896 raise ValueError
897 self.assertRaises(ValueError, min, BadSeq())
898 class BadNumber:
899 def __cmp__(self, other):
900 raise ValueError
901 self.assertRaises(ValueError, min, (42, BadNumber()))
903 for stmt in (
904 "min(key=int)", # no args
905 "min(1, key=int)", # single arg not iterable
906 "min(1, 2, keystone=int)", # wrong keyword
907 "min(1, 2, key=int, abc=int)", # two many keywords
908 "min(1, 2, key=1)", # keyfunc is not callable
910 try:
911 exec(stmt) in globals()
912 except TypeError:
913 pass
914 else:
915 self.fail(stmt)
917 self.assertEqual(min((1,), key=neg), 1) # one elem iterable
918 self.assertEqual(min((1,2), key=neg), 2) # two elem iterable
919 self.assertEqual(min(1, 2, key=neg), 2) # two elems
921 data = [random.randrange(200) for i in range(100)]
922 keys = dict((elem, random.randrange(50)) for elem in data)
923 f = keys.__getitem__
924 self.assertEqual(min(data, key=f),
925 sorted(data, key=f)[0])
927 def test_next(self):
928 it = iter(range(2))
929 self.assertEqual(next(it), 0)
930 self.assertEqual(next(it), 1)
931 self.assertRaises(StopIteration, next, it)
932 self.assertRaises(StopIteration, next, it)
933 self.assertEquals(next(it, 42), 42)
935 class Iter(object):
936 def __iter__(self):
937 return self
938 def next(self):
939 raise StopIteration
941 it = iter(Iter())
942 self.assertEquals(next(it, 42), 42)
943 self.assertRaises(StopIteration, next, it)
945 def gen():
946 yield 1
947 return
949 it = gen()
950 self.assertEquals(next(it), 1)
951 self.assertRaises(StopIteration, next, it)
952 self.assertEquals(next(it, 42), 42)
954 def test_oct(self):
955 self.assertEqual(oct(100), '0144')
956 self.assertEqual(oct(100L), '0144L')
957 self.assertEqual(oct(-100), '-0144')
958 self.assertEqual(oct(-100L), '-0144L')
959 self.assertRaises(TypeError, oct, ())
961 def write_testfile(self):
962 # NB the first 4 lines are also used to test input and raw_input, below
963 fp = open(TESTFN, 'w')
964 try:
965 fp.write('1+1\n')
966 fp.write('1+1\n')
967 fp.write('The quick brown fox jumps over the lazy dog')
968 fp.write('.\n')
969 fp.write('Dear John\n')
970 fp.write('XXX'*100)
971 fp.write('YYY'*100)
972 finally:
973 fp.close()
975 def test_open(self):
976 self.write_testfile()
977 fp = open(TESTFN, 'r')
978 try:
979 self.assertEqual(fp.readline(4), '1+1\n')
980 self.assertEqual(fp.readline(4), '1+1\n')
981 self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
982 self.assertEqual(fp.readline(4), 'Dear')
983 self.assertEqual(fp.readline(100), ' John\n')
984 self.assertEqual(fp.read(300), 'XXX'*100)
985 self.assertEqual(fp.read(1000), 'YYY'*100)
986 finally:
987 fp.close()
988 unlink(TESTFN)
990 def test_ord(self):
991 self.assertEqual(ord(' '), 32)
992 self.assertEqual(ord('A'), 65)
993 self.assertEqual(ord('a'), 97)
994 if have_unicode:
995 self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode)
996 self.assertRaises(TypeError, ord, 42)
997 if have_unicode:
998 self.assertRaises(TypeError, ord, unicode("12"))
1000 def test_pow(self):
1001 self.assertEqual(pow(0,0), 1)
1002 self.assertEqual(pow(0,1), 0)
1003 self.assertEqual(pow(1,0), 1)
1004 self.assertEqual(pow(1,1), 1)
1006 self.assertEqual(pow(2,0), 1)
1007 self.assertEqual(pow(2,10), 1024)
1008 self.assertEqual(pow(2,20), 1024*1024)
1009 self.assertEqual(pow(2,30), 1024*1024*1024)
1011 self.assertEqual(pow(-2,0), 1)
1012 self.assertEqual(pow(-2,1), -2)
1013 self.assertEqual(pow(-2,2), 4)
1014 self.assertEqual(pow(-2,3), -8)
1016 self.assertEqual(pow(0L,0), 1)
1017 self.assertEqual(pow(0L,1), 0)
1018 self.assertEqual(pow(1L,0), 1)
1019 self.assertEqual(pow(1L,1), 1)
1021 self.assertEqual(pow(2L,0), 1)
1022 self.assertEqual(pow(2L,10), 1024)
1023 self.assertEqual(pow(2L,20), 1024*1024)
1024 self.assertEqual(pow(2L,30), 1024*1024*1024)
1026 self.assertEqual(pow(-2L,0), 1)
1027 self.assertEqual(pow(-2L,1), -2)
1028 self.assertEqual(pow(-2L,2), 4)
1029 self.assertEqual(pow(-2L,3), -8)
1031 self.assertAlmostEqual(pow(0.,0), 1.)
1032 self.assertAlmostEqual(pow(0.,1), 0.)
1033 self.assertAlmostEqual(pow(1.,0), 1.)
1034 self.assertAlmostEqual(pow(1.,1), 1.)
1036 self.assertAlmostEqual(pow(2.,0), 1.)
1037 self.assertAlmostEqual(pow(2.,10), 1024.)
1038 self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
1039 self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
1041 self.assertAlmostEqual(pow(-2.,0), 1.)
1042 self.assertAlmostEqual(pow(-2.,1), -2.)
1043 self.assertAlmostEqual(pow(-2.,2), 4.)
1044 self.assertAlmostEqual(pow(-2.,3), -8.)
1046 for x in 2, 2L, 2.0:
1047 for y in 10, 10L, 10.0:
1048 for z in 1000, 1000L, 1000.0:
1049 if isinstance(x, float) or \
1050 isinstance(y, float) or \
1051 isinstance(z, float):
1052 self.assertRaises(TypeError, pow, x, y, z)
1053 else:
1054 self.assertAlmostEqual(pow(x, y, z), 24.0)
1056 self.assertRaises(TypeError, pow, -1, -2, 3)
1057 self.assertRaises(ValueError, pow, 1, 2, 0)
1058 self.assertRaises(TypeError, pow, -1L, -2L, 3L)
1059 self.assertRaises(ValueError, pow, 1L, 2L, 0L)
1060 # Will return complex in 3.0:
1061 self.assertRaises(ValueError, pow, -342.43, 0.234)
1063 self.assertRaises(TypeError, pow)
1065 def test_range(self):
1066 self.assertEqual(range(3), [0, 1, 2])
1067 self.assertEqual(range(1, 5), [1, 2, 3, 4])
1068 self.assertEqual(range(0), [])
1069 self.assertEqual(range(-3), [])
1070 self.assertEqual(range(1, 10, 3), [1, 4, 7])
1071 self.assertEqual(range(5, -5, -3), [5, 2, -1, -4])
1073 # Now test range() with longs
1074 self.assertEqual(range(-2**100), [])
1075 self.assertEqual(range(0, -2**100), [])
1076 self.assertEqual(range(0, 2**100, -1), [])
1077 self.assertEqual(range(0, 2**100, -1), [])
1079 a = long(10 * sys.maxint)
1080 b = long(100 * sys.maxint)
1081 c = long(50 * sys.maxint)
1083 self.assertEqual(range(a, a+2), [a, a+1])
1084 self.assertEqual(range(a+2, a, -1L), [a+2, a+1])
1085 self.assertEqual(range(a+4, a, -2), [a+4, a+2])
1087 seq = range(a, b, c)
1088 self.assertIn(a, seq)
1089 self.assertNotIn(b, seq)
1090 self.assertEqual(len(seq), 2)
1092 seq = range(b, a, -c)
1093 self.assertIn(b, seq)
1094 self.assertNotIn(a, seq)
1095 self.assertEqual(len(seq), 2)
1097 seq = range(-a, -b, -c)
1098 self.assertIn(-a, seq)
1099 self.assertNotIn(-b, seq)
1100 self.assertEqual(len(seq), 2)
1102 self.assertRaises(TypeError, range)
1103 self.assertRaises(TypeError, range, 1, 2, 3, 4)
1104 self.assertRaises(ValueError, range, 1, 2, 0)
1105 self.assertRaises(ValueError, range, a, a + 1, long(0))
1107 class badzero(int):
1108 def __cmp__(self, other):
1109 raise RuntimeError
1110 __hash__ = None # Invalid cmp makes this unhashable
1111 self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
1113 # Reject floats.
1114 self.assertRaises(TypeError, range, 1., 1., 1.)
1115 self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
1117 self.assertRaises(TypeError, range, 0, "spam")
1118 self.assertRaises(TypeError, range, 0, 42, "spam")
1120 self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
1121 self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
1123 bignum = 2*sys.maxint
1124 smallnum = 42
1125 # Old-style user-defined class with __int__ method
1126 class I0:
1127 def __init__(self, n):
1128 self.n = int(n)
1129 def __int__(self):
1130 return self.n
1131 self.assertEqual(range(I0(bignum), I0(bignum + 1)), [bignum])
1132 self.assertEqual(range(I0(smallnum), I0(smallnum + 1)), [smallnum])
1134 # New-style user-defined class with __int__ method
1135 class I1(object):
1136 def __init__(self, n):
1137 self.n = int(n)
1138 def __int__(self):
1139 return self.n
1140 self.assertEqual(range(I1(bignum), I1(bignum + 1)), [bignum])
1141 self.assertEqual(range(I1(smallnum), I1(smallnum + 1)), [smallnum])
1143 # New-style user-defined class with failing __int__ method
1144 class IX(object):
1145 def __int__(self):
1146 raise RuntimeError
1147 self.assertRaises(RuntimeError, range, IX())
1149 # New-style user-defined class with invalid __int__ method
1150 class IN(object):
1151 def __int__(self):
1152 return "not a number"
1153 self.assertRaises(TypeError, range, IN())
1155 # Exercise various combinations of bad arguments, to check
1156 # refcounting logic
1157 self.assertRaises(TypeError, range, 0.0)
1159 self.assertRaises(TypeError, range, 0, 0.0)
1160 self.assertRaises(TypeError, range, 0.0, 0)
1161 self.assertRaises(TypeError, range, 0.0, 0.0)
1163 self.assertRaises(TypeError, range, 0, 0, 1.0)
1164 self.assertRaises(TypeError, range, 0, 0.0, 1)
1165 self.assertRaises(TypeError, range, 0, 0.0, 1.0)
1166 self.assertRaises(TypeError, range, 0.0, 0, 1)
1167 self.assertRaises(TypeError, range, 0.0, 0, 1.0)
1168 self.assertRaises(TypeError, range, 0.0, 0.0, 1)
1169 self.assertRaises(TypeError, range, 0.0, 0.0, 1.0)
1173 def test_input_and_raw_input(self):
1174 self.write_testfile()
1175 fp = open(TESTFN, 'r')
1176 savestdin = sys.stdin
1177 savestdout = sys.stdout # Eats the echo
1178 try:
1179 sys.stdin = fp
1180 sys.stdout = BitBucket()
1181 self.assertEqual(input(), 2)
1182 self.assertEqual(input('testing\n'), 2)
1183 self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.')
1184 self.assertEqual(raw_input('testing\n'), 'Dear John')
1186 # SF 1535165: don't segfault on closed stdin
1187 # sys.stdout must be a regular file for triggering
1188 sys.stdout = savestdout
1189 sys.stdin.close()
1190 self.assertRaises(ValueError, input)
1192 sys.stdout = BitBucket()
1193 sys.stdin = cStringIO.StringIO("NULL\0")
1194 self.assertRaises(TypeError, input, 42, 42)
1195 sys.stdin = cStringIO.StringIO(" 'whitespace'")
1196 self.assertEqual(input(), 'whitespace')
1197 sys.stdin = cStringIO.StringIO()
1198 self.assertRaises(EOFError, input)
1200 # SF 876178: make sure input() respect future options.
1201 sys.stdin = cStringIO.StringIO('1/2')
1202 sys.stdout = cStringIO.StringIO()
1203 exec compile('print input()', 'test_builtin_tmp', 'exec')
1204 sys.stdin.seek(0, 0)
1205 exec compile('from __future__ import division;print input()',
1206 'test_builtin_tmp', 'exec')
1207 sys.stdin.seek(0, 0)
1208 exec compile('print input()', 'test_builtin_tmp', 'exec')
1209 # The result we expect depends on whether new division semantics
1210 # are already in effect.
1211 if 1/2 == 0:
1212 # This test was compiled with old semantics.
1213 expected = ['0', '0.5', '0']
1214 else:
1215 # This test was compiled with new semantics (e.g., -Qnew
1216 # was given on the command line.
1217 expected = ['0.5', '0.5', '0.5']
1218 self.assertEqual(sys.stdout.getvalue().splitlines(), expected)
1220 del sys.stdout
1221 self.assertRaises(RuntimeError, input, 'prompt')
1222 del sys.stdin
1223 self.assertRaises(RuntimeError, input, 'prompt')
1224 finally:
1225 sys.stdin = savestdin
1226 sys.stdout = savestdout
1227 fp.close()
1228 unlink(TESTFN)
1230 def test_reduce(self):
1231 add = lambda x, y: x+y
1232 self.assertEqual(reduce(add, ['a', 'b', 'c'], ''), 'abc')
1233 self.assertEqual(
1234 reduce(add, [['a', 'c'], [], ['d', 'w']], []),
1235 ['a','c','d','w']
1237 self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040)
1238 self.assertEqual(
1239 reduce(lambda x, y: x*y, range(2,21), 1L),
1240 2432902008176640000L
1242 self.assertEqual(reduce(add, Squares(10)), 285)
1243 self.assertEqual(reduce(add, Squares(10), 0), 285)
1244 self.assertEqual(reduce(add, Squares(0), 0), 0)
1245 self.assertRaises(TypeError, reduce)
1246 self.assertRaises(TypeError, reduce, 42)
1247 self.assertRaises(TypeError, reduce, 42, 42)
1248 self.assertRaises(TypeError, reduce, 42, 42, 42)
1249 self.assertRaises(TypeError, reduce, None, range(5))
1250 self.assertRaises(TypeError, reduce, add, 42)
1251 self.assertEqual(reduce(42, "1"), "1") # func is never called with one item
1252 self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item
1253 self.assertRaises(TypeError, reduce, 42, (42, 42))
1254 self.assertRaises(TypeError, reduce, add, []) # arg 2 must not be empty sequence with no initial value
1255 self.assertRaises(TypeError, reduce, add, "")
1256 self.assertRaises(TypeError, reduce, add, ())
1257 self.assertEqual(reduce(add, [], None), None)
1258 self.assertEqual(reduce(add, [], 42), 42)
1260 class BadSeq:
1261 def __getitem__(self, index):
1262 raise ValueError
1263 self.assertRaises(ValueError, reduce, 42, BadSeq())
1265 def test_reload(self):
1266 import marshal
1267 reload(marshal)
1268 import string
1269 reload(string)
1270 ## import sys
1271 ## self.assertRaises(ImportError, reload, sys)
1273 def test_repr(self):
1274 self.assertEqual(repr(''), '\'\'')
1275 self.assertEqual(repr(0), '0')
1276 self.assertEqual(repr(0L), '0L')
1277 self.assertEqual(repr(()), '()')
1278 self.assertEqual(repr([]), '[]')
1279 self.assertEqual(repr({}), '{}')
1280 a = []
1281 a.append(a)
1282 self.assertEqual(repr(a), '[[...]]')
1283 a = {}
1284 a[0] = a
1285 self.assertEqual(repr(a), '{0: {...}}')
1287 def test_round(self):
1288 self.assertEqual(round(0.0), 0.0)
1289 self.assertEqual(type(round(0.0)), float) # Will be int in 3.0.
1290 self.assertEqual(round(1.0), 1.0)
1291 self.assertEqual(round(10.0), 10.0)
1292 self.assertEqual(round(1000000000.0), 1000000000.0)
1293 self.assertEqual(round(1e20), 1e20)
1295 self.assertEqual(round(-1.0), -1.0)
1296 self.assertEqual(round(-10.0), -10.0)
1297 self.assertEqual(round(-1000000000.0), -1000000000.0)
1298 self.assertEqual(round(-1e20), -1e20)
1300 self.assertEqual(round(0.1), 0.0)
1301 self.assertEqual(round(1.1), 1.0)
1302 self.assertEqual(round(10.1), 10.0)
1303 self.assertEqual(round(1000000000.1), 1000000000.0)
1305 self.assertEqual(round(-1.1), -1.0)
1306 self.assertEqual(round(-10.1), -10.0)
1307 self.assertEqual(round(-1000000000.1), -1000000000.0)
1309 self.assertEqual(round(0.9), 1.0)
1310 self.assertEqual(round(9.9), 10.0)
1311 self.assertEqual(round(999999999.9), 1000000000.0)
1313 self.assertEqual(round(-0.9), -1.0)
1314 self.assertEqual(round(-9.9), -10.0)
1315 self.assertEqual(round(-999999999.9), -1000000000.0)
1317 self.assertEqual(round(-8.0, -1), -10.0)
1318 self.assertEqual(type(round(-8.0, -1)), float)
1320 self.assertEqual(type(round(-8.0, 0)), float)
1321 self.assertEqual(type(round(-8.0, 1)), float)
1323 # Check half rounding behaviour.
1324 self.assertEqual(round(5.5), 6)
1325 self.assertEqual(round(6.5), 7)
1326 self.assertEqual(round(-5.5), -6)
1327 self.assertEqual(round(-6.5), -7)
1329 # Check behavior on ints
1330 self.assertEqual(round(0), 0)
1331 self.assertEqual(round(8), 8)
1332 self.assertEqual(round(-8), -8)
1333 self.assertEqual(type(round(0)), float) # Will be int in 3.0.
1334 self.assertEqual(type(round(-8, -1)), float)
1335 self.assertEqual(type(round(-8, 0)), float)
1336 self.assertEqual(type(round(-8, 1)), float)
1338 # test new kwargs
1339 self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
1341 self.assertRaises(TypeError, round)
1343 # test generic rounding delegation for reals
1344 class TestRound(object):
1345 def __float__(self):
1346 return 23.0
1348 class TestNoRound(object):
1349 pass
1351 self.assertEqual(round(TestRound()), 23)
1353 self.assertRaises(TypeError, round, 1, 2, 3)
1354 self.assertRaises(TypeError, round, TestNoRound())
1356 t = TestNoRound()
1357 t.__float__ = lambda *args: args
1358 self.assertRaises(TypeError, round, t)
1359 self.assertRaises(TypeError, round, t, 0)
1361 # Some versions of glibc for alpha have a bug that affects
1362 # float -> integer rounding (floor, ceil, rint, round) for
1363 # values in the range [2**52, 2**53). See:
1365 # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
1367 # We skip this test on Linux/alpha if it would fail.
1368 linux_alpha = (platform.system().startswith('Linux') and
1369 platform.machine().startswith('alpha'))
1370 system_round_bug = round(5e15+1) != 5e15+1
1371 @unittest.skipIf(linux_alpha and system_round_bug,
1372 "test will fail; failure is probably due to a "
1373 "buggy system round function")
1374 def test_round_large(self):
1375 # Issue #1869: integral floats should remain unchanged
1376 self.assertEqual(round(5e15-1), 5e15-1)
1377 self.assertEqual(round(5e15), 5e15)
1378 self.assertEqual(round(5e15+1), 5e15+1)
1379 self.assertEqual(round(5e15+2), 5e15+2)
1380 self.assertEqual(round(5e15+3), 5e15+3)
1382 def test_setattr(self):
1383 setattr(sys, 'spam', 1)
1384 self.assertEqual(sys.spam, 1)
1385 self.assertRaises(TypeError, setattr, sys, 1, 'spam')
1386 self.assertRaises(TypeError, setattr)
1388 def test_sum(self):
1389 self.assertEqual(sum([]), 0)
1390 self.assertEqual(sum(range(2,8)), 27)
1391 self.assertEqual(sum(iter(range(2,8))), 27)
1392 self.assertEqual(sum(Squares(10)), 285)
1393 self.assertEqual(sum(iter(Squares(10))), 285)
1394 self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
1396 self.assertRaises(TypeError, sum)
1397 self.assertRaises(TypeError, sum, 42)
1398 self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
1399 self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
1400 self.assertRaises(TypeError, sum, [[1], [2], [3]])
1401 self.assertRaises(TypeError, sum, [{2:3}])
1402 self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
1404 class BadSeq:
1405 def __getitem__(self, index):
1406 raise ValueError
1407 self.assertRaises(ValueError, sum, BadSeq())
1409 empty = []
1410 sum(([x] for x in range(10)), empty)
1411 self.assertEqual(empty, [])
1413 def test_type(self):
1414 self.assertEqual(type(''), type('123'))
1415 self.assertNotEqual(type(''), type(()))
1417 def test_unichr(self):
1418 if have_unicode:
1419 self.assertEqual(unichr(32), unicode(' '))
1420 self.assertEqual(unichr(65), unicode('A'))
1421 self.assertEqual(unichr(97), unicode('a'))
1422 self.assertEqual(
1423 unichr(sys.maxunicode),
1424 unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape')
1426 self.assertRaises(ValueError, unichr, sys.maxunicode+1)
1427 self.assertRaises(TypeError, unichr)
1428 self.assertRaises((OverflowError, ValueError), unichr, 2**32)
1430 # We don't want self in vars(), so these are static methods
1432 @staticmethod
1433 def get_vars_f0():
1434 return vars()
1436 @staticmethod
1437 def get_vars_f2():
1438 BuiltinTest.get_vars_f0()
1439 a = 1
1440 b = 2
1441 return vars()
1443 class C_get_vars(object):
1444 def getDict(self):
1445 return {'a':2}
1446 __dict__ = property(fget=getDict)
1448 def test_vars(self):
1449 self.assertEqual(set(vars()), set(dir()))
1450 import sys
1451 self.assertEqual(set(vars(sys)), set(dir(sys)))
1452 self.assertEqual(self.get_vars_f0(), {})
1453 self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
1454 self.assertRaises(TypeError, vars, 42, 42)
1455 self.assertRaises(TypeError, vars, 42)
1456 self.assertEqual(vars(self.C_get_vars()), {'a':2})
1458 def test_zip(self):
1459 a = (1, 2, 3)
1460 b = (4, 5, 6)
1461 t = [(1, 4), (2, 5), (3, 6)]
1462 self.assertEqual(zip(a, b), t)
1463 b = [4, 5, 6]
1464 self.assertEqual(zip(a, b), t)
1465 b = (4, 5, 6, 7)
1466 self.assertEqual(zip(a, b), t)
1467 class I:
1468 def __getitem__(self, i):
1469 if i < 0 or i > 2: raise IndexError
1470 return i + 4
1471 self.assertEqual(zip(a, I()), t)
1472 self.assertEqual(zip(), [])
1473 self.assertEqual(zip(*[]), [])
1474 self.assertRaises(TypeError, zip, None)
1475 class G:
1476 pass
1477 self.assertRaises(TypeError, zip, a, G())
1479 # Make sure zip doesn't try to allocate a billion elements for the
1480 # result list when one of its arguments doesn't say how long it is.
1481 # A MemoryError is the most likely failure mode.
1482 class SequenceWithoutALength:
1483 def __getitem__(self, i):
1484 if i == 5:
1485 raise IndexError
1486 else:
1487 return i
1488 self.assertEqual(
1489 zip(SequenceWithoutALength(), xrange(2**30)),
1490 list(enumerate(range(5)))
1493 class BadSeq:
1494 def __getitem__(self, i):
1495 if i == 5:
1496 raise ValueError
1497 else:
1498 return i
1499 self.assertRaises(ValueError, zip, BadSeq(), BadSeq())
1501 def test_format(self):
1502 # Test the basic machinery of the format() builtin. Don't test
1503 # the specifics of the various formatters
1504 self.assertEqual(format(3, ''), '3')
1506 # Returns some classes to use for various tests. There's
1507 # an old-style version, and a new-style version
1508 def classes_new():
1509 class A(object):
1510 def __init__(self, x):
1511 self.x = x
1512 def __format__(self, format_spec):
1513 return str(self.x) + format_spec
1514 class DerivedFromA(A):
1515 pass
1517 class Simple(object): pass
1518 class DerivedFromSimple(Simple):
1519 def __init__(self, x):
1520 self.x = x
1521 def __format__(self, format_spec):
1522 return str(self.x) + format_spec
1523 class DerivedFromSimple2(DerivedFromSimple): pass
1524 return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
1526 # In 3.0, classes_classic has the same meaning as classes_new
1527 def classes_classic():
1528 class A:
1529 def __init__(self, x):
1530 self.x = x
1531 def __format__(self, format_spec):
1532 return str(self.x) + format_spec
1533 class DerivedFromA(A):
1534 pass
1536 class Simple: pass
1537 class DerivedFromSimple(Simple):
1538 def __init__(self, x):
1539 self.x = x
1540 def __format__(self, format_spec):
1541 return str(self.x) + format_spec
1542 class DerivedFromSimple2(DerivedFromSimple): pass
1543 return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
1545 def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
1546 self.assertEqual(format(A(3), 'spec'), '3spec')
1547 self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
1548 self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
1549 self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
1550 '10abcdef')
1552 class_test(*classes_new())
1553 class_test(*classes_classic())
1555 def empty_format_spec(value):
1556 # test that:
1557 # format(x, '') == str(x)
1558 # format(x) == str(x)
1559 self.assertEqual(format(value, ""), str(value))
1560 self.assertEqual(format(value), str(value))
1562 # for builtin types, format(x, "") == str(x)
1563 empty_format_spec(17**13)
1564 empty_format_spec(1.0)
1565 empty_format_spec(3.1415e104)
1566 empty_format_spec(-3.1415e104)
1567 empty_format_spec(3.1415e-104)
1568 empty_format_spec(-3.1415e-104)
1569 empty_format_spec(object)
1570 empty_format_spec(None)
1572 # TypeError because self.__format__ returns the wrong type
1573 class BadFormatResult:
1574 def __format__(self, format_spec):
1575 return 1.0
1576 self.assertRaises(TypeError, format, BadFormatResult(), "")
1578 # TypeError because format_spec is not unicode or str
1579 self.assertRaises(TypeError, format, object(), 4)
1580 self.assertRaises(TypeError, format, object(), object())
1582 # tests for object.__format__ really belong elsewhere, but
1583 # there's no good place to put them
1584 x = object().__format__('')
1585 self.assertTrue(x.startswith('<object object at'))
1587 # first argument to object.__format__ must be string
1588 self.assertRaises(TypeError, object().__format__, 3)
1589 self.assertRaises(TypeError, object().__format__, object())
1590 self.assertRaises(TypeError, object().__format__, None)
1592 # --------------------------------------------------------------------
1593 # Issue #7994: object.__format__ with a non-empty format string is
1594 # pending deprecated
1595 def test_deprecated_format_string(obj, fmt_str, should_raise_warning):
1596 with warnings.catch_warnings(record=True) as w:
1597 warnings.simplefilter("always", PendingDeprecationWarning)
1598 format(obj, fmt_str)
1599 if should_raise_warning:
1600 self.assertEqual(len(w), 1)
1601 self.assertIsInstance(w[0].message, PendingDeprecationWarning)
1602 self.assertIn('object.__format__ with a non-empty format '
1603 'string', str(w[0].message))
1604 else:
1605 self.assertEqual(len(w), 0)
1607 fmt_strs = ['', 's', u'', u's']
1609 class A:
1610 def __format__(self, fmt_str):
1611 return format('', fmt_str)
1613 for fmt_str in fmt_strs:
1614 test_deprecated_format_string(A(), fmt_str, False)
1616 class B:
1617 pass
1619 class C(object):
1620 pass
1622 for cls in [object, B, C]:
1623 for fmt_str in fmt_strs:
1624 test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0)
1625 # --------------------------------------------------------------------
1627 # make sure we can take a subclass of str as a format spec
1628 class DerivedFromStr(str): pass
1629 self.assertEqual(format(0, DerivedFromStr('10')), ' 0')
1631 def test_bin(self):
1632 self.assertEqual(bin(0), '0b0')
1633 self.assertEqual(bin(1), '0b1')
1634 self.assertEqual(bin(-1), '-0b1')
1635 self.assertEqual(bin(2**65), '0b1' + '0' * 65)
1636 self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
1637 self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
1638 self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
1640 def test_bytearray_translate(self):
1641 x = bytearray("abc")
1642 self.assertRaises(ValueError, x.translate, "1", 1)
1643 self.assertRaises(TypeError, x.translate, "1"*256, 1)
1645 class TestSorted(unittest.TestCase):
1647 def test_basic(self):
1648 data = range(100)
1649 copy = data[:]
1650 random.shuffle(copy)
1651 self.assertEqual(data, sorted(copy))
1652 self.assertNotEqual(data, copy)
1654 data.reverse()
1655 random.shuffle(copy)
1656 self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x)))
1657 self.assertNotEqual(data, copy)
1658 random.shuffle(copy)
1659 self.assertEqual(data, sorted(copy, key=lambda x: -x))
1660 self.assertNotEqual(data, copy)
1661 random.shuffle(copy)
1662 self.assertEqual(data, sorted(copy, reverse=1))
1663 self.assertNotEqual(data, copy)
1665 def test_inputtypes(self):
1666 s = 'abracadabra'
1667 types = [list, tuple]
1668 if have_unicode:
1669 types.insert(0, unicode)
1670 for T in types:
1671 self.assertEqual(sorted(s), sorted(T(s)))
1673 s = ''.join(dict.fromkeys(s).keys()) # unique letters only
1674 types = [set, frozenset, list, tuple, dict.fromkeys]
1675 if have_unicode:
1676 types.insert(0, unicode)
1677 for T in types:
1678 self.assertEqual(sorted(s), sorted(T(s)))
1680 def test_baddecorator(self):
1681 data = 'The quick Brown fox Jumped over The lazy Dog'.split()
1682 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
1684 def _run_unittest(*args):
1685 with check_py3k_warnings(
1686 (".+ not supported in 3.x", DeprecationWarning),
1687 (".+ is renamed to imp.reload", DeprecationWarning),
1688 ("classic int division", DeprecationWarning)):
1689 run_unittest(*args)
1691 def test_main(verbose=None):
1692 test_classes = (BuiltinTest, TestSorted)
1694 _run_unittest(*test_classes)
1696 # verify reference counting
1697 if verbose and hasattr(sys, "gettotalrefcount"):
1698 import gc
1699 counts = [None] * 5
1700 for i in xrange(len(counts)):
1701 _run_unittest(*test_classes)
1702 gc.collect()
1703 counts[i] = sys.gettotalrefcount()
1704 print counts
1707 if __name__ == "__main__":
1708 test_main(verbose=True)