0
0
PyTesttesting~10 mins

Asserting warnings (pytest.warns) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to assert that a warning is raised.

PyTest
import warnings
import pytest

def test_warning():
    with pytest.warns([1]):
        warnings.warn("This is a warning", UserWarning)
Drag options to blanks, or click blank then click option'
AUserWarning
BRuntimeWarning
CDeprecationWarning
DWarning
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different warning type than the one raised causes the test to fail.
Not using pytest.warns() context manager.
2fill in blank
medium

Complete the code to capture the warning message text.

PyTest
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"
Drag options to blanks, or click blank then click option'
A2
B0
C1
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using index 1 or 2 which are out of range and cause errors.
Trying to access message attribute directly instead of args.
3fill in blank
hard

Fix the error in the code to correctly assert a warning is raised.

PyTest
import warnings
import pytest

def test_warn():
    with pytest.warns([1]):
        warnings.warn("Deprecated", DeprecationWarning)
Drag options to blanks, or click blank then click option'
ADeprecationWarning
BUserWarning
CRuntimeWarning
DWarning
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different warning type causes the test to fail.
Not using a warning class but a string or variable.
4fill in blank
hard

Fill both blanks to assert a warning and check its message.

PyTest
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"
Drag options to blanks, or click blank then click option'
AUserWarning
BDeprecationWarning
C==
D!=
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong warning type in pytest.warns().
Using != instead of == in the assertion.
5fill in blank
hard

Fill all three blanks to assert a warning, capture it, and check the message content.

PyTest
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"
Drag options to blanks, or click blank then click option'
AUserWarning
BDeprecationWarning
C==
DRuntimeWarning
Attempts:
3 left
💡 Hint
Common Mistakes
Using different warning types in pytest.warns() and warnings.warn().
Using wrong comparison operators in the assertion.