Bird
0
0

How can you capture the exception message text when using pytest.raises?

hard🚀 Application Q8 of 15
PyTest - Writing Assertions
How can you capture the exception message text when using pytest.raises?
AUse <code>pytest.raises(Exception, message=True)</code>
BUse <code>with pytest.raises(Exception) as exc_info:</code> and access <code>exc_info.value</code>
CUse <code>with pytest.raises(Exception, message)</code>
DException messages cannot be captured with pytest.raises
Step-by-Step Solution
Solution:
  1. Step 1: Recall pytest.raises context manager usage

    pytest.raises can be used with 'as' to capture exception info object.
  2. Step 2: Access exception message

    exc_info.value contains the exception instance; str(exc_info.value) gives the message.
  3. Final Answer:

    Use with pytest.raises(Exception) as exc_info: and access exc_info.value -> Option B
  4. Quick Check:

    Capture exception message = use 'as' to get exc_info [OK]
Quick Trick: Use 'as exc_info' to get exception object and message [OK]
Common Mistakes:
MISTAKES
  • Trying to pass message=True argument
  • Using incorrect syntax with pytest.raises
  • Believing exception messages can't be accessed

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes