capfd helps you check what your program prints to the screen. It captures output sent to file descriptors like standard output and error.
0
0
capfd for file descriptors in PyTest
Introduction
You want to test if a function prints the right message to the console.
You need to check error messages printed to standard error during a test.
You want to verify output from code that uses low-level print calls.
You want to capture and check output without changing the original code.
Syntax
PyTest
def test_function(capfd): # run code that prints captured = capfd.readouterr() assert captured.out == 'expected output\n' assert captured.err == ''
capfd is a pytest fixture you add as a test function argument.
Use capfd.readouterr() to get captured output and error as strings.
Examples
This test checks that 'Hello world' is printed to standard output.
PyTest
def test_print_message(capfd): print('Hello world') captured = capfd.readouterr() assert captured.out == 'Hello world\n' assert captured.err == ''
This test checks that an error message is printed to standard error.
PyTest
def test_error_message(capfd): import sys print('Error happened', file=sys.stderr) captured = capfd.readouterr() assert captured.err == 'Error happened\n' assert captured.out == ''
Sample Program
This test calls a function that prints a greeting. It uses capfd to capture and check the printed output.
PyTest
def greet(name): print(f'Hello, {name}!') def test_greet(capfd): greet('Alice') captured = capfd.readouterr() assert captured.out == 'Hello, Alice!\n' assert captured.err == '' # Running this test with pytest will pass if output matches.
OutputSuccess
Important Notes
capfd captures output at the file descriptor level, so it works even if code uses low-level print calls.
Always call capfd.readouterr() after the code that prints to capture fresh output.
Summary
capfd is a pytest tool to capture printed output and errors during tests.
Use it to check what your code prints without changing the code.
Remember to assert both standard output and standard error as needed.