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.
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.
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"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner is ready | — | PASS |
| 2 | Calls test_deprecated_warning function | Inside test function context | — | PASS |
| 3 | Enters pytest.warns context manager expecting DeprecationWarning | Warning capture context active | — | PASS |
| 4 | Calls deprecated_function which triggers DeprecationWarning | Warning emitted and captured in record | Warning of type DeprecationWarning is captured | PASS |
| 5 | Exits pytest.warns context manager | Captured warnings stored in record | record contains exactly one warning | PASS |
| 6 | Asserts warning message text matches expected string | Warning message is 'This function is deprecated' | Warning message equals 'This function is deprecated' | PASS |
| 7 | Test ends successfully | All assertions passed | — | PASS |
pytest.warns in a test?UserWarning using pytest?with to catch warnings during code execution.with pytest.warns(UserWarning): followed by the code that triggers the warning.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'import warnings
import pytest
def test_warning():
with pytest.warns(UserWarning):
warnings.warn('Be careful!')
assert pytest.warns(UserWarning)DeprecationWarning or UserWarning. How can you assert that exactly one warning of either type is raised during the test?pytest.warns((DeprecationWarning, UserWarning)) catches either warning type in one block.Pass the test and this pattern moves unknown