blob: 7a4fa209ab93f4ac5d6f6effeff276a689e404eb [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
204>>> import operator
205>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
206... print cube
207...
2081
2098
21027
211
212>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
213>>> for name in islice(reportlines, 3, len(reportlines), 2):
214... print name.title()
215...
216Alex
217Laura
218Martin
219Walter
220Samuele
221
222>>> def enumerate(iterable):
223... return izip(count(), iterable)
224
225>>> def tabulate(function):
226... "Return function(0), function(1), ..."
227... return imap(function, count())
228
229>>> def iteritems(mapping):
230... return izip(mapping.iterkeys(), mapping.itervalues())
231
232>>> def nth(iterable, n):
233... "Returns the nth item"
Raymond Hettinger60eca932003-02-09 06:40:58 +0000234... return list(islice(iterable, n, n+1))
235
236>>> def all(pred, seq):
237... "Returns True if pred(x) is True for every element in the iterable"
238... return not nth(ifilterfalse(pred, seq), 0)
239
240>>> def some(pred, seq):
241... "Returns True if pred(x) is True at least one element in the iterable"
242... return bool(nth(ifilter(pred, seq), 0))
243
244>>> def no(pred, seq):
245... "Returns True if pred(x) is False for every element in the iterable"
246... return not nth(ifilter(pred, seq), 0)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000247
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000248>>> def pairwise(seq):
249... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
250... return izip(seq, islice(seq,1,len(seq)))
251
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000252>>> def padnone(seq):
253... "Returns the sequence elements and then returns None indefinitely"
254... return chain(seq, repeat(None))
255
256>>> def ncycles(seq, n):
257... "Returns the sequence elements n times"
258... return chain(*repeat(seq, n))
259
260>>> def dotproduct(vec1, vec2):
261... return sum(imap(operator.mul, vec1, vec2))
262
263
264This is not part of the examples but it tests to make sure the definitions
265perform as purported.
266
267>>> list(enumerate('abc'))
268[(0, 'a'), (1, 'b'), (2, 'c')]
269
270>>> list(islice(tabulate(lambda x: 2*x), 4))
271[0, 2, 4, 6]
272
273>>> nth('abcde', 3)
274['d']
275
276>>> all(lambda x: x%2==0, [2, 4, 6, 8])
277True
278
279>>> all(lambda x: x%2==0, [2, 3, 6, 8])
280False
281
282>>> some(lambda x: x%2==0, [2, 4, 6, 8])
283True
284
285>>> some(lambda x: x%2==0, [1, 3, 5, 9])
286False
287
288>>> no(lambda x: x%2==0, [1, 3, 5, 9])
289True
290
291>>> no(lambda x: x%2==0, [1, 2, 5, 9])
292False
293
294>>> list(pairwise('abc'))
295[('a', 'b'), ('b', 'c')]
296
297>>> list(islice(padnone('abc'), 0, 6))
298['a', 'b', 'c', None, None, None]
299
300>>> list(ncycles('abc', 3))
301['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
302
303>>> dotproduct([1,2,3], [4,5,6])
30432
305
306
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000307"""
308
309__test__ = {'libreftest' : libreftest}
310
311def test_main(verbose=None):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000312 test_support.run_unittest(TestBasicOps)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000313
314 # verify reference counting
315 import sys
316 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000317 counts = [None] * 5
318 for i in xrange(len(counts)):
319 test_support.run_unittest(TestBasicOps)
320 counts[i] = sys.gettotalrefcount()
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000321 print counts
322
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000323 # doctest the examples in the library reference
324 import doctest
325 doctest.testmod(sys.modules[__name__])
326
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000327if __name__ == "__main__":
328 test_main(verbose=True)