blob: ebbc62745707cc407067061f2fb471973150f9e7 [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
Hai Shi883bc632020-07-06 17:12:49 +08008from test.support import import_helper
Ezio Melotti8269a442011-05-09 07:15:04 +03009from unittest import TestCase, skipUnless
Raymond Hettinger35db4392014-05-30 02:28:36 -070010from operator import itemgetter
Ezio Melotti8269a442011-05-09 07:15:04 +030011
Hai Shi883bc632020-07-06 17:12:49 +080012py_heapq = import_helper.import_fresh_module('heapq', blocked=['_heapq'])
13c_heapq = import_helper.import_fresh_module('heapq', fresh=['_heapq'])
Tim Petersaa7d2432002-08-03 02:11:26 +000014
Ezio Melotti8269a442011-05-09 07:15:04 +030015# _heapq.nlargest/nsmallest are saved in heapq._nlargest/_smallest when
16# _heapq is imported, so check them there
Raymond Hettinger48f68d02014-06-14 16:43:35 -070017func_names = ['heapify', 'heappop', 'heappush', 'heappushpop', 'heapreplace',
18 '_heappop_max', '_heapreplace_max', '_heapify_max']
Ezio Melotti8269a442011-05-09 07:15:04 +030019
20class TestModules(TestCase):
21 def test_py_functions(self):
22 for fname in func_names:
23 self.assertEqual(getattr(py_heapq, fname).__module__, 'heapq')
24
25 @skipUnless(c_heapq, 'requires _heapq')
26 def test_c_functions(self):
27 for fname in func_names:
28 self.assertEqual(getattr(c_heapq, fname).__module__, '_heapq')
29
30
Rob Day664fe392019-06-01 05:13:57 +010031def load_tests(loader, tests, ignore):
32 # The 'merge' function has examples in its docstring which we should test
33 # with 'doctest'.
34 #
35 # However, doctest can't easily find all docstrings in the module (loading
36 # it through import_fresh_module seems to confuse it), so we specifically
37 # create a finder which returns the doctests from the merge method.
38
39 class HeapqMergeDocTestFinder:
40 def find(self, *args, **kwargs):
41 dtf = doctest.DocTestFinder()
42 return dtf.find(py_heapq.merge)
43
44 tests.addTests(doctest.DocTestSuite(py_heapq,
45 test_finder=HeapqMergeDocTestFinder()))
46 return tests
47
Ezio Melotti22ebb2d2013-01-02 21:19:37 +020048class TestHeap:
Tim Petersaa7d2432002-08-03 02:11:26 +000049
Raymond Hettingerbce036b2004-06-10 05:07:18 +000050 def test_push_pop(self):
51 # 1) Push 256 random numbers and pop them off, verifying all's OK.
52 heap = []
53 data = []
54 self.check_invariant(heap)
55 for i in range(256):
56 item = random.random()
57 data.append(item)
Christian Heimesd3eb5a152008-02-24 00:38:49 +000058 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000059 self.check_invariant(heap)
60 results = []
61 while heap:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000062 item = self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000063 self.check_invariant(heap)
64 results.append(item)
65 data_sorted = data[:]
66 data_sorted.sort()
67 self.assertEqual(data_sorted, results)
68 # 2) Check that the invariant holds for a sorted array
69 self.check_invariant(results)
70
Christian Heimesd3eb5a152008-02-24 00:38:49 +000071 self.assertRaises(TypeError, self.module.heappush, [])
Raymond Hettingere1defa42004-11-29 05:54:48 +000072 try:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000073 self.assertRaises(TypeError, self.module.heappush, None, None)
74 self.assertRaises(TypeError, self.module.heappop, None)
Raymond Hettingere1defa42004-11-29 05:54:48 +000075 except AttributeError:
76 pass
Neal Norwitzd7be1182004-07-08 01:56:46 +000077
Raymond Hettingerbce036b2004-06-10 05:07:18 +000078 def check_invariant(self, heap):
79 # Check the heap invariant.
80 for pos, item in enumerate(heap):
81 if pos: # pos 0 has no parent
82 parentpos = (pos-1) >> 1
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000083 self.assertTrue(heap[parentpos] <= item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000084
85 def test_heapify(self):
Raymond Hettinger849564f2015-05-12 21:42:40 -070086 for size in list(range(30)) + [20000]:
Raymond Hettingerbce036b2004-06-10 05:07:18 +000087 heap = [random.random() for dummy in range(size)]
Christian Heimesd3eb5a152008-02-24 00:38:49 +000088 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000089 self.check_invariant(heap)
90
Christian Heimesd3eb5a152008-02-24 00:38:49 +000091 self.assertRaises(TypeError, self.module.heapify, None)
Neal Norwitzd7be1182004-07-08 01:56:46 +000092
Raymond Hettingerbce036b2004-06-10 05:07:18 +000093 def test_naive_nbest(self):
94 data = [random.randrange(2000) for i in range(1000)]
95 heap = []
96 for item in data:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000097 self.module.heappush(heap, item)
Raymond Hettingerbce036b2004-06-10 05:07:18 +000098 if len(heap) > 10:
Christian Heimesd3eb5a152008-02-24 00:38:49 +000099 self.module.heappop(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000100 heap.sort()
101 self.assertEqual(heap, sorted(data)[-10:])
102
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000103 def heapiter(self, heap):
104 # An iterator returning a heap's elements, smallest-first.
105 try:
106 while 1:
107 yield self.module.heappop(heap)
108 except IndexError:
109 pass
110
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000111 def test_nbest(self):
112 # Less-naive "N-best" algorithm, much faster (if len(data) is big
113 # enough <wink>) than sorting all of data. However, if we had a max
114 # heap instead of a min heap, it could go faster still via
115 # heapify'ing all of data (linear time), then doing 10 heappops
116 # (10 log-time steps).
117 data = [random.randrange(2000) for i in range(1000)]
118 heap = data[:10]
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000119 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000120 for item in data[10:]:
121 if item > heap[0]: # this gets rarer the longer we run
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000122 self.module.heapreplace(heap, item)
123 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000124
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000125 self.assertRaises(TypeError, self.module.heapreplace, None)
126 self.assertRaises(TypeError, self.module.heapreplace, None, None)
127 self.assertRaises(IndexError, self.module.heapreplace, [], None)
Neal Norwitzd7be1182004-07-08 01:56:46 +0000128
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000129 def test_nbest_with_pushpop(self):
130 data = [random.randrange(2000) for i in range(1000)]
131 heap = data[:10]
132 self.module.heapify(heap)
133 for item in data[10:]:
134 self.module.heappushpop(heap, item)
135 self.assertEqual(list(self.heapiter(heap)), sorted(data)[-10:])
136 self.assertEqual(self.module.heappushpop([], 'x'), 'x')
137
138 def test_heappushpop(self):
139 h = []
140 x = self.module.heappushpop(h, 10)
141 self.assertEqual((h, x), ([], 10))
142
143 h = [10]
144 x = self.module.heappushpop(h, 10.0)
145 self.assertEqual((h, x), ([10], 10.0))
146 self.assertEqual(type(h[0]), int)
147 self.assertEqual(type(x), float)
148
149 h = [10];
150 x = self.module.heappushpop(h, 9)
151 self.assertEqual((h, x), ([10], 9))
152
153 h = [10];
154 x = self.module.heappushpop(h, 11)
155 self.assertEqual((h, x), ([11], 10))
156
Rob Day664fe392019-06-01 05:13:57 +0100157 def test_heappop_max(self):
158 # _heapop_max has an optimization for one-item lists which isn't
159 # covered in other tests, so test that case explicitly here
160 h = [3, 2]
161 self.assertEqual(self.module._heappop_max(h), 3)
162 self.assertEqual(self.module._heappop_max(h), 2)
163
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000164 def test_heapsort(self):
165 # Exercise everything with repeated heapsort checks
Guido van Rossum805365e2007-05-07 22:24:25 +0000166 for trial in range(100):
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000167 size = random.randrange(50)
168 data = [random.randrange(25) for i in range(size)]
169 if trial & 1: # Half of the time, use heapify
170 heap = data[:]
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000171 self.module.heapify(heap)
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000172 else: # The rest of the time, use heappush
173 heap = []
174 for item in data:
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000175 self.module.heappush(heap, item)
176 heap_sorted = [self.module.heappop(heap) for i in range(size)]
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000177 self.assertEqual(heap_sorted, sorted(data))
178
Thomas Wouterscf297e42007-02-23 15:07:44 +0000179 def test_merge(self):
180 inputs = []
Raymond Hettinger35db4392014-05-30 02:28:36 -0700181 for i in range(random.randrange(25)):
182 row = []
183 for j in range(random.randrange(100)):
184 tup = random.choice('ABC'), random.randrange(-500, 500)
185 row.append(tup)
Thomas Wouterscf297e42007-02-23 15:07:44 +0000186 inputs.append(row)
Raymond Hettinger35db4392014-05-30 02:28:36 -0700187
188 for key in [None, itemgetter(0), itemgetter(1), itemgetter(1, 0)]:
189 for reverse in [False, True]:
190 seqs = []
191 for seq in inputs:
192 seqs.append(sorted(seq, key=key, reverse=reverse))
193 self.assertEqual(sorted(chain(*inputs), key=key, reverse=reverse),
194 list(self.module.merge(*seqs, key=key, reverse=reverse)))
195 self.assertEqual(list(self.module.merge()), [])
Thomas Wouterscf297e42007-02-23 15:07:44 +0000196
Rob Day664fe392019-06-01 05:13:57 +0100197 def test_empty_merges(self):
198 # Merging two empty lists (with or without a key) should produce
199 # another empty list.
200 self.assertEqual(list(self.module.merge([], [])), [])
201 self.assertEqual(list(self.module.merge([], [], key=lambda: 6)), [])
202
Raymond Hettinger46f5ca32013-09-14 20:51:57 -0700203 def test_merge_does_not_suppress_index_error(self):
204 # Issue 19018: Heapq.merge suppresses IndexError from user generator
205 def iterable():
206 s = list(range(10))
207 for i in range(20):
208 yield s[i] # IndexError when i > 10
209 with self.assertRaises(IndexError):
210 list(self.module.merge(iterable(), iterable()))
211
Thomas Wouterscf297e42007-02-23 15:07:44 +0000212 def test_merge_stability(self):
213 class Int(int):
214 pass
215 inputs = [[], [], [], []]
216 for i in range(20000):
217 stream = random.randrange(4)
218 x = random.randrange(500)
219 obj = Int(x)
220 obj.pair = (x, stream)
221 inputs[stream].append(obj)
222 for stream in inputs:
223 stream.sort()
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000224 result = [i.pair for i in self.module.merge(*inputs)]
Thomas Wouterscf297e42007-02-23 15:07:44 +0000225 self.assertEqual(result, sorted(result))
226
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000227 def test_nsmallest(self):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000228 data = [(random.randrange(2000), i) for i in range(1000)]
229 for f in (None, lambda x: x[0] * 547 % 2000):
230 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000231 self.assertEqual(list(self.module.nsmallest(n, data)),
232 sorted(data)[:n])
233 self.assertEqual(list(self.module.nsmallest(n, data, key=f)),
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000234 sorted(data, key=f)[:n])
Raymond Hettingerbce036b2004-06-10 05:07:18 +0000235
Raymond Hettinger4901a1f2004-12-02 08:59:14 +0000236 def test_nlargest(self):
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000237 data = [(random.randrange(2000), i) for i in range(1000)]
238 for f in (None, lambda x: x[0] * 547 % 2000):
239 for n in (0, 1, 2, 10, 100, 400, 999, 1000, 1100):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000240 self.assertEqual(list(self.module.nlargest(n, data)),
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000241 sorted(data, reverse=True)[:n])
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000242 self.assertEqual(list(self.module.nlargest(n, data, key=f)),
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000243 sorted(data, key=f, reverse=True)[:n])
Tim Petersaa7d2432002-08-03 02:11:26 +0000244
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000245 def test_comparison_operator(self):
Ezio Melottif9756c22011-05-09 18:36:53 +0300246 # Issue 3051: Make sure heapq works with both __lt__
Amaury Forgeot d'Arc2ba198d2008-06-17 21:25:35 +0000247 # For python 3.0, __le__ alone is not enough
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000248 def hsort(data, comp):
249 data = [comp(x) for x in data]
250 self.module.heapify(data)
251 return [self.module.heappop(data).x for i in range(len(data))]
252 class LT:
253 def __init__(self, x):
254 self.x = x
255 def __lt__(self, other):
256 return self.x > other.x
257 class LE:
258 def __init__(self, x):
259 self.x = x
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000260 def __le__(self, other):
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000261 return self.x >= other.x
262 data = [random.random() for i in range(100)]
263 target = sorted(data, reverse=True)
264 self.assertEqual(hsort(data, LT), target)
Amaury Forgeot d'Arc2ba198d2008-06-17 21:25:35 +0000265 self.assertRaises(TypeError, data, LE)
Amaury Forgeot d'Arcfdfe62d2008-06-17 20:36:03 +0000266
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000267
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200268class TestHeapPython(TestHeap, TestCase):
Ezio Melottif9756c22011-05-09 18:36:53 +0300269 module = py_heapq
270
271
272@skipUnless(c_heapq, 'requires _heapq')
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200273class TestHeapC(TestHeap, TestCase):
Ezio Melottif9756c22011-05-09 18:36:53 +0300274 module = c_heapq
275
276
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000277#==============================================================================
278
279class LenOnly:
280 "Dummy sequence class defining __len__ but not __getitem__."
281 def __len__(self):
282 return 10
283
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000284class CmpErr:
285 "Dummy element that always raises an error during comparison"
Mark Dickinsona56c4672009-01-27 18:17:45 +0000286 def __eq__(self, other):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000287 raise ZeroDivisionError
Mark Dickinsona56c4672009-01-27 18:17:45 +0000288 __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __eq__
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000289
290def R(seqn):
291 'Regular generator'
292 for i in seqn:
293 yield i
294
295class G:
296 'Sequence using __getitem__'
297 def __init__(self, seqn):
298 self.seqn = seqn
299 def __getitem__(self, i):
300 return self.seqn[i]
301
302class I:
303 'Sequence using iterator protocol'
304 def __init__(self, seqn):
305 self.seqn = seqn
306 self.i = 0
307 def __iter__(self):
308 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000309 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000310 if self.i >= len(self.seqn): raise StopIteration
311 v = self.seqn[self.i]
312 self.i += 1
313 return v
314
315class Ig:
316 'Sequence using iterator protocol defined with a generator'
317 def __init__(self, seqn):
318 self.seqn = seqn
319 self.i = 0
320 def __iter__(self):
321 for val in self.seqn:
322 yield val
323
324class X:
325 'Missing __getitem__ and __iter__'
326 def __init__(self, seqn):
327 self.seqn = seqn
328 self.i = 0
Georg Brandla18af4e2007-04-21 15:47:16 +0000329 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000330 if self.i >= len(self.seqn): raise StopIteration
331 v = self.seqn[self.i]
332 self.i += 1
333 return v
334
335class N:
Georg Brandla18af4e2007-04-21 15:47:16 +0000336 'Iterator missing __next__()'
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000337 def __init__(self, seqn):
338 self.seqn = seqn
339 self.i = 0
340 def __iter__(self):
341 return self
342
343class E:
344 'Test propagation of exceptions'
345 def __init__(self, seqn):
346 self.seqn = seqn
347 self.i = 0
348 def __iter__(self):
349 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000350 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000351 3 // 0
352
353class S:
354 'Test immediate stop'
355 def __init__(self, seqn):
356 pass
357 def __iter__(self):
358 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000359 def __next__(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000360 raise StopIteration
361
Raymond Hettinger736c0ab2008-03-13 02:09:15 +0000362from itertools import chain
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000363def L(seqn):
364 'Test multiple tiers of iterators'
Raymond Hettingera6c60372008-03-13 01:26:19 +0000365 return chain(map(lambda x:x, R(Ig(G(seqn)))))
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000366
Ezio Melotti8269a442011-05-09 07:15:04 +0300367
Antoine Pitrou44d52142013-03-04 20:30:01 +0100368class SideEffectLT:
369 def __init__(self, value, heap):
370 self.value = value
371 self.heap = heap
372
373 def __lt__(self, other):
374 self.heap[:] = []
375 return self.value < other.value
376
377
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200378class TestErrorHandling:
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000379
380 def test_non_sequence(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000381 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700382 self.assertRaises((TypeError, AttributeError), f, 10)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000383 for f in (self.module.heappush, self.module.heapreplace,
384 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700385 self.assertRaises((TypeError, AttributeError), f, 10, 10)
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000386
387 def test_len_only(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000388 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700389 self.assertRaises((TypeError, AttributeError), f, LenOnly())
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000390 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700391 self.assertRaises((TypeError, AttributeError), f, LenOnly(), 10)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000392 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000393 self.assertRaises(TypeError, f, 2, LenOnly())
394
Raymond Hettinger41011812019-08-23 22:31:22 -0700395 def test_cmp_err(self):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000396 seq = [CmpErr(), CmpErr(), CmpErr()]
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000397 for f in (self.module.heapify, self.module.heappop):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000398 self.assertRaises(ZeroDivisionError, f, seq)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000399 for f in (self.module.heappush, self.module.heapreplace):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000400 self.assertRaises(ZeroDivisionError, f, seq, 10)
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000401 for f in (self.module.nlargest, self.module.nsmallest):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000402 self.assertRaises(ZeroDivisionError, f, 2, seq)
403
404 def test_arg_parsing(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000405 for f in (self.module.heapify, self.module.heappop,
406 self.module.heappush, self.module.heapreplace,
407 self.module.nlargest, self.module.nsmallest):
Raymond Hettinger8a9c4d92011-04-13 11:49:57 -0700408 self.assertRaises((TypeError, AttributeError), f, 10)
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000409
410 def test_iterable_args(self):
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000411 for f in (self.module.nlargest, self.module.nsmallest):
Guido van Rossum805365e2007-05-07 22:24:25 +0000412 for s in ("123", "", range(1000), (1, 1.2), range(2000,2200,5)):
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000413 for g in (G, I, Ig, L, R):
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000414 self.assertEqual(list(f(2, g(s))), list(f(2,s)))
415 self.assertEqual(list(f(2, S(s))), [])
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000416 self.assertRaises(TypeError, f, 2, X(s))
417 self.assertRaises(TypeError, f, 2, N(s))
418 self.assertRaises(ZeroDivisionError, f, 2, E(s))
419
Antoine Pitrou44d52142013-03-04 20:30:01 +0100420 # Issue #17278: the heap may change size while it's being walked.
421
422 def test_heappush_mutating_heap(self):
423 heap = []
424 heap.extend(SideEffectLT(i, heap) for i in range(200))
425 # Python version raises IndexError, C version RuntimeError
426 with self.assertRaises((IndexError, RuntimeError)):
427 self.module.heappush(heap, SideEffectLT(5, heap))
428
429 def test_heappop_mutating_heap(self):
430 heap = []
431 heap.extend(SideEffectLT(i, heap) for i in range(200))
432 # Python version raises IndexError, C version RuntimeError
433 with self.assertRaises((IndexError, RuntimeError)):
434 self.module.heappop(heap)
435
Pablo Galindo79f89e62020-01-23 14:07:05 +0000436 def test_comparison_operator_modifiying_heap(self):
437 # See bpo-39421: Strong references need to be taken
438 # when comparing objects as they can alter the heap
439 class EvilClass(int):
440 def __lt__(self, o):
441 heap.clear()
442 return NotImplemented
443
444 heap = []
445 self.module.heappush(heap, EvilClass(0))
446 self.assertRaises(IndexError, self.module.heappushpop, heap, 1)
447
448 def test_comparison_operator_modifiying_heap_two_heaps(self):
449
450 class h(int):
451 def __lt__(self, o):
452 list2.clear()
453 return NotImplemented
454
455 class g(int):
456 def __lt__(self, o):
457 list1.clear()
458 return NotImplemented
459
460 list1, list2 = [], []
461
462 self.module.heappush(list1, h(0))
463 self.module.heappush(list2, g(0))
464
465 self.assertRaises((IndexError, RuntimeError), self.module.heappush, list1, g(1))
466 self.assertRaises((IndexError, RuntimeError), self.module.heappush, list2, h(1))
Christian Heimesd3eb5a152008-02-24 00:38:49 +0000467
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200468class TestErrorHandlingPython(TestErrorHandling, TestCase):
Ezio Melottifd69abb2011-05-09 07:20:47 +0300469 module = py_heapq
470
Ezio Melotti19f7ca22011-05-09 07:27:20 +0300471@skipUnless(c_heapq, 'requires _heapq')
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200472class TestErrorHandlingC(TestErrorHandling, TestCase):
Ezio Melottifd69abb2011-05-09 07:20:47 +0300473 module = c_heapq
474
Raymond Hettinger855d9a92004-09-28 00:03:54 +0000475
Guido van Rossum0b191782002-08-02 18:29:53 +0000476if __name__ == "__main__":
Ezio Melotti22ebb2d2013-01-02 21:19:37 +0200477 unittest.main()