Skip to content

pytest-raises-exception-group (ASYNC401)

Preview (since 0.17.5) · Category: pedantic · Related issues · View source

Derived from the flake8-async linter.

This rule is unstable and in preview. The --preview flag is required for use.

What it does

Checks for ExceptionGroup or BaseExceptionGroup passed as the expected exception to pytest.raises, pytest.RaisesExc, or pytest.mark.xfail, or as a nested group to pytest.RaisesGroup.

Why is this bad?

pytest.raises(ExceptionGroup) checks the group's type, but not the types or number of exceptions it contains. A test can therefore pass even if the group contains unexpected exceptions. Passing a group type to pytest.RaisesGroup has the same problem for the nested group.

In pytest 8.4.0 and later, use pytest.RaisesGroup to specify the expected exceptions and any nested groups.

Example

import pytest

with pytest.raises(ExceptionGroup):
    raise ExceptionGroup("errors", [ValueError()])

Use instead:

import pytest

with pytest.RaisesGroup(ValueError):
    raise ExceptionGroup("errors", [ValueError()])

Known problems

pytest.RaisesGroup requires an exact number of expected exceptions. Tests that allow an unspecified number can instead use pytest.raises and validate the group's contents with a check callback or subsequent assertions. This rule also reports those calls.

This rule does not check which version of pytest a project uses, so it also reports calls in projects that use a version of pytest older than 8.4.0, where pytest.RaisesGroup is not available.

References