Skip to content

Autofix non-contextmanager use of pytest.raises & friends #16605

@jakkdl

Description

@jakkdl

Summary

Rule request

pytest-dev/pytest#13241 wants to deprecate the use of the callable form of raises, warns and deprecated_call - i.e.

excinfo = pytest.raises(ValueError, int, "hello")
# should be
with pytest.raises(ValueError) as excinfo:
  int("hello")

but in the rare codebase where it's widely used it will be a massive pain to rewrite it manually, so we don't want to deprecate it until there's a good option for autofixing it. I thought ruff would be a good option for supplying this.

It can optionally also handle match, which requires a separate assert when using the callable form:

excinfo = pytest.raises(ValueError, int, "hello")
assert excinfo.match("^invalid literal")
# to
with pytest.raises(ValueError, match="^invalid literal"):
    int("hello")

Rationale

The context-manager form is more readable, easier to extend, and supports additional kwargs. And is not on the verge of being deprecated

Requested uptream in flake8-pytest: m-burst/flake8-pytest-style#331, but it's mostly the autofix we're interested in

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedContributions especially welcomeruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions