m-burst / flake8-pytest-style

A flake8 plugin checking common style issues or inconsistencies with pytest-based tests.
MIT License
230 stars 16 forks source link

I want a rule that will check for `pytest.warns` contexts with multiple statements #317

Open tjkuson opened 1 week ago

tjkuson commented 1 week ago

Rule request

This would be analogous to PT012 which checks for pytest.raises contexts with multiple statements. If accepted, I volunteer to implement the check.

Description (adapted from the PT012 documentation)

Bad code:

import pytest

def test_foo():
    with pytest.warns(UserWarning):
        obj = get_object()
        obj.do_something()

    with pytest.warns(UserWarning):
        if some_condition:
            do_something()

Good code:

import pytest

def test_foo():
    obj = get_object()
    with pytest.warns(UserWarning):
        obj.do_something()

An empty with-statement (containing only a pass inside) is allowed 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.warns(UserWarning):
        with context_manager:
            pass

Rationale

snowdrop4 commented 4 days ago

This lint makes a lot of sense.

There could also be pytest.warns versions of PT010 and PT011 (not just PT012), since they are all analagous.