This commit was manufactured by cvs2svn to create tag 'r234c1'.
[python/dscho.git] / Lib / test / test_types.py
blob242ca018888880021921b7f11a968af1c0436b17
1 # Python test set -- part 6, built-in types
3 from test.test_support import *
5 print '6. Built-in types'
7 print '6.1 Truth value testing'
8 if None: raise TestFailed, 'None is true instead of false'
9 if 0: raise TestFailed, '0 is true instead of false'
10 if 0L: raise TestFailed, '0L is true instead of false'
11 if 0.0: raise TestFailed, '0.0 is true instead of false'
12 if '': raise TestFailed, '\'\' is true instead of false'
13 if (): raise TestFailed, '() is true instead of false'
14 if []: raise TestFailed, '[] is true instead of false'
15 if {}: raise TestFailed, '{} is true instead of false'
16 if not 1: raise TestFailed, '1 is false instead of true'
17 if not 1L: raise TestFailed, '1L is false instead of true'
18 if not 1.0: raise TestFailed, '1.0 is false instead of true'
19 if not 'x': raise TestFailed, '\'x\' is false instead of true'
20 if not (1, 1): raise TestFailed, '(1, 1) is false instead of true'
21 if not [1]: raise TestFailed, '[1] is false instead of true'
22 if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true'
23 def f(): pass
24 class C: pass
25 import sys
26 x = C()
27 if not f: raise TestFailed, 'f is false instead of true'
28 if not C: raise TestFailed, 'C is false instead of true'
29 if not sys: raise TestFailed, 'sys is false instead of true'
30 if not x: raise TestFailed, 'x is false instead of true'
32 print '6.2 Boolean operations'
33 if 0 or 0: raise TestFailed, '0 or 0 is true instead of false'
34 if 1 and 1: pass
35 else: raise TestFailed, '1 and 1 is false instead of true'
36 if not 1: raise TestFailed, 'not 1 is true instead of false'
38 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 else: raise TestFailed, 'float comparisons failed'
45 if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass
46 else: raise TestFailed, 'string comparisons failed'
47 if 0 in [0] and 0 not in [1]: pass
48 else: raise TestFailed, 'membership test failed'
49 if None is None and [] is not []: pass
50 else: raise TestFailed, 'identity test failed'
52 try: float('')
53 except ValueError: pass
54 else: raise TestFailed, "float('') didn't raise ValueError"
56 try: float('5\0')
57 except ValueError: pass
58 else: raise TestFailed, "float('5\0') didn't raise ValueError"
60 try: 5.0 / 0.0
61 except ZeroDivisionError: pass
62 else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError"
64 try: 5.0 // 0.0
65 except ZeroDivisionError: pass
66 else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError"
68 try: 5.0 % 0.0
69 except ZeroDivisionError: pass
70 else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError"
72 try: 5 / 0L
73 except ZeroDivisionError: pass
74 else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError"
76 try: 5 // 0L
77 except ZeroDivisionError: pass
78 else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError"
80 try: 5 % 0L
81 except ZeroDivisionError: pass
82 else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError"
84 print '6.4 Numeric types (mostly conversions)'
85 if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons'
86 if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons'
87 if -1 != -1L or -1 != -1.0 or -1L != -1.0:
88 raise TestFailed, 'int/long/float value not equal'
89 # calling built-in types without argument must return 0
90 if int() != 0: raise TestFailed, 'int() does not return 0'
91 if long() != 0L: raise TestFailed, 'long() does not return 0L'
92 if float() != 0.0: raise TestFailed, 'float() does not return 0.0'
93 if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
94 else: raise TestFailed, 'int() does not round properly'
95 if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass
96 else: raise TestFailed, 'long() does not round properly'
97 if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
98 else: raise TestFailed, 'float() does not work properly'
99 print '6.4.1 32-bit integers'
100 if 12 + 24 != 36: raise TestFailed, 'int op'
101 if 12 + (-24) != -12: raise TestFailed, 'int op'
102 if (-12) + 24 != 12: raise TestFailed, 'int op'
103 if (-12) + (-24) != -36: raise TestFailed, 'int op'
104 if not 12 < 24: raise TestFailed, 'int op'
105 if not -24 < -12: raise TestFailed, 'int op'
106 # Test for a particular bug in integer multiply
107 xsize, ysize, zsize = 238, 356, 4
108 if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912):
109 raise TestFailed, 'int mul commutativity'
110 # And another.
111 m = -sys.maxint - 1
112 for divisor in 1, 2, 4, 8, 16, 32:
113 j = m // divisor
114 prod = divisor * j
115 if prod != m:
116 raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m)
117 if type(prod) is not int:
118 raise TestFailed, ("expected type(prod) to be int, not %r" %
119 type(prod))
120 # Check for expected * overflow to long.
121 for divisor in 1, 2, 4, 8, 16, 32:
122 j = m // divisor - 1
123 prod = divisor * j
124 if type(prod) is not long:
125 raise TestFailed, ("expected type(%r) to be long, not %r" %
126 (prod, type(prod)))
127 # Check for expected * overflow to long.
128 m = sys.maxint
129 for divisor in 1, 2, 4, 8, 16, 32:
130 j = m // divisor + 1
131 prod = divisor * j
132 if type(prod) is not long:
133 raise TestFailed, ("expected type(%r) to be long, not %r" %
134 (prod, type(prod)))
136 print '6.4.2 Long integers'
137 if 12L + 24L != 36L: raise TestFailed, 'long op'
138 if 12L + (-24L) != -12L: raise TestFailed, 'long op'
139 if (-12L) + 24L != 12L: raise TestFailed, 'long op'
140 if (-12L) + (-24L) != -36L: raise TestFailed, 'long op'
141 if not 12L < 24L: raise TestFailed, 'long op'
142 if not -24L < -12L: raise TestFailed, 'long op'
143 x = sys.maxint
144 if int(long(x)) != x: raise TestFailed, 'long op'
145 try: y = int(long(x)+1L)
146 except OverflowError: raise TestFailed, 'long op'
147 if not isinstance(y, long): raise TestFailed, 'long op'
148 x = -x
149 if int(long(x)) != x: raise TestFailed, 'long op'
150 x = x-1
151 if int(long(x)) != x: raise TestFailed, 'long op'
152 try: y = int(long(x)-1L)
153 except OverflowError: raise TestFailed, 'long op'
154 if not isinstance(y, long): raise TestFailed, 'long op'
156 try: 5 << -5
157 except ValueError: pass
158 else: raise TestFailed, 'int negative shift <<'
160 try: 5L << -5L
161 except ValueError: pass
162 else: raise TestFailed, 'long negative shift <<'
164 try: 5 >> -5
165 except ValueError: pass
166 else: raise TestFailed, 'int negative shift >>'
168 try: 5L >> -5L
169 except ValueError: pass
170 else: raise TestFailed, 'long negative shift >>'
172 print '6.4.3 Floating point numbers'
173 if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op'
174 if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op'
175 if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op'
176 if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op'
177 if not 12.0 < 24.0: raise TestFailed, 'float op'
178 if not -24.0 < -12.0: raise TestFailed, 'float op'
180 print '6.5 Sequence types'
182 print '6.5.1 Strings'
183 if len('') != 0: raise TestFailed, 'len(\'\')'
184 if len('a') != 1: raise TestFailed, 'len(\'a\')'
185 if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')'
186 if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation'
187 if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3'
188 if 0*'abcde' != '': raise TestFailed, 'string repetition 0*'
189 if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string'
190 if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass
191 else: raise TestFailed, 'in/not in string'
192 x = 'x'*103
193 if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug'
195 #extended slices for strings
196 a = '0123456789'
197 vereq(a[::], a)
198 vereq(a[::2], '02468')
199 vereq(a[1::2], '13579')
200 vereq(a[::-1],'9876543210')
201 vereq(a[::-2], '97531')
202 vereq(a[3::-2], '31')
203 vereq(a[-100:100:], a)
204 vereq(a[100:-100:-1], a[::-1])
205 vereq(a[-100L:100L:2L], '02468')
207 if have_unicode:
208 a = unicode('0123456789', 'ascii')
209 vereq(a[::], a)
210 vereq(a[::2], unicode('02468', 'ascii'))
211 vereq(a[1::2], unicode('13579', 'ascii'))
212 vereq(a[::-1], unicode('9876543210', 'ascii'))
213 vereq(a[::-2], unicode('97531', 'ascii'))
214 vereq(a[3::-2], unicode('31', 'ascii'))
215 vereq(a[-100:100:], a)
216 vereq(a[100:-100:-1], a[::-1])
217 vereq(a[-100L:100L:2L], unicode('02468', 'ascii'))
220 print '6.5.2 Tuples'
221 # calling built-in types without argument must return empty
222 if tuple() != (): raise TestFailed,'tuple() does not return ()'
223 if len(()) != 0: raise TestFailed, 'len(())'
224 if len((1,)) != 1: raise TestFailed, 'len((1,))'
225 if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))'
226 if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation'
227 if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3'
228 if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*'
229 if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple'
230 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
231 else: raise TestFailed, 'in/not in tuple'
232 try: ()[0]
233 except IndexError: pass
234 else: raise TestFailed, "tuple index error didn't raise IndexError"
235 x = ()
236 x += ()
237 if x != (): raise TestFailed, 'tuple inplace add from () to () failed'
238 x += (1,)
239 if x != (1,): raise TestFailed, 'tuple resize from () failed'
241 # extended slicing - subscript only for tuples
242 a = (0,1,2,3,4)
243 vereq(a[::], a)
244 vereq(a[::2], (0,2,4))
245 vereq(a[1::2], (1,3))
246 vereq(a[::-1], (4,3,2,1,0))
247 vereq(a[::-2], (4,2,0))
248 vereq(a[3::-2], (3,1))
249 vereq(a[-100:100:], a)
250 vereq(a[100:-100:-1], a[::-1])
251 vereq(a[-100L:100L:2L], (0,2,4))
253 # Check that a specific bug in _PyTuple_Resize() is squashed.
254 def f():
255 for i in range(1000):
256 yield i
257 vereq(list(tuple(f())), range(1000))
259 # Verify that __getitem__ overrides are not recognized by __iter__
260 class T(tuple):
261 def __getitem__(self, key):
262 return str(key) + '!!!'
263 vereq(iter(T((1,2))).next(), 1)
265 print '6.5.3 Lists'
266 # calling built-in types without argument must return empty
267 if list() != []: raise TestFailed,'list() does not return []'
268 if len([]) != 0: raise TestFailed, 'len([])'
269 if len([1,]) != 1: raise TestFailed, 'len([1,])'
270 if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])'
271 if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation'
272 if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3'
273 if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L'
274 if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*'
275 if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*'
276 if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list'
277 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
278 else: raise TestFailed, 'in/not in list'
279 a = [1, 2, 3, 4, 5]
280 a[:-1] = a
281 if a != [1, 2, 3, 4, 5, 5]:
282 raise TestFailed, "list self-slice-assign (head)"
283 a = [1, 2, 3, 4, 5]
284 a[1:] = a
285 if a != [1, 1, 2, 3, 4, 5]:
286 raise TestFailed, "list self-slice-assign (tail)"
287 a = [1, 2, 3, 4, 5]
288 a[1:-1] = a
289 if a != [1, 1, 2, 3, 4, 5, 5]:
290 raise TestFailed, "list self-slice-assign (center)"
291 try: [][0]
292 except IndexError: pass
293 else: raise TestFailed, "list index error didn't raise IndexError"
294 try: [][0] = 5
295 except IndexError: pass
296 else: raise TestFailed, "list assignment index error didn't raise IndexError"
297 try: [].pop()
298 except IndexError: pass
299 else: raise TestFailed, "empty list.pop() didn't raise IndexError"
300 try: [1].pop(5)
301 except IndexError: pass
302 else: raise TestFailed, "[1].pop(5) didn't raise IndexError"
303 try: [][0:1] = 5
304 except TypeError: pass
305 else: raise TestFailed, "bad list slice assignment didn't raise TypeError"
306 try: [].extend(None)
307 except TypeError: pass
308 else: raise TestFailed, "list.extend(None) didn't raise TypeError"
309 a = [1, 2, 3, 4]
310 a *= 0
311 if a != []:
312 raise TestFailed, "list inplace repeat"
314 a = []
315 a[:] = tuple(range(10))
316 if a != range(10):
317 raise TestFailed, "assigning tuple to slice"
319 print '6.5.3a Additional list operations'
320 a = [0,1,2,3,4]
321 a[0L] = 1
322 a[1L] = 2
323 a[2L] = 3
324 if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]'
325 a[0] = 5
326 a[1] = 6
327 a[2] = 7
328 if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]'
329 a[-2L] = 88
330 a[-1L] = 99
331 if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]'
332 a[-2] = 8
333 a[-1] = 9
334 if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]'
335 a[:2] = [0,4]
336 a[-3:] = []
337 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 a=range(0,5)
348 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 a.append(0)
355 a.append(1)
356 a.append(2)
357 if a != [0,1,2]: raise TestFailed, 'list append'
358 a.insert(0, -2)
359 a.insert(1, -1)
360 a.insert(2,0)
361 if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert'
362 b = a[:]
363 b.insert(-2, "foo")
364 b.insert(-200, "left")
365 b.insert(200, "right")
366 if b != ["left",-2,-1,0,0,"foo",1,2,"right"]: raise TestFailed, 'list insert2'
367 # a = [-2,-1,0,0,1,2]
368 if a.count(0) != 2: raise TestFailed, ' list count'
369 if a.index(0) != 2: raise TestFailed, 'list index'
370 if a.index(0,2) != 2: raise TestFailed, 'list index, start argument'
371 if a.index(0,-4) != 2: raise TestFailed, 'list index, -start argument'
372 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 if a.index(0,-4*sys.maxint,4*sys.maxint) != 2:
378 raise TestFailed, 'list index, -maxint, maxint argument'
379 try:
380 a.index(0, 4*sys.maxint,-4*sys.maxint)
381 except ValueError:
382 pass
383 else:
384 raise TestFailed, 'list index, maxint,-maxint argument'
386 try:
387 a.index(2,0,-10)
388 except ValueError:
389 pass
390 else:
391 raise TestFailed, 'list index, very -stop argument'
392 a.remove(0)
393 try:
394 a.index(2,0,4)
395 except ValueError:
396 pass
397 else:
398 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 def revcmp(a, b): return cmp(b, a)
405 a.sort(revcmp)
406 if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func'
407 # The following dumps core in unpatched Python 1.5:
408 def myComparison(x,y):
409 return cmp(x%3, y%7)
410 z = range(12)
411 z.sort(myComparison)
413 try: z.sort(2)
414 except TypeError: pass
415 else: raise TestFailed, 'list sort compare function is not callable'
417 def selfmodifyingComparison(x,y):
418 z.append(1)
419 return cmp(x, y)
420 try: z.sort(selfmodifyingComparison)
421 except ValueError: pass
422 else: raise TestFailed, 'modifying list during sort'
424 try: z.sort(lambda x, y: 's')
425 except TypeError: pass
426 else: raise TestFailed, 'list sort compare function does not return int'
428 # Test extreme cases with long ints
429 a = [0,1,2,3,4]
430 if a[ -pow(2,128L): 3 ] != [0,1,2]:
431 raise TestFailed, "list slicing with too-small long integer"
432 if a[ 3: pow(2,145L) ] != [3,4]:
433 raise TestFailed, "list slicing with too-large long integer"
436 # extended slicing
438 # subscript
439 a = [0,1,2,3,4]
440 vereq(a[::], a)
441 vereq(a[::2], [0,2,4])
442 vereq(a[1::2], [1,3])
443 vereq(a[::-1], [4,3,2,1,0])
444 vereq(a[::-2], [4,2,0])
445 vereq(a[3::-2], [3,1])
446 vereq(a[-100:100:], a)
447 vereq(a[100:-100:-1], a[::-1])
448 vereq(a[-100L:100L:2L], [0,2,4])
449 vereq(a[1000:2000:2], [])
450 vereq(a[-1000:-2000:-2], [])
451 # deletion
452 del a[::2]
453 vereq(a, [1,3])
454 a = range(5)
455 del a[1::2]
456 vereq(a, [0,2,4])
457 a = range(5)
458 del a[1::-2]
459 vereq(a, [0,2,3,4])
460 a = range(10)
461 del a[::1000]
462 vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
463 # assignment
464 a = range(10)
465 a[::2] = [-1]*5
466 vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])
467 a = range(10)
468 a[::-4] = [10]*3
469 vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])
470 a = range(4)
471 a[::-1] = a
472 vereq(a, [3, 2, 1, 0])
473 a = range(10)
474 b = a[:]
475 c = a[:]
476 a[2:3] = ["two", "elements"]
477 b[slice(2,3)] = ["two", "elements"]
478 c[2:3:] = ["two", "elements"]
479 vereq(a, b)
480 vereq(a, c)
481 a = range(10)
482 a[::2] = tuple(range(5))
483 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):
487 def __getitem__(self, key):
488 return str(key) + '!!!'
489 vereq(iter(L([1,2])).next(), 1)
492 print '6.6 Mappings == Dictionaries'
493 # calling built-in types without argument must return empty
494 if dict() != {}: raise TestFailed,'dict() does not return {}'
495 d = {}
496 if d.keys() != []: raise TestFailed, '{}.keys()'
497 if d.values() != []: raise TestFailed, '{}.values()'
498 if d.items() != []: raise TestFailed, '{}.items()'
499 if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')'
500 if ('a' in d) != 0: raise TestFailed, "'a' in {}"
501 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 k = d.keys()
506 k.sort()
507 if k != ['a', 'b']: raise TestFailed, 'dict keys()'
508 if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass
509 else: raise TestFailed, 'dict keys()'
510 if 'a' in d and 'b' in d and 'c' not in d: pass
511 else: raise TestFailed, 'dict keys() # in/not in version'
512 if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item'
513 d['c'] = 3
514 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 d = {1:1, 2:2, 3:3}
520 d.clear()
521 if d != {}: raise TestFailed, 'dict clear'
522 # dict.update()
523 d.update({1:100})
524 d.update({2:20})
525 d.update({1:1, 2:2, 3:3})
526 if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
527 d.clear()
528 try: d.update(None)
529 except AttributeError: pass
530 else: raise TestFailed, 'dict.update(None), AttributeError expected'
531 class SimpleUserDict:
532 def __init__(self):
533 self.d = {1:1, 2:2, 3:3}
534 def keys(self):
535 return self.d.keys()
536 def __getitem__(self, i):
537 return self.d[i]
538 d.update(SimpleUserDict())
539 if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
540 d.clear()
541 class FailingUserDict:
542 def keys(self):
543 raise ValueError
544 try: d.update(FailingUserDict())
545 except ValueError: pass
546 else: raise TestFailed, 'dict.keys() expected ValueError'
547 class FailingUserDict:
548 def keys(self):
549 class BogonIter:
550 def __iter__(self):
551 raise ValueError
552 return BogonIter()
553 try: d.update(FailingUserDict())
554 except ValueError: pass
555 else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
556 class FailingUserDict:
557 def keys(self):
558 class BogonIter:
559 def __init__(self):
560 self.i = 1
561 def __iter__(self):
562 return self
563 def next(self):
564 if self.i:
565 self.i = 0
566 return 'a'
567 raise ValueError
568 return BogonIter()
569 def __getitem__(self, key):
570 return key
571 try: d.update(FailingUserDict())
572 except ValueError: pass
573 else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
574 class FailingUserDict:
575 def keys(self):
576 class BogonIter:
577 def __init__(self):
578 self.i = ord('a')
579 def __iter__(self):
580 return self
581 def next(self):
582 if self.i <= ord('z'):
583 rtn = chr(self.i)
584 self.i += 1
585 return rtn
586 raise StopIteration
587 return BogonIter()
588 def __getitem__(self, key):
589 raise ValueError
590 try: d.update(FailingUserDict())
591 except ValueError: pass
592 else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
593 # dict.fromkeys()
594 if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
595 raise TestFailed, 'dict.fromkeys did not work as a class method'
596 d = {}
597 if d.fromkeys('abc') is d:
598 raise TestFailed, 'dict.fromkeys did not return a new dict'
599 if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
600 raise TestFailed, 'dict.fromkeys failed with default value'
601 if d.fromkeys((4,5),0) != {4:0, 5:0}:
602 raise TestFailed, 'dict.fromkeys failed with specified value'
603 if d.fromkeys([]) != {}:
604 raise TestFailed, 'dict.fromkeys failed with null sequence'
605 def g():
606 yield 1
607 if d.fromkeys(g()) != {1:None}:
608 raise TestFailed, 'dict.fromkeys failed with a generator'
609 try: {}.fromkeys(3)
610 except TypeError: pass
611 else: raise TestFailed, 'dict.fromkeys failed to raise TypeError'
612 class dictlike(dict): pass
613 if dictlike.fromkeys('a') != {'a':None}:
614 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
615 if dictlike().fromkeys('a') != {'a':None}:
616 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
617 if type(dictlike.fromkeys('a')) is not dictlike:
618 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
619 if type(dictlike().fromkeys('a')) is not dictlike:
620 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
621 from UserDict import UserDict
622 class mydict(dict):
623 def __new__(cls):
624 return UserDict()
625 ud = mydict.fromkeys('ab')
626 if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict):
627 raise TestFailed, 'fromkeys did not instantiate using __new__'
628 # dict.copy()
629 d = {1:1, 2:2, 3:3}
630 if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
631 if {}.copy() != {}: raise TestFailed, 'empty dict copy'
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'
636 d = {'a' : 1, 'b' : 2}
637 if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg'
638 if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg'
639 if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg'
640 if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg'
641 # dict.setdefault()
642 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 # dict.popitem()
654 for copymode in -1, +1:
655 # -1: b has same structure as a
656 # +1: b is a.copy()
657 for log2size in range(12):
658 size = 2**log2size
659 a = {}
660 b = {}
661 for i in range(size):
662 a[`i`] = i
663 if copymode < 0:
664 b[`i`] = i
665 if copymode > 0:
666 b = a.copy()
667 for i in range(size):
668 ka, va = ta = a.popitem()
669 if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta)
670 kb, vb = tb = b.popitem()
671 if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb)
672 if copymode < 0 and ta != tb:
673 raise TestFailed, "a.popitem != b.popitem: %s, %s" % (
674 str(ta), str(tb))
675 if a: raise TestFailed, 'a not empty after popitems: %s' % str(a)
676 if b: raise TestFailed, 'b not empty after popitems: %s' % str(b)
678 d.clear()
679 try: d.popitem()
680 except KeyError: pass
681 else: raise TestFailed, "{}.popitem doesn't raise KeyError"
683 # Tests for pop with specified key
684 d.clear()
685 k, v = 'abc', 'def'
686 d[k] = v
687 try: d.pop('ghi')
688 except KeyError: pass
689 else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary"
691 if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair"
692 if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair"
694 try: d.pop(k)
695 except KeyError: pass
696 else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty"
698 # verify longs/ints get same value when key > 32 bits (for 64-bit archs)
699 # see SF bug #689659
700 x = 4503599627370496L
701 y = 4503599627370496
702 h = {x: 'anything', y: 'something else'}
703 if h[x] != h[y]:
704 raise TestFailed, "long/int key should match"
706 if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
707 d[k] = v
708 if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"
710 d[1] = 1
711 try:
712 for i in d:
713 d[i+1] = 1
714 except RuntimeError:
715 pass
716 else:
717 raise TestFailed, "changing dict size during iteration doesn't raise Error"
719 try: type(1, 2)
720 except TypeError: pass
721 else: raise TestFailed, 'type(), w/2 args expected TypeError'
723 try: type(1, 2, 3, 4)
724 except TypeError: pass
725 else: raise TestFailed, 'type(), w/4 args expected TypeError'
727 print 'Buffers'
728 try: buffer('asdf', -1)
729 except ValueError: pass
730 else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
732 try: buffer(None)
733 except TypeError: pass
734 else: raise TestFailed, "buffer(None) should raise TypeError"
736 a = buffer('asdf')
737 hash(a)
738 b = a * 5
739 if a == b:
740 raise TestFailed, 'buffers should not be equal'
741 if str(b) != ('asdf' * 5):
742 raise TestFailed, 'repeated buffer has wrong content'
743 if str(a * 0) != '':
744 raise TestFailed, 'repeated buffer zero times has wrong content'
745 if str(a + buffer('def')) != 'asdfdef':
746 raise TestFailed, 'concatenation of buffers yields wrong content'
748 try: a[1] = 'g'
749 except TypeError: pass
750 else: raise TestFailed, "buffer assignment should raise TypeError"
752 try: a[0:1] = 'g'
753 except TypeError: pass
754 else: raise TestFailed, "buffer slice assignment should raise TypeError"