• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""
2Tests common to list and UserList.UserList
3"""
4
5import sys
6import os
7from functools import cmp_to_key
8
9from test import support, seq_tests
10
11
12class CommonTest(seq_tests.CommonTest):
13
14    def test_init(self):
15        # Iterable arg is optional
16        self.assertEqual(self.type2test([]), self.type2test())
17
18        # Init clears previous values
19        a = self.type2test([1, 2, 3])
20        a.__init__()
21        self.assertEqual(a, self.type2test([]))
22
23        # Init overwrites previous values
24        a = self.type2test([1, 2, 3])
25        a.__init__([4, 5, 6])
26        self.assertEqual(a, self.type2test([4, 5, 6]))
27
28        # Mutables always return a new object
29        b = self.type2test(a)
30        self.assertNotEqual(id(a), id(b))
31        self.assertEqual(a, b)
32
33    def test_getitem_error(self):
34        a = []
35        msg = "list indices must be integers or slices"
36        with self.assertRaisesRegex(TypeError, msg):
37            a['a']
38
39    def test_setitem_error(self):
40        a = []
41        msg = "list indices must be integers or slices"
42        with self.assertRaisesRegex(TypeError, msg):
43            a['a'] = "python"
44
45    def test_repr(self):
46        l0 = []
47        l2 = [0, 1, 2]
48        a0 = self.type2test(l0)
49        a2 = self.type2test(l2)
50
51        self.assertEqual(str(a0), str(l0))
52        self.assertEqual(repr(a0), repr(l0))
53        self.assertEqual(repr(a2), repr(l2))
54        self.assertEqual(str(a2), "[0, 1, 2]")
55        self.assertEqual(repr(a2), "[0, 1, 2]")
56
57        a2.append(a2)
58        a2.append(3)
59        self.assertEqual(str(a2), "[0, 1, 2, [...], 3]")
60        self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]")
61
62    def test_repr_deep(self):
63        a = self.type2test([])
64        for i in range(sys.getrecursionlimit() + 100):
65            a = self.type2test([a])
66        self.assertRaises(RecursionError, repr, a)
67
68    def test_print(self):
69        d = self.type2test(range(200))
70        d.append(d)
71        d.extend(range(200,400))
72        d.append(d)
73        d.append(400)
74        try:
75            with open(support.TESTFN, "w") as fo:
76                fo.write(str(d))
77            with open(support.TESTFN, "r") as fo:
78                self.assertEqual(fo.read(), repr(d))
79        finally:
80            os.remove(support.TESTFN)
81
82    def test_set_subscript(self):
83        a = self.type2test(range(20))
84        self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 0), [1,2,3])
85        self.assertRaises(TypeError, a.__setitem__, slice(0, 10), 1)
86        self.assertRaises(ValueError, a.__setitem__, slice(0, 10, 2), [1,2])
87        self.assertRaises(TypeError, a.__getitem__, 'x', 1)
88        a[slice(2,10,3)] = [1,2,3]
89        self.assertEqual(a, self.type2test([0, 1, 1, 3, 4, 2, 6, 7, 3,
90                                            9, 10, 11, 12, 13, 14, 15,
91                                            16, 17, 18, 19]))
92
93    def test_reversed(self):
94        a = self.type2test(range(20))
95        r = reversed(a)
96        self.assertEqual(list(r), self.type2test(range(19, -1, -1)))
97        self.assertRaises(StopIteration, next, r)
98        self.assertEqual(list(reversed(self.type2test())),
99                         self.type2test())
100        # Bug 3689: make sure list-reversed-iterator doesn't have __len__
101        self.assertRaises(TypeError, len, reversed([1,2,3]))
102
103    def test_setitem(self):
104        a = self.type2test([0, 1])
105        a[0] = 0
106        a[1] = 100
107        self.assertEqual(a, self.type2test([0, 100]))
108        a[-1] = 200
109        self.assertEqual(a, self.type2test([0, 200]))
110        a[-2] = 100
111        self.assertEqual(a, self.type2test([100, 200]))
112        self.assertRaises(IndexError, a.__setitem__, -3, 200)
113        self.assertRaises(IndexError, a.__setitem__, 2, 200)
114
115        a = self.type2test([])
116        self.assertRaises(IndexError, a.__setitem__, 0, 200)
117        self.assertRaises(IndexError, a.__setitem__, -1, 200)
118        self.assertRaises(TypeError, a.__setitem__)
119
120        a = self.type2test([0,1,2,3,4])
121        a[0] = 1
122        a[1] = 2
123        a[2] = 3
124        self.assertEqual(a, self.type2test([1,2,3,3,4]))
125        a[0] = 5
126        a[1] = 6
127        a[2] = 7
128        self.assertEqual(a, self.type2test([5,6,7,3,4]))
129        a[-2] = 88
130        a[-1] = 99
131        self.assertEqual(a, self.type2test([5,6,7,88,99]))
132        a[-2] = 8
133        a[-1] = 9
134        self.assertEqual(a, self.type2test([5,6,7,8,9]))
135
136        msg = "list indices must be integers or slices"
137        with self.assertRaisesRegex(TypeError, msg):
138            a['a'] = "python"
139
140    def test_delitem(self):
141        a = self.type2test([0, 1])
142        del a[1]
143        self.assertEqual(a, [0])
144        del a[0]
145        self.assertEqual(a, [])
146
147        a = self.type2test([0, 1])
148        del a[-2]
149        self.assertEqual(a, [1])
150        del a[-1]
151        self.assertEqual(a, [])
152
153        a = self.type2test([0, 1])
154        self.assertRaises(IndexError, a.__delitem__, -3)
155        self.assertRaises(IndexError, a.__delitem__, 2)
156
157        a = self.type2test([])
158        self.assertRaises(IndexError, a.__delitem__, 0)
159
160        self.assertRaises(TypeError, a.__delitem__)
161
162    def test_setslice(self):
163        l = [0, 1]
164        a = self.type2test(l)
165
166        for i in range(-3, 4):
167            a[:i] = l[:i]
168            self.assertEqual(a, l)
169            a2 = a[:]
170            a2[:i] = a[:i]
171            self.assertEqual(a2, a)
172            a[i:] = l[i:]
173            self.assertEqual(a, l)
174            a2 = a[:]
175            a2[i:] = a[i:]
176            self.assertEqual(a2, a)
177            for j in range(-3, 4):
178                a[i:j] = l[i:j]
179                self.assertEqual(a, l)
180                a2 = a[:]
181                a2[i:j] = a[i:j]
182                self.assertEqual(a2, a)
183
184        aa2 = a2[:]
185        aa2[:0] = [-2, -1]
186        self.assertEqual(aa2, [-2, -1, 0, 1])
187        aa2[0:] = []
188        self.assertEqual(aa2, [])
189
190        a = self.type2test([1, 2, 3, 4, 5])
191        a[:-1] = a
192        self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 5]))
193        a = self.type2test([1, 2, 3, 4, 5])
194        a[1:] = a
195        self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5]))
196        a = self.type2test([1, 2, 3, 4, 5])
197        a[1:-1] = a
198        self.assertEqual(a, self.type2test([1, 1, 2, 3, 4, 5, 5]))
199
200        a = self.type2test([])
201        a[:] = tuple(range(10))
202        self.assertEqual(a, self.type2test(range(10)))
203
204        self.assertRaises(TypeError, a.__setitem__, slice(0, 1, 5))
205
206        self.assertRaises(TypeError, a.__setitem__)
207
208    def test_delslice(self):
209        a = self.type2test([0, 1])
210        del a[1:2]
211        del a[0:1]
212        self.assertEqual(a, self.type2test([]))
213
214        a = self.type2test([0, 1])
215        del a[1:2]
216        del a[0:1]
217        self.assertEqual(a, self.type2test([]))
218
219        a = self.type2test([0, 1])
220        del a[-2:-1]
221        self.assertEqual(a, self.type2test([1]))
222
223        a = self.type2test([0, 1])
224        del a[-2:-1]
225        self.assertEqual(a, self.type2test([1]))
226
227        a = self.type2test([0, 1])
228        del a[1:]
229        del a[:1]
230        self.assertEqual(a, self.type2test([]))
231
232        a = self.type2test([0, 1])
233        del a[1:]
234        del a[:1]
235        self.assertEqual(a, self.type2test([]))
236
237        a = self.type2test([0, 1])
238        del a[-1:]
239        self.assertEqual(a, self.type2test([0]))
240
241        a = self.type2test([0, 1])
242        del a[-1:]
243        self.assertEqual(a, self.type2test([0]))
244
245        a = self.type2test([0, 1])
246        del a[:]
247        self.assertEqual(a, self.type2test([]))
248
249    def test_append(self):
250        a = self.type2test([])
251        a.append(0)
252        a.append(1)
253        a.append(2)
254        self.assertEqual(a, self.type2test([0, 1, 2]))
255
256        self.assertRaises(TypeError, a.append)
257
258    def test_extend(self):
259        a1 = self.type2test([0])
260        a2 = self.type2test((0, 1))
261        a = a1[:]
262        a.extend(a2)
263        self.assertEqual(a, a1 + a2)
264
265        a.extend(self.type2test([]))
266        self.assertEqual(a, a1 + a2)
267
268        a.extend(a)
269        self.assertEqual(a, self.type2test([0, 0, 1, 0, 0, 1]))
270
271        a = self.type2test("spam")
272        a.extend("eggs")
273        self.assertEqual(a, list("spameggs"))
274
275        self.assertRaises(TypeError, a.extend, None)
276        self.assertRaises(TypeError, a.extend)
277
278        # overflow test. issue1621
279        class CustomIter:
280            def __iter__(self):
281                return self
282            def __next__(self):
283                raise StopIteration
284            def __length_hint__(self):
285                return sys.maxsize
286        a = self.type2test([1,2,3,4])
287        a.extend(CustomIter())
288        self.assertEqual(a, [1,2,3,4])
289
290
291    def test_insert(self):
292        a = self.type2test([0, 1, 2])
293        a.insert(0, -2)
294        a.insert(1, -1)
295        a.insert(2, 0)
296        self.assertEqual(a, [-2, -1, 0, 0, 1, 2])
297
298        b = a[:]
299        b.insert(-2, "foo")
300        b.insert(-200, "left")
301        b.insert(200, "right")
302        self.assertEqual(b, self.type2test(["left",-2,-1,0,0,"foo",1,2,"right"]))
303
304        self.assertRaises(TypeError, a.insert)
305
306    def test_pop(self):
307        a = self.type2test([-1, 0, 1])
308        a.pop()
309        self.assertEqual(a, [-1, 0])
310        a.pop(0)
311        self.assertEqual(a, [0])
312        self.assertRaises(IndexError, a.pop, 5)
313        a.pop(0)
314        self.assertEqual(a, [])
315        self.assertRaises(IndexError, a.pop)
316        self.assertRaises(TypeError, a.pop, 42, 42)
317        a = self.type2test([0, 10, 20, 30, 40])
318
319    def test_remove(self):
320        a = self.type2test([0, 0, 1])
321        a.remove(1)
322        self.assertEqual(a, [0, 0])
323        a.remove(0)
324        self.assertEqual(a, [0])
325        a.remove(0)
326        self.assertEqual(a, [])
327
328        self.assertRaises(ValueError, a.remove, 0)
329
330        self.assertRaises(TypeError, a.remove)
331
332        class BadExc(Exception):
333            pass
334
335        class BadCmp:
336            def __eq__(self, other):
337                if other == 2:
338                    raise BadExc()
339                return False
340
341        a = self.type2test([0, 1, 2, 3])
342        self.assertRaises(BadExc, a.remove, BadCmp())
343
344        class BadCmp2:
345            def __eq__(self, other):
346                raise BadExc()
347
348        d = self.type2test('abcdefghcij')
349        d.remove('c')
350        self.assertEqual(d, self.type2test('abdefghcij'))
351        d.remove('c')
352        self.assertEqual(d, self.type2test('abdefghij'))
353        self.assertRaises(ValueError, d.remove, 'c')
354        self.assertEqual(d, self.type2test('abdefghij'))
355
356        # Handle comparison errors
357        d = self.type2test(['a', 'b', BadCmp2(), 'c'])
358        e = self.type2test(d)
359        self.assertRaises(BadExc, d.remove, 'c')
360        for x, y in zip(d, e):
361            # verify that original order and values are retained.
362            self.assertIs(x, y)
363
364    def test_index(self):
365        super().test_index()
366        a = self.type2test([-2, -1, 0, 0, 1, 2])
367        a.remove(0)
368        self.assertRaises(ValueError, a.index, 2, 0, 4)
369        self.assertEqual(a, self.type2test([-2, -1, 0, 1, 2]))
370
371        # Test modifying the list during index's iteration
372        class EvilCmp:
373            def __init__(self, victim):
374                self.victim = victim
375            def __eq__(self, other):
376                del self.victim[:]
377                return False
378        a = self.type2test()
379        a[:] = [EvilCmp(a) for _ in range(100)]
380        # This used to seg fault before patch #1005778
381        self.assertRaises(ValueError, a.index, None)
382
383    def test_reverse(self):
384        u = self.type2test([-2, -1, 0, 1, 2])
385        u2 = u[:]
386        u.reverse()
387        self.assertEqual(u, [2, 1, 0, -1, -2])
388        u.reverse()
389        self.assertEqual(u, u2)
390
391        self.assertRaises(TypeError, u.reverse, 42)
392
393    def test_clear(self):
394        u = self.type2test([2, 3, 4])
395        u.clear()
396        self.assertEqual(u, [])
397
398        u = self.type2test([])
399        u.clear()
400        self.assertEqual(u, [])
401
402        u = self.type2test([])
403        u.append(1)
404        u.clear()
405        u.append(2)
406        self.assertEqual(u, [2])
407
408        self.assertRaises(TypeError, u.clear, None)
409
410    def test_copy(self):
411        u = self.type2test([1, 2, 3])
412        v = u.copy()
413        self.assertEqual(v, [1, 2, 3])
414
415        u = self.type2test([])
416        v = u.copy()
417        self.assertEqual(v, [])
418
419        # test that it's indeed a copy and not a reference
420        u = self.type2test(['a', 'b'])
421        v = u.copy()
422        v.append('i')
423        self.assertEqual(u, ['a', 'b'])
424        self.assertEqual(v, u + ['i'])
425
426        # test that it's a shallow, not a deep copy
427        u = self.type2test([1, 2, [3, 4], 5])
428        v = u.copy()
429        self.assertEqual(u, v)
430        self.assertIs(v[3], u[3])
431
432        self.assertRaises(TypeError, u.copy, None)
433
434    def test_sort(self):
435        u = self.type2test([1, 0])
436        u.sort()
437        self.assertEqual(u, [0, 1])
438
439        u = self.type2test([2,1,0,-1,-2])
440        u.sort()
441        self.assertEqual(u, self.type2test([-2,-1,0,1,2]))
442
443        self.assertRaises(TypeError, u.sort, 42, 42)
444
445        def revcmp(a, b):
446            if a == b:
447                return 0
448            elif a < b:
449                return 1
450            else: # a > b
451                return -1
452        u.sort(key=cmp_to_key(revcmp))
453        self.assertEqual(u, self.type2test([2,1,0,-1,-2]))
454
455        # The following dumps core in unpatched Python 1.5:
456        def myComparison(x,y):
457            xmod, ymod = x%3, y%7
458            if xmod == ymod:
459                return 0
460            elif xmod < ymod:
461                return -1
462            else: # xmod > ymod
463                return 1
464        z = self.type2test(range(12))
465        z.sort(key=cmp_to_key(myComparison))
466
467        self.assertRaises(TypeError, z.sort, 2)
468
469        def selfmodifyingComparison(x,y):
470            z.append(1)
471            if x == y:
472                return 0
473            elif x < y:
474                return -1
475            else: # x > y
476                return 1
477        self.assertRaises(ValueError, z.sort,
478                          key=cmp_to_key(selfmodifyingComparison))
479
480        self.assertRaises(TypeError, z.sort, 42, 42, 42, 42)
481
482    def test_slice(self):
483        u = self.type2test("spam")
484        u[:2] = "h"
485        self.assertEqual(u, list("ham"))
486
487    def test_iadd(self):
488        super().test_iadd()
489        u = self.type2test([0, 1])
490        u2 = u
491        u += [2, 3]
492        self.assertIs(u, u2)
493
494        u = self.type2test("spam")
495        u += "eggs"
496        self.assertEqual(u, self.type2test("spameggs"))
497
498        self.assertRaises(TypeError, u.__iadd__, None)
499
500    def test_imul(self):
501        super().test_imul()
502        s = self.type2test([])
503        oldid = id(s)
504        s *= 10
505        self.assertEqual(id(s), oldid)
506
507    def test_extendedslicing(self):
508        #  subscript
509        a = self.type2test([0,1,2,3,4])
510
511        #  deletion
512        del a[::2]
513        self.assertEqual(a, self.type2test([1,3]))
514        a = self.type2test(range(5))
515        del a[1::2]
516        self.assertEqual(a, self.type2test([0,2,4]))
517        a = self.type2test(range(5))
518        del a[1::-2]
519        self.assertEqual(a, self.type2test([0,2,3,4]))
520        a = self.type2test(range(10))
521        del a[::1000]
522        self.assertEqual(a, self.type2test([1, 2, 3, 4, 5, 6, 7, 8, 9]))
523        #  assignment
524        a = self.type2test(range(10))
525        a[::2] = [-1]*5
526        self.assertEqual(a, self.type2test([-1, 1, -1, 3, -1, 5, -1, 7, -1, 9]))
527        a = self.type2test(range(10))
528        a[::-4] = [10]*3
529        self.assertEqual(a, self.type2test([0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
530        a = self.type2test(range(4))
531        a[::-1] = a
532        self.assertEqual(a, self.type2test([3, 2, 1, 0]))
533        a = self.type2test(range(10))
534        b = a[:]
535        c = a[:]
536        a[2:3] = self.type2test(["two", "elements"])
537        b[slice(2,3)] = self.type2test(["two", "elements"])
538        c[2:3:] = self.type2test(["two", "elements"])
539        self.assertEqual(a, b)
540        self.assertEqual(a, c)
541        a = self.type2test(range(10))
542        a[::2] = tuple(range(5))
543        self.assertEqual(a, self.type2test([0, 1, 1, 3, 2, 5, 3, 7, 4, 9]))
544        # test issue7788
545        a = self.type2test(range(10))
546        del a[9::1<<333]
547
548    def test_constructor_exception_handling(self):
549        # Bug #1242657
550        class F(object):
551            def __iter__(self):
552                raise KeyboardInterrupt
553        self.assertRaises(KeyboardInterrupt, list, F())
554
555    def test_exhausted_iterator(self):
556        a = self.type2test([1, 2, 3])
557        exhit = iter(a)
558        empit = iter(a)
559        for x in exhit:  # exhaust the iterator
560            next(empit)  # not exhausted
561        a.append(9)
562        self.assertEqual(list(exhit), [])
563        self.assertEqual(list(empit), [9])
564        self.assertEqual(a, self.type2test([1, 2, 3, 9]))
565