Debian Codegraph @

Lib/test/test_email/test_generator.py

raw
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_flatten_linesep(self):
145 source = 'Subject: one\n two\r three\r\n four\r\n\r\ntest body\r\n'
146 msg = self.msgmaker(self.typ(source))
147 self.assertEqual(msg['Subject'], 'one two three four')
148
149 expected = 'Subject: one\n two\n three\n four\n\ntest body\n'
150 s = self.ioclass()
151 g = self.genclass(s)
152 g.flatten(msg)
153 self.assertEqual(s.getvalue(), self.typ(expected))
154
155 expected = 'Subject: one two three four\n\ntest body\n'
156 s = self.ioclass()
157 g = self.genclass(s, policy=self.policy.clone(refold_source='all'))
158 g.flatten(msg)
159 self.assertEqual(s.getvalue(), self.typ(expected))
160
161 def test_flatten_control_linesep(self):
162 source = 'Subject: one\v two\f three\x1c four\x1d five\x1e six\r\n\r\ntest body\r\n'
163 msg = self.msgmaker(self.typ(source))
164 self.assertEqual(msg['Subject'], 'one\v two\f three\x1c four\x1d five\x1e six')
165
166 expected = 'Subject: one\v two\f three\x1c four\x1d five\x1e six\n\ntest body\n'
167 s = self.ioclass()
168 g = self.genclass(s)
169 g.flatten(msg)
170 self.assertEqual(s.getvalue(), self.typ(expected))
171
172 s = self.ioclass()
173 g = self.genclass(s, policy=self.policy.clone(refold_source='all'))
174 g.flatten(msg)
175 self.assertEqual(s.getvalue(), self.typ(expected))
176
177 def test_set_mangle_from_via_policy(self):
178 source = textwrap.dedent("""\
179 Subject: test that
180 from is mangled in the body!
181
182 From time to time I write a rhyme.
183 """)
184 variants = (
185 (None, True),
186 (policy.compat32, True),
187 (policy.default, False),
188 (policy.default.clone(mangle_from_=True), True),
189 )
190 for p, mangle in variants:
191 expected = source.replace('From ', '>From ') if mangle else source
192 with self.subTest(policy=p, mangle_from_=mangle):
193 msg = self.msgmaker(self.typ(source))
194 s = self.ioclass()
195 g = self.genclass(s, policy=p)
196 g.flatten(msg)
197 self.assertEqual(s.getvalue(), self.typ(expected))
198
199 def test_compat32_max_line_length_does_not_fold_when_none(self):
200 msg = self.msgmaker(self.typ(self.refold_long_expected[0]))
201 s = self.ioclass()
202 g = self.genclass(s, policy=policy.compat32.clone(max_line_length=None))
203 g.flatten(msg)
204 self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[0]))
205
206 def test_rfc2231_wrapping(self):
207 # This is pretty much just to make sure we don't have an infinite
208 # loop; I don't expect anyone to hit this in the field.
209 msg = self.msgmaker(self.typ(textwrap.dedent("""\
210 To: nobody
211 Content-Disposition: attachment;
212 filename="afilenamelongenoghtowraphere"
213
214 None
215 """)))
216 expected = textwrap.dedent("""\
217 To: nobody
218 Content-Disposition: attachment;
219 filename*0*=us-ascii''afilename;
220 filename*1*=longenoghtowraphere
221
222 None
223 """)
224 s = self.ioclass()
225 g = self.genclass(s, policy=self.policy.clone(max_line_length=33))
226 g.flatten(msg)
227 self.assertEqual(s.getvalue(), self.typ(expected))
228
229 def test_rfc2231_wrapping_switches_to_default_len_if_too_narrow(self):
230 # This is just to make sure we don't have an infinite loop; I don't
231 # expect anyone to hit this in the field, so I'm not bothering to make
232 # the result optimal (the encoding isn't needed).
233 msg = self.msgmaker(self.typ(textwrap.dedent("""\
234 To: nobody
235 Content-Disposition: attachment;
236 filename="afilenamelongenoghtowraphere"
237
238 None
239 """)))
240 expected = textwrap.dedent("""\
241 To: nobody
242 Content-Disposition:
243 attachment;
244 filename*0*=us-ascii''afilenamelongenoghtowraphere
245
246 None
247 """)
248 s = self.ioclass()
249 g = self.genclass(s, policy=self.policy.clone(max_line_length=20))
250 g.flatten(msg)
251 self.assertEqual(s.getvalue(), self.typ(expected))
252
253 def test_keep_encoded_newlines(self):
254 msg = self.msgmaker(self.typ(textwrap.dedent("""\
255 To: nobody
256 Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: [email protected]
257
258 None
259 """)))
260 expected = textwrap.dedent("""\
261 To: nobody
262 Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: [email protected]
263
264 None
265 """)
266 s = self.ioclass()
267 g = self.genclass(s, policy=self.policy.clone(max_line_length=80))
268 g.flatten(msg)
269 self.assertEqual(s.getvalue(), self.typ(expected))
270
271 def test_keep_long_encoded_newlines(self):
272 msg = self.msgmaker(self.typ(textwrap.dedent("""\
273 To: nobody
274 Subject: Bad subject=?UTF-8?Q?=0A?=Bcc: [email protected]
275
276 None
277 """)))
278 expected = textwrap.dedent("""\
279 To: nobody
280 Subject: Bad subject
281 =?utf-8?q?=0A?=Bcc:
282 [email protected]
283
284 None
285 """)
286 s = self.ioclass()
287 g = self.genclass(s, policy=self.policy.clone(max_line_length=30))
288 g.flatten(msg)
289 self.assertEqual(s.getvalue(), self.typ(expected))
290
291
292 class TestGenerator(TestGeneratorBase, TestEmailBase):
293
294 msgfunc = staticmethod(message_from_string)
295 genclass = Generator
296 ioclass = io.StringIO
297 typ = str
298
299 def test_flatten_unicode_linesep(self):
300 source = 'Subject: one\x85 two\u2028 three\u2029 four\r\n\r\ntest body\r\n'
301 msg = self.msgmaker(self.typ(source))
302 self.assertEqual(msg['Subject'], 'one\x85 two\u2028 three\u2029 four')
303
304 expected = 'Subject: =?utf-8?b?b25lwoUgdHdv4oCoIHRocmVl4oCp?= four\n\ntest body\n'
305 s = self.ioclass()
306 g = self.genclass(s)
307 g.flatten(msg)
308 self.assertEqual(s.getvalue(), self.typ(expected))
309
310 s = self.ioclass()
311 g = self.genclass(s, policy=self.policy.clone(refold_source='all'))
312 g.flatten(msg)
313 self.assertEqual(s.getvalue(), self.typ(expected))
314
315 def test_verify_generated_headers(self):
316 # gh-121650: by default the generator prevents header injection
317 class LiteralHeader(str):
318 name = 'Header'
319 def fold(self, **kwargs):
320 return self
321
322 for text in (
323 'Value\r\nBad Injection\r\n',
324 'NoNewLine'
325 ):
326 with self.subTest(text=text):
327 message = message_from_string(
328 "Header: Value\r\n\r\nBody",
329 policy=self.policy,
330 )
331
332 del message['Header']
333 message['Header'] = LiteralHeader(text)
334
335 with self.assertRaises(email.errors.HeaderWriteError):
336 message.as_string()
337 with self.assertRaises(email.errors.HeaderWriteError):
338 message.as_bytes()
339
340
341 class TestBytesGenerator(TestGeneratorBase, TestEmailBase):
342
343 msgfunc = staticmethod(message_from_bytes)
344 genclass = BytesGenerator
345 ioclass = io.BytesIO
346 typ = lambda self, x: x.encode('ascii')
347
348 def test_defaults_handle_spaces_between_encoded_words_when_folded(self):
349 source = ("Уведомление о принятии в работу обращения для"
350 " подключения услуги")
351 expected = ('Subject: =?utf-8?b?0KPQstC10LTQvtC80LvQtdC90LjQtSDQviDQv9GA0LjQvdGP0YLQuNC4?=\n'
352 ' =?utf-8?b?INCyINGA0LDQsdC+0YLRgyDQvtCx0YDQsNGJ0LXQvdC40Y8g0LTQu9GPINC/0L4=?=\n'
353 ' =?utf-8?b?0LTQutC70Y7Rh9C10L3QuNGPINGD0YHQu9GD0LPQuA==?=\n\n').encode('ascii')
354 msg = EmailMessage()
355 msg['Subject'] = source
356 s = io.BytesIO()
357 g = BytesGenerator(s)
358 g.flatten(msg)
359 self.assertEqual(s.getvalue(), expected)
360
361 def test_defaults_handle_spaces_when_encoded_words_is_folded_in_middle(self):
362 source = ('A very long long long long long long long long long long long long '
363 'long long long long long long long long long long long súmmäry')
364 expected = ('Subject: A very long long long long long long long long long long long long\n'
365 ' long long long long long long long long long long long =?utf-8?q?s=C3=BAmm?=\n'
366 ' =?utf-8?q?=C3=A4ry?=\n\n').encode('ascii')
367 msg = EmailMessage()
368 msg['Subject'] = source
369 s = io.BytesIO()
370 g = BytesGenerator(s)
371 g.flatten(msg)
372 self.assertEqual(s.getvalue(), expected)
373
374 def test_defaults_handle_spaces_at_start_of_subject(self):
375 source = " Уведомление"
376 expected = b"Subject: =?utf-8?b?0KPQstC10LTQvtC80LvQtdC90LjQtQ==?=\n\n"
377 msg = EmailMessage()
378 msg['Subject'] = source
379 s = io.BytesIO()
380 g = BytesGenerator(s)
381 g.flatten(msg)
382 self.assertEqual(s.getvalue(), expected)
383
384 def test_defaults_handle_spaces_at_start_of_continuation_line(self):
385 source = " ф ффффффффффффффффффф ф ф"
386 expected = (b"Subject: "
387 b"=?utf-8?b?0YQg0YTRhNGE0YTRhNGE0YTRhNGE0YTRhNGE0YTRhNGE0YTRhNGE0YQ=?=\n"
388 b" =?utf-8?b?INGEINGE?=\n\n")
389 msg = EmailMessage()
390 msg['Subject'] = source
391 s = io.BytesIO()
392 g = BytesGenerator(s)
393 g.flatten(msg)
394 self.assertEqual(s.getvalue(), expected)
395
396 def test_cte_type_7bit_handles_unknown_8bit(self):
397 source = ("Subject: Maintenant je vous présente mon "
398 "collègue\n\n").encode('utf-8')
399 expected = ('Subject: Maintenant je vous =?unknown-8bit?q?'
400 'pr=C3=A9sente_mon_coll=C3=A8gue?=\n\n').encode('ascii')
401 msg = message_from_bytes(source)
402 s = io.BytesIO()
403 g = BytesGenerator(s, policy=self.policy.clone(cte_type='7bit'))
404 g.flatten(msg)
405 self.assertEqual(s.getvalue(), expected)
406
407 def test_cte_type_7bit_transforms_8bit_cte(self):
408 source = textwrap.dedent("""\
409 From: [email protected]
410 To: Dinsdale
411 Subject: Nudge nudge, wink, wink
412 Mime-Version: 1.0
413 Content-Type: text/plain; charset="latin-1"
414 Content-Transfer-Encoding: 8bit
415
416 oh là là, know what I mean, know what I mean?
417 """).encode('latin1')
418 msg = message_from_bytes(source)
419 expected = textwrap.dedent("""\
420 From: [email protected]
421 To: Dinsdale
422 Subject: Nudge nudge, wink, wink
423 Mime-Version: 1.0
424 Content-Type: text/plain; charset="iso-8859-1"
425 Content-Transfer-Encoding: quoted-printable
426
427 oh l=E0 l=E0, know what I mean, know what I mean?
428 """).encode('ascii')
429 s = io.BytesIO()
430 g = BytesGenerator(s, policy=self.policy.clone(cte_type='7bit',
431 linesep='\n'))
432 g.flatten(msg)
433 self.assertEqual(s.getvalue(), expected)
434
435 def test_smtputf8_policy(self):
436 msg = EmailMessage()
437 msg['From'] = "Páolo <fő[email protected]>"
438 msg['To'] = 'Dinsdale'
439 msg['Subject'] = 'Nudge nudge, wink, wink \u1F609'
440 msg.set_content("oh là là, know what I mean, know what I mean?")
441 expected = textwrap.dedent("""\
442 From: Páolo <fő[email protected]>
443 To: Dinsdale
444 Subject: Nudge nudge, wink, wink \u1F609
445 Content-Type: text/plain; charset="utf-8"
446 Content-Transfer-Encoding: 8bit
447 MIME-Version: 1.0
448
449 oh là là, know what I mean, know what I mean?
450 """).encode('utf-8').replace(b'\n', b'\r\n')
451 s = io.BytesIO()
452 g = BytesGenerator(s, policy=policy.SMTPUTF8)
453 g.flatten(msg)
454 self.assertEqual(s.getvalue(), expected)
455
456 def test_smtp_policy(self):
457 msg = EmailMessage()
458 msg["From"] = Address(addr_spec="[email protected]", display_name="Páolo")
459 msg["To"] = Address(addr_spec="[email protected]", display_name="Dinsdale")
460 msg["Subject"] = "Nudge nudge, wink, wink"
461 msg.set_content("oh boy, know what I mean, know what I mean?")
462 expected = textwrap.dedent("""\
463 From: =?utf-8?q?P=C3=A1olo?= <[email protected]>
464 To: Dinsdale <[email protected]>
465 Subject: Nudge nudge, wink, wink
466 Content-Type: text/plain; charset="utf-8"
467 Content-Transfer-Encoding: 7bit
468 MIME-Version: 1.0
469
470 oh boy, know what I mean, know what I mean?
471 """).encode().replace(b"\n", b"\r\n")
472 s = io.BytesIO()
473 g = BytesGenerator(s, policy=policy.SMTP)
474 g.flatten(msg)
475 self.assertEqual(s.getvalue(), expected)
476
477
478 if __name__ == '__main__':
479 unittest.main()