Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c6772c4

Browse files
committed
#21476: Unwrap fp in BytesParser so the file isn't unexpectedly closed.
This makes the behavior match that of Parser. Patch by Vajrasky Kok.
1 parent 1945456 commit c6772c4

3 files changed

Lines changed: 31 additions & 1 deletion

File tree

Lib/email/parser.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,10 @@ def parse(self, fp, headersonly=False):
106106
meaning it parses the entire contents of the file.
107107
"""
108108
fp = TextIOWrapper(fp, encoding='ascii', errors='surrogateescape')
109-
with fp:
109+
try:
110110
return self.parser.parse(fp, headersonly)
111+
finally:
112+
fp.detach()
111113

112114

113115
def parsebytes(self, text, headersonly=False):

Lib/test/test_email/test_email.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3390,6 +3390,31 @@ def test_bytes_header_parser(self):
33903390
self.assertIsInstance(msg.get_payload(), str)
33913391
self.assertIsInstance(msg.get_payload(decode=True), bytes)
33923392

3393+
def test_bytes_parser_does_not_close_file(self):
3394+
with openfile('msg_02.txt', 'rb') as fp:
3395+
email.parser.BytesParser().parse(fp)
3396+
self.assertFalse(fp.closed)
3397+
3398+
def test_bytes_parser_on_exception_does_not_close_file(self):
3399+
with openfile('msg_15.txt', 'rb') as fp:
3400+
bytesParser = email.parser.BytesParser
3401+
self.assertRaises(email.errors.StartBoundaryNotFoundDefect,
3402+
bytesParser(policy=email.policy.strict).parse,
3403+
fp)
3404+
self.assertFalse(fp.closed)
3405+
3406+
def test_parser_does_not_close_file(self):
3407+
with openfile('msg_02.txt', 'r') as fp:
3408+
email.parser.Parser().parse(fp)
3409+
self.assertFalse(fp.closed)
3410+
3411+
def test_parser_on_exception_does_not_close_file(self):
3412+
with openfile('msg_15.txt', 'r') as fp:
3413+
parser = email.parser.Parser
3414+
self.assertRaises(email.errors.StartBoundaryNotFoundDefect,
3415+
parser(policy=email.policy.strict).parse, fp)
3416+
self.assertFalse(fp.closed)
3417+
33933418
def test_whitespace_continuation(self):
33943419
eq = self.assertEqual
33953420
# This message contains a line after the Subject: header that has only

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ Core and Builtins
2727
Library
2828
-------
2929

30+
- Issue #21476: Make sure the email.parser.BytesParser TextIOWrapper is
31+
discarded after parsing, so the input file isn't unexpectedly closed.
32+
3033
- Issue #21729: Used the "with" statement in the dbm.dumb module to ensure
3134
files closing. Patch by Claudiu Popa.
3235

0 commit comments

Comments
 (0)