0
0
PyTesttesting~10 mins

capfd for file descriptors in PyTest - Interactive Code Practice

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

Complete the code to capture printed output using capfd fixture.

PyTest
def test_print_output([1]):
    print("Hello, world!")
    out, err = capfd.readouterr()
    assert out == "Hello, world!\n"
Drag options to blanks, or click blank then click option'
Acapfd
Btmp_path
Cmonkeypatch
Dcapsys
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'capsys' instead of 'capfd' when file descriptor capture is needed.
Forgetting to include the fixture as a function argument.
2fill in blank
medium

Complete the code to capture and check stderr output using capfd.

PyTest
def test_error_output(capfd):
    import sys
    print("Error message", file=[1])
    out, err = capfd.readouterr()
    assert err == "Error message\n"
Drag options to blanks, or click blank then click option'
Asys.stdout
Bsys.__stderr__
Csys.stdin
Dsys.stderr
Attempts:
3 left
💡 Hint
Common Mistakes
Printing to sys.stdout instead of sys.stderr.
Confusing sys.stdin with output streams.
3fill in blank
hard

Fix the error in the code to correctly capture output using capfd.

PyTest
def test_output([1]):
    print("Test")
    out, err = capfd.readouterr()
    assert out == "Test\n"
Drag options to blanks, or click blank then click option'
Acapsys
Bcaplog
Ccapfd
Dtmp_path
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'capsys' instead of 'capfd' when file descriptor capture is required.
Not including the fixture argument at all.
4fill in blank
hard

Fill both blanks to capture output and check it after printing.

PyTest
def test_multiple_prints([1]):
    print("First line")
    print("Second line")
    out, err = [2].readouterr()
    assert out == "First line\nSecond line\n"
Drag options to blanks, or click blank then click option'
Acapfd
Bcapsys
Ccaplog
Dtmp_path
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing different fixtures like capsys and capfd.
Using caplog which is for logging, not output capture.
5fill in blank
hard

Fill all three blanks to capture output, print error, and assert both outputs.

PyTest
def test_output_and_error([1]):
    print("Output line")
    import sys
    print("Error line", file=sys.stderr)
    out, err = [2].readouterr()
    assert out == "Output line\n"
    assert err == [3]
Drag options to blanks, or click blank then click option'
Acapfd
Bcapsys
C"Error line\n"
D"Output line\n"
Attempts:
3 left
💡 Hint
Common Mistakes
Using capsys instead of capfd when file descriptor capture is needed.
Forgetting the newline character in the error string assertion.