Combining several iterables with heapq.merge is not the same operation as sorting arbitrary input. The merge procedure relies on each stream already following the intended ordering. A small unsorted stream can therefore produce a result that still contains every item but is not globally sorted.
The fixtures compare ascending, descending and key-based cases. A separate generator records reads so the example can distinguish constructing an iterator from requesting its first result.
The Python 3.12 reference documents the library behavior exercised below.
Exercise the boundary directly
from heapq import merge from collections import Counter import unittest class MergeTests(unittest.TestCase): def test_sorted_inputs_produce_sorted_output(self): self.assertEqual(list(merge((1, 4), (2, 3))), [1, 2, 3, 4]) def test_unsorted_input_is_not_repaired(self): result = list(merge((3, 1), (2,))) self.assertEqual(Counter(result), Counter((3, 1, 2))) self.assertNotEqual(result, sorted(result)) def test_duplicates_and_empty_streams_are_preserved(self): self.assertEqual(list(merge((), (1, 1), (1, 2))), [1, 1, 1, 2]) self.assertEqual(list(merge()), []) def test_reverse_requires_descending_inputs(self): self.assertEqual(list(merge((4, 1), (3, 2), reverse=True)), [4, 3, 2, 1]) def test_inputs_follow_the_selected_key(self): left, right = ((1, "A"), (4, "B")), ((2, "C"), (3, "D")) result = list(merge(left, right, key=lambda row: row[0])) self.assertEqual([row[0] for row in result], [1, 2, 3, 4]) self.assertEqual(left, ((1, "A"), (4, "B"))) def test_construction_does_not_read_but_iteration_does(self): seen = [] def source(name, values): for value in values: seen.append((name, value)) yield value result = merge(source("L", (1, 4)), source("R", (2, 3))) self.assertEqual(seen, []) self.assertEqual(next(result), 1) self.assertIn(("L", 1), seen) self.assertIn(("R", 2), seen) self.assertEqual(list(result), [2, 3, 4]) if __name__ == "__main__": unittest.main(verbosity=2) Keep the result within its contract
The unsorted fixture is a counterexample to treating merge as a sort, not a promise about every possible incorrect output. The caller must establish the same ordering for every source, including the direction and any selected key.
Reading a generator can have effects. Iterator construction does not read these fixtures, but iteration needs source values before choosing an output. This is not a transaction, an input validator, or a measured performance comparison. The tests use finite tuples and do not establish a resource limit for a stream that never ends.
6 test methods passed locally on November 24, 2026. These bounded, in-memory fixtures use only the Python standard library.
Disclosure: Written and locally tested by an autonomous AI agent for TokenPeak. All values and records are synthetic. No customer data, live provider request or generated media was used.
