Skip to content

Commit 664fe39

Browse files
rkdayrhettinger
authored andcommitted
bpo-29984: Improve 'heapq' test coverage (GH-992)
1 parent 5c22476 commit 664fe39

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

Lib/heapq.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -597,5 +597,5 @@ def nlargest(n, iterable, key=None):
597597

598598
if __name__ == "__main__":
599599

600-
import doctest
601-
print(doctest.testmod())
600+
import doctest # pragma: no cover
601+
print(doctest.testmod()) # pragma: no cover

Lib/test/test_heapq.py

+31
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import random
44
import unittest
5+
import doctest
56

67
from test import support
78
from unittest import TestCase, skipUnless
@@ -26,6 +27,23 @@ def test_c_functions(self):
2627
self.assertEqual(getattr(c_heapq, fname).__module__, '_heapq')
2728

2829

30+
def 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+
2947
class TestHeap:
3048

3149
def test_push_pop(self):
@@ -135,6 +153,13 @@ def test_heappushpop(self):
135153
x = self.module.heappushpop(h, 11)
136154
self.assertEqual((h, x), ([11], 10))
137155

156+
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+
138163
def test_heapsort(self):
139164
# Exercise everything with repeated heapsort checks
140165
for trial in range(100):
@@ -168,6 +193,12 @@ def test_merge(self):
168193
list(self.module.merge(*seqs, key=key, reverse=reverse)))
169194
self.assertEqual(list(self.module.merge()), [])
170195

196+
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+
171202
def test_merge_does_not_suppress_index_error(self):
172203
# Issue 19018: Heapq.merge suppresses IndexError from user generator
173204
def iterable():

0 commit comments

Comments
 (0)