Complete the code to assert that a warning is raised.
import warnings import pytest def test_warning(): with pytest.warns([1]): warnings.warn("This is a warning", UserWarning)
pytest.warns() context manager.The pytest.warns() context manager expects the warning class to check. Here, UserWarning matches the warning raised.
Complete the code to capture the warning message text.
import warnings import pytest def test_warning_message(): with pytest.warns(UserWarning) as record: warnings.warn("Check this warning", UserWarning) assert record[0].message.args[[1]] == "Check this warning"
message attribute directly instead of args.The warning message is stored as the first argument in args, so index 0 is correct.
Fix the error in the code to correctly assert a warning is raised.
import warnings import pytest def test_warn(): with pytest.warns([1]): warnings.warn("Deprecated", DeprecationWarning)
The warning raised is DeprecationWarning, so pytest.warns() must check for the same type.
Fill both blanks to assert a warning and check its message.
import warnings import pytest def test_warn_message(): with pytest.warns([1]) as record: warnings.warn("Be careful", UserWarning) assert str(record[0].message) [2] "Be careful"
pytest.warns().!= instead of == in the assertion.The warning type is UserWarning. The assertion checks if the message string equals "Be careful" using ==.
Fill all three blanks to assert a warning, capture it, and check the message content.
import warnings import pytest def test_warning_content(): with pytest.warns([1]) as record: warnings.warn("Use new API", [2]) assert record[0].message.args[0] [3] "Use new API"
pytest.warns() and warnings.warn().The warning raised is DeprecationWarning, so both pytest.warns() and warnings.warn() use it. The assertion checks equality with ==.