Debian Codegraph @

lib-python/3/test/test_email/test_generator.py

raw symbols SCIP
1 import io
2 import textwrap
3 import unittest
4 from email import message_from_string, message_from_bytes
5 from email.message import EmailMessage
6 from email.generator import Generator, BytesGenerator
7 from email.headerregistry import Address
8 from email import policy
9 import email.errors
10 from test.test_email import TestEmailBase, parameterize
11
12
13 @parameterize
14 class TestGeneratorBase:
15
16 policy = policy.default
17
18 def msgmaker(self, msg, policy=None):
19 policy = self.policy if policy is None else policy
20 return self.msgfunc(msg, policy=policy)
21
22 refold_long_expected = {
23 0: textwrap.dedent("""\
24 To: [email protected]
25 From: [email protected]
26 Subject: We the willing led by the unknowing are doing the
27 impossible for the ungrateful. We have done so much for so long with so little
28 we are now qualified to do anything with nothing.
29
30 None
31 """),
32 40: textwrap.dedent("""\
33 To: [email protected]
34 From:
35 [email protected]
36 Subject: We the willing led by the
37 unknowing are doing the impossible for
38 the ungrateful. We have done so much
39 for so long with so little we are now
40 qualified to do anything with nothing.
41
42 None
43 """),
44 20: textwrap.dedent("""\
45 To:
46 [email protected]
47 From:
48 [email protected]
49 Subject: We the
50 willing led by the
51 unknowing are doing
52 the impossible for
53 the ungrateful. We
54 have done so much
55 for so long with so
56 little we are now
57 qualified to do
58 anything with
59 nothing.
60
61 None
62 """),
63 }
64 refold_long_expected[100] = refold_long_expected[0]
65
66 refold_all_expected = refold_long_expected.copy()
67 refold_all_expected[0] = (
68 "To: [email protected]\n"
69 "From: [email protected]\n"
70 "Subject: We the willing led by the unknowing are doing the "
71 "impossible for the ungrateful. We have done so much for "
72 "so long with so little we are now qualified to do anything "
73 "with nothing.\n"
74 "\n"
75 "None\n")
76 refold_all_expected[100] = (
77 "To: [email protected]\n"
78 "From: [email protected]\n"
79 "Subject: We the willing led by the unknowing are doing the "
80 "impossible for the ungrateful. We have\n"
81 " done so much for so long with so little we are now qualified "
82 "to do anything with nothing.\n"
83 "\n"
84 "None\n")
85
86 length_params = [n for n in refold_long_expected]
87
88 def length_as_maxheaderlen_parameter(self, n):
89 msg = self.msgmaker(self.typ(self.refold_long_expected[0]))
90 s = self.ioclass()
91 g = self.genclass(s, maxheaderlen=n, policy=self.policy)
92 g.flatten(msg)
93 self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[n]))
94
95 def length_as_max_line_length_policy(self, n):
96 msg = self.msgmaker(self.typ(self.refold_long_expected[0]))
97 s = self.ioclass()
98 g = self.genclass(s, policy=self.policy.clone(max_line_length=n))
99 g.flatten(msg)
100 self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[n]))
101
102 def length_as_maxheaderlen_parm_overrides_policy(self, n):
103 msg = self.msgmaker(self.typ(self.refold_long_expected[0]))
104 s = self.ioclass()
105 g = self.genclass(s, maxheaderlen=n,
106 policy=self.policy.clone(max_line_length=10))
107 g.flatten(msg)
108 self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[n]))
109
110 def length_as_max_line_length_with_refold_none_does_not_fold(self, n):
111 msg = self.msgmaker(self.typ(self.refold_long_expected[0]))
112 s = self.ioclass()
113 g = self.genclass(s, policy=self.policy.clone(refold_source='none',
114 max_line_length=n))
115 g.flatten(msg)
116 self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[0]))
117
118 def length_as_max_line_length_with_refold_all_folds(self, n):
119 msg = self.msgmaker(self.typ(self.refold_long_expected[0]))
120 s = self.ioclass()
121 g = self.genclass(s, policy=self.policy.clone(refold_source='all',
122 max_line_length=n))
123 g.flatten(msg)
124 self.assertEqual(s.getvalue(), self.typ(self.refold_all_expected[n]))
125
126 def test_crlf_control_via_policy(self):
127 source = "Subject: test\r\n\r\ntest body\r\n"
128 expected = source
129 msg = self.msgmaker(self.typ(source))
130 s = self.ioclass()
131 g = self.genclass(s, policy=policy.SMTP)
132 g.flatten(msg)
133 self.assertEqual(s.getvalue(), self.typ(expected))
134
135 def test_flatten_linesep_overrides_policy(self):
136 source = "Subject: test\n\ntest body\n"
137 expected = source
138 msg = self.msgmaker(self.typ(source))
139 s = self.ioclass()
140 g = self.genclass(s, policy=policy.SMTP)
141 g.flatten(msg, linesep='\n')
142 self.assertEqual(s.getvalue(), self.typ(expected))
143
144 def test_set_mangle_from_via_policy(self):
145 source = textwrap.dedent("""\
146 Subject: test that
147 from is mangled in the body!
148
149 From time to time I write a rhyme.
150 """)
151 variants = (
152 (None, True),
153 (policy.compat32, True),
154 (policy.default, False),
155 (policy.default.clone(mangle_from_=True), True),
156 )
157 for p, mangle in variants:
158 expected = source.replace('From ', '>From ') if mangle else source
159 with self.subTest(policy=p, mangle_from_=mangle):
160 msg = self.msgmaker(self.typ(source))
161 s = self.ioclass()
162 g = self.genclass(s, policy=p)
163 g.flatten(msg)
164 self.assertEqual(s.getvalue(), self.typ(expected))
165
166 def test_compat32_max_line_length_does_not_fold_when_none(self):
167 msg = self.msgmaker(self.typ(self.refold_long_expected[0]))
168 s = self.ioclass()
169 g = self.genclass(s, policy=policy.compat32.clone(max_line_length=None))
170 g.flatten(msg)
171 self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[0]))
172
173 def test_rfc2231_wrapping(self):
174 # This is pretty much just to make sure we don't have an infinite
175 # loop; I don't expect anyone to hit this in the field.
176 msg = self.msgmaker(self.typ(textwrap.dedent("""\
177 To: nobody
178 Content-Disposition: attachment;
179 filename="afilenamelongenoghtowraphere"
180
181 None
182 """)))
183 expected = textwrap.dedent("""\
184 To: nobody
185 Content-Disposition: attachment;
186 filename*0*=us-ascii''afilename;
187 filename*1*=longenoghtowraphere
188
189 None
190 """)
191 s = self.ioclass()
192 g = self.genclass(s, policy=self.policy.clone(max_line_length=33))
193 g.flatten(msg)
194 self.assertEqual(s.getvalue(), self.typ(expected))
195
196 def test_rfc2231_wrapping_switches_to_default_len_if_too_narrow(self):
197 # This is just to make sure we don't have an infinite loop; I don't
198 # expect anyone to hit this in the field, so I'm not bothering to make
199 # the result optimal (the encoding isn't needed).
200 msg = self.msgmaker(self.typ(textwrap.dedent("""\
201 To: nobody
202 Content-Disposition: attachment;
203 filename="afilenamelongenoghtowraphere"
204
205 None
206 """)))
207 expected = textwrap.dedent("""\
208 To: nobody
209 Content-Disposition:
210 attachment;
211 filename*0*=us-ascii''afilenamelongenoghtowraphere
212
213 None
214 """)
215 s = self.ioclass()
216 g = self.genclass(s, policy=self.policy.clone(max_line_length=20))
217 g.flatten(msg)
218 self.assertEqual(s.getvalue(), self.typ(expected))
219
220 def test_keep_encoded_newlines(self):
221 msg = self.msgmaker(self.typ(textwrap.dedent("""\
222 To: nobody
223 Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: [email protected]
224
225 None
226 """)))
227 expected = textwrap.dedent("""\
228 To: nobody
229 Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: [email protected]
230
231 None
232 """)
233 s = self.ioclass()
234 g = self.genclass(s, policy=self.policy.clone(max_line_length=80))
235 g.flatten(msg)
236 self.assertEqual(s.getvalue(), self.typ(expected))
237
238 def test_keep_long_encoded_newlines(self):
239 msg = self.msgmaker(self.typ(textwrap.dedent("""\
240 To: nobody
241 Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: [email protected]
242
243 None
244 """)))
245 expected = textwrap.dedent("""\
246 To: nobody
247 Subject: Bad subject
248 =?utf-8?q?=0A?=Bcc:
249 [email protected]
250
251 None
252 """)
253 s = self.ioclass()
254 g = self.genclass(s, policy=self.policy.clone(max_line_length=30))
255 g.flatten(msg)
256 self.assertEqual(s.getvalue(), self.typ(expected))
257
258
259 class TestGenerator(TestGeneratorBase, TestEmailBase):
260
261 msgfunc = staticmethod(message_from_string)
262 genclass = Generator
263 ioclass = io.StringIO
264 typ = str
265
266 def test_verify_generated_headers(self):
267 # gh-121650: by default the generator prevents header injection
268 class LiteralHeader(str):
269 name = 'Header'
270 def fold(self, **kwargs):
271 return self
272
273 for text in (
274 'Value\r\nBad Injection\r\n',
275 'NoNewLine'
276 ):
277 with self.subTest(text=text):
278 message = message_from_string(
279 "Header: Value\r\n\r\nBody",
280 policy=self.policy,
281 )
282
283 del message['Header']
284 message['Header'] = LiteralHeader(text)
285
286 with self.assertRaises(email.errors.HeaderWriteError):
287 message.as_string()
288 with self.assertRaises(email.errors.HeaderWriteError):
289 message.as_bytes()
290
291
292 class TestBytesGenerator(TestGeneratorBase, TestEmailBase):
293
294 msgfunc = staticmethod(message_from_bytes)
295 genclass = BytesGenerator
296 ioclass = io.BytesIO
297 typ = lambda self, x: x.encode('ascii')
298
299 def test_cte_type_7bit_handles_unknown_8bit(self):
300 source = ("Subject: Maintenant je vous présente mon "
301 "collègue\n\n").encode('utf-8')
302 expected = ('Subject: Maintenant je vous =?unknown-8bit?q?'
303 'pr=C3=A9sente_mon_coll=C3=A8gue?=\n\n').encode('ascii')
304 msg = message_from_bytes(source)
305 s = io.BytesIO()
306 g = BytesGenerator(s, policy=self.policy.clone(cte_type='7bit'))
307 g.flatten(msg)
308 self.assertEqual(s.getvalue(), expected)
309
310 def test_cte_type_7bit_transforms_8bit_cte(self):
311 source = textwrap.dedent("""\
312 From: [email protected]
313 To: Dinsdale
314 Subject: Nudge nudge, wink, wink
315 Mime-Version: 1.0
316 Content-Type: text/plain; charset="latin-1"
317 Content-Transfer-Encoding: 8bit
318
319 oh là là, know what I mean, know what I mean?
320 """).encode('latin1')
321 msg = message_from_bytes(source)
322 expected = textwrap.dedent("""\
323 From: [email protected]
324 To: Dinsdale
325 Subject: Nudge nudge, wink, wink
326 Mime-Version: 1.0
327 Content-Type: text/plain; charset="iso-8859-1"
328 Content-Transfer-Encoding: quoted-printable
329
330 oh l=E0 l=E0, know what I mean, know what I mean?
331 """).encode('ascii')
332 s = io.BytesIO()
333 g = BytesGenerator(s, policy=self.policy.clone(cte_type='7bit',
334 linesep='\n'))
335 g.flatten(msg)
336 self.assertEqual(s.getvalue(), expected)
337
338 def test_smtputf8_policy(self):
339 msg = EmailMessage()
340 msg['From'] = "Páolo <fő[email protected]>"
341 msg['To'] = 'Dinsdale'
342 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
343 msg.set_content("oh là là, know what I mean, know what I mean?")
344 expected = textwrap.dedent("""\
345 From: Páolo <fő[email protected]m>
346 To: Dinsdale
347 Subject: Nudge nudge, wink, wink \u1F609
348 Content-Type: text/plain; charset="utf-8"
349 Content-Transfer-Encoding: 8bit
350 MIME-Version: 1.0
351
352 oh là là, know what I mean, know what I mean?
353 """).encode('utf-8').replace(b'\n', b'\r\n')
354 s = io.BytesIO()
355 g = BytesGenerator(s, policy=policy.SMTPUTF8)
356 g.flatten(msg)
357 self.assertEqual(s.getvalue(), expected)
358
359 def test_smtp_policy(self):
360 msg = EmailMessage()
361 msg["From"] = Address(addr_spec="[email protected]", display_name="Páolo")
362 msg["To"] = Address(addr_spec="[email protected]", display_name="Dinsdale")
363 msg["Subject"] = "Nudge nudge, wink, wink"
364 msg.set_content("oh boy, know what I mean, know what I mean?")
365 expected = textwrap.dedent("""\
366 From: =?utf-8?q?P=C3=A1olo?= <[email protected]>
367 To: Dinsdale <[email protected]>
368 Subject: Nudge nudge, wink, wink
369 Content-Type: text/plain; charset="utf-8"
370 Content-Transfer-Encoding: 7bit
371 MIME-Version: 1.0
372
373 oh boy, know what I mean, know what I mean?
374 """).encode().replace(b"\n", b"\r\n")
375 s = io.BytesIO()
376 g = BytesGenerator(s, policy=policy.SMTP)
377 g.flatten(msg)
378 self.assertEqual(s.getvalue(), expected)
379
380
381 if __name__ == '__main__':
382 unittest.main()