blob: 7f6e4b59e707af1228601b3e339d9f1fb8a13004 [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 Hettingerbce036b2004-06-10 05:07:18 +0000110 def test_heapsort(self):
111 # Exercise everything with repeated heapsort checks
112 for trial in xrange(100):
113 size = random.randrange(50)
114 data = [random.randrange(25) for i in range(size)]
115 if trial & 1: # Half of the time, use heapify
116 heap = data[:]
Georg Brandl0bb85672008-02-23 22:35:33 +0000117 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000118 else: # The rest of the time, use heappush
119 heap = []
120 for item in data:
Georg Brandl0bb85672008-02-23 22:35:33 +0000121 self.module.heappush(heap, item)
122 heap_sorted = [self.module.heappop(heap) for i in range(size)]
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000123 self.assertEqual(heap_sorted, sorted(data))
124
Raymond Hettinger00166c52007-02-19 04:08:43 +0000125 def test_merge(self):
126 inputs = []
127 for i in xrange(random.randrange(5)):
128 row = sorted(random.randrange(1000) for j in range(random.randrange(10)))
129 inputs.append(row)
Georg Brandl0bb85672008-02-23 22:35:33 +0000130 self.assertEqual(sorted(chain(*inputs)), list(self.module.merge(*inputs)))
131 self.assertEqual(list(self.module.merge()), [])
Raymond Hettinger00166c52007-02-19 04:08:43 +0000132
Raymond Hettinger01b98812007-02-19 07:30:21 +0000133 def test_merge_stability(self):
134 class Int(int):
135 pass
136 inputs = [[], [], [], []]
137 for i in range(20000):
138 stream = random.randrange(4)
139 x = random.randrange(500)
140 obj = Int(x)
141 obj.pair = (x, stream)
142 inputs[stream].append(obj)
143 for stream in inputs:
144 stream.sort()
Georg Brandl0bb85672008-02-23 22:35:33 +0000145 result = [i.pair for i in self.module.merge(*inputs)]
Raymond Hettinger01b98812007-02-19 07:30:21 +0000146 self.assertEqual(result, sorted(result))
147
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000148 def test_nsmallest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000149 data = [(random.randrange(2000), i) for i in range(1000)]
150 for f in (None, lambda x: x[0] * 547 % 2000):
151 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Georg Brandl0bb85672008-02-23 22:35:33 +0000152 self.assertEqual(self.module.nsmallest(n, data), sorted(data)[:n])
153 self.assertEqual(self.module.nsmallest(n, data, key=f),
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000154 sorted(data, key=f)[:n])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000155
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000156 def test_nlargest(self):
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000157 data = [(random.randrange(2000), i) for i in range(1000)]
158 for f in (None, lambda x: x[0] * 547 % 2000):
159 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Georg Brandl0bb85672008-02-23 22:35:33 +0000160 self.assertEqual(self.module.nlargest(n, data),
161 sorted(data, reverse=True)[:n])
162 self.assertEqual(self.module.nlargest(n, data, key=f),
Raymond Hettinger769a40a2007-01-04 17:53:34 +0000163 sorted(data, key=f, reverse=True)[:n])
Tim Petersaa7d2432002-08-03 02:11:26 +0000164
Georg Brandl0bb85672008-02-23 22:35:33 +0000165class TestHeapPython(TestHeap):
166 module = py_heapq
167
168class TestHeapC(TestHeap):
169 module = c_heapq
170
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000171
172#==============================================================================
173
174class LenOnly:
175 "Dummy sequence class defining __len__ but not __getitem__."
176 def __len__(self):
177 return 10
178
179class GetOnly:
180 "Dummy sequence class defining __getitem__ but not __len__."
181 def __getitem__(self, ndx):
182 return 10
183
184class CmpErr:
185 "Dummy element that always raises an error during comparison"
186 def __cmp__(self, other):
187 raise ZeroDivisionError
188
189def R(seqn):
190 'Regular generator'
191 for i in seqn:
192 yield i
193
194class G:
195 'Sequence using __getitem__'
196 def __init__(self, seqn):
197 self.seqn = seqn
198 def __getitem__(self, i):
199 return self.seqn[i]
200
201class I:
202 'Sequence using iterator protocol'
203 def __init__(self, seqn):
204 self.seqn = seqn
205 self.i = 0
206 def __iter__(self):
207 return self
208 def next(self):
209 if self.i >= len(self.seqn): raise StopIteration
210 v = self.seqn[self.i]
211 self.i += 1
212 return v
213
214class Ig:
215 'Sequence using iterator protocol defined with a generator'
216 def __init__(self, seqn):
217 self.seqn = seqn
218 self.i = 0
219 def __iter__(self):
220 for val in self.seqn:
221 yield val
222
223class X:
224 'Missing __getitem__ and __iter__'
225 def __init__(self, seqn):
226 self.seqn = seqn
227 self.i = 0
228 def next(self):
229 if self.i >= len(self.seqn): raise StopIteration
230 v = self.seqn[self.i]
231 self.i += 1
232 return v
233
234class N:
235 'Iterator missing next()'
236 def __init__(self, seqn):
237 self.seqn = seqn
238 self.i = 0
239 def __iter__(self):
240 return self
241
242class E:
243 'Test propagation of exceptions'
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 3 // 0
251
252class S:
253 'Test immediate stop'
254 def __init__(self, seqn):
255 pass
256 def __iter__(self):
257 return self
258 def next(self):
259 raise StopIteration
260
261from itertools import chain, imap
262def L(seqn):
263 'Test multiple tiers of iterators'
264 return chain(imap(lambda x:x, R(Ig(G(seqn)))))
265
266class TestErrorHandling(unittest.TestCase):
Georg Brandl0bb85672008-02-23 22:35:33 +0000267 # only for C implementation
268 module = c_heapq
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000269
270 def test_non_sequence(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000271 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000272 self.assertRaises(TypeError, f, 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000273 for f in (self.module.heappush, self.module.heapreplace,
274 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000275 self.assertRaises(TypeError, f, 10, 10)
276
277 def test_len_only(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000278 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000279 self.assertRaises(TypeError, f, LenOnly())
Georg Brandl0bb85672008-02-23 22:35:33 +0000280 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000281 self.assertRaises(TypeError, f, LenOnly(), 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000282 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000283 self.assertRaises(TypeError, f, 2, LenOnly())
284
285 def test_get_only(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000286 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000287 self.assertRaises(TypeError, f, GetOnly())
Georg Brandl0bb85672008-02-23 22:35:33 +0000288 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000289 self.assertRaises(TypeError, f, GetOnly(), 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000290 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000291 self.assertRaises(TypeError, f, 2, GetOnly())
292
293 def test_get_only(self):
294 seq = [CmpErr(), CmpErr(), CmpErr()]
Georg Brandl0bb85672008-02-23 22:35:33 +0000295 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000296 self.assertRaises(ZeroDivisionError, f, seq)
Georg Brandl0bb85672008-02-23 22:35:33 +0000297 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000298 self.assertRaises(ZeroDivisionError, f, seq, 10)
Georg Brandl0bb85672008-02-23 22:35:33 +0000299 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000300 self.assertRaises(ZeroDivisionError, f, 2, seq)
301
302 def test_arg_parsing(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000303 for f in (self.module.heapify, self.module.heappop,
304 self.module.heappush, self.module.heapreplace,
305 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000306 self.assertRaises(TypeError, f, 10)
307
308 def test_iterable_args(self):
Georg Brandl0bb85672008-02-23 22:35:33 +0000309 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000310 for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
311 for g in (G, I, Ig, L, R):
312 self.assertEqual(f(2, g(s)), f(2,s))
313 self.assertEqual(f(2, S(s)), [])
314 self.assertRaises(TypeError, f, 2, X(s))
315 self.assertRaises(TypeError, f, 2, N(s))
316 self.assertRaises(ZeroDivisionError, f, 2, E(s))
317
Georg Brandl0bb85672008-02-23 22:35:33 +0000318
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000319#==============================================================================
320
321
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000322def test_main(verbose=None):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000323 from types import BuiltinFunctionType
324
Georg Brandl0bb85672008-02-23 22:35:33 +0000325 test_classes = [TestHeapPython, TestHeapC, TestErrorHandling]
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000326 test_support.run_unittest(*test_classes)
327
328 # verify reference counting
329 if verbose and hasattr(sys, "gettotalrefcount"):
330 import gc
331 counts = [None] * 5
332 for i in xrange(len(counts)):
333 test_support.run_unittest(*test_classes)
334 gc.collect()
335 counts[i] = sys.gettotalrefcount()
336 print counts
Guido van Rossum0b191782002-08-02 18:29:53 +0000337
338if __name__ == "__main__":
Raymond Hettinger2e3dfaf2004-06-13 05:26:33 +0000339 test_main(verbose=True)