Debian Codegraph @

pypy/module/itertools/test/test_itertools.py

raw symbols SCIP
1 import py
2 import pytest
3
4
5 class AppTestItertools(object):
6 spaceconfig = dict(usemodules=['itertools'])
7
8 def test_count(self):
9 import itertools
10
11 it = itertools.count()
12 for x in range(10):
13 assert next(it) == x
14
15 def test_count_firstval(self):
16 import itertools
17
18 it = itertools.count(3)
19 for x in range(10):
20 assert next(it) == x + 3
21
22 def test_count_repr(self):
23 import itertools
24
25 it = itertools.count(123)
26 assert repr(it) == 'count(123)'
27 next(it)
28 assert repr(it) == 'count(124)'
29 it = itertools.count(12.1, 1.0)
30 assert repr(it) == 'count(12.1, 1.0)'
31
32 def test_count_invalid(self):
33 import itertools
34
35 raises(TypeError, itertools.count, None)
36 raises(TypeError, itertools.count, 'a')
37 raises(TypeError, itertools.count, [])
38
39 def test_count_subclass_repr(self):
40 import itertools
41 class subclass(itertools.count):
42 pass
43 assert repr(subclass(123)) == 'subclass(123)'
44
45 def test_repeat(self):
46 import itertools
47
48 o = object()
49 it = itertools.repeat(o)
50
51 for x in range(10):
52 assert o is next(it)
53
54 def test_repeat_times(self):
55 import itertools
56
57 times = 10
58 it = itertools.repeat(None, times)
59 for i in range(times):
60 next(it)
61 raises(StopIteration, next, it)
62
63 #---does not work in CPython 2.5
64 #it = itertools.repeat(None, None)
65 #for x in range(10):
66 # it.next() # Should be no StopIteration
67
68 it = itertools.repeat(None, 0)
69 raises(StopIteration, next, it)
70 raises(StopIteration, next, it)
71
72 it = itertools.repeat(None, -1)
73 raises(StopIteration, next, it)
74 raises(StopIteration, next, it)
75
76 def test_repeat_overflow(self):
77 import itertools
78 import sys
79
80 raises(OverflowError, itertools.repeat, None, sys.maxsize + 1)
81
82 def test_repeat_repr(self):
83 import itertools
84
85 it = itertools.repeat('foobar')
86 assert repr(it) == "repeat('foobar')"
87 next(it)
88 assert repr(it) == "repeat('foobar')"
89
90 it = itertools.repeat('foobar', 10)
91 assert repr(it) == "repeat('foobar', 10)"
92 next(it)
93 assert repr(it) == "repeat('foobar', 9)"
94 list(it)
95 assert repr(it) == "repeat('foobar', 0)"
96
97 def test_repeat_len(self):
98 import itertools
99 import _operator as operator
100
101 r = itertools.repeat('a', 15)
102 next(r)
103 raises(TypeError, "len(itertools.repeat('xkcd'))")
104
105 r = itertools.repeat('a', -3)
106 assert operator.length_hint(r, 3) == 0
107
108 def test_repeat_subclass_repr(self):
109 import itertools
110 class subclass(itertools.repeat):
111 pass
112 assert repr(subclass('foobar')) == "subclass('foobar')"
113
114 def test_takewhile(self):
115 import itertools
116
117 it = itertools.takewhile(bool, [])
118 raises(StopIteration, next, it)
119
120 it = itertools.takewhile(bool, [False, True, True])
121 raises(StopIteration, next, it)
122
123 it = itertools.takewhile(bool, [1, 2, 3, 0, 1, 1])
124 for x in [1, 2, 3]:
125 assert next(it) == x
126
127 raises(StopIteration, next, it)
128
129 def test_takewhile_wrongargs(self):
130 import itertools
131
132 it = itertools.takewhile(None, [1])
133 raises(TypeError, next, it)
134
135 raises(TypeError, itertools.takewhile, bool, None)
136
137 def test_takewhile_subclass_kwarg(self):
138 from itertools import takewhile
139 class subclass_with_new(takewhile):
140 def __new__(cls, predicate, iterable, newarg=None):
141 self = super().__new__(cls, predicate, iterable)
142 self.newarg = newarg
143 return self
144 u = subclass_with_new(bool, [1, 2], newarg=3)
145 assert u.newarg == 3
146 assert next(u) == 1
147
148 class subclass_with_init(takewhile):
149 def __init__(self, predicate, iterable, newarg=None):
150 self.newarg = newarg
151 u = subclass_with_init(bool, [1, 2], newarg=3)
152 assert u.newarg == 3
153 assert next(u) == 1
154
155 with raises(TypeError) as e:
156 u = takewhile(bool, [1, 2], newargs=3)
157 assert str(e.value) == "takewhile() takes no keyword arguments"
158
159 class subclass(takewhile):
160 pass
161 with raises(TypeError) as e:
162 subclass(bool, [1, 2], newarg=3)
163
164
165 def test_dropwhile(self):
166 import itertools
167
168 it = itertools.dropwhile(bool, [])
169 raises(StopIteration, next, it)
170
171 it = itertools.dropwhile(bool, [True, True, True])
172 raises(StopIteration, next, it)
173
174 def is_odd(arg):
175 return (arg % 2 == 1)
176
177 it = itertools.dropwhile(is_odd, [1, 3, 5, 2, 4, 6])
178 for x in [2, 4, 6]:
179 assert next(it) == x
180
181 raises(StopIteration, next, it)
182
183 def test_dropwhile_wrongargs(self):
184 import itertools
185
186 it = itertools.dropwhile(None, [1])
187 raises(TypeError, next, it)
188
189 raises(TypeError, itertools.dropwhile, bool, None)
190
191 def test_dropwhile_subclass_kwarg(self):
192 from itertools import dropwhile
193 class subclass_with_new(dropwhile):
194 def __new__(cls, predicate, iterable, newarg=None):
195 self = super().__new__(cls, predicate, iterable)
196 self.newarg = newarg
197 return self
198 u = subclass_with_new(lambda a: False, [1, 2], newarg=3)
199 assert u.newarg == 3
200 assert list(u) == [1, 2]
201
202 class subclass_with_init(dropwhile):
203 def __init__(self, predicate, iterable, newarg=None):
204 self.newarg = newarg
205 u = subclass_with_init(lambda a: False, [1, 2], newarg=3)
206 assert u.newarg == 3
207 assert list(u) == [1, 2]
208
209 with raises(TypeError) as e:
210 u = dropwhile(lambda a: False, [1, 2], newargs=3)
211 assert str(e.value) == "dropwhile() takes no keyword arguments"
212
213 class subclass(dropwhile):
214 pass
215 with raises(TypeError) as e:
216 subclass(lambda a: True, [1, 2], newarg=3)
217
218 def test_filterfalse(self):
219 import itertools
220
221 it = itertools.filterfalse(None, [])
222 raises(StopIteration, next, it)
223
224 it = itertools.filterfalse(None, [1, 0, 2, 3, 0])
225 for x in [0, 0]:
226 assert next(it) == x
227 raises(StopIteration, next, it)
228
229 def is_odd(arg):
230 return (arg % 2 == 1)
231
232 it = itertools.filterfalse(is_odd, [1, 2, 3, 4, 5, 6])
233 for x in [2, 4, 6]:
234 assert next(it) == x
235 raises(StopIteration, next, it)
236
237 def test_filterfalse_reduce(self):
238 import itertools
239 it = iter([1, 2, 3, 4, 5])
240 f = itertools.filterfalse(None, it)
241 assert f.__reduce__() == (itertools.filterfalse, (None, it))
242 f = itertools.filterfalse(bool, it)
243 assert f.__reduce__() == (itertools.filterfalse, (bool, it))
244
245 def test_filterfalse_wrongargs(self):
246 import itertools
247
248 it = itertools.filterfalse(0, [1])
249 raises(TypeError, next, it)
250
251 raises(TypeError, itertools.filterfalse, bool, None)
252
253 def test_filterfalse_subclass_kwarg(self):
254 from itertools import filterfalse
255 class subclass_with_new(filterfalse):
256 def __new__(cls, f, v, newarg=None):
257 self = super().__new__(cls, f, v)
258 self.newarg = newarg
259 return self
260 u = subclass_with_new(lambda a: False, [1, 2], newarg=3)
261 assert u.newarg == 3
262 assert list(u) == [1, 2]
263
264 class subclass_with_init(filterfalse):
265 def __init__(self, f, v, newarg=None):
266 self.newarg = newarg
267 u = subclass_with_init(lambda a: False, [1, 2], newarg=3)
268 assert u.newarg == 3
269 assert list(u) == [1, 2]
270
271 with raises(TypeError) as e:
272 u = filterfalse()
273 # CPython has a worse error message (filterfalse() -> filterfalse)
274 assert str(e.value) == "filterfalse() expected 2 arguments, got 0", str(e.value)
275
276 with raises(TypeError) as e:
277 u = filterfalse(None, [1, 2], newargs=3)
278 assert str(e.value) == "filterfalse() takes no keyword arguments"
279
280 class subclass(filterfalse):
281 pass
282 with raises(TypeError) as e:
283 subclass(None, [1, 2], newarg=3)
284
285 def test_islice(self):
286 import itertools
287
288 it = itertools.islice([], 0)
289 raises(StopIteration, next, it)
290
291 it = itertools.islice([1, 2, 3], 0)
292 raises(StopIteration, next, it)
293
294 it = itertools.islice([1, 2, 3, 4, 5], 3)
295 for x in [1, 2, 3]:
296 assert next(it) == x
297 raises(StopIteration, next, it)
298
299 it = itertools.islice([1, 2, 3, 4, 5], 1, 3)
300 for x in [2, 3]:
301 assert next(it) == x
302 raises(StopIteration, next, it)
303
304 it = itertools.islice([1, 2, 3, 4, 5], 0, 3, 2)
305 for x in [1, 3]:
306 assert next(it) == x
307 raises(StopIteration, next, it)
308
309 # Do not allow floats
310 raises(ValueError, itertools.islice, [1, 2, 3, 4, 5], 0.0, 3.0, 2.0)
311
312 it = itertools.islice([1, 2, 3], 0, None)
313 for x in [1, 2, 3]:
314 assert next(it) == x
315 raises(StopIteration, next, it)
316
317 assert list(itertools.islice(range(100), 10, 3)) == []
318
319 # new in 2.5: start=None or step=None
320 assert list(itertools.islice(range(10), None)) == list(range(10))
321 assert list(itertools.islice(range(10), None,None)) == list(range(10))
322 assert list(itertools.islice(range(10), None,None,None)) == list(range(10))
323
324 it = itertools.islice([0, 1, 2], None, None, 2)
325 assert list(it) == [0, 2]
326
327 import weakref
328 for args in [(1,), (None,), (0, None, 2)]:
329 it = (x for x in (1, 2, 3))
330 wr = weakref.ref(it)
331 it = itertools.islice(it, *args)
332 assert wr() is not None
333 list(it) # exhaust the iterator
334 import gc; gc.collect()
335 assert wr() is None
336 raises(StopIteration, next, it)
337
338 def test_islice_dropitems_exact(self):
339 import itertools
340
341 it = iter("abcdefghij")
342 itertools.islice(it, 2, 2) # doesn't eagerly drop anything
343 assert next(it) == "a"
344 itertools.islice(it, 3, 8, 2) # doesn't eagerly drop anything
345 assert next(it) == "b"
346 assert next(it) == "c"
347
348 it = iter("abcdefghij")
349 x = next(itertools.islice(it, 2, 3), None) # drops 2 items
350 assert x == "c"
351 assert next(it) == "d"
352
353 it = iter("abcdefghij")
354 x = next(itertools.islice(it, 3, 8, 2), None) # drops 3 items
355 assert x == "d"
356 assert next(it) == "e"
357
358 it = iter("abcdefghij")
359 x = next(itertools.islice(it, None, 8), None) # drops 0 items
360 assert x == "a"
361 assert next(it) == "b"
362
363 it = iter("abcdefghij")
364 x = next(itertools.islice(it, 3, 2), None) # drops 3 items
365 assert x is None
366 assert next(it) == "d"
367
368 it = iter("abcdefghij")
369 islc = itertools.islice(it, 3, 7, 2)
370 assert next(islc) == "d" # drops 0, 1, 2, returns item #3
371 assert next(it) == "e"
372 assert next(islc) == "g" # drops the 4th and return item #5
373 assert next(it) == "h"
374 raises(StopIteration, next, islc) # drops the 6th and raise
375 assert next(it) == "j"
376
377 it = iter("abcdefghij")
378 islc = itertools.islice(it, 3, 4, 3)
379 assert next(islc) == "d" # drops 0, 1, 2, returns item #3
380 assert next(it) == "e"
381 raises(StopIteration, next, islc) # item #4 is 'stop', so just raise
382 assert next(it) == "f"
383
384 def test_islice_overflow(self):
385 import itertools
386 import sys
387 raises((OverflowError, ValueError), # ValueError on top of CPython
388 itertools.islice, [], sys.maxsize + 1)
389
390 def test_islice_intlike_args(self):
391 import itertools
392
393 class IntLike(object):
394 def __init__(self, value):
395 self.value = value
396 def __index__(self):
397 return self.value
398
399 it = itertools.islice([1, 2, 3, 4, 5], IntLike(0), IntLike(3), IntLike(2))
400 for x in [1, 3]:
401 assert next(it) == x
402 raises(StopIteration, next, it)
403
404 def test_islice_wrongargs(self):
405 import itertools
406
407 raises(TypeError, itertools.islice, None, 0)
408
409 raises(ValueError, itertools.islice, [], -1)
410
411 raises(ValueError, itertools.islice, [], -1, 0)
412 raises(ValueError, itertools.islice, [], 0, -1)
413
414 raises(ValueError, itertools.islice, [], 0, 0, -1)
415 raises(ValueError, itertools.islice, [], 0, 0, 0)
416
417 raises(TypeError, itertools.islice, [], 0, 0, 0, 0)
418
419 # why not TypeError? Because CPython
420 raises(ValueError, itertools.islice, [], "a", 1, 2)
421 raises(ValueError, itertools.islice, [], 0, "a", 2)
422 raises(ValueError, itertools.islice, [], 0, 1, "a")
423
424 def test_islice_subclass_kwarg(self):
425 from itertools import islice
426 class subclass_with_new(islice):
427 def __new__(cls, iterable, startstop, args, newarg=None):
428 self = super().__new__(cls, iterable, startstop, args)
429 self.newarg = newarg
430 return self
431 u = subclass_with_new([1, 2], 0, 3, newarg=3)
432 assert u.newarg == 3
433 assert next(u) == 1
434
435 class subclass_with_init(islice):
436 def __init__(self, iterable, startstop, args, newarg=None):
437 self.newarg = newarg
438 u = subclass_with_init([1, 2], 0, 3, newarg=3)
439 assert u.newarg == 3
440 assert next(u) == 1
441
442 with raises(TypeError) as e:
443 u = islice([1, 2], 0, 3, newargs=3)
444 assert str(e.value) == "islice() takes no keyword arguments"
445
446 class subclass(islice):
447 pass
448 with raises(TypeError) as e:
449 subclass([1, 2], newarg=3)
450
451 def test_islice_big_step(self):
452 import itertools, sys
453 islice = itertools.islice(itertools.count(), 1, 10, sys.maxsize)
454 assert list(islice) == [1]
455
456 def test_chain(self):
457 import itertools
458
459 it = itertools.chain()
460 raises(StopIteration, next, it)
461 raises(StopIteration, next, it)
462
463 it = itertools.chain([1, 2, 3])
464 for x in [1, 2, 3]:
465 assert next(it) == x
466 raises(StopIteration, next, it)
467
468 it = itertools.chain([1, 2, 3], [4], [5, 6])
469 for x in [1, 2, 3, 4, 5, 6]:
470 assert next(it) == x
471 raises(StopIteration, next, it)
472
473 it = itertools.chain([], [], [1], [])
474 assert next(it) == 1
475 raises(StopIteration, next, it)
476
477 def test_chain_subclass_kwarg(self):
478 from itertools import chain
479 class subclass_with_new(chain):
480 def __new__(cls, arg, newarg=None):
481 self = super().__new__(cls, arg)
482 self.newarg = newarg
483 return self
484 u = subclass_with_new([1, 2], newarg=3)
485 assert u.newarg == 3
486 assert next(u) == 1
487
488 class subclass_with_init(chain):
489 def __init__(self, arg, newarg=None):
490 self.newarg = newarg
491 u = subclass_with_init([1, 2], newarg=3)
492 assert u.newarg == 3
493 assert next(u) == 1
494
495 with raises(TypeError) as e:
496 u = chain([1, 2], [3], newargs=3)
497 assert str(e.value) == "chain() takes no keyword arguments"
498
499 class subclass(chain):
500 pass
501 with raises(TypeError) as e:
502 subclass([1, 2], newarg=3)
503
504
505 def test_cycle(self):
506 import itertools
507
508 it = itertools.cycle([])
509 raises(StopIteration, next, it)
510
511 it = itertools.cycle([1, 2, 3])
512 for x in [1, 2, 3, 1, 2, 3, 1, 2, 3]:
513 assert next(it) == x
514
515 def test_cycle_subclass_kwarg(self):
516 from itertools import cycle
517 class subclass_with_new(cycle):
518 def __new__(cls, v, newarg=None):
519 self = super().__new__(cls, v)
520 self.newarg = newarg
521 return self
522 u = subclass_with_new([1, 2], newarg=3)
523 assert u.newarg == 3
524 assert next(u) == 1
525
526 class subclass_with_init(cycle):
527 def __init__(self, v, newarg=None):
528 self.newarg = newarg
529 u = subclass_with_init([1, 2], newarg=3)
530 assert u.newarg == 3
531 assert next(u) == 1
532
533 with raises(TypeError) as e:
534 u = cycle()
535
536 with raises(TypeError) as e:
537 u = cycle([1, 2], newargs=3)
538 assert str(e.value) == "cycle() takes no keyword arguments"
539
540 class subclass(cycle):
541 pass
542 with raises(TypeError) as e:
543 subclass([1, 2], newarg=3)
544
545 def test_starmap(self):
546 import itertools
547 import _operator as operator
548
549 it = itertools.starmap(operator.add, [])
550 raises(StopIteration, next, it)
551
552 it = itertools.starmap(operator.add, [(0, 1), (2, 3), (4, 5)])
553 for x in [1, 5, 9]:
554 assert next(it) == x
555 raises(StopIteration, next, it)
556
557 assert list(itertools.starmap(operator.add, [iter((40,2))])) == [42]
558
559 def test_starmap_wrongargs(self):
560 import itertools
561
562 it = itertools.starmap(None, [(1, )])
563 raises(TypeError, next, it)
564
565 it = itertools.starmap(None, [])
566 raises(StopIteration, next, it)
567
568 it = itertools.starmap(bool, [0])
569 raises(TypeError, next, it)
570
571 def test_starmap_subclass_kwarg(self):
572 from itertools import starmap
573 import _operator as operator
574 class subclass_with_new(starmap):
575 def __new__(cls, f, v, newarg=None):
576 self = super().__new__(cls, f, v)
577 self.newarg = newarg
578 return self
579 u = subclass_with_new(operator.add, [[1, 2]], newarg=3)
580 assert u.newarg == 3
581 assert next(u) == 3
582
583 class subclass_with_init(starmap):
584 def __init__(self, f, v, newarg=None):
585 self.newarg = newarg
586 u = subclass_with_init(operator.add, [[1, 2]], newarg=3)
587 assert u.newarg == 3
588 assert next(u) == 3
589
590 with raises(TypeError) as e:
591 u = starmap()
592 # CPython has a worse error message (starmap() -> starmap)
593 assert str(e.value) == "starmap() expected 2 arguments, got 0", str(e.value)
594
595 with raises(TypeError) as e:
596 u = starmap(operator.add, [[1, 2]], newargs=3)
597 assert str(e.value) == "starmap() takes no keyword arguments"
598
599 class subclass(starmap):
600 pass
601 with raises(TypeError) as e:
602 subclass(operator.add, [[1, 2]], newarg=3)
603
604 def test_tee(self):
605 import itertools
606
607 it1, it2 = itertools.tee([])
608 raises(StopIteration, next, it1)
609 raises(StopIteration, next, it2)
610
611 it1, it2 = itertools.tee([1, 2, 3])
612 for x in [1, 2]:
613 assert next(it1) == x
614 for x in [1, 2, 3]:
615 assert next(it2) == x
616 assert next(it1) == 3
617 raises(StopIteration, next, it1)
618 raises(StopIteration, next, it2)
619
620 assert itertools.tee([], 0) == ()
621
622 iterators = itertools.tee([1, 2, 3], 10)
623 for it in iterators:
624 for x in [1, 2, 3]:
625 assert next(it) == x
626 raises(StopIteration, next, it)
627
628 def test_tee_wrongargs(self):
629 import itertools
630
631 raises(TypeError, itertools.tee, 0)
632 raises(ValueError, itertools.tee, [], -1)
633 raises(TypeError, itertools.tee, [], None)
634
635 def test_tee_optimization(self):
636 import itertools
637
638 a, b = itertools.tee(iter('foobar'))
639 c, d = itertools.tee(b)
640 assert c is b
641 assert a is not c
642 assert a is not d
643 assert c is not d
644 res = list(a)
645 assert res == list('foobar')
646 res = list(c)
647 assert res == list('foobar')
648 res = list(d)
649 assert res == list('foobar')
650
651 def test_tee_copy_bug(self):
652 from itertools import tee
653 class Coll:
654 def __iter__(self):
655 return It()
656
657 def __copy__(self):
658 return self
659
660 class It:
661 def __copy__(self):
662 return It()
663
664 def __next__(self):
665 return 1
666
667 iterator1, iterator2 = tee(Coll())
668 assert isinstance(iterator1, It)
669
670 def test_tee_instantiate(self):
671 import itertools
672
673 a, b = itertools.tee(iter('foobar'))
674 c = type(a)(a)
675 assert a is not b
676 assert a is not c
677 assert b is not c
678 res = list(a)
679 assert res == list('foobar')
680 res = list(b)
681 assert res == list('foobar')
682 res = list(c)
683 assert res == list('foobar')
684
685 def test_groupby(self):
686 import itertools
687
688 it = itertools.groupby([])
689 raises(StopIteration, next, it)
690
691 it = itertools.groupby([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
692 for x in [1, 2, 3, 4]:
693 k, g = next(it)
694 assert k == x
695 assert len(list(g)) == x
696 raises(StopIteration, next, g)
697 raises(StopIteration, next ,it)
698
699 it = itertools.groupby([0, 1, 2, 3, 4, 5], None)
700 for x in [0, 1, 2, 3, 4, 5]:
701 k, g = next(it)
702 assert k == x
703 assert next(g) == x
704 raises(StopIteration, next, g)
705 raises(StopIteration, next, it)
706
707 # consumes after group started
708 it = itertools.groupby([0, 0, 0, 0, 1])
709 k1, g1 = next(it)
710 assert next(g1) == 0
711 k2, g2 = next(it)
712 raises(StopIteration, next, g1)
713 assert next(g2) == 1
714 raises(StopIteration, next, g2)
715
716 # skips with not started group
717 it = itertools.groupby([0, 0, 1])
718 k1, g1 = next(it)
719 k2, g2 = next(it)
720 raises(StopIteration, next, g1)
721 assert next(g2) == 1
722 raises(StopIteration, next, g2)
723
724 it = itertools.groupby([0, 1, 2])
725 k1, g1 = next(it)
726 k2, g2 = next(it)
727 k2, g3 = next(it)
728 raises(StopIteration, next, g1)
729 raises(StopIteration, next, g2)
730 assert next(g3) == 2
731
732 def half_floor(x):
733 return x // 2
734 it = itertools.groupby([0, 1, 2, 3, 4, 5], half_floor)
735 for x in [0, 1, 2]:
736 k, g = next(it)
737 assert k == x
738 assert half_floor(next(g)) == x
739 assert half_floor(next(g)) == x
740 raises(StopIteration, next, g)
741 raises(StopIteration, next, it)
742
743 # keyword argument
744 it = itertools.groupby([0, 1, 2, 3, 4, 5], key = half_floor)
745 for x in [0, 1, 2]:
746 k, g = next(it)
747 assert k == x
748 assert list(g) == [x*2, x*2+1]
749 raises(StopIteration, next, it)
750
751 # Grouping is not based on key identity
752 class NeverEqual(object):
753 def __eq__(self, other):
754 return False
755 objects = [NeverEqual(), NeverEqual(), NeverEqual()]
756 it = itertools.groupby(objects)
757 for x in objects:
758 print("Trying", x)
759 k, g = next(it)
760 assert k is x
761 assert next(g) is x
762 raises(StopIteration, next, g)
763 raises(StopIteration, next, it)
764
765 # Grouping is based on key equality
766 class AlwaysEqual(object):
767 def __eq__(self, other):
768 return True
769 objects = [AlwaysEqual(), AlwaysEqual(), AlwaysEqual()]
770 it = itertools.groupby(objects)
771 k, g = next(it)
772 assert k is objects[0]
773 for x in objects:
774 assert next(g) is x
775 raises(StopIteration, next, g)
776 raises(StopIteration, next, it)
777
778 # inner iterator is used after advancing the groupby iterator
779 s = list(zip('AABBBAAAA', range(9)))
780 it = itertools.groupby(s, key=lambda x: x[0])
781 _, g1 = next(it)
782 _, g2 = next(it)
783 _, g3 = next(it)
784 assert list(g1) == []
785 assert g1.__reduce__() == (iter, ((),))
786 assert list(g2) == []
787 assert g2.__reduce__() == (iter, ((),))
788 assert next(g3) == ('A', 5)
789 list(it) # exhaust the groupby iterator
790 assert list(g3) == []
791 assert g3.__reduce__() == (iter, ((),))
792
793 def test_groupby_wrongargs(self):
794 import itertools
795
796 raises(TypeError, itertools.groupby, 0)
797 it = itertools.groupby([0], 1)
798 raises(TypeError, next, it)
799
800 def test_groupby_question_43905804(self):
801 # http://stackoverflow.com/questions/43905804/
802 # Superseded by https://bugs.python.org/issue30346
803 import itertools
804
805 inputs = ((x > 5, x) for x in range(10))
806 (_, a), (_, b) = itertools.groupby(inputs, key=lambda x: x[0])
807 a = list(a)
808 b = list(b)
809 assert a == []
810 assert b == [] # Before Python 3.7: assert b == [(True, 9)]
811
812 def test_groupby_crash(self):
813 # see http://bugs.python.org/issue30347
814 from itertools import groupby
815 def f(n):
816 if n == 5:
817 list(b)
818 return n != 6
819 for (k, b) in groupby(range(10), f):
820 list(b) # shouldn't crash
821
822 def test_iterables(self):
823 import itertools
824
825 iterables = [
826 itertools.chain(),
827 itertools.count(),
828 itertools.cycle([]),
829 itertools.dropwhile(bool, []),
830 itertools.groupby([]),
831 itertools.filterfalse(None, []),
832 itertools.islice([], 0),
833 itertools.repeat(None),
834 itertools.starmap(bool, []),
835 itertools.takewhile(bool, []),
836 itertools.tee([])[0],
837 itertools.tee([])[1],
838 ]
839
840 for it in iterables:
841 assert hasattr(it, '__iter__')
842 assert iter(it) is it
843 assert hasattr(it, '__next__')
844 assert callable(it.__next__)
845
846 def test_docstrings(self):
847 import itertools
848
849 assert itertools.__doc__
850 methods = [
851 itertools.chain,
852 itertools.count,
853 itertools.cycle,
854 itertools.dropwhile,
855 itertools.groupby,
856 itertools.filterfalse,
857 itertools.islice,
858 itertools.repeat,
859 itertools.starmap,
860 itertools.takewhile,
861 itertools.tee,
862 ]
863 for method in methods:
864 assert method.__doc__
865
866 def test_tee_weakrefable(self):
867 import itertools, weakref
868
869 a, b = itertools.tee(iter('abc'))
870 ref = weakref.ref(b)
871 assert ref() is b
872
873 def test_tee_bug1(self):
874 import itertools
875 a, b = itertools.tee('abcde')
876 x = next(a)
877 assert x == 'a'
878 c, d = itertools.tee(a)
879 x = next(c)
880 assert x == 'b'
881 x = next(d)
882 assert x == 'b'
883
884 def test_tee_defines_copy(self):
885 import itertools
886 a, b = itertools.tee('abc')
887 c = b.__copy__()
888 assert list(a) == ['a', 'b', 'c']
889 assert list(b) == ['a', 'b', 'c']
890 assert list(c) == ['a', 'b', 'c']
891 a, = itertools.tee('abc', 1)
892 x = next(a)
893 assert x == 'a'
894 b = a.__copy__()
895 x = next(a)
896 assert x == 'b'
897 x = next(b)
898 assert x == 'b'
899
900 def test_tee_function_uses_copy(self):
901 import itertools
902 class MyIterator(object):
903 def __iter__(self):
904 return self
905 def __next__(self):
906 raise NotImplementedError
907 def __copy__(self):
908 return iter('def')
909 my = MyIterator()
910 a, = itertools.tee(my, 1)
911 assert a is my
912 a, b = itertools.tee(my)
913 assert a is my
914 assert b is not my
915 assert list(b) == ['d', 'e', 'f']
916
917 def test_tee_function_empty(self):
918 import itertools
919 assert itertools.tee('abc', 0) == ()
920 a, = itertools.tee('abc', 1)
921 assert itertools.tee(a, 0) == ()
922
923
924 class AppTestItertools26(object):
925 spaceconfig = dict(usemodules=['itertools'])
926
927 def test_count_overflow(self):
928 import itertools, sys
929 it = itertools.count(sys.maxsize - 1)
930 assert next(it) == sys.maxsize - 1
931 assert next(it) == sys.maxsize
932 assert next(it) == sys.maxsize + 1
933 it = itertools.count(sys.maxsize + 1)
934 assert next(it) == sys.maxsize + 1
935 assert next(it) == sys.maxsize + 2
936 it = itertools.count(-sys.maxsize-2)
937 assert next(it) == -sys.maxsize - 2
938 assert next(it) == -sys.maxsize - 1
939 assert next(it) == -sys.maxsize
940 assert next(it) == -sys.maxsize + 1
941 it = itertools.count(0, sys.maxsize)
942 assert next(it) == sys.maxsize * 0
943 assert next(it) == sys.maxsize * 1
944 assert next(it) == sys.maxsize * 2
945 it = itertools.count(0, sys.maxsize + 1)
946 assert next(it) == (sys.maxsize + 1) * 0
947 assert next(it) == (sys.maxsize + 1) * 1
948 assert next(it) == (sys.maxsize + 1) * 2
949
950 def test_chain_fromiterable(self):
951 import itertools
952 l = [[1, 2, 3], [4], [5, 6]]
953 it = itertools.chain.from_iterable(l)
954 assert list(it) == sum(l, [])
955
956 def test_combinations(self):
957 from itertools import combinations
958
959 raises(TypeError, combinations, "abc")
960 raises(TypeError, combinations, "abc", 2, 1)
961 raises(TypeError, combinations, None)
962 raises(ValueError, combinations, "abc", -2)
963 assert list(combinations(range(4), 3)) == [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]
964
965 def test_ziplongest(self):
966 from itertools import zip_longest, islice, count
967 for args in [
968 ['abc', range(6)],
969 [range(6), 'abc'],
970 [range(100), range(200,210), range(300,305)],
971 [range(100), range(0), range(300,305), range(120), range(150)],
972 [range(100), range(0), range(300,305), range(120), range(0)],
973 ]:
974 # target = map(None, *args) <- this raises a py3k warning
975 # this is the replacement:
976 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
977 for i in range(max(map(len, args)))]
978 assert list(zip_longest(*args)) == target
979 assert list(zip_longest(*args, **{})) == target
980
981 # Replace None fills with 'X'
982 target = [tuple((e is None and 'X' or e) for e in t) for t in target]
983 assert list(zip_longest(*args, **dict(fillvalue='X'))) == target
984
985 # take 3 from infinite input
986 assert (list(islice(zip_longest('abcdef', count()),3)) ==
987 list(zip('abcdef', range(3))))
988
989 assert list(zip_longest()) == list(zip())
990 assert list(zip_longest([])) == list(zip([]))
991 assert list(zip_longest('abcdef')) == list(zip('abcdef'))
992
993 assert (list(zip_longest('abc', 'defg', **{})) ==
994 list(zip(list('abc') + [None], 'defg'))) # empty keyword dict
995 raises(TypeError, zip_longest, 3)
996 raises(TypeError, zip_longest, range(3), 3)
997
998 for stmt in [
999 "zip_longest('abc', fv=1)",
1000 "zip_longest('abc', fillvalue=1, bogus_keyword=None)",
1001 ]:
1002 try:
1003 eval(stmt, globals(), locals())
1004 except TypeError:
1005 pass
1006 else:
1007 self.fail('Did not raise Type in: ' + stmt)
1008
1009 def test_zip_longest2(self):
1010 import itertools
1011 class Repeater(object):
1012 # this class is similar to itertools.repeat
1013 def __init__(self, o, t, e):
1014 self.o = o
1015 self.t = int(t)
1016 self.e = e
1017 def __iter__(self): # its iterator is itself
1018 return self
1019 def __next__(self):
1020 if self.t > 0:
1021 self.t -= 1
1022 return self.o
1023 else:
1024 raise self.e
1025
1026 # Formerly this code in would fail in debug mode
1027 # with Undetected Error and Stop Iteration
1028 r1 = Repeater(1, 3, StopIteration)
1029 r2 = Repeater(2, 4, StopIteration)
1030 def run(r1, r2):
1031 result = []
1032 for i, j in itertools.zip_longest(r1, r2, fillvalue=0):
1033 result.append((i, j))
1034 return result
1035 assert run(r1, r2) == [(1,2), (1,2), (1,2), (0,2)]
1036
1037 def test_product(self):
1038 from itertools import product
1039 l = [1, 2]
1040 m = ['a', 'b']
1041
1042 prodlist = product(l, m)
1043 res = [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
1044 assert list(prodlist) == res
1045 assert list(product()) == [()]
1046 assert list(product([])) == []
1047 assert list(product(iter(l), iter(m))) == res
1048
1049 prodlist = product(iter(l), iter(m))
1050 assert list(prodlist) == [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
1051
1052 def test_product_repeat(self):
1053 from itertools import product
1054 l = [1, 2]
1055 m = ['a', 'b']
1056
1057 prodlist = product(l, m, repeat=2)
1058 ans = [(1, 'a', 1, 'a'), (1, 'a', 1, 'b'), (1, 'a', 2, 'a'),
1059 (1, 'a', 2, 'b'), (1, 'b', 1, 'a'), (1, 'b', 1, 'b'),
1060 (1, 'b', 2, 'a'), (1, 'b', 2, 'b'), (2, 'a', 1, 'a'),
1061 (2, 'a', 1, 'b'), (2, 'a', 2, 'a'), (2, 'a', 2, 'b'),
1062 (2, 'b', 1, 'a'), (2, 'b', 1, 'b'), (2, 'b', 2, 'a'),
1063 (2, 'b', 2, 'b')]
1064 assert list(prodlist) == ans
1065
1066 raises(TypeError, product, [], foobar=3)
1067
1068 def test_product_diff_sizes(self):
1069 from itertools import product
1070 l = [1, 2]
1071 m = ['a']
1072
1073 prodlist = product(l, m)
1074 assert list(prodlist) == [(1, 'a'), (2, 'a')]
1075
1076 l = [1]
1077 m = ['a', 'b']
1078 prodlist = product(l, m)
1079 assert list(prodlist) == [(1, 'a'), (1, 'b')]
1080
1081 assert list(product([], [1, 2, 3])) == []
1082 assert list(product([1, 2, 3], [])) == []
1083
1084 def test_product_toomany_args(self):
1085 from itertools import product
1086 l = [1, 2]
1087 m = ['a']
1088 raises(TypeError, product, l, m, repeat=1, foo=2)
1089
1090 def test_product_empty(self):
1091 from itertools import product
1092 prod = product('abc', repeat=0)
1093 assert next(prod) == ()
1094 raises (StopIteration, next, prod)
1095
1096 def test_product_powers_of_two(self):
1097 from itertools import product
1098 assert list(product()) == [()]
1099 assert list(product('ab')) == [('a',), ('b',)]
1100 assert list(product('ab', 'cd')) == [
1101 ('a', 'c'), ('a', 'd'),
1102 ('b', 'c'), ('b', 'd')]
1103 assert list(product('ab', 'cd', 'ef')) == [
1104 ('a', 'c', 'e'), ('a', 'c', 'f'),
1105 ('a', 'd', 'e'), ('a', 'd', 'f'),
1106 ('b', 'c', 'e'), ('b', 'c', 'f'),
1107 ('b', 'd', 'e'), ('b', 'd', 'f')]
1108
1109 def test_product_empty_item(self):
1110 from itertools import product
1111 assert list(product('')) == []
1112 assert list(product('ab', '')) == []
1113 assert list(product('', 'cd')) == []
1114 assert list(product('ab', 'cd', '')) == []
1115 assert list(product('ab', '', 'ef')) == []
1116 assert list(product('', 'cd', 'ef')) == []
1117
1118 def test_product_setstate(self):
1119 # test that indices are properly clamped to the length of the tuples
1120 from itertools import product
1121 p = product((1, 2),(3,))
1122 # will access tuple element 1 if not clamped
1123 p.__setstate__((0, 0x1000))
1124 assert next(p) == (2, 3)
1125 # test that empty tuple in the list will result in an
1126 # immediate StopIteration
1127 p = product((1, 2), (), (3,))
1128 # will access tuple element 1 if not clamped
1129 p.__setstate__((0, 0, 0x1000))
1130 raises(StopIteration, next, p)
1131
1132 def test_permutations(self):
1133 from itertools import permutations
1134 assert list(permutations('AB')) == [('A', 'B'), ('B', 'A')]
1135 assert list(permutations('ABCD', 2)) == [
1136 ('A', 'B'),
1137 ('A', 'C'),
1138 ('A', 'D'),
1139 ('B', 'A'),
1140 ('B', 'C'),
1141 ('B', 'D'),
1142 ('C', 'A'),
1143 ('C', 'B'),
1144 ('C', 'D'),
1145 ('D', 'A'),
1146 ('D', 'B'),
1147 ('D', 'C'),
1148 ]
1149 assert list(permutations(range(3))) == [
1150 (0, 1, 2),
1151 (0, 2, 1),
1152 (1, 0, 2),
1153 (1, 2, 0),
1154 (2, 0, 1),
1155 (2, 1, 0),
1156 ]
1157 assert list(permutations([])) == [()]
1158 assert list(permutations([], 0)) == [()]
1159 assert list(permutations([], 1)) == []
1160 assert list(permutations(range(3), 4)) == []
1161 #
1162 perm = list(permutations([1, 2, 3, 4]))
1163 assert perm == [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2),
1164 (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3),
1165 (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1),
1166 (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1),
1167 (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2),
1168 (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
1169
1170 def test_permutations_r(self):
1171 from itertools import permutations
1172 perm = list(permutations([1, 2, 3, 4], 2))
1173 assert perm == [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1),
1174 (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
1175
1176 def test_permutations_r_gt_n(self):
1177 from itertools import permutations
1178 perm = permutations([1, 2], 3)
1179 raises(StopIteration, next, perm)
1180
1181 def test_permutations_neg_r(self):
1182 from itertools import permutations
1183 raises(ValueError, permutations, [1, 2], -1)
1184
1185
1186 class AppTestItertools27(object):
1187 spaceconfig = {"usemodules": ['itertools', 'struct', 'binascii']}
1188
1189 def test_compress(self):
1190 import itertools
1191 it = itertools.compress(['a', 'b', 'c'], [0, 1, 0])
1192 assert list(it) == ['b']
1193
1194 def test_compress_diff_len(self):
1195 import itertools
1196 it = itertools.compress(['a'], [])
1197 raises(StopIteration, next, it)
1198
1199 def test_count_kwargs(self):
1200 import itertools
1201 it = itertools.count(start=2, step=3)
1202 assert next(it) == 2
1203 assert next(it) == 5
1204 assert next(it) == 8
1205
1206 def test_repeat_kwargs(self):
1207 import itertools
1208 assert list(itertools.repeat(object='a', times=3)) == ['a', 'a', 'a']
1209
1210 def test_combinations_overflow(self):
1211 from itertools import combinations
1212 assert list(combinations("abc", 32)) == []
1213
1214 def test_combinations_with_replacement(self):
1215 from itertools import combinations_with_replacement
1216 raises(TypeError, combinations_with_replacement, "abc")
1217 raises(TypeError, combinations_with_replacement, "abc", 2, 1)
1218 raises(TypeError, combinations_with_replacement, None)
1219 raises(ValueError, combinations_with_replacement, "abc", -2)
1220 assert list(combinations_with_replacement("ABC", 2)) == [("A", "A"), ("A", 'B'), ("A", "C"), ("B", "B"), ("B", "C"), ("C", "C")]
1221
1222 def test_combinations_with_replacement_shortcases(self):
1223 from itertools import combinations_with_replacement
1224 assert list(combinations_with_replacement([-12], 2)) == [(-12, -12)]
1225 assert list(combinations_with_replacement("AB", 3)) == [
1226 ("A", "A", "A"), ("A", "A", "B"),
1227 ("A", "B", "B"), ("B", "B", "B")]
1228 assert list(combinations_with_replacement([], 2)) == []
1229 assert list(combinations_with_replacement([], 0)) == [()]
1230
1231 def test_zip_longest3(self):
1232 import itertools
1233 class Repeater(object):
1234 # this class is similar to itertools.repeat
1235 def __init__(self, o, t, e):
1236 self.o = o
1237 self.t = int(t)
1238 self.e = e
1239 def __iter__(self): # its iterator is itself
1240 return self
1241 def __next__(self):
1242 if self.t > 0:
1243 self.t -= 1
1244 return self.o
1245 else:
1246 raise self.e
1247
1248 # Formerly, the RuntimeError would be lost
1249 # and StopIteration would stop as expected
1250 r1 = Repeater(1, 3, RuntimeError)
1251 r2 = Repeater(2, 4, StopIteration)
1252 it = itertools.zip_longest(r1, r2, fillvalue=0)
1253 assert next(it) == (1, 2)
1254 assert next(it) == (1, 2)
1255 assert next(it)== (1, 2)
1256 raises(RuntimeError, next, it)
1257
1258 def test_subclassing(self):
1259 import itertools
1260 class A(itertools.count): pass
1261 assert type(A(5)) is A
1262 class A(itertools.repeat): pass
1263 assert type(A('foo')) is A
1264 class A(itertools.takewhile): pass
1265 assert type(A(lambda x: True, [])) is A
1266 class A(itertools.dropwhile): pass
1267 assert type(A(lambda x: True, [])) is A
1268 class A(itertools.filterfalse): pass
1269 assert type(A(lambda x: True, [])) is A
1270 class A(itertools.islice): pass
1271 assert type(A([], 0)) is A
1272 class A(itertools.chain): pass
1273 assert type(A([], [])) is A
1274 assert type(A.from_iterable([])) is A
1275 class A(itertools.zip_longest): pass
1276 assert type(A([], [])) is A
1277 class A(itertools.cycle): pass
1278 assert type(A([])) is A
1279 class A(itertools.starmap): pass
1280 assert type(A(lambda: 5, [])) is A
1281 class A(itertools.groupby): pass
1282 assert type(A([], lambda: 5)) is A
1283 class A(itertools.compress): pass
1284 assert type(A('', [])) is A
1285 class A(itertools.product): pass
1286 assert type(A('', '')) is A
1287 class A(itertools.combinations): pass
1288 assert type(A('', 0)) is A
1289 class A(itertools.combinations_with_replacement): pass
1290 assert type(A('', 0)) is A
1291
1292 def test_copy_pickle(self):
1293 import itertools, copy, pickle as pickle, sys
1294 for value in [42, -sys.maxsize*99]:
1295 for step in [1, sys.maxsize*42, 5.5]:
1296 expected = [value, value+step, value+2*step]
1297 c = itertools.count(value, step)
1298 assert list(itertools.islice(c, 3)) == expected
1299 c = itertools.count(value, step)
1300 c1 = copy.copy(c)
1301 assert list(itertools.islice(c1, 3)) == expected
1302 c2 = copy.deepcopy(c)
1303 assert list(itertools.islice(c2, 3)) == expected
1304 c3 = pickle.loads(pickle.dumps(c))
1305 assert list(itertools.islice(c3, 3)) == expected
1306 c4 = copy.copy(itertools.islice([1, 2, 3], 1, 5))
1307 assert list(c4) == [2, 3]
1308
1309 def test_islice_attack(self):
1310 import itertools
1311 class Iterator(object):
1312 first = True
1313 def __iter__(self):
1314 return self
1315 def __next__(self):
1316 if self.first:
1317 self.first = False
1318 list(islice)
1319 return 52
1320 myiter = Iterator()
1321 islice = itertools.islice(myiter, 5, 8)
1322 raises(StopIteration, islice.__next__)
1323
1324 def test_combinations_pickle(self):
1325 from itertools import combinations
1326 import _pickle as pickle
1327 for op in (lambda a:a, lambda a:pickle.loads(pickle.dumps(a))):
1328 assert list(op(combinations('abc', 32))) == [] # r > n
1329 assert list(op(combinations('ABCD', 2))) == [
1330 ('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]
1331 testIntermediate = combinations('ABCD', 2)
1332 next(testIntermediate)
1333 assert list(op(testIntermediate)) == [
1334 ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')]
1335
1336 assert list(op(combinations(range(4), 3))) == [
1337 (0,1,2), (0,1,3), (0,2,3), (1,2,3)]
1338 testIntermediate = combinations(range(4), 3)
1339 next(testIntermediate)
1340 assert list(op(testIntermediate)) == [
1341 (0,1,3), (0,2,3), (1,2,3)]
1342
1343 def test_islice_pickle(self):
1344 import itertools, pickle
1345 it = itertools.islice(range(100), 10, 20, 3)
1346 assert list(pickle.loads(pickle.dumps(it))) == list(range(100)[10:20:3])
1347
1348 def test_cycle_pickle(self):
1349 import itertools, pickle
1350 c = itertools.cycle('abc')
1351 next(c)
1352 assert list(itertools.islice(
1353 pickle.loads(pickle.dumps(c)), 10)) == list('bcabcabcab')
1354
1355 # CPython does not add the 'exhausted' state
1356 state = c.__reduce__()
1357 assert len(state[2]) == 2
1358
1359 def test_takewhile_pickle(self):
1360 data = [1, 2, 3, 0, 4, 5, 6]
1361 import itertools, pickle
1362 t = itertools.takewhile(bool, data)
1363 next(t)
1364 assert list(pickle.loads(pickle.dumps(t))) == [2, 3]
1365 t = itertools.dropwhile(bool, data)
1366 next(t)
1367 assert list(pickle.loads(pickle.dumps(t))) == [4, 5, 6]
1368
1369
1370 class AppTestItertools32:
1371 spaceconfig = dict(usemodules=['itertools'])
1372
1373 def test_accumulate(self):
1374 """copied from ./lib-python/3/test/test_itertools.py"""
1375 from itertools import accumulate
1376 import _operator as operator
1377 expected = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
1378 # one positional arg
1379 assert list(accumulate(range(10))) == expected
1380 # kw arg
1381 assert list(accumulate(iterable=range(10))) == expected
1382 # multiple types
1383 for typ in int, complex:
1384 assert list(accumulate(map(typ, range(10)))) == list(map(typ, expected))
1385 assert list(accumulate('abc')) == ['a', 'ab', 'abc'] # works with non-numeric
1386 assert list(accumulate([])) == [] # empty iterable
1387 assert list(accumulate([7])) == [7] # iterable of length one
1388 raises(TypeError, accumulate, range(10), 5, 6) # too many args
1389 raises(TypeError, accumulate) # too few args
1390 raises(TypeError, accumulate, x=range(10)) # unexpected kwd arg
1391 raises(TypeError, list, accumulate([1, "a"])) # args that don't add
1392
1393 s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6]
1394 assert list(accumulate(s, min)) == [2, 2, 2, 2, 2, 0, 0, 0, 0, 0]
1395 assert list(accumulate(s, max)) == [2, 8, 9, 9, 9, 9, 9, 9, 9, 9]
1396 assert list(accumulate(s, operator.mul)) == [2, 16, 144, 720, 5040, 0, 0, 0, 0, 0]
1397 raises(TypeError, list, accumulate(s, chr)) # unary-operation
1398 raises(TypeError, list, accumulate(s, lambda x,y,z: None)) # ternary
1399
1400 it = iter([10, 50, 150])
1401 a = accumulate(it)
1402 assert a.__reduce__() == (accumulate, (it, None), None)
1403 next(a)
1404 next(a)
1405 assert a.__reduce__() == (accumulate, (it, None), 60)
1406
1407 it = iter([10, 50, 150])
1408 a = accumulate(it)
1409 a.__setstate__(20)
1410 assert a.__reduce__() == (accumulate, (it, None), 20)
1411
1412 def test_accumulate_reduce_corner_case(self):
1413 from itertools import accumulate
1414 import _operator as operator
1415 it = iter([None, None, None])
1416 a = accumulate(it, operator.is_)
1417 next(a)
1418 x1, x2 = a.__reduce__()
1419 b = x1(*x2)
1420 res = list(b)
1421 assert res == [True, False]
1422
1423 def test_accumulate_initial(self):
1424 from itertools import accumulate
1425 import _pickle as pickle
1426 assert list(accumulate([1, 1, 1], initial=1)) == [1, 2, 3, 4]
1427 assert list(accumulate([1, 2, 3], initial=8)) == [8, 9, 11, 14]
1428 assert list(accumulate([1, 2, 3], func=max, initial=8)) == [8] * 4
1429
1430 it = accumulate([10, 50, 150], initial=-10)
1431 x1, x2, x3 = it.__reduce__()
1432 it2 = x1(*x2)
1433 it2.__setstate__(x3)
1434 res2 = list(it2)
1435 assert res2 == [-10, 0, 50, 200]
1436
1437 def test_tee_concurrent(self):
1438 from itertools import tee
1439 import threading
1440 start = threading.Event()
1441 finish = threading.Event()
1442 class I:
1443 def __iter__(self):
1444 return self
1445 def __next__(self):
1446 start.set()
1447 finish.wait()
1448
1449 a, b = tee(I())
1450 thread = threading.Thread(target=next, args=[a])
1451 thread.start()
1452 try:
1453 start.wait()
1454 with raises(RuntimeError) as exc:
1455 next(b)
1456 assert 'tee' in str(exc)
1457 finally:
1458 finish.set()
1459 thread.join()
1460