How to Verify Formatted Output with an Approval Test in Python
Write a small Python approval test that verifies a function's exact formatted output using unittest.
Python code
21 linesimport sys
from io import StringIO
import unittest
def generate_output(name, score):
return f"Player: {name} | Score: {score:03d}"
class TestFormattedOutput(unittest.TestCase):
def test_output_format(self):
expected = "Player: Alice | Score: 042"
result = generate_output("Alice", 42)
self.assertEqual(result, expected)
if __name__ == "__main__":
# Simple verification without unittest
test_output = generate_output("Alice", 42)
expected_output = "Player: Alice | Score: 042"
print(f"Actual: {test_output}")
print(f"Expected: {expected_output}")
print("PASS" if test_output == expected_output else "FAIL")
unittest.main(argv=[''], exit=False)
Output
Actual: Player: Alice | Score: 042
Expected: Player: Alice | Score: 042
PASS
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
How it works
This code defines a generate_output function that formats a name and score with a zero-padded score. The TestFormattedOutput unittest class checks the function's output against an expected string using assertEqual. The script also includes a lightweight manual verification block that prints both actual and expected outputs and a PASS/FAIL marker, useful for quick checks without the test runner. Finally, unittest.main runs the formal test suite, giving a clear OK or failure summary.
Common mistakes
- Forgetting that `assertEqual` compares strings exactly, including spaces and punctuation.
- Using `print` statements without flushing in manual verification can mislead in buffered environments.
- Not zero-padding the score in the expected output, causing a mismatch.
Variations
- Use pytest with a simple `assert` statement instead of unittest.
- Use the `approvaltests` library for file-based approval testing.
Real-world use cases
- Verifying that a report generator produces the exact text format expected by a downstream system.
- Ensuring a CLI tool prints the correct summary line before shipping a release.
- Locking down the format of log messages so automated parsers can rely on them.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.