pytest.warns() block should contain a single simple statement
This forbids multiple statements and control flow structures within
pytest.warns() blocks.
Bad code:
import pytest
def test_foo():
with pytest.warns(MyWarning):
# if get_object() raises MyWarning, the test is incorrect
obj = get_object()
obj.do_something()
with pytest.warns(MyWarning):
if some_condition:
do_something()Good code:
import pytest
def test_foo():
obj = get_object()
with pytest.warns(MyWarning):
obj.do_something()An empty with-statement (containing only a pass inside) is allowed
in order to allow testing of warnings raised by context manager enter/exit methods.
import pytest
def test_my_context_manager():
context_manager = get_context_manager()
with pytest.warns(MyWarning):
with context_manager:
pass- to help ensure that only the expected warning from code under test is
caught in a
pytest.warnsblock (e.g. not an warning from initialization/finalization code)