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