Skip to content

Latest commit

 

History

History
41 lines (29 loc) · 820 Bytes

PT012.md

File metadata and controls

41 lines (29 loc) · 820 Bytes

PT012

pytest.raises() block should contain a single simple statement

This forbids multiple statements and control flow structures within pytest.raises() blocks.

Examples

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()

Rationale

  • 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)