1"""
2Tests common to tuple, list and UserList.UserList
3"""
4
5import unittest
6import sys
7from test import test_support as support
8
9# Various iterables
10# This is used for checking the constructor (here and in test_deque.py)
11def iterfunc(seqn):
12    'Regular generator'
13    for i in seqn:
14        yield i
15
16class Sequence:
17    'Sequence using __getitem__'
18    def __init__(self, seqn):
19        self.seqn = seqn
20    def __getitem__(self, i):
21        return self.seqn[i]
22
23class IterFunc:
24    'Sequence using iterator protocol'
25    def __init__(self, seqn):
26        self.seqn = seqn
27        self.i = 0
28    def __iter__(self):
29        return self
30    def next(self):
31        if self.i >= len(self.seqn): raise StopIteration
32        v = self.seqn[self.i]
33        self.i += 1
34        return v
35
36class IterGen:
37    'Sequence using iterator protocol defined with a generator'
38    def __init__(self, seqn):
39        self.seqn = seqn
40        self.i = 0
41    def __iter__(self):
42        for val in self.seqn:
43            yield val
44
45class IterNextOnly:
46    'Missing __getitem__ and __iter__'
47    def __init__(self, seqn):
48        self.seqn = seqn
49        self.i = 0
50    def next(self):
51        if self.i >= len(self.seqn): raise StopIteration
52        v = self.seqn[self.i]
53        self.i += 1
54        return v
55
56class IterNoNext:
57    'Iterator missing next()'
58    def __init__(self, seqn):
59        self.seqn = seqn
60        self.i = 0
61    def __iter__(self):
62        return self
63
64class IterGenExc:
65    'Test propagation of exceptions'
66    def __init__(self, seqn):
67        self.seqn = seqn
68        self.i = 0
69    def __iter__(self):
70        return self
71    def next(self):
72        3 // 0
73
74class IterFuncStop:
75    'Test immediate stop'
76    def __init__(self, seqn):
77        pass
78    def __iter__(self):
79        return self
80    def next(self):
81        raise StopIteration
82
83from itertools import chain, imap
84def itermulti(seqn):
85    'Test multiple tiers of iterators'
86    return chain(imap(lambda x:x, iterfunc(IterGen(Sequence(seqn)))))
87
88class LyingTuple(tuple):
89    def __iter__(self):
90        yield 1
91
92class LyingList(list):
93    def __iter__(self):
94        yield 1
95
96class CommonTest(unittest.TestCase):
97    # The type to be tested
98    type2test = None
99
100    def test_constructors(self):
101        l0 = []
102        l1 = [0]
103        l2 = [0, 1]
104
105        u = self.type2test()
106        u0 = self.type2test(l0)
107        u1 = self.type2test(l1)
108        u2 = self.type2test(l2)
109
110        uu = self.type2test(u)
111        uu0 = self.type2test(u0)
112        uu1 = self.type2test(u1)
113        uu2 = self.type2test(u2)
114
115        v = self.type2test(tuple(u))
116        class OtherSeq:
117            def __init__(self, initseq):
118                self.__data = initseq
119            def __len__(self):
120                return len(self.__data)
121            def __getitem__(self, i):
122                return self.__data[i]
123        s = OtherSeq(u0)
124        v0 = self.type2test(s)
125        self.assertEqual(len(v0), len(s))
126
127        s = "this is also a sequence"
128        vv = self.type2test(s)
129        self.assertEqual(len(vv), len(s))
130
131        # Create from various iteratables
132        for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
133            for g in (Sequence, IterFunc, IterGen,
134                      itermulti, iterfunc):
135                self.assertEqual(self.type2test(g(s)), self.type2test(s))
136            self.assertEqual(self.type2test(IterFuncStop(s)), self.type2test())
137            self.assertEqual(self.type2test(c for c in "123"), self.type2test("123"))
138            self.assertRaises(TypeError, self.type2test, IterNextOnly(s))
139            self.assertRaises(TypeError, self.type2test, IterNoNext(s))
140            self.assertRaises(ZeroDivisionError, self.type2test, IterGenExc(s))
141
142        # Issue #23757
143        self.assertEqual(self.type2test(LyingTuple((2,))), self.type2test((1,)))
144        self.assertEqual(self.type2test(LyingList([2])), self.type2test([1]))
145
146    def test_truth(self):
147        self.assertFalse(self.type2test())
148        self.assertTrue(self.type2test([42]))
149
150    def test_getitem(self):
151        u = self.type2test([0, 1, 2, 3, 4])
152        for i in xrange(len(u)):
153            self.assertEqual(u[i], i)
154            self.assertEqual(u[long(i)], i)
155        for i in xrange(-len(u), -1):
156            self.assertEqual(u[i], len(u)+i)
157            self.assertEqual(u[long(i)], len(u)+i)
158        self.assertRaises(IndexError, u.__getitem__, -len(u)-1)
159        self.assertRaises(IndexError, u.__getitem__, len(u))
160        self.assertRaises(ValueError, u.__getitem__, slice(0,10,0))
161
162        u = self.type2test()
163        self.assertRaises(IndexError, u.__getitem__, 0)
164        self.assertRaises(IndexError, u.__getitem__, -1)
165
166        self.assertRaises(TypeError, u.__getitem__)
167
168        a = self.type2test([10, 11])
169        self.assertEqual(a[0], 10)
170        self.assertEqual(a[1], 11)
171        self.assertEqual(a[-2], 10)
172        self.assertEqual(a[-1], 11)
173        self.assertRaises(IndexError, a.__getitem__, -3)
174        self.assertRaises(IndexError, a.__getitem__, 3)
175
176    def test_getslice(self):
177        l = [0, 1, 2, 3, 4]
178        u = self.type2test(l)
179
180        self.assertEqual(u[0:0], self.type2test())
181        self.assertEqual(u[1:2], self.type2test([1]))
182        self.assertEqual(u[-2:-1], self.type2test([3]))
183        self.assertEqual(u[-1000:1000], u)
184        self.assertEqual(u[1000:-1000], self.type2test([]))
185        self.assertEqual(u[:], u)
186        self.assertEqual(u[1:None], self.type2test([1, 2, 3, 4]))
187        self.assertEqual(u[None:3], self.type2test([0, 1, 2]))
188
189        # Extended slices
190        self.assertEqual(u[::], u)
191        self.assertEqual(u[::2], self.type2test([0, 2, 4]))
192        self.assertEqual(u[1::2], self.type2test([1, 3]))
193        self.assertEqual(u[::-1], self.type2test([4, 3, 2, 1, 0]))
194        self.assertEqual(u[::-2], self.type2test([4, 2, 0]))
195        self.assertEqual(u[3::-2], self.type2test([3, 1]))
196        self.assertEqual(u[3:3:-2], self.type2test([]))
197        self.assertEqual(u[3:2:-2], self.type2test([3]))
198        self.assertEqual(u[3:1:-2], self.type2test([3]))
199        self.assertEqual(u[3:0:-2], self.type2test([3, 1]))
200        self.assertEqual(u[::-100], self.type2test([4]))
201        self.assertEqual(u[100:-100:], self.type2test([]))
202        self.assertEqual(u[-100:100:], u)
203        self.assertEqual(u[100:-100:-1], u[::-1])
204        self.assertEqual(u[-100:100:-1], self.type2test([]))
205        self.assertEqual(u[-100L:100L:2L], self.type2test([0, 2, 4]))
206
207        # Test extreme cases with long ints
208        a = self.type2test([0,1,2,3,4])
209        self.assertEqual(a[ -pow(2,128L): 3 ], self.type2test([0,1,2]))
210        self.assertEqual(a[ 3: pow(2,145L) ], self.type2test([3,4]))
211
212        self.assertRaises(TypeError, u.__getslice__)
213
214    def test_contains(self):
215        u = self.type2test([0, 1, 2])
216        for i in u:
217            self.assertIn(i, u)
218        for i in min(u)-1, max(u)+1:
219            self.assertNotIn(i, u)
220
221        self.assertRaises(TypeError, u.__contains__)
222
223    def test_contains_fake(self):
224        class AllEq:
225            # Sequences must use rich comparison against each item
226            # (unless "is" is true, or an earlier item answered)
227            # So instances of AllEq must be found in all non-empty sequences.
228            def __eq__(self, other):
229                return True
230            __hash__ = None # Can't meet hash invariant requirements
231        self.assertNotIn(AllEq(), self.type2test([]))
232        self.assertIn(AllEq(), self.type2test([1]))
233
234    def test_contains_order(self):
235        # Sequences must test in-order.  If a rich comparison has side
236        # effects, these will be visible to tests against later members.
237        # In this test, the "side effect" is a short-circuiting raise.
238        class DoNotTestEq(Exception):
239            pass
240        class StopCompares:
241            def __eq__(self, other):
242                raise DoNotTestEq
243
244        checkfirst = self.type2test([1, StopCompares()])
245        self.assertIn(1, checkfirst)
246        checklast = self.type2test([StopCompares(), 1])
247        self.assertRaises(DoNotTestEq, checklast.__contains__, 1)
248
249    def test_len(self):
250        self.assertEqual(len(self.type2test()), 0)
251        self.assertEqual(len(self.type2test([])), 0)
252        self.assertEqual(len(self.type2test([0])), 1)
253        self.assertEqual(len(self.type2test([0, 1, 2])), 3)
254
255    def test_minmax(self):
256        u = self.type2test([0, 1, 2])
257        self.assertEqual(min(u), 0)
258        self.assertEqual(max(u), 2)
259
260    def test_addmul(self):
261        u1 = self.type2test([0])
262        u2 = self.type2test([0, 1])
263        self.assertEqual(u1, u1 + self.type2test())
264        self.assertEqual(u1, self.type2test() + u1)
265        self.assertEqual(u1 + self.type2test([1]), u2)
266        self.assertEqual(self.type2test([-1]) + u1, self.type2test([-1, 0]))
267        self.assertEqual(self.type2test(), u2*0)
268        self.assertEqual(self.type2test(), 0*u2)
269        self.assertEqual(self.type2test(), u2*0L)
270        self.assertEqual(self.type2test(), 0L*u2)
271        self.assertEqual(u2, u2*1)
272        self.assertEqual(u2, 1*u2)
273        self.assertEqual(u2, u2*1L)
274        self.assertEqual(u2, 1L*u2)
275        self.assertEqual(u2+u2, u2*2)
276        self.assertEqual(u2+u2, 2*u2)
277        self.assertEqual(u2+u2, u2*2L)
278        self.assertEqual(u2+u2, 2L*u2)
279        self.assertEqual(u2+u2+u2, u2*3)
280        self.assertEqual(u2+u2+u2, 3*u2)
281
282        class subclass(self.type2test):
283            pass
284        u3 = subclass([0, 1])
285        self.assertEqual(u3, u3*1)
286        self.assertIsNot(u3, u3*1)
287
288    def test_iadd(self):
289        u = self.type2test([0, 1])
290        u += self.type2test()
291        self.assertEqual(u, self.type2test([0, 1]))
292        u += self.type2test([2, 3])
293        self.assertEqual(u, self.type2test([0, 1, 2, 3]))
294        u += self.type2test([4, 5])
295        self.assertEqual(u, self.type2test([0, 1, 2, 3, 4, 5]))
296
297        u = self.type2test("spam")
298        u += self.type2test("eggs")
299        self.assertEqual(u, self.type2test("spameggs"))
300
301    def test_imul(self):
302        u = self.type2test([0, 1])
303        u *= 3
304        self.assertEqual(u, self.type2test([0, 1, 0, 1, 0, 1]))
305
306    def test_getitemoverwriteiter(self):
307        # Verify that __getitem__ overrides are not recognized by __iter__
308        class T(self.type2test):
309            def __getitem__(self, key):
310                return str(key) + '!!!'
311        self.assertEqual(iter(T((1,2))).next(), 1)
312
313    def test_repeat(self):
314        for m in xrange(4):
315            s = tuple(range(m))
316            for n in xrange(-3, 5):
317                self.assertEqual(self.type2test(s*n), self.type2test(s)*n)
318            self.assertEqual(self.type2test(s)*(-4), self.type2test([]))
319            self.assertEqual(id(s), id(s*1))
320
321    def test_bigrepeat(self):
322        import sys
323        if sys.maxint <= 2147483647:
324            x = self.type2test([0])
325            x *= 2**16
326            self.assertRaises(MemoryError, x.__mul__, 2**16)
327            if hasattr(x, '__imul__'):
328                self.assertRaises(MemoryError, x.__imul__, 2**16)
329
330    def test_subscript(self):
331        a = self.type2test([10, 11])
332        self.assertEqual(a.__getitem__(0L), 10)
333        self.assertEqual(a.__getitem__(1L), 11)
334        self.assertEqual(a.__getitem__(-2L), 10)
335        self.assertEqual(a.__getitem__(-1L), 11)
336        self.assertRaises(IndexError, a.__getitem__, -3)
337        self.assertRaises(IndexError, a.__getitem__, 3)
338        self.assertEqual(a.__getitem__(slice(0,1)), self.type2test([10]))
339        self.assertEqual(a.__getitem__(slice(1,2)), self.type2test([11]))
340        self.assertEqual(a.__getitem__(slice(0,2)), self.type2test([10, 11]))
341        self.assertEqual(a.__getitem__(slice(0,3)), self.type2test([10, 11]))
342        self.assertEqual(a.__getitem__(slice(3,5)), self.type2test([]))
343        self.assertRaises(ValueError, a.__getitem__, slice(0, 10, 0))
344        self.assertRaises(TypeError, a.__getitem__, 'x')
345
346    def test_count(self):
347        a = self.type2test([0, 1, 2])*3
348        self.assertEqual(a.count(0), 3)
349        self.assertEqual(a.count(1), 3)
350        self.assertEqual(a.count(3), 0)
351
352        self.assertRaises(TypeError, a.count)
353
354        class BadExc(Exception):
355            pass
356
357        class BadCmp:
358            def __eq__(self, other):
359                if other == 2:
360                    raise BadExc()
361                return False
362
363        self.assertRaises(BadExc, a.count, BadCmp())
364
365    def test_index(self):
366        u = self.type2test([0, 1])
367        self.assertEqual(u.index(0), 0)
368        self.assertEqual(u.index(1), 1)
369        self.assertRaises(ValueError, u.index, 2)
370
371        u = self.type2test([-2, -1, 0, 0, 1, 2])
372        self.assertEqual(u.count(0), 2)
373        self.assertEqual(u.index(0), 2)
374        self.assertEqual(u.index(0, 2), 2)
375        self.assertEqual(u.index(-2, -10), 0)
376        self.assertEqual(u.index(0, 3), 3)
377        self.assertEqual(u.index(0, 3, 4), 3)
378        self.assertRaises(ValueError, u.index, 2, 0, -10)
379
380        self.assertRaises(TypeError, u.index)
381
382        class BadExc(Exception):
383            pass
384
385        class BadCmp:
386            def __eq__(self, other):
387                if other == 2:
388                    raise BadExc()
389                return False
390
391        a = self.type2test([0, 1, 2, 3])
392        self.assertRaises(BadExc, a.index, BadCmp())
393
394        a = self.type2test([-2, -1, 0, 0, 1, 2])
395        self.assertEqual(a.index(0), 2)
396        self.assertEqual(a.index(0, 2), 2)
397        self.assertEqual(a.index(0, -4), 2)
398        self.assertEqual(a.index(-2, -10), 0)
399        self.assertEqual(a.index(0, 3), 3)
400        self.assertEqual(a.index(0, -3), 3)
401        self.assertEqual(a.index(0, 3, 4), 3)
402        self.assertEqual(a.index(0, -3, -2), 3)
403        self.assertEqual(a.index(0, -4*sys.maxint, 4*sys.maxint), 2)
404        self.assertRaises(ValueError, a.index, 0, 4*sys.maxint,-4*sys.maxint)
405        self.assertRaises(ValueError, a.index, 2, 0, -10)
406
407    def test_free_after_iterating(self):
408        support.check_free_after_iterating(self, iter, self.type2test)
409        support.check_free_after_iterating(self, reversed, self.type2test)
410