Change a variable type to avoid signed overflow; replace repeated '19999' constant...
[python.git] / Lib / test / test_builtin.py
blobf20d5430068fcc9aa2b06c0b2e168982620e1425
1 # Python test set -- built-in functions
3 import platform
4 import test.test_support, unittest
5 from test.test_support import fcmp, have_unicode, TESTFN, unlink, \
6 run_unittest, run_with_locale
7 from operator import neg
9 import sys, warnings, cStringIO, random, fractions, UserDict
10 warnings.filterwarnings("ignore", "hex../oct.. of negative int",
11 FutureWarning, __name__)
12 warnings.filterwarnings("ignore", "integer argument expected",
13 DeprecationWarning, "unittest")
15 # count the number of test runs.
16 # used to skip running test_execfile() multiple times
17 # and to create unique strings to intern in test_intern()
18 numruns = 0
20 class Squares:
22 def __init__(self, max):
23 self.max = max
24 self.sofar = []
26 def __len__(self): return len(self.sofar)
28 def __getitem__(self, i):
29 if not 0 <= i < self.max: raise IndexError
30 n = len(self.sofar)
31 while n <= i:
32 self.sofar.append(n*n)
33 n += 1
34 return self.sofar[i]
36 class StrSquares:
38 def __init__(self, max):
39 self.max = max
40 self.sofar = []
42 def __len__(self):
43 return len(self.sofar)
45 def __getitem__(self, i):
46 if not 0 <= i < self.max:
47 raise IndexError
48 n = len(self.sofar)
49 while n <= i:
50 self.sofar.append(str(n*n))
51 n += 1
52 return self.sofar[i]
54 class BitBucket:
55 def write(self, line):
56 pass
59 class TestFailingBool:
60 def __nonzero__(self):
61 raise RuntimeError
63 class TestFailingIter:
64 def __iter__(self):
65 raise RuntimeError
67 class BuiltinTest(unittest.TestCase):
69 def test_import(self):
70 __import__('sys')
71 __import__('time')
72 __import__('string')
73 __import__(name='sys')
74 __import__(name='time', level=0)
75 self.assertRaises(ImportError, __import__, 'spamspam')
76 self.assertRaises(TypeError, __import__, 1, 2, 3, 4)
77 self.assertRaises(ValueError, __import__, '')
78 self.assertRaises(TypeError, __import__, 'sys', name='sys')
80 def test_abs(self):
81 # int
82 self.assertEqual(abs(0), 0)
83 self.assertEqual(abs(1234), 1234)
84 self.assertEqual(abs(-1234), 1234)
85 self.assertTrue(abs(-sys.maxint-1) > 0)
86 # float
87 self.assertEqual(abs(0.0), 0.0)
88 self.assertEqual(abs(3.14), 3.14)
89 self.assertEqual(abs(-3.14), 3.14)
90 # long
91 self.assertEqual(abs(0L), 0L)
92 self.assertEqual(abs(1234L), 1234L)
93 self.assertEqual(abs(-1234L), 1234L)
94 # str
95 self.assertRaises(TypeError, abs, 'a')
97 def test_all(self):
98 self.assertEqual(all([2, 4, 6]), True)
99 self.assertEqual(all([2, None, 6]), False)
100 self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
101 self.assertRaises(RuntimeError, all, TestFailingIter())
102 self.assertRaises(TypeError, all, 10) # Non-iterable
103 self.assertRaises(TypeError, all) # No args
104 self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args
105 self.assertEqual(all([]), True) # Empty iterator
106 S = [50, 60]
107 self.assertEqual(all(x > 42 for x in S), True)
108 S = [50, 40, 60]
109 self.assertEqual(all(x > 42 for x in S), False)
111 def test_any(self):
112 self.assertEqual(any([None, None, None]), False)
113 self.assertEqual(any([None, 4, None]), True)
114 self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
115 self.assertRaises(RuntimeError, all, TestFailingIter())
116 self.assertRaises(TypeError, any, 10) # Non-iterable
117 self.assertRaises(TypeError, any) # No args
118 self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args
119 self.assertEqual(any([]), False) # Empty iterator
120 S = [40, 60, 30]
121 self.assertEqual(any(x > 42 for x in S), True)
122 S = [10, 20, 30]
123 self.assertEqual(any(x > 42 for x in S), False)
125 def test_neg(self):
126 x = -sys.maxint-1
127 self.assertTrue(isinstance(x, int))
128 self.assertEqual(-x, sys.maxint+1)
130 def test_apply(self):
131 def f0(*args):
132 self.assertEqual(args, ())
133 def f1(a1):
134 self.assertEqual(a1, 1)
135 def f2(a1, a2):
136 self.assertEqual(a1, 1)
137 self.assertEqual(a2, 2)
138 def f3(a1, a2, a3):
139 self.assertEqual(a1, 1)
140 self.assertEqual(a2, 2)
141 self.assertEqual(a3, 3)
142 apply(f0, ())
143 apply(f1, (1,))
144 apply(f2, (1, 2))
145 apply(f3, (1, 2, 3))
147 # A PyCFunction that takes only positional parameters should allow an
148 # empty keyword dictionary to pass without a complaint, but raise a
149 # TypeError if the dictionary is non-empty.
150 apply(id, (1,), {})
151 self.assertRaises(TypeError, apply, id, (1,), {"foo": 1})
152 self.assertRaises(TypeError, apply)
153 self.assertRaises(TypeError, apply, id, 42)
154 self.assertRaises(TypeError, apply, id, (42,), 42)
156 def test_callable(self):
157 self.assertTrue(callable(len))
158 def f(): pass
159 self.assertTrue(callable(f))
160 class C:
161 def meth(self): pass
162 self.assertTrue(callable(C))
163 x = C()
164 self.assertTrue(callable(x.meth))
165 self.assertTrue(not callable(x))
166 class D(C):
167 def __call__(self): pass
168 y = D()
169 self.assertTrue(callable(y))
172 def test_chr(self):
173 self.assertEqual(chr(32), ' ')
174 self.assertEqual(chr(65), 'A')
175 self.assertEqual(chr(97), 'a')
176 self.assertEqual(chr(0xff), '\xff')
177 self.assertRaises(ValueError, chr, 256)
178 self.assertRaises(TypeError, chr)
180 def test_cmp(self):
181 self.assertEqual(cmp(-1, 1), -1)
182 self.assertEqual(cmp(1, -1), 1)
183 self.assertEqual(cmp(1, 1), 0)
184 # verify that circular objects are not handled
185 a = []; a.append(a)
186 b = []; b.append(b)
187 from UserList import UserList
188 c = UserList(); c.append(c)
189 self.assertRaises(RuntimeError, cmp, a, b)
190 self.assertRaises(RuntimeError, cmp, b, c)
191 self.assertRaises(RuntimeError, cmp, c, a)
192 self.assertRaises(RuntimeError, cmp, a, c)
193 # okay, now break the cycles
194 a.pop(); b.pop(); c.pop()
195 self.assertRaises(TypeError, cmp)
197 def test_coerce(self):
198 self.assertTrue(not fcmp(coerce(1, 1.1), (1.0, 1.1)))
199 self.assertEqual(coerce(1, 1L), (1L, 1L))
200 self.assertTrue(not fcmp(coerce(1L, 1.1), (1.0, 1.1)))
201 self.assertRaises(TypeError, coerce)
202 class BadNumber:
203 def __coerce__(self, other):
204 raise ValueError
205 self.assertRaises(ValueError, coerce, 42, BadNumber())
206 self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000))
208 def test_compile(self):
209 compile('print 1\n', '', 'exec')
210 bom = '\xef\xbb\xbf'
211 compile(bom + 'print 1\n', '', 'exec')
212 compile(source='pass', filename='?', mode='exec')
213 compile(dont_inherit=0, filename='tmp', source='0', mode='eval')
214 compile('pass', '?', dont_inherit=1, mode='exec')
215 self.assertRaises(TypeError, compile)
216 self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
217 self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
218 self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
219 self.assertRaises(TypeError, compile, 'pass', '?', 'exec',
220 mode='eval', source='0', filename='tmp')
221 if have_unicode:
222 compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
223 self.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
224 self.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
227 def test_delattr(self):
228 import sys
229 sys.spam = 1
230 delattr(sys, 'spam')
231 self.assertRaises(TypeError, delattr)
233 def test_dir(self):
234 # dir(wrong number of arguments)
235 self.assertRaises(TypeError, dir, 42, 42)
237 # dir() - local scope
238 local_var = 1
239 self.assertTrue('local_var' in dir())
241 # dir(module)
242 import sys
243 self.assertTrue('exit' in dir(sys))
245 # dir(module_with_invalid__dict__)
246 import types
247 class Foo(types.ModuleType):
248 __dict__ = 8
249 f = Foo("foo")
250 self.assertRaises(TypeError, dir, f)
252 # dir(type)
253 self.assertTrue("strip" in dir(str))
254 self.assertTrue("__mro__" not in dir(str))
256 # dir(obj)
257 class Foo(object):
258 def __init__(self):
259 self.x = 7
260 self.y = 8
261 self.z = 9
262 f = Foo()
263 self.assertTrue("y" in dir(f))
265 # dir(obj_no__dict__)
266 class Foo(object):
267 __slots__ = []
268 f = Foo()
269 self.assertTrue("__repr__" in dir(f))
271 # dir(obj_no__class__with__dict__)
272 # (an ugly trick to cause getattr(f, "__class__") to fail)
273 class Foo(object):
274 __slots__ = ["__class__", "__dict__"]
275 def __init__(self):
276 self.bar = "wow"
277 f = Foo()
278 self.assertTrue("__repr__" not in dir(f))
279 self.assertTrue("bar" in dir(f))
281 # dir(obj_using __dir__)
282 class Foo(object):
283 def __dir__(self):
284 return ["kan", "ga", "roo"]
285 f = Foo()
286 self.assertTrue(dir(f) == ["ga", "kan", "roo"])
288 # dir(obj__dir__not_list)
289 class Foo(object):
290 def __dir__(self):
291 return 7
292 f = Foo()
293 self.assertRaises(TypeError, dir, f)
295 def test_divmod(self):
296 self.assertEqual(divmod(12, 7), (1, 5))
297 self.assertEqual(divmod(-12, 7), (-2, 2))
298 self.assertEqual(divmod(12, -7), (-2, -2))
299 self.assertEqual(divmod(-12, -7), (1, -5))
301 self.assertEqual(divmod(12L, 7L), (1L, 5L))
302 self.assertEqual(divmod(-12L, 7L), (-2L, 2L))
303 self.assertEqual(divmod(12L, -7L), (-2L, -2L))
304 self.assertEqual(divmod(-12L, -7L), (1L, -5L))
306 self.assertEqual(divmod(12, 7L), (1, 5L))
307 self.assertEqual(divmod(-12, 7L), (-2, 2L))
308 self.assertEqual(divmod(12L, -7), (-2L, -2))
309 self.assertEqual(divmod(-12L, -7), (1L, -5))
311 self.assertEqual(divmod(-sys.maxint-1, -1),
312 (sys.maxint+1, 0))
314 self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
315 self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
316 self.assertTrue(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
317 self.assertTrue(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
319 self.assertRaises(TypeError, divmod)
321 def test_eval(self):
322 self.assertEqual(eval('1+1'), 2)
323 self.assertEqual(eval(' 1+1\n'), 2)
324 globals = {'a': 1, 'b': 2}
325 locals = {'b': 200, 'c': 300}
326 self.assertEqual(eval('a', globals) , 1)
327 self.assertEqual(eval('a', globals, locals), 1)
328 self.assertEqual(eval('b', globals, locals), 200)
329 self.assertEqual(eval('c', globals, locals), 300)
330 if have_unicode:
331 self.assertEqual(eval(unicode('1+1')), 2)
332 self.assertEqual(eval(unicode(' 1+1\n')), 2)
333 globals = {'a': 1, 'b': 2}
334 locals = {'b': 200, 'c': 300}
335 if have_unicode:
336 self.assertEqual(eval(unicode('a'), globals), 1)
337 self.assertEqual(eval(unicode('a'), globals, locals), 1)
338 self.assertEqual(eval(unicode('b'), globals, locals), 200)
339 self.assertEqual(eval(unicode('c'), globals, locals), 300)
340 bom = '\xef\xbb\xbf'
341 self.assertEqual(eval(bom + 'a', globals, locals), 1)
342 self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals),
343 unicode('\xc3\xa5', 'utf8'))
344 self.assertRaises(TypeError, eval)
345 self.assertRaises(TypeError, eval, ())
347 def test_general_eval(self):
348 # Tests that general mappings can be used for the locals argument
350 class M:
351 "Test mapping interface versus possible calls from eval()."
352 def __getitem__(self, key):
353 if key == 'a':
354 return 12
355 raise KeyError
356 def keys(self):
357 return list('xyz')
359 m = M()
360 g = globals()
361 self.assertEqual(eval('a', g, m), 12)
362 self.assertRaises(NameError, eval, 'b', g, m)
363 self.assertEqual(eval('dir()', g, m), list('xyz'))
364 self.assertEqual(eval('globals()', g, m), g)
365 self.assertEqual(eval('locals()', g, m), m)
366 self.assertRaises(TypeError, eval, 'a', m)
367 class A:
368 "Non-mapping"
369 pass
370 m = A()
371 self.assertRaises(TypeError, eval, 'a', g, m)
373 # Verify that dict subclasses work as well
374 class D(dict):
375 def __getitem__(self, key):
376 if key == 'a':
377 return 12
378 return dict.__getitem__(self, key)
379 def keys(self):
380 return list('xyz')
382 d = D()
383 self.assertEqual(eval('a', g, d), 12)
384 self.assertRaises(NameError, eval, 'b', g, d)
385 self.assertEqual(eval('dir()', g, d), list('xyz'))
386 self.assertEqual(eval('globals()', g, d), g)
387 self.assertEqual(eval('locals()', g, d), d)
389 # Verify locals stores (used by list comps)
390 eval('[locals() for i in (2,3)]', g, d)
391 eval('[locals() for i in (2,3)]', g, UserDict.UserDict())
393 class SpreadSheet:
394 "Sample application showing nested, calculated lookups."
395 _cells = {}
396 def __setitem__(self, key, formula):
397 self._cells[key] = formula
398 def __getitem__(self, key):
399 return eval(self._cells[key], globals(), self)
401 ss = SpreadSheet()
402 ss['a1'] = '5'
403 ss['a2'] = 'a1*6'
404 ss['a3'] = 'a2*7'
405 self.assertEqual(ss['a3'], 210)
407 # Verify that dir() catches a non-list returned by eval
408 # SF bug #1004669
409 class C:
410 def __getitem__(self, item):
411 raise KeyError(item)
412 def keys(self):
413 return 'a'
414 self.assertRaises(TypeError, eval, 'dir()', globals(), C())
416 # Done outside of the method test_z to get the correct scope
417 z = 0
418 f = open(TESTFN, 'w')
419 f.write('z = z+1\n')
420 f.write('z = z*2\n')
421 f.close()
422 execfile(TESTFN)
424 def test_execfile(self):
425 global numruns
426 if numruns:
427 return
428 numruns += 1
430 globals = {'a': 1, 'b': 2}
431 locals = {'b': 200, 'c': 300}
433 self.assertEqual(self.__class__.z, 2)
434 globals['z'] = 0
435 execfile(TESTFN, globals)
436 self.assertEqual(globals['z'], 2)
437 locals['z'] = 0
438 execfile(TESTFN, globals, locals)
439 self.assertEqual(locals['z'], 2)
441 class M:
442 "Test mapping interface versus possible calls from execfile()."
443 def __init__(self):
444 self.z = 10
445 def __getitem__(self, key):
446 if key == 'z':
447 return self.z
448 raise KeyError
449 def __setitem__(self, key, value):
450 if key == 'z':
451 self.z = value
452 return
453 raise KeyError
455 locals = M()
456 locals['z'] = 0
457 execfile(TESTFN, globals, locals)
458 self.assertEqual(locals['z'], 2)
460 unlink(TESTFN)
461 self.assertRaises(TypeError, execfile)
462 self.assertRaises(TypeError, execfile, TESTFN, {}, ())
463 import os
464 self.assertRaises(IOError, execfile, os.curdir)
465 self.assertRaises(IOError, execfile, "I_dont_exist")
467 def test_filter(self):
468 self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
469 self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
470 self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2])
471 self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
472 self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81])
473 def identity(item):
474 return 1
475 filter(identity, Squares(5))
476 self.assertRaises(TypeError, filter)
477 class BadSeq(object):
478 def __getitem__(self, index):
479 if index<4:
480 return 42
481 raise ValueError
482 self.assertRaises(ValueError, filter, lambda x: x, BadSeq())
483 def badfunc():
484 pass
485 self.assertRaises(TypeError, filter, badfunc, range(5))
487 # test bltinmodule.c::filtertuple()
488 self.assertEqual(filter(None, (1, 2)), (1, 2))
489 self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4))
490 self.assertRaises(TypeError, filter, 42, (1, 2))
492 # test bltinmodule.c::filterstring()
493 self.assertEqual(filter(None, "12"), "12")
494 self.assertEqual(filter(lambda x: x>="3", "1234"), "34")
495 self.assertRaises(TypeError, filter, 42, "12")
496 class badstr(str):
497 def __getitem__(self, index):
498 raise ValueError
499 self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234"))
501 class badstr2(str):
502 def __getitem__(self, index):
503 return 42
504 self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234"))
506 class weirdstr(str):
507 def __getitem__(self, index):
508 return weirdstr(2*str.__getitem__(self, index))
509 self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344")
511 class shiftstr(str):
512 def __getitem__(self, index):
513 return chr(ord(str.__getitem__(self, index))+1)
514 self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345")
516 if have_unicode:
517 # test bltinmodule.c::filterunicode()
518 self.assertEqual(filter(None, unicode("12")), unicode("12"))
519 self.assertEqual(filter(lambda x: x>="3", unicode("1234")), unicode("34"))
520 self.assertRaises(TypeError, filter, 42, unicode("12"))
521 self.assertRaises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234")))
523 class badunicode(unicode):
524 def __getitem__(self, index):
525 return 42
526 self.assertRaises(TypeError, filter, lambda x: x >=42, badunicode("1234"))
528 class weirdunicode(unicode):
529 def __getitem__(self, index):
530 return weirdunicode(2*unicode.__getitem__(self, index))
531 self.assertEqual(
532 filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344"))
534 class shiftunicode(unicode):
535 def __getitem__(self, index):
536 return unichr(ord(unicode.__getitem__(self, index))+1)
537 self.assertEqual(
538 filter(lambda x: x>=unicode("3"), shiftunicode("1234")),
539 unicode("345")
542 def test_filter_subclasses(self):
543 # test that filter() never returns tuple, str or unicode subclasses
544 # and that the result always goes through __getitem__
545 funcs = (None, bool, lambda x: True)
546 class tuple2(tuple):
547 def __getitem__(self, index):
548 return 2*tuple.__getitem__(self, index)
549 class str2(str):
550 def __getitem__(self, index):
551 return 2*str.__getitem__(self, index)
552 inputs = {
553 tuple2: {(): (), (1, 2, 3): (2, 4, 6)},
554 str2: {"": "", "123": "112233"}
556 if have_unicode:
557 class unicode2(unicode):
558 def __getitem__(self, index):
559 return 2*unicode.__getitem__(self, index)
560 inputs[unicode2] = {
561 unicode(): unicode(),
562 unicode("123"): unicode("112233")
565 for (cls, inps) in inputs.iteritems():
566 for (inp, exp) in inps.iteritems():
567 # make sure the output goes through __getitem__
568 # even if func is None
569 self.assertEqual(
570 filter(funcs[0], cls(inp)),
571 filter(funcs[1], cls(inp))
573 for func in funcs:
574 outp = filter(func, cls(inp))
575 self.assertEqual(outp, exp)
576 self.assertTrue(not isinstance(outp, cls))
578 def test_getattr(self):
579 import sys
580 self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
581 self.assertRaises(TypeError, getattr, sys, 1)
582 self.assertRaises(TypeError, getattr, sys, 1, "foo")
583 self.assertRaises(TypeError, getattr)
584 if have_unicode:
585 self.assertRaises(UnicodeError, getattr, sys, unichr(sys.maxunicode))
587 def test_hasattr(self):
588 import sys
589 self.assertTrue(hasattr(sys, 'stdout'))
590 self.assertRaises(TypeError, hasattr, sys, 1)
591 self.assertRaises(TypeError, hasattr)
592 if have_unicode:
593 self.assertRaises(UnicodeError, hasattr, sys, unichr(sys.maxunicode))
595 # Check that hasattr allows SystemExit and KeyboardInterrupts by
596 class A:
597 def __getattr__(self, what):
598 raise KeyboardInterrupt
599 self.assertRaises(KeyboardInterrupt, hasattr, A(), "b")
600 class B:
601 def __getattr__(self, what):
602 raise SystemExit
603 self.assertRaises(SystemExit, hasattr, B(), "b")
605 def test_hash(self):
606 hash(None)
607 self.assertEqual(hash(1), hash(1L))
608 self.assertEqual(hash(1), hash(1.0))
609 hash('spam')
610 if have_unicode:
611 self.assertEqual(hash('spam'), hash(unicode('spam')))
612 hash((0,1,2,3))
613 def f(): pass
614 self.assertRaises(TypeError, hash, [])
615 self.assertRaises(TypeError, hash, {})
616 # Bug 1536021: Allow hash to return long objects
617 class X:
618 def __hash__(self):
619 return 2**100
620 self.assertEquals(type(hash(X())), int)
621 class Y(object):
622 def __hash__(self):
623 return 2**100
624 self.assertEquals(type(hash(Y())), int)
625 class Z(long):
626 def __hash__(self):
627 return self
628 self.assertEquals(hash(Z(42)), hash(42L))
630 def test_hex(self):
631 self.assertEqual(hex(16), '0x10')
632 self.assertEqual(hex(16L), '0x10L')
633 self.assertEqual(hex(-16), '-0x10')
634 self.assertEqual(hex(-16L), '-0x10L')
635 self.assertRaises(TypeError, hex, {})
637 def test_id(self):
638 id(None)
639 id(1)
640 id(1L)
641 id(1.0)
642 id('spam')
643 id((0,1,2,3))
644 id([0,1,2,3])
645 id({'spam': 1, 'eggs': 2, 'ham': 3})
647 # Test input() later, together with raw_input
649 def test_intern(self):
650 self.assertRaises(TypeError, intern)
651 # This fails if the test is run twice with a constant string,
652 # therefore append the run counter
653 s = "never interned before " + str(numruns)
654 self.assertTrue(intern(s) is s)
655 s2 = s.swapcase().swapcase()
656 self.assertTrue(intern(s2) is s)
658 # Subclasses of string can't be interned, because they
659 # provide too much opportunity for insane things to happen.
660 # We don't want them in the interned dict and if they aren't
661 # actually interned, we don't want to create the appearance
662 # that they are by allowing intern() to succeeed.
663 class S(str):
664 def __hash__(self):
665 return 123
667 self.assertRaises(TypeError, intern, S("abc"))
669 # It's still safe to pass these strings to routines that
670 # call intern internally, e.g. PyObject_SetAttr().
671 s = S("abc")
672 setattr(s, s, s)
673 self.assertEqual(getattr(s, s), s)
675 def test_iter(self):
676 self.assertRaises(TypeError, iter)
677 self.assertRaises(TypeError, iter, 42, 42)
678 lists = [("1", "2"), ["1", "2"], "12"]
679 if have_unicode:
680 lists.append(unicode("12"))
681 for l in lists:
682 i = iter(l)
683 self.assertEqual(i.next(), '1')
684 self.assertEqual(i.next(), '2')
685 self.assertRaises(StopIteration, i.next)
687 def test_isinstance(self):
688 class C:
689 pass
690 class D(C):
691 pass
692 class E:
693 pass
694 c = C()
695 d = D()
696 e = E()
697 self.assertTrue(isinstance(c, C))
698 self.assertTrue(isinstance(d, C))
699 self.assertTrue(not isinstance(e, C))
700 self.assertTrue(not isinstance(c, D))
701 self.assertTrue(not isinstance('foo', E))
702 self.assertRaises(TypeError, isinstance, E, 'foo')
703 self.assertRaises(TypeError, isinstance)
705 def test_issubclass(self):
706 class C:
707 pass
708 class D(C):
709 pass
710 class E:
711 pass
712 c = C()
713 d = D()
714 e = E()
715 self.assertTrue(issubclass(D, C))
716 self.assertTrue(issubclass(C, C))
717 self.assertTrue(not issubclass(C, D))
718 self.assertRaises(TypeError, issubclass, 'foo', E)
719 self.assertRaises(TypeError, issubclass, E, 'foo')
720 self.assertRaises(TypeError, issubclass)
722 def test_len(self):
723 self.assertEqual(len('123'), 3)
724 self.assertEqual(len(()), 0)
725 self.assertEqual(len((1, 2, 3, 4)), 4)
726 self.assertEqual(len([1, 2, 3, 4]), 4)
727 self.assertEqual(len({}), 0)
728 self.assertEqual(len({'a':1, 'b': 2}), 2)
729 class BadSeq:
730 def __len__(self):
731 raise ValueError
732 self.assertRaises(ValueError, len, BadSeq())
734 def test_map(self):
735 self.assertEqual(
736 map(None, 'hello world'),
737 ['h','e','l','l','o',' ','w','o','r','l','d']
739 self.assertEqual(
740 map(None, 'abcd', 'efg'),
741 [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
743 self.assertEqual(
744 map(None, range(10)),
745 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
747 self.assertEqual(
748 map(lambda x: x*x, range(1,4)),
749 [1, 4, 9]
751 try:
752 from math import sqrt
753 except ImportError:
754 def sqrt(x):
755 return pow(x, 0.5)
756 self.assertEqual(
757 map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]),
758 [[4.0, 2.0], [9.0, 3.0]]
760 self.assertEqual(
761 map(lambda x, y: x+y, [1,3,2], [9,1,4]),
762 [10, 4, 6]
765 def plus(*v):
766 accu = 0
767 for i in v: accu = accu + i
768 return accu
769 self.assertEqual(
770 map(plus, [1, 3, 7]),
771 [1, 3, 7]
773 self.assertEqual(
774 map(plus, [1, 3, 7], [4, 9, 2]),
775 [1+4, 3+9, 7+2]
777 self.assertEqual(
778 map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
779 [1+4+1, 3+9+1, 7+2+0]
781 self.assertEqual(
782 map(None, Squares(10)),
783 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
785 self.assertEqual(
786 map(int, Squares(10)),
787 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
789 self.assertEqual(
790 map(None, Squares(3), Squares(2)),
791 [(0,0), (1,1), (4,None)]
793 self.assertEqual(
794 map(max, Squares(3), Squares(2)),
795 [0, 1, 4]
797 self.assertRaises(TypeError, map)
798 self.assertRaises(TypeError, map, lambda x: x, 42)
799 self.assertEqual(map(None, [42]), [42])
800 class BadSeq:
801 def __getitem__(self, index):
802 raise ValueError
803 self.assertRaises(ValueError, map, lambda x: x, BadSeq())
804 def badfunc(x):
805 raise RuntimeError
806 self.assertRaises(RuntimeError, map, badfunc, range(5))
808 def test_max(self):
809 self.assertEqual(max('123123'), '3')
810 self.assertEqual(max(1, 2, 3), 3)
811 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
812 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
814 self.assertEqual(max(1, 2L, 3.0), 3.0)
815 self.assertEqual(max(1L, 2.0, 3), 3)
816 self.assertEqual(max(1.0, 2, 3L), 3L)
818 for stmt in (
819 "max(key=int)", # no args
820 "max(1, key=int)", # single arg not iterable
821 "max(1, 2, keystone=int)", # wrong keyword
822 "max(1, 2, key=int, abc=int)", # two many keywords
823 "max(1, 2, key=1)", # keyfunc is not callable
825 try:
826 exec(stmt) in globals()
827 except TypeError:
828 pass
829 else:
830 self.fail(stmt)
832 self.assertEqual(max((1,), key=neg), 1) # one elem iterable
833 self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
834 self.assertEqual(max(1, 2, key=neg), 1) # two elems
836 data = [random.randrange(200) for i in range(100)]
837 keys = dict((elem, random.randrange(50)) for elem in data)
838 f = keys.__getitem__
839 self.assertEqual(max(data, key=f),
840 sorted(reversed(data), key=f)[-1])
842 def test_min(self):
843 self.assertEqual(min('123123'), '1')
844 self.assertEqual(min(1, 2, 3), 1)
845 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
846 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
848 self.assertEqual(min(1, 2L, 3.0), 1)
849 self.assertEqual(min(1L, 2.0, 3), 1L)
850 self.assertEqual(min(1.0, 2, 3L), 1.0)
852 self.assertRaises(TypeError, min)
853 self.assertRaises(TypeError, min, 42)
854 self.assertRaises(ValueError, min, ())
855 class BadSeq:
856 def __getitem__(self, index):
857 raise ValueError
858 self.assertRaises(ValueError, min, BadSeq())
859 class BadNumber:
860 def __cmp__(self, other):
861 raise ValueError
862 self.assertRaises(ValueError, min, (42, BadNumber()))
864 for stmt in (
865 "min(key=int)", # no args
866 "min(1, key=int)", # single arg not iterable
867 "min(1, 2, keystone=int)", # wrong keyword
868 "min(1, 2, key=int, abc=int)", # two many keywords
869 "min(1, 2, key=1)", # keyfunc is not callable
871 try:
872 exec(stmt) in globals()
873 except TypeError:
874 pass
875 else:
876 self.fail(stmt)
878 self.assertEqual(min((1,), key=neg), 1) # one elem iterable
879 self.assertEqual(min((1,2), key=neg), 2) # two elem iterable
880 self.assertEqual(min(1, 2, key=neg), 2) # two elems
882 data = [random.randrange(200) for i in range(100)]
883 keys = dict((elem, random.randrange(50)) for elem in data)
884 f = keys.__getitem__
885 self.assertEqual(min(data, key=f),
886 sorted(data, key=f)[0])
888 def test_next(self):
889 it = iter(range(2))
890 self.assertEqual(next(it), 0)
891 self.assertEqual(next(it), 1)
892 self.assertRaises(StopIteration, next, it)
893 self.assertRaises(StopIteration, next, it)
894 self.assertEquals(next(it, 42), 42)
896 class Iter(object):
897 def __iter__(self):
898 return self
899 def next(self):
900 raise StopIteration
902 it = iter(Iter())
903 self.assertEquals(next(it, 42), 42)
904 self.assertRaises(StopIteration, next, it)
906 def gen():
907 yield 1
908 return
910 it = gen()
911 self.assertEquals(next(it), 1)
912 self.assertRaises(StopIteration, next, it)
913 self.assertEquals(next(it, 42), 42)
915 def test_oct(self):
916 self.assertEqual(oct(100), '0144')
917 self.assertEqual(oct(100L), '0144L')
918 self.assertEqual(oct(-100), '-0144')
919 self.assertEqual(oct(-100L), '-0144L')
920 self.assertRaises(TypeError, oct, ())
922 def write_testfile(self):
923 # NB the first 4 lines are also used to test input and raw_input, below
924 fp = open(TESTFN, 'w')
925 try:
926 fp.write('1+1\n')
927 fp.write('1+1\n')
928 fp.write('The quick brown fox jumps over the lazy dog')
929 fp.write('.\n')
930 fp.write('Dear John\n')
931 fp.write('XXX'*100)
932 fp.write('YYY'*100)
933 finally:
934 fp.close()
936 def test_open(self):
937 self.write_testfile()
938 fp = open(TESTFN, 'r')
939 try:
940 self.assertEqual(fp.readline(4), '1+1\n')
941 self.assertEqual(fp.readline(4), '1+1\n')
942 self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n')
943 self.assertEqual(fp.readline(4), 'Dear')
944 self.assertEqual(fp.readline(100), ' John\n')
945 self.assertEqual(fp.read(300), 'XXX'*100)
946 self.assertEqual(fp.read(1000), 'YYY'*100)
947 finally:
948 fp.close()
949 unlink(TESTFN)
951 def test_ord(self):
952 self.assertEqual(ord(' '), 32)
953 self.assertEqual(ord('A'), 65)
954 self.assertEqual(ord('a'), 97)
955 if have_unicode:
956 self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode)
957 self.assertRaises(TypeError, ord, 42)
958 if have_unicode:
959 self.assertRaises(TypeError, ord, unicode("12"))
961 def test_pow(self):
962 self.assertEqual(pow(0,0), 1)
963 self.assertEqual(pow(0,1), 0)
964 self.assertEqual(pow(1,0), 1)
965 self.assertEqual(pow(1,1), 1)
967 self.assertEqual(pow(2,0), 1)
968 self.assertEqual(pow(2,10), 1024)
969 self.assertEqual(pow(2,20), 1024*1024)
970 self.assertEqual(pow(2,30), 1024*1024*1024)
972 self.assertEqual(pow(-2,0), 1)
973 self.assertEqual(pow(-2,1), -2)
974 self.assertEqual(pow(-2,2), 4)
975 self.assertEqual(pow(-2,3), -8)
977 self.assertEqual(pow(0L,0), 1)
978 self.assertEqual(pow(0L,1), 0)
979 self.assertEqual(pow(1L,0), 1)
980 self.assertEqual(pow(1L,1), 1)
982 self.assertEqual(pow(2L,0), 1)
983 self.assertEqual(pow(2L,10), 1024)
984 self.assertEqual(pow(2L,20), 1024*1024)
985 self.assertEqual(pow(2L,30), 1024*1024*1024)
987 self.assertEqual(pow(-2L,0), 1)
988 self.assertEqual(pow(-2L,1), -2)
989 self.assertEqual(pow(-2L,2), 4)
990 self.assertEqual(pow(-2L,3), -8)
992 self.assertAlmostEqual(pow(0.,0), 1.)
993 self.assertAlmostEqual(pow(0.,1), 0.)
994 self.assertAlmostEqual(pow(1.,0), 1.)
995 self.assertAlmostEqual(pow(1.,1), 1.)
997 self.assertAlmostEqual(pow(2.,0), 1.)
998 self.assertAlmostEqual(pow(2.,10), 1024.)
999 self.assertAlmostEqual(pow(2.,20), 1024.*1024.)
1000 self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
1002 self.assertAlmostEqual(pow(-2.,0), 1.)
1003 self.assertAlmostEqual(pow(-2.,1), -2.)
1004 self.assertAlmostEqual(pow(-2.,2), 4.)
1005 self.assertAlmostEqual(pow(-2.,3), -8.)
1007 for x in 2, 2L, 2.0:
1008 for y in 10, 10L, 10.0:
1009 for z in 1000, 1000L, 1000.0:
1010 if isinstance(x, float) or \
1011 isinstance(y, float) or \
1012 isinstance(z, float):
1013 self.assertRaises(TypeError, pow, x, y, z)
1014 else:
1015 self.assertAlmostEqual(pow(x, y, z), 24.0)
1017 self.assertRaises(TypeError, pow, -1, -2, 3)
1018 self.assertRaises(ValueError, pow, 1, 2, 0)
1019 self.assertRaises(TypeError, pow, -1L, -2L, 3L)
1020 self.assertRaises(ValueError, pow, 1L, 2L, 0L)
1021 # Will return complex in 3.0:
1022 self.assertRaises(ValueError, pow, -342.43, 0.234)
1024 self.assertRaises(TypeError, pow)
1026 def test_range(self):
1027 self.assertEqual(range(3), [0, 1, 2])
1028 self.assertEqual(range(1, 5), [1, 2, 3, 4])
1029 self.assertEqual(range(0), [])
1030 self.assertEqual(range(-3), [])
1031 self.assertEqual(range(1, 10, 3), [1, 4, 7])
1032 self.assertEqual(range(5, -5, -3), [5, 2, -1, -4])
1034 # Now test range() with longs
1035 self.assertEqual(range(-2**100), [])
1036 self.assertEqual(range(0, -2**100), [])
1037 self.assertEqual(range(0, 2**100, -1), [])
1038 self.assertEqual(range(0, 2**100, -1), [])
1040 a = long(10 * sys.maxint)
1041 b = long(100 * sys.maxint)
1042 c = long(50 * sys.maxint)
1044 self.assertEqual(range(a, a+2), [a, a+1])
1045 self.assertEqual(range(a+2, a, -1L), [a+2, a+1])
1046 self.assertEqual(range(a+4, a, -2), [a+4, a+2])
1048 seq = range(a, b, c)
1049 self.assertTrue(a in seq)
1050 self.assertTrue(b not in seq)
1051 self.assertEqual(len(seq), 2)
1053 seq = range(b, a, -c)
1054 self.assertTrue(b in seq)
1055 self.assertTrue(a not in seq)
1056 self.assertEqual(len(seq), 2)
1058 seq = range(-a, -b, -c)
1059 self.assertTrue(-a in seq)
1060 self.assertTrue(-b not in seq)
1061 self.assertEqual(len(seq), 2)
1063 self.assertRaises(TypeError, range)
1064 self.assertRaises(TypeError, range, 1, 2, 3, 4)
1065 self.assertRaises(ValueError, range, 1, 2, 0)
1066 self.assertRaises(ValueError, range, a, a + 1, long(0))
1068 class badzero(int):
1069 def __cmp__(self, other):
1070 raise RuntimeError
1071 __hash__ = None # Invalid cmp makes this unhashable
1072 self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
1074 # Reject floats when it would require PyLongs to represent.
1075 # (smaller floats still accepted, but deprecated)
1076 self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
1078 self.assertRaises(TypeError, range, 0, "spam")
1079 self.assertRaises(TypeError, range, 0, 42, "spam")
1081 self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint)
1082 self.assertRaises(OverflowError, range, 0, 2*sys.maxint)
1084 def test_input_and_raw_input(self):
1085 self.write_testfile()
1086 fp = open(TESTFN, 'r')
1087 savestdin = sys.stdin
1088 savestdout = sys.stdout # Eats the echo
1089 try:
1090 sys.stdin = fp
1091 sys.stdout = BitBucket()
1092 self.assertEqual(input(), 2)
1093 self.assertEqual(input('testing\n'), 2)
1094 self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.')
1095 self.assertEqual(raw_input('testing\n'), 'Dear John')
1097 # SF 1535165: don't segfault on closed stdin
1098 # sys.stdout must be a regular file for triggering
1099 sys.stdout = savestdout
1100 sys.stdin.close()
1101 self.assertRaises(ValueError, input)
1103 sys.stdout = BitBucket()
1104 sys.stdin = cStringIO.StringIO("NULL\0")
1105 self.assertRaises(TypeError, input, 42, 42)
1106 sys.stdin = cStringIO.StringIO(" 'whitespace'")
1107 self.assertEqual(input(), 'whitespace')
1108 sys.stdin = cStringIO.StringIO()
1109 self.assertRaises(EOFError, input)
1111 # SF 876178: make sure input() respect future options.
1112 sys.stdin = cStringIO.StringIO('1/2')
1113 sys.stdout = cStringIO.StringIO()
1114 exec compile('print input()', 'test_builtin_tmp', 'exec')
1115 sys.stdin.seek(0, 0)
1116 exec compile('from __future__ import division;print input()',
1117 'test_builtin_tmp', 'exec')
1118 sys.stdin.seek(0, 0)
1119 exec compile('print input()', 'test_builtin_tmp', 'exec')
1120 # The result we expect depends on whether new division semantics
1121 # are already in effect.
1122 if 1/2 == 0:
1123 # This test was compiled with old semantics.
1124 expected = ['0', '0.5', '0']
1125 else:
1126 # This test was compiled with new semantics (e.g., -Qnew
1127 # was given on the command line.
1128 expected = ['0.5', '0.5', '0.5']
1129 self.assertEqual(sys.stdout.getvalue().splitlines(), expected)
1131 del sys.stdout
1132 self.assertRaises(RuntimeError, input, 'prompt')
1133 del sys.stdin
1134 self.assertRaises(RuntimeError, input, 'prompt')
1135 finally:
1136 sys.stdin = savestdin
1137 sys.stdout = savestdout
1138 fp.close()
1139 unlink(TESTFN)
1141 def test_reduce(self):
1142 self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc')
1143 self.assertEqual(
1144 reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []),
1145 ['a','c','d','w']
1147 self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040)
1148 self.assertEqual(
1149 reduce(lambda x, y: x*y, range(2,21), 1L),
1150 2432902008176640000L
1152 self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285)
1153 self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285)
1154 self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0)
1155 self.assertRaises(TypeError, reduce)
1156 self.assertRaises(TypeError, reduce, 42, 42)
1157 self.assertRaises(TypeError, reduce, 42, 42, 42)
1158 self.assertEqual(reduce(42, "1"), "1") # func is never called with one item
1159 self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item
1160 self.assertRaises(TypeError, reduce, 42, (42, 42))
1162 class BadSeq:
1163 def __getitem__(self, index):
1164 raise ValueError
1165 self.assertRaises(ValueError, reduce, 42, BadSeq())
1167 def test_reload(self):
1168 import marshal
1169 reload(marshal)
1170 import string
1171 reload(string)
1172 ## import sys
1173 ## self.assertRaises(ImportError, reload, sys)
1175 def test_repr(self):
1176 self.assertEqual(repr(''), '\'\'')
1177 self.assertEqual(repr(0), '0')
1178 self.assertEqual(repr(0L), '0L')
1179 self.assertEqual(repr(()), '()')
1180 self.assertEqual(repr([]), '[]')
1181 self.assertEqual(repr({}), '{}')
1182 a = []
1183 a.append(a)
1184 self.assertEqual(repr(a), '[[...]]')
1185 a = {}
1186 a[0] = a
1187 self.assertEqual(repr(a), '{0: {...}}')
1189 def test_round(self):
1190 self.assertEqual(round(0.0), 0.0)
1191 self.assertEqual(type(round(0.0)), float) # Will be int in 3.0.
1192 self.assertEqual(round(1.0), 1.0)
1193 self.assertEqual(round(10.0), 10.0)
1194 self.assertEqual(round(1000000000.0), 1000000000.0)
1195 self.assertEqual(round(1e20), 1e20)
1197 self.assertEqual(round(-1.0), -1.0)
1198 self.assertEqual(round(-10.0), -10.0)
1199 self.assertEqual(round(-1000000000.0), -1000000000.0)
1200 self.assertEqual(round(-1e20), -1e20)
1202 self.assertEqual(round(0.1), 0.0)
1203 self.assertEqual(round(1.1), 1.0)
1204 self.assertEqual(round(10.1), 10.0)
1205 self.assertEqual(round(1000000000.1), 1000000000.0)
1207 self.assertEqual(round(-1.1), -1.0)
1208 self.assertEqual(round(-10.1), -10.0)
1209 self.assertEqual(round(-1000000000.1), -1000000000.0)
1211 self.assertEqual(round(0.9), 1.0)
1212 self.assertEqual(round(9.9), 10.0)
1213 self.assertEqual(round(999999999.9), 1000000000.0)
1215 self.assertEqual(round(-0.9), -1.0)
1216 self.assertEqual(round(-9.9), -10.0)
1217 self.assertEqual(round(-999999999.9), -1000000000.0)
1219 self.assertEqual(round(-8.0, -1), -10.0)
1220 self.assertEqual(type(round(-8.0, -1)), float)
1222 self.assertEqual(type(round(-8.0, 0)), float)
1223 self.assertEqual(type(round(-8.0, 1)), float)
1225 # Check half rounding behaviour.
1226 self.assertEqual(round(5.5), 6)
1227 self.assertEqual(round(6.5), 7)
1228 self.assertEqual(round(-5.5), -6)
1229 self.assertEqual(round(-6.5), -7)
1231 # Check behavior on ints
1232 self.assertEqual(round(0), 0)
1233 self.assertEqual(round(8), 8)
1234 self.assertEqual(round(-8), -8)
1235 self.assertEqual(type(round(0)), float) # Will be int in 3.0.
1236 self.assertEqual(type(round(-8, -1)), float)
1237 self.assertEqual(type(round(-8, 0)), float)
1238 self.assertEqual(type(round(-8, 1)), float)
1240 # test new kwargs
1241 self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)
1243 self.assertRaises(TypeError, round)
1245 # test generic rounding delegation for reals
1246 class TestRound(object):
1247 def __float__(self):
1248 return 23.0
1250 class TestNoRound(object):
1251 pass
1253 self.assertEqual(round(TestRound()), 23)
1255 self.assertRaises(TypeError, round, 1, 2, 3)
1256 self.assertRaises(TypeError, round, TestNoRound())
1258 t = TestNoRound()
1259 t.__float__ = lambda *args: args
1260 self.assertRaises(TypeError, round, t)
1261 self.assertRaises(TypeError, round, t, 0)
1263 # Some versions of glibc for alpha have a bug that affects
1264 # float -> integer rounding (floor, ceil, rint, round) for
1265 # values in the range [2**52, 2**53). See:
1267 # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350
1269 # We skip this test on Linux/alpha if it would fail.
1270 linux_alpha = (platform.system().startswith('Linux') and
1271 platform.machine().startswith('alpha'))
1272 system_round_bug = round(5e15+1) != 5e15+1
1273 @unittest.skipIf(linux_alpha and system_round_bug,
1274 "test will fail; failure is probably due to a "
1275 "buggy system round function")
1276 def test_round_large(self):
1277 # Issue #1869: integral floats should remain unchanged
1278 self.assertEqual(round(5e15-1), 5e15-1)
1279 self.assertEqual(round(5e15), 5e15)
1280 self.assertEqual(round(5e15+1), 5e15+1)
1281 self.assertEqual(round(5e15+2), 5e15+2)
1282 self.assertEqual(round(5e15+3), 5e15+3)
1284 def test_setattr(self):
1285 setattr(sys, 'spam', 1)
1286 self.assertEqual(sys.spam, 1)
1287 self.assertRaises(TypeError, setattr, sys, 1, 'spam')
1288 self.assertRaises(TypeError, setattr)
1290 def test_sum(self):
1291 self.assertEqual(sum([]), 0)
1292 self.assertEqual(sum(range(2,8)), 27)
1293 self.assertEqual(sum(iter(range(2,8))), 27)
1294 self.assertEqual(sum(Squares(10)), 285)
1295 self.assertEqual(sum(iter(Squares(10))), 285)
1296 self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
1298 self.assertRaises(TypeError, sum)
1299 self.assertRaises(TypeError, sum, 42)
1300 self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
1301 self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
1302 self.assertRaises(TypeError, sum, [[1], [2], [3]])
1303 self.assertRaises(TypeError, sum, [{2:3}])
1304 self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
1306 class BadSeq:
1307 def __getitem__(self, index):
1308 raise ValueError
1309 self.assertRaises(ValueError, sum, BadSeq())
1311 empty = []
1312 sum(([x] for x in range(10)), empty)
1313 self.assertEqual(empty, [])
1315 def test_type(self):
1316 self.assertEqual(type(''), type('123'))
1317 self.assertNotEqual(type(''), type(()))
1319 def test_unichr(self):
1320 if have_unicode:
1321 self.assertEqual(unichr(32), unicode(' '))
1322 self.assertEqual(unichr(65), unicode('A'))
1323 self.assertEqual(unichr(97), unicode('a'))
1324 self.assertEqual(
1325 unichr(sys.maxunicode),
1326 unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape')
1328 self.assertRaises(ValueError, unichr, sys.maxunicode+1)
1329 self.assertRaises(TypeError, unichr)
1330 self.assertRaises((OverflowError, ValueError), unichr, 2**32)
1332 # We don't want self in vars(), so these are static methods
1334 @staticmethod
1335 def get_vars_f0():
1336 return vars()
1338 @staticmethod
1339 def get_vars_f2():
1340 BuiltinTest.get_vars_f0()
1341 a = 1
1342 b = 2
1343 return vars()
1345 def test_vars(self):
1346 self.assertEqual(set(vars()), set(dir()))
1347 import sys
1348 self.assertEqual(set(vars(sys)), set(dir(sys)))
1349 self.assertEqual(self.get_vars_f0(), {})
1350 self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})
1351 self.assertRaises(TypeError, vars, 42, 42)
1352 self.assertRaises(TypeError, vars, 42)
1354 def test_zip(self):
1355 a = (1, 2, 3)
1356 b = (4, 5, 6)
1357 t = [(1, 4), (2, 5), (3, 6)]
1358 self.assertEqual(zip(a, b), t)
1359 b = [4, 5, 6]
1360 self.assertEqual(zip(a, b), t)
1361 b = (4, 5, 6, 7)
1362 self.assertEqual(zip(a, b), t)
1363 class I:
1364 def __getitem__(self, i):
1365 if i < 0 or i > 2: raise IndexError
1366 return i + 4
1367 self.assertEqual(zip(a, I()), t)
1368 self.assertEqual(zip(), [])
1369 self.assertEqual(zip(*[]), [])
1370 self.assertRaises(TypeError, zip, None)
1371 class G:
1372 pass
1373 self.assertRaises(TypeError, zip, a, G())
1375 # Make sure zip doesn't try to allocate a billion elements for the
1376 # result list when one of its arguments doesn't say how long it is.
1377 # A MemoryError is the most likely failure mode.
1378 class SequenceWithoutALength:
1379 def __getitem__(self, i):
1380 if i == 5:
1381 raise IndexError
1382 else:
1383 return i
1384 self.assertEqual(
1385 zip(SequenceWithoutALength(), xrange(2**30)),
1386 list(enumerate(range(5)))
1389 class BadSeq:
1390 def __getitem__(self, i):
1391 if i == 5:
1392 raise ValueError
1393 else:
1394 return i
1395 self.assertRaises(ValueError, zip, BadSeq(), BadSeq())
1397 def test_format(self):
1398 # Test the basic machinery of the format() builtin. Don't test
1399 # the specifics of the various formatters
1400 self.assertEqual(format(3, ''), '3')
1402 # Returns some classes to use for various tests. There's
1403 # an old-style version, and a new-style version
1404 def classes_new():
1405 class A(object):
1406 def __init__(self, x):
1407 self.x = x
1408 def __format__(self, format_spec):
1409 return str(self.x) + format_spec
1410 class DerivedFromA(A):
1411 pass
1413 class Simple(object): pass
1414 class DerivedFromSimple(Simple):
1415 def __init__(self, x):
1416 self.x = x
1417 def __format__(self, format_spec):
1418 return str(self.x) + format_spec
1419 class DerivedFromSimple2(DerivedFromSimple): pass
1420 return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
1422 # In 3.0, classes_classic has the same meaning as classes_new
1423 def classes_classic():
1424 class A:
1425 def __init__(self, x):
1426 self.x = x
1427 def __format__(self, format_spec):
1428 return str(self.x) + format_spec
1429 class DerivedFromA(A):
1430 pass
1432 class Simple: pass
1433 class DerivedFromSimple(Simple):
1434 def __init__(self, x):
1435 self.x = x
1436 def __format__(self, format_spec):
1437 return str(self.x) + format_spec
1438 class DerivedFromSimple2(DerivedFromSimple): pass
1439 return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
1441 def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
1442 self.assertEqual(format(A(3), 'spec'), '3spec')
1443 self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
1444 self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
1445 self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
1446 '10abcdef')
1448 class_test(*classes_new())
1449 class_test(*classes_classic())
1451 def empty_format_spec(value):
1452 # test that:
1453 # format(x, '') == str(x)
1454 # format(x) == str(x)
1455 self.assertEqual(format(value, ""), str(value))
1456 self.assertEqual(format(value), str(value))
1458 # for builtin types, format(x, "") == str(x)
1459 empty_format_spec(17**13)
1460 empty_format_spec(1.0)
1461 empty_format_spec(3.1415e104)
1462 empty_format_spec(-3.1415e104)
1463 empty_format_spec(3.1415e-104)
1464 empty_format_spec(-3.1415e-104)
1465 empty_format_spec(object)
1466 empty_format_spec(None)
1468 # TypeError because self.__format__ returns the wrong type
1469 class BadFormatResult:
1470 def __format__(self, format_spec):
1471 return 1.0
1472 self.assertRaises(TypeError, format, BadFormatResult(), "")
1474 # TypeError because format_spec is not unicode or str
1475 self.assertRaises(TypeError, format, object(), 4)
1476 self.assertRaises(TypeError, format, object(), object())
1478 # tests for object.__format__ really belong elsewhere, but
1479 # there's no good place to put them
1480 x = object().__format__('')
1481 self.assertTrue(x.startswith('<object object at'))
1483 # first argument to object.__format__ must be string
1484 self.assertRaises(TypeError, object().__format__, 3)
1485 self.assertRaises(TypeError, object().__format__, object())
1486 self.assertRaises(TypeError, object().__format__, None)
1488 # make sure we can take a subclass of str as a format spec
1489 class DerivedFromStr(str): pass
1490 self.assertEqual(format(0, DerivedFromStr('10')), ' 0')
1492 def test_bin(self):
1493 self.assertEqual(bin(0), '0b0')
1494 self.assertEqual(bin(1), '0b1')
1495 self.assertEqual(bin(-1), '-0b1')
1496 self.assertEqual(bin(2**65), '0b1' + '0' * 65)
1497 self.assertEqual(bin(2**65-1), '0b' + '1' * 65)
1498 self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
1499 self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
1501 def test_bytearray_translate(self):
1502 x = bytearray("abc")
1503 self.assertRaises(ValueError, x.translate, "1", 1)
1504 self.assertRaises(TypeError, x.translate, "1"*256, 1)
1506 class TestSorted(unittest.TestCase):
1508 def test_basic(self):
1509 data = range(100)
1510 copy = data[:]
1511 random.shuffle(copy)
1512 self.assertEqual(data, sorted(copy))
1513 self.assertNotEqual(data, copy)
1515 data.reverse()
1516 random.shuffle(copy)
1517 self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x)))
1518 self.assertNotEqual(data, copy)
1519 random.shuffle(copy)
1520 self.assertEqual(data, sorted(copy, key=lambda x: -x))
1521 self.assertNotEqual(data, copy)
1522 random.shuffle(copy)
1523 self.assertEqual(data, sorted(copy, reverse=1))
1524 self.assertNotEqual(data, copy)
1526 def test_inputtypes(self):
1527 s = 'abracadabra'
1528 types = [list, tuple]
1529 if have_unicode:
1530 types.insert(0, unicode)
1531 for T in types:
1532 self.assertEqual(sorted(s), sorted(T(s)))
1534 s = ''.join(dict.fromkeys(s).keys()) # unique letters only
1535 types = [set, frozenset, list, tuple, dict.fromkeys]
1536 if have_unicode:
1537 types.insert(0, unicode)
1538 for T in types:
1539 self.assertEqual(sorted(s), sorted(T(s)))
1541 def test_baddecorator(self):
1542 data = 'The quick Brown fox Jumped over The lazy Dog'.split()
1543 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)
1545 def test_main(verbose=None):
1546 test_classes = (BuiltinTest, TestSorted)
1548 run_unittest(*test_classes)
1550 # verify reference counting
1551 if verbose and hasattr(sys, "gettotalrefcount"):
1552 import gc
1553 counts = [None] * 5
1554 for i in xrange(len(counts)):
1555 run_unittest(*test_classes)
1556 gc.collect()
1557 counts[i] = sys.gettotalrefcount()
1558 print counts
1561 if __name__ == "__main__":
1562 test_main(verbose=True)