blob: fec027e3b659fbc2c97dbc9256c7c3256e969974 [file] [log] [blame]
Guido van Rossum0b191782002-08-02 18:29:53 +00001"""Unittests for heapq."""
2
Guido van Rossum0b191782002-08-02 18:29:53 +00003import random
Raymond Hettingerbce036b2004-06-10 05:07:18 +00004import unittest
5from test import test_support
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +00006import sys
Guido van Rossum0b191782002-08-02 18:29:53 +00007
Georg Brandl0bb85672008-02-23 22:35:33 +00008# We do a bit of trickery here to be able to test both the C implementation
9# and the Python implementation of the module.
Guido van Rossum0b191782002-08-02 18:29:53 +000010
Georg Brandl0bb85672008-02-23 22:35:33 +000011# Make it impossible to import the C implementation anymore.
12sys.modules['_heapq'] = 0
13# We must also handle the case that heapq was imported before.
14if 'heapq' in sys.modules:
15 del sys.modules['heapq']
16
17# Now we can import the module and get the pure Python implementation.
18import heapq as py_heapq
19
20# Restore everything to normal.
21del sys.modules['_heapq']
22del sys.modules['heapq']
23
24# This is now the module with the C implementation.
25import heapq as c_heapq
26
Tim Petersaa7d2432002-08-03 02:11:26 +000027
Raymond Hettingerbce036b2004-06-10 05:07:18 +000028class TestHeap(unittest.TestCase):
Georg Brandl0bb85672008-02-23 22:35:33 +000029 module = None
Tim Petersaa7d2432002-08-03 02:11:26 +000030
Raymond Hettingerbce036b2004-06-10 05:07:18 +000031 def test_push_pop(self):
32 # 1) Push 256 random numbers and pop them off, verifying all's OK.
33 heap = []
34 data = []
35 self.check_invariant(heap)
36 for i in range(256):
37 item = random.random()
38 data.append(item)
Georg Brandl0bb85672008-02-23 22:35:33 +000039 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000040 self.check_invariant(heap)
41 results = []
42 while heap:
Georg Brandl0bb85672008-02-23 22:35:33 +000043 item = self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000044 self.check_invariant(heap)
45 results.append(item)
46 data_sorted = data[:]
47 data_sorted.sort()
48 self.assertEqual(data_sorted, results)
49 # 2) Check that the invariant holds for a sorted array
50 self.check_invariant(results)
51
Georg Brandl0bb85672008-02-23 22:35:33 +000052 self.assertRaises(TypeError, self.module.heappush, [])
Raymond Hettingere1defa42004-11-29 05:54:48 +000053 try:
Georg Brandl0bb85672008-02-23 22:35:33 +000054 self.assertRaises(TypeError, self.module.heappush, None, None)
55 self.assertRaises(TypeError, self.module.heappop, None)
Raymond Hettingere1defa42004-11-29 05:54:48 +000056 except AttributeError:
57 pass
Neal Norwitzd7be1182004-07-08 01:56:46 +000058
Raymond Hettingerbce036b2004-06-10 05:07:18 +000059 def check_invariant(self, heap):
60 # Check the heap invariant.
61 for pos, item in enumerate(heap):
62 if pos: # pos 0 has no parent
63 parentpos = (pos-1) >> 1
64 self.assert_(heap[parentpos] <= item)
65
66 def test_heapify(self):
67 for size in range(30):
68 heap = [random.random() for dummy in range(size)]
Georg Brandl0bb85672008-02-23 22:35:33 +000069 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000070 self.check_invariant(heap)
71
Georg Brandl0bb85672008-02-23 22:35:33 +000072 self.assertRaises(TypeError, self.module.heapify, None)
Neal Norwitzd7be1182004-07-08 01:56:46 +000073
Raymond Hettingerbce036b2004-06-10 05:07:18 +000074 def test_naive_nbest(self):
75 data = [random.randrange(2000) for i in range(1000)]
76 heap = []
77 for item in data:
Georg Brandl0bb85672008-02-23 22:35:33 +000078 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000079 if len(heap) > 10:
Georg Brandl0bb85672008-02-23 22:35:33 +000080 self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000081 heap.sort()
82 self.assertEqual(heap, sorted(data)[-10:])
83
Georg Brandl0bb85672008-02-23 22:35:33 +000084 def heapiter(self, heap):
85 # An iterator returning a heap's elements, smallest-first.
86 try:
87 while 1:
88 yield self.module.heappop(heap)
89 except IndexError:
90 pass
91
Raymond Hettingerbce036b2004-06-10 05:07:18 +000092 def test_nbest(self):
93 # Less-naive "N-best" algorithm, much faster (if len(data) is big
94 # enough <wink>) than sorting all of data. However, if we had a max
95 # heap instead of a min heap, it could go faster still via
96 # heapify'ing all of data (linear time), then doing 10 heappops
97 # (10 log-time steps).
98 data = [random.randrange(2000) for i in range(1000)]
99 heap = data[:10]
Georg Brandl0bb85672008-02-23 22:35:33 +0000100 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000101 for item in data[10:]:
102 if item > heap[0]: # this gets rarer the longer we run
Georg Brandl0bb85672008-02-23 22:35:33 +0000103 self.module.heapreplace(heap, item)
104 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000105
Georg Brandl0bb85672008-02-23 22:35:33 +0000106 self.assertRaises(TypeError, self.module.heapreplace, None)
107 self.assertRaises(TypeError, self.module.heapreplace, None, None)
108 self.assertRaises(IndexError, self.module.heapreplace, [], None)
Neal Norwitzd7be1182004-07-08 01:56:46 +0000109
Raymond Hettinger53bdf092008-03-13 19:03:51 +0000110 def test_nbest_with_pushpop(self):
111 data = [random.randrange(2000) for i in range(1000)]
112 heap = data[:10]
113 self.module.heapify(heap)
114 for item in data[10:]:
115 self.module.heappushpop(heap, item)
116 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
117 self.assertEqual(self.module.heappushpop([], 'x'), 'x')
118
119 def test_heappushpop(self):
120 h = []
121 x = self.module.heappushpop(h, 10)
122 self.assertEqual((h, x), ([], 10))
123
124 h = [10]
125 x = self.module.heappushpop(h, 10.0)
126 self.assertEqual((h, x), ([10], 10.0))
127 self.assertEqual(type(h[0]), int)
128 self.assertEqual(type(x), float)
129
130 h = [10];
131 x = self.module.heappushpop(h, 9)
132 self.assertEqual((h, x), ([10], 9))
133
134 h = [10];
135 x = self.module.heappushpop(h, 11)
136 self.assertEqual((h, x), ([11], 10))
137
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000138 def test_heapsort(self):
139 # Exercise everything with repeated heapsort checks
140 for trial in xrange(100):
141 size = random.randrange(50)
142 data = [random.randrange(25) for i in range(size)]
143 if trial & 1: # Half of the time, use heapify
144 heap = data[:]
Georg Brandl0bb85672008-02-23 22:35:33 +0000145 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000146 else: # The rest of the time, use heappush
147 heap = []
148 for item in data:
Georg Brandl0bb85672008-02-23 22:35:33 +0000149 self.module.heappush(heap, item)
150 heap_sorted = [self.module.heappop(heap) for i in range(size)]
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000151 self.assertEqual(heap_sorted, sorted(data))
152
Raymond Hettinger00166c52007-02-19 04:08:43 +0000153 def test_merge(self):
154 inputs = []
155 for i in xrange(random.randrange(5)):
156 row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
157 inputs.append(row)
Georg Brandl0bb85672008-02-23 22:35:33 +0000158 self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs)))
159 self.assertEqual(list(self.module.merge()), [])
Raymond Hettinger00166c52007-02-19 04:08:43 +0000160
Raymond Hettinger01b98812007-02-19 07:30:21 +0000161 def test_merge_stability(self):
162 class Int(int):
163 pass
164 inputs = [[], [], [], []]
165 for i in range(20000):
166 stream = random.randrange(4)
167 x = random.randrange(500)
168 obj = Int(x)
169 obj.pair = (x, stream)
170 inputs[stream].append(obj)
171 for stream in inputs:
172 stream.sort()
Georg Brandl0bb85672008-02-23 22:35:33 +0000173 result = [i.pair for i in self.module.merge(*inputs)]
Raymond Hettinger01b98812007-02-19 07:30:21 +0000174 self.assertEqual(result, sorted(result))
175
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000176 def test_nsmallest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000177 data = [(random.randrange(2000), i) for i in range(1000)]
178 for f in (None, lambda x: x[0] * 547 % 2000):
179 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Georg Brandl0bb85672008-02-23 22:35:33 +0000180 self.assertEqual(self.module.nsmallest(n, data), sorted(data)[:n])
181 self.assertEqual(self.module.nsmallest(n, data, key=f),
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000182 sorted(data, key=f)[:n])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000183
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000184 def test_nlargest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000185 data = [(random.randrange(2000), i) for i in range(1000)]
186 for f in (None, lambda x: x[0] * 547 % 2000):
187 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Georg Brandl0bb85672008-02-23 22:35:33 +0000188 self.assertEqual(self.module.nlargest(n, data),
189 sorted(data, reverse=True)[:n])
190 self.assertEqual(self.module.nlargest(n, data, key=f),
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000191 sorted(data, key=f, reverse=True)[:n])
Tim Petersaa7d2432002-08-03 02:11:26 +0000192
Georg Brandl0bb85672008-02-23 22:35:33 +0000193class TestHeapPython(TestHeap):
194 module = py_heapq
195
196class TestHeapC(TestHeap):
197 module = c_heapq
198
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000199
200#==============================================================================
201
202class LenOnly:
203 "Dummy sequence class defining __len__ but not __getitem__."
204 def __len__(self):
205 return 10
206
207class GetOnly:
208 "Dummy sequence class defining __getitem__ but not __len__."
209 def __getitem__(self, ndx):
210 return 10
211
212class CmpErr:
213 "Dummy element that always raises an error during comparison"
214 def __cmp__(self, other):
215 raise ZeroDivisionError
216
217def R(seqn):
218 'Regular generator'
219 for i in seqn:
220 yield i
221
222class G:
223 'Sequence using __getitem__'
224 def __init__(self, seqn):
225 self.seqn = seqn
226 def __getitem__(self, i):
227 return self.seqn[i]
228
229class I:
230 'Sequence using iterator protocol'
231 def __init__(self, seqn):
232 self.seqn = seqn
233 self.i = 0
234 def __iter__(self):
235 return self
236 def next(self):
237 if self.i >= len(self.seqn): raise StopIteration
238 v = self.seqn[self.i]
239 self.i += 1
240 return v
241
242class Ig:
243 'Sequence using iterator protocol defined with a generator'
244 def __init__(self, seqn):
245 self.seqn = seqn
246 self.i = 0
247 def __iter__(self):
248 for val in self.seqn:
249 yield val
250
251class X:
252 'Missing __getitem__ and __iter__'
253 def __init__(self, seqn):
254 self.seqn = seqn
255 self.i = 0
256 def next(self):
257 if self.i >= len(self.seqn): raise StopIteration
258 v = self.seqn[self.i]
259 self.i += 1
260 return v
261
262class N:
263 'Iterator missing next()'
264 def __init__(self, seqn):
265 self.seqn = seqn
266 self.i = 0
267 def __iter__(self):
268 return self
269
270class E:
271 'Test propagation of exceptions'
272 def __init__(self, seqn):
273 self.seqn = seqn
274 self.i = 0
275 def __iter__(self):
276 return self
277 def next(self):
278 3 // 0
279
280class S:
281 'Test immediate stop'
282 def __init__(self, seqn):
283 pass
284 def __iter__(self):
285 return self
286 def next(self):
287 raise StopIteration
288
289from itertools import chain, imap
290def L(seqn):
291 'Test multiple tiers of iterators'
292 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
293
294class TestErrorHandling(unittest.TestCase):
Georg Brandl0bb85672008-02-23 22:35:33 +0000295 # only for C implementation
296 module = c_heapq
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000297
298 def test_non_sequence(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000299 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000300 self.assertRaises(TypeError, f, 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000301 for f in (self.module.heappush, self.module.heapreplace,
302 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000303 self.assertRaises(TypeError, f, 10, 10)
304
305 def test_len_only(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000306 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000307 self.assertRaises(TypeError, f, LenOnly())
Georg Brandl0bb85672008-02-23 22:35:33 +0000308 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000309 self.assertRaises(TypeError, f, LenOnly(), 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000310 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000311 self.assertRaises(TypeError, f, 2, LenOnly())
312
313 def test_get_only(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000314 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000315 self.assertRaises(TypeError, f, GetOnly())
Georg Brandl0bb85672008-02-23 22:35:33 +0000316 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000317 self.assertRaises(TypeError, f, GetOnly(), 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000318 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000319 self.assertRaises(TypeError, f, 2, GetOnly())
320
321 def test_get_only(self):
322 seq = [CmpErr(), CmpErr(), CmpErr()]
Georg Brandl0bb85672008-02-23 22:35:33 +0000323 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000324 self.assertRaises(ZeroDivisionError, f, seq)
Georg Brandl0bb85672008-02-23 22:35:33 +0000325 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000326 self.assertRaises(ZeroDivisionError, f, seq, 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000327 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000328 self.assertRaises(ZeroDivisionError, f, 2, seq)
329
330 def test_arg_parsing(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000331 for f in (self.module.heapify, self.module.heappop,
332 self.module.heappush, self.module.heapreplace,
333 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000334 self.assertRaises(TypeError, f, 10)
335
336 def test_iterable_args(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000337 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000338 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
339 for g in (G, I, Ig, L, R):
340 self.assertEqual(f(2, g(s)), f(2,s))
341 self.assertEqual(f(2, S(s)), [])
342 self.assertRaises(TypeError, f, 2, X(s))
343 self.assertRaises(TypeError, f, 2, N(s))
344 self.assertRaises(ZeroDivisionError, f, 2, E(s))
345
Georg Brandl0bb85672008-02-23 22:35:33 +0000346
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000347#==============================================================================
348
349
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000350def test_main(verbose=None):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000351 from types import BuiltinFunctionType
352
Georg Brandl0bb85672008-02-23 22:35:33 +0000353 test_classes = [TestHeapPython, TestHeapC, TestErrorHandling]
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000354 test_support.run_unittest(*test_classes)
355
356 # verify reference counting
357 if verbose and hasattr(sys, "gettotalrefcount"):
358 import gc
359 counts = [None] * 5
360 for i in xrange(len(counts)):
361 test_support.run_unittest(*test_classes)
362 gc.collect()
363 counts[i] = sys.gettotalrefcount()
364 print counts
Guido van Rossum0b191782002-08-02 18:29:53 +0000365
366if __name__ == "__main__":
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000367 test_main(verbose=True)