blob: b2bbfab0fa1586391091386b2240945a98b018f6 [file] [log] [blame]
Guido van Rossum0b191782002-08-02 18:29:53 +00001"""Unittests for heapq."""
2
Raymond Hettinger00166c52007-02-19 04:08:43 +00003from heapq import heappush, heappop, heapify, heapreplace, merge, nlargest, nsmallest
Guido van Rossum0b191782002-08-02 18:29:53 +00004import random
Raymond Hettingerbce036b2004-06-10 05:07:18 +00005import unittest
6from test import test_support
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +00007import sys
Guido van Rossum0b191782002-08-02 18:29:53 +00008
Guido van Rossum0b191782002-08-02 18:29:53 +00009
Raymond Hettingerbce036b2004-06-10 05:07:18 +000010def heapiter(heap):
11 # An iterator returning a heap's elements, smallest-first.
12 try:
13 while 1:
14 yield heappop(heap)
15 except IndexError:
16 pass
Tim Petersaa7d2432002-08-03 02:11:26 +000017
Raymond Hettingerbce036b2004-06-10 05:07:18 +000018class TestHeap(unittest.TestCase):
Tim Petersaa7d2432002-08-03 02:11:26 +000019
Raymond Hettingerbce036b2004-06-10 05:07:18 +000020 def test_push_pop(self):
21 # 1) Push 256 random numbers and pop them off, verifying all's OK.
22 heap = []
23 data = []
24 self.check_invariant(heap)
25 for i in range(256):
26 item = random.random()
27 data.append(item)
28 heappush(heap, item)
29 self.check_invariant(heap)
30 results = []
31 while heap:
32 item = heappop(heap)
33 self.check_invariant(heap)
34 results.append(item)
35 data_sorted = data[:]
36 data_sorted.sort()
37 self.assertEqual(data_sorted, results)
38 # 2) Check that the invariant holds for a sorted array
39 self.check_invariant(results)
40
Neal Norwitzd7be1182004-07-08 01:56:46 +000041 self.assertRaises(TypeError, heappush, [])
Raymond Hettingere1defa42004-11-29 05:54:48 +000042 try:
43 self.assertRaises(TypeError, heappush, None, None)
44 self.assertRaises(TypeError, heappop, None)
45 except AttributeError:
46 pass
Neal Norwitzd7be1182004-07-08 01:56:46 +000047
Raymond Hettingerbce036b2004-06-10 05:07:18 +000048 def check_invariant(self, heap):
49 # Check the heap invariant.
50 for pos, item in enumerate(heap):
51 if pos: # pos 0 has no parent
52 parentpos = (pos-1) >> 1
53 self.assert_(heap[parentpos] <= item)
54
55 def test_heapify(self):
56 for size in range(30):
57 heap = [random.random() for dummy in range(size)]
58 heapify(heap)
59 self.check_invariant(heap)
60
Neal Norwitzd7be1182004-07-08 01:56:46 +000061 self.assertRaises(TypeError, heapify, None)
62
Raymond Hettingerbce036b2004-06-10 05:07:18 +000063 def test_naive_nbest(self):
64 data = [random.randrange(2000) for i in range(1000)]
65 heap = []
66 for item in data:
67 heappush(heap, item)
68 if len(heap) > 10:
69 heappop(heap)
70 heap.sort()
71 self.assertEqual(heap, sorted(data)[-10:])
72
73 def test_nbest(self):
74 # Less-naive "N-best" algorithm, much faster (if len(data) is big
75 # enough <wink>) than sorting all of data. However, if we had a max
76 # heap instead of a min heap, it could go faster still via
77 # heapify'ing all of data (linear time), then doing 10 heappops
78 # (10 log-time steps).
79 data = [random.randrange(2000) for i in range(1000)]
80 heap = data[:10]
81 heapify(heap)
82 for item in data[10:]:
83 if item > heap[0]: # this gets rarer the longer we run
84 heapreplace(heap, item)
85 self.assertEqual(list(heapiter(heap)), sorted(data)[-10:])
86
Neal Norwitzd7be1182004-07-08 01:56:46 +000087 self.assertRaises(TypeError, heapreplace, None)
88 self.assertRaises(TypeError, heapreplace, None, None)
89 self.assertRaises(IndexError, heapreplace, [], None)
90
Raymond Hettingerbce036b2004-06-10 05:07:18 +000091 def test_heapsort(self):
92 # Exercise everything with repeated heapsort checks
93 for trial in xrange(100):
94 size = random.randrange(50)
95 data = [random.randrange(25) for i in range(size)]
96 if trial & 1: # Half of the time, use heapify
97 heap = data[:]
98 heapify(heap)
99 else: # The rest of the time, use heappush
100 heap = []
101 for item in data:
102 heappush(heap, item)
103 heap_sorted = [heappop(heap) for i in range(size)]
104 self.assertEqual(heap_sorted, sorted(data))
105
Raymond Hettinger00166c52007-02-19 04:08:43 +0000106 def test_merge(self):
107 inputs = []
108 for i in xrange(random.randrange(5)):
109 row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
110 inputs.append(row)
111 self.assertEqual(sorted(chain(*inputs)), list(merge(*inputs)))
112 self.assertEqual(list(merge()), [])
113
Raymond Hettinger01b98812007-02-19 07:30:21 +0000114 def test_merge_stability(self):
115 class Int(int):
116 pass
117 inputs = [[], [], [], []]
118 for i in range(20000):
119 stream = random.randrange(4)
120 x = random.randrange(500)
121 obj = Int(x)
122 obj.pair = (x, stream)
123 inputs[stream].append(obj)
124 for stream in inputs:
125 stream.sort()
126 result = [i.pair for i in merge(*inputs)]
127 self.assertEqual(result, sorted(result))
128
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000129 def test_nsmallest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000130 data = [(random.randrange(2000), i) for i in range(1000)]
131 for f in (None, lambda x: x[0] * 547 % 2000):
132 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
133 self.assertEqual(nsmallest(n, data), sorted(data)[:n])
134 self.assertEqual(nsmallest(n, data, key=f),
135 sorted(data, key=f)[:n])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000136
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000137 def test_nlargest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000138 data = [(random.randrange(2000), i) for i in range(1000)]
139 for f in (None, lambda x: x[0] * 547 % 2000):
140 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
141 self.assertEqual(nlargest(n, data), sorted(data, reverse=True)[:n])
142 self.assertEqual(nlargest(n, data, key=f),
143 sorted(data, key=f, reverse=True)[:n])
Tim Petersaa7d2432002-08-03 02:11:26 +0000144
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000145
146#==============================================================================
147
148class LenOnly:
149 "Dummy sequence class defining __len__ but not __getitem__."
150 def __len__(self):
151 return 10
152
153class GetOnly:
154 "Dummy sequence class defining __getitem__ but not __len__."
155 def __getitem__(self, ndx):
156 return 10
157
158class CmpErr:
159 "Dummy element that always raises an error during comparison"
160 def __cmp__(self, other):
161 raise ZeroDivisionError
162
163def R(seqn):
164 'Regular generator'
165 for i in seqn:
166 yield i
167
168class G:
169 'Sequence using __getitem__'
170 def __init__(self, seqn):
171 self.seqn = seqn
172 def __getitem__(self, i):
173 return self.seqn[i]
174
175class I:
176 'Sequence using iterator protocol'
177 def __init__(self, seqn):
178 self.seqn = seqn
179 self.i = 0
180 def __iter__(self):
181 return self
182 def next(self):
183 if self.i >= len(self.seqn): raise StopIteration
184 v = self.seqn[self.i]
185 self.i += 1
186 return v
187
188class Ig:
189 'Sequence using iterator protocol defined with a generator'
190 def __init__(self, seqn):
191 self.seqn = seqn
192 self.i = 0
193 def __iter__(self):
194 for val in self.seqn:
195 yield val
196
197class X:
198 'Missing __getitem__ and __iter__'
199 def __init__(self, seqn):
200 self.seqn = seqn
201 self.i = 0
202 def next(self):
203 if self.i >= len(self.seqn): raise StopIteration
204 v = self.seqn[self.i]
205 self.i += 1
206 return v
207
208class N:
209 'Iterator missing next()'
210 def __init__(self, seqn):
211 self.seqn = seqn
212 self.i = 0
213 def __iter__(self):
214 return self
215
216class E:
217 'Test propagation of exceptions'
218 def __init__(self, seqn):
219 self.seqn = seqn
220 self.i = 0
221 def __iter__(self):
222 return self
223 def next(self):
224 3 // 0
225
226class S:
227 'Test immediate stop'
228 def __init__(self, seqn):
229 pass
230 def __iter__(self):
231 return self
232 def next(self):
233 raise StopIteration
234
235from itertools import chain, imap
236def L(seqn):
237 'Test multiple tiers of iterators'
238 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
239
240class TestErrorHandling(unittest.TestCase):
241
242 def test_non_sequence(self):
243 for f in (heapify, heappop):
244 self.assertRaises(TypeError, f, 10)
245 for f in (heappush, heapreplace, nlargest, nsmallest):
246 self.assertRaises(TypeError, f, 10, 10)
247
248 def test_len_only(self):
249 for f in (heapify, heappop):
250 self.assertRaises(TypeError, f, LenOnly())
251 for f in (heappush, heapreplace):
252 self.assertRaises(TypeError, f, LenOnly(), 10)
253 for f in (nlargest, nsmallest):
254 self.assertRaises(TypeError, f, 2, LenOnly())
255
256 def test_get_only(self):
257 for f in (heapify, heappop):
258 self.assertRaises(TypeError, f, GetOnly())
259 for f in (heappush, heapreplace):
260 self.assertRaises(TypeError, f, GetOnly(), 10)
261 for f in (nlargest, nsmallest):
262 self.assertRaises(TypeError, f, 2, GetOnly())
263
264 def test_get_only(self):
265 seq = [CmpErr(), CmpErr(), CmpErr()]
266 for f in (heapify, heappop):
267 self.assertRaises(ZeroDivisionError, f, seq)
268 for f in (heappush, heapreplace):
269 self.assertRaises(ZeroDivisionError, f, seq, 10)
270 for f in (nlargest, nsmallest):
271 self.assertRaises(ZeroDivisionError, f, 2, seq)
272
273 def test_arg_parsing(self):
274 for f in (heapify, heappop, heappush, heapreplace, nlargest, nsmallest):
275 self.assertRaises(TypeError, f, 10)
276
277 def test_iterable_args(self):
278 for f in (nlargest, nsmallest):
279 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
280 for g in (G, I, Ig, L, R):
281 self.assertEqual(f(2, g(s)), f(2,s))
282 self.assertEqual(f(2, S(s)), [])
283 self.assertRaises(TypeError, f, 2, X(s))
284 self.assertRaises(TypeError, f, 2, N(s))
285 self.assertRaises(ZeroDivisionError, f, 2, E(s))
286
287#==============================================================================
288
289
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000290def test_main(verbose=None):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000291 from types import BuiltinFunctionType
292
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000293 test_classes = [TestHeap]
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000294 if isinstance(heapify, BuiltinFunctionType):
295 test_classes.append(TestErrorHandling)
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000296 test_support.run_unittest(*test_classes)
297
298 # verify reference counting
299 if verbose and hasattr(sys, "gettotalrefcount"):
300 import gc
301 counts = [None] * 5
302 for i in xrange(len(counts)):
303 test_support.run_unittest(*test_classes)
304 gc.collect()
305 counts[i] = sys.gettotalrefcount()
306 print counts
Guido van Rossum0b191782002-08-02 18:29:53 +0000307
308if __name__ == "__main__":
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000309 test_main(verbose=True)