test_whitespace_eater_unicode(): Make this test Python 2.1 compatible.
[python/dscho.git] / Lib / test / test_types.py
blobf2a7ccdeb5be02cb02f6c73a103f9f965198056e
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 if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
90 else: raise TestFailed, 'int() does not round properly'
91 if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass
92 else: raise TestFailed, 'long() does not round properly'
93 if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
94 else: raise TestFailed, 'float() does not work properly'
95 print '6.4.1 32-bit integers'
96 if 12 + 24 != 36: raise TestFailed, 'int op'
97 if 12 + (-24) != -12: raise TestFailed, 'int op'
98 if (-12) + 24 != 12: raise TestFailed, 'int op'
99 if (-12) + (-24) != -36: raise TestFailed, 'int op'
100 if not 12 < 24: raise TestFailed, 'int op'
101 if not -24 < -12: raise TestFailed, 'int op'
102 # Test for a particular bug in integer multiply
103 xsize, ysize, zsize = 238, 356, 4
104 if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912):
105 raise TestFailed, 'int mul commutativity'
106 # And another.
107 m = -sys.maxint - 1
108 for divisor in 1, 2, 4, 8, 16, 32:
109 j = m // divisor
110 prod = divisor * j
111 if prod != m:
112 raise TestFailed, "%r * %r == %r != %r" % (divisor, j, prod, m)
113 if type(prod) is not int:
114 raise TestFailed, ("expected type(prod) to be int, not %r" %
115 type(prod))
116 # Check for expected * overflow to long.
117 for divisor in 1, 2, 4, 8, 16, 32:
118 j = m // divisor - 1
119 prod = divisor * j
120 if type(prod) is not long:
121 raise TestFailed, ("expected type(%r) to be long, not %r" %
122 (prod, type(prod)))
123 # Check for expected * overflow to long.
124 m = sys.maxint
125 for divisor in 1, 2, 4, 8, 16, 32:
126 j = m // divisor + 1
127 prod = divisor * j
128 if type(prod) is not long:
129 raise TestFailed, ("expected type(%r) to be long, not %r" %
130 (prod, type(prod)))
132 print '6.4.2 Long integers'
133 if 12L + 24L != 36L: raise TestFailed, 'long op'
134 if 12L + (-24L) != -12L: raise TestFailed, 'long op'
135 if (-12L) + 24L != 12L: raise TestFailed, 'long op'
136 if (-12L) + (-24L) != -36L: raise TestFailed, 'long op'
137 if not 12L < 24L: raise TestFailed, 'long op'
138 if not -24L < -12L: raise TestFailed, 'long op'
139 x = sys.maxint
140 if int(long(x)) != x: raise TestFailed, 'long op'
141 try: y = int(long(x)+1L)
142 except OverflowError: raise TestFailed, 'long op'
143 if not isinstance(y, long): raise TestFailed, 'long op'
144 x = -x
145 if int(long(x)) != x: raise TestFailed, 'long op'
146 x = x-1
147 if int(long(x)) != x: raise TestFailed, 'long op'
148 try: y = int(long(x)-1L)
149 except OverflowError: raise TestFailed, 'long op'
150 if not isinstance(y, long): raise TestFailed, 'long op'
152 try: 5 << -5
153 except ValueError: pass
154 else: raise TestFailed, 'int negative shift <<'
156 try: 5L << -5L
157 except ValueError: pass
158 else: raise TestFailed, 'long negative shift <<'
160 try: 5 >> -5
161 except ValueError: pass
162 else: raise TestFailed, 'int negative shift >>'
164 try: 5L >> -5L
165 except ValueError: pass
166 else: raise TestFailed, 'long negative shift >>'
168 print '6.4.3 Floating point numbers'
169 if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op'
170 if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op'
171 if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op'
172 if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op'
173 if not 12.0 < 24.0: raise TestFailed, 'float op'
174 if not -24.0 < -12.0: raise TestFailed, 'float op'
176 print '6.5 Sequence types'
178 print '6.5.1 Strings'
179 if len('') != 0: raise TestFailed, 'len(\'\')'
180 if len('a') != 1: raise TestFailed, 'len(\'a\')'
181 if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')'
182 if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation'
183 if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3'
184 if 0*'abcde' != '': raise TestFailed, 'string repetition 0*'
185 if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string'
186 if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass
187 else: raise TestFailed, 'in/not in string'
188 x = 'x'*103
189 if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug'
191 #extended slices for strings
192 a = '0123456789'
193 vereq(a[::], a)
194 vereq(a[::2], '02468')
195 vereq(a[1::2], '13579')
196 vereq(a[::-1],'9876543210')
197 vereq(a[::-2], '97531')
198 vereq(a[3::-2], '31')
199 vereq(a[-100:100:], a)
200 vereq(a[100:-100:-1], a[::-1])
201 vereq(a[-100L:100L:2L], '02468')
203 if have_unicode:
204 a = unicode('0123456789', 'ascii')
205 vereq(a[::], a)
206 vereq(a[::2], unicode('02468', 'ascii'))
207 vereq(a[1::2], unicode('13579', 'ascii'))
208 vereq(a[::-1], unicode('9876543210', 'ascii'))
209 vereq(a[::-2], unicode('97531', 'ascii'))
210 vereq(a[3::-2], unicode('31', 'ascii'))
211 vereq(a[-100:100:], a)
212 vereq(a[100:-100:-1], a[::-1])
213 vereq(a[-100L:100L:2L], unicode('02468', 'ascii'))
216 print '6.5.2 Tuples'
217 if len(()) != 0: raise TestFailed, 'len(())'
218 if len((1,)) != 1: raise TestFailed, 'len((1,))'
219 if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))'
220 if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation'
221 if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3'
222 if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*'
223 if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple'
224 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
225 else: raise TestFailed, 'in/not in tuple'
226 try: ()[0]
227 except IndexError: pass
228 else: raise TestFailed, "tuple index error didn't raise IndexError"
229 x = ()
230 x += ()
231 if x != (): raise TestFailed, 'tuple inplace add from () to () failed'
232 x += (1,)
233 if x != (1,): raise TestFailed, 'tuple resize from () failed'
235 # extended slicing - subscript only for tuples
236 a = (0,1,2,3,4)
237 vereq(a[::], a)
238 vereq(a[::2], (0,2,4))
239 vereq(a[1::2], (1,3))
240 vereq(a[::-1], (4,3,2,1,0))
241 vereq(a[::-2], (4,2,0))
242 vereq(a[3::-2], (3,1))
243 vereq(a[-100:100:], a)
244 vereq(a[100:-100:-1], a[::-1])
245 vereq(a[-100L:100L:2L], (0,2,4))
247 # Check that a specific bug in _PyTuple_Resize() is squashed.
248 def f():
249 for i in range(1000):
250 yield i
251 vereq(list(tuple(f())), range(1000))
253 print '6.5.3 Lists'
254 if len([]) != 0: raise TestFailed, 'len([])'
255 if len([1,]) != 1: raise TestFailed, 'len([1,])'
256 if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])'
257 if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation'
258 if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3'
259 if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L'
260 if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*'
261 if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*'
262 if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list'
263 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
264 else: raise TestFailed, 'in/not in list'
265 a = [1, 2, 3, 4, 5]
266 a[:-1] = a
267 if a != [1, 2, 3, 4, 5, 5]:
268 raise TestFailed, "list self-slice-assign (head)"
269 a = [1, 2, 3, 4, 5]
270 a[1:] = a
271 if a != [1, 1, 2, 3, 4, 5]:
272 raise TestFailed, "list self-slice-assign (tail)"
273 a = [1, 2, 3, 4, 5]
274 a[1:-1] = a
275 if a != [1, 1, 2, 3, 4, 5, 5]:
276 raise TestFailed, "list self-slice-assign (center)"
277 try: [][0]
278 except IndexError: pass
279 else: raise TestFailed, "list index error didn't raise IndexError"
280 try: [][0] = 5
281 except IndexError: pass
282 else: raise TestFailed, "list assignment index error didn't raise IndexError"
283 try: [].pop()
284 except IndexError: pass
285 else: raise TestFailed, "empty list.pop() didn't raise IndexError"
286 try: [1].pop(5)
287 except IndexError: pass
288 else: raise TestFailed, "[1].pop(5) didn't raise IndexError"
289 try: [][0:1] = 5
290 except TypeError: pass
291 else: raise TestFailed, "bad list slice assignment didn't raise TypeError"
292 try: [].extend(None)
293 except TypeError: pass
294 else: raise TestFailed, "list.extend(None) didn't raise TypeError"
295 a = [1, 2, 3, 4]
296 a *= 0
297 if a != []:
298 raise TestFailed, "list inplace repeat"
300 a = []
301 a[:] = tuple(range(10))
302 if a != range(10):
303 raise TestFailed, "assigning tuple to slice"
305 print '6.5.3a Additional list operations'
306 a = [0,1,2,3,4]
307 a[0L] = 1
308 a[1L] = 2
309 a[2L] = 3
310 if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]'
311 a[0] = 5
312 a[1] = 6
313 a[2] = 7
314 if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]'
315 a[-2L] = 88
316 a[-1L] = 99
317 if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]'
318 a[-2] = 8
319 a[-1] = 9
320 if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]'
321 a[:2] = [0,4]
322 a[-3:] = []
323 a[1:1] = [1,2,3]
324 if a != [0,1,2,3,4]: raise TestFailed, 'list slice assignment'
325 a[ 1L : 4L] = [7,8,9]
326 if a != [0,7,8,9,4]: raise TestFailed, 'list slice assignment using long ints'
327 del a[1:4]
328 if a != [0,4]: raise TestFailed, 'list slice deletion'
329 del a[0]
330 if a != [4]: raise TestFailed, 'list item deletion [0]'
331 del a[-1]
332 if a != []: raise TestFailed, 'list item deletion [-1]'
333 a=range(0,5)
334 del a[1L:4L]
335 if a != [0,4]: raise TestFailed, 'list slice deletion'
336 del a[0L]
337 if a != [4]: raise TestFailed, 'list item deletion [0]'
338 del a[-1L]
339 if a != []: raise TestFailed, 'list item deletion [-1]'
340 a.append(0)
341 a.append(1)
342 a.append(2)
343 if a != [0,1,2]: raise TestFailed, 'list append'
344 a.insert(0, -2)
345 a.insert(1, -1)
346 a.insert(2,0)
347 if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert'
348 if a.count(0) != 2: raise TestFailed, ' list count'
349 if a.index(0) != 2: raise TestFailed, 'list index'
350 a.remove(0)
351 if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove'
352 a.reverse()
353 if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse'
354 a.sort()
355 if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort'
356 def revcmp(a, b): return cmp(b, a)
357 a.sort(revcmp)
358 if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func'
359 # The following dumps core in unpatched Python 1.5:
360 def myComparison(x,y):
361 return cmp(x%3, y%7)
362 z = range(12)
363 z.sort(myComparison)
365 try: z.sort(2)
366 except TypeError: pass
367 else: raise TestFailed, 'list sort compare function is not callable'
369 def selfmodifyingComparison(x,y):
370 z.append(1)
371 return cmp(x, y)
372 try: z.sort(selfmodifyingComparison)
373 except ValueError: pass
374 else: raise TestFailed, 'modifying list during sort'
376 try: z.sort(lambda x, y: 's')
377 except TypeError: pass
378 else: raise TestFailed, 'list sort compare function does not return int'
380 # Test extreme cases with long ints
381 a = [0,1,2,3,4]
382 if a[ -pow(2,128L): 3 ] != [0,1,2]:
383 raise TestFailed, "list slicing with too-small long integer"
384 if a[ 3: pow(2,145L) ] != [3,4]:
385 raise TestFailed, "list slicing with too-large long integer"
388 # extended slicing
390 # subscript
391 a = [0,1,2,3,4]
392 vereq(a[::], a)
393 vereq(a[::2], [0,2,4])
394 vereq(a[1::2], [1,3])
395 vereq(a[::-1], [4,3,2,1,0])
396 vereq(a[::-2], [4,2,0])
397 vereq(a[3::-2], [3,1])
398 vereq(a[-100:100:], a)
399 vereq(a[100:-100:-1], a[::-1])
400 vereq(a[-100L:100L:2L], [0,2,4])
401 vereq(a[1000:2000:2], [])
402 vereq(a[-1000:-2000:-2], [])
403 # deletion
404 del a[::2]
405 vereq(a, [1,3])
406 a = range(5)
407 del a[1::2]
408 vereq(a, [0,2,4])
409 a = range(5)
410 del a[1::-2]
411 vereq(a, [0,2,3,4])
412 a = range(10)
413 del a[::1000]
414 vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
415 # assignment
416 a = range(10)
417 a[::2] = [-1]*5
418 vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])
419 a = range(10)
420 a[::-4] = [10]*3
421 vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])
422 a = range(4)
423 a[::-1] = a
424 vereq(a, [3, 2, 1, 0])
425 a = range(10)
426 b = a[:]
427 c = a[:]
428 a[2:3] = ["two", "elements"]
429 b[slice(2,3)] = ["two", "elements"]
430 c[2:3:] = ["two", "elements"]
431 vereq(a, b)
432 vereq(a, c)
433 a = range(10)
434 a[::2] = tuple(range(5))
435 vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9])
438 print '6.6 Mappings == Dictionaries'
439 d = {}
440 if d.keys() != []: raise TestFailed, '{}.keys()'
441 if d.values() != []: raise TestFailed, '{}.values()'
442 if d.items() != []: raise TestFailed, '{}.items()'
443 if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')'
444 if ('a' in d) != 0: raise TestFailed, "'a' in {}"
445 if ('a' not in d) != 1: raise TestFailed, "'a' not in {}"
446 if len(d) != 0: raise TestFailed, 'len({})'
447 d = {'a': 1, 'b': 2}
448 if len(d) != 2: raise TestFailed, 'len(dict)'
449 k = d.keys()
450 k.sort()
451 if k != ['a', 'b']: raise TestFailed, 'dict keys()'
452 if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass
453 else: raise TestFailed, 'dict keys()'
454 if 'a' in d and 'b' in d and 'c' not in d: pass
455 else: raise TestFailed, 'dict keys() # in/not in version'
456 if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item'
457 d['c'] = 3
458 d['a'] = 4
459 if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment'
460 del d['b']
461 if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion'
462 # dict.clear()
463 d = {1:1, 2:2, 3:3}
464 d.clear()
465 if d != {}: raise TestFailed, 'dict clear'
466 # dict.update()
467 d.update({1:100})
468 d.update({2:20})
469 d.update({1:1, 2:2, 3:3})
470 if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
471 d.clear()
472 try: d.update(None)
473 except AttributeError: pass
474 else: raise TestFailed, 'dict.update(None), AttributeError expected'
475 class SimpleUserDict:
476 def __init__(self):
477 self.d = {1:1, 2:2, 3:3}
478 def keys(self):
479 return self.d.keys()
480 def __getitem__(self, i):
481 return self.d[i]
482 d.update(SimpleUserDict())
483 if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
484 d.clear()
485 class FailingUserDict:
486 def keys(self):
487 raise ValueError
488 try: d.update(FailingUserDict())
489 except ValueError: pass
490 else: raise TestFailed, 'dict.keys() expected ValueError'
491 class FailingUserDict:
492 def keys(self):
493 class BogonIter:
494 def __iter__(self):
495 raise ValueError
496 return BogonIter()
497 try: d.update(FailingUserDict())
498 except ValueError: pass
499 else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
500 class FailingUserDict:
501 def keys(self):
502 class BogonIter:
503 def __init__(self):
504 self.i = 1
505 def __iter__(self):
506 return self
507 def next(self):
508 if self.i:
509 self.i = 0
510 return 'a'
511 raise ValueError
512 return BogonIter()
513 def __getitem__(self, key):
514 return key
515 try: d.update(FailingUserDict())
516 except ValueError: pass
517 else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
518 class FailingUserDict:
519 def keys(self):
520 class BogonIter:
521 def __init__(self):
522 self.i = ord('a')
523 def __iter__(self):
524 return self
525 def next(self):
526 if self.i <= ord('z'):
527 rtn = chr(self.i)
528 self.i += 1
529 return rtn
530 raise StopIteration
531 return BogonIter()
532 def __getitem__(self, key):
533 raise ValueError
534 try: d.update(FailingUserDict())
535 except ValueError: pass
536 else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
537 # dict.fromkeys()
538 if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
539 raise TestFailed, 'dict.fromkeys did not work as a class method'
540 d = {}
541 if d.fromkeys('abc') is d:
542 raise TestFailed, 'dict.fromkeys did not return a new dict'
543 if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
544 raise TestFailed, 'dict.fromkeys failed with default value'
545 if d.fromkeys((4,5),0) != {4:0, 5:0}:
546 raise TestFailed, 'dict.fromkeys failed with specified value'
547 if d.fromkeys([]) != {}:
548 raise TestFailed, 'dict.fromkeys failed with null sequence'
549 def g():
550 yield 1
551 if d.fromkeys(g()) != {1:None}:
552 raise TestFailed, 'dict.fromkeys failed with a generator'
553 try: {}.fromkeys(3)
554 except TypeError: pass
555 else: raise TestFailed, 'dict.fromkeys failed to raise TypeError'
556 class dictlike(dict): pass
557 if dictlike.fromkeys('a') != {'a':None}:
558 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
559 if dictlike().fromkeys('a') != {'a':None}:
560 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
561 if type(dictlike.fromkeys('a')) is not dictlike:
562 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
563 if type(dictlike().fromkeys('a')) is not dictlike:
564 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
565 from UserDict import UserDict
566 class mydict(dict):
567 def __new__(cls):
568 return UserDict()
569 ud = mydict.fromkeys('ab')
570 if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict):
571 raise TestFailed, 'fromkeys did not instantiate using __new__'
572 # dict.copy()
573 d = {1:1, 2:2, 3:3}
574 if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
575 if {}.copy() != {}: raise TestFailed, 'empty dict copy'
576 # dict.get()
577 d = {}
578 if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg'
579 if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg'
580 d = {'a' : 1, 'b' : 2}
581 if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg'
582 if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg'
583 if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg'
584 if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg'
585 # dict.setdefault()
586 d = {}
587 if d.setdefault('key0') is not None:
588 raise TestFailed, 'missing {} setdefault, no 2nd arg'
589 if d.setdefault('key0') is not None:
590 raise TestFailed, 'present {} setdefault, no 2nd arg'
591 d.setdefault('key', []).append(3)
592 if d['key'][0] != 3:
593 raise TestFailed, 'missing {} setdefault, w/ 2nd arg'
594 d.setdefault('key', []).append(4)
595 if len(d['key']) != 2:
596 raise TestFailed, 'present {} setdefault, w/ 2nd arg'
597 # dict.popitem()
598 for copymode in -1, +1:
599 # -1: b has same structure as a
600 # +1: b is a.copy()
601 for log2size in range(12):
602 size = 2**log2size
603 a = {}
604 b = {}
605 for i in range(size):
606 a[`i`] = i
607 if copymode < 0:
608 b[`i`] = i
609 if copymode > 0:
610 b = a.copy()
611 for i in range(size):
612 ka, va = ta = a.popitem()
613 if va != int(ka): raise TestFailed, "a.popitem: %s" % str(ta)
614 kb, vb = tb = b.popitem()
615 if vb != int(kb): raise TestFailed, "b.popitem: %s" % str(tb)
616 if copymode < 0 and ta != tb:
617 raise TestFailed, "a.popitem != b.popitem: %s, %s" % (
618 str(ta), str(tb))
619 if a: raise TestFailed, 'a not empty after popitems: %s' % str(a)
620 if b: raise TestFailed, 'b not empty after popitems: %s' % str(b)
622 d.clear()
623 try: d.popitem()
624 except KeyError: pass
625 else: raise TestFailed, "{}.popitem doesn't raise KeyError"
627 # Tests for pop with specified key
628 d.clear()
629 k, v = 'abc', 'def'
630 d[k] = v
631 try: d.pop('ghi')
632 except KeyError: pass
633 else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary"
635 if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair"
636 if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair"
638 try: d.pop(k)
639 except KeyError: pass
640 else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty"
642 # verify longs/ints get same value when key > 32 bits (for 64-bit archs)
643 # see SF bug #689659
644 x = 4503599627370496L
645 y = 4503599627370496
646 h = {x: 'anything', y: 'something else'}
647 if h[x] != h[y]:
648 raise TestFailed, "long/int key should match"
650 if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
651 d[k] = v
652 if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"
654 d[1] = 1
655 try:
656 for i in d:
657 d[i+1] = 1
658 except RuntimeError:
659 pass
660 else:
661 raise TestFailed, "changing dict size during iteration doesn't raise Error"
663 try: type(1, 2)
664 except TypeError: pass
665 else: raise TestFailed, 'type(), w/2 args expected TypeError'
667 try: type(1, 2, 3, 4)
668 except TypeError: pass
669 else: raise TestFailed, 'type(), w/4 args expected TypeError'
671 print 'Buffers'
672 try: buffer('asdf', -1)
673 except ValueError: pass
674 else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
676 try: buffer(None)
677 except TypeError: pass
678 else: raise TestFailed, "buffer(None) should raise TypeError"
680 a = buffer('asdf')
681 hash(a)
682 b = a * 5
683 if a == b:
684 raise TestFailed, 'buffers should not be equal'
685 if str(b) != ('asdf' * 5):
686 raise TestFailed, 'repeated buffer has wrong content'
687 if str(a * 0) != '':
688 raise TestFailed, 'repeated buffer zero times has wrong content'
689 if str(a + buffer('def')) != 'asdfdef':
690 raise TestFailed, 'concatenation of buffers yields wrong content'
692 try: a[1] = 'g'
693 except TypeError: pass
694 else: raise TestFailed, "buffer assignment should raise TypeError"
696 try: a[0:1] = 'g'
697 except TypeError: pass
698 else: raise TestFailed, "buffer slice assignment should raise TypeError"