test_types.py 25.1 KB
Newer Older
1 2
# Python test set -- part 6, built-in types

3
from test.test_support import *
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

print '6. Built-in types'

print '6.1 Truth value testing'
if None: raise TestFailed, 'None is true instead of false'
if 0: raise TestFailed, '0 is true instead of false'
if 0L: raise TestFailed, '0L is true instead of false'
if 0.0: raise TestFailed, '0.0 is true instead of false'
if '': raise TestFailed, '\'\' is true instead of false'
if (): raise TestFailed, '() is true instead of false'
if []: raise TestFailed, '[] is true instead of false'
if {}: raise TestFailed, '{} is true instead of false'
if not 1: raise TestFailed, '1 is false instead of true'
if not 1L: raise TestFailed, '1L is false instead of true'
if not 1.0: raise TestFailed, '1.0 is false instead of true'
if not 'x': raise TestFailed, '\'x\' is false instead of true'
if not (1, 1): raise TestFailed, '(1, 1) is false instead of true'
if not [1]: raise TestFailed, '[1] is false instead of true'
if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true'
def f(): pass
24
class C: pass
25 26 27 28 29 30 31 32 33 34 35 36 37 38
import sys
x = C()
if not f: raise TestFailed, 'f is false instead of true'
if not C: raise TestFailed, 'C is false instead of true'
if not sys: raise TestFailed, 'sys is false instead of true'
if not x: raise TestFailed, 'x is false instead of true'

print '6.2 Boolean operations'
if 0 or 0: raise TestFailed, '0 or 0 is true instead of false'
if 1 and 1: pass
else: raise TestFailed, '1 and 1 is false instead of false'
if not 1: raise TestFailed, 'not 1 is true instead of false'

print '6.3 Comparisons'
39
if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
40
else: raise TestFailed, 'int comparisons failed'
41
if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass
42
else: raise TestFailed, 'long int comparisons failed'
43
if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass
44 45 46 47 48 49 50 51
else: raise TestFailed, 'float comparisons failed'
if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass
else: raise TestFailed, 'string comparisons failed'
if 0 in [0] and 0 not in [1]: pass
else: raise TestFailed, 'membership test failed'
if None is None and [] is not []: pass
else: raise TestFailed, 'identity test failed'

52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
try: float('')
except ValueError: pass
else: raise TestFailed, "float('') didn't raise ValueError"

try: float('5\0')
except ValueError: pass
else: raise TestFailed, "float('5\0') didn't raise ValueError"

try: 5.0 / 0.0
except ZeroDivisionError: pass
else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError"

try: 5.0 // 0.0
except ZeroDivisionError: pass
else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError"

try: 5.0 % 0.0
except ZeroDivisionError: pass
else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError"

try: 5 / 0L
except ZeroDivisionError: pass
else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError"

try: 5 // 0L
except ZeroDivisionError: pass
else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError"

try: 5 % 0L
except ZeroDivisionError: pass
else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError"

84
print '6.4 Numeric types (mostly conversions)'
85 86 87
if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons'
if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons'
if -1 != -1L or -1 != -1.0 or -1L != -1.0:
88
    raise TestFailed, 'int/long/float value not equal'
89 90 91 92
# calling built-in types without argument must return 0
if int() != 0: raise TestFailed, 'int() does not return 0'
if long() != 0L: raise TestFailed, 'long() does not return 0L'
if float() != 0.0: raise TestFailed, 'float() does not return 0.0'
93 94 95 96 97 98
if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
else: raise TestFailed, 'int() does not round properly'
if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass
else: raise TestFailed, 'long() does not round properly'
if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
else: raise TestFailed, 'float() does not work properly'
99
print '6.4.1 32-bit integers'
100 101 102 103
if 12 + 24 != 36: raise TestFailed, 'int op'
if 12 + (-24) != -12: raise TestFailed, 'int op'
if (-12) + 24 != 12: raise TestFailed, 'int op'
if (-12) + (-24) != -36: raise TestFailed, 'int op'
104 105
if not 12 < 24: raise TestFailed, 'int op'
if not -24 < -12: raise TestFailed, 'int op'
106 107 108
# Test for a particular bug in integer multiply
xsize, ysize, zsize = 238, 356, 4
if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912):
109
    raise TestFailed, 'int mul commutativity'
