blob: fb533dfba2887889de5780a289195d3bc8e8acae [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.
Georg Brandl0bb85672008-02-23 22:35:33 +000010import heapq as c_heapq
Nick Coghlan5533ff62009-04-22 15:26:04 +000011py_heapq = test_support.import_fresh_module('heapq', blocked=['_heapq'])
Tim Petersaa7d2432002-08-03 02:11:26 +000012
Raymond Hettingerbce036b2004-06-10 05:07:18 +000013class TestHeap(unittest.TestCase):
Georg Brandl0bb85672008-02-23 22:35:33 +000014 module = None
Tim Petersaa7d2432002-08-03 02:11:26 +000015
Raymond Hettingerbce036b2004-06-10 05:07:18 +000016 def test_push_pop(self):
17 # 1) Push 256 random numbers and pop them off, verifying all's OK.
18 heap = []
19 data = []
20 self.check_invariant(heap)
21 for i in range(256):
22 item = random.random()
23 data.append(item)
Georg Brandl0bb85672008-02-23 22:35:33 +000024 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000025 self.check_invariant(heap)
26 results = []
27 while heap:
Georg Brandl0bb85672008-02-23 22:35:33 +000028 item = self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000029 self.check_invariant(heap)
30 results.append(item)
31 data_sorted = data[:]
32 data_sorted.sort()
33 self.assertEqual(data_sorted, results)
34 # 2) Check that the invariant holds for a sorted array
35 self.check_invariant(results)
36
Georg Brandl0bb85672008-02-23 22:35:33 +000037 self.assertRaises(TypeError, self.module.heappush, [])
Raymond Hettingere1defa42004-11-29 05:54:48 +000038 try:
Georg Brandl0bb85672008-02-23 22:35:33 +000039 self.assertRaises(TypeError, self.module.heappush, None, None)
40 self.assertRaises(TypeError, self.module.heappop, None)
Raymond Hettingere1defa42004-11-29 05:54:48 +000041 except AttributeError:
42 pass
Neal Norwitzd7be1182004-07-08 01:56:46 +000043
Raymond Hettingerbce036b2004-06-10 05:07:18 +000044 def check_invariant(self, heap):
45 # Check the heap invariant.
46 for pos, item in enumerate(heap):
47 if pos: # pos 0 has no parent
48 parentpos = (pos-1) >> 1
Benjamin Peterson5c8da862009-06-30 22:57:08 +000049 self.assertTrue(heap[parentpos] <= item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000050
51 def test_heapify(self):
52 for size in range(30):
53 heap = [random.random() for dummy in range(size)]
Georg Brandl0bb85672008-02-23 22:35:33 +000054 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000055 self.check_invariant(heap)
56
Georg Brandl0bb85672008-02-23 22:35:33 +000057 self.assertRaises(TypeError, self.module.heapify, None)
Neal Norwitzd7be1182004-07-08 01:56:46 +000058
Raymond Hettingerbce036b2004-06-10 05:07:18 +000059 def test_naive_nbest(self):
60 data = [random.randrange(2000) for i in range(1000)]
61 heap = []
62 for item in data:
Georg Brandl0bb85672008-02-23 22:35:33 +000063 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000064 if len(heap) > 10:
Georg Brandl0bb85672008-02-23 22:35:33 +000065 self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000066 heap.sort()
67 self.assertEqual(heap, sorted(data)[-10:])
68
Georg Brandl0bb85672008-02-23 22:35:33 +000069 def heapiter(self, heap):
70 # An iterator returning a heap's elements, smallest-first.
71 try:
72 while 1:
73 yield self.module.heappop(heap)
74 except IndexError:
75 pass
76
Raymond Hettingerbce036b2004-06-10 05:07:18 +000077 def test_nbest(self):
78 # Less-naive "N-best" algorithm, much faster (if len(data) is big
79 # enough <wink>) than sorting all of data. However, if we had a max
80 # heap instead of a min heap, it could go faster still via
81 # heapify'ing all of data (linear time), then doing 10 heappops
82 # (10 log-time steps).
83 data = [random.randrange(2000) for i in range(1000)]
84 heap = data[:10]
Georg Brandl0bb85672008-02-23 22:35:33 +000085 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000086 for item in data[10:]:
87 if item > heap[0]: # this gets rarer the longer we run
Georg Brandl0bb85672008-02-23 22:35:33 +000088 self.module.heapreplace(heap, item)
89 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
Raymond Hettingerbce036b2004-06-10 05:07:18 +000090
Georg Brandl0bb85672008-02-23 22:35:33 +000091 self.assertRaises(TypeError, self.module.heapreplace, None)
92 self.assertRaises(TypeError, self.module.heapreplace, None, None)
93 self.assertRaises(IndexError, self.module.heapreplace, [], None)
Neal Norwitzd7be1182004-07-08 01:56:46 +000094
Raymond Hettinger53bdf092008-03-13 19:03:51 +000095 def test_nbest_with_pushpop(self):
96 data = [random.randrange(2000) for i in range(1000)]
97 heap = data[:10]
98 self.module.heapify(heap)
99 for item in data[10:]:
100 self.module.heappushpop(heap, item)
101 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
102 self.assertEqual(self.module.heappushpop([], 'x'), 'x')
103
104 def test_heappushpop(self):
105 h = []
106 x = self.module.heappushpop(h, 10)
107 self.assertEqual((h, x), ([], 10))
108
109 h = [10]
110 x = self.module.heappushpop(h, 10.0)
111 self.assertEqual((h, x), ([10], 10.0))
112 self.assertEqual(type(h[0]), int)
113 self.assertEqual(type(x), float)
114
115 h = [10];
116 x = self.module.heappushpop(h, 9)
117 self.assertEqual((h, x), ([10], 9))
118
119 h = [10];
120 x = self.module.heappushpop(h, 11)
121 self.assertEqual((h, x), ([11], 10))
122
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000123 def test_heapsort(self):
124 # Exercise everything with repeated heapsort checks
125 for trial in xrange(100):
126 size = random.randrange(50)
127 data = [random.randrange(25) for i in range(size)]
128 if trial & 1: # Half of the time, use heapify
129 heap = data[:]
Georg Brandl0bb85672008-02-23 22:35:33 +0000130 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000131 else: # The rest of the time, use heappush
132 heap = []
133 for item in data:
Georg Brandl0bb85672008-02-23 22:35:33 +0000134 self.module.heappush(heap, item)
135 heap_sorted = [self.module.heappop(heap) for i in range(size)]
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000136 self.assertEqual(heap_sorted, sorted(data))
137
Raymond Hettinger00166c52007-02-19 04:08:43 +0000138 def test_merge(self):
139 inputs = []
140 for i in xrange(random.randrange(5)):
141 row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
142 inputs.append(row)
Georg Brandl0bb85672008-02-23 22:35:33 +0000143 self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs)))
144 self.assertEqual(list(self.module.merge()), [])
Raymond Hettinger00166c52007-02-19 04:08:43 +0000145
Raymond Hettinger01b98812007-02-19 07:30:21 +0000146 def test_merge_stability(self):
147 class Int(int):
148 pass
149 inputs = [[], [], [], []]
150 for i in range(20000):
151 stream = random.randrange(4)
152 x = random.randrange(500)
153 obj = Int(x)
154 obj.pair = (x, stream)
155 inputs[stream].append(obj)
156 for stream in inputs:
157 stream.sort()
Georg Brandl0bb85672008-02-23 22:35:33 +0000158 result = [i.pair for i in self.module.merge(*inputs)]
Raymond Hettinger01b98812007-02-19 07:30:21 +0000159 self.assertEqual(result, sorted(result))
160
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000161 def test_nsmallest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000162 data = [(random.randrange(2000), i) for i in range(1000)]
163 for f in (None, lambda x: x[0] * 547 % 2000):
164 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Georg Brandl0bb85672008-02-23 22:35:33 +0000165 self.assertEqual(self.module.nsmallest(n, data), sorted(data)[:n])
166 self.assertEqual(self.module.nsmallest(n, data, key=f),
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000167 sorted(data, key=f)[:n])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000168
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000169 def test_nlargest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000170 data = [(random.randrange(2000), i) for i in range(1000)]
171 for f in (None, lambda x: x[0] * 547 % 2000):
172 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Georg Brandl0bb85672008-02-23 22:35:33 +0000173 self.assertEqual(self.module.nlargest(n, data),
174 sorted(data, reverse=True)[:n])
175 self.assertEqual(self.module.nlargest(n, data, key=f),
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000176 sorted(data, key=f, reverse=True)[:n])
Tim Petersaa7d2432002-08-03 02:11:26 +0000177
Georg Brandl0bb85672008-02-23 22:35:33 +0000178class TestHeapPython(TestHeap):
179 module = py_heapq
180
Nick Coghlancd2e7042009-04-11 13:31:31 +0000181 # As an early adopter, we sanity check the
182 # test_support.import_fresh_module utility function
183 def test_pure_python(self):
184 self.assertFalse(sys.modules['heapq'] is self.module)
185 self.assertTrue(hasattr(self.module.heapify, 'func_code'))
186
187
Georg Brandl0bb85672008-02-23 22:35:33 +0000188class TestHeapC(TestHeap):
189 module = c_heapq
190
Raymond Hettingere29a1032008-06-11 13:14:50 +0000191 def test_comparison_operator(self):
192 # Issue 3501: Make sure heapq works with both __lt__ and __le__
193 def hsort(data, comp):
194 data = map(comp, data)
195 self.module.heapify(data)
196 return [self.module.heappop(data).x for i in range(len(data))]
197 class LT:
198 def __init__(self, x):
199 self.x = x
200 def __lt__(self, other):
201 return self.x > other.x
202 class LE:
203 def __init__(self, x):
204 self.x = x
Neal Norwitz04097a62008-06-13 06:03:25 +0000205 def __le__(self, other):
Raymond Hettingere29a1032008-06-11 13:14:50 +0000206 return self.x >= other.x
207 data = [random.random() for i in range(100)]
208 target = sorted(data, reverse=True)
209 self.assertEqual(hsort(data, LT), target)
210 self.assertEqual(hsort(data, LE), target)
211
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000212
213#==============================================================================
214
215class LenOnly:
216 "Dummy sequence class defining __len__ but not __getitem__."
217 def __len__(self):
218 return 10
219
220class GetOnly:
221 "Dummy sequence class defining __getitem__ but not __len__."
222 def __getitem__(self, ndx):
223 return 10
224
225class CmpErr:
226 "Dummy element that always raises an error during comparison"
227 def __cmp__(self, other):
228 raise ZeroDivisionError
229
230def R(seqn):
231 'Regular generator'
232 for i in seqn:
233 yield i
234
235class G:
236 'Sequence using __getitem__'
237 def __init__(self, seqn):
238 self.seqn = seqn
239 def __getitem__(self, i):
240 return self.seqn[i]
241
242class I:
243 'Sequence using iterator protocol'
244 def __init__(self, seqn):
245 self.seqn = seqn
246 self.i = 0
247 def __iter__(self):
248 return self
249 def next(self):
250 if self.i >= len(self.seqn): raise StopIteration
251 v = self.seqn[self.i]
252 self.i += 1
253 return v
254
255class Ig:
256 'Sequence using iterator protocol defined with a generator'
257 def __init__(self, seqn):
258 self.seqn = seqn
259 self.i = 0
260 def __iter__(self):
261 for val in self.seqn:
262 yield val
263
264class X:
265 'Missing __getitem__ and __iter__'
266 def __init__(self, seqn):
267 self.seqn = seqn
268 self.i = 0
269 def next(self):
270 if self.i >= len(self.seqn): raise StopIteration
271 v = self.seqn[self.i]
272 self.i += 1
273 return v
274
275class N:
276 'Iterator missing next()'
277 def __init__(self, seqn):
278 self.seqn = seqn
279 self.i = 0
280 def __iter__(self):
281 return self
282
283class E:
284 'Test propagation of exceptions'
285 def __init__(self, seqn):
286 self.seqn = seqn
287 self.i = 0
288 def __iter__(self):
289 return self
290 def next(self):
291 3 // 0
292
293class S:
294 'Test immediate stop'
295 def __init__(self, seqn):
296 pass
297 def __iter__(self):
298 return self
299 def next(self):
300 raise StopIteration
301
302from itertools import chain, imap
303def L(seqn):
304 'Test multiple tiers of iterators'
305 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
306
307class TestErrorHandling(unittest.TestCase):
308
309 def test_non_sequence(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000310 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger9b342c62011-04-13 11:15:58 -0700311 self.assertRaises((TypeError, AttributeError), f, 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000312 for f in (self.module.heappush, self.module.heapreplace,
313 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger9b342c62011-04-13 11:15:58 -0700314 self.assertRaises((TypeError, AttributeError), f, 10, 10)
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000315
316 def test_len_only(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000317 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger9b342c62011-04-13 11:15:58 -0700318 self.assertRaises((TypeError, AttributeError), f, LenOnly())
Georg Brandl0bb85672008-02-23 22:35:33 +0000319 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger9b342c62011-04-13 11:15:58 -0700320 self.assertRaises((TypeError, AttributeError), f, LenOnly(), 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000321 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000322 self.assertRaises(TypeError, f, 2, LenOnly())
323
324 def test_get_only(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000325 seq = [CmpErr(), CmpErr(), CmpErr()]
Georg Brandl0bb85672008-02-23 22:35:33 +0000326 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000327 self.assertRaises(ZeroDivisionError, f, seq)
Georg Brandl0bb85672008-02-23 22:35:33 +0000328 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000329 self.assertRaises(ZeroDivisionError, f, seq, 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000330 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000331 self.assertRaises(ZeroDivisionError, f, 2, seq)
332
333 def test_arg_parsing(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000334 for f in (self.module.heapify, self.module.heappop,
335 self.module.heappush, self.module.heapreplace,
336 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger9b342c62011-04-13 11:15:58 -0700337 self.assertRaises((TypeError, AttributeError), f, 10)
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000338
339 def test_iterable_args(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000340 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000341 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
342 for g in (G, I, Ig, L, R):
Florent Xicluna07627882010-03-21 01:14:24 +0000343 with test_support.check_py3k_warnings(
344 ("comparing unequal types not supported",
345 DeprecationWarning), quiet=True):
346 self.assertEqual(f(2, g(s)), f(2,s))
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000347 self.assertEqual(f(2, S(s)), [])
348 self.assertRaises(TypeError, f, 2, X(s))
349 self.assertRaises(TypeError, f, 2, N(s))
350 self.assertRaises(ZeroDivisionError, f, 2, E(s))
351
Raymond Hettinger1bd816e2011-05-07 15:19:34 -0700352class TestErrorHandling_Python(TestErrorHandling):
Raymond Hettinger8dd06242011-05-07 14:16:42 -0700353 module = py_heapq
354
355class TestErrorHandling_C(TestErrorHandling):
356 module = c_heapq
357
Georg Brandl0bb85672008-02-23 22:35:33 +0000358
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000359#==============================================================================
360
361
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000362def test_main(verbose=None):
Raymond Hettinger8dd06242011-05-07 14:16:42 -0700363 test_classes = [TestHeapPython, TestHeapC, TestErrorHandling_Python,
364 TestErrorHandling_C]
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000365 test_support.run_unittest(*test_classes)
366
367 # verify reference counting
368 if verbose and hasattr(sys, "gettotalrefcount"):
369 import gc
370 counts = [None] * 5
371 for i in xrange(len(counts)):
372 test_support.run_unittest(*test_classes)
373 gc.collect()
374 counts[i] = sys.gettotalrefcount()
375 print counts
Guido van Rossum0b191782002-08-02 18:29:53 +0000376
377if __name__ == "__main__":
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000378 test_main(verbose=True)