0
0
PyTesttesting~10 mins

Asserting warnings (pytest.warns) - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if a specific warning is raised during the execution of a function. It verifies that the warning message matches the expected text.

Test Code - pytest
PyTest
import warnings
import pytest

def deprecated_function():
    warnings.warn("This function is deprecated", DeprecationWarning)

def test_deprecated_warning():
    with pytest.warns(DeprecationWarning) as record:
        deprecated_function()
    assert len(record) == 1
    assert str(record[0].message) == "This function is deprecated"
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner is ready-PASS
2Calls test_deprecated_warning functionInside test function context-PASS
3Enters pytest.warns context manager expecting DeprecationWarningWarning capture context active-PASS
4Calls deprecated_function which triggers DeprecationWarningWarning emitted and captured in recordWarning of type DeprecationWarning is capturedPASS
5Exits pytest.warns context managerCaptured warnings stored in recordrecord contains exactly one warningPASS
6Asserts warning message text matches expected stringWarning message is 'This function is deprecated'Warning message equals 'This function is deprecated'PASS
7Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: No DeprecationWarning is raised by deprecated_function
Execution Trace Quiz - 3 Questions
Test your understanding
What does pytest.warns check in this test?
AThat no warnings are raised
BThat the function returns a specific value
CThat a DeprecationWarning is raised during the function call
DThat the function raises an exception
Key Result
Use pytest.warns to catch and verify warnings in your code. This helps ensure your code warns users correctly and your tests confirm the warning details.