Skip to content

Commit 844b0e6

Browse files
committed
#16811: Fix folding of headers with no value in provisional policies.
1 parent 36b365c commit 844b0e6

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

Lib/email/policy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def _fold(self, name, value, refold_binary=False):
173173
lines = value.splitlines()
174174
refold = (self.refold_source == 'all' or
175175
self.refold_source == 'long' and
176-
(len(lines[0])+len(name)+2 > maxlen or
176+
(lines and len(lines[0])+len(name)+2 > maxlen or
177177
any(len(x) > maxlen for x in lines[1:])))
178178
if refold or refold_binary and _has_surrogates(value):
179179
return self.header_factory(name, ''.join(lines)).fold(policy=self)
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""Test the parser and generator are inverses.
2+
3+
Note that this is only strictly true if we are parsing RFC valid messages and
4+
producing RFC valid messages.
5+
"""
6+
7+
import io
8+
import unittest
9+
from email import policy, message_from_bytes
10+
from email.generator import BytesGenerator
11+
from test.test_email import TestEmailBase, parameterize
12+
13+
# This is like textwrap.dedent for bytes, except that it uses \r\n for the line
14+
# separators on the rebuilt string.
15+
def dedent(bstr):
16+
lines = bstr.splitlines()
17+
if not lines[0].strip():
18+
raise ValueError("First line must contain text")
19+
stripamt = len(lines[0]) - len(lines[0].lstrip())
20+
return b'\r\n'.join(
21+
[x[stripamt:] if len(x)>=stripamt else b''
22+
for x in lines])
23+
24+
25+
@parameterize
26+
class TestInversion(TestEmailBase, unittest.TestCase):
27+
28+
def msg_as_input(self, msg):
29+
m = message_from_bytes(msg, policy=policy.SMTP)
30+
b = io.BytesIO()
31+
g = BytesGenerator(b)
32+
g.flatten(m)
33+
self.assertEqual(b.getvalue(), msg)
34+
35+
# XXX: spaces are not preserved correctly here yet in the general case.
36+
msg_params = {
37+
'header_with_one_space_body': (dedent(b"""\
38+
From: abc@xyz.com
39+
X-Status:\x20
40+
Subject: test
41+
42+
foo
43+
"""),),
44+
45+
}

0 commit comments

Comments
 (0)