110 111 112
# And another.
m = -sys.maxint - 1
for divisor in 1, 2, 4, 8, 16, 32:
113
    j = m // divisor
114 115 116 117 118 119 120 121
    prod = divisor * j
    if prod != m:
        raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m)
    if type(prod) is not int:
        raise TestFailed, ("expected type(prod) to be int, not %r" %
                           type(prod))
# Check for expected * overflow to long.
for divisor in 1, 2, 4, 8, 16, 32:
122
    j = m // divisor - 1
123 124 125 126 127 128 129
    prod = divisor * j
    if type(prod) is not long:
        raise TestFailed, ("expected type(%r) to be long, not %r" %
                           (prod, type(prod)))
# Check for expected * overflow to long.
m = sys.maxint
for divisor in 1, 2, 4, 8, 16, 32:
130
    j = m // divisor + 1
131 132 133 134 135
    prod = divisor * j
    if type(prod) is not long:
        raise TestFailed, ("expected type(%r) to be long, not %r" %
                           (prod, type(prod)))

136
print '6.4.2 Long integers'
137 138 139 140
if 12L + 24L != 36L: raise TestFailed, 'long op'
if 12L + (-24L) != -12L: raise TestFailed, 'long op'
if (-12L) + 24L != 12L: raise TestFailed, 'long op'
if (-12L) + (-24L) != -36L: raise TestFailed, 'long op'
141 142
if not 12L < 24L: raise TestFailed, 'long op'
if not -24L < -12L: raise TestFailed, 'long op'
143 144
x = sys.maxint
if int(long(x)) != x: raise TestFailed, 'long op'
145 146 147
try: y = int(long(x)+1L)
except OverflowError: raise TestFailed, 'long op'
if not isinstance(y, long): raise TestFailed, 'long op'
148 149 150 151
x = -x
if int(long(x)) != x: raise TestFailed, 'long op'
x = x-1
if int(long(x)) != x: raise TestFailed, 'long op'
152 153 154
try: y = int(long(x)-1L)
except OverflowError: raise TestFailed, 'long op'
if not isinstance(y, long): raise TestFailed, 'long op'
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

try: 5 << -5
except ValueError: pass
else: raise TestFailed, 'int negative shift <<'

try: 5L << -5L
except ValueError: pass
else: raise TestFailed, 'long negative shift <<'

try: 5 >> -5
except ValueError: pass
else: raise TestFailed, 'int negative shift >>'

try: 5L >> -5L
except ValueError: pass
else: raise TestFailed, 'long negative shift >>'

172
print '6.4.3 Floating point numbers'
173 174 175 176
if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op'
if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op'
if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op'
if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op'
177 178
if not 12.0 < 24.0: raise TestFailed, 'float op'
if not -24.0 < -12.0: raise TestFailed, 'float op'
179 180 181 182

print '6.5 Sequence types'

print '6.5.1 Strings'
183 184 185 186 187 188 189
if len('') != 0: raise TestFailed, 'len(\'\')'
if len('a') != 1: raise TestFailed, 'len(\'a\')'
if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')'
if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation'
if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3'
if 0*'abcde' != '': raise TestFailed, 'string repetition 0*'
if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string'
190 191
if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass
else: raise TestFailed, 'in/not in string'
192 193
x = 'x'*103
if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug'
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
#extended slices for strings
a = '0123456789'
vereq(a[::], a)
vereq(a[::2], '02468')
vereq(a[1::2], '13579')
vereq(a[::-1],'9876543210')
vereq(a[::-2], '97531')
vereq(a[3::-2], '31')
vereq(a[-100:100:], a)
vereq(a[100:-100:-1], a[::-1])
vereq(a[-100L:100L:2L], '02468')

if have_unicode:
    a = unicode('0123456789', 'ascii')
    vereq(a[::], a)
    vereq(a[::2], unicode('02468', 'ascii'))
    vereq(a[1::2], unicode('13579', 'ascii'))
    vereq(a[::-1], unicode('9876543210', 'ascii'))
    vereq(a[::-2], unicode('97531', 'ascii'))
    vereq(a[3::-2], unicode('31', 'ascii'))
    vereq(a[-100:100:], a)
    vereq(a[100:-100:-1], a[::-1])
    vereq(a[-100L:100L:2L], unicode('02468', 'ascii'))
Tim Peters's avatar
Tim Peters committed
218

219

220
print '6.5.2 Tuples'
221 222
# calling built-in types without argument must return empty
if tuple() != (): raise TestFailed,'tuple() does not return ()'
223 224 225 226 227 228 229
if len(()) != 0: raise TestFailed, 'len(())'
if len((1,)) != 1: raise TestFailed, 'len((1,))'
if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))'
if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation'
if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3'
if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*'
if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple'
230 231
if 0 in (0,1,2) and 1 in (0,1,2) and 2 in (0,1,2) and 3 not in (0,1,2): pass
else: raise TestFailed, 'in/not in tuple'
232 233 234 235 236 237 238 239
try: ()[0]
except IndexError: pass
else: raise TestFailed, "tuple index error didn't raise IndexError"
x = ()
x += ()
if x != (): raise TestFailed, 'tuple inplace add from () to () failed'
x += (1,)
if x != (1,): raise TestFailed, 'tuple resize from () failed'
240

241 242 243 244 245 246 247 248 249 250 251 252
# extended slicing - subscript only for tuples
a = (0,1,2,3,4)
vereq(a[::], a)
vereq(a[::2], (0,2,4))
vereq(a[1::2], (1,3))
vereq(a[::-1], (4,3,2,1,0))
vereq(a[::-2], (4,2,0))
vereq(a[3::-2], (3,1))
vereq(a[-100:100:], a)
vereq(a[100:-100:-1], a[::-1])
vereq(a[-100L:100L:2L], (0,2,4))

253 254 255 256 257
# Check that a specific bug in _PyTuple_Resize() is squashed.
def f():
    for i in range(1000):
        yield i
vereq(list(tuple(f())), range(1000))
258

259
# Verify that __getitem__ overrides are not recognized by __iter__
260
class T(tuple):
Tim Peters's avatar
Tim Peters committed
261 262
    def __getitem__(self, key):
        return str(key) + '!!!'
263
vereq(iter(T((1,2))).next(), 1)
264

265
print '6.5.3 Lists'
266 267
# calling built-in types without argument must return empty
if list() != []: raise TestFailed,'list() does not return []'
268 269 270 271 272 273 274 275 276
if len([]) != 0: raise TestFailed, 'len([])'
if len([1,]) != 1: raise TestFailed, 'len([1,])'
if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])'
if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation'
if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3'
if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L'
if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*'
if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*'
if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list'
277 278
if 0 in [0,1,2] and 1 in [0,1,2] and 2 in [0,1,2] and 3 not in [0,1,2]: pass
else: raise TestFailed, 'in/not in list'
279 280 281
a = [1, 2, 3, 4, 5]
a[:-1] = a
if a != [1, 2, 3, 4, 5, 5]:
282
    raise TestFailed, "list self-slice-assign (head)"
283 284 285
a = [1, 2, 3, 4, 5]
a[1:] = a
if a != [1, 1, 2, 3, 4, 5]:
286
    raise TestFailed, "list self-slice-assign (tail)"
287 288 289
a = [1, 2, 3, 4, 5]
a[1:-1] = a
if a != [1, 1, 2, 3, 4, 5, 5]:
290
    raise TestFailed, "list self-slice-assign (center)"
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
try: [][0]
except IndexError: pass
else: raise TestFailed, "list index error didn't raise IndexError"
try: [][0] = 5
except IndexError: pass
else: raise TestFailed, "list assignment index error didn't raise IndexError"
try: [].pop()
except IndexError: pass
else: raise TestFailed, "empty list.pop() didn't raise IndexError"
try: [1].pop(5)
except IndexError: pass
else: raise TestFailed, "[1].pop(5) didn't raise IndexError"
try: [][0:1] = 5
except TypeError: pass
else: raise TestFailed, "bad list slice assignment didn't raise TypeError"
try: [].extend(None)
except TypeError: pass
else: raise TestFailed, "list.extend(None) didn't raise TypeError"
a = [1, 2, 3, 4]
a *= 0
if a != []:
    raise TestFailed, "list inplace repeat"
313

314 315 316 317
a = []
a[:] = tuple(range(10))
if a != range(10):
    raise TestFailed, "assigning tuple to slice"
318 319 320

print '6.5.3a Additional list operations'
a = [0,1,2,3,4]
321 322 323
a[0L] = 1
a[1L] = 2
a[2L] = 3
324
if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]'
325 326 327
a[0] = 5
a[1] = 6
a[2] = 7
328
if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]'
329 330
a[-2L] = 88
a[-1L] = 99
331
if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]'
332 333
a[-2] = 8
a[-1] = 9
334
if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]'
335 336 337
a[:2] = [0,4]
a[-3:] = []
a[1:1] = [1,2,3]
338
if a != [0,1,2,3,4]: raise TestFailed, 'list slice assignment'
339
a[ 1L : 4L] = [7,8,9]
340
if a != [0,7,8,9,4]: raise TestFailed, 'list slice assignment using long ints'
341
del a[1:4]
342
if a != [0,4]: raise TestFailed, 'list slice deletion'
343
del a[0]
344
if a != [4]: raise TestFailed, 'list item deletion [0]'
345
del a[-1]
346
if a != []: raise TestFailed, 'list item deletion [-1]'
347 348
a=range(0,5)
del a[1L:4L]
349
if a != [0,4]: raise TestFailed, 'list slice deletion'
350
del a[0L]
351
if a != [4]: raise TestFailed, 'list item deletion [0]'
352
del a[-1L]
353
if a != []: raise TestFailed, 'list item deletion [-1]'
354 355 356
a.append(0)
a.append(1)
a.append(2)
357
if a != [0,1,2]: raise TestFailed, 'list append'
358 359 360
a.insert(0, -2)
a.insert(1, -1)
a.insert(2,0)
361
if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert'
362 363 364 365 366
b = a[:]
b.insert(-2, "foo")
b.insert(-200, "left")
b.insert(200, "right")
if b != ["left",-2,-1,0,0,"foo",1,2,"right"]: raise TestFailed, 'list insert2'
367
# a = [-2,-1,0,0,1,2]
368 369
if a.count(0) != 2: raise TestFailed, ' list count'
if a.index(0) != 2: raise TestFailed, 'list index'
370
if a.index(0,2) != 2: raise TestFailed, 'list index, start argument'
371 372
if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument'
if a.index(-2,-10) != 0: raise TestFailed, 'list index, very -start argument'
373
if a.index(0,3) != 3: raise TestFailed, 'list index, start argument'
374
if a.index(0,-3) != 3: raise TestFailed, 'list index, -start argument'
375
if a.index(0,3,4) != 3: raise TestFailed, 'list index, stop argument'
376
if a.index(0,-3,-2) != 3: raise TestFailed, 'list index, -stop argument'
377 378 379 380 381 382 383 384 385
if a.index(0,-4*sys.maxint,4*sys.maxint) != 2:
    raise TestFailed, 'list index, -maxint, maxint argument'
try:
    a.index(0, 4*sys.maxint,-4*sys.maxint)
except ValueError:
    pass
else:
    raise TestFailed, 'list index, maxint,-maxint argument'

386 387 388 389 390
try:
    a.index(2,0,-10)
except ValueError:
    pass
else:
391
    raise TestFailed, 'list index, very -stop argument'
392
a.remove(0)
393 394 395 396 397 398
try:
    a.index(2,0,4)
except ValueError:
    pass
else:
    raise TestFailed, 'list index, stop argument.'
