0001 # Python test set -- built-in functions 0002 0003 import test.test_support, unittest 0004 from test.test_support import fcmp, have_unicode, TESTFN, unlink 0005 0006 import sys, warnings, cStringIO, random, UserDict 0007 warnings.filterwarnings("ignore", "hex../oct.. of negative int", 0008 FutureWarning, __name__) 0009 warnings.filterwarnings("ignore", "integer argument expected", 0010 DeprecationWarning, "unittest") 0011 0012 class Squares: 0013 0014 def __init__(self, max): 0015 self.max = max 0016 self.sofar = [] 0017 0018 def __len__(self): return len(self.sofar) 0019 0020 def __getitem__(self, i): 0021 if not 0 <= i < self.max: raise IndexError 0022 n = len(self.sofar) 0023 while n <= i: 0024 self.sofar.append(n*n) 0025 n += 1 0026 return self.sofar[i] 0027 0028 class StrSquares: 0029 0030 def __init__(self, max): 0031 self.max = max 0032 self.sofar = [] 0033 0034 def __len__(self): 0035 return len(self.sofar) 0036 0037 def __getitem__(self, i): 0038 if not 0 <= i < self.max: 0039 raise IndexError 0040 n = len(self.sofar) 0041 while n <= i: 0042 self.sofar.append(str(n*n)) 0043 n += 1 0044 return self.sofar[i] 0045 0046 class BitBucket: 0047 def write(self, line): 0048 pass 0049 0050 L = [ 0051 ('0', 0), 0052 ('1', 1), 0053 ('9', 9), 0054 ('10', 10), 0055 ('99', 99), 0056 ('100', 100), 0057 ('314', 314), 0058 (' 314', 314), 0059 ('314 ', 314), 0060 (' \t\t 314 \t\t ', 314), 0061 (repr(sys.maxint), sys.maxint), 0062 (' 1x', ValueError), 0063 (' 1 ', 1), 0064 (' 1\02 ', ValueError), 0065 ('', ValueError), 0066 (' ', ValueError), 0067 (' \t\t ', ValueError) 0068 ] 0069 if have_unicode: 0070 L += [ 0071 (unicode('0'), 0), 0072 (unicode('1'), 1), 0073 (unicode('9'), 9), 0074 (unicode('10'), 10), 0075 (unicode('99'), 99), 0076 (unicode('100'), 100), 0077 (unicode('314'), 314), 0078 (unicode(' 314'), 314), 0079 (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314), 0080 (unicode(' \t\t 314 \t\t '), 314), 0081 (unicode(' 1x'), ValueError), 0082 (unicode(' 1 '), 1), 0083 (unicode(' 1\02 '), ValueError), 0084 (unicode(''), ValueError), 0085 (unicode(' '), ValueError), 0086 (unicode(' \t\t '), ValueError), 0087 (unichr(0x200), ValueError), 0088 ] 0089 0090 class BuiltinTest(unittest.TestCase): 0091 0092 def test_import(self): 0093 __import__('sys') 0094 __import__('time') 0095 __import__('string') 0096 self.assertRaises(ImportError, __import__, 'spamspam') 0097 self.assertRaises(TypeError, __import__, 1, 2, 3, 4) 0098 0099 def test_abs(self): 0100 # int 0101 self.assertEqual(abs(0), 0) 0102 self.assertEqual(abs(1234), 1234) 0103 self.assertEqual(abs(-1234), 1234) 0104 # float 0105 self.assertEqual(abs(0.0), 0.0) 0106 self.assertEqual(abs(3.14), 3.14) 0107 self.assertEqual(abs(-3.14), 3.14) 0108 # long 0109 self.assertEqual(abs(0L), 0L) 0110 self.assertEqual(abs(1234L), 1234L) 0111 self.assertEqual(abs(-1234L), 1234L) 0112 # str 0113 self.assertRaises(TypeError, abs, 'a') 0114 0115 def test_apply(self): 0116 def f0(*args): 0117 self.assertEqual(args, ()) 0118 def f1(a1): 0119 self.assertEqual(a1, 1) 0120 def f2(a1, a2): 0121 self.assertEqual(a1, 1) 0122 self.assertEqual(a2, 2) 0123 def f3(a1, a2, a3): 0124 self.assertEqual(a1, 1) 0125 self.assertEqual(a2, 2) 0126 self.assertEqual(a3, 3) 0127 apply(f0, ()) 0128 apply(f1, (1,)) 0129 apply(f2, (1, 2)) 0130 apply(f3, (1, 2, 3)) 0131 0132 # A PyCFunction that takes only positional parameters should allow an 0133 # empty keyword dictionary to pass without a complaint, but raise a 0134 # TypeError if the dictionary is non-empty. 0135 apply(id, (1,), {}) 0136 self.assertRaises(TypeError, apply, id, (1,), {"foo": 1}) 0137 self.assertRaises(TypeError, apply) 0138 self.assertRaises(TypeError, apply, id, 42) 0139 self.assertRaises(TypeError, apply, id, (42,), 42) 0140 0141 def test_callable(self): 0142 self.assert_(callable(len)) 0143 def f(): pass 0144 self.assert_(callable(f)) 0145 class C: 0146 def meth(self): pass 0147 self.assert_(callable(C)) 0148 x = C() 0149 self.assert_(callable(x.meth)) 0150 self.assert_(not callable(x)) 0151 class D(C): 0152 def __call__(self): pass 0153 y = D() 0154 self.assert_(callable(y)) 0155 y() 0156 0157 def test_chr(self): 0158 self.assertEqual(chr(32), ' ') 0159 self.assertEqual(chr(65), 'A') 0160 self.assertEqual(chr(97), 'a') 0161 self.assertEqual(chr(0xff), '\xff') 0162 self.assertRaises(ValueError, chr, 256) 0163 self.assertRaises(TypeError, chr) 0164 0165 def test_cmp(self): 0166 self.assertEqual(cmp(-1, 1), -1) 0167 self.assertEqual(cmp(1, -1), 1) 0168 self.assertEqual(cmp(1, 1), 0) 0169 # verify that circular objects are not handled 0170 a = []; a.append(a) 0171 b = []; b.append(b) 0172 from UserList import UserList 0173 c = UserList(); c.append(c) 0174 self.assertRaises(RuntimeError, cmp, a, b) 0175 self.assertRaises(RuntimeError, cmp, b, c) 0176 self.assertRaises(RuntimeError, cmp, c, a) 0177 self.assertRaises(RuntimeError, cmp, a, c) 0178 # okay, now break the cycles 0179 a.pop(); b.pop(); c.pop() 0180 self.assertRaises(TypeError, cmp) 0181 0182 def test_coerce(self): 0183 self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1))) 0184 self.assertEqual(coerce(1, 1L), (1L, 1L)) 0185 self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1))) 0186 self.assertRaises(TypeError, coerce) 0187 class BadNumber: 0188 def __coerce__(self, other): 0189 raise ValueError 0190 self.assertRaises(ValueError, coerce, 42, BadNumber()) 0191 self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000)) 0192 0193 def test_compile(self): 0194 compile('print 1\n', '', 'exec') 0195 bom = '\xef\xbb\xbf' 0196 compile(bom + 'print 1\n', '', 'exec') 0197 self.assertRaises(TypeError, compile) 0198 self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'badmode') 0199 self.assertRaises(ValueError, compile, 'print 42\n', '<string>', 'single', 0xff) 0200 if have_unicode: 0201 compile(unicode('print u"\xc3\xa5"\n', 'utf8'), '', 'exec') 0202 0203 def test_delattr(self): 0204 import sys 0205 sys.spam = 1 0206 delattr(sys, 'spam') 0207 self.assertRaises(TypeError, delattr) 0208 0209 def test_dir(self): 0210 x = 1 0211 self.assert_('x' in dir()) 0212 import sys 0213 self.assert_('modules' in dir(sys)) 0214 self.assertRaises(TypeError, dir, 42, 42) 0215 0216 def test_divmod(self): 0217 self.assertEqual(divmod(12, 7), (1, 5)) 0218 self.assertEqual(divmod(-12, 7), (-2, 2)) 0219 self.assertEqual(divmod(12, -7), (-2, -2)) 0220 self.assertEqual(divmod(-12, -7), (1, -5)) 0221 0222 self.assertEqual(divmod(12L, 7L), (1L, 5L)) 0223 self.assertEqual(divmod(-12L, 7L), (-2L, 2L)) 0224 self.assertEqual(divmod(12L, -7L), (-2L, -2L)) 0225 self.assertEqual(divmod(-12L, -7L), (1L, -5L)) 0226 0227 self.assertEqual(divmod(12, 7L), (1, 5L)) 0228 self.assertEqual(divmod(-12, 7L), (-2, 2L)) 0229 self.assertEqual(divmod(12L, -7), (-2L, -2)) 0230 self.assertEqual(divmod(-12L, -7), (1L, -5)) 0231 0232 self.assertEqual(divmod(-sys.maxint-1, -1), 0233 (sys.maxint+1, 0)) 0234 0235 self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25))) 0236 self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75))) 0237 self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75))) 0238 self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25))) 0239 0240 self.assertRaises(TypeError, divmod) 0241 0242 def test_eval(self): 0243 self.assertEqual(eval('1+1'), 2) 0244 self.assertEqual(eval(' 1+1\n'), 2) 0245 globals = {'a': 1, 'b': 2} 0246 locals = {'b': 200, 'c': 300} 0247 self.assertEqual(eval('a', globals) , 1) 0248 self.assertEqual(eval('a', globals, locals), 1) 0249 self.assertEqual(eval('b', globals, locals), 200) 0250 self.assertEqual(eval('c', globals, locals), 300) 0251 if have_unicode: 0252 self.assertEqual(eval(unicode('1+1')), 2) 0253 self.assertEqual(eval(unicode(' 1+1\n')), 2) 0254 globals = {'a': 1, 'b': 2} 0255 locals = {'b': 200, 'c': 300} 0256 if have_unicode: 0257 self.assertEqual(eval(unicode('a'), globals), 1) 0258 self.assertEqual(eval(unicode('a'), globals, locals), 1) 0259 self.assertEqual(eval(unicode('b'), globals, locals), 200) 0260 self.assertEqual(eval(unicode('c'), globals, locals), 300) 0261 bom = '\xef\xbb\xbf' 0262 self.assertEqual(eval(bom + 'a', globals, locals), 1) 0263 self.assertEqual(eval(unicode('u"\xc3\xa5"', 'utf8'), globals), 0264 unicode('\xc3\xa5', 'utf8')) 0265 self.assertRaises(TypeError, eval) 0266 self.assertRaises(TypeError, eval, ()) 0267 0268 def test_general_eval(self): 0269 # Tests that general mappings can be used for the locals argument 0270 0271 class M: 0272 "Test mapping interface versus possible calls from eval()." 0273 def __getitem__(self, key): 0274 if key == 'a': 0275 return 12 0276 raise KeyError 0277 def keys(self): 0278 return list('xyz') 0279 0280 m = M() 0281 g = globals() 0282 self.assertEqual(eval('a', g, m), 12) 0283 self.assertRaises(NameError, eval, 'b', g, m) 0284 self.assertEqual(eval('dir()', g, m), list('xyz')) 0285 self.assertEqual(eval('globals()', g, m), g) 0286 self.assertEqual(eval('locals()', g, m), m) 0287 self.assertRaises(TypeError, eval, 'a', m) 0288 class A: 0289 "Non-mapping" 0290 pass 0291 m = A() 0292 self.assertRaises(TypeError, eval, 'a', g, m) 0293 0294 # Verify that dict subclasses work as well 0295 class D(dict): 0296 def __getitem__(self, key): 0297 if key == 'a': 0298 return 12 0299 return dict.__getitem__(self, key) 0300 def keys(self): 0301 return list('xyz') 0302 0303 d = D() 0304 self.assertEqual(eval('a', g, d), 12) 0305 self.assertRaises(NameError, eval, 'b', g, d) 0306 self.assertEqual(eval('dir()', g, d), list('xyz')) 0307 self.assertEqual(eval('globals()', g, d), g) 0308 self.assertEqual(eval('locals()', g, d), d) 0309 0310 # Verify locals stores (used by list comps) 0311 eval('[locals() for i in (2,3)]', g, d) 0312 eval('[locals() for i in (2,3)]', g, UserDict.UserDict()) 0313 0314 class SpreadSheet: 0315 "Sample application showing nested, calculated lookups." 0316 _cells = {} 0317 def __setitem__(self, key, formula): 0318 self._cells[key] = formula 0319 def __getitem__(self, key ): 0320 return eval(self._cells[key], globals(), self) 0321 0322 ss = SpreadSheet() 0323 ss['a1'] = '5' 0324 ss['a2'] = 'a1*6' 0325 ss['a3'] = 'a2*7' 0326 self.assertEqual(ss['a3'], 210) 0327 0328 # Verify that dir() catches a non-list returned by eval 0329 # SF bug #1004669 0330 class C: 0331 def __getitem__(self, item): 0332 raise KeyError(item) 0333 def keys(self): 0334 return 'a' 0335 self.assertRaises(TypeError, eval, 'dir()', globals(), C()) 0336 0337 # Done outside of the method test_z to get the correct scope 0338 z = 0 0339 f = open(TESTFN, 'w') 0340 f.write('z = z+1\n') 0341 f.write('z = z*2\n') 0342 f.close() 0343 execfile(TESTFN) 0344 0345 def test_execfile(self): 0346 globals = {'a': 1, 'b': 2} 0347 locals = {'b': 200, 'c': 300} 0348 0349 self.assertEqual(self.__class__.z, 2) 0350 globals['z'] = 0 0351 execfile(TESTFN, globals) 0352 self.assertEqual(globals['z'], 2) 0353 locals['z'] = 0 0354 execfile(TESTFN, globals, locals) 0355 self.assertEqual(locals['z'], 2) 0356 0357 class M: 0358 "Test mapping interface versus possible calls from execfile()." 0359 def __init__(self): 0360 self.z = 10 0361 def __getitem__(self, key): 0362 if key == 'z': 0363 return self.z 0364 raise KeyError 0365 def __setitem__(self, key, value): 0366 if key == 'z': 0367 self.z = value 0368 return 0369 raise KeyError 0370 0371 locals = M() 0372 locals['z'] = 0 0373 execfile(TESTFN, globals, locals) 0374 self.assertEqual(locals['z'], 2) 0375 0376 unlink(TESTFN) 0377 self.assertRaises(TypeError, execfile) 0378 import os 0379 self.assertRaises(IOError, execfile, os.curdir) 0380 self.assertRaises(IOError, execfile, "I_dont_exist") 0381 0382 def test_filter(self): 0383 self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld') 0384 self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9]) 0385 self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2]) 0386 self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81]) 0387 self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81]) 0388 def identity(item): 0389 return 1 0390 filter(identity, Squares(5)) 0391 self.assertRaises(TypeError, filter) 0392 class BadSeq(object): 0393 def __getitem__(self, index): 0394 if index<4: 0395 return 42 0396 raise ValueError 0397 self.assertRaises(ValueError, filter, lambda x: x, BadSeq()) 0398 def badfunc(): 0399 pass 0400 self.assertRaises(TypeError, filter, badfunc, range(5)) 0401 0402 # test bltinmodule.c::filtertuple() 0403 self.assertEqual(filter(None, (1, 2)), (1, 2)) 0404 self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4)) 0405 self.assertRaises(TypeError, filter, 42, (1, 2)) 0406 0407 # test bltinmodule.c::filterstring() 0408 self.assertEqual(filter(None, "12"), "12") 0409 self.assertEqual(filter(lambda x: x>="3", "1234"), "34") 0410 self.assertRaises(TypeError, filter, 42, "12") 0411 class badstr(str): 0412 def __getitem__(self, index): 0413 raise ValueError 0414 self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234")) 0415 0416 class badstr2(str): 0417 def __getitem__(self, index): 0418 return 42 0419 self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234")) 0420 0421 class weirdstr(str): 0422 def __getitem__(self, index): 0423 return weirdstr(2*str.__getitem__(self, index)) 0424 self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344") 0425 0426 class shiftstr(str): 0427 def __getitem__(self, index): 0428 return chr(ord(str.__getitem__(self, index))+1) 0429 self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345") 0430 0431 if have_unicode: 0432 # test bltinmodule.c::filterunicode() 0433 self.assertEqual(filter(None, unicode("12")), unicode("12")) 0434 self.assertEqual(filter(lambda x: x>="3", unicode("1234")), unicode("34")) 0435 self.assertRaises(TypeError, filter, 42, unicode("12")) 0436 self.assertRaises(ValueError, filter, lambda x: x >="3", badstr(unicode("1234"))) 0437 0438 class badunicode(unicode): 0439 def __getitem__(self, index): 0440 return 42 0441 self.assertRaises(TypeError, filter, lambda x: x >=42, badunicode("1234")) 0442 0443 class weirdunicode(unicode): 0444 def __getitem__(self, index): 0445 return weirdunicode(2*unicode.__getitem__(self, index)) 0446 self.assertEqual( 0447 filter(lambda x: x>=unicode("33"), weirdunicode("1234")), unicode("3344")) 0448 0449 class shiftunicode(unicode): 0450 def __getitem__(self, index): 0451 return unichr(ord(unicode.__getitem__(self, index))+1) 0452 self.assertEqual( 0453 filter(lambda x: x>=unicode("3"), shiftunicode("1234")), 0454 unicode("345") 0455 ) 0456 0457 def test_filter_subclasses(self): 0458 # test that filter() never returns tuple, str or unicode subclasses 0459 # and that the result always goes through __getitem__ 0460 funcs = (None, bool, lambda x: True) 0461 class tuple2(tuple): 0462 def __getitem__(self, index): 0463 return 2*tuple.__getitem__(self, index) 0464 class str2(str): 0465 def __getitem__(self, index): 0466 return 2*str.__getitem__(self, index) 0467 inputs = { 0468 tuple2: {(): (), (1, 2, 3): (2, 4, 6)}, 0469 str2: {"": "", "123": "112233"} 0470 } 0471 if have_unicode: 0472 class unicode2(unicode): 0473 def __getitem__(self, index): 0474 return 2*unicode.__getitem__(self, index) 0475 inputs[unicode2] = { 0476 unicode(): unicode(), 0477 unicode("123"): unicode("112233") 0478 } 0479 0480 for (cls, inps) in inputs.iteritems(): 0481 for (inp, exp) in inps.iteritems(): 0482 # make sure the output goes through __getitem__ 0483 # even if func is None 0484 self.assertEqual( 0485 filter(funcs[0], cls(inp)), 0486 filter(funcs[1], cls(inp)) 0487 ) 0488 for func in funcs: 0489 outp = filter(func, cls(inp)) 0490 self.assertEqual(outp, exp) 0491 self.assert_(not isinstance(outp, cls)) 0492 0493 def test_float(self): 0494 self.assertEqual(float(3.14), 3.14) 0495 self.assertEqual(float(314), 314.0) 0496 self.assertEqual(float(314L), 314.0) 0497 self.assertEqual(float(" 3.14 "), 3.14) 0498 if have_unicode: 0499 self.assertEqual(float(unicode(" 3.14 ")), 3.14) 0500 self.assertEqual(float(unicode(" \u0663.\u0661\u0664 ",'raw-unicode-escape')), 3.14) 0501 0502 def test_getattr(self): 0503 import sys 0504 self.assert_(getattr(sys, 'stdout') is sys.stdout) 0505 self.assertRaises(TypeError, getattr, sys, 1) 0506 self.assertRaises(TypeError, getattr, sys, 1, "foo") 0507 self.assertRaises(TypeError, getattr) 0508 self.assertRaises(UnicodeError, getattr, sys, unichr(sys.maxunicode)) 0509 0510 def test_hasattr(self): 0511 import sys 0512 self.assert_(hasattr(sys, 'stdout')) 0513 self.assertRaises(TypeError, hasattr, sys, 1) 0514 self.assertRaises(TypeError, hasattr) 0515 self.assertRaises(UnicodeError, hasattr, sys, unichr(sys.maxunicode)) 0516 0517 def test_hash(self): 0518 hash(None) 0519 self.assertEqual(hash(1), hash(1L)) 0520 self.assertEqual(hash(1), hash(1.0)) 0521 hash('spam') 0522 if have_unicode: 0523 self.assertEqual(hash('spam'), hash(unicode('spam'))) 0524 hash((0,1,2,3)) 0525 def f(): pass 0526 self.assertRaises(TypeError, hash, []) 0527 self.assertRaises(TypeError, hash, {}) 0528 0529 def test_hex(self): 0530 self.assertEqual(hex(16), '0x10') 0531 self.assertEqual(hex(16L), '0x10L') 0532 self.assertEqual(hex(-16), '-0x10') 0533 self.assertEqual(hex(-16L), '-0x10L') 0534 self.assertRaises(TypeError, hex, {}) 0535 0536 def test_id(self): 0537 id(None) 0538 id(1) 0539 id(1L) 0540 id(1.0) 0541 id('spam') 0542 id((0,1,2,3)) 0543 id([0,1,2,3]) 0544 id({'spam': 1, 'eggs': 2, 'ham': 3}) 0545 0546 # Test input() later, together with raw_input 0547 0548 def test_int(self): 0549 self.assertEqual(int(314), 314) 0550 self.assertEqual(int(3.14), 3) 0551 self.assertEqual(int(314L), 314) 0552 # Check that conversion from float truncates towards zero 0553 self.assertEqual(int(-3.14), -3) 0554 self.assertEqual(int(3.9), 3) 0555 self.assertEqual(int(-3.9), -3) 0556 self.assertEqual(int(3.5), 3) 0557 self.assertEqual(int(-3.5), -3) 0558 # Different base: 0559 self.assertEqual(int("10",16), 16L) 0560 if have_unicode: 0561 self.assertEqual(int(unicode("10"),16), 16L) 0562 # Test conversion from strings and various anomalies 0563 for s, v in L: 0564 for sign in "", "+", "-": 0565 for prefix in "", " ", "\t", " \t\t ": 0566 ss = prefix + sign + s 0567 vv = v 0568 if sign == "-" and v is not ValueError: 0569 vv = -v 0570 try: 0571 self.assertEqual(int(ss), vv) 0572 except v: 0573 pass 0574 0575 s = repr(-1-sys.maxint) 0576 self.assertEqual(int(s)+1, -sys.maxint) 0577 # should return long 0578 int(s[1:]) 0579 0580 # should return long 0581 x = int(1e100) 0582 self.assert_(isinstance(x, long)) 0583 x = int(-1e100) 0584 self.assert_(isinstance(x, long)) 0585 0586 0587 # SF bug 434186: 0x80000000/2 != 0x80000000>>1. 0588 # Worked by accident in Windows release build, but failed in debug build. 0589 # Failed in all Linux builds. 0590 x = -1-sys.maxint 0591 self.assertEqual(x >> 1, x//2) 0592 0593 self.assertRaises(ValueError, int, '123\0') 0594 self.assertRaises(ValueError, int, '53', 40) 0595 0596 x = int('1' * 600) 0597 self.assert_(isinstance(x, long)) 0598 0599 if have_unicode: 0600 x = int(unichr(0x661) * 600) 0601 self.assert_(isinstance(x, long)) 0602 0603 self.assertRaises(TypeError, int, 1, 12) 0604 0605 self.assertEqual(int('0123', 0), 83) 0606 0607 def test_intern(self): 0608 self.assertRaises(TypeError, intern) 0609 s = "never interned before" 0610 self.assert_(intern(s) is s) 0611 s2 = s.swapcase().swapcase() 0612 self.assert_(intern(s2) is s) 0613 0614 # Subclasses of string can't be interned, because they 0615 # provide too much opportunity for insane things to happen. 0616 # We don't want them in the interned dict and if they aren't 0617 # actually interned, we don't want to create the appearance 0618 # that they are by allowing intern() to succeeed. 0619 class S(str): 0620 def __hash__(self): 0621 return 123 0622 0623 self.assertRaises(TypeError, intern, S("abc")) 0624 0625 # It's still safe to pass these strings to routines that 0626 # call intern internally, e.g. PyObject_SetAttr(). 0627 s = S("abc") 0628 setattr(s, s, s) 0629 self.assertEqual(getattr(s, s), s) 0630 0631 def test_iter(self): 0632 self.assertRaises(TypeError, iter) 0633 self.assertRaises(TypeError, iter, 42, 42) 0634 lists = [("1", "2"), ["1", "2"], "12"] 0635 if have_unicode: 0636 lists.append(unicode("12")) 0637 for l in lists: 0638 i = iter(l) 0639 self.assertEqual(i.next(), '1') 0640 self.assertEqual(i.next(), '2') 0641 self.assertRaises(StopIteration, i.next) 0642 0643 def test_isinstance(self): 0644 class C: 0645 pass 0646 class D(C): 0647 pass 0648 class E: 0649 pass 0650 c = C() 0651 d = D() 0652 e = E() 0653 self.assert_(isinstance(c, C)) 0654 self.assert_(isinstance(d, C)) 0655 self.assert_(not isinstance(e, C)) 0656 self.assert_(not isinstance(c, D)) 0657 self.assert_(not isinstance('foo', E)) 0658 self.assertRaises(TypeError, isinstance, E, 'foo') 0659 self.assertRaises(TypeError, isinstance) 0660 0661 def test_issubclass(self): 0662 class C: 0663 pass 0664 class D(C): 0665 pass 0666 class E: 0667 pass 0668 c = C() 0669 d = D() 0670 e = E() 0671 self.assert_(issubclass(D, C)) 0672 self.assert_(issubclass(C, C)) 0673 self.assert_(not issubclass(C, D)) 0674 self.assertRaises(TypeError, issubclass, 'foo', E) 0675 self.assertRaises(TypeError, issubclass, E, 'foo') 0676 self.assertRaises(TypeError, issubclass) 0677 0678 def test_len(self): 0679 self.assertEqual(len('123'), 3) 0680 self.assertEqual(len(()), 0) 0681 self.assertEqual(len((1, 2, 3, 4)), 4) 0682 self.assertEqual(len([1, 2, 3, 4]), 4) 0683 self.assertEqual(len({}), 0) 0684 self.assertEqual(len({'a':1, 'b': 2}), 2) 0685 class BadSeq: 0686 def __len__(self): 0687 raise ValueError 0688 self.assertRaises(ValueError, len, BadSeq()) 0689 0690 def test_list(self): 0691 self.assertEqual(list([]), []) 0692 l0_3 = [0, 1, 2, 3] 0693 l0_3_bis = list(l0_3) 0694 self.assertEqual(l0_3, l0_3_bis) 0695 self.assert_(l0_3 is not l0_3_bis) 0696 self.assertEqual(list(()), []) 0697 self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3]) 0698 self.assertEqual(list(''), []) 0699 self.assertEqual(list('spam'), ['s', 'p', 'a', 'm']) 0700 0701 if sys.maxint == 0x7fffffff: 0702 # This test can currently only work on 32-bit machines. 0703 # XXX If/when PySequence_Length() returns a ssize_t, it should be 0704 # XXX re-enabled. 0705 # Verify clearing of bug #556025. 0706 # This assumes that the max data size (sys.maxint) == max 0707 # address size this also assumes that the address size is at 0708 # least 4 bytes with 8 byte addresses, the bug is not well 0709 # tested 0710 # 0711 # Note: This test is expected to SEGV under Cygwin 1.3.12 or 0712 # earlier due to a newlib bug. See the following mailing list 0713 # thread for the details: 0714 0715 # http://sources.redhat.com/ml/newlib/2002/msg00369.html 0716 self.assertRaises(MemoryError, list, xrange(sys.maxint // 2)) 0717 0718 # This code used to segfault in Py2.4a3 0719 x = [] 0720 x.extend(-y for y in x) 0721 self.assertEqual(x, []) 0722 0723 def test_long(self): 0724 self.assertEqual(long(314), 314L) 0725 self.assertEqual(long(3.14), 3L) 0726 self.assertEqual(long(314L), 314L) 0727 # Check that conversion from float truncates towards zero 0728 self.assertEqual(long(-3.14), -3L) 0729 self.assertEqual(long(3.9), 3L) 0730 self.assertEqual(long(-3.9), -3L) 0731 self.assertEqual(long(3.5), 3L) 0732 self.assertEqual(long(-3.5), -3L) 0733 self.assertEqual(long("-3"), -3L) 0734 if have_unicode: 0735 self.assertEqual(long(unicode("-3")), -3L) 0736 # Different base: 0737 self.assertEqual(long("10",16), 16L) 0738 if have_unicode: 0739 self.assertEqual(long(unicode("10"),16), 16L) 0740 # Check conversions from string (same test set as for int(), and then some) 0741 LL = [ 0742 ('1' + '0'*20, 10L**20), 0743 ('1' + '0'*100, 10L**100) 0744 ] 0745 L2 = L[:] 0746 if have_unicode: 0747 L2 += [ 0748 (unicode('1') + unicode('0')*20, 10L**20), 0749 (unicode('1') + unicode('0')*100, 10L**100), 0750 ] 0751 for s, v in L2 + LL: 0752 for sign in "", "+", "-": 0753 for prefix in "", " ", "\t", " \t\t ": 0754 ss = prefix + sign + s 0755 vv = v 0756 if sign == "-" and v is not ValueError: 0757 vv = -v 0758 try: 0759 self.assertEqual(long(ss), long(vv)) 0760 except v: 0761 pass 0762 0763 self.assertRaises(ValueError, long, '123\0') 0764 self.assertRaises(ValueError, long, '53', 40) 0765 self.assertRaises(TypeError, long, 1, 12) 0766 0767 def test_map(self): 0768 self.assertEqual( 0769 map(None, 'hello world'), 0770 ['h','e','l','l','o',' ','w','o','r','l','d'] 0771 ) 0772 self.assertEqual( 0773 map(None, 'abcd', 'efg'), 0774 [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)] 0775 ) 0776 self.assertEqual( 0777 map(None, range(10)), 0778 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 0779 ) 0780 self.assertEqual( 0781 map(lambda x: x*x, range(1,4)), 0782 [1, 4, 9] 0783 ) 0784 try: 0785 from math import sqrt 0786 except ImportError: 0787 def sqrt(x): 0788 return pow(x, 0.5) 0789 self.assertEqual( 0790 map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]), 0791 [[4.0, 2.0], [9.0, 3.0]] 0792 ) 0793 self.assertEqual( 0794 map(lambda x, y: x+y, [1,3,2], [9,1,4]), 0795 [10, 4, 6] 0796 ) 0797 0798 def plus(*v): 0799 accu = 0 0800 for i in v: accu = accu + i 0801 return accu 0802 self.assertEqual( 0803 map(plus, [1, 3, 7]), 0804 [1, 3, 7] 0805 ) 0806 self.assertEqual( 0807 map(plus, [1, 3, 7], [4, 9, 2]), 0808 [1+4, 3+9, 7+2] 0809 ) 0810 self.assertEqual( 0811 map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]), 0812 [1+4+1, 3+9+1, 7+2+0] 0813 ) 0814 self.assertEqual( 0815 map(None, Squares(10)), 0816 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 0817 ) 0818 self.assertEqual( 0819 map(int, Squares(10)), 0820 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 0821 ) 0822 self.assertEqual( 0823 map(None, Squares(3), Squares(2)), 0824 [(0,0), (1,1), (4,None)] 0825 ) 0826 self.assertEqual( 0827 map(max, Squares(3), Squares(2)), 0828 [0, 1, 4] 0829 ) 0830 self.assertRaises(TypeError, map) 0831 self.assertRaises(TypeError, map, lambda x: x, 42) 0832 self.assertEqual(map(None, [42]), [42]) 0833 class BadSeq: 0834 def __getitem__(self, index): 0835 raise ValueError 0836 self.assertRaises(ValueError, map, lambda x: x, BadSeq()) 0837 0838 def test_max(self): 0839 self.assertEqual(max('123123'), '3') 0840 self.assertEqual(max(1, 2, 3), 3) 0841 self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) 0842 self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) 0843 0844 self.assertEqual(max(1, 2L, 3.0), 3.0) 0845 self.assertEqual(max(1L, 2.0, 3), 3) 0846 self.assertEqual(max(1.0, 2, 3L), 3L) 0847 0848 def test_min(self): 0849 self.assertEqual(min('123123'), '1') 0850 self.assertEqual(min(1, 2, 3), 1) 0851 self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) 0852 self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) 0853 0854 self.assertEqual(min(1, 2L, 3.0), 1) 0855 self.assertEqual(min(1L, 2.0, 3), 1L) 0856 self.assertEqual(min(1.0, 2, 3L), 1.0) 0857 0858 self.assertRaises(TypeError, min) 0859 self.assertRaises(TypeError, min, 42) 0860 self.assertRaises(ValueError, min, ()) 0861 class BadSeq: 0862 def __getitem__(self, index): 0863 raise ValueError 0864 self.assertRaises(ValueError, min, BadSeq()) 0865 class BadNumber: 0866 def __cmp__(self, other): 0867 raise ValueError 0868 self.assertRaises(ValueError, min, (42, BadNumber())) 0869 0870 def test_oct(self): 0871 self.assertEqual(oct(100), '0144') 0872 self.assertEqual(oct(100L), '0144L') 0873 self.assertEqual(oct(-100), '-0144') 0874 self.assertEqual(oct(-100L), '-0144L') 0875 self.assertRaises(TypeError, oct, ()) 0876 0877 def write_testfile(self): 0878 # NB the first 4 lines are also used to test input and raw_input, below 0879 fp = open(TESTFN, 'w') 0880 try: 0881 fp.write('1+1\n') 0882 fp.write('1+1\n') 0883 fp.write('The quick brown fox jumps over the lazy dog') 0884 fp.write('.\n') 0885 fp.write('Dear John\n') 0886 fp.write('XXX'*100) 0887 fp.write('YYY'*100) 0888 finally: 0889 fp.close() 0890 0891 def test_open(self): 0892 self.write_testfile() 0893 fp = open(TESTFN, 'r') 0894 try: 0895 self.assertEqual(fp.readline(4), '1+1\n') 0896 self.assertEqual(fp.readline(4), '1+1\n') 0897 self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') 0898 self.assertEqual(fp.readline(4), 'Dear') 0899 self.assertEqual(fp.readline(100), ' John\n') 0900 self.assertEqual(fp.read(300), 'XXX'*100) 0901 self.assertEqual(fp.read(1000), 'YYY'*100) 0902 finally: 0903 fp.close() 0904 unlink(TESTFN) 0905 0906 def test_ord(self): 0907 self.assertEqual(ord(' '), 32) 0908 self.assertEqual(ord('A'), 65) 0909 self.assertEqual(ord('a'), 97) 0910 if have_unicode: 0911 self.assertEqual(ord(unichr(sys.maxunicode)), sys.maxunicode) 0912 self.assertRaises(TypeError, ord, 42) 0913 self.assertRaises(TypeError, ord, unicode("12")) 0914 0915 def test_pow(self): 0916 self.assertEqual(pow(0,0), 1) 0917 self.assertEqual(pow(0,1), 0) 0918 self.assertEqual(pow(1,0), 1) 0919 self.assertEqual(pow(1,1), 1) 0920 0921 self.assertEqual(pow(2,0), 1) 0922 self.assertEqual(pow(2,10), 1024) 0923 self.assertEqual(pow(2,20), 1024*1024) 0924 self.assertEqual(pow(2,30), 1024*1024*1024) 0925 0926 self.assertEqual(pow(-2,0), 1) 0927 self.assertEqual(pow(-2,1), -2) 0928 self.assertEqual(pow(-2,2), 4) 0929 self.assertEqual(pow(-2,3), -8) 0930 0931 self.assertEqual(pow(0L,0), 1) 0932 self.assertEqual(pow(0L,1), 0) 0933 self.assertEqual(pow(1L,0), 1) 0934 self.assertEqual(pow(1L,1), 1) 0935 0936 self.assertEqual(pow(2L,0), 1) 0937 self.assertEqual(pow(2L,10), 1024) 0938 self.assertEqual(pow(2L,20), 1024*1024) 0939 self.assertEqual(pow(2L,30), 1024*1024*1024) 0940 0941 self.assertEqual(pow(-2L,0), 1) 0942 self.assertEqual(pow(-2L,1), -2) 0943 self.assertEqual(pow(-2L,2), 4) 0944 self.assertEqual(pow(-2L,3), -8) 0945 0946 self.assertAlmostEqual(pow(0.,0), 1.) 0947 self.assertAlmostEqual(pow(0.,1), 0.) 0948 self.assertAlmostEqual(pow(1.,0), 1.) 0949 self.assertAlmostEqual(pow(1.,1), 1.) 0950 0951 self.assertAlmostEqual(pow(2.,0), 1.) 0952 self.assertAlmostEqual(pow(2.,10), 1024.) 0953 self.assertAlmostEqual(pow(2.,20), 1024.*1024.) 0954 self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) 0955 0956 self.assertAlmostEqual(pow(-2.,0), 1.) 0957 self.assertAlmostEqual(pow(-2.,1), -2.) 0958 self.assertAlmostEqual(pow(-2.,2), 4.) 0959 self.assertAlmostEqual(pow(-2.,3), -8.) 0960 0961 for x in 2, 2L, 2.0: 0962 for y in 10, 10L, 10.0: 0963 for z in 1000, 1000L, 1000.0: 0964 if isinstance(x, float) or \ 0965 isinstance(y, float) or \ 0966 isinstance(z, float): 0967 self.assertRaises(TypeError, pow, x, y, z) 0968 else: 0969 self.assertAlmostEqual(pow(x, y, z), 24.0) 0970 0971 self.assertRaises(TypeError, pow, -1, -2, 3) 0972 self.assertRaises(ValueError, pow, 1, 2, 0) 0973 self.assertRaises(TypeError, pow, -1L, -2L, 3L) 0974 self.assertRaises(ValueError, pow, 1L, 2L, 0L) 0975 self.assertRaises(ValueError, pow, -342.43, 0.234) 0976 0977 self.assertRaises(TypeError, pow) 0978 0979 def test_range(self): 0980 self.assertEqual(range(3), [0, 1, 2]) 0981 self.assertEqual(range(1, 5), [1, 2, 3, 4]) 0982 self.assertEqual(range(0), []) 0983 self.assertEqual(range(-3), []) 0984 self.assertEqual(range(1, 10, 3), [1, 4, 7]) 0985 self.assertEqual(range(5, -5, -3), [5, 2, -1, -4]) 0986 0987 # Now test range() with longs 0988 self.assertEqual(range(-2**100), []) 0989 self.assertEqual(range(0, -2**100), []) 0990 self.assertEqual(range(0, 2**100, -1), []) 0991 self.assertEqual(range(0, 2**100, -1), []) 0992 0993 a = long(10 * sys.maxint) 0994 b = long(100 * sys.maxint) 0995 c = long(50 * sys.maxint) 0996 0997 self.assertEqual(range(a, a+2), [a, a+1]) 0998 self.assertEqual(range(a+2, a, -1L), [a+2, a+1]) 0999 self.assertEqual(range(a+4, a, -2), [a+4, a+2]) 1000 1001 seq = range(a, b, c) 1002 self.assert_(a in seq) 1003 self.assert_(b not in seq) 1004 self.assertEqual(len(seq), 2) 1005 1006 seq = range(b, a, -c) 1007 self.assert_(b in seq) 1008 self.assert_(a not in seq) 1009 self.assertEqual(len(seq), 2) 1010 1011 seq = range(-a, -b, -c) 1012 self.assert_(-a in seq) 1013 self.assert_(-b not in seq) 1014 self.assertEqual(len(seq), 2) 1015 1016 self.assertRaises(TypeError, range) 1017 self.assertRaises(TypeError, range, 1, 2, 3, 4) 1018 self.assertRaises(ValueError, range, 1, 2, 0) 1019 1020 # Reject floats when it would require PyLongs to represent. 1021 # (smaller floats still accepted, but deprecated) 1022 self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) 1023 1024 self.assertRaises(TypeError, range, 0, "spam") 1025 self.assertRaises(TypeError, range, 0, 42, "spam") 1026 1027 self.assertRaises(OverflowError, range, -sys.maxint, sys.maxint) 1028 self.assertRaises(OverflowError, range, 0, 2*sys.maxint) 1029 1030 def test_input_and_raw_input(self): 1031 self.write_testfile() 1032 fp = open(TESTFN, 'r') 1033 savestdin = sys.stdin 1034 savestdout = sys.stdout # Eats the echo 1035 try: 1036 sys.stdin = fp 1037 sys.stdout = BitBucket() 1038 self.assertEqual(input(), 2) 1039 self.assertEqual(input('testing\n'), 2) 1040 self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.') 1041 self.assertEqual(raw_input('testing\n'), 'Dear John') 1042 sys.stdin = cStringIO.StringIO("NULL\0") 1043 self.assertRaises(TypeError, input, 42, 42) 1044 sys.stdin = cStringIO.StringIO(" 'whitespace'") 1045 self.assertEqual(input(), 'whitespace') 1046 sys.stdin = cStringIO.StringIO() 1047 self.assertRaises(EOFError, input) 1048 1049 # SF 876178: make sure input() respect future options. 1050 sys.stdin = cStringIO.StringIO('1/2') 1051 sys.stdout = cStringIO.StringIO() 1052 exec compile('print input()', 'test_builtin_tmp', 'exec') 1053 sys.stdin.seek(0, 0) 1054 exec compile('from __future__ import division;print input()', 1055 'test_builtin_tmp', 'exec') 1056 sys.stdin.seek(0, 0) 1057 exec compile('print input()', 'test_builtin_tmp', 'exec') 1058 self.assertEqual(sys.stdout.getvalue().splitlines(), 1059 ['0', '0.5', '0']) 1060 1061 del sys.stdout 1062 self.assertRaises(RuntimeError, input, 'prompt') 1063 del sys.stdin 1064 self.assertRaises(RuntimeError, input, 'prompt') 1065 finally: 1066 sys.stdin = savestdin 1067 sys.stdout = savestdout 1068 fp.close() 1069 unlink(TESTFN) 1070 1071 def test_reduce(self): 1072 self.assertEqual(reduce(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc') 1073 self.assertEqual( 1074 reduce(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []), 1075 ['a','c','d','w'] 1076 ) 1077 self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040) 1078 self.assertEqual( 1079 reduce(lambda x, y: x*y, range(2,21), 1L), 1080 2432902008176640000L 1081 ) 1082 self.assertEqual(reduce(lambda x, y: x+y, Squares(10)), 285) 1083 self.assertEqual(reduce(lambda x, y: x+y, Squares(10), 0), 285) 1084 self.assertEqual(reduce(lambda x, y: x+y, Squares(0), 0), 0) 1085 self.assertRaises(TypeError, reduce) 1086 self.assertRaises(TypeError, reduce, 42, 42) 1087 self.assertRaises(TypeError, reduce, 42, 42, 42) 1088 self.assertEqual(reduce(42, "1"), "1") # func is never called with one item 1089 self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item 1090 self.assertRaises(TypeError, reduce, 42, (42, 42)) 1091 1092 class BadSeq: 1093 def __getitem__(self, index): 1094 raise ValueError 1095 self.assertRaises(ValueError, reduce, 42, BadSeq()) 1096 1097 def test_reload(self): 1098 import marshal 1099 reload(marshal) 1100 import string 1101 reload(string) 1102 ## import sys 1103 ## self.assertRaises(ImportError, reload, sys) 1104 1105 def test_repr(self): 1106 self.assertEqual(repr(''), '\'\'') 1107 self.assertEqual(repr(0), '0') 1108 self.assertEqual(repr(0L), '0L') 1109 self.assertEqual(repr(()), '()') 1110 self.assertEqual(repr([]), '[]') 1111 self.assertEqual(repr({}), '{}') 1112 a = [] 1113 a.append(a) 1114 self.assertEqual(repr(a), '[[...]]') 1115 a = {} 1116 a[0] = a 1117 self.assertEqual(repr(a), '{0: {...}}') 1118 1119 def test_round(self): 1120 self.assertEqual(round(0.0), 0.0) 1121 self.assertEqual(round(1.0), 1.0) 1122 self.assertEqual(round(10.0), 10.0) 1123 self.assertEqual(round(1000000000.0), 1000000000.0) 1124 self.assertEqual(round(1e20), 1e20) 1125 1126 self.assertEqual(round(-1.0), -1.0) 1127 self.assertEqual(round(-10.0), -10.0) 1128 self.assertEqual(round(-1000000000.0), -1000000000.0) 1129 self.assertEqual(round(-1e20), -1e20) 1130 1131 self.assertEqual(round(0.1), 0.0) 1132 self.assertEqual(round(1.1), 1.0) 1133 self.assertEqual(round(10.1), 10.0) 1134 self.assertEqual(round(1000000000.1), 1000000000.0) 1135 1136 self.assertEqual(round(-1.1), -1.0) 1137 self.assertEqual(round(-10.1), -10.0) 1138 self.assertEqual(round(-1000000000.1), -1000000000.0) 1139 1140 self.assertEqual(round(0.9), 1.0) 1141 self.assertEqual(round(9.9), 10.0) 1142 self.assertEqual(round(999999999.9), 1000000000.0) 1143 1144 self.assertEqual(round(-0.9), -1.0) 1145 self.assertEqual(round(-9.9), -10.0) 1146 self.assertEqual(round(-999999999.9), -1000000000.0) 1147 1148 self.assertEqual(round(-8.0, -1), -10.0) 1149 1150 self.assertRaises(TypeError, round) 1151 1152 def test_setattr(self): 1153 setattr(sys, 'spam', 1) 1154 self.assertEqual(sys.spam, 1) 1155 self.assertRaises(TypeError, setattr, sys, 1, 'spam') 1156 self.assertRaises(TypeError, setattr) 1157 1158 def test_str(self): 1159 self.assertEqual(str(''), '') 1160 self.assertEqual(str(0), '0') 1161 self.assertEqual(str(0L), '0') 1162 self.assertEqual(str(()), '()') 1163 self.assertEqual(str([]), '[]') 1164 self.assertEqual(str({}), '{}') 1165 a = [] 1166 a.append(a) 1167 self.assertEqual(str(a), '[[...]]') 1168 a = {} 1169 a[0] = a 1170 self.assertEqual(str(a), '{0: {...}}') 1171 1172 def test_sum(self): 1173 self.assertEqual(sum([]), 0) 1174 self.assertEqual(sum(range(2,8)), 27) 1175 self.assertEqual(sum(iter(range(2,8))), 27) 1176 self.assertEqual(sum(Squares(10)), 285) 1177 self.assertEqual(sum(iter(Squares(10))), 285) 1178 self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) 1179 1180 self.assertRaises(TypeError, sum) 1181 self.assertRaises(TypeError, sum, 42) 1182 self.assertRaises(TypeError, sum, ['a', 'b', 'c']) 1183 self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '') 1184 self.assertRaises(TypeError, sum, [[1], [2], [3]]) 1185 self.assertRaises(TypeError, sum, [{2:3}]) 1186 self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3}) 1187 1188 class BadSeq: 1189 def __getitem__(self, index): 1190 raise ValueError 1191 self.assertRaises(ValueError, sum, BadSeq()) 1192 1193 def test_tuple(self): 1194 self.assertEqual(tuple(()), ()) 1195 t0_3 = (0, 1, 2, 3) 1196 t0_3_bis = tuple(t0_3) 1197 self.assert_(t0_3 is t0_3_bis) 1198 self.assertEqual(tuple([]), ()) 1199 self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3)) 1200 self.assertEqual(tuple(''), ()) 1201 self.assertEqual(tuple('spam'), ('s', 'p', 'a', 'm')) 1202 1203 def test_type(self): 1204 self.assertEqual(type(''), type('123')) 1205 self.assertNotEqual(type(''), type(())) 1206 1207 def test_unichr(self): 1208 if have_unicode: 1209 self.assertEqual(unichr(32), unicode(' ')) 1210 self.assertEqual(unichr(65), unicode('A')) 1211 self.assertEqual(unichr(97), unicode('a')) 1212 self.assertEqual( 1213 unichr(sys.maxunicode), 1214 unicode('\\U%08x' % (sys.maxunicode), 'unicode-escape') 1215 ) 1216 self.assertRaises(ValueError, unichr, sys.maxunicode+1) 1217 self.assertRaises(TypeError, unichr) 1218 1219 def get_vars_f0(): 1220 return vars() 1221 # we don't want self in vars(), so use staticmethod 1222 get_vars_f0 = staticmethod(get_vars_f0) 1223 1224 def get_vars_f2(): 1225 BuiltinTest.get_vars_f0() 1226 a = 1 1227 b = 2 1228 return vars() 1229 get_vars_f2 = staticmethod(get_vars_f2) 1230 1231 def test_vars(self): 1232 self.assertEqual(set(vars()), set(dir())) 1233 import sys 1234 self.assertEqual(set(vars(sys)), set(dir(sys))) 1235 self.assertEqual(self.get_vars_f0(), {}) 1236 self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) 1237 self.assertRaises(TypeError, vars, 42, 42) 1238 self.assertRaises(TypeError, vars, 42) 1239 1240 def test_zip(self): 1241 a = (1, 2, 3) 1242 b = (4, 5, 6) 1243 t = [(1, 4), (2, 5), (3, 6)] 1244 self.assertEqual(zip(a, b), t) 1245 b = [4, 5, 6] 1246 self.assertEqual(zip(a, b), t) 1247 b = (4, 5, 6, 7) 1248 self.assertEqual(zip(a, b), t) 1249 class I: 1250 def __getitem__(self, i): 1251 if i < 0 or i > 2: raise IndexError 1252 return i + 4 1253 self.assertEqual(zip(a, I()), t) 1254 self.assertEqual(zip(), []) 1255 self.assertEqual(zip(*[]), []) 1256 self.assertRaises(TypeError, zip, None) 1257 class G: 1258 pass 1259 self.assertRaises(TypeError, zip, a, G()) 1260 1261 # Make sure zip doesn't try to allocate a billion elements for the 1262 # result list when one of its arguments doesn't say how long it is. 1263 # A MemoryError is the most likely failure mode. 1264 class SequenceWithoutALength: 1265 def __getitem__(self, i): 1266 if i == 5: 1267 raise IndexError 1268 else: 1269 return i 1270 self.assertEqual( 1271 zip(SequenceWithoutALength(), xrange(2**30)), 1272 list(enumerate(range(5))) 1273 ) 1274 1275 class BadSeq: 1276 def __getitem__(self, i): 1277 if i == 5: 1278 raise ValueError 1279 else: 1280 return i 1281 self.assertRaises(ValueError, zip, BadSeq(), BadSeq()) 1282 1283 class TestSorted(unittest.TestCase): 1284 1285 def test_basic(self): 1286 data = range(100) 1287 copy = data[:] 1288 random.shuffle(copy) 1289 self.assertEqual(data, sorted(copy)) 1290 self.assertNotEqual(data, copy) 1291 1292 data.reverse() 1293 random.shuffle(copy) 1294 self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x))) 1295 self.assertNotEqual(data, copy) 1296 random.shuffle(copy) 1297 self.assertEqual(data, sorted(copy, key=lambda x: -x)) 1298 self.assertNotEqual(data, copy) 1299 random.shuffle(copy) 1300 self.assertEqual(data, sorted(copy, reverse=1)) 1301 self.assertNotEqual(data, copy) 1302 1303 def test_inputtypes(self): 1304 s = 'abracadabra' 1305 for T in [unicode, list, tuple]: 1306 self.assertEqual(sorted(s), sorted(T(s))) 1307 1308 s = ''.join(dict.fromkeys(s).keys()) # unique letters only 1309 for T in [unicode, set, frozenset, list, tuple, dict.fromkeys]: 1310 self.assertEqual(sorted(s), sorted(T(s))) 1311 1312 def test_baddecorator(self): 1313 data = 'The quick Brown fox Jumped over The lazy Dog'.split() 1314 self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) 1315 1316 def test_main(): 1317 test.test_support.run_unittest(BuiltinTest, TestSorted) 1318 1319 if __name__ == "__main__": 1320 test_main() 1321
Generated by PyXR 0.9.4