Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to capture standard output using capsys in pytest.
PyTest
def test_print_output(capsys): print("Hello, world!") captured = capsys.[1]() assert captured.out == "Hello, world!\n"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent method like capture() or getoutput()
Trying to access capsys.out directly without calling a method
✗ Incorrect
The capsys fixture provides the method readouterr() to capture stdout and stderr output.
2fill in blank
mediumComplete the code to capture standard error output using capsys in pytest.
PyTest
def test_error_output(capsys): import sys print("Error message", file=sys.stderr) captured = capsys.[1]() assert captured.err == "Error message\n"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use a method that only captures stdout
Using a method name that does not exist in capsys
✗ Incorrect
The readouterr() method captures both stdout and stderr; captured.err contains the stderr output.
3fill in blank
hardFix the error in the code to correctly capture and assert printed output using capsys.
PyTest
def test_output(capsys): print("Test output") captured = capsys.[1]() assert captured.out == "Test output\n"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the newline character in the assertion
Using a wrong method to capture output
✗ Incorrect
The captured output includes a newline, so the assertion must match the exact string including '\n'.
4fill in blank
hardFill both blanks to capture output and check that stderr is empty.
PyTest
def test_stdout_only(capsys): print("Only stdout") captured = capsys.[1]() assert captured.out == "Only stdout\n" assert captured.[2] == ""
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking captured.out instead of captured.err for stderr
Using a non-existent method to capture output
✗ Incorrect
Use readouterr() to capture both outputs, then check captured.err for empty stderr.
5fill in blank
hardFill all three blanks to capture output, check stdout, and check stderr after printing to both.
PyTest
def test_both_outputs(capsys): import sys print("Output message") print("Error message", file=sys.stderr) captured = capsys.[1]() assert captured.[2] == "Output message\n" assert captured.[3] == "Error message\n"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up captured.out and captured.err
Using a wrong method name to capture output
✗ Incorrect
readouterr() captures both outputs; captured.out holds stdout, captured.err holds stderr.