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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 13 views 0 copies

Python code

21 lines
Python 3.9+
import 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

stdout
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

  1. Use pytest with a simple `assert` statement instead of unittest.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.