blob: ccdbf8abcbf2b10f753db49fbe1b67f3fd00a49b [file] [log] [blame]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001import unittest
2from test import test_support
3from itertools import *
Raymond Hettingera9f60922004-10-17 16:40:14 +00004from weakref import proxy
Raymond Hettingeraa044612009-02-12 12:04:26 +00005from decimal import Decimal
Raymond Hettingerdbe3bfb2009-02-12 12:43:01 +00006from fractions import Fraction
Raymond Hettinger2012f172003-02-07 05:32:58 +00007import sys
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00008import operator
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00009import random
Raymond Hettingere09f45a2009-11-30 19:44:40 +000010import copy
11import pickle
Ezio Melottidde5b942010-02-03 05:37:26 +000012from functools import reduce
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +000013maxsize = test_support.MAX_Py_ssize_t
14minsize = -maxsize-1
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000015
16def onearg(x):
17 'Test function of one argument'
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000018 return 2*x
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000019
20def errfunc(*args):
21 'Test function that raises an error'
22 raise ValueError
23
24def gen3():
25 'Non-restartable source sequence'
26 for i in (0, 1, 2):
27 yield i
28
29def isEven(x):
30 'Test predicate'
31 return x%2==0
32
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000033def isOdd(x):
34 'Test predicate'
35 return x%2==1
36
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000037class StopNow:
38 'Class emulating an empty iterable.'
39 def __iter__(self):
40 return self
41 def next(self):
42 raise StopIteration
Raymond Hettinger96ef8112003-02-01 00:10:11 +000043
Raymond Hettinger02420702003-06-29 20:36:23 +000044def take(n, seq):
45 'Convenience function for partially consuming a long of infinite iterable'
46 return list(islice(seq, n))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +000047
Raymond Hettingerd553d852008-03-04 04:17:08 +000048def prod(iterable):
49 return reduce(operator.mul, iterable, 1)
50
Raymond Hettinger93e804d2008-02-26 23:40:50 +000051def fact(n):
52 'Factorial'
Raymond Hettingerd553d852008-03-04 04:17:08 +000053 return prod(range(1, n+1))
54
Raymond Hettinger96ef8112003-02-01 00:10:11 +000055class TestBasicOps(unittest.TestCase):
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000056 def test_chain(self):
Raymond Hettingerad47fa12008-03-06 20:52:01 +000057
58 def chain2(*iterables):
59 'Pure python version in the docs'
60 for it in iterables:
61 for element in it:
62 yield element
63
64 for c in (chain, chain2):
65 self.assertEqual(list(c('abc', 'def')), list('abcdef'))
66 self.assertEqual(list(c('abc')), list('abc'))
67 self.assertEqual(list(c('')), [])
68 self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
69 self.assertRaises(TypeError, list,c(2, 3))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000070
Raymond Hettingerb4cbc982008-02-28 22:46:41 +000071 def test_chain_from_iterable(self):
72 self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
73 self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
74 self.assertEqual(list(chain.from_iterable([''])), [])
75 self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
76 self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
77
Raymond Hettinger93e804d2008-02-26 23:40:50 +000078 def test_combinations(self):
Raymond Hettinger5b913e32009-01-08 06:39:04 +000079 self.assertRaises(TypeError, combinations, 'abc') # missing r argument
Raymond Hettinger93e804d2008-02-26 23:40:50 +000080 self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
Raymond Hettingerd553d852008-03-04 04:17:08 +000081 self.assertRaises(TypeError, combinations, None) # pool is not iterable
Raymond Hettinger93e804d2008-02-26 23:40:50 +000082 self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
Raymond Hettinger5b913e32009-01-08 06:39:04 +000083 self.assertEqual(list(combinations('abc', 32)), []) # r > n
Raymond Hettinger93e804d2008-02-26 23:40:50 +000084 self.assertEqual(list(combinations(range(4), 3)),
85 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
Raymond Hettingerd553d852008-03-04 04:17:08 +000086
87 def combinations1(iterable, r):
88 'Pure python version shown in the docs'
89 pool = tuple(iterable)
90 n = len(pool)
Raymond Hettinger5b913e32009-01-08 06:39:04 +000091 if r > n:
92 return
Raymond Hettingerd553d852008-03-04 04:17:08 +000093 indices = range(r)
94 yield tuple(pool[i] for i in indices)
95 while 1:
96 for i in reversed(range(r)):
97 if indices[i] != i + n - r:
98 break
99 else:
100 return
101 indices[i] += 1
102 for j in range(i+1, r):
103 indices[j] = indices[j-1] + 1
104 yield tuple(pool[i] for i in indices)
105
106 def combinations2(iterable, r):
107 'Pure python version shown in the docs'
108 pool = tuple(iterable)
109 n = len(pool)
110 for indices in permutations(range(n), r):
111 if sorted(indices) == list(indices):
112 yield tuple(pool[i] for i in indices)
113
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000114 def combinations3(iterable, r):
115 'Pure python version from cwr()'
116 pool = tuple(iterable)
117 n = len(pool)
118 for indices in combinations_with_replacement(range(n), r):
119 if len(set(indices)) == r:
120 yield tuple(pool[i] for i in indices)
121
Raymond Hettingerd553d852008-03-04 04:17:08 +0000122 for n in range(7):
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000123 values = [5*x-12 for x in range(n)]
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000124 for r in range(n+2):
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000125 result = list(combinations(values, r))
Ezio Melottidde5b942010-02-03 05:37:26 +0000126 self.assertEqual(len(result), 0 if r>n else fact(n) // fact(r) // fact(n-r)) # right number of combs
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000127 self.assertEqual(len(result), len(set(result))) # no repeats
128 self.assertEqual(result, sorted(result)) # lexicographic order
129 for c in result:
130 self.assertEqual(len(c), r) # r-length combinations
131 self.assertEqual(len(set(c)), r) # no duplicate elements
132 self.assertEqual(list(c), sorted(c)) # keep original ordering
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000133 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000134 self.assertEqual(list(c),
135 [e for e in values if e in c]) # comb is a subsequence of the input iterable
Raymond Hettingerd553d852008-03-04 04:17:08 +0000136 self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000137 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000138 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
Raymond Hettingerd553d852008-03-04 04:17:08 +0000139
Alex Gaynor97376482011-07-17 16:44:31 -0700140 @test_support.impl_detail("tuple reuse is specific to CPython")
141 def test_combinations_tuple_reuse(self):
Raymond Hettingerd553d852008-03-04 04:17:08 +0000142 self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
143 self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
144
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000145 def test_combinations_with_replacement(self):
146 cwr = combinations_with_replacement
147 self.assertRaises(TypeError, cwr, 'abc') # missing r argument
148 self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments
149 self.assertRaises(TypeError, cwr, None) # pool is not iterable
150 self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative
151 self.assertEqual(list(cwr('ABC', 2)),
152 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
153
154 def cwr1(iterable, r):
155 'Pure python version shown in the docs'
156 # number items returned: (n+r-1)! / r! / (n-1)! when n>0
157 pool = tuple(iterable)
158 n = len(pool)
159 if not n and r:
160 return
161 indices = [0] * r
162 yield tuple(pool[i] for i in indices)
163 while 1:
164 for i in reversed(range(r)):
165 if indices[i] != n - 1:
166 break
167 else:
168 return
169 indices[i:] = [indices[i] + 1] * (r - i)
170 yield tuple(pool[i] for i in indices)
171
172 def cwr2(iterable, r):
173 'Pure python version shown in the docs'
174 pool = tuple(iterable)
175 n = len(pool)
176 for indices in product(range(n), repeat=r):
177 if sorted(indices) == list(indices):
178 yield tuple(pool[i] for i in indices)
179
180 def numcombs(n, r):
181 if not n:
182 return 0 if r else 1
Ezio Melottidde5b942010-02-03 05:37:26 +0000183 return fact(n+r-1) // fact(r) // fact(n-1)
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000184
185 for n in range(7):
186 values = [5*x-12 for x in range(n)]
187 for r in range(n+2):
188 result = list(cwr(values, r))
189
190 self.assertEqual(len(result), numcombs(n, r)) # right number of combs
191 self.assertEqual(len(result), len(set(result))) # no repeats
192 self.assertEqual(result, sorted(result)) # lexicographic order
193
194 regular_combs = list(combinations(values, r)) # compare to combs without replacement
195 if n == 0 or r <= 1:
Ezio Melotti2623a372010-11-21 13:34:58 +0000196 self.assertEqual(result, regular_combs) # cases that should be identical
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000197 else:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000198 self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000199
200 for c in result:
201 self.assertEqual(len(c), r) # r-length combinations
202 noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
203 self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
204 self.assertEqual(list(c), sorted(c)) # keep original ordering
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000205 self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000206 self.assertEqual(noruns,
207 [e for e in values if e in c]) # comb is a subsequence of the input iterable
208 self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
209 self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version
210
Alex Gaynor97376482011-07-17 16:44:31 -0700211 @test_support.impl_detail("tuple reuse is specific to CPython")
212 def test_combinations_with_replacement_tuple_reuse(self):
213 cwr = combinations_with_replacement
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000214 self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
215 self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
216
Raymond Hettingerd553d852008-03-04 04:17:08 +0000217 def test_permutations(self):
218 self.assertRaises(TypeError, permutations) # too few arguments
219 self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000220 self.assertRaises(TypeError, permutations, None) # pool is not iterable
221 self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000222 self.assertEqual(list(permutations('abc', 32)), []) # r > n
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000223 self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
Raymond Hettingerd553d852008-03-04 04:17:08 +0000224 self.assertEqual(list(permutations(range(3), 2)),
225 [(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
226
227 def permutations1(iterable, r=None):
228 'Pure python version shown in the docs'
229 pool = tuple(iterable)
230 n = len(pool)
231 r = n if r is None else r
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000232 if r > n:
233 return
Raymond Hettingerd553d852008-03-04 04:17:08 +0000234 indices = range(n)
Raymond Hettingere70bb8d2008-03-23 00:55:46 +0000235 cycles = range(n, n-r, -1)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000236 yield tuple(pool[i] for i in indices[:r])
237 while n:
238 for i in reversed(range(r)):
239 cycles[i] -= 1
240 if cycles[i] == 0:
241 indices[i:] = indices[i+1:] + indices[i:i+1]
242 cycles[i] = n - i
243 else:
244 j = cycles[i]
245 indices[i], indices[-j] = indices[-j], indices[i]
246 yield tuple(pool[i] for i in indices[:r])
247 break
248 else:
249 return
250
251 def permutations2(iterable, r=None):
252 'Pure python version shown in the docs'
253 pool = tuple(iterable)
254 n = len(pool)
255 r = n if r is None else r
256 for indices in product(range(n), repeat=r):
257 if len(set(indices)) == r:
258 yield tuple(pool[i] for i in indices)
259
260 for n in range(7):
261 values = [5*x-12 for x in range(n)]
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000262 for r in range(n+2):
Raymond Hettingerd553d852008-03-04 04:17:08 +0000263 result = list(permutations(values, r))
Ezio Melottidde5b942010-02-03 05:37:26 +0000264 self.assertEqual(len(result), 0 if r>n else fact(n) // fact(n-r)) # right number of perms
Raymond Hettingerd553d852008-03-04 04:17:08 +0000265 self.assertEqual(len(result), len(set(result))) # no repeats
266 self.assertEqual(result, sorted(result)) # lexicographic order
267 for p in result:
268 self.assertEqual(len(p), r) # r-length permutations
269 self.assertEqual(len(set(p)), r) # no duplicate elements
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000270 self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
Raymond Hettingerd553d852008-03-04 04:17:08 +0000271 self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
Raymond Hettinger5b913e32009-01-08 06:39:04 +0000272 self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
Raymond Hettingerd553d852008-03-04 04:17:08 +0000273 if r == n:
274 self.assertEqual(result, list(permutations(values, None))) # test r as None
275 self.assertEqual(result, list(permutations(values))) # test default r
276
Alex Gaynor97376482011-07-17 16:44:31 -0700277 @test_support.impl_detail("tuple resuse is CPython specific")
278 def test_permutations_tuple_reuse(self):
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000279 self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000280 self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
Raymond Hettinger93e804d2008-02-26 23:40:50 +0000281
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000282 def test_combinatorics(self):
283 # Test relationships between product(), permutations(),
284 # combinations() and combinations_with_replacement().
285
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000286 for n in range(6):
287 s = 'ABCDEFG'[:n]
288 for r in range(8):
289 prod = list(product(s, repeat=r))
290 cwr = list(combinations_with_replacement(s, r))
291 perm = list(permutations(s, r))
292 comb = list(combinations(s, r))
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000293
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000294 # Check size
Ezio Melotti2623a372010-11-21 13:34:58 +0000295 self.assertEqual(len(prod), n**r)
296 self.assertEqual(len(cwr), (fact(n+r-1) // fact(r) // fact(n-1)) if n else (not r))
297 self.assertEqual(len(perm), 0 if r>n else fact(n) // fact(n-r))
298 self.assertEqual(len(comb), 0 if r>n else fact(n) // fact(r) // fact(n-r))
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000299
300 # Check lexicographic order without repeated tuples
Ezio Melotti2623a372010-11-21 13:34:58 +0000301 self.assertEqual(prod, sorted(set(prod)))
302 self.assertEqual(cwr, sorted(set(cwr)))
303 self.assertEqual(perm, sorted(set(perm)))
304 self.assertEqual(comb, sorted(set(comb)))
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000305
306 # Check interrelationships
Ezio Melotti2623a372010-11-21 13:34:58 +0000307 self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
308 self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups
Raymond Hettinger2f6c2e02009-01-27 10:36:14 +0000309 self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
310 self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups
311 self.assertEqual(comb, filter(set(cwr).__contains__, perm)) # comb: perm that is a cwr
312 self.assertEqual(comb, filter(set(perm).__contains__, cwr)) # comb: cwr that is a perm
313 self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm
Raymond Hettinger2976aaa2009-01-27 09:33:06 +0000314
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000315 def test_compress(self):
Raymond Hettinger2e2909f2009-02-19 02:15:14 +0000316 self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000317 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
318 self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
319 self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
320 self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
321 self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
322 n = 10000
323 data = chain.from_iterable(repeat(range(6), n))
324 selectors = chain.from_iterable(repeat((0, 1)))
325 self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
326 self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable
327 self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable
328 self.assertRaises(TypeError, compress, range(6)) # too few args
329 self.assertRaises(TypeError, compress, range(6), None) # too many args
330
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000331 def test_count(self):
332 self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
333 self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
Raymond Hettinger02420702003-06-29 20:36:23 +0000334 self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000335 self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
336 self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000337 self.assertRaises(TypeError, count, 2, 3, 4)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000338 self.assertRaises(TypeError, count, 'a')
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000339 self.assertEqual(list(islice(count(maxsize-5), 10)), range(maxsize-5, maxsize+5))
340 self.assertEqual(list(islice(count(-maxsize-5), 10)), range(-maxsize-5, -maxsize+5))
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000341 c = count(3)
342 self.assertEqual(repr(c), 'count(3)')
343 c.next()
344 self.assertEqual(repr(c), 'count(4)')
Jack Diederich36234e82006-09-21 17:50:26 +0000345 c = count(-9)
346 self.assertEqual(repr(c), 'count(-9)')
347 c.next()
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000348 self.assertEqual(repr(count(10.25)), 'count(10.25)')
Jack Diederich36234e82006-09-21 17:50:26 +0000349 self.assertEqual(c.next(), -8)
Raymond Hettinger50e90e22007-10-04 00:20:27 +0000350 for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
Raymond Hettinger3a0de082007-10-12 17:53:11 +0000351 # Test repr (ignoring the L in longs)
352 r1 = repr(count(i)).replace('L', '')
353 r2 = 'count(%r)'.__mod__(i).replace('L', '')
354 self.assertEqual(r1, r2)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000355
Raymond Hettingere09f45a2009-11-30 19:44:40 +0000356 # check copy, deepcopy, pickle
357 for value in -3, 3, sys.maxint-5, sys.maxint+5:
358 c = count(value)
359 self.assertEqual(next(copy.copy(c)), value)
360 self.assertEqual(next(copy.deepcopy(c)), value)
361 self.assertEqual(next(pickle.loads(pickle.dumps(c))), value)
362
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000363 def test_count_with_stride(self):
364 self.assertEqual(zip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingera4038032009-02-14 00:25:51 +0000365 self.assertEqual(zip('abc',count(start=2,step=3)),
366 [('a', 2), ('b', 5), ('c', 8)])
Raymond Hettingeraa681c72009-02-21 07:17:22 +0000367 self.assertEqual(zip('abc',count(step=-1)),
368 [('a', 0), ('b', -1), ('c', -2)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000369 self.assertEqual(zip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
370 self.assertEqual(zip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
371 self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
372 self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
373 self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
Raymond Hettingeraa044612009-02-12 12:04:26 +0000374 self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
375 [Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
Raymond Hettingerdbe3bfb2009-02-12 12:43:01 +0000376 self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
377 [Fraction(2,3), Fraction(17,21), Fraction(20,21)])
Raymond Hettinger31c769c2009-02-12 05:39:46 +0000378 self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
379 c = count(3, 5)
380 self.assertEqual(repr(c), 'count(3, 5)')
381 c.next()
382 self.assertEqual(repr(c), 'count(8, 5)')
383 c = count(-9, 0)
384 self.assertEqual(repr(c), 'count(-9, 0)')
385 c.next()
386 self.assertEqual(repr(c), 'count(-9, 0)')
387 c = count(-9, -3)
388 self.assertEqual(repr(c), 'count(-9, -3)')
389 c.next()
390 self.assertEqual(repr(c), 'count(-12, -3)')
391 self.assertEqual(repr(c), 'count(-12, -3)')
392 self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
393 self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
394 self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
395 for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
396 for j in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 1, 10, sys.maxint-5, sys.maxint+5):
397 # Test repr (ignoring the L in longs)
398 r1 = repr(count(i, j)).replace('L', '')
399 if j == 1:
400 r2 = ('count(%r)' % i).replace('L', '')
401 else:
402 r2 = ('count(%r, %r)' % (i, j)).replace('L', '')
403 self.assertEqual(r1, r2)
404
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000405 def test_cycle(self):
Raymond Hettinger02420702003-06-29 20:36:23 +0000406 self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000407 self.assertEqual(list(cycle('')), [])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000408 self.assertRaises(TypeError, cycle)
409 self.assertRaises(TypeError, cycle, 5)
410 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000411
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000412 def test_groupby(self):
413 # Check whether it accepts arguments correctly
414 self.assertEqual([], list(groupby([])))
415 self.assertEqual([], list(groupby([], key=id)))
416 self.assertRaises(TypeError, list, groupby('abc', []))
417 self.assertRaises(TypeError, groupby, None)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000418 self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000419
420 # Check normal input
421 s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
422 (2,15,22), (3,16,23), (3,17,23)]
423 dup = []
424 for k, g in groupby(s, lambda r:r[0]):
425 for elem in g:
426 self.assertEqual(k, elem[0])
427 dup.append(elem)
428 self.assertEqual(s, dup)
429
430 # Check nested case
431 dup = []
432 for k, g in groupby(s, lambda r:r[0]):
433 for ik, ig in groupby(g, lambda r:r[2]):
434 for elem in ig:
435 self.assertEqual(k, elem[0])
436 self.assertEqual(ik, elem[2])
437 dup.append(elem)
438 self.assertEqual(s, dup)
439
440 # Check case where inner iterator is not used
441 keys = [k for k, g in groupby(s, lambda r:r[0])]
442 expectedkeys = set([r[0] for r in s])
443 self.assertEqual(set(keys), expectedkeys)
444 self.assertEqual(len(keys), len(expectedkeys))
445
446 # Exercise pipes and filters style
447 s = 'abracadabra'
448 # sort s | uniq
Raymond Hettinger64958a12003-12-17 20:43:33 +0000449 r = [k for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000450 self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
451 # sort s | uniq -d
Raymond Hettinger64958a12003-12-17 20:43:33 +0000452 r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000453 self.assertEqual(r, ['a', 'b', 'r'])
454 # sort s | uniq -c
Raymond Hettinger64958a12003-12-17 20:43:33 +0000455 r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000456 self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
457 # sort s | uniq -c | sort -rn | head -3
Raymond Hettinger64958a12003-12-17 20:43:33 +0000458 r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000459 self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
460
461 # iter.next failure
462 class ExpectedError(Exception):
463 pass
464 def delayed_raise(n=0):
465 for i in range(n):
466 yield 'yo'
467 raise ExpectedError
468 def gulp(iterable, keyp=None, func=list):
469 return [func(g) for k, g in groupby(iterable, keyp)]
470
471 # iter.next failure on outer object
472 self.assertRaises(ExpectedError, gulp, delayed_raise(0))
473 # iter.next failure on inner object
474 self.assertRaises(ExpectedError, gulp, delayed_raise(1))
475
476 # __cmp__ failure
477 class DummyCmp:
478 def __cmp__(self, dst):
479 raise ExpectedError
480 s = [DummyCmp(), DummyCmp(), None]
481
482 # __cmp__ failure on outer object
483 self.assertRaises(ExpectedError, gulp, s, func=id)
484 # __cmp__ failure on inner object
485 self.assertRaises(ExpectedError, gulp, s)
486
487 # keyfunc failure
488 def keyfunc(obj):
489 if keyfunc.skip > 0:
490 keyfunc.skip -= 1
491 return obj
492 else:
493 raise ExpectedError
494
495 # keyfunc failure on outer object
496 keyfunc.skip = 0
497 self.assertRaises(ExpectedError, gulp, [None], keyfunc)
498 keyfunc.skip = 1
499 self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
500
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000501 def test_ifilter(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000502 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000503 self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000504 self.assertEqual(list(ifilter(bool, [0,1,0,2,0])), [1,2])
Raymond Hettinger02420702003-06-29 20:36:23 +0000505 self.assertEqual(take(4, ifilter(isEven, count())), [0,2,4,6])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000506 self.assertRaises(TypeError, ifilter)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000507 self.assertRaises(TypeError, ifilter, lambda x:x)
508 self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000509 self.assertRaises(TypeError, ifilter, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000510 self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000511
512 def test_ifilterfalse(self):
Raymond Hettinger60eca932003-02-09 06:40:58 +0000513 self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
514 self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger9d638372008-02-25 22:42:32 +0000515 self.assertEqual(list(ifilterfalse(bool, [0,1,0,2,0])), [0,0,0])
Raymond Hettinger02420702003-06-29 20:36:23 +0000516 self.assertEqual(take(4, ifilterfalse(isEven, count())), [1,3,5,7])
Raymond Hettinger60eca932003-02-09 06:40:58 +0000517 self.assertRaises(TypeError, ifilterfalse)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000518 self.assertRaises(TypeError, ifilterfalse, lambda x:x)
519 self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000520 self.assertRaises(TypeError, ifilterfalse, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000521 self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000522
523 def test_izip(self):
524 ans = [(x,y) for x, y in izip('abc',count())]
525 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000526 self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
527 self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
Raymond Hettinger02420702003-06-29 20:36:23 +0000528 self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3)))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000529 self.assertEqual(list(izip('abcdef')), zip('abcdef'))
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000530 self.assertEqual(list(izip()), zip())
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000531 self.assertRaises(TypeError, izip, 3)
532 self.assertRaises(TypeError, izip, range(3), 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000533 self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
534 zip('abc', 'def'))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000535 self.assertEqual([pair for pair in izip('abc', 'def')],
536 zip('abc', 'def'))
Alex Gaynor97376482011-07-17 16:44:31 -0700537
538 @test_support.impl_detail("tuple reuse is specific to CPython")
539 def test_izip_tuple_resuse(self):
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000540 ids = map(id, izip('abc', 'def'))
541 self.assertEqual(min(ids), max(ids))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +0000542 ids = map(id, list(izip('abc', 'def')))
543 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000544
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000545 def test_iziplongest(self):
546 for args in [
547 ['abc', range(6)],
548 [range(6), 'abc'],
549 [range(1000), range(2000,2100), range(3000,3050)],
550 [range(1000), range(0), range(3000,3050), range(1200), range(1500)],
551 [range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
552 ]:
Ezio Melottidde5b942010-02-03 05:37:26 +0000553 # target = map(None, *args) <- this raises a py3k warning
554 # this is the replacement:
555 target = [tuple([arg[i] if i < len(arg) else None for arg in args])
556 for i in range(max(map(len, args)))]
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000557 self.assertEqual(list(izip_longest(*args)), target)
558 self.assertEqual(list(izip_longest(*args, **{})), target)
559 target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
560 self.assertEqual(list(izip_longest(*args, **dict(fillvalue='X'))), target)
Tim Petersea5962f2007-03-12 18:07:52 +0000561
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000562 self.assertEqual(take(3,izip_longest('abcdef', count())), zip('abcdef', range(3))) # take 3 from infinite input
563
564 self.assertEqual(list(izip_longest()), zip())
565 self.assertEqual(list(izip_longest([])), zip([]))
566 self.assertEqual(list(izip_longest('abcdef')), zip('abcdef'))
Tim Petersea5962f2007-03-12 18:07:52 +0000567
Ezio Melottidde5b942010-02-03 05:37:26 +0000568 self.assertEqual(list(izip_longest('abc', 'defg', **{})),
569 zip(list('abc') + [None], 'defg')) # empty keyword dict
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000570 self.assertRaises(TypeError, izip_longest, 3)
571 self.assertRaises(TypeError, izip_longest, range(3), 3)
572
573 for stmt in [
574 "izip_longest('abc', fv=1)",
Tim Petersea5962f2007-03-12 18:07:52 +0000575 "izip_longest('abc', fillvalue=1, bogus_keyword=None)",
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000576 ]:
577 try:
578 eval(stmt, globals(), locals())
579 except TypeError:
580 pass
581 else:
582 self.fail('Did not raise Type in: ' + stmt)
Tim Petersea5962f2007-03-12 18:07:52 +0000583
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000584 self.assertEqual([tuple(list(pair)) for pair in izip_longest('abc', 'def')],
585 zip('abc', 'def'))
586 self.assertEqual([pair for pair in izip_longest('abc', 'def')],
587 zip('abc', 'def'))
Alex Gaynor97376482011-07-17 16:44:31 -0700588
589 @test_support.impl_detail("tuple reuse is specific to CPython")
590 def test_izip_longest_tuple_reuse(self):
Raymond Hettingerd36862c2007-02-21 05:20:38 +0000591 ids = map(id, izip_longest('abc', 'def'))
592 self.assertEqual(min(ids), max(ids))
593 ids = map(id, list(izip_longest('abc', 'def')))
594 self.assertEqual(len(dict.fromkeys(ids)), len(ids))
595
Raymond Hettingerfa7dadd2009-11-01 20:45:16 +0000596 def test_bug_7244(self):
597
598 class Repeater(object):
599 # this class is similar to itertools.repeat
600 def __init__(self, o, t, e):
601 self.o = o
602 self.t = int(t)
603 self.e = e
604 def __iter__(self): # its iterator is itself
605 return self
606 def next(self):
607 if self.t > 0:
608 self.t -= 1
609 return self.o
610 else:
611 raise self.e
612
613 # Formerly this code in would fail in debug mode
614 # with Undetected Error and Stop Iteration
615 r1 = Repeater(1, 3, StopIteration)
616 r2 = Repeater(2, 4, StopIteration)
617 def run(r1, r2):
618 result = []
619 for i, j in izip_longest(r1, r2, fillvalue=0):
620 with test_support.captured_output('stdout'):
621 print (i, j)
622 result.append((i, j))
623 return result
624 self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
625
626 # Formerly, the RuntimeError would be lost
627 # and StopIteration would stop as expected
628 r1 = Repeater(1, 3, RuntimeError)
629 r2 = Repeater(2, 4, StopIteration)
630 it = izip_longest(r1, r2, fillvalue=0)
631 self.assertEqual(next(it), (1, 2))
632 self.assertEqual(next(it), (1, 2))
633 self.assertEqual(next(it), (1, 2))
634 self.assertRaises(RuntimeError, next, it)
635
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000636 def test_product(self):
637 for args, result in [
Raymond Hettingerd553d852008-03-04 04:17:08 +0000638 ([], [()]), # zero iterables
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000639 (['ab'], [('a',), ('b',)]), # one iterable
640 ([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
641 ([range(0), range(2), range(3)], []), # first iterable with zero length
642 ([range(2), range(0), range(3)], []), # middle iterable with zero length
643 ([range(2), range(3), range(0)], []), # last iterable with zero length
644 ]:
645 self.assertEqual(list(product(*args)), result)
Raymond Hettinger08ff6822008-02-29 02:21:48 +0000646 for r in range(4):
647 self.assertEqual(list(product(*(args*r))),
648 list(product(*args, **dict(repeat=r))))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000649 self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
650 self.assertRaises(TypeError, product, range(6), None)
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000651
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000652 def product1(*args, **kwds):
653 pools = map(tuple, args) * kwds.get('repeat', 1)
654 n = len(pools)
655 if n == 0:
656 yield ()
657 return
658 if any(len(pool) == 0 for pool in pools):
659 return
660 indices = [0] * n
661 yield tuple(pool[i] for pool, i in zip(pools, indices))
662 while 1:
663 for i in reversed(range(n)): # right to left
664 if indices[i] == len(pools[i]) - 1:
665 continue
666 indices[i] += 1
667 for j in range(i+1, n):
668 indices[j] = 0
669 yield tuple(pool[i] for pool, i in zip(pools, indices))
670 break
671 else:
672 return
673
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000674 def product2(*args, **kwds):
675 'Pure python version used in docs'
676 pools = map(tuple, args) * kwds.get('repeat', 1)
677 result = [[]]
678 for pool in pools:
679 result = [x+[y] for x in result for y in pool]
680 for prod in result:
681 yield tuple(prod)
682
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000683 argtypes = ['', 'abc', '', xrange(0), xrange(4), dict(a=1, b=2, c=3),
684 set('abcdefg'), range(11), tuple(range(13))]
685 for i in range(100):
686 args = [random.choice(argtypes) for j in range(random.randrange(5))]
Raymond Hettingerd553d852008-03-04 04:17:08 +0000687 expected_len = prod(map(len, args))
688 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +0000689 self.assertEqual(list(product(*args)), list(product1(*args)))
Raymond Hettinger66f91ea2008-03-05 20:59:58 +0000690 self.assertEqual(list(product(*args)), list(product2(*args)))
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000691 args = map(iter, args)
Raymond Hettingerd553d852008-03-04 04:17:08 +0000692 self.assertEqual(len(list(product(*args))), expected_len)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000693
Alex Gaynor97376482011-07-17 16:44:31 -0700694 @test_support.impl_detail("tuple reuse is specific to CPython")
695 def test_product_tuple_reuse(self):
Raymond Hettinger73d79632008-02-23 02:20:41 +0000696 self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
697 self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
Raymond Hettinger50986cc2008-02-22 03:16:42 +0000698
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000699 def test_repeat(self):
Raymond Hettinger182edae2009-02-19 02:38:25 +0000700 self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000701 self.assertEqual(zip(xrange(3),repeat('a')),
702 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000703 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger02420702003-06-29 20:36:23 +0000704 self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000705 self.assertEqual(list(repeat('a', 0)), [])
706 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000707 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000708 self.assertRaises(TypeError, repeat, None, 3, 4)
709 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000710 r = repeat(1+0j)
711 self.assertEqual(repr(r), 'repeat((1+0j))')
712 r = repeat(1+0j, 5)
713 self.assertEqual(repr(r), 'repeat((1+0j), 5)')
714 list(r)
715 self.assertEqual(repr(r), 'repeat((1+0j), 0)')
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000716
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000717 def test_imap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000718 self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
719 [0**1, 1**2, 2**3])
720 self.assertEqual(list(imap(None, 'abc', range(5))),
721 [('a',0),('b',1),('c',2)])
Raymond Hettinger02420702003-06-29 20:36:23 +0000722 self.assertEqual(list(imap(None, 'abc', count())),
723 [('a',0),('b',1),('c',2)])
724 self.assertEqual(take(2,imap(None, 'abc', count())),
725 [('a',0),('b',1)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000726 self.assertEqual(list(imap(operator.pow, [])), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000727 self.assertRaises(TypeError, imap)
728 self.assertRaises(TypeError, imap, operator.neg)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000729 self.assertRaises(TypeError, imap(10, range(5)).next)
730 self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
731 self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000732
733 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000734 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
735 [0**1, 1**2, 2**3])
Raymond Hettinger02420702003-06-29 20:36:23 +0000736 self.assertEqual(take(3, starmap(operator.pow, izip(count(), count(1)))),
737 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000738 self.assertEqual(list(starmap(operator.pow, [])), [])
Raymond Hettinger47317092008-01-17 03:02:14 +0000739 self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
740 self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000741 self.assertRaises(TypeError, starmap)
742 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
743 self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
744 self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
745 self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000746
747 def test_islice(self):
748 for args in [ # islice(args) should agree with range(args)
749 (10, 20, 3),
750 (10, 3, 20),
751 (10, 20),
752 (10, 3),
753 (20,)
754 ]:
755 self.assertEqual(list(islice(xrange(100), *args)), range(*args))
756
757 for args, tgtargs in [ # Stop when seqn is exhausted
758 ((10, 110, 3), ((10, 100, 3))),
759 ((10, 110), ((10, 100))),
760 ((110,), (100,))
761 ]:
762 self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
763
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000764 # Test stop=None
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000765 self.assertEqual(list(islice(xrange(10), None)), range(10))
Raymond Hettingerb2594052004-12-05 09:25:51 +0000766 self.assertEqual(list(islice(xrange(10), None, None)), range(10))
767 self.assertEqual(list(islice(xrange(10), None, None, None)), range(10))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000768 self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
769 self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
770
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +0000771 # Test number of items consumed SF #1171417
772 it = iter(range(10))
773 self.assertEqual(list(islice(it, 3)), range(3))
774 self.assertEqual(list(it), range(3, 10))
775
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000776 # Test invalid arguments
Raymond Hettinger341deb72003-05-02 19:44:20 +0000777 self.assertRaises(TypeError, islice, xrange(10))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000778 self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
779 self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
780 self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
781 self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
782 self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000783 self.assertRaises(ValueError, islice, xrange(10), 'a')
784 self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
785 self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
786 self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
787 self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
Kristján Valur Jónsson170eee92007-05-03 20:09:56 +0000788 self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000789
Raymond Hettinger061bf7a2010-11-30 03:15:35 +0000790 # Issue #10323: Less islice in a predictable state
791 c = count()
792 self.assertEqual(list(islice(c, 1, 3, 50)), [1])
793 self.assertEqual(next(c), 3)
794
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000795 def test_takewhile(self):
796 data = [1, 3, 5, 20, 2, 4, 6, 8]
797 underten = lambda x: x<10
798 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000799 self.assertEqual(list(takewhile(underten, [])), [])
800 self.assertRaises(TypeError, takewhile)
801 self.assertRaises(TypeError, takewhile, operator.pow)
802 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
803 self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
804 self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000805 t = takewhile(bool, [1, 1, 1, 0, 0, 0])
806 self.assertEqual(list(t), [1, 1, 1])
807 self.assertRaises(StopIteration, t.next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000808
809 def test_dropwhile(self):
810 data = [1, 3, 5, 20, 2, 4, 6, 8]
811 underten = lambda x: x<10
812 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000813 self.assertEqual(list(dropwhile(underten, [])), [])
814 self.assertRaises(TypeError, dropwhile)
815 self.assertRaises(TypeError, dropwhile, operator.pow)
816 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
817 self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
818 self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000819
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000820 def test_tee(self):
Raymond Hettingerad983e72003-11-12 14:32:26 +0000821 n = 200
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000822 def irange(n):
823 for i in xrange(n):
824 yield i
825
826 a, b = tee([]) # test empty iterator
827 self.assertEqual(list(a), [])
828 self.assertEqual(list(b), [])
829
830 a, b = tee(irange(n)) # test 100% interleaved
831 self.assertEqual(zip(a,b), zip(range(n),range(n)))
832
833 a, b = tee(irange(n)) # test 0% interleaved
834 self.assertEqual(list(a), range(n))
835 self.assertEqual(list(b), range(n))
836
837 a, b = tee(irange(n)) # test dealloc of leading iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000838 for i in xrange(100):
839 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000840 del a
841 self.assertEqual(list(b), range(n))
842
843 a, b = tee(irange(n)) # test dealloc of trailing iterator
Raymond Hettingerad983e72003-11-12 14:32:26 +0000844 for i in xrange(100):
845 self.assertEqual(a.next(), i)
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000846 del b
Raymond Hettingerad983e72003-11-12 14:32:26 +0000847 self.assertEqual(list(a), range(100, n))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000848
849 for j in xrange(5): # test randomly interleaved
850 order = [0]*n + [1]*n
851 random.shuffle(order)
852 lists = ([], [])
853 its = tee(irange(n))
854 for i in order:
855 value = its[i].next()
856 lists[i].append(value)
857 self.assertEqual(lists[0], range(n))
858 self.assertEqual(lists[1], range(n))
859
Raymond Hettingerad983e72003-11-12 14:32:26 +0000860 # test argument format checking
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000861 self.assertRaises(TypeError, tee)
862 self.assertRaises(TypeError, tee, 3)
863 self.assertRaises(TypeError, tee, [1,2], 'x')
Raymond Hettingerad983e72003-11-12 14:32:26 +0000864 self.assertRaises(TypeError, tee, [1,2], 3, 'x')
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000865
Raymond Hettingerad983e72003-11-12 14:32:26 +0000866 # tee object should be instantiable
867 a, b = tee('abc')
868 c = type(a)('def')
869 self.assertEqual(list(c), list('def'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000870
Raymond Hettingerad983e72003-11-12 14:32:26 +0000871 # test long-lagged and multi-way split
872 a, b, c = tee(xrange(2000), 3)
873 for i in xrange(100):
874 self.assertEqual(a.next(), i)
875 self.assertEqual(list(b), range(2000))
876 self.assertEqual([c.next(), c.next()], range(2))
877 self.assertEqual(list(a), range(100,2000))
878 self.assertEqual(list(c), range(2,2000))
879
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000880 # test values of n
881 self.assertRaises(TypeError, tee, 'abc', 'invalid')
Neal Norwitz69e88972006-09-02 02:58:13 +0000882 self.assertRaises(ValueError, tee, [], -1)
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000883 for n in xrange(5):
884 result = tee('abc', n)
885 self.assertEqual(type(result), tuple)
886 self.assertEqual(len(result), n)
887 self.assertEqual(map(list, result), [list('abc')]*n)
888
Raymond Hettingerad983e72003-11-12 14:32:26 +0000889 # tee pass-through to copyable iterator
890 a, b = tee('abc')
891 c, d = tee(a)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000892 self.assertTrue(a is c)
Raymond Hettingerad983e72003-11-12 14:32:26 +0000893
Raymond Hettinger4cda01e2004-09-28 04:45:28 +0000894 # test tee_new
895 t1, t2 = tee('abc')
896 tnew = type(t1)
897 self.assertRaises(TypeError, tnew)
898 self.assertRaises(TypeError, tnew, 10)
899 t3 = tnew(t1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000900 self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
Raymond Hettingerf0c5aec2003-10-26 14:25:56 +0000901
Raymond Hettingera9f60922004-10-17 16:40:14 +0000902 # test that tee objects are weak referencable
903 a, b = tee(xrange(10))
904 p = proxy(a)
905 self.assertEqual(getattr(p, '__class__'), type(b))
906 del a
907 self.assertRaises(ReferenceError, getattr, p, '__class__')
908
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000909 def test_StopIteration(self):
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000910 self.assertRaises(StopIteration, izip().next)
911
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000912 for f in (chain, cycle, izip, groupby):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000913 self.assertRaises(StopIteration, f([]).next)
914 self.assertRaises(StopIteration, f(StopNow()).next)
915
916 self.assertRaises(StopIteration, islice([], None).next)
917 self.assertRaises(StopIteration, islice(StopNow(), None).next)
918
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000919 p, q = tee([])
920 self.assertRaises(StopIteration, p.next)
921 self.assertRaises(StopIteration, q.next)
922 p, q = tee(StopNow())
923 self.assertRaises(StopIteration, p.next)
924 self.assertRaises(StopIteration, q.next)
925
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000926 self.assertRaises(StopIteration, repeat(None, 0).next)
927
928 for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
929 self.assertRaises(StopIteration, f(lambda x:x, []).next)
930 self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
931
Raymond Hettingerad47fa12008-03-06 20:52:01 +0000932class TestExamples(unittest.TestCase):
933
934 def test_chain(self):
935 self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
936
937 def test_chain_from_iterable(self):
938 self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
939
940 def test_combinations(self):
941 self.assertEqual(list(combinations('ABCD', 2)),
942 [('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
943 self.assertEqual(list(combinations(range(4), 3)),
944 [(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
945
Raymond Hettingerd081abc2009-01-27 02:58:49 +0000946 def test_combinations_with_replacement(self):
947 self.assertEqual(list(combinations_with_replacement('ABC', 2)),
948 [('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
949
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +0000950 def test_compress(self):
951 self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
952
Raymond Hettingerad47fa12008-03-06 20:52:01 +0000953 def test_count(self):
954 self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
955
956 def test_cycle(self):
957 self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
958
959 def test_dropwhile(self):
960 self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
961
962 def test_groupby(self):
963 self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
964 list('ABCDAB'))
965 self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
966 [list('AAAA'), list('BBB'), list('CC'), list('D')])
967
968 def test_ifilter(self):
969 self.assertEqual(list(ifilter(lambda x: x%2, range(10))), [1,3,5,7,9])
970
971 def test_ifilterfalse(self):
972 self.assertEqual(list(ifilterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
973
974 def test_imap(self):
975 self.assertEqual(list(imap(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
976
977 def test_islice(self):
978 self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
979 self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
980 self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
981 self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
982
983 def test_izip(self):
984 self.assertEqual(list(izip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
985
986 def test_izip_longest(self):
987 self.assertEqual(list(izip_longest('ABCD', 'xy', fillvalue='-')),
988 [('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
989
990 def test_permutations(self):
991 self.assertEqual(list(permutations('ABCD', 2)),
992 map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split()))
993 self.assertEqual(list(permutations(range(3))),
994 [(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
995
996 def test_product(self):
997 self.assertEqual(list(product('ABCD', 'xy')),
998 map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split()))
999 self.assertEqual(list(product(range(2), repeat=3)),
1000 [(0,0,0), (0,0,1), (0,1,0), (0,1,1),
1001 (1,0,0), (1,0,1), (1,1,0), (1,1,1)])
1002
1003 def test_repeat(self):
1004 self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
1005
1006 def test_stapmap(self):
1007 self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
1008 [32, 9, 1000])
1009
1010 def test_takewhile(self):
1011 self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
1012
1013
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001014class TestGC(unittest.TestCase):
1015
1016 def makecycle(self, iterator, container):
1017 container.append(iterator)
1018 iterator.next()
1019 del container, iterator
1020
1021 def test_chain(self):
1022 a = []
1023 self.makecycle(chain(a), a)
1024
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001025 def test_chain_from_iterable(self):
1026 a = []
1027 self.makecycle(chain.from_iterable([a]), a)
1028
1029 def test_combinations(self):
1030 a = []
1031 self.makecycle(combinations([1,2,a,3], 3), a)
1032
Raymond Hettingerd081abc2009-01-27 02:58:49 +00001033 def test_combinations_with_replacement(self):
1034 a = []
1035 self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
1036
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001037 def test_compress(self):
1038 a = []
1039 self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
1040
Raymond Hettingerb21d8102009-02-16 20:39:12 +00001041 def test_count(self):
1042 a = []
1043 Int = type('Int', (int,), dict(x=a))
1044 self.makecycle(count(Int(0), Int(1)), a)
1045
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001046 def test_cycle(self):
1047 a = []
1048 self.makecycle(cycle([a]*2), a)
1049
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001050 def test_dropwhile(self):
1051 a = []
1052 self.makecycle(dropwhile(bool, [0, a, a]), a)
1053
1054 def test_groupby(self):
1055 a = []
1056 self.makecycle(groupby([a]*2, lambda x:x), a)
1057
Raymond Hettingera1ca94a2008-03-06 22:51:36 +00001058 def test_issue2246(self):
1059 # Issue 2246 -- the _grouper iterator was not included in GC
1060 n = 10
1061 keyfunc = lambda x: x
1062 for i, j in groupby(xrange(n), key=keyfunc):
1063 keyfunc.__dict__.setdefault('x',[]).append(j)
1064
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001065 def test_ifilter(self):
1066 a = []
1067 self.makecycle(ifilter(lambda x:True, [a]*2), a)
1068
1069 def test_ifilterfalse(self):
1070 a = []
1071 self.makecycle(ifilterfalse(lambda x:False, a), a)
1072
1073 def test_izip(self):
1074 a = []
1075 self.makecycle(izip([a]*2, [a]*3), a)
1076
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001077 def test_izip_longest(self):
1078 a = []
1079 self.makecycle(izip_longest([a]*2, [a]*3), a)
1080 b = [a, None]
1081 self.makecycle(izip_longest([a]*2, [a]*3, fillvalue=b), a)
1082
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001083 def test_imap(self):
1084 a = []
1085 self.makecycle(imap(lambda x:x, [a]*2), a)
1086
1087 def test_islice(self):
1088 a = []
1089 self.makecycle(islice([a]*2, None), a)
1090
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001091 def test_permutations(self):
1092 a = []
1093 self.makecycle(permutations([1,2,a,3], 3), a)
1094
1095 def test_product(self):
1096 a = []
1097 self.makecycle(product([1,2,a,3], repeat=3), a)
1098
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001099 def test_repeat(self):
1100 a = []
1101 self.makecycle(repeat(a), a)
1102
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001103 def test_starmap(self):
1104 a = []
1105 self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
1106
Raymond Hettingerff5dc0e2004-09-29 11:40:50 +00001107 def test_takewhile(self):
1108 a = []
1109 self.makecycle(takewhile(bool, [1, 0, a, a]), a)
1110
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001111def R(seqn):
1112 'Regular generator'
1113 for i in seqn:
1114 yield i
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001115
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001116class G:
1117 'Sequence using __getitem__'
1118 def __init__(self, seqn):
1119 self.seqn = seqn
1120 def __getitem__(self, i):
1121 return self.seqn[i]
1122
1123class I:
1124 'Sequence using iterator protocol'
1125 def __init__(self, seqn):
1126 self.seqn = seqn
1127 self.i = 0
1128 def __iter__(self):
1129 return self
1130 def next(self):
1131 if self.i >= len(self.seqn): raise StopIteration
1132 v = self.seqn[self.i]
1133 self.i += 1
1134 return v
1135
1136class Ig:
1137 'Sequence using iterator protocol defined with a generator'
1138 def __init__(self, seqn):
1139 self.seqn = seqn
1140 self.i = 0
1141 def __iter__(self):
1142 for val in self.seqn:
1143 yield val
1144
1145class X:
1146 'Missing __getitem__ and __iter__'
1147 def __init__(self, seqn):
1148 self.seqn = seqn
1149 self.i = 0
1150 def next(self):
1151 if self.i >= len(self.seqn): raise StopIteration
1152 v = self.seqn[self.i]
1153 self.i += 1
1154 return v
1155
1156class N:
1157 'Iterator missing next()'
1158 def __init__(self, seqn):
1159 self.seqn = seqn
1160 self.i = 0
1161 def __iter__(self):
1162 return self
1163
1164class E:
1165 'Test propagation of exceptions'
1166 def __init__(self, seqn):
1167 self.seqn = seqn
1168 self.i = 0
1169 def __iter__(self):
1170 return self
1171 def next(self):
Raymond Hettingerffdb8bb2004-09-27 15:29:05 +00001172 3 // 0
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001173
1174class S:
1175 'Test immediate stop'
1176 def __init__(self, seqn):
1177 pass
1178 def __iter__(self):
1179 return self
1180 def next(self):
1181 raise StopIteration
1182
1183def L(seqn):
1184 'Test multiple tiers of iterators'
1185 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
1186
1187
1188class TestVariousIteratorArgs(unittest.TestCase):
1189
1190 def test_chain(self):
1191 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1192 for g in (G, I, Ig, S, L, R):
1193 self.assertEqual(list(chain(g(s))), list(g(s)))
1194 self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
Raymond Hettinger05bf6332008-02-28 22:30:42 +00001195 self.assertRaises(TypeError, list, chain(X(s)))
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001196 self.assertRaises(TypeError, list, chain(N(s)))
1197 self.assertRaises(ZeroDivisionError, list, chain(E(s)))
1198
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001199 def test_compress(self):
1200 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1201 n = len(s)
1202 for g in (G, I, Ig, S, L, R):
1203 self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
1204 self.assertRaises(TypeError, compress, X(s), repeat(1))
1205 self.assertRaises(TypeError, list, compress(N(s), repeat(1)))
1206 self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
1207
Raymond Hettinger50986cc2008-02-22 03:16:42 +00001208 def test_product(self):
1209 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1210 self.assertRaises(TypeError, product, X(s))
1211 self.assertRaises(TypeError, product, N(s))
1212 self.assertRaises(ZeroDivisionError, product, E(s))
1213
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001214 def test_cycle(self):
1215 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1216 for g in (G, I, Ig, S, L, R):
1217 tgtlen = len(s) * 3
1218 expected = list(g(s))*3
1219 actual = list(islice(cycle(g(s)), tgtlen))
1220 self.assertEqual(actual, expected)
1221 self.assertRaises(TypeError, cycle, X(s))
1222 self.assertRaises(TypeError, list, cycle(N(s)))
1223 self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
1224
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001225 def test_groupby(self):
1226 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1227 for g in (G, I, Ig, S, L, R):
1228 self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
1229 self.assertRaises(TypeError, groupby, X(s))
1230 self.assertRaises(TypeError, list, groupby(N(s)))
1231 self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
1232
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001233 def test_ifilter(self):
1234 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1235 for g in (G, I, Ig, S, L, R):
1236 self.assertEqual(list(ifilter(isEven, g(s))), filter(isEven, g(s)))
1237 self.assertRaises(TypeError, ifilter, isEven, X(s))
1238 self.assertRaises(TypeError, list, ifilter(isEven, N(s)))
1239 self.assertRaises(ZeroDivisionError, list, ifilter(isEven, E(s)))
1240
1241 def test_ifilterfalse(self):
1242 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1243 for g in (G, I, Ig, S, L, R):
1244 self.assertEqual(list(ifilterfalse(isEven, g(s))), filter(isOdd, g(s)))
1245 self.assertRaises(TypeError, ifilterfalse, isEven, X(s))
1246 self.assertRaises(TypeError, list, ifilterfalse(isEven, N(s)))
1247 self.assertRaises(ZeroDivisionError, list, ifilterfalse(isEven, E(s)))
1248
1249 def test_izip(self):
1250 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1251 for g in (G, I, Ig, S, L, R):
1252 self.assertEqual(list(izip(g(s))), zip(g(s)))
1253 self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s)))
1254 self.assertRaises(TypeError, izip, X(s))
1255 self.assertRaises(TypeError, list, izip(N(s)))
1256 self.assertRaises(ZeroDivisionError, list, izip(E(s)))
1257
Raymond Hettingerd36862c2007-02-21 05:20:38 +00001258 def test_iziplongest(self):
1259 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1260 for g in (G, I, Ig, S, L, R):
1261 self.assertEqual(list(izip_longest(g(s))), zip(g(s)))
1262 self.assertEqual(list(izip_longest(g(s), g(s))), zip(g(s), g(s)))
1263 self.assertRaises(TypeError, izip_longest, X(s))
1264 self.assertRaises(TypeError, list, izip_longest(N(s)))
1265 self.assertRaises(ZeroDivisionError, list, izip_longest(E(s)))
1266
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001267 def test_imap(self):
1268 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1269 for g in (G, I, Ig, S, L, R):
1270 self.assertEqual(list(imap(onearg, g(s))), map(onearg, g(s)))
1271 self.assertEqual(list(imap(operator.pow, g(s), g(s))), map(operator.pow, g(s), g(s)))
1272 self.assertRaises(TypeError, imap, onearg, X(s))
1273 self.assertRaises(TypeError, list, imap(onearg, N(s)))
1274 self.assertRaises(ZeroDivisionError, list, imap(onearg, E(s)))
1275
1276 def test_islice(self):
1277 for s in ("12345", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1278 for g in (G, I, Ig, S, L, R):
1279 self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
1280 self.assertRaises(TypeError, islice, X(s), 10)
1281 self.assertRaises(TypeError, list, islice(N(s), 10))
1282 self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
1283
1284 def test_starmap(self):
1285 for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)):
1286 for g in (G, I, Ig, S, L, R):
1287 ss = zip(s, s)
1288 self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s)))
1289 self.assertRaises(TypeError, starmap, operator.pow, X(ss))
1290 self.assertRaises(TypeError, list, starmap(operator.pow, N(ss)))
1291 self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
1292
1293 def test_takewhile(self):
1294 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1295 for g in (G, I, Ig, S, L, R):
1296 tgt = []
1297 for elem in g(s):
1298 if not isEven(elem): break
1299 tgt.append(elem)
1300 self.assertEqual(list(takewhile(isEven, g(s))), tgt)
1301 self.assertRaises(TypeError, takewhile, isEven, X(s))
1302 self.assertRaises(TypeError, list, takewhile(isEven, N(s)))
1303 self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
1304
1305 def test_dropwhile(self):
1306 for s in (range(10), range(0), range(1000), (7,11), xrange(2000,2200,5)):
1307 for g in (G, I, Ig, S, L, R):
1308 tgt = []
1309 for elem in g(s):
1310 if not tgt and isOdd(elem): continue
1311 tgt.append(elem)
1312 self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
1313 self.assertRaises(TypeError, dropwhile, isOdd, X(s))
1314 self.assertRaises(TypeError, list, dropwhile(isOdd, N(s)))
1315 self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
1316
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001317 def test_tee(self):
1318 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1319 for g in (G, I, Ig, S, L, R):
1320 it1, it2 = tee(g(s))
1321 self.assertEqual(list(it1), list(g(s)))
1322 self.assertEqual(list(it2), list(g(s)))
1323 self.assertRaises(TypeError, tee, X(s))
1324 self.assertRaises(TypeError, list, tee(N(s))[0])
1325 self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
1326
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001327class LengthTransparency(unittest.TestCase):
1328
1329 def test_repeat(self):
Raymond Hettinger6b27cda2005-09-24 21:23:05 +00001330 from test.test_iterlen import len
Raymond Hettinger5cab2e32004-02-10 09:25:40 +00001331 self.assertEqual(len(repeat(None, 50)), 50)
1332 self.assertRaises(TypeError, len, repeat(None))
1333
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001334class RegressionTests(unittest.TestCase):
1335
1336 def test_sf_793826(self):
1337 # Fix Armin Rigo's successful efforts to wreak havoc
1338
1339 def mutatingtuple(tuple1, f, tuple2):
1340 # this builds a tuple t which is a copy of tuple1,
1341 # then calls f(t), then mutates t to be equal to tuple2
1342 # (needs len(tuple1) == len(tuple2)).
1343 def g(value, first=[1]):
1344 if first:
1345 del first[:]
1346 f(z.next())
1347 return value
1348 items = list(tuple2)
1349 items[1:1] = list(tuple1)
1350 gen = imap(g, items)
1351 z = izip(*[gen]*len(tuple1))
1352 z.next()
1353
1354 def f(t):
1355 global T
1356 T = t
1357 first[:] = list(T)
1358
1359 first = []
1360 mutatingtuple((1,2,3), f, (4,5,6))
1361 second = list(T)
1362 self.assertEqual(first, second)
1363
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001364
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001365 def test_sf_950057(self):
1366 # Make sure that chain() and cycle() catch exceptions immediately
1367 # rather than when shifting between input sources
1368
1369 def gen1():
1370 hist.append(0)
1371 yield 1
1372 hist.append(1)
Tim Petersbeb7c0c2004-07-18 17:34:03 +00001373 raise AssertionError
Raymond Hettinger9d7c8702004-05-08 19:49:42 +00001374 hist.append(2)
1375
1376 def gen2(x):
1377 hist.append(3)
1378 yield 2
1379 hist.append(4)
1380 if x:
1381 raise StopIteration
1382
1383 hist = []
1384 self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
1385 self.assertEqual(hist, [0,1])
1386
1387 hist = []
1388 self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
1389 self.assertEqual(hist, [0,1])
1390
1391 hist = []
1392 self.assertRaises(AssertionError, list, cycle(gen1()))
1393 self.assertEqual(hist, [0,1])
1394
Georg Brandlb84c1372007-01-21 10:28:43 +00001395class SubclassWithKwargsTest(unittest.TestCase):
1396 def test_keywords_in_subclass(self):
1397 # count is not subclassable...
1398 for cls in (repeat, izip, ifilter, ifilterfalse, chain, imap,
Raymond Hettinger2bcb8e92009-01-25 21:04:14 +00001399 starmap, islice, takewhile, dropwhile, cycle, compress):
Georg Brandlb84c1372007-01-21 10:28:43 +00001400 class Subclass(cls):
1401 def __init__(self, newarg=None, *args):
1402 cls.__init__(self, *args)
1403 try:
1404 Subclass(newarg=1)
1405 except TypeError, err:
1406 # we expect type errors because of wrong argument count
Ezio Melottiaa980582010-01-23 23:04:36 +00001407 self.assertNotIn("does not take keyword arguments", err.args[0])
Georg Brandlb84c1372007-01-21 10:28:43 +00001408
1409
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001410libreftest = """ Doctest for examples in the library reference: libitertools.tex
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001411
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001412
1413>>> amounts = [120.15, 764.05, 823.14]
1414>>> for checknum, amount in izip(count(1200), amounts):
1415... print 'Check %d is for $%.2f' % (checknum, amount)
1416...
1417Check 1200 is for $120.15
1418Check 1201 is for $764.05
1419Check 1202 is for $823.14
1420
1421>>> import operator
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001422>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
1423... print cube
1424...
14251
14268
142727
1428
1429>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +00001430>>> for name in islice(reportlines, 3, None, 2):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001431... print name.title()
1432...
1433Alex
1434Laura
1435Martin
1436Walter
1437Samuele
1438
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001439>>> from operator import itemgetter
1440>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Armin Rigoa3f09272006-05-28 19:13:17 +00001441>>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +00001442>>> for k, g in groupby(di, itemgetter(1)):
1443... print k, map(itemgetter(0), g)
1444...
14451 ['a', 'c', 'e']
14462 ['b', 'd', 'f']
14473 ['g']
1448
Raymond Hettinger734fb572004-01-20 20:04:40 +00001449# Find runs of consecutive numbers using groupby. The key to the solution
1450# is differencing with a range so that consecutive numbers all appear in
1451# same group.
1452>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Ezio Melottidde5b942010-02-03 05:37:26 +00001453>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Raymond Hettinger734fb572004-01-20 20:04:40 +00001454... print map(operator.itemgetter(1), g)
1455...
1456[1]
1457[4, 5, 6]
1458[10]
1459[15, 16, 17, 18]
1460[22]
1461[25, 26, 27, 28]
1462
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001463>>> def take(n, iterable):
1464... "Return first n items of the iterable as a list"
1465... return list(islice(iterable, n))
Raymond Hettingera098b332003-09-08 23:58:40 +00001466
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001467>>> def enumerate(iterable, start=0):
1468... return izip(count(start), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001469
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001470>>> def tabulate(function, start=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001471... "Return function(0), function(1), ..."
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001472... return imap(function, count(start))
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001473
Raymond Hettingerf9bce832009-02-19 05:34:35 +00001474>>> def nth(iterable, n, default=None):
1475... "Returns the nth item or a default value"
1476... return next(islice(iterable, n, None), default)
Raymond Hettinger60eca932003-02-09 06:40:58 +00001477
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001478>>> def quantify(iterable, pred=bool):
1479... "Count how many times the predicate is true"
1480... return sum(imap(pred, iterable))
Raymond Hettinger60eca932003-02-09 06:40:58 +00001481
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001482>>> def padnone(iterable):
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001483... "Returns the sequence elements and then returns None indefinitely"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001484... return chain(iterable, repeat(None))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001485
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001486>>> def ncycles(iterable, n):
Ezio Melottic2077b02011-03-16 12:34:31 +02001487... "Returns the sequence elements n times"
Raymond Hettingerf1f46f02008-07-19 23:58:47 +00001488... return chain(*repeat(iterable, n))
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001489
1490>>> def dotproduct(vec1, vec2):
1491... return sum(imap(operator.mul, vec1, vec2))
1492
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001493>>> def flatten(listOfLists):
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001494... return list(chain.from_iterable(listOfLists))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001495
1496>>> def repeatfunc(func, times=None, *args):
1497... "Repeat calls to func with specified arguments."
1498... " Example: repeatfunc(random.random)"
1499... if times is None:
1500... return starmap(func, repeat(args))
1501... else:
1502... return starmap(func, repeat(args, times))
1503
Raymond Hettingerd591f662003-10-26 15:34:50 +00001504>>> def pairwise(iterable):
1505... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1506... a, b = tee(iterable)
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001507... for elem in b:
1508... break
Raymond Hettingerad983e72003-11-12 14:32:26 +00001509... return izip(a, b)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001510
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001511>>> def grouper(n, iterable, fillvalue=None):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001512... "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
Raymond Hettinger38fb9be2008-03-07 01:33:20 +00001513... args = [iter(iterable)] * n
Raymond Hettingerf080e6d2008-07-31 01:19:50 +00001514... return izip_longest(fillvalue=fillvalue, *args)
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001515
1516>>> def roundrobin(*iterables):
Raymond Hettingerefdf7062008-07-30 07:27:30 +00001517... "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001518... # Recipe credited to George Sakkis
1519... pending = len(iterables)
1520... nexts = cycle(iter(it).next for it in iterables)
1521... while pending:
1522... try:
1523... for next in nexts:
1524... yield next()
1525... except StopIteration:
1526... pending -= 1
1527... nexts = cycle(islice(nexts, pending))
1528
1529>>> def powerset(iterable):
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001530... "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
1531... s = list(iterable)
1532... return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001533
Raymond Hettinger44e15812009-01-02 21:26:45 +00001534>>> def unique_everseen(iterable, key=None):
1535... "List unique elements, preserving order. Remember all elements ever seen."
1536... # unique_everseen('AAAABBBCCDAABBB') --> A B C D
1537... # unique_everseen('ABBCcAD', str.lower) --> A B C D
1538... seen = set()
1539... seen_add = seen.add
1540... if key is None:
1541... for element in iterable:
1542... if element not in seen:
1543... seen_add(element)
1544... yield element
1545... else:
1546... for element in iterable:
1547... k = key(element)
1548... if k not in seen:
1549... seen_add(k)
1550... yield element
1551
1552>>> def unique_justseen(iterable, key=None):
1553... "List unique elements, preserving order. Remember only the element just seen."
1554... # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
1555... # unique_justseen('ABBCcAD', str.lower) --> A B C A D
1556... return imap(next, imap(itemgetter(1), groupby(iterable, key)))
1557
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001558This is not part of the examples but it tests to make sure the definitions
1559perform as purported.
1560
Raymond Hettingera098b332003-09-08 23:58:40 +00001561>>> take(10, count())
1562[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1563
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001564>>> list(enumerate('abc'))
1565[(0, 'a'), (1, 'b'), (2, 'c')]
1566
1567>>> list(islice(tabulate(lambda x: 2*x), 4))
1568[0, 2, 4, 6]
1569
1570>>> nth('abcde', 3)
Raymond Hettingerd507afd2009-02-04 10:52:32 +00001571'd'
1572
1573>>> nth('abcde', 9) is None
1574True
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001575
Raymond Hettingerdbe3d282003-10-05 16:47:36 +00001576>>> quantify(xrange(99), lambda x: x%2==0)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000157750
1578
Raymond Hettinger6a5b0272003-10-24 08:45:23 +00001579>>> a = [[1, 2, 3], [4, 5, 6]]
1580>>> flatten(a)
1581[1, 2, 3, 4, 5, 6]
1582
1583>>> list(repeatfunc(pow, 5, 2, 3))
1584[8, 8, 8, 8, 8]
1585
1586>>> import random
1587>>> take(5, imap(int, repeatfunc(random.random)))
1588[0, 0, 0, 0, 0]
1589
Raymond Hettingerd591f662003-10-26 15:34:50 +00001590>>> list(pairwise('abcd'))
1591[('a', 'b'), ('b', 'c'), ('c', 'd')]
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001592
Raymond Hettingerd591f662003-10-26 15:34:50 +00001593>>> list(pairwise([]))
1594[]
1595
1596>>> list(pairwise('a'))
Raymond Hettingerbefa37d2003-06-18 19:25:37 +00001597[]
1598
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001599>>> list(islice(padnone('abc'), 0, 6))
1600['a', 'b', 'c', None, None, None]
1601
1602>>> list(ncycles('abc', 3))
1603['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
1604
1605>>> dotproduct([1,2,3], [4,5,6])
160632
1607
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001608>>> list(grouper(3, 'abcdefg', 'x'))
1609[('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
1610
1611>>> list(roundrobin('abc', 'd', 'ef'))
1612['a', 'd', 'e', 'b', 'f', 'c']
1613
Raymond Hettinger68d919e2009-01-25 21:31:47 +00001614>>> list(powerset([1,2,3]))
1615[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001616
Raymond Hettinger560f9a82009-01-27 13:26:35 +00001617>>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
1618True
1619
1620>>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
1621True
1622
Raymond Hettinger44e15812009-01-02 21:26:45 +00001623>>> list(unique_everseen('AAAABBBCCDAABBB'))
1624['A', 'B', 'C', 'D']
1625
1626>>> list(unique_everseen('ABBCcAD', str.lower))
1627['A', 'B', 'C', 'D']
1628
1629>>> list(unique_justseen('AAAABBBCCDAABBB'))
1630['A', 'B', 'C', 'D', 'A', 'B']
1631
1632>>> list(unique_justseen('ABBCcAD', str.lower))
1633['A', 'B', 'C', 'A', 'D']
1634
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001635"""
1636
1637__test__ = {'libreftest' : libreftest}
1638
1639def test_main(verbose=None):
Raymond Hettingera56f6b62003-08-29 23:09:58 +00001640 test_classes = (TestBasicOps, TestVariousIteratorArgs, TestGC,
Georg Brandlb84c1372007-01-21 10:28:43 +00001641 RegressionTests, LengthTransparency,
Raymond Hettingerad47fa12008-03-06 20:52:01 +00001642 SubclassWithKwargsTest, TestExamples)
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001643 test_support.run_unittest(*test_classes)
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001644
1645 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001646 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger02420702003-06-29 20:36:23 +00001647 import gc
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001648 counts = [None] * 5
1649 for i in xrange(len(counts)):
Raymond Hettingerf0fa1c02003-05-29 07:18:57 +00001650 test_support.run_unittest(*test_classes)
Raymond Hettinger02420702003-06-29 20:36:23 +00001651 gc.collect()
Raymond Hettinger8fd3f872003-05-02 22:38:07 +00001652 counts[i] = sys.gettotalrefcount()
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001653 print counts
1654
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001655 # doctest the examples in the library reference
Raymond Hettinger929f06c2003-05-16 23:16:36 +00001656 test_support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +00001657
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001658if __name__ == "__main__":
1659 test_main(verbose=True)