Bird
0
0

Which pytest code correctly asserts this behavior and checks the error message?

hard📝 framework Q15 of 15
PyTest - Writing Assertions
You want to test a function parse_int(s) that should raise ValueError with message containing 'invalid literal' when given a non-integer string. Which pytest code correctly asserts this behavior and checks the error message?
Awith pytest.raises(ValueError): parse_int('abc') assert 'invalid literal' in e.value
Bpytest.raises(ValueError, parse_int('abc')) assert 'invalid literal' in e.value
Cwith pytest.raises(ValueError) as e: parse_int('abc') assert 'invalid literal' in str(e.value)
Dwith pytest.raises('ValueError') as e: parse_int('abc') assert 'invalid literal' in str(e.value)
Step-by-Step Solution
Solution:
  1. Step 1: Use correct syntax to capture exception info

    Use with pytest.raises(ValueError) as e: to catch the exception and store info in e.
  2. Step 2: Check error message properly

    After the block, check if the string 'invalid literal' is in str(e.value). This converts the exception to string for message checking.
  3. Step 3: Eliminate incorrect options

    with pytest.raises(ValueError): parse_int('abc') assert 'invalid literal' in e.value tries to use e outside the block without capturing it. pytest.raises(ValueError, parse_int('abc')) assert 'invalid literal' in e.value calls the function inside pytest.raises incorrectly and uses e undefined. with pytest.raises('ValueError') as e: parse_int('abc') assert 'invalid literal' in str(e.value) uses exception name as string instead of class.
  4. Final Answer:

    with pytest.raises(ValueError) as e: parse_int('abc') assert 'invalid literal' in str(e.value) -> Option C
  5. Quick Check:

    Capture exception with 'as' and check message string [OK]
Quick Trick: Use 'as' to capture exception and check message with str(e.value) [OK]
Common Mistakes:
MISTAKES
  • Using exception name as string instead of class
  • Calling function inside pytest.raises arguments
  • Accessing exception info outside 'with' without 'as'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes