From a1bf80bb402c8205bc270b403eba0e4b28de9ab3 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Sun, 22 Nov 2026 17:47:55 +0800 Subject: [PATCH] Report unknown source encodings as ModuleSyntaxError --- CHANGELOG.md | 2 ++ rope/base/pyobjectsdef.py | 2 ++ ropetest/contrib/codeassisttest.py | 4 ++++ ropetest/pycoretest.py | 7 +++++++ 4 files changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88e4748e2..981849087 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # **Upcoming release** +- #83 Report unknown source encodings as ModuleSyntaxError instead of leaking LookupError (@Aschenbath) + - #859 Fix `find_definition`/Rename not resolving `async def` methods called via `self` (@gadievron) - #895 patchedast Starred and keyword now consumes their syntactically expected and ** (@lieryan) - #896 patchedast cleanup and refactoring (@lieryan) diff --git a/rope/base/pyobjectsdef.py b/rope/base/pyobjectsdef.py index 95bd15691..221e1d305 100644 --- a/rope/base/pyobjectsdef.py +++ b/rope/base/pyobjectsdef.py @@ -202,6 +202,8 @@ def _init_source(self, pycore, source_code, resource): raise exceptions.ModuleSyntaxError(filename, e.lineno, e.msg) except UnicodeDecodeError as e: raise exceptions.ModuleSyntaxError(filename, 1, "%s" % (e.reason)) + except LookupError as e: + raise exceptions.ModuleSyntaxError(filename, 1, str(e)) from e return source_code, ast_node @utils.prevent_recursion(lambda: {}) diff --git a/ropetest/contrib/codeassisttest.py b/ropetest/contrib/codeassisttest.py index 8ecf24452..0b5d853be 100644 --- a/ropetest/contrib/codeassisttest.py +++ b/ropetest/contrib/codeassisttest.py @@ -33,6 +33,10 @@ def _assist(self, code, offset=None, **args): def test_simple_assist(self): self._assist("", 0) + def test_unknown_source_encoding_reports_module_syntax_error(self): + with self.assertRaises(exceptions.ModuleSyntaxError): + self._assist("# coding: utf-8X\n", 0, maxfixes=5) + def assert_completion_in_result(self, name, scope, result, type=None): for proposal in result: if proposal.name == name: diff --git a/ropetest/pycoretest.py b/ropetest/pycoretest.py index 5ccd80d2a..4f0720a83 100644 --- a/ropetest/pycoretest.py +++ b/ropetest/pycoretest.py @@ -693,6 +693,13 @@ def test_syntax_errors_in_code(self): with self.assertRaises(exceptions.ModuleSyntaxError): libutils.get_string_module(self.project, "xyx print\n") + def test_unknown_source_encoding_is_a_module_syntax_error(self): + with self.assertRaises(exceptions.ModuleSyntaxError) as caught: + libutils.get_string_module(self.project, "# coding: utf-8X\n") + self.assertEqual(caught.exception.filename, "string") + self.assertEqual(caught.exception.lineno, 1) + self.assertIn("unknown encoding", str(caught.exception)) + def test_holding_error_location_information(self): try: libutils.get_string_module(self.project, "xyx print\n")