399
if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove'
400
a.reverse()
401
if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse'
402
a.sort()
403
if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort'
404 405
def revcmp(a, b): return cmp(b, a)
a.sort(revcmp)
406
if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func'
407 408 409 410 411
# The following dumps core in unpatched Python 1.5:
def myComparison(x,y):
    return cmp(x%3, y%7)
z = range(12)
z.sort(myComparison)
412

413 414 415 416 417
try: z.sort(2)
except TypeError: pass
else: raise TestFailed, 'list sort compare function is not callable'

def selfmodifyingComparison(x,y):
418
    z.append(1)
419 420
    return cmp(x, y)
try: z.sort(selfmodifyingComparison)
421
except ValueError: pass
422 423 424 425 426 427
else: raise TestFailed, 'modifying list during sort'

try: z.sort(lambda x, y: 's')
except TypeError: pass
else: raise TestFailed, 'list sort compare function does not return int'

428 429
# Test extreme cases with long ints
a = [0,1,2,3,4]
430 431 432 433
if a[ -pow(2,128L): 3 ] != [0,1,2]:
    raise TestFailed, "list slicing with too-small long integer"
if a[ 3: pow(2,145L) ] != [3,4]:
    raise TestFailed, "list slicing with too-large long integer"
434

435 436 437 438 439 440 441 442 443 444 445 446 447 448

# extended slicing

#  subscript
a = [0,1,2,3,4]
vereq(a[::], a)
vereq(a[::2], [0,2,4])
vereq(a[1::2], [1,3])
vereq(a[::-1], [4,3,2,1,0])
vereq(a[::-2], [4,2,0])
vereq(a[3::-2], [3,1])
vereq(a[-100:100:], a)
vereq(a[100:-100:-1], a[::-1])
vereq(a[-100L:100L:2L], [0,2,4])
449 450
vereq(a[1000:2000:2], [])
vereq(a[-1000:-2000:-2], [])
451 452 453 454 455 456 457 458 459
#  deletion
del a[::2]
vereq(a, [1,3])
a = range(5)
del a[1::2]
vereq(a, [0,2,4])
a = range(5)
del a[1::-2]
vereq(a, [0,2,3,4])
Michael W. Hudson's avatar
Michael W. Hudson committed
460 461 462
a = range(10)
del a[::1000]
vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
463 464 465 466 467 468 469 470 471 472
#  assignment
a = range(10)
a[::2] = [-1]*5
vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])
a = range(10)
a[::-4] = [10]*3
vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])
a = range(4)
a[::-1] = a
vereq(a, [3, 2, 1, 0])
473 474 475 476 477 478 479 480
a = range(10)
b = a[:]
c = a[:]
a[2:3] = ["two", "elements"]
b[slice(2,3)] = ["two", "elements"]
c[2:3:] = ["two", "elements"]
vereq(a, b)
vereq(a, c)
481 482 483 484
a = range(10)
a[::2] = tuple(range(5))
vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9])

485
# Verify that __getitem__ overrides are not recognized by __iter__
486
class L(list):
Tim Peters's avatar
Tim Peters committed
487 488
    def __getitem__(self, key):
        return str(key) + '!!!'
489
vereq(iter(L([1,2])).next(), 1)
490

491

