1 # Python test set -- built-in functions
3 import test
.test_support
, unittest
4 from test
.test_support
import fcmp
, have_unicode
, TESTFN
, unlink
, \
5 run_unittest
, run_with_locale
6 from operator
import neg
8 import sys
, warnings
, cStringIO
, random
, fractions
, UserDict
9 warnings
.filterwarnings("ignore", "hex../oct.. of negative int",
10 FutureWarning
, __name__
)
11 warnings
.filterwarnings("ignore", "integer argument expected",
12 DeprecationWarning, "unittest")
14 # count the number of test runs.
15 # used to skip running test_execfile() multiple times
20 def __init__(self
, max):
24 def __len__(self
): return len(self
.sofar
)
26 def __getitem__(self
, i
):
27 if not 0 <= i
< self
.max: raise IndexError
30 self
.sofar
.append(n
*n
)
36 def __init__(self
, max):
41 return len(self
.sofar
)
43 def __getitem__(self
, i
):
44 if not 0 <= i
< self
.max:
48 self
.sofar
.append(str(n
*n
))
53 def write(self
, line
):
57 class TestFailingBool
:
58 def __nonzero__(self
):
61 class TestFailingIter
:
65 class BuiltinTest(unittest
.TestCase
):
67 def test_import(self
):
71 __import__(name
='sys')
72 __import__(name
='time', level
=0)
73 self
.assertRaises(ImportError, __import__, 'spamspam')
74 self
.assertRaises(TypeError, __import__, 1, 2, 3, 4)
75 self
.assertRaises(ValueError, __import__, '')
76 self
.assertRaises(TypeError, __import__, 'sys', name
='sys')
80 self
.assertEqual(abs(0), 0)
81 self
.assertEqual(abs(1234), 1234)
82 self
.assertEqual(abs(-1234), 1234)
83 self
.assertTrue(abs(-sys
.maxint
-1) > 0)
85 self
.assertEqual(abs(0.0), 0.0)
86 self
.assertEqual(abs(3.14), 3.14)
87 self
.assertEqual(abs(-3.14), 3.14)
89 self
.assertEqual(abs(0L), 0L)
90 self
.assertEqual(abs(1234L), 1234L)
91 self
.assertEqual(abs(-1234L), 1234L)
93 self
.assertRaises(TypeError, abs, 'a')
96 self
.assertEqual(all([2, 4, 6]), True)
97 self
.assertEqual(all([2, None, 6]), False)
98 self
.assertRaises(RuntimeError, all
, [2, TestFailingBool(), 6])
99 self
.assertRaises(RuntimeError, all
, TestFailingIter())
100 self
.assertRaises(TypeError, all
, 10) # Non-iterable
101 self
.assertRaises(TypeError, all
) # No args
102 self
.assertRaises(TypeError, all
, [2, 4, 6], []) # Too many args
103 self
.assertEqual(all([]), True) # Empty iterator
105 self
.assertEqual(all(x
> 42 for x
in S
), True)
107 self
.assertEqual(all(x
> 42 for x
in S
), False)
110 self
.assertEqual(any([None, None, None]), False)
111 self
.assertEqual(any([None, 4, None]), True)
112 self
.assertRaises(RuntimeError, any
, [None, TestFailingBool(), 6])
113 self
.assertRaises(RuntimeError, all
, TestFailingIter())
114 self
.assertRaises(TypeError, any
, 10) # Non-iterable
115 self
.assertRaises(TypeError, any
) # No args
116 self
.assertRaises(TypeError, any
, [2, 4, 6], []) # Too many args
117 self
.assertEqual(any([]), False) # Empty iterator
119 self
.assertEqual(any(x
> 42 for x
in S
), True)
121 self
.assertEqual(any(x
> 42 for x
in S
), False)
125 self
.assert_(isinstance(x
, int))
126 self
.assertEqual(-x
, sys
.maxint
+1)
128 def test_apply(self
):
130 self
.assertEqual(args
, ())
132 self
.assertEqual(a1
, 1)
134 self
.assertEqual(a1
, 1)
135 self
.assertEqual(a2
, 2)
137 self
.assertEqual(a1
, 1)
138 self
.assertEqual(a2
, 2)
139 self
.assertEqual(a3
, 3)
145 # A PyCFunction that takes only positional parameters should allow an
146 # empty keyword dictionary to pass without a complaint, but raise a
147 # TypeError if the dictionary is non-empty.
149 self
.assertRaises(TypeError, apply, id, (1,), {"foo": 1})
150 self
.assertRaises(TypeError, apply)
151 self
.assertRaises(TypeError, apply, id, 42)
152 self
.assertRaises(TypeError, apply, id, (42,), 42)
154 def test_callable(self
):
155 self
.assert_(callable(len))
157 self
.assert_(callable(f
))
160 self
.assert_(callable(C
))
162 self
.assert_(callable(x
.meth
))
163 self
.assert_(not callable(x
))
165 def __call__(self
): pass
167 self
.assert_(callable(y
))
171 self
.assertEqual(chr(32), ' ')
172 self
.assertEqual(chr(65), 'A')
173 self
.assertEqual(chr(97), 'a')
174 self
.assertEqual(chr(0xff), '\xff')
175 self
.assertRaises(ValueError, chr, 256)
176 self
.assertRaises(TypeError, chr)
179 self
.assertEqual(cmp(-1, 1), -1)
180 self
.assertEqual(cmp(1, -1), 1)
181 self
.assertEqual(cmp(1, 1), 0)
182 # verify that circular objects are not handled
185 from UserList
import UserList
186 c
= UserList(); c
.append(c
)
187 self
.assertRaises(RuntimeError, cmp, a
, b
)
188 self
.assertRaises(RuntimeError, cmp, b
, c
)
189 self
.assertRaises(RuntimeError, cmp, c
, a
)
190 self
.assertRaises(RuntimeError, cmp, a
, c
)
191 # okay, now break the cycles
192 a
.pop(); b
.pop(); c
.pop()
193 self
.assertRaises(TypeError, cmp)
195 def test_coerce(self
):
196 self
.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1)))
197 self
.assertEqual(coerce(1, 1L), (1L, 1L))
198 self
.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1)))
199 self
.assertRaises(TypeError, coerce)
201 def __coerce__(self
, other
):
203 self
.assertRaises(ValueError, coerce, 42, BadNumber())
204 self
.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000))
206 def test_compile(self
):
207 compile('print 1\n', '', 'exec')
209 compile(bom
+ 'print 1\n', '', 'exec')
210 compile(source
='pass', filename
='?', mode
='exec')
211 compile(dont_inherit
=0, filename
='tmp', source
='0', mode
='eval')
212 compile('pass', '?', dont_inherit
=1, mode
='exec')
213 self
.assertRaises(TypeError, compile)
214 self
.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode')
215 self
.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff)
216 self
.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
217 self
.assertRaises(TypeError, compile, 'pass', '?', 'exec',
218 mode
='eval', source
='0', filename
='tmp')
220 compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec')
221 self
.assertRaises(TypeError, compile, unichr(0), 'f', 'exec')
222 self
.assertRaises(ValueError, compile, unicode('a = 1'), 'f', 'bad')
225 def test_delattr(self
):
229 self
.assertRaises(TypeError, delattr)
232 # dir(wrong number of arguments)
233 self
.assertRaises(TypeError, dir, 42, 42)
235 # dir() - local scope
237 self
.assert_('local_var' in dir())
241 self
.assert_('exit' in dir(sys
))
243 # dir(module_with_invalid__dict__)
245 class Foo(types
.ModuleType
):
248 self
.assertRaises(TypeError, dir, f
)
251 self
.assert_("strip" in dir(str))
252 self
.assert_("__mro__" not in dir(str))
261 self
.assert_("y" in dir(f
))
263 # dir(obj_no__dict__)
267 self
.assert_("__repr__" in dir(f
))
269 # dir(obj_no__class__with__dict__)
270 # (an ugly trick to cause getattr(f, "__class__") to fail)
272 __slots__
= ["__class__", "__dict__"]
276 self
.assert_("__repr__" not in dir(f
))
277 self
.assert_("bar" in dir(f
))
279 # dir(obj_using __dir__)
282 return ["kan", "ga", "roo"]
284 self
.assert_(dir(f
) == ["ga", "kan", "roo"])
286 # dir(obj__dir__not_list)
291 self
.assertRaises(TypeError, dir, f
)
293 def test_divmod(self
):
294 self
.assertEqual(divmod(12, 7), (1, 5))
295 self
.assertEqual(divmod(-12, 7), (-2, 2))
296 self
.assertEqual(divmod(12, -7), (-2, -2))
297 self
.assertEqual(divmod(-12, -7), (1, -5))
299 self
.assertEqual(divmod(12L, 7L), (1L, 5L))
300 self
.assertEqual(divmod(-12L, 7L), (-2L, 2L))
301 self
.assertEqual(divmod(12L, -7L), (-2L, -2L))
302 self
.assertEqual(divmod(-12L, -7L), (1L, -5L))
304 self
.assertEqual(divmod(12, 7L), (1, 5L))
305 self
.assertEqual(divmod(-12, 7L), (-2, 2L))
306 self
.assertEqual(divmod(12L, -7), (-2L, -2))
307 self
.assertEqual(divmod(-12L, -7), (1L, -5))
309 self
.assertEqual(divmod(-sys
.maxint
-1, -1),
312 self
.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
313 self
.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
314 self
.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
315 self
.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
317 self
.assertRaises(TypeError, divmod)
320 self
.assertEqual(eval('1+1'), 2)
321 self
.assertEqual(eval(' 1+1\n'), 2)
322 globals = {'a': 1, 'b': 2}
323 locals = {'b': 200, 'c': 300}
324 self
.assertEqual(eval('a', globals) , 1)
325 self
.assertEqual(eval('a', globals, locals), 1)
326 self
.assertEqual(eval('b', globals, locals), 200)
327 self
.assertEqual(eval('c', globals, locals), 300)
329 self
.assertEqual(eval(unicode('1+1')), 2)
330 self
.assertEqual(eval(unicode(' 1+1\n')), 2)
331 globals = {'a': 1, 'b': 2}
332 locals = {'b': 200, 'c': 300}
334 self
.assertEqual(eval(unicode('a'), globals), 1)
335 self
.assertEqual(eval(unicode('a'), globals, locals), 1)
336 self
.assertEqual(eval(unicode('b'), globals, locals), 200)
337 self
.assertEqual(eval(unicode('c'), globals, locals), 300)
339 self
.assertEqual(eval(bom
+ 'a', globals, locals), 1)
340 self
.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals),
341 unicode('\xc3\xa5', 'utf8'))
342 self
.assertRaises(TypeError, eval)
343 self
.assertRaises(TypeError, eval, ())
345 def test_general_eval(self
):
346 # Tests that general mappings can be used for the locals argument
349 "Test mapping interface versus possible calls from eval()."
350 def __getitem__(self
, key
):
359 self
.assertEqual(eval('a', g
, m
), 12)
360 self
.assertRaises(NameError, eval, 'b', g
, m
)
361 self
.assertEqual(eval('dir()', g
, m
), list('xyz'))
362 self
.assertEqual(eval('globals()', g
, m
), g
)
363 self
.assertEqual(eval('locals()', g
, m
), m
)
364 self
.assertRaises(TypeError, eval, 'a', m
)
369 self
.assertRaises(TypeError, eval, 'a', g
, m
)
371 # Verify that dict subclasses work as well
373 def __getitem__(self
, key
):
376 return dict.__getitem
__(self
, key
)
381 self
.assertEqual(eval('a', g
, d
), 12)
382 self
.assertRaises(NameError, eval, 'b', g
, d
)
383 self
.assertEqual(eval('dir()', g
, d
), list('xyz'))
384 self
.assertEqual(eval('globals()', g
, d
), g
)
385 self
.assertEqual(eval('locals()', g
, d
), d
)
387 # Verify locals stores (used by list comps)
388 eval('[locals() for i in (2,3)]', g
, d
)
389 eval('[locals() for i in (2,3)]', g
, UserDict
.UserDict())
392 "Sample application showing nested, calculated lookups."
394 def __setitem__(self
, key
, formula
):
395 self
._cells
[key
] = formula
396 def __getitem__(self
, key
):
397 return eval(self
._cells
[key
], globals(), self
)
403 self
.assertEqual(ss
['a3'], 210)
405 # Verify that dir() catches a non-list returned by eval
408 def __getitem__(self
, item
):
412 self
.assertRaises(TypeError, eval, 'dir()', globals(), C())
414 # Done outside of the method test_z to get the correct scope
416 f
= open(TESTFN
, 'w')
422 def test_execfile(self
):
428 globals = {'a': 1, 'b': 2}
429 locals = {'b': 200, 'c': 300}
431 self
.assertEqual(self
.__class
__.z
, 2)
433 execfile(TESTFN
, globals)
434 self
.assertEqual(globals['z'], 2)
436 execfile(TESTFN
, globals, locals)
437 self
.assertEqual(locals['z'], 2)
440 "Test mapping interface versus possible calls from execfile()."
443 def __getitem__(self
, key
):
447 def __setitem__(self
, key
, value
):
455 execfile(TESTFN
, globals, locals)
456 self
.assertEqual(locals['z'], 2)
459 self
.assertRaises(TypeError, execfile)
460 self
.assertRaises(TypeError, execfile, TESTFN
, {}, ())
462 self
.assertRaises(IOError, execfile, os
.curdir
)
463 self
.assertRaises(IOError, execfile, "I_dont_exist")
465 def test_filter(self
):
466 self
.assertEqual(filter(lambda c
: 'a' <= c
<= 'z', 'Hello World'), 'elloorld')
467 self
.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
468 self
.assertEqual(filter(lambda x
: x
> 0, [1, -3, 9, 0, 2]), [1, 9, 2])
469 self
.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
470 self
.assertEqual(filter(lambda x
: x
%2, Squares(10)), [1, 9, 25, 49, 81])
473 filter(identity
, Squares(5))
474 self
.assertRaises(TypeError, filter)
475 class BadSeq(object):
476 def __getitem__(self
, index
):
480 self
.assertRaises(ValueError, filter, lambda x
: x
, BadSeq())
483 self
.assertRaises(TypeError, filter, badfunc
, range(5))
485 # test bltinmodule.c::filtertuple()
486 self
.assertEqual(filter(None, (1, 2)), (1, 2))
487 self
.assertEqual(filter(lambda x
: x
>=3, (1, 2, 3, 4)), (3, 4))
488 self
.assertRaises(TypeError, filter, 42, (1, 2))
490 # test bltinmodule.c::filterstring()
491 self
.assertEqual(filter(None, "12"), "12")
492 self
.assertEqual(filter(lambda x
: x
>="3", "1234"), "34")
493 self
.assertRaises(TypeError, filter, 42, "12")
495 def __getitem__(self
, index
):
497 self
.assertRaises(ValueError, filter, lambda x
: x
>="3", badstr("1234"))
500 def __getitem__(self
, index
):
502 self
.assertRaises(TypeError, filter, lambda x
: x
>=42, badstr2("1234"))
505 def __getitem__(self
, index
):
506 return weirdstr(2*str.__getitem
__(self
, index
))
507 self
.assertEqual(filter(lambda x
: x
>="33", weirdstr("1234")), "3344")
510 def __getitem__(self
, index
):
511 return chr(ord(str.__getitem
__(self
, index
))+1)
512 self
.assertEqual(filter(lambda x
: x
>="3", shiftstr("1234")), "345")
515 # test bltinmodule.c::filterunicode()
516 self
.assertEqual(filter(None, unicode("12")), unicode("12"))
517 self
.assertEqual(filter(lambda x
: x
>="3", unicode("1234")), unicode("34"))
518 self
.assertRaises(TypeError, filter, 42, unicode("12"))
519 self
.assertRaises(ValueError, filter, lambda x
: x
>="3", badstr(unicode("1234")))
521 class badunicode(unicode):
522 def __getitem__(self
, index
):
524 self
.assertRaises(TypeError, filter, lambda x
: x
>=42, badunicode("1234"))
526 class weirdunicode(unicode):
527 def __getitem__(self
, index
):
528 return weirdunicode(2*unicode.__getitem
__(self
, index
))
530 filter(lambda x
: x
>=unicode("33"), weirdunicode("1234")), unicode("3344"))
532 class shiftunicode(unicode):
533 def __getitem__(self
, index
):
534 return unichr(ord(unicode.__getitem
__(self
, index
))+1)
536 filter(lambda x
: x
>=unicode("3"), shiftunicode("1234")),
540 def test_filter_subclasses(self
):
541 # test that filter() never returns tuple, str or unicode subclasses
542 # and that the result always goes through __getitem__
543 funcs
= (None, bool, lambda x
: True)
545 def __getitem__(self
, index
):
546 return 2*tuple.__getitem
__(self
, index
)
548 def __getitem__(self
, index
):
549 return 2*str.__getitem
__(self
, index
)
551 tuple2
: {(): (), (1, 2, 3): (2, 4, 6)},
552 str2
: {"": "", "123": "112233"}
555 class unicode2(unicode):
556 def __getitem__(self
, index
):
557 return 2*unicode.__getitem
__(self
, index
)
559 unicode(): unicode(),
560 unicode("123"): unicode("112233")
563 for (cls
, inps
) in inputs
.iteritems():
564 for (inp
, exp
) in inps
.iteritems():
565 # make sure the output goes through __getitem__
566 # even if func is None
568 filter(funcs
[0], cls(inp
)),
569 filter(funcs
[1], cls(inp
))
572 outp
= filter(func
, cls(inp
))
573 self
.assertEqual(outp
, exp
)
574 self
.assert_(not isinstance(outp
, cls
))
576 def test_getattr(self
):
578 self
.assert_(getattr(sys
, 'stdout') is sys
.stdout
)
579 self
.assertRaises(TypeError, getattr, sys
, 1)
580 self
.assertRaises(TypeError, getattr, sys
, 1, "foo")
581 self
.assertRaises(TypeError, getattr)
583 self
.assertRaises(UnicodeError, getattr, sys
, unichr(sys
.maxunicode
))
585 def test_hasattr(self
):
587 self
.assert_(hasattr(sys
, 'stdout'))
588 self
.assertRaises(TypeError, hasattr, sys
, 1)
589 self
.assertRaises(TypeError, hasattr)
591 self
.assertRaises(UnicodeError, hasattr, sys
, unichr(sys
.maxunicode
))
593 # Check that hasattr allows SystemExit and KeyboardInterrupts by
595 def __getattr__(self
, what
):
596 raise KeyboardInterrupt
597 self
.assertRaises(KeyboardInterrupt, hasattr, A(), "b")
599 def __getattr__(self
, what
):
601 self
.assertRaises(SystemExit, hasattr, B(), "b")
605 self
.assertEqual(hash(1), hash(1L))
606 self
.assertEqual(hash(1), hash(1.0))
609 self
.assertEqual(hash('spam'), hash(unicode('spam')))
612 self
.assertRaises(TypeError, hash, [])
613 self
.assertRaises(TypeError, hash, {})
614 # Bug 1536021: Allow hash to return long objects
618 self
.assertEquals(type(hash(X())), int)
622 self
.assertEquals(type(hash(Y())), int)
626 self
.assertEquals(hash(Z(42)), hash(42L))
629 self
.assertEqual(hex(16), '0x10')
630 self
.assertEqual(hex(16L), '0x10L')
631 self
.assertEqual(hex(-16), '-0x10')
632 self
.assertEqual(hex(-16L), '-0x10L')
633 self
.assertRaises(TypeError, hex, {})
634 self
.assertEqual(hex(3.125), '0x19 * 2.0 ** -3')
635 self
.assertEqual(hex(0.0), '0x0 * 2.0 ** 0')
636 for sv
in float('nan'), float('inf'), float('-inf'):
637 self
.assertEqual(hex(sv
), repr(sv
))
639 x
= random
.expovariate(.05)
640 self
.assertEqual(eval(hex(x
)), x
, (x
, hex(x
), eval(hex(x
))))
641 self
.assertEqual(eval(hex(-x
)), -x
)
642 self
.assertEqual(hex(-x
), ('-' + hex(x
)))
652 id({'spam': 1, 'eggs': 2, 'ham': 3})
654 # Test input() later, together with raw_input
656 def test_intern(self
):
657 self
.assertRaises(TypeError, intern)
658 s
= "never interned before"
659 self
.assert_(intern(s
) is s
)
660 s2
= s
.swapcase().swapcase()
661 self
.assert_(intern(s2
) is s
)
663 # Subclasses of string can't be interned, because they
664 # provide too much opportunity for insane things to happen.
665 # We don't want them in the interned dict and if they aren't
666 # actually interned, we don't want to create the appearance
667 # that they are by allowing intern() to succeeed.
672 self
.assertRaises(TypeError, intern, S("abc"))
674 # It's still safe to pass these strings to routines that
675 # call intern internally, e.g. PyObject_SetAttr().
678 self
.assertEqual(getattr(s
, s
), s
)
681 self
.assertRaises(TypeError, iter)
682 self
.assertRaises(TypeError, iter, 42, 42)
683 lists
= [("1", "2"), ["1", "2"], "12"]
685 lists
.append(unicode("12"))
688 self
.assertEqual(i
.next(), '1')
689 self
.assertEqual(i
.next(), '2')
690 self
.assertRaises(StopIteration, i
.next
)
692 def test_isinstance(self
):
702 self
.assert_(isinstance(c
, C
))
703 self
.assert_(isinstance(d
, C
))
704 self
.assert_(not isinstance(e
, C
))
705 self
.assert_(not isinstance(c
, D
))
706 self
.assert_(not isinstance('foo', E
))
707 self
.assertRaises(TypeError, isinstance, E
, 'foo')
708 self
.assertRaises(TypeError, isinstance)
710 def test_issubclass(self
):
720 self
.assert_(issubclass(D
, C
))
721 self
.assert_(issubclass(C
, C
))
722 self
.assert_(not issubclass(C
, D
))
723 self
.assertRaises(TypeError, issubclass, 'foo', E
)
724 self
.assertRaises(TypeError, issubclass, E
, 'foo')
725 self
.assertRaises(TypeError, issubclass)
728 self
.assertEqual(len('123'), 3)
729 self
.assertEqual(len(()), 0)
730 self
.assertEqual(len((1, 2, 3, 4)), 4)
731 self
.assertEqual(len([1, 2, 3, 4]), 4)
732 self
.assertEqual(len({}), 0)
733 self
.assertEqual(len({'a':1, 'b': 2}), 2)
737 self
.assertRaises(ValueError, len, BadSeq())
741 map(None, 'hello world'),
742 ['h','e','l','l','o',' ','w','o','r','l','d']
745 map(None, 'abcd', 'efg'),
746 [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
749 map(None, range(10)),
750 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
753 map(lambda x
: x
*x
, range(1,4)),
757 from math
import sqrt
762 map(lambda x
: map(sqrt
,x
), [[16, 4], [81, 9]]),
763 [[4.0, 2.0], [9.0, 3.0]]
766 map(lambda x
, y
: x
+y
, [1,3,2], [9,1,4]),
772 for i
in v
: accu
= accu
+ i
775 map(plus
, [1, 3, 7]),
779 map(plus
, [1, 3, 7], [4, 9, 2]),
783 map(plus
, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
784 [1+4+1, 3+9+1, 7+2+0]
787 map(None, Squares(10)),
788 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
791 map(int, Squares(10)),
792 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
795 map(None, Squares(3), Squares(2)),
796 [(0,0), (1,1), (4,None)]
799 map(max, Squares(3), Squares(2)),
802 self
.assertRaises(TypeError, map)
803 self
.assertRaises(TypeError, map, lambda x
: x
, 42)
804 self
.assertEqual(map(None, [42]), [42])
806 def __getitem__(self
, index
):
808 self
.assertRaises(ValueError, map, lambda x
: x
, BadSeq())
811 self
.assertRaises(RuntimeError, map, badfunc
, range(5))
814 self
.assertEqual(max('123123'), '3')
815 self
.assertEqual(max(1, 2, 3), 3)
816 self
.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
817 self
.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
819 self
.assertEqual(max(1, 2L, 3.0), 3.0)
820 self
.assertEqual(max(1L, 2.0, 3), 3)
821 self
.assertEqual(max(1.0, 2, 3L), 3L)
824 "max(key=int)", # no args
825 "max(1, key=int)", # single arg not iterable
826 "max(1, 2, keystone=int)", # wrong keyword
827 "max(1, 2, key=int, abc=int)", # two many keywords
828 "max(1, 2, key=1)", # keyfunc is not callable
831 exec(stmt
) in globals()
837 self
.assertEqual(max((1,), key
=neg
), 1) # one elem iterable
838 self
.assertEqual(max((1,2), key
=neg
), 1) # two elem iterable
839 self
.assertEqual(max(1, 2, key
=neg
), 1) # two elems
841 data
= [random
.randrange(200) for i
in range(100)]
842 keys
= dict((elem
, random
.randrange(50)) for elem
in data
)
844 self
.assertEqual(max(data
, key
=f
),
845 sorted(reversed(data
), key
=f
)[-1])
848 self
.assertEqual(min('123123'), '1')
849 self
.assertEqual(min(1, 2, 3), 1)
850 self
.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)
851 self
.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)
853 self
.assertEqual(min(1, 2L, 3.0), 1)
854 self
.assertEqual(min(1L, 2.0, 3), 1L)
855 self
.assertEqual(min(1.0, 2, 3L), 1.0)
857 self
.assertRaises(TypeError, min)
858 self
.assertRaises(TypeError, min, 42)
859 self
.assertRaises(ValueError, min, ())
861 def __getitem__(self
, index
):
863 self
.assertRaises(ValueError, min, BadSeq())
865 def __cmp__(self
, other
):
867 self
.assertRaises(ValueError, min, (42, BadNumber()))
870 "min(key=int)", # no args
871 "min(1, key=int)", # single arg not iterable
872 "min(1, 2, keystone=int)", # wrong keyword
873 "min(1, 2, key=int, abc=int)", # two many keywords
874 "min(1, 2, key=1)", # keyfunc is not callable
877 exec(stmt
) in globals()
883 self
.assertEqual(min((1,), key
=neg
), 1) # one elem iterable
884 self
.assertEqual(min((1,2), key
=neg
), 2) # two elem iterable
885 self
.assertEqual(min(1, 2, key
=neg
), 2) # two elems
887 data
= [random
.randrange(200) for i
in range(100)]
888 keys
= dict((elem
, random
.randrange(50)) for elem
in data
)
890 self
.assertEqual(min(data
, key
=f
),
891 sorted(data
, key
=f
)[0])
895 self
.assertEqual(next(it
), 0)
896 self
.assertEqual(next(it
), 1)
897 self
.assertRaises(StopIteration, next
, it
)
898 self
.assertRaises(StopIteration, next
, it
)
899 self
.assertEquals(next(it
, 42), 42)
908 self
.assertEquals(next(it
, 42), 42)
909 self
.assertRaises(StopIteration, next
, it
)
916 self
.assertEquals(next(it
), 1)
917 self
.assertRaises(StopIteration, next
, it
)
918 self
.assertEquals(next(it
, 42), 42)
921 self
.assertEqual(oct(100), '0144')
922 self
.assertEqual(oct(100L), '0144L')
923 self
.assertEqual(oct(-100), '-0144')
924 self
.assertEqual(oct(-100L), '-0144L')
925 self
.assertRaises(TypeError, oct, ())
926 self
.assertEqual(oct(3.125), '031 * 2.0 ** -3')
927 self
.assertEqual(oct(0.0), '0 * 2.0 ** 0')
928 for sv
in float('nan'), float('inf'), float('-inf'):
929 self
.assertEqual(oct(sv
), repr(sv
))
931 x
= random
.expovariate(.05)
932 self
.assertEqual(eval(oct(x
)), x
)
933 self
.assertEqual(eval(oct(-x
)), -x
)
934 self
.assertEqual(oct(-x
), ('-' + oct(x
)))
936 def write_testfile(self
):
937 # NB the first 4 lines are also used to test input and raw_input, below
938 fp
= open(TESTFN
, 'w')
942 fp
.write('The quick brown fox jumps over the lazy dog')
944 fp
.write('Dear John\n')
951 self
.write_testfile()
952 fp
= open(TESTFN
, 'r')
954 self
.assertEqual(fp
.readline(4), '1+1\n')
955 self
.assertEqual(fp
.readline(4), '1+1\n')
956 self
.assertEqual(fp
.readline(), 'The quick brown fox jumps over the lazy dog.\n')
957 self
.assertEqual(fp
.readline(4), 'Dear')
958 self
.assertEqual(fp
.readline(100), ' John\n')
959 self
.assertEqual(fp
.read(300), 'XXX'*100)
960 self
.assertEqual(fp
.read(1000), 'YYY'*100)
966 self
.assertEqual(ord(' '), 32)
967 self
.assertEqual(ord('A'), 65)
968 self
.assertEqual(ord('a'), 97)
970 self
.assertEqual(ord(unichr(sys
.maxunicode
)), sys
.maxunicode
)
971 self
.assertRaises(TypeError, ord, 42)
973 self
.assertRaises(TypeError, ord, unicode("12"))
976 self
.assertEqual(pow(0,0), 1)
977 self
.assertEqual(pow(0,1), 0)
978 self
.assertEqual(pow(1,0), 1)
979 self
.assertEqual(pow(1,1), 1)
981 self
.assertEqual(pow(2,0), 1)
982 self
.assertEqual(pow(2,10), 1024)
983 self
.assertEqual(pow(2,20), 1024*1024)
984 self
.assertEqual(pow(2,30), 1024*1024*1024)
986 self
.assertEqual(pow(-2,0), 1)
987 self
.assertEqual(pow(-2,1), -2)
988 self
.assertEqual(pow(-2,2), 4)
989 self
.assertEqual(pow(-2,3), -8)
991 self
.assertEqual(pow(0L,0), 1)
992 self
.assertEqual(pow(0L,1), 0)
993 self
.assertEqual(pow(1L,0), 1)
994 self
.assertEqual(pow(1L,1), 1)
996 self
.assertEqual(pow(2L,0), 1)
997 self
.assertEqual(pow(2L,10), 1024)
998 self
.assertEqual(pow(2L,20), 1024*1024)
999 self
.assertEqual(pow(2L,30), 1024*1024*1024)
1001 self
.assertEqual(pow(-2L,0), 1)
1002 self
.assertEqual(pow(-2L,1), -2)
1003 self
.assertEqual(pow(-2L,2), 4)
1004 self
.assertEqual(pow(-2L,3), -8)
1006 self
.assertAlmostEqual(pow(0.,0), 1.)
1007 self
.assertAlmostEqual(pow(0.,1), 0.)
1008 self
.assertAlmostEqual(pow(1.,0), 1.)
1009 self
.assertAlmostEqual(pow(1.,1), 1.)
1011 self
.assertAlmostEqual(pow(2.,0), 1.)
1012 self
.assertAlmostEqual(pow(2.,10), 1024.)
1013 self
.assertAlmostEqual(pow(2.,20), 1024.*1024.)
1014 self
.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)
1016 self
.assertAlmostEqual(pow(-2.,0), 1.)
1017 self
.assertAlmostEqual(pow(-2.,1), -2.)
1018 self
.assertAlmostEqual(pow(-2.,2), 4.)
1019 self
.assertAlmostEqual(pow(-2.,3), -8.)
1021 for x
in 2, 2L, 2.0:
1022 for y
in 10, 10L, 10.0:
1023 for z
in 1000, 1000L, 1000.0:
1024 if isinstance(x
, float) or \
1025 isinstance(y
, float) or \
1026 isinstance(z
, float):
1027 self
.assertRaises(TypeError, pow, x
, y
, z
)
1029 self
.assertAlmostEqual(pow(x
, y
, z
), 24.0)
1031 self
.assertRaises(TypeError, pow, -1, -2, 3)
1032 self
.assertRaises(ValueError, pow, 1, 2, 0)
1033 self
.assertRaises(TypeError, pow, -1L, -2L, 3L)
1034 self
.assertRaises(ValueError, pow, 1L, 2L, 0L)
1035 # Will return complex in 3.0:
1036 self
.assertRaises(ValueError, pow, -342.43, 0.234)
1038 self
.assertRaises(TypeError, pow)
1040 def test_range(self
):
1041 self
.assertEqual(range(3), [0, 1, 2])
1042 self
.assertEqual(range(1, 5), [1, 2, 3, 4])
1043 self
.assertEqual(range(0), [])
1044 self
.assertEqual(range(-3), [])
1045 self
.assertEqual(range(1, 10, 3), [1, 4, 7])
1046 self
.assertEqual(range(5, -5, -3), [5, 2, -1, -4])
1048 # Now test range() with longs
1049 self
.assertEqual(range(-2**100), [])
1050 self
.assertEqual(range(0, -2**100), [])
1051 self
.assertEqual(range(0, 2**100, -1), [])
1052 self
.assertEqual(range(0, 2**100, -1), [])
1054 a
= long(10 * sys
.maxint
)
1055 b
= long(100 * sys
.maxint
)
1056 c
= long(50 * sys
.maxint
)
1058 self
.assertEqual(range(a
, a
+2), [a
, a
+1])
1059 self
.assertEqual(range(a
+2, a
, -1L), [a
+2, a
+1])
1060 self
.assertEqual(range(a
+4, a
, -2), [a
+4, a
+2])
1062 seq
= range(a
, b
, c
)
1063 self
.assert_(a
in seq
)
1064 self
.assert_(b
not in seq
)
1065 self
.assertEqual(len(seq
), 2)
1067 seq
= range(b
, a
, -c
)
1068 self
.assert_(b
in seq
)
1069 self
.assert_(a
not in seq
)
1070 self
.assertEqual(len(seq
), 2)
1072 seq
= range(-a
, -b
, -c
)
1073 self
.assert_(-a
in seq
)
1074 self
.assert_(-b
not in seq
)
1075 self
.assertEqual(len(seq
), 2)
1077 self
.assertRaises(TypeError, range)
1078 self
.assertRaises(TypeError, range, 1, 2, 3, 4)
1079 self
.assertRaises(ValueError, range, 1, 2, 0)
1080 self
.assertRaises(ValueError, range, a
, a
+ 1, long(0))
1083 def __cmp__(self
, other
):
1085 self
.assertRaises(RuntimeError, range, a
, a
+ 1, badzero(1))
1087 # Reject floats when it would require PyLongs to represent.
1088 # (smaller floats still accepted, but deprecated)
1089 self
.assertRaises(TypeError, range, 1e100
, 1e101
, 1e101
)
1091 self
.assertRaises(TypeError, range, 0, "spam")
1092 self
.assertRaises(TypeError, range, 0, 42, "spam")
1094 self
.assertRaises(OverflowError, range, -sys
.maxint
, sys
.maxint
)
1095 self
.assertRaises(OverflowError, range, 0, 2*sys
.maxint
)
1097 def test_input_and_raw_input(self
):
1098 self
.write_testfile()
1099 fp
= open(TESTFN
, 'r')
1100 savestdin
= sys
.stdin
1101 savestdout
= sys
.stdout
# Eats the echo
1104 sys
.stdout
= BitBucket()
1105 self
.assertEqual(input(), 2)
1106 self
.assertEqual(input('testing\n'), 2)
1107 self
.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.')
1108 self
.assertEqual(raw_input('testing\n'), 'Dear John')
1110 # SF 1535165: don't segfault on closed stdin
1111 # sys.stdout must be a regular file for triggering
1112 sys
.stdout
= savestdout
1114 self
.assertRaises(ValueError, input)
1116 sys
.stdout
= BitBucket()
1117 sys
.stdin
= cStringIO
.StringIO("NULL\0")
1118 self
.assertRaises(TypeError, input, 42, 42)
1119 sys
.stdin
= cStringIO
.StringIO(" 'whitespace'")
1120 self
.assertEqual(input(), 'whitespace')
1121 sys
.stdin
= cStringIO
.StringIO()
1122 self
.assertRaises(EOFError, input)
1124 # SF 876178: make sure input() respect future options.
1125 sys
.stdin
= cStringIO
.StringIO('1/2')
1126 sys
.stdout
= cStringIO
.StringIO()
1127 exec compile('print input()', 'test_builtin_tmp', 'exec')
1128 sys
.stdin
.seek(0, 0)
1129 exec compile('from __future__ import division;print input()',
1130 'test_builtin_tmp', 'exec')
1131 sys
.stdin
.seek(0, 0)
1132 exec compile('print input()', 'test_builtin_tmp', 'exec')
1133 # The result we expect depends on whether new division semantics
1134 # are already in effect.
1136 # This test was compiled with old semantics.
1137 expected
= ['0', '0.5', '0']
1139 # This test was compiled with new semantics (e.g., -Qnew
1140 # was given on the command line.
1141 expected
= ['0.5', '0.5', '0.5']
1142 self
.assertEqual(sys
.stdout
.getvalue().splitlines(), expected
)
1145 self
.assertRaises(RuntimeError, input, 'prompt')
1147 self
.assertRaises(RuntimeError, input, 'prompt')
1149 sys
.stdin
= savestdin
1150 sys
.stdout
= savestdout
1154 def test_reduce(self
):
1155 self
.assertEqual(reduce(lambda x
, y
: x
+y
, ['a', 'b', 'c'], ''), 'abc')
1157 reduce(lambda x
, y
: x
+y
, [['a', 'c'], [], ['d', 'w']], []),
1160 self
.assertEqual(reduce(lambda x
, y
: x
*y
, range(2,8), 1), 5040)
1162 reduce(lambda x
, y
: x
*y
, range(2,21), 1L),
1163 2432902008176640000L
1165 self
.assertEqual(reduce(lambda x
, y
: x
+y
, Squares(10)), 285)
1166 self
.assertEqual(reduce(lambda x
, y
: x
+y
, Squares(10), 0), 285)
1167 self
.assertEqual(reduce(lambda x
, y
: x
+y
, Squares(0), 0), 0)
1168 self
.assertRaises(TypeError, reduce)
1169 self
.assertRaises(TypeError, reduce, 42, 42)
1170 self
.assertRaises(TypeError, reduce, 42, 42, 42)
1171 self
.assertEqual(reduce(42, "1"), "1") # func is never called with one item
1172 self
.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item
1173 self
.assertRaises(TypeError, reduce, 42, (42, 42))
1176 def __getitem__(self
, index
):
1178 self
.assertRaises(ValueError, reduce, 42, BadSeq())
1180 def test_reload(self
):
1186 ## self.assertRaises(ImportError, reload, sys)
1188 def test_repr(self
):
1189 self
.assertEqual(repr(''), '\'\'')
1190 self
.assertEqual(repr(0), '0')
1191 self
.assertEqual(repr(0L), '0L')
1192 self
.assertEqual(repr(()), '()')
1193 self
.assertEqual(repr([]), '[]')
1194 self
.assertEqual(repr({}), '{}')
1197 self
.assertEqual(repr(a
), '[[...]]')
1200 self
.assertEqual(repr(a
), '{0: {...}}')
1202 def test_round(self
):
1203 self
.assertEqual(round(0.0), 0.0)
1204 self
.assertEqual(type(round(0.0)), float) # Will be int in 3.0.
1205 self
.assertEqual(round(1.0), 1.0)
1206 self
.assertEqual(round(10.0), 10.0)
1207 self
.assertEqual(round(1000000000.0), 1000000000.0)
1208 self
.assertEqual(round(1e20
), 1e20
)
1210 self
.assertEqual(round(-1.0), -1.0)
1211 self
.assertEqual(round(-10.0), -10.0)
1212 self
.assertEqual(round(-1000000000.0), -1000000000.0)
1213 self
.assertEqual(round(-1e20
), -1e20
)
1215 self
.assertEqual(round(0.1), 0.0)
1216 self
.assertEqual(round(1.1), 1.0)
1217 self
.assertEqual(round(10.1), 10.0)
1218 self
.assertEqual(round(1000000000.1), 1000000000.0)
1220 self
.assertEqual(round(-1.1), -1.0)
1221 self
.assertEqual(round(-10.1), -10.0)
1222 self
.assertEqual(round(-1000000000.1), -1000000000.0)
1224 self
.assertEqual(round(0.9), 1.0)
1225 self
.assertEqual(round(9.9), 10.0)
1226 self
.assertEqual(round(999999999.9), 1000000000.0)
1228 self
.assertEqual(round(-0.9), -1.0)
1229 self
.assertEqual(round(-9.9), -10.0)
1230 self
.assertEqual(round(-999999999.9), -1000000000.0)
1232 self
.assertEqual(round(-8.0, -1), -10.0)
1233 self
.assertEqual(type(round(-8.0, -1)), float)
1235 self
.assertEqual(type(round(-8.0, 0)), float)
1236 self
.assertEqual(type(round(-8.0, 1)), float)
1238 # Check half rounding behaviour.
1239 self
.assertEqual(round(5.5), 6)
1240 self
.assertEqual(round(6.5), 7)
1241 self
.assertEqual(round(-5.5), -6)
1242 self
.assertEqual(round(-6.5), -7)
1244 # Check behavior on ints
1245 self
.assertEqual(round(0), 0)
1246 self
.assertEqual(round(8), 8)
1247 self
.assertEqual(round(-8), -8)
1248 self
.assertEqual(type(round(0)), float) # Will be int in 3.0.
1249 self
.assertEqual(type(round(-8, -1)), float)
1250 self
.assertEqual(type(round(-8, 0)), float)
1251 self
.assertEqual(type(round(-8, 1)), float)
1254 self
.assertEqual(round(number
=-8.0, ndigits
=-1), -10.0)
1256 self
.assertRaises(TypeError, round)
1258 # test generic rounding delegation for reals
1259 class TestRound(object):
1260 def __float__(self
):
1263 class TestNoRound(object):
1266 self
.assertEqual(round(TestRound()), 23)
1268 self
.assertRaises(TypeError, round, 1, 2, 3)
1269 self
.assertRaises(TypeError, round, TestNoRound())
1272 t
.__float
__ = lambda *args
: args
1273 self
.assertRaises(TypeError, round, t
)
1274 self
.assertRaises(TypeError, round, t
, 0)
1276 def test_setattr(self
):
1277 setattr(sys
, 'spam', 1)
1278 self
.assertEqual(sys
.spam
, 1)
1279 self
.assertRaises(TypeError, setattr, sys
, 1, 'spam')
1280 self
.assertRaises(TypeError, setattr)
1283 self
.assertEqual(sum([]), 0)
1284 self
.assertEqual(sum(range(2,8)), 27)
1285 self
.assertEqual(sum(iter(range(2,8))), 27)
1286 self
.assertEqual(sum(Squares(10)), 285)
1287 self
.assertEqual(sum(iter(Squares(10))), 285)
1288 self
.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
1290 self
.assertRaises(TypeError, sum)
1291 self
.assertRaises(TypeError, sum, 42)
1292 self
.assertRaises(TypeError, sum, ['a', 'b', 'c'])
1293 self
.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
1294 self
.assertRaises(TypeError, sum, [[1], [2], [3]])
1295 self
.assertRaises(TypeError, sum, [{2:3}])
1296 self
.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
1299 def __getitem__(self
, index
):
1301 self
.assertRaises(ValueError, sum, BadSeq())
1303 def test_type(self
):
1304 self
.assertEqual(type(''), type('123'))
1305 self
.assertNotEqual(type(''), type(()))
1307 def test_unichr(self
):
1309 self
.assertEqual(unichr(32), unicode(' '))
1310 self
.assertEqual(unichr(65), unicode('A'))
1311 self
.assertEqual(unichr(97), unicode('a'))
1313 unichr(sys
.maxunicode
),
1314 unicode('\\U%08x' % (sys
.maxunicode
), 'unicode-escape')
1316 self
.assertRaises(ValueError, unichr, sys
.maxunicode
+1)
1317 self
.assertRaises(TypeError, unichr)
1319 # We don't want self in vars(), so these are static methods
1327 BuiltinTest
.get_vars_f0()
1332 def test_vars(self
):
1333 self
.assertEqual(set(vars()), set(dir()))
1335 self
.assertEqual(set(vars(sys
)), set(dir(sys
)))
1336 self
.assertEqual(self
.get_vars_f0(), {})
1337 self
.assertEqual(self
.get_vars_f2(), {'a': 1, 'b': 2})
1338 self
.assertRaises(TypeError, vars, 42, 42)
1339 self
.assertRaises(TypeError, vars, 42)
1344 t
= [(1, 4), (2, 5), (3, 6)]
1345 self
.assertEqual(zip(a
, b
), t
)
1347 self
.assertEqual(zip(a
, b
), t
)
1349 self
.assertEqual(zip(a
, b
), t
)
1351 def __getitem__(self
, i
):
1352 if i
< 0 or i
> 2: raise IndexError
1354 self
.assertEqual(zip(a
, I()), t
)
1355 self
.assertEqual(zip(), [])
1356 self
.assertEqual(zip(*[]), [])
1357 self
.assertRaises(TypeError, zip, None)
1360 self
.assertRaises(TypeError, zip, a
, G())
1362 # Make sure zip doesn't try to allocate a billion elements for the
1363 # result list when one of its arguments doesn't say how long it is.
1364 # A MemoryError is the most likely failure mode.
1365 class SequenceWithoutALength
:
1366 def __getitem__(self
, i
):
1372 zip(SequenceWithoutALength(), xrange(2**30)),
1373 list(enumerate(range(5)))
1377 def __getitem__(self
, i
):
1382 self
.assertRaises(ValueError, zip, BadSeq(), BadSeq())
1384 def test_format(self
):
1385 # Test the basic machinery of the format() builtin. Don't test
1386 # the specifics of the various formatters
1387 self
.assertEqual(format(3, ''), '3')
1389 # Returns some classes to use for various tests. There's
1390 # an old-style version, and a new-style version
1393 def __init__(self
, x
):
1395 def __format__(self
, format_spec
):
1396 return str(self
.x
) + format_spec
1397 class DerivedFromA(A
):
1400 class Simple(object): pass
1401 class DerivedFromSimple(Simple
):
1402 def __init__(self
, x
):
1404 def __format__(self
, format_spec
):
1405 return str(self
.x
) + format_spec
1406 class DerivedFromSimple2(DerivedFromSimple
): pass
1407 return A
, DerivedFromA
, DerivedFromSimple
, DerivedFromSimple2
1409 # In 3.0, classes_classic has the same meaning as classes_new
1410 def classes_classic():
1412 def __init__(self
, x
):
1414 def __format__(self
, format_spec
):
1415 return str(self
.x
) + format_spec
1416 class DerivedFromA(A
):
1420 class DerivedFromSimple(Simple
):
1421 def __init__(self
, x
):
1423 def __format__(self
, format_spec
):
1424 return str(self
.x
) + format_spec
1425 class DerivedFromSimple2(DerivedFromSimple
): pass
1426 return A
, DerivedFromA
, DerivedFromSimple
, DerivedFromSimple2
1428 def class_test(A
, DerivedFromA
, DerivedFromSimple
, DerivedFromSimple2
):
1429 self
.assertEqual(format(A(3), 'spec'), '3spec')
1430 self
.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
1431 self
.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
1432 self
.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
1435 class_test(*classes_new())
1436 class_test(*classes_classic())
1438 def empty_format_spec(value
):
1440 # format(x, '') == str(x)
1441 # format(x) == str(x)
1442 self
.assertEqual(format(value
, ""), str(value
))
1443 self
.assertEqual(format(value
), str(value
))
1445 # for builtin types, format(x, "") == str(x)
1446 empty_format_spec(17**13)
1447 empty_format_spec(1.0)
1448 empty_format_spec(3.1415e104
)
1449 empty_format_spec(-3.1415e104
)
1450 empty_format_spec(3.1415e-104)
1451 empty_format_spec(-3.1415e-104)
1452 empty_format_spec(object)
1453 empty_format_spec(None)
1455 # TypeError because self.__format__ returns the wrong type
1456 class BadFormatResult
:
1457 def __format__(self
, format_spec
):
1459 self
.assertRaises(TypeError, format
, BadFormatResult(), "")
1461 # TypeError because format_spec is not unicode or str
1462 self
.assertRaises(TypeError, format
, object(), 4)
1463 self
.assertRaises(TypeError, format
, object(), object())
1465 # tests for object.__format__ really belong elsewhere, but
1466 # there's no good place to put them
1467 x
= object().__format
__('')
1468 self
.assert_(x
.startswith('<object object at'))
1470 # first argument to object.__format__ must be string
1471 self
.assertRaises(TypeError, object().__format
__, 3)
1472 self
.assertRaises(TypeError, object().__format
__, object())
1473 self
.assertRaises(TypeError, object().__format
__, None)
1475 # make sure we can take a subclass of str as a format spec
1476 class DerivedFromStr(str): pass
1477 self
.assertEqual(format(0, DerivedFromStr('10')), ' 0')
1480 self
.assertEqual(bin(0), '0b0')
1481 self
.assertEqual(bin(1), '0b1')
1482 self
.assertEqual(bin(-1), '-0b1')
1483 self
.assertEqual(bin(2**65), '0b1' + '0' * 65)
1484 self
.assertEqual(bin(2**65-1), '0b' + '1' * 65)
1485 self
.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)
1486 self
.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)
1487 self
.assertEqual(bin(3.125), '0b11001 * 2.0 ** -3')
1488 self
.assertEqual(bin(0.0), '0b0 * 2.0 ** 0')
1489 for sv
in float('nan'), float('inf'), float('-inf'):
1490 self
.assertEqual(bin(sv
), repr(sv
))
1491 for i
in range(100):
1492 x
= random
.expovariate(.05)
1493 self
.assertEqual(eval(bin(x
)), x
)
1494 self
.assertEqual(eval(bin(-x
)), -x
)
1495 self
.assertEqual(bin(-x
), ('-' + bin(x
)))
1497 class TestSorted(unittest
.TestCase
):
1499 def test_basic(self
):
1502 random
.shuffle(copy
)
1503 self
.assertEqual(data
, sorted(copy
))
1504 self
.assertNotEqual(data
, copy
)
1507 random
.shuffle(copy
)
1508 self
.assertEqual(data
, sorted(copy
, cmp=lambda x
, y
: cmp(y
,x
)))
1509 self
.assertNotEqual(data
, copy
)
1510 random
.shuffle(copy
)
1511 self
.assertEqual(data
, sorted(copy
, key
=lambda x
: -x
))
1512 self
.assertNotEqual(data
, copy
)
1513 random
.shuffle(copy
)
1514 self
.assertEqual(data
, sorted(copy
, reverse
=1))
1515 self
.assertNotEqual(data
, copy
)
1517 def test_inputtypes(self
):
1519 types
= [list, tuple]
1521 types
.insert(0, unicode)
1523 self
.assertEqual(sorted(s
), sorted(T(s
)))
1525 s
= ''.join(dict.fromkeys(s
).keys()) # unique letters only
1526 types
= [set, frozenset, list, tuple, dict.fromkeys
]
1528 types
.insert(0, unicode)
1530 self
.assertEqual(sorted(s
), sorted(T(s
)))
1532 def test_baddecorator(self
):
1533 data
= 'The quick Brown fox Jumped over The lazy Dog'.split()
1534 self
.assertRaises(TypeError, sorted, data
, None, lambda x
,y
: 0)
1536 def test_main(verbose
=None):
1537 test_classes
= (BuiltinTest
, TestSorted
)
1539 run_unittest(*test_classes
)
1541 # verify reference counting
1542 if verbose
and hasattr(sys
, "gettotalrefcount"):
1545 for i
in xrange(len(counts
)):
1546 run_unittest(*test_classes
)
1548 counts
[i
] = sys
.gettotalrefcount()
1552 if __name__
== "__main__":
1553 test_main(verbose
=True)