A. The assertion misses the newline character at the end of output.
B. capsys fixture is not passed to the test function.
C. The function say_hi() does not print anything.
D. capsys.readouterr() should be called before say_hi().
Solution
Step 1: Understand print output format
print('Hi!') outputs 'Hi!' plus a newline character '\n' at the end.
Step 2: Check assertion string against captured output
The assertion compares captured.out to 'Hi!' without the newline, causing it to fail.
Final Answer:
The assertion misses the newline character at the end of output. -> Option A
Quick Check:
Print adds newline; assertion must include it [OK]
Hint: Always include newline in output assertions [OK]
Common Mistakes:
Ignoring newline added by print
Calling capsys.readouterr() too early
Not passing capsys fixture to test
5. You want to test a function that prints different messages based on input. Which pytest approach best validates its behavior using output capture?
def respond(answer):
if answer == 'yes':
print('Confirmed')
else:
print('Denied')
hard
A. Replace print statements with return statements and assert return values without output capture.
B. Call respond('yes') and respond('no') without capturing output, then assert return values.
C. Use capsys to capture output once after both calls, then assert combined output equals 'ConfirmedDenied'.
D. Call respond('yes'), capture output with capsys, assert output is 'Confirmed\n', then repeat for 'no' with 'Denied\n'.
Solution
Step 1: Understand output capture per call
Each call to respond prints a message; capturing output after each call separately lets us check exact printed text.
Step 2: Validate output for each input
Calling respond('yes') should print 'Confirmed\n', and respond('no') should print 'Denied\n'. Separate captures and assertions confirm correct behavior.
Final Answer:
Call respond('yes'), capture output with capsys, assert output is 'Confirmed\n', then repeat for 'no' with 'Denied\n'. -> Option D
Quick Check:
Separate capture/assert per call = correct validation [OK]
Hint: Capture output separately for each function call [OK]
Common Mistakes:
Capturing output once for multiple calls
Asserting combined output without newlines
Ignoring output capture and checking return values
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.