Skip to content

Latest commit

 

History

History
53 lines (39 loc) · 1.12 KB

File metadata and controls

53 lines (39 loc) · 1.12 KB

PT031

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

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

Examples

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

Rationale

  • to help ensure that only the expected warning from code under test is caught in a pytest.warns block (e.g. not an warning from initialization/finalization code)