0
0
PyTesttesting~10 mins

Why capturing output validates behavior in PyTest - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to capture printed output in a pytest test function.

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'
Areadouterr
Bcapture
Cgetoutput
Dread
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent method like capsys.capture()
Trying to read output without calling a method
2fill in blank
medium

Complete the assertion to check that the captured output contains the expected substring.

PyTest
def test_partial_output(capsys):
    print('Test output for pytest')
    captured = capsys.readouterr()
    assert [1] in captured.out
Drag options to blanks, or click blank then click option'
A'pytest'
Bcaptured.out
C'output'
D'fail'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for a string not present in the output
Using the whole output instead of a substring
3fill in blank
hard

Fix the error in the test code to correctly capture and assert printed output.

PyTest
def test_error_output(capsys):
    print('Error occurred')
    captured = capsys.[1]()
    assert captured.err == ''
Drag options to blanks, or click blank then click option'
Areadouterror
Breadouterr
Creadoutput
Dcapture
Attempts:
3 left
💡 Hint
Common Mistakes
Misspelling the method name
Using a method that does not exist
4fill in blank
hard

Fill both blanks to capture output and assert it matches the expected string.

PyTest
def test_output_match(capsys):
    print('Success!')
    captured = capsys.[1]()
    assert captured.[2] == 'Success!\n'
Drag options to blanks, or click blank then click option'
Areadouterr
Bout
Cerr
Dcapture
Attempts:
3 left
💡 Hint
Common Mistakes
Checking captured.err instead of captured.out
Using a wrong method name for capturing
5fill in blank
hard

Fill all three blanks to capture output, strip whitespace, and assert the exact message.

PyTest
def test_strip_output(capsys):
    print('  Trim me  ')
    captured = capsys.[1]()
    output = captured.[2].[3]()
    assert output == 'Trim me'
Drag options to blanks, or click blank then click option'
Areadouterr
Bout
Cstrip
Drstrip
Attempts:
3 left
💡 Hint
Common Mistakes
Using rstrip() which only removes trailing spaces
Forgetting to call the method with parentheses