]> granicus.if.org Git - python/commitdiff
Issue #23840: tokenize.open() now closes the temporary binary file on error to
authorVictor Stinner <victor.stinner@gmail.com>
Mon, 25 May 2015 22:43:58 +0000 (00:43 +0200)
committerVictor Stinner <victor.stinner@gmail.com>
Mon, 25 May 2015 22:43:58 +0000 (00:43 +0200)
fix a resource warning.

Lib/test/test_tokenize.py
Lib/tokenize.py
Misc/NEWS

index 4a8be3be5a230b58d00bea7bd59d594721f38208..984220729d2b2321f2a8f5a6f47d7d52ac58cf4d 100644 (file)
@@ -646,7 +646,7 @@ from tokenize import (tokenize, _tokenize, untokenize, NUMBER, NAME, OP,
                      STRING, ENDMARKER, ENCODING, tok_name, detect_encoding,
                      open as tokenize_open, Untokenizer)
 from io import BytesIO
-from unittest import TestCase
+from unittest import TestCase, mock
 import os, sys, glob
 import token
 
@@ -1058,6 +1058,14 @@ class TestDetectEncoding(TestCase):
             ins = Bunk(lines, path)
             detect_encoding(ins.readline)
 
+    def test_open_error(self):
+        # Issue #23840: open() must close the binary file on error
+        m = BytesIO(b'#coding:xxx')
+        with mock.patch('tokenize._builtin_open', return_value=m):
+            self.assertRaises(SyntaxError, tokenize_open, 'foobar')
+        self.assertTrue(m.closed)
+
+
 
 class TestTokenize(TestCase):
 
index ed4153cec66006226b94f38c03b2f645d243630c..cf18bf9f2db0bdbfce209fd6b5470c4ca1ecac89 100644 (file)
@@ -435,11 +435,15 @@ def open(filename):
     detect_encoding().
     """
     buffer = _builtin_open(filename, 'rb')
-    encoding, lines = detect_encoding(buffer.readline)
-    buffer.seek(0)
-    text = TextIOWrapper(buffer, encoding, line_buffering=True)
-    text.mode = 'r'
-    return text
+    try:
+        encoding, lines = detect_encoding(buffer.readline)
+        buffer.seek(0)
+        text = TextIOWrapper(buffer, encoding, line_buffering=True)
+        text.mode = 'r'
+        return text
+    except:
+        buffer.close()
+        raise
 
 
 def tokenize(readline):
index 74c9114d9221d8593c3a0efd94df38b304aa4e01..5d93c29f597db5d10b5efce547268c0f8bbf35ac 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -59,6 +59,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #23840: tokenize.open() now closes the temporary binary file on error
+  to fix a resource warning.
+
 - Issue #24257: Fixed segmentation fault in sqlite3.Row constructor with faked
   cursor type.