0
0
PyTesttesting~15 mins

capfd for file descriptors in PyTest - Build an Automation Script

Choose your learning style9 modes available
Capture and verify output printed to stdout and stderr using capfd
Preconditions (2)
Step 1: Write a test function that uses the capfd fixture
Step 2: Call the function that prints to stdout and stderr inside the test
Step 3: Use capfd.readouterr() to capture the output
Step 4: Verify that the captured stdout contains the expected message
Step 5: Verify that the captured stderr contains the expected error message
✅ Expected Result: The test passes if the captured stdout and stderr match the expected messages
Automation Requirements - pytest
Assertions Needed:
Assert that captured stdout contains the expected string
Assert that captured stderr contains the expected string
Best Practices:
Use capfd fixture parameter in the test function
Call capfd.readouterr() only once after the output is generated
Avoid printing inside assertions
Keep test functions simple and focused
Automated Solution
PyTest
import sys
import pytest

def print_messages():
    print("Hello stdout")
    print("Error message", file=sys.stderr)


def test_capture_output(capfd):
    print_messages()
    out, err = capfd.readouterr()
    assert "Hello stdout" in out
    assert "Error message" in err

The print_messages function prints a message to standard output and another to standard error.

The test function test_capture_output uses the capfd fixture to capture these outputs.

After calling print_messages(), it calls capfd.readouterr() once to get both stdout and stderr.

Assertions check that the expected messages appear in the captured output streams.

This approach ensures the test verifies exactly what the function prints, without showing output during test runs.

Common Mistakes - 3 Pitfalls
Calling capfd.readouterr() multiple times in the same test
Not using the capfd fixture parameter in the test function
Printing inside the test assertions
Bonus Challenge

Now add data-driven testing with 3 different functions that print different messages to stdout and stderr, and verify each output using capfd.

Show Hint