0
0
PyTesttesting~5 mins

capsys for capturing output 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 helps you check what your code prints.

Click to reveal answer
beginner
How do you access captured output using capsys?

Use capsys.readouterr() which returns a namedtuple with out (standard output) and err (standard error) strings.

Click to reveal answer
beginner
Why is capturing output useful in testing?

It lets you verify that your program prints the correct messages, like logs or errors, without showing them on the screen during tests.

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

Each call returns the output captured since the last call and clears the buffer. So, output is reset after reading.

Click to reveal answer
What does capsys.readouterr() return?
AA namedtuple with <code>out</code> and <code>err</code> strings
BOnly the standard output string
COnly the standard error string
DA boolean indicating if output was captured
Which pytest fixture is used to capture printed output?
Acapout
Bstdout
Ccapsys
Dcapture
If your code prints 'Hi' and you want to test it, what assertion checks the output correctly?
Aassert captured.out == 'Hi'
Bassert captured.out == 'Hi\n'
Cassert captured.err == 'Hi\n'
Dassert captured.out == 'hi\n'
What happens to the captured output after calling capsys.readouterr()?
AIt remains unchanged
BIt is saved to a file
CIt doubles
DIt is cleared/reset
Which output streams does capsys capture?
ABoth standard output and standard error
BOnly standard error
COnly standard output
DNeither
Explain how to use capsys in a pytest test to verify printed output.
Think about how you capture and check what print shows.
You got /4 concepts.
    Why is it important to include the newline character when asserting printed output captured by capsys?
    Remember how print behaves in Python.
    You got /3 concepts.