Skip to content

Commit 364282e

Browse files
tybugnedbat
andauthored
fix: catch TokenError on parse (#1788)
* catch TokenError on parse * typo, use env.PYVERSION * Update tests/test_parser.py --------- Co-authored-by: Ned Batchelder <ned@nedbatchelder.com>
1 parent 81089de commit 364282e

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

coverage/parser.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -263,10 +263,14 @@ def parse_source(self) -> None:
263263
try:
264264
self._ast_root = ast.parse(self.text)
265265
self._raw_parse()
266-
except (IndentationError, SyntaxError) as err:
266+
except (tokenize.TokenError, IndentationError, SyntaxError) as err:
267+
if hasattr(err, "lineno"):
268+
lineno = err.lineno # IndentationError
269+
else:
270+
lineno = err.args[1][0] # TokenError
267271
raise NotPython(
268272
f"Couldn't parse '{self.filename}' as Python source: " +
269-
f"{err.args[0]!r} at line {err.lineno}",
273+
f"{err.args[0]!r} at line {lineno}",
270274
) from err
271275

272276
ignore = self.excluded | self.raw_docstrings

tests/test_parser.py

+8
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,14 @@ def foo():
128128
pytest.param("0 spaces\n 2\n 1", id="bad_indent"),
129129
pytest.param("'''", id="string_eof"),
130130
pytest.param("$hello", id="dollar"),
131+
# on 3.10 this passes ast.parse but fails on tokenize.generate_tokens
132+
pytest.param(
133+
"\r'\\\n'''",
134+
id="leading_newline_eof",
135+
marks=[
136+
pytest.mark.skipif(env.PYVERSION >= (3, 12), reason="parses fine in 3.12"),
137+
]
138+
)
131139
])
132140
def test_not_python(self, text: str) -> None:
133141
msg = r"Couldn't parse '<code>' as Python source: '.*' at line \d+"

0 commit comments

Comments
 (0)