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