[issue11701] email.parser.BytesParser().parse() closes file argument

Steffen Daode Nurpmeso report at bugs.python.org
Wed Apr 13 15:52:35 CEST 2011


Steffen Daode Nurpmeso <sdaoden at googlemail.com> added the comment:

So i'll changed the existing message_from_(binary_)?file() tests
to also test the file closing.

----------
Added file: http://bugs.python.org/file21649/11701.2.diff

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11701>
_______________________________________
-------------- next part --------------
diff --git a/Lib/email/parser.py b/Lib/email/parser.py
--- a/Lib/email/parser.py
+++ b/Lib/email/parser.py
@@ -100,9 +100,9 @@
         meaning it parses the entire contents of the file.
         """
         fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape')
-        with fp:
-            return self.parser.parse(fp, headersonly)
-
+        msg = self.parser.parse(fp, headersonly)
+        fp.detach()
+        return msg
 
     def parsebytes(self, text, headersonly=False):
         """Create a message structure from a byte string.
diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py
--- a/Lib/test/test_email/test_email.py
+++ b/Lib/test/test_email/test_email.py
@@ -2268,16 +2268,18 @@
         self.assertEqual(text, s.getvalue())
 
     def test_message_from_file(self):
-        with openfile('msg_01.txt') as fp:
-            text = fp.read()
-            fp.seek(0)
-            msg = email.message_from_file(fp)
-            s = StringIO()
-            # Don't wrap/continue long headers since we're trying to test
-            # idempotency.
-            g = Generator(s, maxheaderlen=0)
-            g.flatten(msg)
-            self.assertEqual(text, s.getvalue())
+        fp = openfile('msg_01.txt')
+        text = fp.read()
+        fp.seek(0)
+        msg = email.parser.Parser().parse(fp)
+        self.assertFalse(fp.closed)
+        fp.close()
+        s = StringIO()
+        # Don't wrap/continue long headers since we're trying to test
+        # idempotency.
+        g = Generator(s, maxheaderlen=0)
+        g.flatten(msg)
+        self.assertEqual(text, s.getvalue())
 
     def test_message_from_string_with_class(self):
         unless = self.assertTrue
@@ -3181,9 +3183,11 @@
         self.addCleanup(unlink, fn)
         with open(fn, 'wb') as testfile:
             testfile.write(self.non_latin_bin_msg)
-        with open(fn, 'rb') as testfile:
-            m = email.parser.BytesParser().parse(testfile)
+        fp = open(fn, 'rb')
+        m = email.parser.BytesParser().parse(fp)
+        self.assertFalse(fp.closed)
         self.assertEqual(str(m), self.non_latin_bin_msg_as7bit)
+        fp.close()
 
     latin_bin_msg = textwrap.dedent("""\
         From: foo at bar.com


More information about the Python-bugs-list mailing list