Bird
0
0

You want to test a function that may raise either DeprecationWarning or UserWarning. How can you assert that exactly one warning of either type is raised during the test?

hard📝 framework Q15 of 15
PyTest - Writing Assertions
You want to test a function that may raise either DeprecationWarning or UserWarning. How can you assert that exactly one warning of either type is raised during the test?
AUse two separate with blocks for each warning type and assert one warning each
BUse a single with block with pytest.warns(Warning) and check the warning type inside
CUse pytest.warns with a tuple of warning types and assert one warning caught
DUse pytest.warns without specifying warning type and count warnings
Step-by-Step Solution
Solution:
  1. Step 1: Understand pytest.warns supports multiple warning types

    pytest.warns can accept a tuple of warning classes to catch any of those types.
  2. Step 2: Use tuple to catch either DeprecationWarning or UserWarning

    Using pytest.warns((DeprecationWarning, UserWarning)) catches either warning type in one block.
  3. Step 3: Assert exactly one warning was caught

    Inside the block, assert that one warning was raised to ensure test precision.
  4. Final Answer:

    Use pytest.warns with a tuple of warning types and assert one warning caught -> Option C
  5. Quick Check:

    Tuple of warnings in pytest.warns = D [OK]
Quick Trick: Pass tuple of warnings to pytest.warns to catch multiple types [OK]
Common Mistakes:
MISTAKES
  • Using multiple with blocks causing multiple warnings
  • Not specifying warning types and catching unrelated warnings
  • Assuming pytest.warns accepts multiple calls in one block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes