Bird
0
0

What is wrong with this test code?

medium📝 Debug Q6 of 15
PyTest - Writing Assertions
What is wrong with this test code?
import pytest
def test_attribute_error():
    with pytest.raises(AttributeError):
        obj = None
    obj.method()
AThe test will always pass regardless of exceptions
Bpytest.raises cannot be used to catch AttributeError
CThe variable <code>obj</code> is not defined
DThe call to <code>obj.method()</code> is outside the pytest.raises block and will raise an unhandled exception
Step-by-Step Solution
Solution:
  1. Step 1: Identify the exception raising code

    The call obj.method() will raise an AttributeError because obj is None.
  2. Step 2: Check the context manager scope

    This call is outside the with pytest.raises(AttributeError): block, so the exception is not caught by pytest.raises.
  3. Step 3: Consequence

    The test will error instead of passing because the exception is unhandled.
  4. Final Answer:

    The call to obj.method() is outside the pytest.raises block and will raise an unhandled exception -> Option D
  5. Quick Check:

    Is the exception raising code inside pytest.raises? [OK]
Quick Trick: Exception must be inside pytest.raises block to be caught [OK]
Common Mistakes:
MISTAKES
  • Placing exception raising code outside pytest.raises
  • Assuming pytest.raises catches exceptions globally
  • Misunderstanding scope of context manager

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes