blob: 861ba7540df2bcbe860b41ff85c3f9918cf8389c [file] [log] [blame]
Guido van Rossum0b191782002-08-02 18:29:53 +00001"""Unittests for heapq."""
2
Ezio Melotti8269a442011-05-09 07:15:04 +03003import random
Ezio Melotti22ebb2d2013-01-02 21:19:37 +02004import unittest
Rob Day664fe392019-06-01 05:13:57 +01005import doctest
Guido van Rossum0b191782002-08-02 18:29:53 +00006
Ezio Melotti8269a442011-05-09 07:15:04 +03007from test import support
8from unittest import TestCase, skipUnless
Raymond Hettinger35db4392014-05-30 02:28:36 -07009from operator import itemgetter
Ezio Melotti8269a442011-05-09 07:15:04 +030010
Nick Coghlan47384702009-04-22 16:13:36 +000011py_heapq = support.import_fresh_module('heapq', blocked=['_heapq'])
Ezio Melotti8269a442011-05-09 07:15:04 +030012c_heapq = support.import_fresh_module('heapq', fresh=['_heapq'])
Tim Petersaa7d2432002-08-03 02:11:26 +000013
Ezio Melotti8269a442011-05-09 07:15:04 +030014# _heapq.nlargest/nsmallest are saved in heapq._nlargest/_smallest when
15# _heapq is imported, so check them there
Raymond Hettinger48f68d02014-06-14 16:43:35 -070016func_names = ['heapify', 'heappop', 'heappush', 'heappushpop', 'heapreplace',
17 '_heappop_max', '_heapreplace_max', '_heapify_max']
Ezio Melotti8269a442011-05-09 07:15:04 +030018
19class TestModules(TestCase):
20 def test_py_functions(self):
21 for fname in func_names:
22 self.assertEqual(getattr(py_heapq, fname).__module__, 'heapq')
23
24 @skipUnless(c_heapq, 'requires _heapq')
25 def test_c_functions(self):
26 for fname in func_names:
27 self.assertEqual(getattr(c_heapq, fname).__module__, '_heapq')
28
29
Rob Day664fe392019-06-01 05:13:57 +010030def load_tests(loader, tests, ignore):
31 # The 'merge' function has examples in its docstring which we should test
32 # with 'doctest'.
33 #
34 # However, doctest can't easily find all docstrings in the module (loading
35 # it through import_fresh_module seems to confuse it), so we specifically
36 # create a finder which returns the doctests from the merge method.
37
38 class HeapqMergeDocTestFinder:
39 def find(self, *args, **kwargs):
40 dtf = doctest.DocTestFinder()
41 return dtf.find(py_heapq.merge)
42
43 tests.addTests(doctest.DocTestSuite(py_heapq,
44 test_finder=HeapqMergeDocTestFinder()))
45 return tests
46
Ezio Melotti22ebb2d2013-01-02 21:19:37 +020047class TestHeap:
Tim Petersaa7d2432002-08-03 02:11:26 +000048
Raymond Hettingerbce036b2004-06-10 05:07:18 +000049 def test_push_pop(self):
50 # 1) Push 256 random numbers and pop them off, verifying all's OK.
51 heap = []
52 data = []
53 self.check_invariant(heap)
54 for i in range(256):
55 item = random.random()
56 data.append(item)
Christian Heimesd3eb5a152008-02-24 00:38:49 +000057 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000058 self.check_invariant(heap)
59 results = []
60 while heap:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000061 item = self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000062 self.check_invariant(heap)
63 results.append(item)
64 data_sorted = data[:]
65 data_sorted.sort()
66 self.assertEqual(data_sorted, results)
67 # 2) Check that the invariant holds for a sorted array
68 self.check_invariant(results)
69
Christian Heimesd3eb5a152008-02-24 00:38:49 +000070 self.assertRaises(TypeError, self.module.heappush, [])
Raymond Hettingere1defa42004-11-29 05:54:48 +000071 try:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000072 self.assertRaises(TypeError, self.module.heappush, None, None)
73 self.assertRaises(TypeError, self.module.heappop, None)
Raymond Hettingere1defa42004-11-29 05:54:48 +000074 except AttributeError:
75 pass
Neal Norwitzd7be1182004-07-08 01:56:46 +000076
Raymond Hettingerbce036b2004-06-10 05:07:18 +000077 def check_invariant(self, heap):
78 # Check the heap invariant.
79 for pos, item in enumerate(heap):
80 if pos: # pos 0 has no parent
81 parentpos = (pos-1) >> 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000082 self.assertTrue(heap[parentpos] <= item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000083
84 def test_heapify(self):
Raymond Hettinger849564f2015-05-12 21:42:40 -070085 for size in list(range(30)) + [20000]:
Raymond Hettingerbce036b2004-06-10 05:07:18 +000086 heap = [random.random() for dummy in range(size)]
Christian Heimesd3eb5a152008-02-24 00:38:49 +000087 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000088 self.check_invariant(heap)
89
Christian Heimesd3eb5a152008-02-24 00:38:49 +000090 self.assertRaises(TypeError, self.module.heapify, None)
Neal Norwitzd7be1182004-07-08 01:56:46 +000091
Raymond Hettingerbce036b2004-06-10 05:07:18 +000092 def test_naive_nbest(self):
93 data = [random.randrange(2000) for i in range(1000)]
94 heap = []
95 for item in data:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000096 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000097 if len(heap) > 10:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000098 self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000099 heap.sort()
100 self.assertEqual(heap, sorted(data)[-10:])
101
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000102 def heapiter(self, heap):
103 # An iterator returning a heap's elements, smallest-first.
104 try:
105 while 1:
106 yield self.module.heappop(heap)
107 except IndexError:
108 pass
109
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000110 def test_nbest(self):
111 # Less-naive "N-best" algorithm, much faster (if len(data) is big
112 # enough <wink>) than sorting all of data. However, if we had a max
113 # heap instead of a min heap, it could go faster still via
114 # heapify'ing all of data (linear time), then doing 10 heappops
115 # (10 log-time steps).
116 data = [random.randrange(2000) for i in range(1000)]
117 heap = data[:10]
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000118 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000119 for item in data[10:]:
120 if item > heap[0]: # this gets rarer the longer we run
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000121 self.module.heapreplace(heap, item)
122 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000123
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000124 self.assertRaises(TypeError, self.module.heapreplace, None)
125 self.assertRaises(TypeError, self.module.heapreplace, None, None)
126 self.assertRaises(IndexError, self.module.heapreplace, [], None)
Neal Norwitzd7be1182004-07-08 01:56:46 +0000127
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000128 def test_nbest_with_pushpop(self):
129 data = [random.randrange(2000) for i in range(1000)]
130 heap = data[:10]
131 self.module.heapify(heap)
132 for item in data[10:]:
133 self.module.heappushpop(heap, item)
134 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
135 self.assertEqual(self.module.heappushpop([], 'x'), 'x')
136
137 def test_heappushpop(self):
138 h = []
139 x = self.module.heappushpop(h, 10)
140 self.assertEqual((h, x), ([], 10))
141
142 h = [10]
143 x = self.module.heappushpop(h, 10.0)
144 self.assertEqual((h, x), ([10], 10.0))
145 self.assertEqual(type(h[0]), int)
146 self.assertEqual(type(x), float)
147
148 h = [10];
149 x = self.module.heappushpop(h, 9)
150 self.assertEqual((h, x), ([10], 9))
151
152 h = [10];
153 x = self.module.heappushpop(h, 11)
154 self.assertEqual((h, x), ([11], 10))
155
Rob Day664fe392019-06-01 05:13:57 +0100156 def test_heappop_max(self):
157 # _heapop_max has an optimization for one-item lists which isn't
158 # covered in other tests, so test that case explicitly here
159 h = [3, 2]
160 self.assertEqual(self.module._heappop_max(h), 3)
161 self.assertEqual(self.module._heappop_max(h), 2)
162
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000163 def test_heapsort(self):
164 # Exercise everything with repeated heapsort checks
Guido van Rossum805365e2007-05-07 22:24:25 +0000165 for trial in range(100):
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000166 size = random.randrange(50)
167 data = [random.randrange(25) for i in range(size)]
168 if trial & 1: # Half of the time, use heapify
169 heap = data[:]
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000170 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000171 else: # The rest of the time, use heappush
172 heap = []
173 for item in data:
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000174 self.module.heappush(heap, item)
175 heap_sorted = [self.module.heappop(heap) for i in range(size)]
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000176 self.assertEqual(heap_sorted, sorted(data))
177
Thomas Wouterscf297e42007-02-23 15:07:44 +0000178 def test_merge(self):
179 inputs = []
Raymond Hettinger35db4392014-05-30 02:28:36 -0700180 for i in range(random.randrange(25)):
181 row = []
182 for j in range(random.randrange(100)):
183 tup = random.choice('ABC'), random.randrange(-500, 500)
184 row.append(tup)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000185 inputs.append(row)
Raymond Hettinger35db4392014-05-30 02:28:36 -0700186
187 for key in [None, itemgetter(0), itemgetter(1), itemgetter(1, 0)]:
188 for reverse in [False, True]:
189 seqs = []
190 for seq in inputs:
191 seqs.append(sorted(seq, key=key, reverse=reverse))
192 self.assertEqual(sorted(chain(*inputs), key=key, reverse=reverse),
193 list(self.module.merge(*seqs, key=key, reverse=reverse)))
194 self.assertEqual(list(self.module.merge()), [])
Thomas Wouterscf297e42007-02-23 15:07:44 +0000195
Rob Day664fe392019-06-01 05:13:57 +0100196 def test_empty_merges(self):
197 # Merging two empty lists (with or without a key) should produce
198 # another empty list.
199 self.assertEqual(list(self.module.merge([], [])), [])
200 self.assertEqual(list(self.module.merge([], [], key=lambda: 6)), [])
201
Raymond Hettinger46f5ca32013-09-14 20:51:57 -0700202 def test_merge_does_not_suppress_index_error(self):
203 # Issue 19018: Heapq.merge suppresses IndexError from user generator
204 def iterable():
205 s = list(range(10))
206 for i in range(20):
207 yield s[i] # IndexError when i > 10
208 with self.assertRaises(IndexError):
209 list(self.module.merge(iterable(), iterable()))
210
Thomas Wouterscf297e42007-02-23 15:07:44 +0000211 def test_merge_stability(self):
212 class Int(int):
213 pass
214 inputs = [[], [], [], []]
215 for i in range(20000):
216 stream = random.randrange(4)
217 x = random.randrange(500)
218 obj = Int(x)
219 obj.pair = (x, stream)
220 inputs[stream].append(obj)
221 for stream in inputs:
222 stream.sort()
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000223 result = [i.pair for i in self.module.merge(*inputs)]
Thomas Wouterscf297e42007-02-23 15:07:44 +0000224 self.assertEqual(result, sorted(result))
225
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000226 def test_nsmallest(self):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000227 data = [(random.randrange(2000), i) for i in range(1000)]
228 for f in (None, lambda x: x[0] * 547 % 2000):
229 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000230 self.assertEqual(list(self.module.nsmallest(n, data)),
231 sorted(data)[:n])
232 self.assertEqual(list(self.module.nsmallest(n, data, key=f)),
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000233 sorted(data, key=f)[:n])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000234
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000235 def test_nlargest(self):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000236 data = [(random.randrange(2000), i) for i in range(1000)]
237 for f in (None, lambda x: x[0] * 547 % 2000):
238 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000239 self.assertEqual(list(self.module.nlargest(n, data)),
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000240 sorted(data, reverse=True)[:n])
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000241 self.assertEqual(list(self.module.nlargest(n, data, key=f)),
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000242 sorted(data, key=f, reverse=True)[:n])
Tim Petersaa7d2432002-08-03 02:11:26 +0000243
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000244 def test_comparison_operator(self):
Ezio Melottif9756c22011-05-09 18:36:53 +0300245 # Issue 3051: Make sure heapq works with both __lt__
Amaury Forgeot d'Arc2ba198d2008-06-17 21:25:35 +0000246 # For python 3.0, __le__ alone is not enough
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000247 def hsort(data, comp):
248 data = [comp(x) for x in data]
249 self.module.heapify(data)
250 return [self.module.heappop(data).x for i in range(len(data))]
251 class LT:
252 def __init__(self, x):
253 self.x = x
254 def __lt__(self, other):
255 return self.x > other.x
256 class LE:
257 def __init__(self, x):
258 self.x = x
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000259 def __le__(self, other):
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000260 return self.x >= other.x
261 data = [random.random() for i in range(100)]
262 target = sorted(data, reverse=True)
263 self.assertEqual(hsort(data, LT), target)
Amaury Forgeot d'Arc2ba198d2008-06-17 21:25:35 +0000264 self.assertRaises(TypeError, data, LE)
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000265
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000266
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200267class TestHeapPython(TestHeap, TestCase):
Ezio Melottif9756c22011-05-09 18:36:53 +0300268 module = py_heapq
269
270
271@skipUnless(c_heapq, 'requires _heapq')
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200272class TestHeapC(TestHeap, TestCase):
Ezio Melottif9756c22011-05-09 18:36:53 +0300273 module = c_heapq
274
275
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000276#==============================================================================
277
278class LenOnly:
279 "Dummy sequence class defining __len__ but not __getitem__."
280 def __len__(self):
281 return 10
282
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000283class CmpErr:
284 "Dummy element that always raises an error during comparison"
Mark Dickinsona56c4672009-01-27 18:17:45 +0000285 def __eq__(self, other):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000286 raise ZeroDivisionError
Mark Dickinsona56c4672009-01-27 18:17:45 +0000287 __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __eq__
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000288
289def R(seqn):
290 'Regular generator'
291 for i in seqn:
292 yield i
293
294class G:
295 'Sequence using __getitem__'
296 def __init__(self, seqn):
297 self.seqn = seqn
298 def __getitem__(self, i):
299 return self.seqn[i]
300
301class I:
302 'Sequence using iterator protocol'
303 def __init__(self, seqn):
304 self.seqn = seqn
305 self.i = 0
306 def __iter__(self):
307 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000308 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000309 if self.i >= len(self.seqn): raise StopIteration
310 v = self.seqn[self.i]
311 self.i += 1
312 return v
313
314class Ig:
315 'Sequence using iterator protocol defined with a generator'
316 def __init__(self, seqn):
317 self.seqn = seqn
318 self.i = 0
319 def __iter__(self):
320 for val in self.seqn:
321 yield val
322
323class X:
324 'Missing __getitem__ and __iter__'
325 def __init__(self, seqn):
326 self.seqn = seqn
327 self.i = 0
Georg Brandla18af4e2007-04-21 15:47:16 +0000328 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000329 if self.i >= len(self.seqn): raise StopIteration
330 v = self.seqn[self.i]
331 self.i += 1
332 return v
333
334class N:
Georg Brandla18af4e2007-04-21 15:47:16 +0000335 'Iterator missing __next__()'
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000336 def __init__(self, seqn):
337 self.seqn = seqn
338 self.i = 0
339 def __iter__(self):
340 return self
341
342class E:
343 'Test propagation of exceptions'
344 def __init__(self, seqn):
345 self.seqn = seqn
346 self.i = 0
347 def __iter__(self):
348 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000349 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000350 3 // 0
351
352class S:
353 'Test immediate stop'
354 def __init__(self, seqn):
355 pass
356 def __iter__(self):
357 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000358 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000359 raise StopIteration
360
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000361from itertools import chain
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000362def L(seqn):
363 'Test multiple tiers of iterators'
Raymond Hettingera6c60372008-03-13 01:26:19 +0000364 return chain(map(lambda x:x, R(Ig(G(seqn)))))
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000365
Ezio Melotti8269a442011-05-09 07:15:04 +0300366
Antoine Pitrou44d52142013-03-04 20:30:01 +0100367class SideEffectLT:
368 def __init__(self, value, heap):
369 self.value = value
370 self.heap = heap
371
372 def __lt__(self, other):
373 self.heap[:] = []
374 return self.value < other.value
375
376
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200377class TestErrorHandling:
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000378
379 def test_non_sequence(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000380 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700381 self.assertRaises((TypeError, AttributeError), f, 10)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000382 for f in (self.module.heappush, self.module.heapreplace,
383 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700384 self.assertRaises((TypeError, AttributeError), f, 10, 10)
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000385
386 def test_len_only(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000387 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700388 self.assertRaises((TypeError, AttributeError), f, LenOnly())
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000389 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700390 self.assertRaises((TypeError, AttributeError), f, LenOnly(), 10)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000391 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000392 self.assertRaises(TypeError, f, 2, LenOnly())
393
Miss Islington (bot)ef3ccd72019-08-23 22:54:07 -0700394 def test_cmp_err(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000395 seq = [CmpErr(), CmpErr(), CmpErr()]
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000396 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000397 self.assertRaises(ZeroDivisionError, f, seq)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000398 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000399 self.assertRaises(ZeroDivisionError, f, seq, 10)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000400 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000401 self.assertRaises(ZeroDivisionError, f, 2, seq)
402
403 def test_arg_parsing(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000404 for f in (self.module.heapify, self.module.heappop,
405 self.module.heappush, self.module.heapreplace,
406 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700407 self.assertRaises((TypeError, AttributeError), f, 10)
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000408
409 def test_iterable_args(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000410 for f in (self.module.nlargest, self.module.nsmallest):
Guido van Rossum805365e2007-05-07 22:24:25 +0000411 for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000412 for g in (G, I, Ig, L, R):
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000413 self.assertEqual(list(f(2, g(s))), list(f(2,s)))
414 self.assertEqual(list(f(2, S(s))), [])
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000415 self.assertRaises(TypeError, f, 2, X(s))
416 self.assertRaises(TypeError, f, 2, N(s))
417 self.assertRaises(ZeroDivisionError, f, 2, E(s))
418
Antoine Pitrou44d52142013-03-04 20:30:01 +0100419 # Issue #17278: the heap may change size while it's being walked.
420
421 def test_heappush_mutating_heap(self):
422 heap = []
423 heap.extend(SideEffectLT(i, heap) for i in range(200))
424 # Python version raises IndexError, C version RuntimeError
425 with self.assertRaises((IndexError, RuntimeError)):
426 self.module.heappush(heap, SideEffectLT(5, heap))
427
428 def test_heappop_mutating_heap(self):
429 heap = []
430 heap.extend(SideEffectLT(i, heap) for i in range(200))
431 # Python version raises IndexError, C version RuntimeError
432 with self.assertRaises((IndexError, RuntimeError)):
433 self.module.heappop(heap)
434
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000435
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200436class TestErrorHandlingPython(TestErrorHandling, TestCase):
Ezio Melottifd69abb2011-05-09 07:20:47 +0300437 module = py_heapq
438
Ezio Melotti19f7ca22011-05-09 07:27:20 +0300439@skipUnless(c_heapq, 'requires _heapq')
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200440class TestErrorHandlingC(TestErrorHandling, TestCase):
Ezio Melottifd69abb2011-05-09 07:20:47 +0300441 module = c_heapq
442
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000443
Guido van Rossum0b191782002-08-02 18:29:53 +0000444if __name__ == "__main__":
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200445 unittest.main()