blob: d9c1c41d025ff21c6ce7b530069ccfb04b9a4385 [file] [log] [blame]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001import unittest
2from test import test_support
3from itertools import *
Raymond Hettinger2012f172003-02-07 05:32:58 +00004import sys
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +00005import operator
6
7def onearg(x):
8 'Test function of one argument'
9 return x
10
11def errfunc(*args):
12 'Test function that raises an error'
13 raise ValueError
14
15def gen3():
16 'Non-restartable source sequence'
17 for i in (0, 1, 2):
18 yield i
19
20def isEven(x):
21 'Test predicate'
22 return x%2==0
23
24class StopNow:
25 'Class emulating an empty iterable.'
26 def __iter__(self):
27 return self
28 def next(self):
29 raise StopIteration
Raymond Hettinger96ef8112003-02-01 00:10:11 +000030
31class TestBasicOps(unittest.TestCase):
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000032 def test_chain(self):
33 self.assertEqual(list(chain('abc', 'def')), list('abcdef'))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000034 self.assertEqual(list(chain('abc')), list('abc'))
35 self.assertEqual(list(chain('')), [])
36 self.assertRaises(TypeError, chain, 2, 3)
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000037
Raymond Hettinger96ef8112003-02-01 00:10:11 +000038 def test_count(self):
39 self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
40 self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
41 self.assertRaises(TypeError, count, 2, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000042 self.assertRaises(TypeError, count, 'a')
43 c = count(sys.maxint-2) # verify that rollover doesn't crash
44 c.next(); c.next(); c.next(); c.next(); c.next()
Raymond Hettinger96ef8112003-02-01 00:10:11 +000045
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000046 def test_cycle(self):
47 self.assertEqual(list(islice(cycle('abc'),10)), list('abcabcabca'))
48 self.assertEqual(list(cycle('')), [])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000049 self.assertRaises(TypeError, cycle)
50 self.assertRaises(TypeError, cycle, 5)
51 self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000052
Raymond Hettinger96ef8112003-02-01 00:10:11 +000053 def test_ifilter(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +000054 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
Raymond Hettinger96ef8112003-02-01 00:10:11 +000055 self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
56 self.assertRaises(TypeError, ifilter)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000057 self.assertRaises(TypeError, ifilter, lambda x:x)
58 self.assertRaises(TypeError, ifilter, lambda x:x, range(6), 7)
Raymond Hettinger96ef8112003-02-01 00:10:11 +000059 self.assertRaises(TypeError, ifilter, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000060 self.assertRaises(TypeError, ifilter(range(6), range(6)).next)
Raymond Hettinger60eca932003-02-09 06:40:58 +000061
62 def test_ifilterfalse(self):
Raymond Hettinger60eca932003-02-09 06:40:58 +000063 self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
64 self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
65 self.assertRaises(TypeError, ifilterfalse)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000066 self.assertRaises(TypeError, ifilterfalse, lambda x:x)
67 self.assertRaises(TypeError, ifilterfalse, lambda x:x, range(6), 7)
Raymond Hettinger60eca932003-02-09 06:40:58 +000068 self.assertRaises(TypeError, ifilterfalse, isEven, 3)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000069 self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +000070
71 def test_izip(self):
72 ans = [(x,y) for x, y in izip('abc',count())]
73 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000074 self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6)))
75 self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3)))
76 self.assertEqual(list(izip('abcdef')), zip('abcdef'))
Raymond Hettinger96ef8112003-02-01 00:10:11 +000077 self.assertRaises(TypeError, izip)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000078 self.assertRaises(TypeError, izip, 3)
79 self.assertRaises(TypeError, izip, range(3), 3)
80 # Check tuple re-use (implementation detail)
81 self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')],
82 zip('abc', 'def'))
83 ids = map(id, izip('abc', 'def'))
84 self.assertEqual(min(ids), max(ids))
Raymond Hettinger96ef8112003-02-01 00:10:11 +000085
86 def test_repeat(self):
87 self.assertEqual(zip(xrange(3),repeat('a')),
88 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000089 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000090 self.assertEqual(list(repeat('a', 0)), [])
91 self.assertEqual(list(repeat('a', -3)), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +000092 self.assertRaises(TypeError, repeat)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +000093 self.assertRaises(TypeError, repeat, None, 3, 4)
94 self.assertRaises(TypeError, repeat, None, 'a')
Raymond Hettinger96ef8112003-02-01 00:10:11 +000095
Raymond Hettinger96ef8112003-02-01 00:10:11 +000096 def test_imap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +000097 self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
98 [0**1, 1**2, 2**3])
99 self.assertEqual(list(imap(None, 'abc', range(5))),
100 [('a',0),('b',1),('c',2)])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000101 self.assertEqual(list(imap(operator.pow, [])), [])
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000102 self.assertRaises(TypeError, imap)
103 self.assertRaises(TypeError, imap, operator.neg)
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000104 self.assertRaises(TypeError, imap(10, range(5)).next)
105 self.assertRaises(ValueError, imap(errfunc, [4], [5]).next)
106 self.assertRaises(TypeError, imap(onearg, [4], [5]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000107
108 def test_starmap(self):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000109 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
110 [0**1, 1**2, 2**3])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000111 self.assertEqual(list(starmap(operator.pow, [])), [])
Raymond Hettinger2012f172003-02-07 05:32:58 +0000112 self.assertRaises(TypeError, list, starmap(operator.pow, [[4,5]]))
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000113 self.assertRaises(TypeError, starmap)
114 self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
115 self.assertRaises(TypeError, starmap(10, [(4,5)]).next)
116 self.assertRaises(ValueError, starmap(errfunc, [(4,5)]).next)
117 self.assertRaises(TypeError, starmap(onearg, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000118
119 def test_islice(self):
120 for args in [ # islice(args) should agree with range(args)
121 (10, 20, 3),
122 (10, 3, 20),
123 (10, 20),
124 (10, 3),
125 (20,)
126 ]:
127 self.assertEqual(list(islice(xrange(100), *args)), range(*args))
128
129 for args, tgtargs in [ # Stop when seqn is exhausted
130 ((10, 110, 3), ((10, 100, 3))),
131 ((10, 110), ((10, 100))),
132 ((110,), (100,))
133 ]:
134 self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
135
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000136 # Test stop=None
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000137 self.assertEqual(list(islice(xrange(10), None)), range(10))
138 self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
139 self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
140
141 # Test invalid arguments
Raymond Hettinger341deb72003-05-02 19:44:20 +0000142 self.assertRaises(TypeError, islice, xrange(10))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000143 self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
144 self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
145 self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
146 self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
147 self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000148 self.assertRaises(ValueError, islice, xrange(10), 'a')
149 self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
150 self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
151 self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
152 self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
Raymond Hettinger2012f172003-02-07 05:32:58 +0000153 self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000154
155 def test_takewhile(self):
156 data = [1, 3, 5, 20, 2, 4, 6, 8]
157 underten = lambda x: x<10
158 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000159 self.assertEqual(list(takewhile(underten, [])), [])
160 self.assertRaises(TypeError, takewhile)
161 self.assertRaises(TypeError, takewhile, operator.pow)
162 self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
163 self.assertRaises(TypeError, takewhile(10, [(4,5)]).next)
164 self.assertRaises(ValueError, takewhile(errfunc, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000165
166 def test_dropwhile(self):
167 data = [1, 3, 5, 20, 2, 4, 6, 8]
168 underten = lambda x: x<10
169 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
Raymond Hettinger7c2bb5b2003-05-03 05:59:48 +0000170 self.assertEqual(list(dropwhile(underten, [])), [])
171 self.assertRaises(TypeError, dropwhile)
172 self.assertRaises(TypeError, dropwhile, operator.pow)
173 self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
174 self.assertRaises(TypeError, dropwhile(10, [(4,5)]).next)
175 self.assertRaises(ValueError, dropwhile(errfunc, [(4,5)]).next)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000176
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000177 def test_StopIteration(self):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000178 for f in (chain, cycle, izip):
179 self.assertRaises(StopIteration, f([]).next)
180 self.assertRaises(StopIteration, f(StopNow()).next)
181
182 self.assertRaises(StopIteration, islice([], None).next)
183 self.assertRaises(StopIteration, islice(StopNow(), None).next)
184
185 self.assertRaises(StopIteration, repeat(None, 0).next)
186
187 for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
188 self.assertRaises(StopIteration, f(lambda x:x, []).next)
189 self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
190
191
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000192libreftest = """ Doctest for examples in the library reference, libitertools.tex
193
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000194
195>>> amounts = [120.15, 764.05, 823.14]
196>>> for checknum, amount in izip(count(1200), amounts):
197... print 'Check %d is for $%.2f' % (checknum, amount)
198...
199Check 1200 is for $120.15
200Check 1201 is for $764.05
201Check 1202 is for $823.14
202
203>>> import operator
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000204>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
205... print cube
206...
2071
2088
20927
210
211>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
212>>> for name in islice(reportlines, 3, len(reportlines), 2):
213... print name.title()
214...
215Alex
216Laura
217Martin
218Walter
219Samuele
220
221>>> def enumerate(iterable):
222... return izip(count(), iterable)
223
224>>> def tabulate(function):
225... "Return function(0), function(1), ..."
226... return imap(function, count())
227
228>>> def iteritems(mapping):
229... return izip(mapping.iterkeys(), mapping.itervalues())
230
231>>> def nth(iterable, n):
232... "Returns the nth item"
Raymond Hettinger60eca932003-02-09 06:40:58 +0000233... return list(islice(iterable, n, n+1))
234
235>>> def all(pred, seq):
236... "Returns True if pred(x) is True for every element in the iterable"
237... return not nth(ifilterfalse(pred, seq), 0)
238
239>>> def some(pred, seq):
240... "Returns True if pred(x) is True at least one element in the iterable"
241... return bool(nth(ifilter(pred, seq), 0))
242
243>>> def no(pred, seq):
244... "Returns True if pred(x) is False for every element in the iterable"
245... return not nth(ifilter(pred, seq), 0)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000246
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000247>>> def pairwise(seq):
248... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
249... return izip(seq, islice(seq,1,len(seq)))
250
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000251>>> def padnone(seq):
252... "Returns the sequence elements and then returns None indefinitely"
253... return chain(seq, repeat(None))
254
255>>> def ncycles(seq, n):
256... "Returns the sequence elements n times"
257... return chain(*repeat(seq, n))
258
259>>> def dotproduct(vec1, vec2):
260... return sum(imap(operator.mul, vec1, vec2))
261
262
263This is not part of the examples but it tests to make sure the definitions
264perform as purported.
265
266>>> list(enumerate('abc'))
267[(0, 'a'), (1, 'b'), (2, 'c')]
268
269>>> list(islice(tabulate(lambda x: 2*x), 4))
270[0, 2, 4, 6]
271
272>>> nth('abcde', 3)
273['d']
274
275>>> all(lambda x: x%2==0, [2, 4, 6, 8])
276True
277
278>>> all(lambda x: x%2==0, [2, 3, 6, 8])
279False
280
281>>> some(lambda x: x%2==0, [2, 4, 6, 8])
282True
283
284>>> some(lambda x: x%2==0, [1, 3, 5, 9])
285False
286
287>>> no(lambda x: x%2==0, [1, 3, 5, 9])
288True
289
290>>> no(lambda x: x%2==0, [1, 2, 5, 9])
291False
292
293>>> list(pairwise('abc'))
294[('a', 'b'), ('b', 'c')]
295
296>>> list(islice(padnone('abc'), 0, 6))
297['a', 'b', 'c', None, None, None]
298
299>>> list(ncycles('abc', 3))
300['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
301
302>>> dotproduct([1,2,3], [4,5,6])
30332
304
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000305"""
306
307__test__ = {'libreftest' : libreftest}
308
309def test_main(verbose=None):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000310 test_support.run_unittest(TestBasicOps)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000311
312 # verify reference counting
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000313 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000314 counts = [None] * 5
315 for i in xrange(len(counts)):
316 test_support.run_unittest(TestBasicOps)
317 counts[i] = sys.gettotalrefcount()
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000318 print counts
319
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000320 # doctest the examples in the library reference
Raymond Hettinger929f06c2003-05-16 23:16:36 +0000321 test_support.run_doctest(sys.modules[__name__], verbose)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000322
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000323if __name__ == "__main__":
324 test_main(verbose=True)