492
print '6.6 Mappings == Dictionaries'
493 494
# calling built-in types without argument must return empty
if dict() != {}: raise TestFailed,'dict() does not return {}'
495
d = {}
496
if d.keys() != []: raise TestFailed, '{}.keys()'
497 498
if d.values() != []: raise TestFailed, '{}.values()'
if d.items() != []: raise TestFailed, '{}.items()'
499
if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')'
500 501
if ('a' in d) != 0: raise TestFailed, "'a' in {}"
if ('a' not in d) != 1: raise TestFailed, "'a' not in {}"
502
if len(d) != 0: raise TestFailed, 'len({})'
503
d = {'a': 1, 'b': 2}
504
if len(d) != 2: raise TestFailed, 'len(dict)'
505 506
k = d.keys()
k.sort()
507
if k != ['a', 'b']: raise TestFailed, 'dict keys()'
508 509
if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass
else: raise TestFailed, 'dict keys()'
510 511
if 'a' in d and 'b' in d and 'c' not in d: pass
else: raise TestFailed, 'dict keys() # in/not in version'
512
if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item'
513 514
d['c'] = 3
d['a'] = 4
515
if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment'
516
del d['b']
517
if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion'
518
# dict.clear()
519 520 521
d = {1:1, 2:2, 3:3}
d.clear()
if d != {}: raise TestFailed, 'dict clear'
522
# dict.update()
523 524 525 526
d.update({1:100})
d.update({2:20})
d.update({1:1, 2:2, 3:3})
if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
d.clear()
try: d.update(None)
except AttributeError: pass
else: raise TestFailed, 'dict.update(None), AttributeError expected'
class SimpleUserDict:
    def __init__(self):
        self.d = {1:1, 2:2, 3:3}
    def keys(self):
        return self.d.keys()
    def __getitem__(self, i):
        return self.d[i]
d.update(SimpleUserDict())
if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
d.clear()
class FailingUserDict:
    def keys(self):
        raise ValueError
try: d.update(FailingUserDict())
except ValueError: pass
else: raise TestFailed, 'dict.keys() expected ValueError'
class FailingUserDict:
    def keys(self):
        class BogonIter:
            def __iter__(self):
                raise ValueError
        return BogonIter()
try: d.update(FailingUserDict())
except ValueError: pass
else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
class FailingUserDict:
    def keys(self):
        class BogonIter:
            def __init__(self):
                self.i = 1
            def __iter__(self):
                return self
            def next(self):
                if self.i:
                    self.i = 0
                    return 'a'
                raise ValueError
        return BogonIter()
    def __getitem__(self, key):
        return key
try: d.update(FailingUserDict())
except ValueError: pass
else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
class FailingUserDict:
    def keys(self):
        class BogonIter:
            def __init__(self):
                self.i = ord('a')
            def __iter__(self):
                return self
            def next(self):
                if self.i <= ord('z'):
                    rtn = chr(self.i)
                    self.i += 1
                    return rtn
                raise StopIteration
        return BogonIter()
    def __getitem__(self, key):
        raise ValueError
try: d.update(FailingUserDict())
except ValueError: pass
else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
# dict.fromkeys()
if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
    raise TestFailed, 'dict.fromkeys did not work as a class method'
d = {}
if d.fromkeys('abc') is d:
    raise TestFailed, 'dict.fromkeys did not return a new dict'
if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
    raise TestFailed, 'dict.fromkeys failed with default value'
if d.fromkeys((4,5),0) != {4:0, 5:0}:
    raise TestFailed, 'dict.fromkeys failed with specified value'
if d.fromkeys([]) != {}:
    raise TestFailed, 'dict.fromkeys failed with null sequence'
def g():
    yield 1
if d.fromkeys(g()) != {1:None}:
    raise TestFailed, 'dict.fromkeys failed with a generator'
try: {}.fromkeys(3)
except TypeError: pass
else: raise TestFailed, 'dict.fromkeys failed to raise TypeError'
class dictlike(dict): pass
if dictlike.fromkeys('a') != {'a':None}:
    raise TestFailed, 'dictsubclass.fromkeys did not inherit'
if dictlike().fromkeys('a') != {'a':None}:
    raise TestFailed, 'dictsubclass.fromkeys did not inherit'
if type(dictlike.fromkeys('a')) is not dictlike:
    raise TestFailed, 'dictsubclass.fromkeys created wrong type'
if type(dictlike().fromkeys('a')) is not dictlike:
    raise TestFailed, 'dictsubclass.fromkeys created wrong type'
621 622
from UserDict import UserDict
class mydict(dict):
623 624
    def __new__(cls):
        return UserDict()
625 626 627
ud = mydict.fromkeys('ab')
if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict):
    raise TestFailed, 'fromkeys did not instantiate using  __new__'
