Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

catch TokenError on parse #1788

Merged
merged 3 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions coverage/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,10 +263,14 @@ def parse_source(self) -> None:
try:
self._ast_root = ast.parse(self.text)
self._raw_parse()
except (IndentationError, SyntaxError) as err:
except (tokenize.TokenError, IndentationError, SyntaxError) as err:
if hasattr(err, "lineno"):
lineno = err.lineno # IndentationError
else:
lineno = err.args[1][0] # TokenError
raise NotPython(
f"Couldn't parse '{self.filename}' as Python source: " +
f"{err.args[0]!r} at line {err.lineno}",
f"{err.args[0]!r} at line {lineno}",
) from err

ignore = self.excluded | self.raw_docstrings
Expand Down
9 changes: 9 additions & 0 deletions tests/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from __future__ import annotations

import textwrap
import sys

import pytest

Expand Down Expand Up @@ -128,6 +129,14 @@ def foo():
pytest.param("0 spaces\n 2\n 1", id="bad_indent"),
pytest.param("'''", id="string_eof"),
pytest.param("$hello", id="dollar"),
# on 3.10 this passes ast.parse but fails on tokenize.generate_tokens
pytest.param(
"\r'\\\n'''",
id="ledaing_newline_eof",
tybug marked this conversation as resolved.
Show resolved Hide resolved
marks=[
pytest.mark.skipif(sys.version_info >= (3, 12), reason="parses fine in 3.11")
]
)
])
def test_not_python(self, text: str) -> None:
msg = r"Couldn't parse '<code>' as Python source: '.*' at line \d+"
Expand Down