blob: e03ce8c18d76114db6ab01803033136ffa89f43d [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 Hettinger96ef8112003-02-01 00:10:11 +00005
6class TestBasicOps(unittest.TestCase):
Raymond Hettinger61fe64d2003-02-23 04:40:07 +00007 def test_chain(self):
8 self.assertEqual(list(chain('abc', 'def')), list('abcdef'))
9
Raymond Hettinger96ef8112003-02-01 00:10:11 +000010 def test_count(self):
11 self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
12 self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
13 self.assertRaises(TypeError, count, 2, 3)
14
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000015 def test_cycle(self):
16 self.assertEqual(list(islice(cycle('abc'),10)), list('abcabcabca'))
17 self.assertEqual(list(cycle('')), [])
18
Raymond Hettinger96ef8112003-02-01 00:10:11 +000019 def test_ifilter(self):
20 def isEven(x):
21 return x%2==0
22 self.assertEqual(list(ifilter(isEven, range(6))), [0,2,4])
Raymond Hettinger96ef8112003-02-01 00:10:11 +000023 self.assertEqual(list(ifilter(None, [0,1,0,2,0])), [1,2])
24 self.assertRaises(TypeError, ifilter)
25 self.assertRaises(TypeError, ifilter, 3)
26 self.assertRaises(TypeError, ifilter, isEven, 3)
Raymond Hettinger60eca932003-02-09 06:40:58 +000027
28 def test_ifilterfalse(self):
29 def isEven(x):
30 return x%2==0
31 self.assertEqual(list(ifilterfalse(isEven, range(6))), [1,3,5])
32 self.assertEqual(list(ifilterfalse(None, [0,1,0,2,0])), [0,0,0])
33 self.assertRaises(TypeError, ifilterfalse)
34 self.assertRaises(TypeError, ifilterfalse, 3)
35 self.assertRaises(TypeError, ifilterfalse, isEven, 3)
Raymond Hettinger96ef8112003-02-01 00:10:11 +000036
37 def test_izip(self):
38 ans = [(x,y) for x, y in izip('abc',count())]
39 self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
40 self.assertRaises(TypeError, izip)
41
42 def test_repeat(self):
43 self.assertEqual(zip(xrange(3),repeat('a')),
44 [(0, 'a'), (1, 'a'), (2, 'a')])
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000045 self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
Raymond Hettinger96ef8112003-02-01 00:10:11 +000046 self.assertRaises(TypeError, repeat)
47
Raymond Hettinger96ef8112003-02-01 00:10:11 +000048 def test_imap(self):
49 import operator
50 self.assertEqual(list(imap(operator.pow, range(3), range(1,7))),
51 [0**1, 1**2, 2**3])
52 self.assertEqual(list(imap(None, 'abc', range(5))),
53 [('a',0),('b',1),('c',2)])
54 self.assertRaises(TypeError, imap)
55 self.assertRaises(TypeError, imap, operator.neg)
56
57 def test_starmap(self):
58 import operator
59 self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
60 [0**1, 1**2, 2**3])
Raymond Hettinger2012f172003-02-07 05:32:58 +000061 self.assertRaises(TypeError, list, starmap(operator.pow, [[4,5]]))
Raymond Hettinger96ef8112003-02-01 00:10:11 +000062
63 def test_islice(self):
64 for args in [ # islice(args) should agree with range(args)
65 (10, 20, 3),
66 (10, 3, 20),
67 (10, 20),
68 (10, 3),
69 (20,)
70 ]:
71 self.assertEqual(list(islice(xrange(100), *args)), range(*args))
72
73 for args, tgtargs in [ # Stop when seqn is exhausted
74 ((10, 110, 3), ((10, 100, 3))),
75 ((10, 110), ((10, 100))),
76 ((110,), (100,))
77 ]:
78 self.assertEqual(list(islice(xrange(100), *args)), range(*tgtargs))
79
Raymond Hettinger14ef54c2003-05-02 19:04:37 +000080 # Test stop=None
Raymond Hettinger14ef54c2003-05-02 19:04:37 +000081 self.assertEqual(list(islice(xrange(10), None)), range(10))
82 self.assertEqual(list(islice(xrange(10), 2, None)), range(2, 10))
83 self.assertEqual(list(islice(xrange(10), 1, None, 2)), range(1, 10, 2))
84
85 # Test invalid arguments
Raymond Hettinger341deb72003-05-02 19:44:20 +000086 self.assertRaises(TypeError, islice, xrange(10))
Raymond Hettinger96ef8112003-02-01 00:10:11 +000087 self.assertRaises(TypeError, islice, xrange(10), 1, 2, 3, 4)
88 self.assertRaises(ValueError, islice, xrange(10), -5, 10, 1)
89 self.assertRaises(ValueError, islice, xrange(10), 1, -5, -1)
90 self.assertRaises(ValueError, islice, xrange(10), 1, 10, -1)
91 self.assertRaises(ValueError, islice, xrange(10), 1, 10, 0)
Raymond Hettinger14ef54c2003-05-02 19:04:37 +000092 self.assertRaises(ValueError, islice, xrange(10), 'a')
93 self.assertRaises(ValueError, islice, xrange(10), 'a', 1)
94 self.assertRaises(ValueError, islice, xrange(10), 1, 'a')
95 self.assertRaises(ValueError, islice, xrange(10), 'a', 1, 1)
96 self.assertRaises(ValueError, islice, xrange(10), 1, 'a', 1)
Raymond Hettinger2012f172003-02-07 05:32:58 +000097 self.assertEqual(len(list(islice(count(), 1, 10, sys.maxint))), 1)
Raymond Hettinger96ef8112003-02-01 00:10:11 +000098
99 def test_takewhile(self):
100 data = [1, 3, 5, 20, 2, 4, 6, 8]
101 underten = lambda x: x<10
102 self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
103
104 def test_dropwhile(self):
105 data = [1, 3, 5, 20, 2, 4, 6, 8]
106 underten = lambda x: x<10
107 self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
108
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000109 def test_StopIteration(self):
110 class StopNow:
111 """Test support class . Emulates an empty iterable."""
112 def __iter__(self):
113 return self
114 def next(self):
115 raise StopIteration
116
117 for f in (chain, cycle, izip):
118 self.assertRaises(StopIteration, f([]).next)
119 self.assertRaises(StopIteration, f(StopNow()).next)
120
121 self.assertRaises(StopIteration, islice([], None).next)
122 self.assertRaises(StopIteration, islice(StopNow(), None).next)
123
124 self.assertRaises(StopIteration, repeat(None, 0).next)
125
126 for f in (ifilter, ifilterfalse, imap, takewhile, dropwhile, starmap):
127 self.assertRaises(StopIteration, f(lambda x:x, []).next)
128 self.assertRaises(StopIteration, f(lambda x:x, StopNow()).next)
129
130
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000131libreftest = """ Doctest for examples in the library reference, libitertools.tex
132
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000133
134>>> amounts = [120.15, 764.05, 823.14]
135>>> for checknum, amount in izip(count(1200), amounts):
136... print 'Check %d is for $%.2f' % (checknum, amount)
137...
138Check 1200 is for $120.15
139Check 1201 is for $764.05
140Check 1202 is for $823.14
141
142>>> import operator
143>>> import operator
144>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
145... print cube
146...
1471
1488
14927
150
151>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
152>>> for name in islice(reportlines, 3, len(reportlines), 2):
153... print name.title()
154...
155Alex
156Laura
157Martin
158Walter
159Samuele
160
161>>> def enumerate(iterable):
162... return izip(count(), iterable)
163
164>>> def tabulate(function):
165... "Return function(0), function(1), ..."
166... return imap(function, count())
167
168>>> def iteritems(mapping):
169... return izip(mapping.iterkeys(), mapping.itervalues())
170
171>>> def nth(iterable, n):
172... "Returns the nth item"
Raymond Hettinger60eca932003-02-09 06:40:58 +0000173... return list(islice(iterable, n, n+1))
174
175>>> def all(pred, seq):
176... "Returns True if pred(x) is True for every element in the iterable"
177... return not nth(ifilterfalse(pred, seq), 0)
178
179>>> def some(pred, seq):
180... "Returns True if pred(x) is True at least one element in the iterable"
181... return bool(nth(ifilter(pred, seq), 0))
182
183>>> def no(pred, seq):
184... "Returns True if pred(x) is False for every element in the iterable"
185... return not nth(ifilter(pred, seq), 0)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000186
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000187>>> def pairwise(seq):
188... "s -> (s0,s1), (s1,s2), (s2, s3), ..."
189... return izip(seq, islice(seq,1,len(seq)))
190
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000191>>> def padnone(seq):
192... "Returns the sequence elements and then returns None indefinitely"
193... return chain(seq, repeat(None))
194
195>>> def ncycles(seq, n):
196... "Returns the sequence elements n times"
197... return chain(*repeat(seq, n))
198
199>>> def dotproduct(vec1, vec2):
200... return sum(imap(operator.mul, vec1, vec2))
201
202
203This is not part of the examples but it tests to make sure the definitions
204perform as purported.
205
206>>> list(enumerate('abc'))
207[(0, 'a'), (1, 'b'), (2, 'c')]
208
209>>> list(islice(tabulate(lambda x: 2*x), 4))
210[0, 2, 4, 6]
211
212>>> nth('abcde', 3)
213['d']
214
215>>> all(lambda x: x%2==0, [2, 4, 6, 8])
216True
217
218>>> all(lambda x: x%2==0, [2, 3, 6, 8])
219False
220
221>>> some(lambda x: x%2==0, [2, 4, 6, 8])
222True
223
224>>> some(lambda x: x%2==0, [1, 3, 5, 9])
225False
226
227>>> no(lambda x: x%2==0, [1, 3, 5, 9])
228True
229
230>>> no(lambda x: x%2==0, [1, 2, 5, 9])
231False
232
233>>> list(pairwise('abc'))
234[('a', 'b'), ('b', 'c')]
235
236>>> list(islice(padnone('abc'), 0, 6))
237['a', 'b', 'c', None, None, None]
238
239>>> list(ncycles('abc', 3))
240['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
241
242>>> dotproduct([1,2,3], [4,5,6])
24332
244
245
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000246"""
247
248__test__ = {'libreftest' : libreftest}
249
250def test_main(verbose=None):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000251 test_support.run_unittest(TestBasicOps)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000252
253 # verify reference counting
254 import sys
255 if verbose and hasattr(sys, "gettotalrefcount"):
Raymond Hettinger8fd3f872003-05-02 22:38:07 +0000256 counts = [None] * 5
257 for i in xrange(len(counts)):
258 test_support.run_unittest(TestBasicOps)
259 counts[i] = sys.gettotalrefcount()
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000260 print counts
261
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000262 # doctest the examples in the library reference
263 import doctest
264 doctest.testmod(sys.modules[__name__])
265
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000266if __name__ == "__main__":
267 test_main(verbose=True)