628 629
# dict.copy()
d = {1:1, 2:2, 3:3}
630 631
if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
if {}.copy() != {}: raise TestFailed, 'empty dict copy'
Barry Warsaw's avatar
Barry Warsaw committed
632
# dict.get()
633
d = {}
634
if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg'
635
if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg'
Barry Warsaw's avatar
Barry Warsaw committed
636
d = {'a' : 1, 'b' : 2}
637
if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg'
Barry Warsaw's avatar
Barry Warsaw committed
638 639 640
if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg'
if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg'
if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg'
641 642
# dict.setdefault()
d = {}
643
if d.setdefault('key0') is not None:
644
    raise TestFailed, 'missing {} setdefault, no 2nd arg'
645
if d.setdefault('key0') is not None:
646
    raise TestFailed, 'present {} setdefault, no 2nd arg'
647
d.setdefault('key', []).append(3)
648
if d['key'][0] != 3:
649
    raise TestFailed, 'missing {} setdefault, w/ 2nd arg'
650
d.setdefault('key', []).append(4)
651
if len(d['key']) != 2:
652
    raise TestFailed, 'present {} setdefault, w/ 2nd arg'
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
# dict.popitem()
for copymode in -1, +1:
    # -1: b has same structure as a
    # +1: b is a.copy()
    for log2size in range(12):
        size = 2**log2size
        a = {}
        b = {}
        for i in range(size):
            a[`i`] = i
            if copymode < 0:
                b[`i`] = i
        if copymode > 0:
            b = a.copy()
        for i in range(size):
            ka, va = ta = a.popitem()
            if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta)
            kb, vb = tb = b.popitem()
            if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb)
            if copymode < 0 and ta != tb:
                raise TestFailed, "a.popitem != b.popitem: %s, %s" % (
                    str(ta), str(tb))
        if a: raise TestFailed, 'a not empty after popitems: %s' % str(a)
        if b: raise TestFailed, 'b not empty after popitems: %s' % str(b)
677

678 679 680 681 682
d.clear()
try: d.popitem()
except KeyError: pass
else: raise TestFailed, "{}.popitem doesn't raise KeyError"

683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
# Tests for pop with specified key
d.clear()
k, v = 'abc', 'def'
d[k] = v
try: d.pop('ghi')
except KeyError: pass
else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary"

if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair"
if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair"

try: d.pop(k)
except KeyError: pass
else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty"

698 699 700 701
# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
# see SF bug #689659
x = 4503599627370496L
y = 4503599627370496
702
h = {x: 'anything', y: 'something else'}
703 704 705
if h[x] != h[y]:
    raise TestFailed, "long/int key should match"

706 707 708 709
if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
d[k] = v
if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"

710 711 712
d[1] = 1
try:
    for i in d:
Tim Peters's avatar
Tim Peters committed
713
        d[i+1] = 1
714 715 716 717 718
except RuntimeError:
    pass
else:
    raise TestFailed, "changing dict size during iteration doesn't raise Error"

719 720 721 722 723 724 725
try: type(1, 2)
except TypeError: pass
else: raise TestFailed, 'type(), w/2 args expected TypeError'

try: type(1, 2, 3, 4)
except TypeError: pass
else: raise TestFailed, 'type(), w/4 args expected TypeError'
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740

print 'Buffers'
try: buffer('asdf', -1)
except ValueError: pass
else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"

try: buffer(None)
except TypeError: pass
else: raise TestFailed, "buffer(None) should raise TypeError"

a = buffer('asdf')
hash(a)
b = a * 5
if a == b:
    raise TestFailed, 'buffers should not be equal'
741 742 743 744 745 746
if str(b) != ('asdf' * 5):
    raise TestFailed, 'repeated buffer has wrong content'
if str(a * 0) != '':
    raise TestFailed, 'repeated buffer zero times has wrong content'
if str(a + buffer('def')) != 'asdfdef':
    raise TestFailed, 'concatenation of buffers yields wrong content'
747 748 749 750 751 752 753 754

try: a[1] = 'g'
except TypeError: pass
else: raise TestFailed, "buffer assignment should raise TypeError"

try: a[0:1] = 'g'
except TypeError: pass
else: raise TestFailed, "buffer slice assignment should raise TypeError"