|
1 | 1 | """4XX error classes, which handle exception groups. |
2 | 2 |
|
3 | 3 | ASYNC400 except-star-invalid-attribute checks for invalid attribute access on except* |
| 4 | +ASYNC401 pytest-raises-exception-group checks for pytest.raises(ExceptionGroup) |
4 | 5 | """ |
5 | 6 |
|
6 | 7 | from __future__ import annotations |
|
9 | 10 | from typing import TYPE_CHECKING, Any |
10 | 11 |
|
11 | 12 | from .flake8asyncvisitor import Flake8AsyncVisitor |
12 | | -from .helpers import error_class |
| 13 | +from .helpers import disabled_by_default, error_class |
13 | 14 |
|
14 | 15 | if TYPE_CHECKING: |
15 | 16 | from collections.abc import Mapping |
@@ -96,3 +97,52 @@ def visit_FunctionDef( |
96 | 97 |
|
97 | 98 | visit_AsyncFunctionDef = visit_FunctionDef |
98 | 99 | visit_Lambda = visit_FunctionDef |
| 100 | + |
| 101 | + |
| 102 | +EXCGROUP_QUALNAMES = ( |
| 103 | + "ExceptionGroup", |
| 104 | + "BaseExceptionGroup", |
| 105 | + "builtins.ExceptionGroup", |
| 106 | + "builtins.BaseExceptionGroup", |
| 107 | + "exceptiongroup.ExceptionGroup", |
| 108 | + "exceptiongroup.BaseExceptionGroup", |
| 109 | +) |
| 110 | + |
| 111 | + |
| 112 | +@error_class |
| 113 | +@disabled_by_default |
| 114 | +class Visitor401(Flake8AsyncVisitor): |
| 115 | + error_codes: Mapping[str, str] = { |
| 116 | + "ASYNC401": ( |
| 117 | + "Use `pytest.RaisesGroup` instead of `pytest.raises({})` when expecting" |
| 118 | + " exception groups." |
| 119 | + ) |
| 120 | + } |
| 121 | + |
| 122 | + def _exception_group_name(self, node: ast.expr) -> str | None: |
| 123 | + if isinstance(node, ast.Tuple): |
| 124 | + for elt in node.elts: |
| 125 | + if name := self._exception_group_name(elt): |
| 126 | + return name |
| 127 | + return None |
| 128 | + |
| 129 | + canonical = self.canonical_name(node) |
| 130 | + if canonical in EXCGROUP_QUALNAMES: |
| 131 | + return ast.unparse(node) |
| 132 | + return None |
| 133 | + |
| 134 | + def _expected_exception_arg(self, node: ast.Call) -> ast.expr | None: |
| 135 | + if node.args: |
| 136 | + return node.args[0] |
| 137 | + for kw in node.keywords: |
| 138 | + if kw.arg == "expected_exception": |
| 139 | + return kw.value |
| 140 | + return None |
| 141 | + |
| 142 | + def visit_Call(self, node: ast.Call): |
| 143 | + if ( |
| 144 | + self.canonical_name(node.func) == "pytest.raises" |
| 145 | + and (expected_exception := self._expected_exception_arg(node)) is not None |
| 146 | + and (exception_group := self._exception_group_name(expected_exception)) |
| 147 | + ): |
| 148 | + self.error(node, exception_group) |
0 commit comments