0
0
PyTesttesting~15 mins

capsys for capturing output in PyTest - Build an Automation Script

Choose your learning style9 modes available
Capture and verify printed output using capsys in pytest
Preconditions (2)
Step 1: Write a Python function that prints 'Hello, world!'
Step 2: Write a pytest test function that calls the print function
Step 3: Use the capsys fixture to capture the printed output
Step 4: Assert that the captured output matches 'Hello, world!\n'
✅ Expected Result: The test passes confirming the printed output is correctly captured and matches the expected string
Automation Requirements - pytest
Assertions Needed:
Assert captured stdout equals 'Hello, world!\n'
Best Practices:
Use the capsys fixture parameter in the test function
Call the function that prints output inside the test
Use capsys.readouterr() to capture stdout and stderr
Assert only the needed output, avoid hardcoding unrelated text
Automated Solution
PyTest
import pytest

def greet():
    print("Hello, world!")


def test_greet_output(capsys):
    greet()
    captured = capsys.readouterr()
    assert captured.out == "Hello, world!\n"

The greet function prints the string 'Hello, world!'.

The test function test_greet_output uses the capsys fixture provided by pytest to capture output printed to the console.

Inside the test, we call greet() which prints the message. Then capsys.readouterr() captures the output streams.

We assert that captured.out (standard output) exactly matches the expected string including the newline character.

This confirms the printed output is correctly captured and verified.

Common Mistakes - 3 Pitfalls
Not using the capsys fixture parameter in the test function
Calling capsys.readouterr() before the function that prints output
{'mistake': 'Asserting captured.out without considering the newline character', 'why_bad': 'Print adds a newline, so missing it in the assertion causes false failures.', 'correct_approach': "Include the newline character '\\n' in the expected string when asserting captured output."}
Bonus Challenge

Now add data-driven testing to capture and verify output for three different greetings: 'Hello, world!', 'Hi there!', and 'Good morning!'

Show Hint