1 # Python test set -- built-in functions
5 from test
.test_support
import fcmp
, have_unicode
, TESTFN
, unlink
, \
6 run_unittest
, check_py3k_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()
19 def __init__(self
, max):
23 def __len__(self
): return len(self
.sofar
)
25 def __getitem__(self
, i
):
26 if not 0 <= i
< self
.max: raise IndexError
29 self
.sofar
.append(n
*n
)
35 def __init__(self
, max):
40 return len(self
.sofar
)
42 def __getitem__(self
, i
):
43 if not 0 <= i
< self
.max:
47 self
.sofar
.append(str(n
*n
))
52 def write(self
, line
):
56 class TestFailingBool
:
57 def __nonzero__(self
):
60 class TestFailingIter
:
64 class BuiltinTest(unittest
.TestCase
):
66 def test_import(self
):
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')
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)
84 self
.assertEqual(abs(0.0), 0.0)
85 self
.assertEqual(abs(3.14), 3.14)
86 self
.assertEqual(abs(-3.14), 3.14)
88 self
.assertEqual(abs(0L), 0L)
89 self
.assertEqual(abs(1234L), 1234L)
90 self
.assertEqual(abs(-1234L), 1234L)
92 self
.assertRaises(TypeError, abs, 'a')
94 self
.assertEqual(abs(True), 1)
95 self
.assertEqual(abs(False), 0)
97 self
.assertRaises(TypeError, abs)
98 self
.assertRaises(TypeError, abs, None)
99 class AbsClass(object):
102 self
.assertEqual(abs(AbsClass()), -5)
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
114 self
.assertEqual(all(x
> 42 for x
in S
), True)
116 self
.assertEqual(all(x
> 42 for x
in S
), False)
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
128 self
.assertEqual(any(x
> 42 for x
in S
), True)
130 self
.assertEqual(any(x
> 42 for x
in S
), False)
134 self
.assertTrue(isinstance(x
, int))
135 self
.assertEqual(-x
, sys
.maxint
+1)
137 def test_apply(self
):
139 self
.assertEqual(args
, ())
141 self
.assertEqual(a1
, 1)
143 self
.assertEqual(a1
, 1)
144 self
.assertEqual(a2
, 2)
146 self
.assertEqual(a1
, 1)
147 self
.assertEqual(a2
, 2)
148 self
.assertEqual(a3
, 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.
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__
))
170 self
.assertTrue(callable(f
))
174 self
.assertTrue(callable(Classic
))
176 self
.assertTrue(callable(c
.meth
))
177 self
.assertFalse(callable(c
))
179 class NewStyle(object):
181 self
.assertTrue(callable(NewStyle
))
183 self
.assertTrue(callable(n
.meth
))
184 self
.assertFalse(callable(n
))
186 # Classic and new-style classes evaluate __call__() differently
188 self
.assertTrue(callable(c
))
190 self
.assertFalse(callable(c
))
192 self
.assertFalse(callable(n
))
194 self
.assertFalse(callable(n
))
197 def __call__(self
): pass
199 self
.assertTrue(callable(n2
))
202 self
.assertTrue(callable(n3
))
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)
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
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)
235 def __coerce__(self
, other
):
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')
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')
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
):
263 self
.assertRaises(TypeError, delattr)
266 # dir(wrong number of arguments)
267 self
.assertRaises(TypeError, dir, 42, 42)
269 # dir() - local scope
271 self
.assertIn('local_var', dir())
275 self
.assertIn('exit', dir(sys
))
277 # dir(module_with_invalid__dict__)
279 class Foo(types
.ModuleType
):
282 self
.assertRaises(TypeError, dir, f
)
285 self
.assertIn("strip", dir(str))
286 self
.assertNotIn("__mro__", dir(str))
295 self
.assertIn("y", dir(f
))
297 # dir(obj_no__dict__)
301 self
.assertIn("__repr__", dir(f
))
303 # dir(obj_no__class__with__dict__)
304 # (an ugly trick to cause getattr(f, "__class__") to fail)
306 __slots__
= ["__class__", "__dict__"]
310 self
.assertNotIn("__repr__", dir(f
))
311 self
.assertIn("bar", dir(f
))
313 # dir(obj_using __dir__)
316 return ["kan", "ga", "roo"]
318 self
.assertTrue(dir(f
) == ["ga", "kan", "roo"])
320 # dir(obj__dir__not_list)
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),
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)
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)
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}
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)
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
383 "Test mapping interface versus possible calls from eval()."
384 def __getitem__(self
, key
):
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
)
403 self
.assertRaises(TypeError, eval, 'a', g
, m
)
405 # Verify that dict subclasses work as well
407 def __getitem__(self
, key
):
410 return dict.__getitem
__(self
, key
)
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())
426 "Sample application showing nested, calculated lookups."
428 def __setitem__(self
, key
, formula
):
429 self
._cells
[key
] = formula
430 def __getitem__(self
, key
):
431 return eval(self
._cells
[key
], globals(), self
)
437 self
.assertEqual(ss
['a3'], 210)
439 # Verify that dir() catches a non-list returned by eval
442 def __getitem__(self
, item
):
446 self
.assertRaises(TypeError, eval, 'dir()', globals(), C())
448 # Done outside of the method test_z to get the correct scope
450 f
= open(TESTFN
, 'w')
454 with
check_py3k_warnings(("execfile.. not supported in 3.x",
455 DeprecationWarning)):
458 def test_execfile(self
):
464 globals = {'a': 1, 'b': 2}
465 locals = {'b': 200, 'c': 300}
467 self
.assertEqual(self
.__class
__.z
, 2)
469 execfile(TESTFN
, globals)
470 self
.assertEqual(globals['z'], 2)
472 execfile(TESTFN
, globals, locals)
473 self
.assertEqual(locals['z'], 2)
476 "Test mapping interface versus possible calls from execfile()."
479 def __getitem__(self
, key
):
483 def __setitem__(self
, key
, value
):
491 execfile(TESTFN
, globals, locals)
492 self
.assertEqual(locals['z'], 2)
495 self
.assertRaises(TypeError, execfile)
496 self
.assertRaises(TypeError, execfile, TESTFN
, {}, ())
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])
509 filter(identity
, Squares(5))
510 self
.assertRaises(TypeError, filter)
511 class BadSeq(object):
512 def __getitem__(self
, index
):
516 self
.assertRaises(ValueError, filter, lambda x
: x
, BadSeq())
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")
531 def __getitem__(self
, index
):
533 self
.assertRaises(ValueError, filter, lambda x
: x
>="3", badstr("1234"))
536 def __getitem__(self
, index
):
538 self
.assertRaises(TypeError, filter, lambda x
: x
>=42, badstr2("1234"))
541 def __getitem__(self
, index
):
542 return weirdstr(2*str.__getitem
__(self
, index
))
543 self
.assertEqual(filter(lambda x
: x
>="33", weirdstr("1234")), "3344")
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")
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
):
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
))
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)
572 filter(lambda x
: x
>=unicode("3"), shiftunicode("1234")),
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)
581 def __getitem__(self
, index
):
582 return 2*tuple.__getitem
__(self
, index
)
584 def __getitem__(self
, index
):
585 return 2*str.__getitem
__(self
, index
)
587 tuple2
: {(): (), (1, 2, 3): (2, 4, 6)},
588 str2
: {"": "", "123": "112233"}
591 class unicode2(unicode):
592 def __getitem__(self
, index
):
593 return 2*unicode.__getitem
__(self
, index
)
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
604 filter(funcs
[0], cls(inp
)),
605 filter(funcs
[1], cls(inp
))
608 outp
= filter(func
, cls(inp
))
609 self
.assertEqual(outp
, exp
)
610 self
.assertTrue(not isinstance(outp
, cls
))
612 def test_getattr(self
):
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)
619 self
.assertRaises(UnicodeError, getattr, sys
, unichr(sys
.maxunicode
))
621 def test_hasattr(self
):
623 self
.assertTrue(hasattr(sys
, 'stdout'))
624 self
.assertRaises(TypeError, hasattr, sys
, 1)
625 self
.assertRaises(TypeError, hasattr)
627 self
.assertRaises(UnicodeError, hasattr, sys
, unichr(sys
.maxunicode
))
629 # Check that hasattr allows SystemExit and KeyboardInterrupts by
631 def __getattr__(self
, what
):
632 raise KeyboardInterrupt
633 self
.assertRaises(KeyboardInterrupt, hasattr, A(), "b")
635 def __getattr__(self
, what
):
637 self
.assertRaises(SystemExit, hasattr, B(), "b")
641 self
.assertEqual(hash(1), hash(1L))
642 self
.assertEqual(hash(1), hash(1.0))
645 self
.assertEqual(hash('spam'), hash(unicode('spam')))
648 self
.assertRaises(TypeError, hash, [])
649 self
.assertRaises(TypeError, hash, {})
650 # Bug 1536021: Allow hash to return long objects
654 self
.assertEquals(type(hash(X())), int)
658 self
.assertEquals(type(hash(Y())), int)
662 self
.assertEquals(hash(Z(42)), hash(42L))
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, {})
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.
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().
707 self
.assertEqual(getattr(s
, s
), s
)
710 self
.assertRaises(TypeError, iter)
711 self
.assertRaises(TypeError, iter, 42, 42)
712 lists
= [("1", "2"), ["1", "2"], "12"]
714 lists
.append(unicode("12"))
717 self
.assertEqual(i
.next(), '1')
718 self
.assertEqual(i
.next(), '2')
719 self
.assertRaises(StopIteration, i
.next
)
721 def test_isinstance(self
):
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
):
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)
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)
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())
775 map(None, 'hello world'),
776 ['h','e','l','l','o',' ','w','o','r','l','d']
779 map(None, 'abcd', 'efg'),
780 [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
783 map(None, range(10)),
784 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
787 map(lambda x
: x
*x
, range(1,4)),
791 from math
import sqrt
796 map(lambda x
: map(sqrt
,x
), [[16, 4], [81, 9]]),
797 [[4.0, 2.0], [9.0, 3.0]]
800 map(lambda x
, y
: x
+y
, [1,3,2], [9,1,4]),
806 for i
in v
: accu
= accu
+ i
809 map(plus
, [1, 3, 7]),
813 map(plus
, [1, 3, 7], [4, 9, 2]),
817 map(plus
, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
818 [1+4+1, 3+9+1, 7+2+0]
821 map(None, Squares(10)),
822 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
825 map(int, Squares(10)),
826 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
829 map(None, Squares(3), Squares(2)),
830 [(0,0), (1,1), (4,None)]
833 map(max, Squares(3), Squares(2)),
836 self
.assertRaises(TypeError, map)
837 self
.assertRaises(TypeError, map, lambda x
: x
, 42)
838 self
.assertEqual(map(None, [42]), [42])
840 def __getitem__(self
, index
):
842 self
.assertRaises(ValueError, map, lambda x
: x
, BadSeq())
845 self
.assertRaises(RuntimeError, map, badfunc
, range(5))
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)
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
865 exec(stmt
) in globals()
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
)
878 self
.assertEqual(max(data
, key
=f
),
879 sorted(reversed(data
), key
=f
)[-1])
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, ())
895 def __getitem__(self
, index
):
897 self
.assertRaises(ValueError, min, BadSeq())
899 def __cmp__(self
, other
):
901 self
.assertRaises(ValueError, min, (42, BadNumber()))
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
911 exec(stmt
) in globals()
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
)
924 self
.assertEqual(min(data
, key
=f
),
925 sorted(data
, key
=f
)[0])
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)
942 self
.assertEquals(next(it
, 42), 42)
943 self
.assertRaises(StopIteration, next
, it
)
950 self
.assertEquals(next(it
), 1)
951 self
.assertRaises(StopIteration, next
, it
)
952 self
.assertEquals(next(it
, 42), 42)
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')
967 fp
.write('The quick brown fox jumps over the lazy dog')
969 fp
.write('Dear John\n')
976 self
.write_testfile()
977 fp
= open(TESTFN
, 'r')
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)
991 self
.assertEqual(ord(' '), 32)
992 self
.assertEqual(ord('A'), 65)
993 self
.assertEqual(ord('a'), 97)
995 self
.assertEqual(ord(unichr(sys
.maxunicode
)), sys
.maxunicode
)
996 self
.assertRaises(TypeError, ord, 42)
998 self
.assertRaises(TypeError, ord, unicode("12"))
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
)
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))
1108 def __cmp__(self
, other
):
1110 __hash__
= None # Invalid cmp makes this unhashable
1111 self
.assertRaises(RuntimeError, range, a
, a
+ 1, badzero(1))
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
1125 # Old-style user-defined class with __int__ method
1127 def __init__(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
1136 def __init__(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
1147 self
.assertRaises(RuntimeError, range, IX())
1149 # New-style user-defined class with invalid __int__ method
1152 return "not a number"
1153 self
.assertRaises(TypeError, range, IN())
1155 # Exercise various combinations of bad arguments, to check
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
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
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.
1212 # This test was compiled with old semantics.
1213 expected
= ['0', '0.5', '0']
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
)
1221 self
.assertRaises(RuntimeError, input, 'prompt')
1223 self
.assertRaises(RuntimeError, input, 'prompt')
1225 sys
.stdin
= savestdin
1226 sys
.stdout
= savestdout
1230 def test_reduce(self
):
1231 add
= lambda x
, y
: x
+y
1232 self
.assertEqual(reduce(add
, ['a', 'b', 'c'], ''), 'abc')
1234 reduce(add
, [['a', 'c'], [], ['d', 'w']], []),
1237 self
.assertEqual(reduce(lambda x
, y
: x
*y
, range(2,8), 1), 5040)
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)
1261 def __getitem__(self
, index
):
1263 self
.assertRaises(ValueError, reduce, 42, BadSeq())
1265 def test_reload(self
):
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({}), '{}')
1282 self
.assertEqual(repr(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)
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
):
1348 class TestNoRound(object):
1351 self
.assertEqual(round(TestRound()), 23)
1353 self
.assertRaises(TypeError, round, 1, 2, 3)
1354 self
.assertRaises(TypeError, round, 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)
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})
1405 def __getitem__(self
, index
):
1407 self
.assertRaises(ValueError, sum, BadSeq())
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
):
1419 self
.assertEqual(unichr(32), unicode(' '))
1420 self
.assertEqual(unichr(65), unicode('A'))
1421 self
.assertEqual(unichr(97), unicode('a'))
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
1438 BuiltinTest
.get_vars_f0()
1443 class C_get_vars(object):
1446 __dict__
= property(fget
=getDict
)
1448 def test_vars(self
):
1449 self
.assertEqual(set(vars()), set(dir()))
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})
1461 t
= [(1, 4), (2, 5), (3, 6)]
1462 self
.assertEqual(zip(a
, b
), t
)
1464 self
.assertEqual(zip(a
, b
), t
)
1466 self
.assertEqual(zip(a
, b
), t
)
1468 def __getitem__(self
, i
):
1469 if i
< 0 or i
> 2: raise IndexError
1471 self
.assertEqual(zip(a
, I()), t
)
1472 self
.assertEqual(zip(), [])
1473 self
.assertEqual(zip(*[]), [])
1474 self
.assertRaises(TypeError, zip, None)
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
):
1489 zip(SequenceWithoutALength(), xrange(2**30)),
1490 list(enumerate(range(5)))
1494 def __getitem__(self
, 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
1510 def __init__(self
, x
):
1512 def __format__(self
, format_spec
):
1513 return str(self
.x
) + format_spec
1514 class DerivedFromA(A
):
1517 class Simple(object): pass
1518 class DerivedFromSimple(Simple
):
1519 def __init__(self
, 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():
1529 def __init__(self
, x
):
1531 def __format__(self
, format_spec
):
1532 return str(self
.x
) + format_spec
1533 class DerivedFromA(A
):
1537 class DerivedFromSimple(Simple
):
1538 def __init__(self
, 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'),
1552 class_test(*classes_new())
1553 class_test(*classes_classic())
1555 def empty_format_spec(value
):
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
):
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
))
1605 self
.assertEqual(len(w
), 0)
1607 fmt_strs
= ['', 's', u
'', u
's']
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)
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')
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
):
1650 random
.shuffle(copy
)
1651 self
.assertEqual(data
, sorted(copy
))
1652 self
.assertNotEqual(data
, copy
)
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
):
1667 types
= [list, tuple]
1669 types
.insert(0, unicode)
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
]
1676 types
.insert(0, unicode)
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)):
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"):
1700 for i
in xrange(len(counts
)):
1701 _run_unittest(*test_classes
)
1703 counts
[i
] = sys
.gettotalrefcount()
1707 if __name__
== "__main__":
1708 test_main(verbose
=True)