blob: 7e238df3e0ae4f7897462e2a28445475d35531e5 [file] [log] [blame]
Guido van Rossum85f18201992-11-27 22:53:50 +00001# Python test set -- part 6, built-in types
2
Barry Warsaw04f357c2002-07-23 19:04:11 +00003from test.test_support import *
Guido van Rossum85f18201992-11-27 22:53:50 +00004
5print '6. Built-in types'
6
7print '6.1 Truth value testing'
8if None: raise TestFailed, 'None is true instead of false'
9if 0: raise TestFailed, '0 is true instead of false'
10if 0L: raise TestFailed, '0L is true instead of false'
11if 0.0: raise TestFailed, '0.0 is true instead of false'
12if '': raise TestFailed, '\'\' is true instead of false'
13if (): raise TestFailed, '() is true instead of false'
14if []: raise TestFailed, '[] is true instead of false'
15if {}: raise TestFailed, '{} is true instead of false'
16if not 1: raise TestFailed, '1 is false instead of true'
17if not 1L: raise TestFailed, '1L is false instead of true'
18if not 1.0: raise TestFailed, '1.0 is false instead of true'
19if not 'x': raise TestFailed, '\'x\' is false instead of true'
20if not (1, 1): raise TestFailed, '(1, 1) is false instead of true'
21if not [1]: raise TestFailed, '[1] is false instead of true'
22if not {'x': 1}: raise TestFailed, '{\'x\': 1} is false instead of true'
23def f(): pass
Guido van Rossumd3166071993-05-24 14:16:22 +000024class C: pass
Guido van Rossum85f18201992-11-27 22:53:50 +000025import sys
26x = C()
27if not f: raise TestFailed, 'f is false instead of true'
28if not C: raise TestFailed, 'C is false instead of true'
29if not sys: raise TestFailed, 'sys is false instead of true'
30if not x: raise TestFailed, 'x is false instead of true'
31
32print '6.2 Boolean operations'
33if 0 or 0: raise TestFailed, '0 or 0 is true instead of false'
34if 1 and 1: pass
35else: raise TestFailed, '1 and 1 is false instead of false'
36if not 1: raise TestFailed, 'not 1 is true instead of false'
37
38print '6.3 Comparisons'
Fred Drake132dce22000-12-12 23:11:42 +000039if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass
Guido van Rossum85f18201992-11-27 22:53:50 +000040else: raise TestFailed, 'int comparisons failed'
Fred Drake132dce22000-12-12 23:11:42 +000041if 0L < 1L <= 1L == 1L >= 1L > 0L != 1L: pass
Guido van Rossum85f18201992-11-27 22:53:50 +000042else: raise TestFailed, 'long int comparisons failed'
Fred Drake132dce22000-12-12 23:11:42 +000043if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass
Guido van Rossum85f18201992-11-27 22:53:50 +000044else: raise TestFailed, 'float comparisons failed'
45if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass
46else: raise TestFailed, 'string comparisons failed'
47if 0 in [0] and 0 not in [1]: pass
48else: raise TestFailed, 'membership test failed'
49if None is None and [] is not []: pass
50else: raise TestFailed, 'identity test failed'
51
Neil Schemenauereff72442002-03-24 01:24:54 +000052try: float('')
53except ValueError: pass
54else: raise TestFailed, "float('') didn't raise ValueError"
55
56try: float('5\0')
57except ValueError: pass
58else: raise TestFailed, "float('5\0') didn't raise ValueError"
59
60try: 5.0 / 0.0
61except ZeroDivisionError: pass
62else: raise TestFailed, "5.0 / 0.0 didn't raise ZeroDivisionError"
63
64try: 5.0 // 0.0
65except ZeroDivisionError: pass
66else: raise TestFailed, "5.0 // 0.0 didn't raise ZeroDivisionError"
67
68try: 5.0 % 0.0
69except ZeroDivisionError: pass
70else: raise TestFailed, "5.0 % 0.0 didn't raise ZeroDivisionError"
71
72try: 5 / 0L
73except ZeroDivisionError: pass
74else: raise TestFailed, "5 / 0L didn't raise ZeroDivisionError"
75
76try: 5 // 0L
77except ZeroDivisionError: pass
78else: raise TestFailed, "5 // 0L didn't raise ZeroDivisionError"
79
80try: 5 % 0L
81except ZeroDivisionError: pass
82else: raise TestFailed, "5 % 0L didn't raise ZeroDivisionError"
83
Guido van Rossum85f18201992-11-27 22:53:50 +000084print '6.4 Numeric types (mostly conversions)'
Fred Drake132dce22000-12-12 23:11:42 +000085if 0 != 0L or 0 != 0.0 or 0L != 0.0: raise TestFailed, 'mixed comparisons'
86if 1 != 1L or 1 != 1.0 or 1L != 1.0: raise TestFailed, 'mixed comparisons'
87if -1 != -1L or -1 != -1.0 or -1L != -1.0:
Fred Drake004d5e62000-10-23 17:22:08 +000088 raise TestFailed, 'int/long/float value not equal'
Guido van Rossumaa86e352003-04-19 18:15:10 +000089# calling built-in types without argument must return 0
90if int() != 0: raise TestFailed, 'int() does not return 0'
91if long() != 0L: raise TestFailed, 'long() does not return 0L'
92if float() != 0.0: raise TestFailed, 'float() does not return 0.0'
Guido van Rossum85f18201992-11-27 22:53:50 +000093if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass
94else: raise TestFailed, 'int() does not round properly'
95if long(1.9) == 1L == long(1.1) and long(-1.1) == -1L == long(-1.9): pass
96else: raise TestFailed, 'long() does not round properly'
97if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass
98else: raise TestFailed, 'float() does not work properly'
Guido van Rossum80530ce1993-01-21 15:36:40 +000099print '6.4.1 32-bit integers'
Fred Drake132dce22000-12-12 23:11:42 +0000100if 12 + 24 != 36: raise TestFailed, 'int op'
101if 12 + (-24) != -12: raise TestFailed, 'int op'
102if (-12) + 24 != 12: raise TestFailed, 'int op'
103if (-12) + (-24) != -36: raise TestFailed, 'int op'
Guido van Rossum80530ce1993-01-21 15:36:40 +0000104if not 12 < 24: raise TestFailed, 'int op'
105if not -24 < -12: raise TestFailed, 'int op'
Guido van Rossumb6775db1994-08-01 11:34:53 +0000106# Test for a particular bug in integer multiply
107xsize, ysize, zsize = 238, 356, 4
108if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912):
Fred Drake004d5e62000-10-23 17:22:08 +0000109 raise TestFailed, 'int mul commutativity'
Tim Petersa3c01ce2001-12-04 23:05:10 +0000110# And another.
111m = -sys.maxint - 1
112for divisor in 1, 2, 4, 8, 16, 32:
Tim Peters6d30c3e2001-12-05 00:30:09 +0000113 j = m // divisor
Tim Petersa3c01ce2001-12-04 23:05:10 +0000114 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.
121for divisor in 1, 2, 4, 8, 16, 32:
Tim Peters6d30c3e2001-12-05 00:30:09 +0000122 j = m // divisor - 1
Tim Petersa3c01ce2001-12-04 23:05:10 +0000123 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.
128m = sys.maxint
129for divisor in 1, 2, 4, 8, 16, 32:
Tim Peters6d30c3e2001-12-05 00:30:09 +0000130 j = m // divisor + 1
Tim Petersa3c01ce2001-12-04 23:05:10 +0000131 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)))
135
Guido van Rossum80530ce1993-01-21 15:36:40 +0000136print '6.4.2 Long integers'
Fred Drake132dce22000-12-12 23:11:42 +0000137if 12L + 24L != 36L: raise TestFailed, 'long op'
138if 12L + (-24L) != -12L: raise TestFailed, 'long op'
139if (-12L) + 24L != 12L: raise TestFailed, 'long op'
140if (-12L) + (-24L) != -36L: raise TestFailed, 'long op'
Guido van Rossum80530ce1993-01-21 15:36:40 +0000141if not 12L < 24L: raise TestFailed, 'long op'
142if not -24L < -12L: raise TestFailed, 'long op'
Guido van Rossum74629421998-05-26 14:51:55 +0000143x = sys.maxint
144if int(long(x)) != x: raise TestFailed, 'long op'
Walter Dörwaldf1715402002-11-19 20:49:15 +0000145try: y = int(long(x)+1L)
146except OverflowError: raise TestFailed, 'long op'
147if not isinstance(y, long): raise TestFailed, 'long op'
Guido van Rossum74629421998-05-26 14:51:55 +0000148x = -x
149if int(long(x)) != x: raise TestFailed, 'long op'
150x = x-1
151if int(long(x)) != x: raise TestFailed, 'long op'
Walter Dörwaldf1715402002-11-19 20:49:15 +0000152try: y = int(long(x)-1L)
153except OverflowError: raise TestFailed, 'long op'
154if not isinstance(y, long): raise TestFailed, 'long op'
Neil Schemenauereff72442002-03-24 01:24:54 +0000155
156try: 5 << -5
157except ValueError: pass
158else: raise TestFailed, 'int negative shift <<'
159
160try: 5L << -5L
161except ValueError: pass
162else: raise TestFailed, 'long negative shift <<'
163
164try: 5 >> -5
165except ValueError: pass
166else: raise TestFailed, 'int negative shift >>'
167
168try: 5L >> -5L
169except ValueError: pass
170else: raise TestFailed, 'long negative shift >>'
171
Guido van Rossum80530ce1993-01-21 15:36:40 +0000172print '6.4.3 Floating point numbers'
Fred Drake132dce22000-12-12 23:11:42 +0000173if 12.0 + 24.0 != 36.0: raise TestFailed, 'float op'
174if 12.0 + (-24.0) != -12.0: raise TestFailed, 'float op'
175if (-12.0) + 24.0 != 12.0: raise TestFailed, 'float op'
176if (-12.0) + (-24.0) != -36.0: raise TestFailed, 'float op'
Guido van Rossum80530ce1993-01-21 15:36:40 +0000177if not 12.0 < 24.0: raise TestFailed, 'float op'
178if not -24.0 < -12.0: raise TestFailed, 'float op'
Guido van Rossum85f18201992-11-27 22:53:50 +0000179
180print '6.5 Sequence types'
181
182print '6.5.1 Strings'
Fred Drake132dce22000-12-12 23:11:42 +0000183if len('') != 0: raise TestFailed, 'len(\'\')'
184if len('a') != 1: raise TestFailed, 'len(\'a\')'
185if len('abcdef') != 6: raise TestFailed, 'len(\'abcdef\')'
186if 'xyz' + 'abcde' != 'xyzabcde': raise TestFailed, 'string concatenation'
187if 'xyz'*3 != 'xyzxyzxyz': raise TestFailed, 'string repetition *3'
188if 0*'abcde' != '': raise TestFailed, 'string repetition 0*'
189if min('abc') != 'a' or max('abc') != 'c': raise TestFailed, 'min/max string'
Guido van Rossum85f18201992-11-27 22:53:50 +0000190if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass
191else: raise TestFailed, 'in/not in string'
Guido van Rossumb6775db1994-08-01 11:34:53 +0000192x = 'x'*103
193if '%s!'%x != x+'!': raise TestFailed, 'nasty string formatting bug'
Guido van Rossum85f18201992-11-27 22:53:50 +0000194
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000195#extended slices for strings
196a = '0123456789'
197vereq(a[::], a)
198vereq(a[::2], '02468')
199vereq(a[1::2], '13579')
200vereq(a[::-1],'9876543210')
201vereq(a[::-2], '97531')
202vereq(a[3::-2], '31')
203vereq(a[-100:100:], a)
204vereq(a[100:-100:-1], a[::-1])
205vereq(a[-100L:100L:2L], '02468')
206
207if 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'))
Tim Petersc411dba2002-07-16 21:35:23 +0000218
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000219
Guido van Rossum85f18201992-11-27 22:53:50 +0000220print '6.5.2 Tuples'
Guido van Rossumaa86e352003-04-19 18:15:10 +0000221# calling built-in types without argument must return empty
222if tuple() != (): raise TestFailed,'tuple() does not return ()'
Fred Drake132dce22000-12-12 23:11:42 +0000223if len(()) != 0: raise TestFailed, 'len(())'
224if len((1,)) != 1: raise TestFailed, 'len((1,))'
225if len((1,2,3,4,5,6)) != 6: raise TestFailed, 'len((1,2,3,4,5,6))'
226if (1,2)+(3,4) != (1,2,3,4): raise TestFailed, 'tuple concatenation'
227if (1,2)*3 != (1,2,1,2,1,2): raise TestFailed, 'tuple repetition *3'
228if 0*(1,2,3) != (): raise TestFailed, 'tuple repetition 0*'
229if min((1,2)) != 1 or max((1,2)) != 2: raise TestFailed, 'min/max tuple'
Guido van Rossum85f18201992-11-27 22:53:50 +0000230if 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
231else: raise TestFailed, 'in/not in tuple'
Neil Schemenauereff72442002-03-24 01:24:54 +0000232try: ()[0]
233except IndexError: pass
234else: raise TestFailed, "tuple index error didn't raise IndexError"
235x = ()
236x += ()
237if x != (): raise TestFailed, 'tuple inplace add from () to () failed'
238x += (1,)
239if x != (1,): raise TestFailed, 'tuple resize from () failed'
Guido van Rossum85f18201992-11-27 22:53:50 +0000240
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000241# extended slicing - subscript only for tuples
242a = (0,1,2,3,4)
243vereq(a[::], a)
244vereq(a[::2], (0,2,4))
245vereq(a[1::2], (1,3))
246vereq(a[::-1], (4,3,2,1,0))
247vereq(a[::-2], (4,2,0))
248vereq(a[3::-2], (3,1))
249vereq(a[-100:100:], a)
250vereq(a[100:-100:-1], a[::-1])
251vereq(a[-100L:100L:2L], (0,2,4))
252
Guido van Rossum10f36d92002-06-21 02:14:10 +0000253# Check that a specific bug in _PyTuple_Resize() is squashed.
254def f():
255 for i in range(1000):
256 yield i
257vereq(list(tuple(f())), range(1000))
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000258
Raymond Hettinger99285712003-04-24 16:52:47 +0000259# Verify that __getitem__ overrides are recognized by __iter__
260class T(tuple):
261 def __getitem__(self, key):
262 return str(key) + '!!!'
263vereq(iter(T()).next(), '0!!!')
264
Guido van Rossum85f18201992-11-27 22:53:50 +0000265print '6.5.3 Lists'
Guido van Rossumaa86e352003-04-19 18:15:10 +0000266# calling built-in types without argument must return empty
267if list() != []: raise TestFailed,'list() does not return []'
Fred Drake132dce22000-12-12 23:11:42 +0000268if len([]) != 0: raise TestFailed, 'len([])'
269if len([1,]) != 1: raise TestFailed, 'len([1,])'
270if len([1,2,3,4,5,6]) != 6: raise TestFailed, 'len([1,2,3,4,5,6])'
271if [1,2]+[3,4] != [1,2,3,4]: raise TestFailed, 'list concatenation'
272if [1,2]*3 != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3'
273if [1,2]*3L != [1,2,1,2,1,2]: raise TestFailed, 'list repetition *3L'
274if 0*[1,2,3] != []: raise TestFailed, 'list repetition 0*'
275if 0L*[1,2,3] != []: raise TestFailed, 'list repetition 0L*'
276if min([1,2]) != 1 or max([1,2]) != 2: raise TestFailed, 'min/max list'
Guido van Rossum85f18201992-11-27 22:53:50 +0000277if 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
278else: raise TestFailed, 'in/not in list'
Guido van Rossumaffd77f1998-07-16 15:29:06 +0000279a = [1, 2, 3, 4, 5]
280a[:-1] = a
281if a != [1, 2, 3, 4, 5, 5]:
Fred Drake004d5e62000-10-23 17:22:08 +0000282 raise TestFailed, "list self-slice-assign (head)"
Guido van Rossumaffd77f1998-07-16 15:29:06 +0000283a = [1, 2, 3, 4, 5]
284a[1:] = a
285if a != [1, 1, 2, 3, 4, 5]:
Fred Drake004d5e62000-10-23 17:22:08 +0000286 raise TestFailed, "list self-slice-assign (tail)"
Guido van Rossumaffd77f1998-07-16 15:29:06 +0000287a = [1, 2, 3, 4, 5]
288a[1:-1] = a
289if a != [1, 1, 2, 3, 4, 5, 5]:
Fred Drake004d5e62000-10-23 17:22:08 +0000290 raise TestFailed, "list self-slice-assign (center)"
Neil Schemenauereff72442002-03-24 01:24:54 +0000291try: [][0]
292except IndexError: pass
293else: raise TestFailed, "list index error didn't raise IndexError"
294try: [][0] = 5
295except IndexError: pass
296else: raise TestFailed, "list assignment index error didn't raise IndexError"
297try: [].pop()
298except IndexError: pass
299else: raise TestFailed, "empty list.pop() didn't raise IndexError"
300try: [1].pop(5)
301except IndexError: pass
302else: raise TestFailed, "[1].pop(5) didn't raise IndexError"
303try: [][0:1] = 5
304except TypeError: pass
305else: raise TestFailed, "bad list slice assignment didn't raise TypeError"
306try: [].extend(None)
307except TypeError: pass
308else: raise TestFailed, "list.extend(None) didn't raise TypeError"
309a = [1, 2, 3, 4]
310a *= 0
311if a != []:
312 raise TestFailed, "list inplace repeat"
Guido van Rossumaffd77f1998-07-16 15:29:06 +0000313
Michael W. Hudson5da854f2002-11-05 17:38:05 +0000314a = []
315a[:] = tuple(range(10))
316if a != range(10):
317 raise TestFailed, "assigning tuple to slice"
Guido van Rossum85f18201992-11-27 22:53:50 +0000318
319print '6.5.3a Additional list operations'
320a = [0,1,2,3,4]
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000321a[0L] = 1
322a[1L] = 2
323a[2L] = 3
Fred Drake132dce22000-12-12 23:11:42 +0000324if a != [1,2,3,3,4]: raise TestFailed, 'list item assignment [0L], [1L], [2L]'
Guido van Rossum85f18201992-11-27 22:53:50 +0000325a[0] = 5
326a[1] = 6
327a[2] = 7
Fred Drake132dce22000-12-12 23:11:42 +0000328if a != [5,6,7,3,4]: raise TestFailed, 'list item assignment [0], [1], [2]'
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000329a[-2L] = 88
330a[-1L] = 99
Fred Drake132dce22000-12-12 23:11:42 +0000331if a != [5,6,7,88,99]: raise TestFailed, 'list item assignment [-2L], [-1L]'
Guido van Rossum85f18201992-11-27 22:53:50 +0000332a[-2] = 8
333a[-1] = 9
Fred Drake132dce22000-12-12 23:11:42 +0000334if a != [5,6,7,8,9]: raise TestFailed, 'list item assignment [-2], [-1]'
Guido van Rossum85f18201992-11-27 22:53:50 +0000335a[:2] = [0,4]
336a[-3:] = []
337a[1:1] = [1,2,3]
Fred Drake132dce22000-12-12 23:11:42 +0000338if a != [0,1,2,3,4]: raise TestFailed, 'list slice assignment'
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000339a[ 1L : 4L] = [7,8,9]
Fred Drake132dce22000-12-12 23:11:42 +0000340if a != [0,7,8,9,4]: raise TestFailed, 'list slice assignment using long ints'
Guido van Rossum85f18201992-11-27 22:53:50 +0000341del a[1:4]
Fred Drake132dce22000-12-12 23:11:42 +0000342if a != [0,4]: raise TestFailed, 'list slice deletion'
Guido van Rossum85f18201992-11-27 22:53:50 +0000343del a[0]
Fred Drake132dce22000-12-12 23:11:42 +0000344if a != [4]: raise TestFailed, 'list item deletion [0]'
Guido van Rossum85f18201992-11-27 22:53:50 +0000345del a[-1]
Fred Drake132dce22000-12-12 23:11:42 +0000346if a != []: raise TestFailed, 'list item deletion [-1]'
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000347a=range(0,5)
348del a[1L:4L]
Fred Drake132dce22000-12-12 23:11:42 +0000349if a != [0,4]: raise TestFailed, 'list slice deletion'
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000350del a[0L]
Fred Drake132dce22000-12-12 23:11:42 +0000351if a != [4]: raise TestFailed, 'list item deletion [0]'
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000352del a[-1L]
Fred Drake132dce22000-12-12 23:11:42 +0000353if a != []: raise TestFailed, 'list item deletion [-1]'
Guido van Rossum85f18201992-11-27 22:53:50 +0000354a.append(0)
355a.append(1)
356a.append(2)
Fred Drake132dce22000-12-12 23:11:42 +0000357if a != [0,1,2]: raise TestFailed, 'list append'
Guido van Rossum85f18201992-11-27 22:53:50 +0000358a.insert(0, -2)
359a.insert(1, -1)
360a.insert(2,0)
Fred Drake132dce22000-12-12 23:11:42 +0000361if a != [-2,-1,0,0,1,2]: raise TestFailed, 'list insert'
Guido van Rossum3a3cca52003-04-14 20:58:14 +0000362b = a[:]
363b.insert(-2, "foo")
364b.insert(-200, "left")
365b.insert(200, "right")
366if b != ["left",-2,-1,0,0,"foo",1,2,"right"]: raise TestFailed, 'list insert2'
Fred Drake132dce22000-12-12 23:11:42 +0000367if a.count(0) != 2: raise TestFailed, ' list count'
368if a.index(0) != 2: raise TestFailed, 'list index'
Guido van Rossum85f18201992-11-27 22:53:50 +0000369a.remove(0)
Fred Drake132dce22000-12-12 23:11:42 +0000370if a != [-2,-1,0,1,2]: raise TestFailed, 'list remove'
Guido van Rossum85f18201992-11-27 22:53:50 +0000371a.reverse()
Fred Drake132dce22000-12-12 23:11:42 +0000372if a != [2,1,0,-1,-2]: raise TestFailed, 'list reverse'
Guido van Rossum85f18201992-11-27 22:53:50 +0000373a.sort()
Fred Drake132dce22000-12-12 23:11:42 +0000374if a != [-2,-1,0,1,2]: raise TestFailed, 'list sort'
Guido van Rossume61fa0a1993-10-22 13:56:35 +0000375def revcmp(a, b): return cmp(b, a)
376a.sort(revcmp)
Fred Drake132dce22000-12-12 23:11:42 +0000377if a != [2,1,0,-1,-2]: raise TestFailed, 'list sort with cmp func'
Guido van Rossumd151d341998-02-25 17:51:50 +0000378# The following dumps core in unpatched Python 1.5:
379def myComparison(x,y):
380 return cmp(x%3, y%7)
381z = range(12)
382z.sort(myComparison)
Guido van Rossum85f18201992-11-27 22:53:50 +0000383
Neal Norwitz6fc36c52002-06-13 22:23:06 +0000384try: z.sort(2)
385except TypeError: pass
386else: raise TestFailed, 'list sort compare function is not callable'
387
388def selfmodifyingComparison(x,y):
Tim Petersb9099c32002-11-12 22:08:10 +0000389 z.append(1)
Neal Norwitz6fc36c52002-06-13 22:23:06 +0000390 return cmp(x, y)
391try: z.sort(selfmodifyingComparison)
Tim Petersb9099c32002-11-12 22:08:10 +0000392except ValueError: pass
Neal Norwitz6fc36c52002-06-13 22:23:06 +0000393else: raise TestFailed, 'modifying list during sort'
394
395try: z.sort(lambda x, y: 's')
396except TypeError: pass
397else: raise TestFailed, 'list sort compare function does not return int'
398
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000399# Test extreme cases with long ints
400a = [0,1,2,3,4]
Fred Drake004d5e62000-10-23 17:22:08 +0000401if a[ -pow(2,128L): 3 ] != [0,1,2]:
402 raise TestFailed, "list slicing with too-small long integer"
403if a[ 3: pow(2,145L) ] != [3,4]:
404 raise TestFailed, "list slicing with too-large long integer"
Andrew M. Kuchling5ebfa2a2000-02-23 22:23:17 +0000405
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000406
407# extended slicing
408
409# subscript
410a = [0,1,2,3,4]
411vereq(a[::], a)
412vereq(a[::2], [0,2,4])
413vereq(a[1::2], [1,3])
414vereq(a[::-1], [4,3,2,1,0])
415vereq(a[::-2], [4,2,0])
416vereq(a[3::-2], [3,1])
417vereq(a[-100:100:], a)
418vereq(a[100:-100:-1], a[::-1])
419vereq(a[-100L:100L:2L], [0,2,4])
Michael W. Hudson589dc932002-06-11 13:38:42 +0000420vereq(a[1000:2000:2], [])
421vereq(a[-1000:-2000:-2], [])
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000422# deletion
423del a[::2]
424vereq(a, [1,3])
425a = range(5)
426del a[1::2]
427vereq(a, [0,2,4])
428a = range(5)
429del a[1::-2]
430vereq(a, [0,2,3,4])
Michael W. Hudson56796f62002-07-29 14:35:04 +0000431a = range(10)
432del a[::1000]
433vereq(a, [1, 2, 3, 4, 5, 6, 7, 8, 9])
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000434# assignment
435a = range(10)
436a[::2] = [-1]*5
437vereq(a, [-1, 1, -1, 3, -1, 5, -1, 7, -1, 9])
438a = range(10)
439a[::-4] = [10]*3
440vereq(a, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10])
441a = range(4)
442a[::-1] = a
443vereq(a, [3, 2, 1, 0])
Michael W. Hudson9c14bad2002-06-19 15:44:15 +0000444a = range(10)
445b = a[:]
446c = a[:]
447a[2:3] = ["two", "elements"]
448b[slice(2,3)] = ["two", "elements"]
449c[2:3:] = ["two", "elements"]
450vereq(a, b)
451vereq(a, c)
Michael W. Hudsona69c0302002-12-05 21:32:32 +0000452a = range(10)
453a[::2] = tuple(range(5))
454vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9])
455
Raymond Hettinger99285712003-04-24 16:52:47 +0000456# Verify that __getitem__ overrides are recognized by __iter__
457class L(list):
458 def __getitem__(self, key):
459 return str(key) + '!!!'
460vereq(iter(L()).next(), '0!!!')
461
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +0000462
Guido van Rossum85f18201992-11-27 22:53:50 +0000463print '6.6 Mappings == Dictionaries'
Guido van Rossumaa86e352003-04-19 18:15:10 +0000464# calling built-in types without argument must return empty
465if dict() != {}: raise TestFailed,'dict() does not return {}'
Guido van Rossum85f18201992-11-27 22:53:50 +0000466d = {}
Fred Drake132dce22000-12-12 23:11:42 +0000467if d.keys() != []: raise TestFailed, '{}.keys()'
Neil Schemenauereff72442002-03-24 01:24:54 +0000468if d.values() != []: raise TestFailed, '{}.values()'
469if d.items() != []: raise TestFailed, '{}.items()'
Fred Drake132dce22000-12-12 23:11:42 +0000470if d.has_key('a') != 0: raise TestFailed, '{}.has_key(\'a\')'
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000471if ('a' in d) != 0: raise TestFailed, "'a' in {}"
472if ('a' not in d) != 1: raise TestFailed, "'a' not in {}"
Fred Drake132dce22000-12-12 23:11:42 +0000473if len(d) != 0: raise TestFailed, 'len({})'
Guido van Rossum85f18201992-11-27 22:53:50 +0000474d = {'a': 1, 'b': 2}
Fred Drake132dce22000-12-12 23:11:42 +0000475if len(d) != 2: raise TestFailed, 'len(dict)'
Guido van Rossum85f18201992-11-27 22:53:50 +0000476k = d.keys()
477k.sort()
Fred Drake132dce22000-12-12 23:11:42 +0000478if k != ['a', 'b']: raise TestFailed, 'dict keys()'
Guido van Rossum85f18201992-11-27 22:53:50 +0000479if d.has_key('a') and d.has_key('b') and not d.has_key('c'): pass
480else: raise TestFailed, 'dict keys()'
Guido van Rossum0dbb4fb2001-04-20 16:50:40 +0000481if 'a' in d and 'b' in d and 'c' not in d: pass
482else: raise TestFailed, 'dict keys() # in/not in version'
Fred Drake132dce22000-12-12 23:11:42 +0000483if d['a'] != 1 or d['b'] != 2: raise TestFailed, 'dict item'
Guido van Rossum85f18201992-11-27 22:53:50 +0000484d['c'] = 3
485d['a'] = 4
Fred Drake132dce22000-12-12 23:11:42 +0000486if d['c'] != 3 or d['a'] != 4: raise TestFailed, 'dict item assignment'
Guido van Rossum85f18201992-11-27 22:53:50 +0000487del d['b']
Fred Drake132dce22000-12-12 23:11:42 +0000488if d != {'a': 4, 'c': 3}: raise TestFailed, 'dict item deletion'
Barry Warsaw41775382001-06-26 20:09:28 +0000489# dict.clear()
Guido van Rossumce1fa261997-06-02 23:14:00 +0000490d = {1:1, 2:2, 3:3}
491d.clear()
492if d != {}: raise TestFailed, 'dict clear'
Barry Warsaw41775382001-06-26 20:09:28 +0000493# dict.update()
Guido van Rossumce1fa261997-06-02 23:14:00 +0000494d.update({1:100})
495d.update({2:20})
496d.update({1:1, 2:2, 3:3})
497if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict update'
Barry Warsaw41775382001-06-26 20:09:28 +0000498d.clear()
499try: d.update(None)
500except AttributeError: pass
501else: raise TestFailed, 'dict.update(None), AttributeError expected'
502class 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]
509d.update(SimpleUserDict())
510if d != {1:1, 2:2, 3:3}: raise TestFailed, 'dict.update(instance)'
511d.clear()
512class FailingUserDict:
513 def keys(self):
514 raise ValueError
515try: d.update(FailingUserDict())
516except ValueError: pass
517else: raise TestFailed, 'dict.keys() expected ValueError'
518class FailingUserDict:
519 def keys(self):
520 class BogonIter:
521 def __iter__(self):
522 raise ValueError
523 return BogonIter()
524try: d.update(FailingUserDict())
525except ValueError: pass
526else: raise TestFailed, 'iter(dict.keys()) expected ValueError'
527class 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
542try: d.update(FailingUserDict())
543except ValueError: pass
544else: raise TestFailed, 'iter(dict.keys()).next() expected ValueError'
545class 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
561try: d.update(FailingUserDict())
562except ValueError: pass
563else: raise TestFailed, 'dict.update(), __getitem__ expected ValueError'
Raymond Hettingere33d3df2002-11-27 07:29:33 +0000564# dict.fromkeys()
565if dict.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
566 raise TestFailed, 'dict.fromkeys did not work as a class method'
567d = {}
568if d.fromkeys('abc') is d:
569 raise TestFailed, 'dict.fromkeys did not return a new dict'
570if d.fromkeys('abc') != {'a':None, 'b':None, 'c':None}:
571 raise TestFailed, 'dict.fromkeys failed with default value'
572if d.fromkeys((4,5),0) != {4:0, 5:0}:
573 raise TestFailed, 'dict.fromkeys failed with specified value'
574if d.fromkeys([]) != {}:
575 raise TestFailed, 'dict.fromkeys failed with null sequence'
576def g():
577 yield 1
578if d.fromkeys(g()) != {1:None}:
579 raise TestFailed, 'dict.fromkeys failed with a generator'
580try: {}.fromkeys(3)
581except TypeError: pass
582else: raise TestFailed, 'dict.fromkeys failed to raise TypeError'
583class dictlike(dict): pass
584if dictlike.fromkeys('a') != {'a':None}:
585 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
586if dictlike().fromkeys('a') != {'a':None}:
587 raise TestFailed, 'dictsubclass.fromkeys did not inherit'
588if type(dictlike.fromkeys('a')) is not dictlike:
589 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
590if type(dictlike().fromkeys('a')) is not dictlike:
591 raise TestFailed, 'dictsubclass.fromkeys created wrong type'
Raymond Hettingerb02bb5e2002-12-04 07:32:25 +0000592from UserDict import UserDict
593class mydict(dict):
Raymond Hettingerbabc83a2002-12-07 09:04:29 +0000594 def __new__(cls):
595 return UserDict()
Raymond Hettingere03e5b12002-12-07 08:10:51 +0000596ud = mydict.fromkeys('ab')
597if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict):
598 raise TestFailed, 'fromkeys did not instantiate using __new__'
Barry Warsaw41775382001-06-26 20:09:28 +0000599# dict.copy()
600d = {1:1, 2:2, 3:3}
Guido van Rossumce1fa261997-06-02 23:14:00 +0000601if d.copy() != {1:1, 2:2, 3:3}: raise TestFailed, 'dict copy'
602if {}.copy() != {}: raise TestFailed, 'empty dict copy'
Barry Warsaw9b887c71997-10-20 17:34:43 +0000603# dict.get()
Guido van Rossumfb5cef11997-10-20 20:10:43 +0000604d = {}
Fred Drake132dce22000-12-12 23:11:42 +0000605if d.get('c') is not None: raise TestFailed, 'missing {} get, no 2nd arg'
Guido van Rossumfb5cef11997-10-20 20:10:43 +0000606if d.get('c', 3) != 3: raise TestFailed, 'missing {} get, w/ 2nd arg'
Barry Warsaw9b887c71997-10-20 17:34:43 +0000607d = {'a' : 1, 'b' : 2}
Fred Drake132dce22000-12-12 23:11:42 +0000608if d.get('c') is not None: raise TestFailed, 'missing dict get, no 2nd arg'
Barry Warsaw9b887c71997-10-20 17:34:43 +0000609if d.get('c', 3) != 3: raise TestFailed, 'missing dict get, w/ 2nd arg'
610if d.get('a') != 1: raise TestFailed, 'present dict get, no 2nd arg'
611if d.get('a', 3) != 1: raise TestFailed, 'present dict get, w/ 2nd arg'
Guido van Rossum79c9b172000-08-08 16:13:23 +0000612# dict.setdefault()
613d = {}
Fred Drake132dce22000-12-12 23:11:42 +0000614if d.setdefault('key0') is not None:
Fred Drake004d5e62000-10-23 17:22:08 +0000615 raise TestFailed, 'missing {} setdefault, no 2nd arg'
Fred Drake132dce22000-12-12 23:11:42 +0000616if d.setdefault('key0') is not None:
Fred Drake004d5e62000-10-23 17:22:08 +0000617 raise TestFailed, 'present {} setdefault, no 2nd arg'
Guido van Rossum79c9b172000-08-08 16:13:23 +0000618d.setdefault('key', []).append(3)
Fred Drake132dce22000-12-12 23:11:42 +0000619if d['key'][0] != 3:
Fred Drake004d5e62000-10-23 17:22:08 +0000620 raise TestFailed, 'missing {} setdefault, w/ 2nd arg'
Guido van Rossum79c9b172000-08-08 16:13:23 +0000621d.setdefault('key', []).append(4)
Fred Drake132dce22000-12-12 23:11:42 +0000622if len(d['key']) != 2:
Fred Drake004d5e62000-10-23 17:22:08 +0000623 raise TestFailed, 'present {} setdefault, w/ 2nd arg'
Guido van Rossumb822c612000-12-12 22:02:59 +0000624# dict.popitem()
625for 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)
Guido van Rossum29d26062001-12-11 04:37:34 +0000648
Neil Schemenauereff72442002-03-24 01:24:54 +0000649d.clear()
650try: d.popitem()
651except KeyError: pass
652else: raise TestFailed, "{}.popitem doesn't raise KeyError"
653
Guido van Rossume027d982002-04-12 15:11:59 +0000654# Tests for pop with specified key
655d.clear()
656k, v = 'abc', 'def'
657d[k] = v
658try: d.pop('ghi')
659except KeyError: pass
660else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when k not in dictionary"
661
662if d.pop(k) != v: raise TestFailed, "{}.pop(k) doesn't find known key/value pair"
663if len(d) > 0: raise TestFailed, "{}.pop(k) failed to remove the specified pair"
664
665try: d.pop(k)
666except KeyError: pass
667else: raise TestFailed, "{}.pop(k) doesn't raise KeyError when dictionary is empty"
668
Neal Norwitzd5a65a72003-02-23 23:11:41 +0000669# verify longs/ints get same value when key > 32 bits (for 64-bit archs)
670# see SF bug #689659
671x = 4503599627370496L
672y = 4503599627370496
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +0000673h = {x: 'anything', y: 'something else'}
Neal Norwitzd5a65a72003-02-23 23:11:41 +0000674if h[x] != h[y]:
675 raise TestFailed, "long/int key should match"
676
Raymond Hettingera3e1e4c2003-03-06 23:54:28 +0000677if d.pop(k, v) != v: raise TestFailed, "{}.pop(k, v) doesn't return default value"
678d[k] = v
679if d.pop(k, 1) != v: raise TestFailed, "{}.pop(k, v) doesn't find known key/value pair"
680
Neil Schemenauereff72442002-03-24 01:24:54 +0000681d[1] = 1
682try:
683 for i in d:
Tim Peters863ac442002-04-16 01:38:40 +0000684 d[i+1] = 1
Neil Schemenauereff72442002-03-24 01:24:54 +0000685except RuntimeError:
686 pass
687else:
688 raise TestFailed, "changing dict size during iteration doesn't raise Error"
689
Guido van Rossum29d26062001-12-11 04:37:34 +0000690try: type(1, 2)
691except TypeError: pass
692else: raise TestFailed, 'type(), w/2 args expected TypeError'
693
694try: type(1, 2, 3, 4)
695except TypeError: pass
696else: raise TestFailed, 'type(), w/4 args expected TypeError'
Neil Schemenauereff72442002-03-24 01:24:54 +0000697
698print 'Buffers'
699try: buffer('asdf', -1)
700except ValueError: pass
701else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
702
703try: buffer(None)
704except TypeError: pass
705else: raise TestFailed, "buffer(None) should raise TypeError"
706
707a = buffer('asdf')
708hash(a)
709b = a * 5
710if a == b:
711 raise TestFailed, 'buffers should not be equal'
Fred Drake485f3402002-05-02 04:27:20 +0000712if str(b) != ('asdf' * 5):
713 raise TestFailed, 'repeated buffer has wrong content'
714if str(a * 0) != '':
715 raise TestFailed, 'repeated buffer zero times has wrong content'
716if str(a + buffer('def')) != 'asdfdef':
717 raise TestFailed, 'concatenation of buffers yields wrong content'
Neil Schemenauereff72442002-03-24 01:24:54 +0000718
719try: a[1] = 'g'
720except TypeError: pass
721else: raise TestFailed, "buffer assignment should raise TypeError"
722
723try: a[0:1] = 'g'
724except TypeError: pass
725else: raise TestFailed, "buffer slice assignment should raise TypeError"