Skip to content

Commit 0f044f8

Browse files
authored
REF: "bare_pytest_raises" to use the ast module (#32932)
1 parent 5b39709 commit 0f044f8

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

scripts/validate_unwanted_patterns.py

+23-11
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
"""
1212

1313
import argparse
14+
import ast
1415
import os
1516
import sys
1617
import token
@@ -83,23 +84,34 @@ def bare_pytest_raises(file_obj: IO[str]) -> Iterable[Tuple[int, str]]:
8384
-----
8485
GH #23922
8586
"""
86-
tokens: List = list(tokenize.generate_tokens(file_obj.readline))
87+
contents = file_obj.read()
88+
tree = ast.parse(contents)
89+
90+
for node in ast.walk(tree):
91+
if not isinstance(node, ast.Call):
92+
continue
8793

88-
for counter, current_token in enumerate(tokens, start=1):
89-
if not (current_token.type == token.NAME and current_token.string == "raises"):
94+
try:
95+
if not (node.func.value.id == "pytest" and node.func.attr == "raises"):
96+
continue
97+
except AttributeError:
9098
continue
91-
for next_token in tokens[counter:]:
92-
if next_token.type == token.NAME and next_token.string == "match":
93-
break
94-
# token.NEWLINE refers to the end of a logical line
95-
# unlike token.NL or "\n" which represents a newline
96-
if next_token.type == token.NEWLINE:
99+
100+
if not node.keywords:
101+
yield (
102+
node.lineno,
103+
"Bare pytests raise have been found. "
104+
"Please pass in the argument 'match' as well the exception.",
105+
)
106+
else:
107+
# Means that there are arguments that are being passed in,
108+
# now we validate that `match` is one of the passed in arguments
109+
if not any(keyword.arg == "match" for keyword in node.keywords):
97110
yield (
98-
current_token.start[0],
111+
node.lineno,
99112
"Bare pytests raise have been found. "
100113
"Please pass in the argument 'match' as well the exception.",
101114
)
102-
break
103115

104116

105117
def strings_to_concatenate(file_obj: IO[str]) -> Iterable[Tuple[int, str]]:

0 commit comments

Comments
 (0)