Bird
0
0

What will be the result of this pytest code snippet?

medium📝 Predict Output Q13 of 15
PyTest - Writing Assertions
What will be the result of this pytest code snippet?
import warnings
import pytest

def func():
    warnings.warn('Deprecated feature', DeprecationWarning)

def test_func():
    with pytest.warns(DeprecationWarning) as record:
        func()
    assert len(record) == 1
    assert record[0].message.args[0] == 'Deprecated feature'
ATest fails because no warning is raised
BTest passes because the warning is correctly caught and message matches
CTest fails due to wrong warning type
DTest raises an exception because record is not iterable
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the warning raised by func()

    The function func() raises a DeprecationWarning with message 'Deprecated feature'.
  2. Step 2: Check pytest.warns usage and assertions

    The test uses pytest.warns to catch DeprecationWarning and stores it in record. It asserts one warning was caught and the message matches exactly.
  3. Final Answer:

    Test passes because the warning is correctly caught and message matches -> Option B
  4. Quick Check:

    Warning caught and message correct = A [OK]
Quick Trick: Check warning type and message inside pytest.warns block [OK]
Common Mistakes:
MISTAKES
  • Assuming warnings.warn does not raise warnings
  • Confusing warning types
  • Not using 'as record' to capture warnings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes