Skip to content

Commit

Permalink
[syntax-error] Fix a crash when the line and column can't be retrieved
Browse files Browse the repository at this point in the history
Closes #3860
  • Loading branch information
Pierre-Sassoulas committed Jul 9, 2022
1 parent b9419a2 commit 319a5c9
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 12 deletions.
17 changes: 8 additions & 9 deletions pylint/lint/pylinter.py
Original file line number Diff line number Diff line change
Expand Up @@ -692,11 +692,9 @@ def _check_files(
)
msg = get_fatal_error_message(file.filepath, template_path)
if isinstance(ex, AstroidError):
symbol = "astroid-error"
self.add_message(symbol, args=(file.filepath, msg))
self.add_message("astroid-error", args=(file.filepath, msg))
else:
symbol = "fatal"
self.add_message(symbol, args=msg)
self.add_message("fatal", args=msg)

def _check_file(
self,
Expand Down Expand Up @@ -914,12 +912,13 @@ def get_ast(
data, modname, filepath
)
except astroid.AstroidSyntaxError as ex:
# pylint: disable=no-member
# TODO 2.16: Clearer less dynamic Exception classes in astroid
error, line, col = getattr(ex, "error", None), 0, 0
if error:
line = error.lineno or 0
col = error.offset or 0
self.add_message(
"syntax-error",
line=getattr(ex.error, "lineno", 0),
col_offset=getattr(ex.error, "offset", None),
args=str(ex.error),
"syntax-error", line=line, col_offset=col, args=ex, confidence=HIGH
)
except astroid.AstroidBuildingError as ex:
self.add_message("parse-error", args=ex)
Expand Down
3 changes: 2 additions & 1 deletion tests/functional/s/syntax/syntax_error.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
syntax-error:1:10:None:None::invalid syntax (<unknown>, line 1):UNDEFINED
syntax-error:1:10:None:None::"Parsing Python code failed:
invalid syntax (<unknown>, line 1)":HIGH
14 changes: 12 additions & 2 deletions tests/test_self.py
Original file line number Diff line number Diff line change
Expand Up @@ -582,10 +582,11 @@ def foobar(arg):
expected_output=expected,
)

def test_stdin_syntaxerror(self) -> None:
def test_stdin_syntax_error(self) -> None:
expected_output = (
"************* Module a\n"
"a.py:1:4: E0001: invalid syntax (<unknown>, line 1) (syntax-error)"
"a.py:1:4: E0001: Parsing Python code failed:\n"
"invalid syntax (<unknown>, line 1) (syntax-error)"
)

with mock.patch(
Expand All @@ -597,6 +598,15 @@ def test_stdin_syntaxerror(self) -> None:
)
assert mock_stdin.call_count == 1

def test_astroid_syntax_error(self, tmp_path) -> None:
file_path = tmp_path / "a.py"
with open(file_path, "w", encoding="utf8") as f:
f.write("# encoding=UTF-9\n")
self._test_output(
[str(file_path), "--disable=all", "--enable=syntax-error"],
expected_output="a.py': UTF-9 (syntax-error)",
)

def test_version(self) -> None:
def check(lines: list[str]) -> None:
assert lines[0].startswith("pylint ")
Expand Down

0 comments on commit 319a5c9

Please sign in to comment.