Verify that a warning is raised when calling deprecated_function
Preconditions (2)
✅ Expected Result: The test passes if a DeprecationWarning is raised and the warning message contains 'deprecated'
import pytest # Example deprecated function def deprecated_function(): import warnings warnings.warn('This function is deprecated', DeprecationWarning) def test_deprecated_function_warns(): with pytest.warns(DeprecationWarning) as record: deprecated_function() # Assert that exactly one warning was raised assert len(record) == 1 # Assert warning message contains 'deprecated' assert 'deprecated' in str(record[0].message)
The test imports pytest and defines a sample deprecated_function that raises a DeprecationWarning.
The test function test_deprecated_function_warns uses pytest.warns as a context manager to catch warnings of type DeprecationWarning.
Inside the context, it calls the deprecated function.
After the call, it asserts that exactly one warning was caught and that the warning message contains the word 'deprecated'.
This ensures the warning is properly raised and the message is as expected.
Now add data-driven testing to check multiple functions that raise different warnings
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