This commit was manufactured by cvs2svn to create tag 'r23b1-mac'.
[python/dscho.git] / Lib / test / test_types.py
blob7e238df3e0ae4f7897462e2a28445475d35531e5
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 false'
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 recognized by __iter__
260 class T(tuple):
261 def __getitem__(self, key):
262 return str(key) + '!!!'
263 vereq(iter(T()).next(), '0!!!')
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 if a.count(0) != 2: raise TestFailed, ' list count'
368 if a.index(0) != 2: raise TestFailed, 'list index'
369 a.remove(0)
370 if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove'
371 a.reverse()
372 if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse'
373 a.sort()
374 if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort'
375 def revcmp(a, b): return cmp(b, a)
376 a.sort(revcmp)
377 if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func'
378 # The following dumps core in unpatched Python 1.5:
379 def myComparison(x,y):
380 return cmp(x%3, y%7)
381 z = range(12)
382 z.sort(myComparison)
384 try: z.sort(2)
385 except TypeError: pass
386 else: raise TestFailed, 'list sort compare function is not callable'
388 def selfmodifyingComparison(x,y):
389 z.append(1)
390 return cmp(x, y)
391 try: z.sort(selfmodifyingComparison)
392 except ValueError: pass
393 else: raise TestFailed, 'modifying list during sort'
395 try: z.sort(lambda x, y: 's')
396 except TypeError: pass
397 else: raise TestFailed, 'list sort compare function does not return int'
399 # Test extreme cases with long ints
400 a = [0,1,2,3,4]
401 if a[ -pow(2,128L): 3 ] != [0,1,2]:
402 raise TestFailed, "list slicing with too-small long integer"
403 if a[ 3: pow(2,145L) ] != [3,4]:
404 raise TestFailed, "list slicing with too-large long integer"
407 # extended slicing
409 # subscript
410 a = [0,1,2,3,4]
411 vereq(a[::], a)
412 vereq(a[::2], [0,2,4])
413 vereq(a[1::2], [1,3])
414 vereq(a[::-1], [4,3,2,1,0])
415 vereq(a[::-2], [4,2,0])
416 vereq(a[3::-2], [3,1])
417 vereq(a[-100:100:], a)
418 vereq(a[100:-100:-1], a[::-1])
419 vereq(a[-100L:100L:2L], [0,2,4])
420 vereq(a[1000:2000:2], [])
421 vereq(a[-1000:-2000:-2], [])
422 # deletion
423 del a[::2]
424 vereq(a, [1,3])
425 a = range(5)
426 del a[1::2]
427 vereq(a, [0,2,4])
428 a = range(5)
429 del a[1::-2]
430 vereq(a, [0,2,3,4])
431 a = range(10)
432 del a[::1000]
433 vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
434 # assignment
435 a = range(10)
436 a[::2] = [-1]*5
437 vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])
438 a = range(10)
439 a[::-4] = [10]*3
440 vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])
441 a = range(4)
442 a[::-1] = a
443 vereq(a, [3, 2, 1, 0])
444 a = range(10)
445 b = a[:]
446 c = a[:]
447 a[2:3] = ["two", "elements"]
448 b[slice(2,3)] = ["two", "elements"]
449 c[2:3:] = ["two", "elements"]
450 vereq(a, b)
451 vereq(a, c)
452 a = range(10)
453 a[::2] = tuple(range(5))
454 vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9])
456 # Verify that __getitem__ overrides are recognized by __iter__
457 class L(list):
458 def __getitem__(self, key):
459 return str(key) + '!!!'
460 vereq(iter(L()).next(), '0!!!')
463 print '6.6 Mappings == Dictionaries'
464 # calling built-in types without argument must return empty
465 if dict() != {}: raise TestFailed,'dict() does not return {}'
466 d = {}
467 if d.keys() != []: raise TestFailed, '{}.keys()'
468 if d.values() != []: raise TestFailed, '{}.values()'
469 if d.items() != []: raise TestFailed, '{}.items()'
470 if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')'
471 if ('a' in d) != 0: raise TestFailed, "'a' in {}"
472 if ('a' not in d) != 1: raise TestFailed, "'a' not in {}"
473 if len(d) != 0: raise TestFailed, 'len({})'
474 d = {'a': 1, 'b': 2}
475 if len(d) != 2: raise TestFailed, 'len(dict)'
476 k = d.keys()
477 k.sort()
478 if k != ['a', 'b']: raise TestFailed, 'dict keys()'
479 if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass
480 else: raise TestFailed, 'dict keys()'
481 if 'a' in d and 'b' in d and 'c' not in d: pass
482 else: raise TestFailed, 'dict keys() # in/not in version'
483 if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item'
484 d['c'] = 3
485 d['a'] = 4
486 if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment'
487 del d['b']
488 if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion'
489 # dict.clear()
490 d = {1:1, 2:2, 3:3}
491 d.clear()
492 if d != {}: raise TestFailed, 'dict clear'
493 # dict.update()
494 d.update({1:100})
495 d.update({2:20})
496 d.update({1:1, 2:2, 3:3})
497 if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
498 d.clear()
499 try: d.update(None)
500 except AttributeError: pass
501 else: raise TestFailed, 'dict.update(None), AttributeError expected'
502 class SimpleUserDict:
503 def __init__(self):
504 self.d = {1:1, 2:2, 3:3}
505 def keys(self):
506 return self.d.keys()
507 def __getitem__(self, i):
508 return self.d[i]
509 d.update(SimpleUserDict())
510 if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
511 d.clear()
512 class FailingUserDict:
513 def keys(self):
514 raise ValueError
515 try: d.update(FailingUserDict())
516 except ValueError: pass
517 else: raise TestFailed, 'dict.keys() expected ValueError'
518 class FailingUserDict:
519 def keys(self):
520 class BogonIter:
521 def __iter__(self):
522 raise ValueError
523 return BogonIter()
524 try: d.update(FailingUserDict())
525 except ValueError: pass
526 else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
527 class FailingUserDict:
528 def keys(self):
529 class BogonIter:
530 def __init__(self):
531 self.i = 1
532 def __iter__(self):
533 return self
534 def next(self):
535 if self.i:
536 self.i = 0
537 return 'a'
538 raise ValueError
539 return BogonIter()
540 def __getitem__(self, key):
541 return key
542 try: d.update(FailingUserDict())
543 except ValueError: pass
544 else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
545 class FailingUserDict:
546 def keys(self):
547 class BogonIter:
548 def __init__(self):
549 self.i = ord('a')
550 def __iter__(self):
551 return self
552 def next(self):
553 if self.i <= ord('z'):
554 rtn = chr(self.i)
555 self.i += 1
556 return rtn
557 raise StopIteration
558 return BogonIter()
559 def __getitem__(self, key):
560 raise ValueError
561 try: d.update(FailingUserDict())
562 except ValueError: pass
563 else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
564 # dict.fromkeys()
565 if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
566 raise TestFailed, 'dict.fromkeys did not work as a class method'
567 d = {}
568 if d.fromkeys('abc') is d:
569 raise TestFailed, 'dict.fromkeys did not return a new dict'
570 if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
571 raise TestFailed, 'dict.fromkeys failed with default value'
572 if d.fromkeys((4,5),0) != {4:0, 5:0}:
573 raise TestFailed, 'dict.fromkeys failed with specified value'
574 if d.fromkeys([]) != {}:
575 raise TestFailed, 'dict.fromkeys failed with null sequence'
576 def g():
577 yield 1
578 if d.fromkeys(g()) != {1:None}:
579 raise TestFailed, 'dict.fromkeys failed with a generator'
580 try: {}.fromkeys(3)
581 except TypeError: pass
582 else: raise TestFailed, 'dict.fromkeys failed to raise TypeError'
583 class dictlike(dict): pass
584 if dictlike.fromkeys('a') != {'a':None}:
585 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
586 if dictlike().fromkeys('a') != {'a':None}:
587 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
588 if type(dictlike.fromkeys('a')) is not dictlike:
589 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
590 if type(dictlike().fromkeys('a')) is not dictlike:
591 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
592 from UserDict import UserDict
593 class mydict(dict):
594 def __new__(cls):
595 return UserDict()
596 ud = mydict.fromkeys('ab')
597 if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict):
598 raise TestFailed, 'fromkeys did not instantiate using __new__'
599 # dict.copy()
600 d = {1:1, 2:2, 3:3}
601 if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
602 if {}.copy() != {}: raise TestFailed, 'empty dict copy'
603 # dict.get()
604 d = {}
605 if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg'
606 if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg'
607 d = {'a' : 1, 'b' : 2}
608 if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg'
609 if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg'
610 if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg'
611 if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg'
612 # dict.setdefault()
613 d = {}
614 if d.setdefault('key0') is not None:
615 raise TestFailed, 'missing {} setdefault, no 2nd arg'
616 if d.setdefault('key0') is not None:
617 raise TestFailed, 'present {} setdefault, no 2nd arg'
618 d.setdefault('key', []).append(3)
619 if d['key'][0] != 3:
620 raise TestFailed, 'missing {} setdefault, w/ 2nd arg'
621 d.setdefault('key', []).append(4)
622 if len(d['key']) != 2:
623 raise TestFailed, 'present {} setdefault, w/ 2nd arg'
624 # dict.popitem()
625 for copymode in -1, +1:
626 # -1: b has same structure as a
627 # +1: b is a.copy()
628 for log2size in range(12):
629 size = 2**log2size
630 a = {}
631 b = {}
632 for i in range(size):
633 a[`i`] = i
634 if copymode < 0:
635 b[`i`] = i
636 if copymode > 0:
637 b = a.copy()
638 for i in range(size):
639 ka, va = ta = a.popitem()
640 if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta)
641 kb, vb = tb = b.popitem()
642 if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb)
643 if copymode < 0 and ta != tb:
644 raise TestFailed, "a.popitem != b.popitem: %s, %s" % (
645 str(ta), str(tb))
646 if a: raise TestFailed, 'a not empty after popitems: %s' % str(a)
647 if b: raise TestFailed, 'b not empty after popitems: %s' % str(b)
649 d.clear()
650 try: d.popitem()
651 except KeyError: pass
652 else: raise TestFailed, "{}.popitem doesn't raise KeyError"
654 # Tests for pop with specified key
655 d.clear()
656 k, v = 'abc', 'def'
657 d[k] = v
658 try: d.pop('ghi')
659 except KeyError: pass
660 else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary"
662 if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair"
663 if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair"
665 try: d.pop(k)
666 except KeyError: pass
667 else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty"
669 # verify longs/ints get same value when key > 32 bits (for 64-bit archs)
670 # see SF bug #689659
671 x = 4503599627370496L
672 y = 4503599627370496
673 h = {x: 'anything', y: 'something else'}
674 if h[x] != h[y]:
675 raise TestFailed, "long/int key should match"
677 if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
678 d[k] = v
679 if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"
681 d[1] = 1
682 try:
683 for i in d:
684 d[i+1] = 1
685 except RuntimeError:
686 pass
687 else:
688 raise TestFailed, "changing dict size during iteration doesn't raise Error"
690 try: type(1, 2)
691 except TypeError: pass
692 else: raise TestFailed, 'type(), w/2 args expected TypeError'
694 try: type(1, 2, 3, 4)
695 except TypeError: pass
696 else: raise TestFailed, 'type(), w/4 args expected TypeError'
698 print 'Buffers'
699 try: buffer('asdf', -1)
700 except ValueError: pass
701 else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
703 try: buffer(None)
704 except TypeError: pass
705 else: raise TestFailed, "buffer(None) should raise TypeError"
707 a = buffer('asdf')
708 hash(a)
709 b = a * 5
710 if a == b:
711 raise TestFailed, 'buffers should not be equal'
712 if str(b) != ('asdf' * 5):
713 raise TestFailed, 'repeated buffer has wrong content'
714 if str(a * 0) != '':
715 raise TestFailed, 'repeated buffer zero times has wrong content'
716 if str(a + buffer('def')) != 'asdfdef':
717 raise TestFailed, 'concatenation of buffers yields wrong content'
719 try: a[1] = 'g'
720 except TypeError: pass
721 else: raise TestFailed, "buffer assignment should raise TypeError"
723 try: a[0:1] = 'g'
724 except TypeError: pass
725 else: raise TestFailed, "buffer slice assignment should raise TypeError"