Debian Codegraph @

Lib/test/test_email/test_contentmanager.py

raw
1 import unittest
2 from test.test_email import TestEmailBase, parameterize
3 import textwrap
4 from email import policy
5 from email.message import EmailMessage
6 from email.contentmanager import ContentManager, raw_data_manager
7
8
9 @parameterize
10 class TestContentManager(TestEmailBase):
11
12 policy = policy.default
13 message = EmailMessage
14
15 get_key_params = {
16 'full_type': (1, 'text/plain',),
17 'maintype_only': (2, 'text',),
18 'null_key': (3, '',),
19 }
20
21 def get_key_as_get_content_key(self, order, key):
22 def foo_getter(msg, foo=None):
23 bar = msg['X-Bar-Header']
24 return foo, bar
25 cm = ContentManager()
26 cm.add_get_handler(key, foo_getter)
27 m = self._make_message()
28 m['Content-Type'] = 'text/plain'
29 m['X-Bar-Header'] = 'foo'
30 self.assertEqual(cm.get_content(m, foo='bar'), ('bar', 'foo'))
31
32 def get_key_as_get_content_key_order(self, order, key):
33 def bar_getter(msg):
34 return msg['X-Bar-Header']
35 def foo_getter(msg):
36 return msg['X-Foo-Header']
37 cm = ContentManager()
38 cm.add_get_handler(key, foo_getter)
39 for precedence, key in self.get_key_params.values():
40 if precedence > order:
41 cm.add_get_handler(key, bar_getter)
42 m = self._make_message()
43 m['Content-Type'] = 'text/plain'
44 m['X-Bar-Header'] = 'bar'
45 m['X-Foo-Header'] = 'foo'
46 self.assertEqual(cm.get_content(m), ('foo'))
47
48 def test_get_content_raises_if_unknown_mimetype_and_no_default(self):
49 cm = ContentManager()
50 m = self._make_message()
51 m['Content-Type'] = 'text/plain'
52 with self.assertRaisesRegex(KeyError, 'text/plain'):
53 cm.get_content(m)
54
55 class BaseThing(str):
56 pass
57 baseobject_full_path = __name__ + '.' + 'TestContentManager.BaseThing'
58 class Thing(BaseThing):
59 pass
60 testobject_full_path = __name__ + '.' + 'TestContentManager.Thing'
61
62 set_key_params = {
63 'type': (0, Thing,),
64 'full_path': (1, testobject_full_path,),
65 'qualname': (2, 'TestContentManager.Thing',),
66 'name': (3, 'Thing',),
67 'base_type': (4, BaseThing,),
68 'base_full_path': (5, baseobject_full_path,),
69 'base_qualname': (6, 'TestContentManager.BaseThing',),
70 'base_name': (7, 'BaseThing',),
71 'str_type': (8, str,),
72 'str_full_path': (9, 'builtins.str',),
73 'str_name': (10, 'str',), # str name and qualname are the same
74 'null_key': (11, None,),
75 }
76
77 def set_key_as_set_content_key(self, order, key):
78 def foo_setter(msg, obj, foo=None):
79 msg['X-Foo-Header'] = foo
80 msg.set_payload(obj)
81 cm = ContentManager()
82 cm.add_set_handler(key, foo_setter)
83 m = self._make_message()
84 msg_obj = self.Thing()
85 cm.set_content(m, msg_obj, foo='bar')
86 self.assertEqual(m['X-Foo-Header'], 'bar')
87 self.assertEqual(m.get_payload(), msg_obj)
88
89 def set_key_as_set_content_key_order(self, order, key):
90 def foo_setter(msg, obj):
91 msg['X-FooBar-Header'] = 'foo'
92 msg.set_payload(obj)
93 def bar_setter(msg, obj):
94 msg['X-FooBar-Header'] = 'bar'
95 cm = ContentManager()
96 cm.add_set_handler(key, foo_setter)
97 for precedence, key in self.get_key_params.values():
98 if precedence > order:
99 cm.add_set_handler(key, bar_setter)
100 m = self._make_message()
101 msg_obj = self.Thing()
102 cm.set_content(m, msg_obj)
103 self.assertEqual(m['X-FooBar-Header'], 'foo')
104 self.assertEqual(m.get_payload(), msg_obj)
105
106 def test_set_content_raises_if_unknown_type_and_no_default(self):
107 cm = ContentManager()
108 m = self._make_message()
109 msg_obj = self.Thing()
110 with self.assertRaisesRegex(KeyError, self.testobject_full_path):
111 cm.set_content(m, msg_obj)
112
113 def test_set_content_raises_if_called_on_multipart(self):
114 cm = ContentManager()
115 m = self._make_message()
116 m['Content-Type'] = 'multipart/foo'
117 with self.assertRaises(TypeError):
118 cm.set_content(m, 'test')
119
120 def test_set_content_calls_clear_content(self):
121 m = self._make_message()
122 m['Content-Foo'] = 'bar'
123 m['Content-Type'] = 'text/html'
124 m['To'] = 'test'
125 m.set_payload('abc')
126 cm = ContentManager()
127 cm.add_set_handler(str, lambda *args, **kw: None)
128 m.set_content('xyz', content_manager=cm)
129 self.assertIsNone(m['Content-Foo'])
130 self.assertIsNone(m['Content-Type'])
131 self.assertEqual(m['To'], 'test')
132 self.assertIsNone(m.get_payload())
133
134
135 @parameterize
136 class TestRawDataManager(TestEmailBase):
137 # Note: these tests are dependent on the order in which headers are added
138 # to the message objects by the code. There's no defined ordering in
139 # RFC5322/MIME, so this makes the tests more fragile than the standards
140 # require. However, if the header order changes it is best to understand
141 # *why*, and make sure it isn't a subtle bug in whatever change was
142 # applied.
143
144 policy = policy.default.clone(max_line_length=60,
145 content_manager=raw_data_manager)
146 message = EmailMessage
147
148 def test_get_text_plain(self):
149 m = self._str_msg(textwrap.dedent("""\
150 Content-Type: text/plain
151
152 Basic text.
153 """))
154 self.assertEqual(raw_data_manager.get_content(m), "Basic text.\n")
155
156 def test_get_text_html(self):
157 m = self._str_msg(textwrap.dedent("""\
158 Content-Type: text/html
159
160 <p>Basic text.</p>
161 """))
162 self.assertEqual(raw_data_manager.get_content(m),
163 "<p>Basic text.</p>\n")
164
165 def test_get_text_plain_latin1(self):
166 m = self._bytes_msg(textwrap.dedent("""\
167 Content-Type: text/plain; charset=latin1
168
169 Basìc tëxt.
170 """).encode('latin1'))
171 self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n")
172
173 def test_get_text_plain_latin1_quoted_printable(self):
174 m = self._str_msg(textwrap.dedent("""\
175 Content-Type: text/plain; charset="latin-1"
176 Content-Transfer-Encoding: quoted-printable
177
178 Bas=ECc t=EBxt.
179 """))
180 self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n")
181
182 def test_get_text_plain_utf8_base64(self):
183 m = self._str_msg(textwrap.dedent("""\
184 Content-Type: text/plain; charset="utf8"
185 Content-Transfer-Encoding: base64
186
187 QmFzw6xjIHTDq3h0Lgo=
188 """))
189 self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n")
190
191 def test_get_text_plain_bad_utf8_quoted_printable(self):
192 m = self._str_msg(textwrap.dedent("""\
193 Content-Type: text/plain; charset="utf8"
194 Content-Transfer-Encoding: quoted-printable
195
196 Bas=c3=acc t=c3=abxt=fd.
197 """))
198 self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt�.\n")
199
200 def test_get_text_plain_bad_utf8_quoted_printable_ignore_errors(self):
201 m = self._str_msg(textwrap.dedent("""\
202 Content-Type: text/plain; charset="utf8"
203 Content-Transfer-Encoding: quoted-printable
204
205 Bas=c3=acc t=c3=abxt=fd.
206 """))
207 self.assertEqual(raw_data_manager.get_content(m, errors='ignore'),
208 "Basìc tëxt.\n")
209
210 def test_get_text_plain_utf8_base64_recoverable_bad_CTE_data(self):
211 m = self._str_msg(textwrap.dedent("""\
212 Content-Type: text/plain; charset="utf8"
213 Content-Transfer-Encoding: base64
214
215 QmFzw6xjIHTDq3h0Lgo\xFF=
216 """))
217 self.assertEqual(raw_data_manager.get_content(m, errors='ignore'),
218 "Basìc tëxt.\n")
219
220 def test_get_text_invalid_keyword(self):
221 m = self._str_msg(textwrap.dedent("""\
222 Content-Type: text/plain
223
224 Basic text.
225 """))
226 with self.assertRaises(TypeError):
227 raw_data_manager.get_content(m, foo='ignore')
228
229 def test_get_non_text(self):
230 template = textwrap.dedent("""\
231 Content-Type: {}
232 Content-Transfer-Encoding: base64
233
234 Ym9ndXMgZGF0YQ==
235 """)
236 for maintype in 'audio image video application'.split():
237 with self.subTest(maintype=maintype):
238 m = self._str_msg(template.format(maintype+'/foo'))
239 self.assertEqual(raw_data_manager.get_content(m), b"bogus data")
240
241 def test_get_non_text_invalid_keyword(self):
242 m = self._str_msg(textwrap.dedent("""\
243 Content-Type: image/jpg
244 Content-Transfer-Encoding: base64
245
246 Ym9ndXMgZGF0YQ==
247 """))
248 with self.assertRaises(TypeError):
249 raw_data_manager.get_content(m, errors='ignore')
250
251 def test_get_raises_on_multipart(self):
252 m = self._str_msg(textwrap.dedent("""\
253 Content-Type: multipart/mixed; boundary="==="
254
255 --===
256 --===--
257 """))
258 with self.assertRaises(KeyError):
259 raw_data_manager.get_content(m)
260
261 def test_get_message_rfc822_and_external_body(self):
262 template = textwrap.dedent("""\
263 Content-Type: message/{}
264
265 To: [email protected]
266 From: [email protected]
267 Subject: example
268
269 an example message
270 """)
271 for subtype in 'rfc822 external-body'.split():
272 with self.subTest(subtype=subtype):
273 m = self._str_msg(template.format(subtype))
274 sub_msg = raw_data_manager.get_content(m)
275 self.assertIsInstance(sub_msg, self.message)
276 self.assertEqual(raw_data_manager.get_content(sub_msg),
277 "an example message\n")
278 self.assertEqual(sub_msg['to'], '[email protected]')
279 self.assertEqual(sub_msg['from'].addresses[0].username, 'bar')
280
281 def test_get_message_non_rfc822_or_external_body_yields_bytes(self):
282 m = self._str_msg(textwrap.dedent("""\
283 Content-Type: message/partial
284
285 To: [email protected]
286 From: [email protected]
287 Subject: example
288
289 The real body is in another message.
290 """))
291 self.assertStartsWith(raw_data_manager.get_content(m), b'To: foo@ex')
292
293 def test_set_text_plain(self):
294 m = self._make_message()
295 content = "Simple message.\n"
296 raw_data_manager.set_content(m, content)
297 self.assertEqual(str(m), textwrap.dedent("""\
298 Content-Type: text/plain; charset="utf-8"
299 Content-Transfer-Encoding: 7bit
300
301 Simple message.
302 """))
303 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
304 self.assertEqual(m.get_content(), content)
305
306 def test_set_text_plain_null(self):
307 m = self._make_message()
308 content = ''
309 raw_data_manager.set_content(m, content)
310 self.assertEqual(str(m), textwrap.dedent("""\
311 Content-Type: text/plain; charset="utf-8"
312 Content-Transfer-Encoding: 7bit
313
314
315 """))
316 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), '\n')
317 self.assertEqual(m.get_content(), '\n')
318
319 def test_set_text_html(self):
320 m = self._make_message()
321 content = "<p>Simple message.</p>\n"
322 raw_data_manager.set_content(m, content, subtype='html')
323 self.assertEqual(str(m), textwrap.dedent("""\
324 Content-Type: text/html; charset="utf-8"
325 Content-Transfer-Encoding: 7bit
326
327 <p>Simple message.</p>
328 """))
329 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
330 self.assertEqual(m.get_content(), content)
331
332 def test_set_text_charset_latin_1(self):
333 m = self._make_message()
334 content = "Simple message.\n"
335 raw_data_manager.set_content(m, content, charset='latin-1')
336 self.assertEqual(str(m), textwrap.dedent("""\
337 Content-Type: text/plain; charset="iso-8859-1"
338 Content-Transfer-Encoding: 7bit
339
340 Simple message.
341 """))
342 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
343 self.assertEqual(m.get_content(), content)
344
345 def test_set_text_charset_shift_jis(self):
346 m = self._make_message()
347 content = "\u65e5\u672c\u8a9e\n"
348 raw_data_manager.set_content(m, content, charset='shift_jis')
349 self.assertEqual(m['Content-Type'], 'text/plain; charset="iso-2022-jp"')
350 self.assertEqual(m.get_payload(decode=True), content.encode('iso-2022-jp'))
351 self.assertEqual(m.get_content(), content)
352 self.assertEqual(str(m), textwrap.dedent("""\
353 Content-Type: text/plain; charset="iso-2022-jp"
354 Content-Transfer-Encoding: 7bit
355
356 \x1b$BF|K\\8l\x1b(B
357 """))
358 self.assertEqual(bytes(m), textwrap.dedent("""\
359 Content-Type: text/plain; charset="iso-2022-jp"
360 Content-Transfer-Encoding: 7bit
361
362 \u65e5\u672c\u8a9e
363 """).encode('iso-2022-jp'))
364
365 def test_set_text_charset_euc_jp(self):
366 m = self._make_message()
367 content = "\u65e5\u672c\u8a9e\n"
368 raw_data_manager.set_content(m, content, charset='euc-jp')
369 self.assertEqual(m['Content-Type'], 'text/plain; charset="iso-2022-jp"')
370 self.assertEqual(m.get_payload(decode=True), content.encode('iso-2022-jp'))
371 self.assertEqual(m.get_content(), content)
372 self.assertEqual(str(m), textwrap.dedent("""\
373 Content-Type: text/plain; charset="iso-2022-jp"
374 Content-Transfer-Encoding: 7bit
375
376 \x1b$BF|K\\8l\x1b(B
377 """))
378 self.assertEqual(bytes(m), textwrap.dedent("""\
379 Content-Type: text/plain; charset="iso-2022-jp"
380 Content-Transfer-Encoding: 7bit
381
382 \u65e5\u672c\u8a9e
383 """).encode('iso-2022-jp'))
384
385 def test_set_text_plain_long_line_heuristics(self):
386 m = self._make_message()
387 content = ("Simple but long message that is over 78 characters"
388 " long to force transfer encoding.\n")
389 raw_data_manager.set_content(m, content)
390 self.assertEqual(str(m), textwrap.dedent("""\
391 Content-Type: text/plain; charset="utf-8"
392 Content-Transfer-Encoding: quoted-printable
393
394 Simple but long message that is over 78 characters long to =
395 force transfer encoding.
396 """))
397 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
398 self.assertEqual(m.get_content(), content)
399
400 def test_set_text_short_line_minimal_non_ascii_heuristics(self):
401 m = self._make_message()
402 content = "et là il est monté sur moi et il commence à m'éto.\n"
403 raw_data_manager.set_content(m, content)
404 self.assertEqual(bytes(m), textwrap.dedent("""\
405 Content-Type: text/plain; charset="utf-8"
406 Content-Transfer-Encoding: 8bit
407
408 et là il est monté sur moi et il commence à m'éto.
409 """).encode('utf-8'))
410 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
411 self.assertEqual(m.get_content(), content)
412
413 def test_set_text_long_line_minimal_non_ascii_heuristics(self):
414 m = self._make_message()
415 content = ("j'ai un problème de python. il est sorti de son"
416 " vivarium. et là il est monté sur moi et il commence"
417 " à m'éto.\n")
418 raw_data_manager.set_content(m, content)
419 self.assertEqual(bytes(m), textwrap.dedent("""\
420 Content-Type: text/plain; charset="utf-8"
421 Content-Transfer-Encoding: quoted-printable
422
423 j'ai un probl=C3=A8me de python. il est sorti de son vivari=
424 um. et l=C3=A0 il est mont=C3=A9 sur moi et il commence =
425 =C3=A0 m'=C3=A9to.
426 """).encode('utf-8'))
427 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
428 self.assertEqual(m.get_content(), content)
429
430 def test_set_text_11_lines_long_line_minimal_non_ascii_heuristics(self):
431 m = self._make_message()
432 content = '\n'*10 + (
433 "j'ai un problème de python. il est sorti de son"
434 " vivarium. et là il est monté sur moi et il commence"
435 " à m'éto.\n")
436 raw_data_manager.set_content(m, content)
437 self.assertEqual(bytes(m), textwrap.dedent("""\
438 Content-Type: text/plain; charset="utf-8"
439 Content-Transfer-Encoding: quoted-printable
440 """ + '\n'*10 + """
441 j'ai un probl=C3=A8me de python. il est sorti de son vivari=
442 um. et l=C3=A0 il est mont=C3=A9 sur moi et il commence =
443 =C3=A0 m'=C3=A9to.
444 """).encode('utf-8'))
445 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
446 self.assertEqual(m.get_content(), content)
447
448 def test_set_text_maximal_non_ascii_heuristics(self):
449 m = self._make_message()
450 content = "áàäéèęöő.\n"
451 raw_data_manager.set_content(m, content)
452 self.assertEqual(bytes(m), textwrap.dedent("""\
453 Content-Type: text/plain; charset="utf-8"
454 Content-Transfer-Encoding: 8bit
455
456 áàäéèęöő.
457 """).encode('utf-8'))
458 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
459 self.assertEqual(m.get_content(), content)
460
461 def test_set_text_11_lines_maximal_non_ascii_heuristics(self):
462 m = self._make_message()
463 content = '\n'*10 + "áàäéèęöő.\n"
464 raw_data_manager.set_content(m, content)
465 self.assertEqual(bytes(m), textwrap.dedent("""\
466 Content-Type: text/plain; charset="utf-8"
467 Content-Transfer-Encoding: 8bit
468 """ + '\n'*10 + """
469 áàäéèęöő.
470 """).encode('utf-8'))
471 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
472 self.assertEqual(m.get_content(), content)
473
474 def test_set_text_long_line_maximal_non_ascii_heuristics(self):
475 m = self._make_message()
476 content = ("áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő"
477 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő"
478 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő.\n")
479 raw_data_manager.set_content(m, content)
480 self.assertEqual(bytes(m), textwrap.dedent("""\
481 Content-Type: text/plain; charset="utf-8"
482 Content-Transfer-Encoding: base64
483
484 w6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOgw6TDqcOoxJnD
485 tsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOgw6TDqcOo
486 xJnDtsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOgw6TD
487 qcOoxJnDtsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOg
488 w6TDqcOoxJnDtsWRLgo=
489 """).encode('utf-8'))
490 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
491 self.assertEqual(m.get_content(), content)
492
493 def test_set_text_11_lines_long_line_maximal_non_ascii_heuristics(self):
494 # Yes, it chooses "wrong" here. It's a heuristic. So this result
495 # could change if we come up with a better heuristic.
496 m = self._make_message()
497 content = ('\n'*10 +
498 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő"
499 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő"
500 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő.\n")
501 raw_data_manager.set_content(m, "\n"*10 +
502 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő"
503 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő"
504 "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő.\n")
505 self.assertEqual(bytes(m), textwrap.dedent("""\
506 Content-Type: text/plain; charset="utf-8"
507 Content-Transfer-Encoding: quoted-printable
508 """ + '\n'*10 + """
509 =C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=
510 =A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=
511 =C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=
512 =A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=
513 =C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=
514 =91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=
515 =C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=
516 =A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=
517 =C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=
518 =99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=
519 =C5=91.
520 """).encode('utf-8'))
521 self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content)
522 self.assertEqual(m.get_content(), content)
523
524 def test_set_text_non_ascii_with_cte_7bit_raises(self):
525 m = self._make_message()
526 with self.assertRaises(UnicodeError):
527 raw_data_manager.set_content(m,"áàäéèęöő.\n", cte='7bit')
528
529 def test_set_text_non_ascii_with_charset_ascii_raises(self):
530 m = self._make_message()
531 with self.assertRaises(UnicodeError):
532 raw_data_manager.set_content(m,"áàäéèęöő.\n", charset='ascii')
533
534 def test_set_text_non_ascii_with_cte_7bit_and_charset_ascii_raises(self):
535 m = self._make_message()
536 with self.assertRaises(UnicodeError):
537 raw_data_manager.set_content(m,"áàäéèęöő.\n", cte='7bit', charset='ascii')
538
539 def test_set_message(self):
540 m = self._make_message()
541 m['Subject'] = "Forwarded message"
542 content = self._make_message()
543 content['To'] = '[email protected]'
544 content['From'] = '[email protected]'
545 content['Subject'] = "get back in your box"
546 content.set_content("Or face the comfy chair.")
547 raw_data_manager.set_content(m, content)
548 self.assertEqual(str(m), textwrap.dedent("""\
549 Subject: Forwarded message
550 Content-Type: message/rfc822
551 Content-Transfer-Encoding: 8bit
552
553 To: [email protected]
554 From: [email protected]
555 Subject: get back in your box
556 Content-Type: text/plain; charset="utf-8"
557 Content-Transfer-Encoding: 7bit
558 MIME-Version: 1.0
559
560 Or face the comfy chair.
561 """))
562 payload = m.get_payload(0)
563 self.assertIsInstance(payload, self.message)
564 self.assertEqual(str(payload), str(content))
565 self.assertIsInstance(m.get_content(), self.message)
566 self.assertEqual(str(m.get_content()), str(content))
567
568 def test_set_message_with_non_ascii_and_coercion_to_7bit(self):
569 m = self._make_message()
570 m['Subject'] = "Escape report"
571 content = self._make_message()
572 content['To'] = '[email protected]'
573 content['From'] = '[email protected]'
574 content['Subject'] = "Help"
575 content.set_content("j'ai un problème de python. il est sorti de son"
576 " vivarium.")
577 raw_data_manager.set_content(m, content)
578 self.assertEqual(bytes(m), textwrap.dedent("""\
579 Subject: Escape report
580 Content-Type: message/rfc822
581 Content-Transfer-Encoding: 8bit
582
583 To: [email protected]
584 From: [email protected]
585 Subject: Help
586 Content-Type: text/plain; charset="utf-8"
587 Content-Transfer-Encoding: 8bit
588 MIME-Version: 1.0
589
590 j'ai un problème de python. il est sorti de son vivarium.
591 """).encode('utf-8'))
592 # The choice of base64 for the body encoding is because generator
593 # doesn't bother with heuristics and uses it unconditionally for utf-8
594 # text.
595 # XXX: the first cte should be 7bit, too...that's a generator bug.
596 # XXX: the line length in the body also looks like a generator bug.
597 self.assertEqual(m.as_string(maxheaderlen=self.policy.max_line_length),
598 textwrap.dedent("""\
599 Subject: Escape report
600 Content-Type: message/rfc822
601 Content-Transfer-Encoding: 8bit
602
603 To: [email protected]
604 From: [email protected]
605 Subject: Help
606 Content-Type: text/plain; charset="utf-8"
607 Content-Transfer-Encoding: base64
608 MIME-Version: 1.0
609
610 aidhaSB1biBwcm9ibMOobWUgZGUgcHl0aG9uLiBpbCBlc3Qgc29ydGkgZGUgc29uIHZpdmFyaXVt
611 Lgo=
612 """))
613 self.assertIsInstance(m.get_content(), self.message)
614 self.assertEqual(str(m.get_content()), str(content))
615
616 def test_set_message_invalid_cte_raises(self):
617 m = self._make_message()
618 content = self._make_message()
619 for cte in 'quoted-printable base64'.split():
620 for subtype in 'rfc822 external-body'.split():
621 with self.subTest(cte=cte, subtype=subtype):
622 with self.assertRaises(ValueError) as ar:
623 m.set_content(content, subtype, cte=cte)
624 exc = str(ar.exception)
625 self.assertIn(cte, exc)
626 self.assertIn(subtype, exc)
627 subtype = 'external-body'
628 for cte in '8bit binary'.split():
629 with self.subTest(cte=cte, subtype=subtype):
630 with self.assertRaises(ValueError) as ar:
631 m.set_content(content, subtype, cte=cte)
632 exc = str(ar.exception)
633 self.assertIn(cte, exc)
634 self.assertIn(subtype, exc)
635
636 def test_set_image_jpg(self):
637 for content in (b"bogus content",
638 bytearray(b"bogus content"),
639 memoryview(b"bogus content")):
640 with self.subTest(content=content):
641 m = self._make_message()
642 raw_data_manager.set_content(m, content, 'image', 'jpeg')
643 self.assertEqual(str(m), textwrap.dedent("""\
644 Content-Type: image/jpeg
645 Content-Transfer-Encoding: base64
646
647 Ym9ndXMgY29udGVudA==
648 """))
649 self.assertEqual(m.get_payload(decode=True), content)
650 self.assertEqual(m.get_content(), content)
651
652 def test_set_audio_aif_with_quoted_printable_cte(self):
653 # Why you would use qp, I don't know, but it is technically supported.
654 # XXX: the incorrect line length is because binascii.b2a_qp doesn't
655 # support a line length parameter, but we must use it to get newline
656 # encoding.
657 # XXX: what about that lack of tailing newline? Do we actually handle
658 # that correctly in all cases? That is, if the *source* has an
659 # unencoded newline, do we add an extra newline to the returned payload
660 # or not? And can that actually be disambiguated based on the RFC?
661 m = self._make_message()
662 content = b'b\xFFgus\tcon\nt\rent ' + b'z'*100
663 m.set_content(content, 'audio', 'aif', cte='quoted-printable')
664 self.assertEqual(bytes(m), textwrap.dedent("""\
665 Content-Type: audio/aif
666 Content-Transfer-Encoding: quoted-printable
667 MIME-Version: 1.0
668
669 b=FFgus=09con=0At=0Dent=20zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz=
670 zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz""").encode('latin-1'))
671 self.assertEqual(m.get_payload(decode=True), content)
672 self.assertEqual(m.get_content(), content)
673
674 def test_set_video_mpeg_with_binary_cte(self):
675 m = self._make_message()
676 content = b'b\xFFgus\tcon\nt\rent ' + b'z'*100
677 m.set_content(content, 'video', 'mpeg', cte='binary')
678 self.assertEqual(bytes(m), textwrap.dedent("""\
679 Content-Type: video/mpeg
680 Content-Transfer-Encoding: binary
681 MIME-Version: 1.0
682
683 """).encode('ascii') +
684 # XXX: the second \n ought to be a \r, but generator gets it wrong.
685 # THIS MEANS WE DON'T ACTUALLY SUPPORT THE 'binary' CTE.
686 b'b\xFFgus\tcon\nt\nent zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz' +
687 b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz')
688 self.assertEqual(m.get_payload(decode=True), content)
689 self.assertEqual(m.get_content(), content)
690
691 def test_set_application_octet_stream_with_8bit_cte(self):
692 # In 8bit mode, universal line end logic applies. It is up to the
693 # application to make sure the lines are short enough; we don't check.
694 m = self._make_message()
695 content = b'b\xFFgus\tcon\nt\rent\n' + b'z'*60 + b'\n'
696 m.set_content(content, 'application', 'octet-stream', cte='8bit')
697 self.assertEqual(bytes(m), textwrap.dedent("""\
698 Content-Type: application/octet-stream
699 Content-Transfer-Encoding: 8bit
700 MIME-Version: 1.0
701
702 """).encode('ascii') +
703 b'b\xFFgus\tcon\nt\nent\n' +
704 b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n')
705 self.assertEqual(m.get_payload(decode=True), content)
706 self.assertEqual(m.get_content(), content)
707
708 def test_set_headers_from_header_objects(self):
709 m = self._make_message()
710 content = "Simple message.\n"
711 header_factory = self.policy.header_factory
712 raw_data_manager.set_content(m, content, headers=(
713 header_factory("To", "[email protected]"),
714 header_factory("From", "[email protected]"),
715 header_factory("Subject", "I'm talking to myself.")))
716 self.assertEqual(str(m), textwrap.dedent("""\
717 Content-Type: text/plain; charset="utf-8"
718 To: [email protected]
719 From: [email protected]
720 Subject: I'm talking to myself.
721 Content-Transfer-Encoding: 7bit
722
723 Simple message.
724 """))
725
726 def test_set_headers_from_strings(self):
727 m = self._make_message()
728 content = "Simple message.\n"
729 raw_data_manager.set_content(m, content, headers=(
730 "X-Foo-Header: foo",
731 "X-Bar-Header: bar",))
732 self.assertEqual(str(m), textwrap.dedent("""\
733 Content-Type: text/plain; charset="utf-8"
734 X-Foo-Header: foo
735 X-Bar-Header: bar
736 Content-Transfer-Encoding: 7bit
737
738 Simple message.
739 """))
740
741 def test_set_headers_with_invalid_duplicate_string_header_raises(self):
742 m = self._make_message()
743 content = "Simple message.\n"
744 with self.assertRaisesRegex(ValueError, 'Content-Type'):
745 raw_data_manager.set_content(m, content, headers=(
746 "Content-Type: foo/bar",)
747 )
748
749 def test_set_headers_with_invalid_duplicate_header_header_raises(self):
750 m = self._make_message()
751 content = "Simple message.\n"
752 header_factory = self.policy.header_factory
753 with self.assertRaisesRegex(ValueError, 'Content-Type'):
754 raw_data_manager.set_content(m, content, headers=(
755 header_factory("Content-Type", " foo/bar"),)
756 )
757
758 def test_set_headers_with_defective_string_header_raises(self):
759 m = self._make_message()
760 content = "Simple message.\n"
761 with self.assertRaisesRegex(ValueError, 'a@fairly@@invalid@address'):
762 raw_data_manager.set_content(m, content, headers=(
763 'To: a@fairly@@invalid@address',)
764 )
765 print(m['To'].defects)
766
767 def test_set_headers_with_defective_header_header_raises(self):
768 m = self._make_message()
769 content = "Simple message.\n"
770 header_factory = self.policy.header_factory
771 with self.assertRaisesRegex(ValueError, 'a@fairly@@invalid@address'):
772 raw_data_manager.set_content(m, content, headers=(
773 header_factory('To', 'a@fairly@@invalid@address'),)
774 )
775 print(m['To'].defects)
776
777 def test_set_disposition_inline(self):
778 m = self._make_message()
779 m.set_content('foo', disposition='inline')
780 self.assertEqual(m['Content-Disposition'], 'inline')
781
782 def test_set_disposition_attachment(self):
783 m = self._make_message()
784 m.set_content('foo', disposition='attachment')
785 self.assertEqual(m['Content-Disposition'], 'attachment')
786
787 def test_set_disposition_foo(self):
788 m = self._make_message()
789 m.set_content('foo', disposition='foo')
790 self.assertEqual(m['Content-Disposition'], 'foo')
791
792 # XXX: we should have a 'strict' policy mode (beyond raise_on_defect) that
793 # would cause 'foo' above to raise.
794
795 def test_set_filename(self):
796 m = self._make_message()
797 m.set_content('foo', filename='bar.txt')
798 self.assertEqual(m['Content-Disposition'],
799 'attachment; filename="bar.txt"')
800
801 def test_set_filename_and_disposition_inline(self):
802 m = self._make_message()
803 m.set_content('foo', disposition='inline', filename='bar.txt')
804 self.assertEqual(m['Content-Disposition'], 'inline; filename="bar.txt"')
805
806 def test_set_non_ascii_filename(self):
807 m = self._make_message()
808 m.set_content('foo', filename='ábárî.txt')
809 self.assertEqual(bytes(m), textwrap.dedent("""\
810 Content-Type: text/plain; charset="utf-8"
811 Content-Transfer-Encoding: 7bit
812 Content-Disposition: attachment;
813 filename*=utf-8''%C3%A1b%C3%A1r%C3%AE.txt
814 MIME-Version: 1.0
815
816 foo
817 """).encode('ascii'))
818
819 def test_set_content_bytes_cte_7bit(self):
820 m = self._make_message()
821 m.set_content(b'ASCII-only message.\n',
822 maintype='application', subtype='octet-stream', cte='7bit')
823 self.assertEqual(str(m), textwrap.dedent("""\
824 Content-Type: application/octet-stream
825 Content-Transfer-Encoding: 7bit
826 MIME-Version: 1.0
827
828 ASCII-only message.
829 """))
830
831 content_object_params = {
832 'text_plain': ('content', ()),
833 'text_html': ('content', ('html',)),
834 'application_octet_stream': (b'content',
835 ('application', 'octet_stream')),
836 'image_jpeg': (b'content', ('image', 'jpeg')),
837 'message_rfc822': (message(), ()),
838 'message_external_body': (message(), ('external-body',)),
839 }
840
841 def content_object_as_header_receiver(self, obj, mimetype):
842 m = self._make_message()
843 m.set_content(obj, *mimetype, headers=(
844 'To: [email protected]',
845 'From: [email protected]'))
846 self.assertEqual(m['to'], '[email protected]')
847 self.assertEqual(m['from'], '[email protected]')
848
849 def content_object_as_disposition_inline_receiver(self, obj, mimetype):
850 m = self._make_message()
851 m.set_content(obj, *mimetype, disposition='inline')
852 self.assertEqual(m['Content-Disposition'], 'inline')
853
854 def content_object_as_non_ascii_filename_receiver(self, obj, mimetype):
855 m = self._make_message()
856 m.set_content(obj, *mimetype, disposition='inline', filename='bár.txt')
857 self.assertEqual(m['Content-Disposition'], 'inline; filename="bár.txt"')
858 self.assertEqual(m.get_filename(), "bár.txt")
859 self.assertEqual(m['Content-Disposition'].params['filename'], "bár.txt")
860
861 def content_object_as_cid_receiver(self, obj, mimetype):
862 m = self._make_message()
863 m.set_content(obj, *mimetype, cid='some_random_stuff')
864 self.assertEqual(m['Content-ID'], 'some_random_stuff')
865
866 def content_object_as_params_receiver(self, obj, mimetype):
867 m = self._make_message()
868 params = {'foo': 'bár', 'abc': 'xyz'}
869 m.set_content(obj, *mimetype, params=params)
870 if isinstance(obj, str):
871 params['charset'] = 'utf-8'
872 self.assertEqual(m['Content-Type'].params, params)
873
874
875 if __name__ == '__main__':
876 unittest.main()