]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-92336: linecache.getline should not raise exceptions on decoding errors (GH-94410)
authorIrit Katriel <1055913+iritkatriel@users.noreply.github.com>
Thu, 30 Jun 2022 09:18:18 +0000 (10:18 +0100)
committerGitHub <noreply@github.com>
Thu, 30 Jun 2022 09:18:18 +0000 (10:18 +0100)
Lib/linecache.py
Lib/test/test_linecache.py
Misc/NEWS.d/next/Library/2022-06-29-09-48-37.gh-issue-92336.otA6c6.rst [new file with mode: 0644]

index 23191d6501d2a836b24edb452fc3ddb6c1a2b2bf..97644a8e3794e17151a415bb92af22cda8d595bb 100644 (file)
@@ -135,7 +135,7 @@ def updatecache(filename, module_globals=None):
     try:
         with tokenize.open(fullname) as fp:
             lines = fp.readlines()
-    except OSError:
+    except (OSError, UnicodeDecodeError, SyntaxError):
         return []
     if lines and not lines[-1].endswith('\n'):
         lines[-1] += '\n'
index c6e2dadbb25e1fd9cd3b66c28d7a8d9ac805f240..72dd40136cfdb24b7bec3ee8798c259b4597e397 100644 (file)
@@ -73,12 +73,10 @@ class GetLineTestsBadData(TempFile):
     # file_byte_string = b'Bad data goes here'
 
     def test_getline(self):
-        self.assertRaises((SyntaxError, UnicodeDecodeError),
-                          linecache.getline, self.file_name, 1)
+        self.assertEqual(linecache.getline(self.file_name, 1), '')
 
     def test_getlines(self):
-        self.assertRaises((SyntaxError, UnicodeDecodeError),
-                          linecache.getlines, self.file_name)
+        self.assertEqual(linecache.getlines(self.file_name), [])
 
 
 class EmptyFile(GetLineTestsGoodData, unittest.TestCase):
@@ -92,9 +90,11 @@ class SingleEmptyLine(GetLineTestsGoodData, unittest.TestCase):
 class GoodUnicode(GetLineTestsGoodData, unittest.TestCase):
     file_list = ['á\n', 'b\n', 'abcdef\n', 'ááááá\n']
 
+class BadUnicode_NoDeclaration(GetLineTestsBadData, unittest.TestCase):
+    file_byte_string = b'\n\x80abc'
 
-class BadUnicode(GetLineTestsBadData, unittest.TestCase):
-    file_byte_string = b'\x80abc'
+class BadUnicode_WithDeclaration(GetLineTestsBadData, unittest.TestCase):
+    file_byte_string = b'# coding=utf-8\n\x80abc'
 
 
 class LineCacheTests(unittest.TestCase):
diff --git a/Misc/NEWS.d/next/Library/2022-06-29-09-48-37.gh-issue-92336.otA6c6.rst b/Misc/NEWS.d/next/Library/2022-06-29-09-48-37.gh-issue-92336.otA6c6.rst
new file mode 100644 (file)
index 0000000..eb74e0c
--- /dev/null
@@ -0,0 +1 @@
+Fix bug where :meth:`linecache.getline` fails on bad files with :exc:`UnicodeDecodeError` or :exc:`SyntaxError`. It now returns an empty string as per the documentation.