From a258854d73827d426a0d5347bfa2eaf478127108 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20van=20Noord?= <13665637+DanielNoord@users.noreply.github.com> Date: Sun, 2 Oct 2022 22:23:20 +0200 Subject: [PATCH] Raise ``syntax-error`` correctly on invalid encodings (#7553) --- doc/whatsnew/fragments/7522.bugfix | 3 +++ pylint/lint/pylinter.py | 5 ++++- tests/regrtest_data/invalid_encoding.py | 1 + tests/test_self.py | 5 +++++ 4 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 doc/whatsnew/fragments/7522.bugfix create mode 100644 tests/regrtest_data/invalid_encoding.py diff --git a/doc/whatsnew/fragments/7522.bugfix b/doc/whatsnew/fragments/7522.bugfix new file mode 100644 index 0000000000..f4fa9da1af --- /dev/null +++ b/doc/whatsnew/fragments/7522.bugfix @@ -0,0 +1,3 @@ +Fixed an issue where ``syntax-error`` couldn't be raised on files with invalid encodings. + +Closes #7522 diff --git a/pylint/lint/pylinter.py b/pylint/lint/pylinter.py index 28ad79e4ca..cb528c5df7 100644 --- a/pylint/lint/pylinter.py +++ b/pylint/lint/pylinter.py @@ -1013,9 +1013,12 @@ def get_ast( data, modname, filepath ) except astroid.AstroidSyntaxError as ex: + line = getattr(ex.error, "lineno", None) + if line is None: + line = 0 self.add_message( "syntax-error", - line=getattr(ex.error, "lineno", 0), + line=line, col_offset=getattr(ex.error, "offset", None), args=f"Parsing failed: '{ex.error}'", confidence=HIGH, diff --git a/tests/regrtest_data/invalid_encoding.py b/tests/regrtest_data/invalid_encoding.py new file mode 100644 index 0000000000..d508d19df8 --- /dev/null +++ b/tests/regrtest_data/invalid_encoding.py @@ -0,0 +1 @@ +# -*- coding: lala -*- diff --git a/tests/test_self.py b/tests/test_self.py index c382edb196..a69b45aaf0 100644 --- a/tests/test_self.py +++ b/tests/test_self.py @@ -1191,6 +1191,11 @@ def test_ignore_path_recursive_current_dir(self) -> None: code=0, ) + def test_syntax_error_invalid_encoding(self) -> None: + module = join(HERE, "regrtest_data", "invalid_encoding.py") + expected_output = "unknown encoding" + self._test_output([module, "-E"], expected_output=expected_output) + class TestCallbackOptions: """Test for all callback options we support."""