0
0
PyTesttesting~15 mins

Asserting warnings (pytest.warns) - Build an Automation Script

Choose your learning style9 modes available
Verify that a warning is raised when calling deprecated_function
Preconditions (2)
Step 1: Import deprecated_function from the module
Step 2: Call deprecated_function inside a pytest.warns context manager for DeprecationWarning
Step 3: Capture the warning message
Step 4: Assert that the warning message contains the expected text 'deprecated'
✅ Expected Result: The test passes if a DeprecationWarning is raised and the warning message contains 'deprecated'
Automation Requirements - pytest
Assertions Needed:
Assert that DeprecationWarning is raised
Assert that warning message contains expected text
Best Practices:
Use pytest.warns context manager to catch warnings
Check warning message content for accuracy
Keep test code simple and readable
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Not using pytest.warns context manager and instead using try-except
Not asserting the warning message content
Catching the wrong warning type or no warning type specified
Bonus Challenge

Now add data-driven testing to check multiple functions that raise different warnings

Show Hint