Batu Lab NotesPractical developer guides

Keep long unittest diffs available when debugging a mismatch

By Batu · English technical notes

A direct answer to “Keep long unittest diffs available when debugging a mismatch Python” is: set maxDiff to None on the test case that needs the full diff. A finite value can keep routine failures compact, but it can replace useful details of a large comparison with a truncation notice.

This fixture creates the same deterministic dictionary mismatch twice. With maxDiff = 60, the captured failure reports that the diff is abbreviated and suggests setting maxDiff to None. With maxDiff = None, the failure contains the changed key and both synthetic values. The code checks those relevant fragments instead of snapshotting the full exception text, whose formatting and total length can vary across Python releases.

Apply the unlimited setting to a focused debugging test or test class when the complete difference is valuable. It affects assertion diagnostics, not equality: both comparisons still fail because the dictionaries differ. It also cannot guarantee that a terminal, CI log collector, or editor preserves every emitted character after the failure is reported. TestCase.maxDiff was added in Python 3.2. See the official maxDiff documentation.

AI assistance disclosure: this synthetic mismatch fixture was drafted with AI assistance.

import unittest

left = {f"item_{number:02}": "A" * 20 for number in range(8)}
right = {f"item_{number:02}": "B" * 20 for number in range(8)}

bounded = unittest.TestCase()
bounded.maxDiff = 60
try:
    bounded.assertDictEqual(left, right)
except AssertionError as error:
    bounded_message = str(error)
else:
    raise AssertionError("the dictionaries must differ")

unlimited = unittest.TestCase()
unlimited.maxDiff = None
try:
    unlimited.assertDictEqual(left, right)
except AssertionError as error:
    unlimited_message = str(error)
else:
    raise AssertionError("the dictionaries must differ")

assert "Diff is" in bounded_message
assert "Set self.maxDiff to None" in bounded_message
assert "item_00" in unlimited_message
assert "AAAAAAAAAAAAAAAAAAAA" in unlimited_message
assert "BBBBBBBBBBBBBBBBBBBB" in unlimited_message

print("bounded=truncated")
print("unlimited=contains-changed-values")
bounded=truncated
unlimited=contains-changed-values