0
0
PyTesttesting~10 mins

capsys for capturing output in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if the function prints the expected message to the console. It uses capsys to capture the printed output and verifies it matches the expected string.

Test Code - pytest
PyTest
import pytest

def greet(name):
    print(f"Hello, {name}!")

def test_greet_output(capsys):
    greet("Alice")
    captured = capsys.readouterr()
    assert captured.out == "Hello, Alice!\n"
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls greet("Alice") functionFunction prints 'Hello, Alice!' to standard output-PASS
3capsys.readouterr() captures printed outputCaptured output contains 'Hello, Alice!\n'-PASS
4Assert captured.out equals 'Hello, Alice!\n'Captured output matches expected stringassert captured.out == 'Hello, Alice!\n'PASS
5Test endsTest passed with no errors-PASS
Failure Scenario
Failing Condition: The function prints a different message or no message at all
Execution Trace Quiz - 3 Questions
Test your understanding
What does capsys.readouterr() do in this test?
AChecks if the output matches expected string
BRuns the test function
CCaptures the printed output from the function
DRaises an error if output is missing
Key Result
Use capsys in pytest to capture and verify printed output easily, ensuring your functions produce the expected console messages.