Bird
Raised Fist0
PyTesttesting~20 mins

capsys for capturing output in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Capsys Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output captured by capsys?
Consider this pytest test function using capsys to capture printed output. What will be the value of captured.out after the test runs?
PyTest
def test_print_output(capsys):
    print('Hello, world!')
    captured = capsys.readouterr()
    assert captured.out == 'Hello, world!\n'
A'Hello, world!\n'
B'Hello, world!'
C''
D'hello, world!\n'
Attempts:
2 left
💡 Hint
Remember that print adds a newline character at the end.
❓ assertion
intermediate
2:00remaining
Which assertion correctly checks captured stderr output?
Given this test code snippet, which assertion correctly verifies that the error message 'Error occurred' was printed to standard error?
PyTest
def test_error_output(capsys):
    import sys
    print('Error occurred', file=sys.stderr)
    captured = capsys.readouterr()
Aassert captured.err == 'Error occurred\n'
Bassert captured.out == 'Error occurred\n'
Cassert 'Error occurred' in captured.out
Dassert captured.err == 'error occurred\n'
Attempts:
2 left
💡 Hint
Standard error output is captured in captured.err, not captured.out.
🔧 Debug
advanced
2:00remaining
Why does this test fail to capture output?
This test tries to capture printed output but fails. What is the reason?
PyTest
def test_no_capture(capsys):
    captured = capsys.readouterr()
    print('Test output')
    assert captured.out == 'Test output\n'
Acapsys.readouterr() clears output after reading, so print is lost
Bprint does not output anything to capture
Ccaptured is read before print, so it captures nothing
Dassertion syntax is incorrect
Attempts:
2 left
💡 Hint
Think about when capsys.readouterr() is called relative to print.
❓ framework
advanced
2:00remaining
How to capture output from a function called multiple times?
You want to test a function that prints output multiple times. How do you capture all output using capsys?
PyTest
def greet():
    print('Hello')
    print('World')

def test_greet(capsys):
    greet()
    captured = capsys.readouterr()
ACall capsys.readouterr() before greet() to capture output
BUse capsys.readouterr() only once before test starts
CCall capsys.readouterr() after each print inside greet()
DCall capsys.readouterr() after all prints to capture combined output
Attempts:
2 left
💡 Hint
capsys accumulates output until readouterr() is called.
🧠 Conceptual
expert
2:00remaining
What happens if you call capsys.readouterr() multiple times?
In a pytest test, what is the effect of calling capsys.readouterr() multiple times during the test?
AOnly the first call returns output; others return empty strings
BEach call returns output since last call and clears the buffer
CCalling multiple times causes an error
DEach call returns all output from test start without clearing
Attempts:
2 left
💡 Hint
Think of capsys.readouterr() like reading and emptying a mailbox.

Practice

(1/5)
1. What is the main purpose of using capsys in pytest tests?
easy
A. To generate test reports with screenshots
B. To speed up test execution by skipping print statements
C. To automatically fix syntax errors in print statements
D. To capture and check printed output during test execution

Solution

  1. Step 1: Understand capsys role in pytest

    capsys is a pytest feature that captures output sent to stdout and stderr during tests.
  2. Step 2: Identify what capsys helps verify

    It helps verify printed messages, ensuring the program outputs expected text.
  3. Final Answer:

    To capture and check printed output during test execution -> Option D
  4. Quick Check:

    capsys captures output = A [OK]
Hint: Remember: capsys catches print output for checking [OK]
Common Mistakes:
  • Thinking capsys speeds up tests
  • Believing capsys fixes code errors
  • Confusing capsys with report generation
2. Which of the following is the correct way to capture output using capsys in a pytest test function?
easy
A. output = capsys.readouterr()
B. output = capsys.capture()
C. output = capsys.getoutput()
D. output = capsys.print()

Solution

  1. Step 1: Recall capsys method to get output

    The correct method to retrieve captured output is capsys.readouterr().
  2. Step 2: Check other options for correctness

    Other methods like capture(), getoutput(), or print() do not exist on capsys.
  3. Final Answer:

    output = capsys.readouterr() -> Option A
  4. Quick Check:

    capsys.readouterr() reads output = B [OK]
Hint: Use readouterr() to get captured stdout and stderr [OK]
Common Mistakes:
  • Using non-existent capsys methods
  • Trying to capture output without readouterr()
  • Confusing capsys with other pytest fixtures
3. What will be the output of the following pytest test using capsys?
def greet():
    print('Hello, Tester!')

def test_greet(capsys):
    greet()
    captured = capsys.readouterr()
    assert captured.out == 'Hello, Tester!\n'
medium
A. Test passes because output matches exactly
B. Test fails because captured.out is empty
C. Test fails due to missing newline in assertion
D. Test raises an exception due to wrong capsys usage

Solution

  1. Step 1: Understand what greet() prints

    The function prints 'Hello, Tester!' followed by a newline.
  2. Step 2: Check assertion against captured output

    capsys.readouterr() captures stdout including newline, so captured.out equals 'Hello, Tester!\n'.
  3. Final Answer:

    Test passes because output matches exactly -> Option A
  4. Quick Check:

    captured.out == 'Hello, Tester!\n' = C [OK]
Hint: Remember print adds newline, so include \n in assertion [OK]
Common Mistakes:
  • Forgetting newline in expected output
  • Assuming captured.out excludes newlines
  • Misusing capsys.readouterr() causing errors
4. Identify the error in this pytest test using capsys:
def test_error(capsys):
    print('Start')
    captured = capsys.readouterr
    assert captured.out == 'Start\n'
medium
A. capsys fixture is not passed as argument
B. Incorrect assertion comparing to 'Start' without newline
C. Missing parentheses when calling capsys.readouterr
D. print statement should be inside a function

Solution

  1. Step 1: Check how capsys.readouterr is used

    capsys.readouterr is a method and must be called with parentheses: capsys.readouterr()
  2. Step 2: Verify assertion and other code parts

    The assertion correctly expects 'Start\n', print is inside the test function, and capsys is passed as argument.
  3. Final Answer:

    Missing parentheses when calling capsys.readouterr -> Option C
  4. Quick Check:

    Method call needs () = D [OK]
Hint: Always call readouterr() with parentheses [OK]
Common Mistakes:
  • Forgetting () after readouterr
  • Ignoring newline in output assertion
  • Not passing capsys fixture to test
5. You want to test a function that prints multiple lines and errors. How do you use capsys to verify both stdout and stderr outputs correctly?
hard
A. Call capsys.readouterr() twice, once for stdout and once for stderr separately
B. Call capsys.readouterr() once and check both captured.out and captured.err
C. Use capsys.readouterr() only for stdout and ignore stderr
D. Use print statements to manually check outputs instead of capsys

Solution

  1. Step 1: Understand capsys.readouterr() output

    It returns a namedtuple with two attributes: out (stdout) and err (stderr).
  2. Step 2: Verify how to check both outputs

    Calling readouterr() once captures both streams; check captured.out and captured.err separately.
  3. Final Answer:

    Call capsys.readouterr() once and check both captured.out and captured.err -> Option B
  4. Quick Check:

    One readouterr() call captures both streams = A [OK]
Hint: One readouterr() call captures stdout and stderr together [OK]
Common Mistakes:
  • Calling readouterr() multiple times expecting separate streams
  • Ignoring stderr output in tests
  • Using print instead of capsys for output verification
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard