Index: Lib/test/test_heapq.py =================================================================== --- Lib/test/test_heapq.py (revision 64118) +++ Lib/test/test_heapq.py (working copy) @@ -135,21 +135,78 @@ x = self.module.heappushpop(h, 11) self.assertEqual((h, x), ([11], 10)) + def _heapsort_test(self, trial, data): + if trial & 1: # Half of the time, use heapify + heap = data[:] + self.module.heapify(heap) + else: # The rest of the time, use heappush + heap = [] + for item in data: + self.module.heappush(heap, item) + heap_sorted = [self.module.heappop(heap) for i in range(len(data))] + return heap_sorted + + def test_heapsort(self): # Exercise everything with repeated heapsort checks for trial in xrange(100): size = random.randrange(50) data = [random.randrange(25) for i in range(size)] - if trial & 1: # Half of the time, use heapify - heap = data[:] - self.module.heapify(heap) - else: # The rest of the time, use heappush - heap = [] - for item in data: - self.module.heappush(heap, item) - heap_sorted = [self.module.heappop(heap) for i in range(size)] + heap_sorted = self._heapsort_test(trial, data) self.assertEqual(heap_sorted, sorted(data)) + + def _only_one_comparison_test(self, cls): + for trial in xrange(100): + size = random.randrange(50) + data = [cls(random.randrange(25)) for i in range(size)] + heap_sorted = self._heapsort_test(trial, data) + self.assertEqual( + [only.value for only in heap_sorted], + sorted([only.value for only in heap_sorted])) + + + def test_only_le(self): + """ + heapify, heappush, and heappop behave same when operating on a list + of objects which only implement __le__ as they do when operating on + a list of ints. + """ + class OnlyLE: + """ + An example of a class the instances of which might appear in a + heap and which only implements <=, no other comparison + operators. + """ + def __init__(self, value): + self.value = value + + def __le__(self, other): + return self.value <= other.value + + self._only_one_comparison_test(OnlyLE) + + + def test_only_lt(self): + """ + heapify, heappush, and heappop behave same when operating on a list + of objects which only implement __lt__ as they do when operating on + a list of ints. + """ + class OnlyLT: + """ + An example of a class the instances of which might appear in a + heap and which only implements <, no other comparison operators. + """ + def __init__(self, value): + self.value = value + + def __lt__(self, other): + return self.value < other.value + + self._only_one_comparison_test(OnlyLT) + + def test_merge(self): inputs = [] for i in xrange(random.randrange(5)): @@ -190,6 +247,7 @@ self.assertEqual(self.module.nlargest(n, data, key=f), sorted(data, key=f, reverse=True)[:n]) + class TestHeapPython(TestHeap): module = py_heapq