0
0
PyTesttesting~5 mins

capsys for stdout/stderr in PyTest - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is capsys in pytest?

capsys is a pytest fixture that captures output sent to stdout and stderr during test execution. It allows you to check what your code prints or logs.

Click to reveal answer
beginner
How do you access captured stdout and stderr using capsys?

Use capsys.readouterr() which returns a namedtuple with out (stdout) and err (stderr) strings.

Click to reveal answer
beginner
Why is capturing stdout and stderr useful in tests?

It helps verify that your program prints the correct messages or error logs, similar to checking a receipt after a purchase to confirm details.

Click to reveal answer
beginner
Show a simple pytest test function using capsys to check printed output.
def test_print_message(capsys):
    print('Hello, world!')
    captured = capsys.readouterr()
    assert captured.out == 'Hello, world!\n'
Click to reveal answer
intermediate
What happens if you call capsys.readouterr() multiple times in the same test?

Each call returns the output captured since the last call, then clears the buffer. This lets you check output in parts.

Click to reveal answer
What does capsys.readouterr() return?
AA namedtuple with <code>stdout</code> and <code>stderr</code> output
BOnly the <code>stdout</code> output
COnly the <code>stderr</code> output
DA boolean indicating if output was captured
Why use capsys in pytest tests?
ATo mock database calls
BTo capture and check printed output
CTo speed up test execution
DTo generate test data
If your code prints 'Error!' to stderr, how do you check it with capsys?
AUse <code>assert False</code>
BCheck <code>captured.out</code> after <code>capsys.readouterr()</code>
CUse <code>print()</code> in the test
DCheck <code>captured.err</code> after <code>capsys.readouterr()</code>
What happens if you forget to call capsys.readouterr() in your test?
AOutput is printed to the console
BThe test will fail automatically
CYou cannot access the captured output
DThe test runs faster
Can capsys capture output from functions called inside your test?
AYes, it captures all output during the test
BNo, only output from the test function itself
COnly output from imported modules
DOnly output from print statements in the test
Explain how to use capsys in a pytest test to verify printed output.
Think about how you capture and check what your code prints.
You got /4 concepts.
    Describe the difference between stdout and stderr and how capsys helps test both.
    Consider normal messages vs error messages.
    You got /4 concepts.