Debian Codegraph @

Lib/test/test_email/test_headerregistry.py

raw
1 import datetime
2 import textwrap
3 import unittest
4 from email import errors
5 from email import policy
6 from email.message import Message
7 from test.test_email import TestEmailBase, parameterize
8 from email import headerregistry
9 from email.headerregistry import Address, Group
10 from email.header import decode_header
11 from test.support import ALWAYS_EQ
12
13
14 DITTO = object()
15
16
17 class TestHeaderRegistry(TestEmailBase):
18
19 def test_arbitrary_name_unstructured(self):
20 factory = headerregistry.HeaderRegistry()
21 h = factory('foobar', 'test')
22 self.assertIsInstance(h, headerregistry.BaseHeader)
23 self.assertIsInstance(h, headerregistry.UnstructuredHeader)
24
25 def test_name_case_ignored(self):
26 factory = headerregistry.HeaderRegistry()
27 # Whitebox check that test is valid
28 self.assertNotIn('Subject', factory.registry)
29 h = factory('Subject', 'test')
30 self.assertIsInstance(h, headerregistry.BaseHeader)
31 self.assertIsInstance(h, headerregistry.UniqueUnstructuredHeader)
32
33 class FooBase:
34 def __init__(self, *args, **kw):
35 pass
36
37 def test_override_default_base_class(self):
38 factory = headerregistry.HeaderRegistry(base_class=self.FooBase)
39 h = factory('foobar', 'test')
40 self.assertIsInstance(h, self.FooBase)
41 self.assertIsInstance(h, headerregistry.UnstructuredHeader)
42
43 class FooDefault:
44 parse = headerregistry.UnstructuredHeader.parse
45
46 def test_override_default_class(self):
47 factory = headerregistry.HeaderRegistry(default_class=self.FooDefault)
48 h = factory('foobar', 'test')
49 self.assertIsInstance(h, headerregistry.BaseHeader)
50 self.assertIsInstance(h, self.FooDefault)
51
52 def test_override_default_class_only_overrides_default(self):
53 factory = headerregistry.HeaderRegistry(default_class=self.FooDefault)
54 h = factory('subject', 'test')
55 self.assertIsInstance(h, headerregistry.BaseHeader)
56 self.assertIsInstance(h, headerregistry.UniqueUnstructuredHeader)
57
58 def test_dont_use_default_map(self):
59 factory = headerregistry.HeaderRegistry(use_default_map=False)
60 h = factory('subject', 'test')
61 self.assertIsInstance(h, headerregistry.BaseHeader)
62 self.assertIsInstance(h, headerregistry.UnstructuredHeader)
63
64 def test_map_to_type(self):
65 factory = headerregistry.HeaderRegistry()
66 h1 = factory('foobar', 'test')
67 factory.map_to_type('foobar', headerregistry.UniqueUnstructuredHeader)
68 h2 = factory('foobar', 'test')
69 self.assertIsInstance(h1, headerregistry.BaseHeader)
70 self.assertIsInstance(h1, headerregistry.UnstructuredHeader)
71 self.assertIsInstance(h2, headerregistry.BaseHeader)
72 self.assertIsInstance(h2, headerregistry.UniqueUnstructuredHeader)
73
74
75 class TestHeaderBase(TestEmailBase):
76
77 factory = headerregistry.HeaderRegistry()
78
79 def make_header(self, name, value):
80 return self.factory(name, value)
81
82
83 class TestBaseHeaderFeatures(TestHeaderBase):
84
85 def test_str(self):
86 h = self.make_header('subject', 'this is a test')
87 self.assertIsInstance(h, str)
88 self.assertEqual(h, 'this is a test')
89 self.assertEqual(str(h), 'this is a test')
90
91 def test_substr(self):
92 h = self.make_header('subject', 'this is a test')
93 self.assertEqual(h[5:7], 'is')
94
95 def test_has_name(self):
96 h = self.make_header('subject', 'this is a test')
97 self.assertEqual(h.name, 'subject')
98
99 def _test_attr_ro(self, attr):
100 h = self.make_header('subject', 'this is a test')
101 with self.assertRaises(AttributeError):
102 setattr(h, attr, 'foo')
103
104 def test_name_read_only(self):
105 self._test_attr_ro('name')
106
107 def test_defects_read_only(self):
108 self._test_attr_ro('defects')
109
110 def test_defects_is_tuple(self):
111 h = self.make_header('subject', 'this is a test')
112 self.assertEqual(len(h.defects), 0)
113 self.assertIsInstance(h.defects, tuple)
114 # Make sure it is still true when there are defects.
115 h = self.make_header('date', '')
116 self.assertEqual(len(h.defects), 1)
117 self.assertIsInstance(h.defects, tuple)
118
119 # XXX: FIXME
120 #def test_CR_in_value(self):
121 # # XXX: this also re-raises the issue of embedded headers,
122 # # need test and solution for that.
123 # value = '\r'.join(['this is', ' a test'])
124 # h = self.make_header('subject', value)
125 # self.assertEqual(h, value)
126 # self.assertDefectsEqual(h.defects, [errors.ObsoleteHeaderDefect])
127
128
129 @parameterize
130 class TestUnstructuredHeader(TestHeaderBase):
131
132 def string_as_value(self,
133 source,
134 decoded,
135 *args):
136 l = len(args)
137 defects = args[0] if l>0 else []
138 header = 'Subject:' + (' ' if source else '')
139 folded = header + (args[1] if l>1 else source) + '\n'
140 h = self.make_header('Subject', source)
141 self.assertEqual(h, decoded)
142 self.assertDefectsEqual(h.defects, defects)
143 self.assertEqual(h.fold(policy=policy.default), folded)
144
145 string_params = {
146
147 'rfc2047_simple_quopri': (
148 '=?utf-8?q?this_is_a_test?=',
149 'this is a test',
150 [],
151 'this is a test'),
152
153 'rfc2047_gb2312_base64': (
154 '=?gb2312?b?1eLKx9bQzsSy4srUo6E=?=',
155 '\u8fd9\u662f\u4e2d\u6587\u6d4b\u8bd5\uff01',
156 [],
157 '=?utf-8?b?6L+Z5piv5Lit5paH5rWL6K+V77yB?='),
158
159 'rfc2047_simple_nonascii_quopri': (
160 '=?utf-8?q?=C3=89ric?=',
161 'Éric'),
162
163 'rfc2047_quopri_with_regular_text': (
164 'The =?utf-8?q?=C3=89ric=2C?= Himself',
165 'The Éric, Himself'),
166
167 }
168
169
170 @parameterize
171 class TestDateHeader(TestHeaderBase):
172
173 datestring = 'Sun, 23 Sep 2001 20:10:55 -0700'
174 utcoffset = datetime.timedelta(hours=-7)
175 tz = datetime.timezone(utcoffset)
176 dt = datetime.datetime(2001, 9, 23, 20, 10, 55, tzinfo=tz)
177
178 def test_parse_date(self):
179 h = self.make_header('date', self.datestring)
180 self.assertEqual(h, self.datestring)
181 self.assertEqual(h.datetime, self.dt)
182 self.assertEqual(h.datetime.utcoffset(), self.utcoffset)
183 self.assertEqual(h.defects, ())
184
185 def test_set_from_datetime(self):
186 h = self.make_header('date', self.dt)
187 self.assertEqual(h, self.datestring)
188 self.assertEqual(h.datetime, self.dt)
189 self.assertEqual(h.defects, ())
190
191 def test_date_header_properties(self):
192 h = self.make_header('date', self.datestring)
193 self.assertIsInstance(h, headerregistry.UniqueDateHeader)
194 self.assertEqual(h.max_count, 1)
195 self.assertEqual(h.defects, ())
196
197 def test_resent_date_header_properties(self):
198 h = self.make_header('resent-date', self.datestring)
199 self.assertIsInstance(h, headerregistry.DateHeader)
200 self.assertEqual(h.max_count, None)
201 self.assertEqual(h.defects, ())
202
203 def test_no_value_is_defect(self):
204 h = self.make_header('date', '')
205 self.assertEqual(len(h.defects), 1)
206 self.assertIsInstance(h.defects[0], errors.HeaderMissingRequiredValue)
207
208 def test_invalid_date_format(self):
209 s = 'Not a date header'
210 h = self.make_header('date', s)
211 self.assertEqual(h, s)
212 self.assertIsNone(h.datetime)
213 self.assertEqual(len(h.defects), 1)
214 self.assertIsInstance(h.defects[0], errors.InvalidDateDefect)
215
216 def test_invalid_date_value(self):
217 s = 'Tue, 06 Jun 2017 27:39:33 +0600'
218 h = self.make_header('date', s)
219 self.assertEqual(h, s)
220 self.assertIsNone(h.datetime)
221 self.assertEqual(len(h.defects), 1)
222 self.assertIsInstance(h.defects[0], errors.InvalidDateDefect)
223
224 def test_out_of_range_date_value(self):
225 s = 'Mon, 20 Nov 9999999999 12:00:00 +0000'
226 h = self.make_header('date', s)
227 self.assertEqual(h, s)
228 self.assertIsNone(h.datetime)
229 self.assertEqual(len(h.defects), 1)
230 self.assertIsInstance(h.defects[0], errors.InvalidDateDefect)
231
232 def test_datetime_read_only(self):
233 h = self.make_header('date', self.datestring)
234 with self.assertRaises(AttributeError):
235 h.datetime = 'foo'
236
237 def test_set_date_header_from_datetime(self):
238 m = Message(policy=policy.default)
239 m['Date'] = self.dt
240 self.assertEqual(m['Date'], self.datestring)
241 self.assertEqual(m['Date'].datetime, self.dt)
242
243
244 @parameterize
245 class TestContentTypeHeader(TestHeaderBase):
246
247 def content_type_as_value(self,
248 source,
249 content_type,
250 maintype,
251 subtype,
252 *args):
253 l = len(args)
254 parmdict = args[0] if l>0 else {}
255 defects = args[1] if l>1 else []
256 decoded = args[2] if l>2 and args[2] is not DITTO else source
257 header = 'Content-Type:' + ' ' if source else ''
258 folded = args[3] if l>3 else header + decoded + '\n'
259 h = self.make_header('Content-Type', source)
260 self.assertEqual(h.content_type, content_type)
261 self.assertEqual(h.maintype, maintype)
262 self.assertEqual(h.subtype, subtype)
263 self.assertEqual(h.params, parmdict)
264 with self.assertRaises(TypeError):
265 h.params['abc'] = 'xyz' # make sure params is read-only.
266 self.assertDefectsEqual(h.defects, defects)
267 self.assertEqual(h, decoded)
268 self.assertEqual(h.fold(policy=policy.default), folded)
269
270 content_type_params = {
271
272 # Examples from RFC 2045.
273
274 'RFC_2045_1': (
275 'text/plain; charset=us-ascii (Plain text)',
276 'text/plain',
277 'text',
278 'plain',
279 {'charset': 'us-ascii'},
280 [],
281 'text/plain; charset="us-ascii"'),
282
283 'RFC_2045_2': (
284 'text/plain; charset=us-ascii',
285 'text/plain',
286 'text',
287 'plain',
288 {'charset': 'us-ascii'},
289 [],
290 'text/plain; charset="us-ascii"'),
291
292 'RFC_2045_3': (
293 'text/plain; charset="us-ascii"',
294 'text/plain',
295 'text',
296 'plain',
297 {'charset': 'us-ascii'}),
298
299 # RFC 2045 5.2 says syntactically invalid values are to be treated as
300 # text/plain.
301
302 'no_subtype_in_content_type': (
303 'text/',
304 'text/plain',
305 'text',
306 'plain',
307 {},
308 [errors.InvalidHeaderDefect]),
309
310 'no_slash_in_content_type': (
311 'foo',
312 'text/plain',
313 'text',
314 'plain',
315 {},
316 [errors.InvalidHeaderDefect]),
317
318 'junk_text_in_content_type': (
319 '<crazy "stuff">',
320 'text/plain',
321 'text',
322 'plain',
323 {},
324 [errors.InvalidHeaderDefect]),
325
326 'too_many_slashes_in_content_type': (
327 'image/jpeg/foo',
328 'text/plain',
329 'text',
330 'plain',
331 {},
332 [errors.InvalidHeaderDefect]),
333
334 # But unknown names are OK. We could make non-IANA names a defect, but
335 # by not doing so we make ourselves future proof. The fact that they
336 # are unknown will be detectable by the fact that they don't appear in
337 # the mime_registry...and the application is free to extend that list
338 # to handle them even if the core library doesn't.
339
340 'unknown_content_type': (
341 'bad/names',
342 'bad/names',
343 'bad',
344 'names'),
345
346 # The content type is case insensitive, and CFWS is ignored.
347
348 'mixed_case_content_type': (
349 'ImAge/JPeg',
350 'image/jpeg',
351 'image',
352 'jpeg'),
353
354 'spaces_in_content_type': (
355 ' text / plain ',
356 'text/plain',
357 'text',
358 'plain'),
359
360 'cfws_in_content_type': (
361 '(foo) text (bar)/(baz)plain(stuff)',
362 'text/plain',
363 'text',
364 'plain'),
365
366 # test some parameters (more tests could be added for parameters
367 # associated with other content types, but since parameter parsing is
368 # generic they would be redundant for the current implementation).
369
370 'charset_param': (
371 'text/plain; charset="utf-8"',
372 'text/plain',
373 'text',
374 'plain',
375 {'charset': 'utf-8'}),
376
377 'capitalized_charset': (
378 'text/plain; charset="US-ASCII"',
379 'text/plain',
380 'text',
381 'plain',
382 {'charset': 'US-ASCII'}),
383
384 'unknown_charset': (
385 'text/plain; charset="fOo"',
386 'text/plain',
387 'text',
388 'plain',
389 {'charset': 'fOo'}),
390
391 'capitalized_charset_param_name_and_comment': (
392 'text/plain; (interjection) Charset="utf-8"',
393 'text/plain',
394 'text',
395 'plain',
396 {'charset': 'utf-8'},
397 [],
398 # Should the parameter name be lowercased here?
399 'text/plain; Charset="utf-8"'),
400
401 # Since this is pretty much the ur-mimeheader, we'll put all the tests
402 # that exercise the parameter parsing and formatting here. Note that
403 # when we refold we may canonicalize, so things like whitespace,
404 # quoting, and rfc2231 encoding may change from what was in the input
405 # header.
406
407 'unquoted_param_value': (
408 'text/plain; title=foo',
409 'text/plain',
410 'text',
411 'plain',
412 {'title': 'foo'},
413 [],
414 'text/plain; title="foo"',
415 ),
416
417 'param_value_with_tspecials': (
418 'text/plain; title="(bar)foo blue"',
419 'text/plain',
420 'text',
421 'plain',
422 {'title': '(bar)foo blue'}),
423
424 'param_with_extra_quoted_whitespace': (
425 'text/plain; title=" a loong way \t home "',
426 'text/plain',
427 'text',
428 'plain',
429 {'title': ' a loong way \t home '}),
430
431 'bad_params': (
432 'blarg; baz; boo',
433 'text/plain',
434 'text',
435 'plain',
436 {'baz': '', 'boo': ''},
437 [errors.InvalidHeaderDefect]*3),
438
439 'spaces_around_param_equals': (
440 'Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"',
441 'multipart/mixed',
442 'multipart',
443 'mixed',
444 {'boundary': 'CPIMSSMTPC06p5f3tG'},
445 [],
446 'Multipart/mixed; boundary="CPIMSSMTPC06p5f3tG"',
447 ),
448
449 'spaces_around_semis': (
450 ('image/jpeg; name="wibble.JPG" ; x-mac-type="4A504547" ; '
451 'x-mac-creator="474B4F4E"'),
452 'image/jpeg',
453 'image',
454 'jpeg',
455 {'name': 'wibble.JPG',
456 'x-mac-type': '4A504547',
457 'x-mac-creator': '474B4F4E'},
458 [],
459 ('image/jpeg; name="wibble.JPG"; x-mac-type="4A504547"; '
460 'x-mac-creator="474B4F4E"'),
461 ('Content-Type: image/jpeg; name="wibble.JPG";'
462 ' x-mac-type="4A504547";\n'
463 ' x-mac-creator="474B4F4E"\n'),
464 ),
465
466 'lots_of_mime_params': (
467 ('image/jpeg; name="wibble.JPG"; x-mac-type="4A504547"; '
468 'x-mac-creator="474B4F4E"; x-extrastuff="make it longer"'),
469 'image/jpeg',
470 'image',
471 'jpeg',
472 {'name': 'wibble.JPG',
473 'x-mac-type': '4A504547',
474 'x-mac-creator': '474B4F4E',
475 'x-extrastuff': 'make it longer'},
476 [],
477 ('image/jpeg; name="wibble.JPG"; x-mac-type="4A504547"; '
478 'x-mac-creator="474B4F4E"; x-extrastuff="make it longer"'),
479 # In this case the whole of the MimeParameters does *not* fit
480 # one one line, so we break at a lower syntactic level.
481 ('Content-Type: image/jpeg; name="wibble.JPG";'
482 ' x-mac-type="4A504547";\n'
483 ' x-mac-creator="474B4F4E"; x-extrastuff="make it longer"\n'),
484 ),
485
486 'semis_inside_quotes': (
487 'image/jpeg; name="Jim&amp;&amp;Jill"',
488 'image/jpeg',
489 'image',
490 'jpeg',
491 {'name': 'Jim&amp;&amp;Jill'}),
492
493 'single_quotes_inside_quotes': (
494 'image/jpeg; name="Jim \'Bob\' Jill"',
495 'image/jpeg',
496 'image',
497 'jpeg',
498 {'name': "Jim 'Bob' Jill"}),
499
500 'double_quotes_inside_quotes': (
501 r'image/jpeg; name="Jim \"Bob\" Jill"',
502 'image/jpeg',
503 'image',
504 'jpeg',
505 {'name': 'Jim "Bob" Jill'},
506 [],
507 r'image/jpeg; name="Jim \"Bob\" Jill"'),
508
509 'non_ascii_in_params': (
510 ('foo\xa7/bar; b\xa7r=two; '
511 'baz=thr\xa7e'.encode('latin-1').decode('us-ascii',
512 'surrogateescape')),
513 'foo\uFFFD/bar',
514 'foo\uFFFD',
515 'bar',
516 {'b\uFFFDr': 'two', 'baz': 'thr\uFFFDe'},
517 [errors.UndecodableBytesDefect]*3,
518 'foo�/bar; b�r="two"; baz="thr�e"',
519 # XXX Two bugs here: the mime type is not allowed to be an encoded
520 # word, and we shouldn't be emitting surrogates in the parameter
521 # names. But I don't know what the behavior should be here, so I'm
522 # punting for now. In practice this is unlikely to be encountered
523 # since headers with binary in them only come from a binary source
524 # and are almost certain to be re-emitted without refolding.
525 'Content-Type: =?unknown-8bit?q?foo=A7?=/bar; b\udca7r="two";\n'
526 " baz*=unknown-8bit''thr%A7e\n",
527 ),
528
529 # RFC 2231 parameter tests.
530
531 'rfc2231_segmented_normal_values': (
532 'image/jpeg; name*0="abc"; name*1=".html"',
533 'image/jpeg',
534 'image',
535 'jpeg',
536 {'name': "abc.html"},
537 [],
538 'image/jpeg; name="abc.html"'),
539
540 'quotes_inside_rfc2231_value': (
541 r'image/jpeg; bar*0="baz\"foobar"; bar*1="\"baz"',
542 'image/jpeg',
543 'image',
544 'jpeg',
545 {'bar': 'baz"foobar"baz'},
546 [],
547 r'image/jpeg; bar="baz\"foobar\"baz"'),
548
549 'non_ascii_rfc2231_value': (
550 ('text/plain; charset=us-ascii; '
551 "title*=us-ascii'en'This%20is%20"
552 'not%20f\xa7n').encode('latin-1').decode('us-ascii',
553 'surrogateescape'),
554 'text/plain',
555 'text',
556 'plain',
557 {'charset': 'us-ascii', 'title': 'This is not f\uFFFDn'},
558 [errors.UndecodableBytesDefect],
559 'text/plain; charset="us-ascii"; title="This is not f�n"',
560 'Content-Type: text/plain; charset="us-ascii";\n'
561 " title*=unknown-8bit''This%20is%20not%20f%A7n\n",
562 ),
563
564 'rfc2231_encoded_charset': (
565 'text/plain; charset*=ansi-x3.4-1968\'\'us-ascii',
566 'text/plain',
567 'text',
568 'plain',
569 {'charset': 'us-ascii'},
570 [],
571 'text/plain; charset="us-ascii"'),
572
573 # This follows the RFC: no double quotes around encoded values.
574 'rfc2231_encoded_no_double_quotes': (
575 ("text/plain;"
576 "\tname*0*=''This%20is%20;"
577 "\tname*1*=%2A%2A%2Afun%2A%2A%2A%20;"
578 '\tname*2="is it not.pdf"'),
579 'text/plain',
580 'text',
581 'plain',
582 {'name': 'This is ***fun*** is it not.pdf'},
583 [],
584 'text/plain; name="This is ***fun*** is it not.pdf"',
585 ),
586
587 # Make sure we also handle it if there are spurious double quotes.
588 'rfc2231_encoded_with_double_quotes': (
589 ("text/plain;"
590 '\tname*0*="us-ascii\'\'This%20is%20even%20more%20";'
591 '\tname*1*="%2A%2A%2Afun%2A%2A%2A%20";'
592 '\tname*2="is it not.pdf"'),
593 'text/plain',
594 'text',
595 'plain',
596 {'name': 'This is even more ***fun*** is it not.pdf'},
597 [errors.InvalidHeaderDefect]*2,
598 'text/plain; name="This is even more ***fun*** is it not.pdf"',
599 ),
600
601 'rfc2231_single_quote_inside_double_quotes': (
602 ('text/plain; charset=us-ascii;'
603 '\ttitle*0*="us-ascii\'en\'This%20is%20really%20";'
604 '\ttitle*1*="%2A%2A%2Afun%2A%2A%2A%20";'
605 '\ttitle*2="isn\'t it!"'),
606 'text/plain',
607 'text',
608 'plain',
609 {'charset': 'us-ascii', 'title': "This is really ***fun*** isn't it!"},
610 [errors.InvalidHeaderDefect]*2,
611 ('text/plain; charset="us-ascii"; '
612 'title="This is really ***fun*** isn\'t it!"'),
613 ('Content-Type: text/plain; charset="us-ascii";\n'
614 ' title="This is really ***fun*** isn\'t it!"\n'),
615 ),
616
617 'rfc2231_single_quote_in_value_with_charset_and_lang': (
618 ('application/x-foo;'
619 "\tname*0*=\"us-ascii'en-us'Frank's\"; name*1*=\" Document\""),
620 'application/x-foo',
621 'application',
622 'x-foo',
623 {'name': "Frank's Document"},
624 [errors.InvalidHeaderDefect]*2,
625 'application/x-foo; name="Frank\'s Document"',
626 ),
627
628 'rfc2231_single_quote_in_non_encoded_value': (
629 ('application/x-foo;'
630 "\tname*0=\"us-ascii'en-us'Frank's\"; name*1=\" Document\""),
631 'application/x-foo',
632 'application',
633 'x-foo',
634 {'name': "us-ascii'en-us'Frank's Document"},
635 [],
636 'application/x-foo; name="us-ascii\'en-us\'Frank\'s Document"',
637 ),
638
639 'rfc2231_no_language_or_charset': (
640 'text/plain; NAME*0*=english_is_the_default.html',
641 'text/plain',
642 'text',
643 'plain',
644 {'name': 'english_is_the_default.html'},
645 [errors.InvalidHeaderDefect],
646 'text/plain; NAME="english_is_the_default.html"'),
647
648 'rfc2231_encoded_no_charset': (
649 ("text/plain;"
650 '\tname*0*="\'\'This%20is%20even%20more%20";'
651 '\tname*1*="%2A%2A%2Afun%2A%2A%2A%20";'
652 '\tname*2="is it.pdf"'),
653 'text/plain',
654 'text',
655 'plain',
656 {'name': 'This is even more ***fun*** is it.pdf'},
657 [errors.InvalidHeaderDefect]*2,
658 'text/plain; name="This is even more ***fun*** is it.pdf"',
659 ),
660
661 'rfc2231_partly_encoded': (
662 ("text/plain;"
663 '\tname*0*="\'\'This%20is%20even%20more%20";'
664 '\tname*1*="%2A%2A%2Afun%2A%2A%2A%20";'
665 '\tname*2="is it.pdf"'),
666 'text/plain',
667 'text',
668 'plain',
669 {'name': 'This is even more ***fun*** is it.pdf'},
670 [errors.InvalidHeaderDefect]*2,
671 'text/plain; name="This is even more ***fun*** is it.pdf"',
672 ),
673
674 'rfc2231_partly_encoded_2': (
675 ("text/plain;"
676 '\tname*0*="\'\'This%20is%20even%20more%20";'
677 '\tname*1="%2A%2A%2Afun%2A%2A%2A%20";'
678 '\tname*2="is it.pdf"'),
679 'text/plain',
680 'text',
681 'plain',
682 {'name': 'This is even more %2A%2A%2Afun%2A%2A%2A%20is it.pdf'},
683 [errors.InvalidHeaderDefect],
684 ('text/plain;'
685 ' name="This is even more %2A%2A%2Afun%2A%2A%2A%20is it.pdf"'),
686 ('Content-Type: text/plain;\n'
687 ' name="This is even more %2A%2A%2Afun%2A%2A%2A%20is'
688 ' it.pdf"\n'),
689 ),
690
691 'rfc2231_unknown_charset_treated_as_ascii': (
692 "text/plain; name*0*=bogus'xx'ascii_is_the_default",
693 'text/plain',
694 'text',
695 'plain',
696 {'name': 'ascii_is_the_default'},
697 [],
698 'text/plain; name="ascii_is_the_default"'),
699
700 'rfc2231_bad_character_in_charset_parameter_value': (
701 "text/plain; charset*=ascii''utf-8%F1%F2%F3",
702 'text/plain',
703 'text',
704 'plain',
705 {'charset': 'utf-8\uFFFD\uFFFD\uFFFD'},
706 [errors.UndecodableBytesDefect],
707 'text/plain; charset="utf-8\uFFFD\uFFFD\uFFFD"',
708 "Content-Type: text/plain;"
709 " charset*=unknown-8bit''utf-8%F1%F2%F3\n",
710 ),
711
712 'rfc2231_utf8_in_supposedly_ascii_charset_parameter_value': (
713 "text/plain; charset*=ascii''utf-8%E2%80%9D",
714 'text/plain',
715 'text',
716 'plain',
717 {'charset': 'utf-8”'},
718 [errors.UndecodableBytesDefect],
719 'text/plain; charset="utf-8”"',
720 # XXX Should folding change the charset to utf8? Currently it just
721 # reproduces the original, which is arguably fine.
722 "Content-Type: text/plain;"
723 " charset*=unknown-8bit''utf-8%E2%80%9D\n",
724 ),
725
726 'rfc2231_nonascii_in_charset_of_charset_parameter_value': (
727 "text/plain; charset*=utf-8”''utf-8%E2%80%9D",
728 'text/plain',
729 'text',
730 'plain',
731 {'charset': 'utf-8”'},
732 [],
733 'text/plain; charset="utf-8”"',
734 "Content-Type: text/plain;"
735 " charset*=utf-8''utf-8%E2%80%9D\n",
736 ),
737
738 'rfc2231_encoded_then_unencoded_segments': (
739 ('application/x-foo;'
740 '\tname*0*="us-ascii\'en-us\'My";'
741 '\tname*1=" Document";'
742 '\tname*2=" For You"'),
743 'application/x-foo',
744 'application',
745 'x-foo',
746 {'name': 'My Document For You'},
747 [errors.InvalidHeaderDefect],
748 'application/x-foo; name="My Document For You"',
749 ),
750
751 # My reading of the RFC is that this is an invalid header. The RFC
752 # says that if charset and language information is given, the first
753 # segment *must* be encoded.
754 'rfc2231_unencoded_then_encoded_segments': (
755 ('application/x-foo;'
756 '\tname*0=us-ascii\'en-us\'My;'
757 '\tname*1*=" Document";'
758 '\tname*2*=" For You"'),
759 'application/x-foo',
760 'application',
761 'x-foo',
762 {'name': 'My Document For You'},
763 [errors.InvalidHeaderDefect]*3,
764 'application/x-foo; name="My Document For You"',
765 ),
766
767 # XXX: I would say this one should default to ascii/en for the
768 # "encoded" segment, since the first segment is not encoded and is
769 # in double quotes, making the value a valid non-encoded string. The
770 # old parser decodes this just like the previous case, which may be the
771 # better Postel rule, but could equally result in borking headers that
772 # intentionally have quoted quotes in them. We could get this 98%
773 # right if we treat it as a quoted string *unless* it matches the
774 # charset'lang'value pattern exactly *and* there is at least one
775 # encoded segment. Implementing that algorithm will require some
776 # refactoring, so I haven't done it (yet).
777 'rfc2231_quoted_unencoded_then_encoded_segments': (
778 ('application/x-foo;'
779 '\tname*0="us-ascii\'en-us\'My";'
780 '\tname*1*=" Document";'
781 '\tname*2*=" For You"'),
782 'application/x-foo',
783 'application',
784 'x-foo',
785 {'name': "us-ascii'en-us'My Document For You"},
786 [errors.InvalidHeaderDefect]*2,
787 'application/x-foo; name="us-ascii\'en-us\'My Document For You"',
788 ),
789
790 # Make sure our folding algorithm produces multiple sections correctly.
791 # We could mix encoded and non-encoded segments, but we don't, we just
792 # make them all encoded. It might be worth fixing that, since the
793 # sections can get used for wrapping ascii text.
794 'rfc2231_folded_segments_correctly_formatted': (
795 ('application/x-foo;'
796 '\tname="' + "with spaces"*8 + '"'),
797 'application/x-foo',
798 'application',
799 'x-foo',
800 {'name': "with spaces"*8},
801 [],
802 'application/x-foo; name="' + "with spaces"*8 + '"',
803 "Content-Type: application/x-foo;\n"
804 " name*0*=us-ascii''with%20spaceswith%20spaceswith%20spaceswith"
805 "%20spaceswith;\n"
806 " name*1*=%20spaceswith%20spaceswith%20spaceswith%20spaces\n"
807 ),
808
809 }
810
811
812 @parameterize
813 class TestContentTransferEncoding(TestHeaderBase):
814
815 def cte_as_value(self,
816 source,
817 cte,
818 *args):
819 l = len(args)
820 defects = args[0] if l>0 else []
821 decoded = args[1] if l>1 and args[1] is not DITTO else source
822 header = 'Content-Transfer-Encoding:' + ' ' if source else ''
823 folded = args[2] if l>2 else header + source + '\n'
824 h = self.make_header('Content-Transfer-Encoding', source)
825 self.assertEqual(h.cte, cte)
826 self.assertDefectsEqual(h.defects, defects)
827 self.assertEqual(h, decoded)
828 self.assertEqual(h.fold(policy=policy.default), folded)
829
830 cte_params = {
831
832 'RFC_2183_1': (
833 'base64',
834 'base64',),
835
836 'no_value': (
837 '',
838 '7bit',
839 [errors.HeaderMissingRequiredValue],
840 '',
841 'Content-Transfer-Encoding:\n',
842 ),
843
844 'junk_after_cte': (
845 '7bit and a bunch more',
846 '7bit',
847 [errors.InvalidHeaderDefect]),
848
849 'extra_space_after_cte': (
850 'base64 ',
851 'base64',
852 []),
853
854 }
855
856
857 @parameterize
858 class TestContentDisposition(TestHeaderBase):
859
860 def content_disp_as_value(self,
861 source,
862 content_disposition,
863 *args):
864 l = len(args)
865 parmdict = args[0] if l>0 else {}
866 defects = args[1] if l>1 else []
867 decoded = args[2] if l>2 and args[2] is not DITTO else source
868 header = 'Content-Disposition:' + ' ' if source else ''
869 folded = args[3] if l>3 else header + source + '\n'
870 h = self.make_header('Content-Disposition', source)
871 self.assertEqual(h.content_disposition, content_disposition)
872 self.assertEqual(h.params, parmdict)
873 self.assertDefectsEqual(h.defects, defects)
874 self.assertEqual(h, decoded)
875 self.assertEqual(h.fold(policy=policy.default), folded)
876
877 content_disp_params = {
878
879 # Examples from RFC 2183.
880
881 'RFC_2183_1': (
882 'inline',
883 'inline',),
884
885 'RFC_2183_2': (
886 ('attachment; filename=genome.jpeg;'
887 ' modification-date="Wed, 12 Feb 1997 16:29:51 -0500";'),
888 'attachment',
889 {'filename': 'genome.jpeg',
890 'modification-date': 'Wed, 12 Feb 1997 16:29:51 -0500'},
891 [],
892 ('attachment; filename="genome.jpeg"; '
893 'modification-date="Wed, 12 Feb 1997 16:29:51 -0500"'),
894 ('Content-Disposition: attachment; filename="genome.jpeg";\n'
895 ' modification-date="Wed, 12 Feb 1997 16:29:51 -0500"\n'),
896 ),
897
898 'no_value': (
899 '',
900 None,
901 {},
902 [errors.HeaderMissingRequiredValue],
903 '',
904 'Content-Disposition:\n'),
905
906 'invalid_value': (
907 'ab./k',
908 'ab.',
909 {},
910 [errors.InvalidHeaderDefect]),
911
912 'invalid_value_with_params': (
913 'ab./k; filename="foo"',
914 'ab.',
915 {'filename': 'foo'},
916 [errors.InvalidHeaderDefect]),
917
918 'invalid_parameter_value_with_fws_between_ew': (
919 'attachment; filename="=?UTF-8?Q?Schulbesuchsbest=C3=A4ttigung=2E?='
920 ' =?UTF-8?Q?pdf?="',
921 'attachment',
922 {'filename': 'Schulbesuchsbestättigung.pdf'},
923 [errors.InvalidHeaderDefect]*3,
924 ('attachment; filename="Schulbesuchsbestättigung.pdf"'),
925 ('Content-Disposition: attachment;\n'
926 ' filename*=utf-8\'\'Schulbesuchsbest%C3%A4ttigung.pdf\n'),
927 ),
928
929 'parameter_value_with_fws_between_tokens': (
930 'attachment; filename="File =?utf-8?q?Name?= With Spaces.pdf"',
931 'attachment',
932 {'filename': 'File Name With Spaces.pdf'},
933 [errors.InvalidHeaderDefect],
934 'attachment; filename="File Name With Spaces.pdf"',
935 ('Content-Disposition: attachment; filename="File Name With Spaces.pdf"\n'),
936 )
937 }
938
939
940 @parameterize
941 class TestMIMEVersionHeader(TestHeaderBase):
942
943 def version_string_as_MIME_Version(self,
944 source,
945 decoded,
946 version,
947 major,
948 minor,
949 defects):
950 h = self.make_header('MIME-Version', source)
951 self.assertEqual(h, decoded)
952 self.assertEqual(h.version, version)
953 self.assertEqual(h.major, major)
954 self.assertEqual(h.minor, minor)
955 self.assertDefectsEqual(h.defects, defects)
956 if source:
957 source = ' ' + source
958 self.assertEqual(h.fold(policy=policy.default),
959 'MIME-Version:' + source + '\n')
960
961 version_string_params = {
962
963 # Examples from the RFC.
964
965 'RFC_2045_1': (
966 '1.0',
967 '1.0',
968 '1.0',
969 1,
970 0,
971 []),
972
973 'RFC_2045_2': (
974 '1.0 (produced by MetaSend Vx.x)',
975 '1.0 (produced by MetaSend Vx.x)',
976 '1.0',
977 1,
978 0,
979 []),
980
981 'RFC_2045_3': (
982 '(produced by MetaSend Vx.x) 1.0',
983 '(produced by MetaSend Vx.x) 1.0',
984 '1.0',
985 1,
986 0,
987 []),
988
989 'RFC_2045_4': (
990 '1.(produced by MetaSend Vx.x)0',
991 '1.(produced by MetaSend Vx.x)0',
992 '1.0',
993 1,
994 0,
995 []),
996
997 # Other valid values.
998
999 '1_1': (
1000 '1.1',
1001 '1.1',
1002 '1.1',
1003 1,
1004 1,
1005 []),
1006
1007 '2_1': (
1008 '2.1',
1009 '2.1',
1010 '2.1',
1011 2,
1012 1,
1013 []),
1014
1015 'whitespace': (
1016 '1 .0',
1017 '1 .0',
1018 '1.0',
1019 1,
1020 0,
1021 []),
1022
1023 'leading_trailing_whitespace_ignored': (
1024 ' 1.0 ',
1025 ' 1.0 ',
1026 '1.0',
1027 1,
1028 0,
1029 []),
1030
1031 # Recoverable invalid values. We can recover here only because we
1032 # already have a valid value by the time we encounter the garbage.
1033 # Anywhere else, and we don't know where the garbage ends.
1034
1035 'non_comment_garbage_after': (
1036 '1.0 <abc>',
1037 '1.0 <abc>',
1038 '1.0',
1039 1,
1040 0,
1041 [errors.InvalidHeaderDefect]),
1042
1043 # Unrecoverable invalid values. We *could* apply more heuristics to
1044 # get something out of the first two, but doing so is not worth the
1045 # effort.
1046
1047 'non_comment_garbage_before': (
1048 '<abc> 1.0',
1049 '<abc> 1.0',
1050 None,
1051 None,
1052 None,
1053 [errors.InvalidHeaderDefect]),
1054
1055 'non_comment_garbage_inside': (
1056 '1.<abc>0',
1057 '1.<abc>0',
1058 None,
1059 None,
1060 None,
1061 [errors.InvalidHeaderDefect]),
1062
1063 'two_periods': (
1064 '1..0',
1065 '1..0',
1066 None,
1067 None,
1068 None,
1069 [errors.InvalidHeaderDefect]),
1070
1071 '2_x': (
1072 '2.x',
1073 '2.x',
1074 None, # This could be 2, but it seems safer to make it None.
1075 None,
1076 None,
1077 [errors.InvalidHeaderDefect]),
1078
1079 'foo': (
1080 'foo',
1081 'foo',
1082 None,
1083 None,
1084 None,
1085 [errors.InvalidHeaderDefect]),
1086
1087 'missing': (
1088 '',
1089 '',
1090 None,
1091 None,
1092 None,
1093 [errors.HeaderMissingRequiredValue]),
1094
1095 }
1096
1097
1098 @parameterize
1099 class TestAddressHeader(TestHeaderBase):
1100
1101 example_params = {
1102
1103 'empty':
1104 ('<>',
1105 [errors.InvalidHeaderDefect],
1106 '<>',
1107 '',
1108 '<>',
1109 '',
1110 '',
1111 None),
1112
1113 'address_only':
1114 ('[email protected]',
1115 [],
1116 '[email protected]',
1117 '',
1118 '[email protected]',
1119 'zippy',
1120 'pinhead.com',
1121 None),
1122
1123 'name_and_address':
1124 ('Zaphrod Beblebrux <[email protected]>',
1125 [],
1126 'Zaphrod Beblebrux <[email protected]>',
1127 'Zaphrod Beblebrux',
1128 '[email protected]',
1129 'zippy',
1130 'pinhead.com',
1131 None),
1132
1133 'quoted_local_part':
1134 ('Zaphrod Beblebrux <"foo bar"@pinhead.com>',
1135 [],
1136 'Zaphrod Beblebrux <"foo bar"@pinhead.com>',
1137 'Zaphrod Beblebrux',
1138 '"foo bar"@pinhead.com',
1139 'foo bar',
1140 'pinhead.com',
1141 None),
1142
1143 'quoted_parens_in_name':
1144 (r'"A \(Special\) Person" <[email protected]>',
1145 [],
1146 '"A (Special) Person" <[email protected]>',
1147 'A (Special) Person',
1148 '[email protected]',
1149 'person',
1150 'dom.ain',
1151 None),
1152
1153 'quoted_backslashes_in_name':
1154 (r'"Arthur \\Backslash\\ Foobar" <[email protected]>',
1155 [],
1156 r'"Arthur \\Backslash\\ Foobar" <[email protected]>',
1157 r'Arthur \Backslash\ Foobar',
1158 '[email protected]',
1159 'person',
1160 'dom.ain',
1161 None),
1162
1163 'name_with_dot':
1164 ('John X. Doe <[email protected]>',
1165 [errors.ObsoleteHeaderDefect],
1166 '"John X. Doe" <[email protected]>',
1167 'John X. Doe',
1168 '[email protected]',
1169 'jxd',
1170 'example.com',
1171 None),
1172
1173 'quoted_strings_in_local_part':
1174 ('""example" example"@example.com',
1175 [errors.InvalidHeaderDefect]*3,
1176 '"example example"@example.com',
1177 '',
1178 '"example example"@example.com',
1179 'example example',
1180 'example.com',
1181 None),
1182
1183 'escaped_quoted_strings_in_local_part':
1184 (r'"\"example\" example"@example.com',
1185 [],
1186 r'"\"example\" example"@example.com',
1187 '',
1188 r'"\"example\" example"@example.com',
1189 r'"example" example',
1190 'example.com',
1191 None),
1192
1193 'escaped_escapes_in_local_part':
1194 (r'"\\"example\\" example"@example.com',
1195 [errors.InvalidHeaderDefect]*5,
1196 r'"\\example\\\\ example"@example.com',
1197 '',
1198 r'"\\example\\\\ example"@example.com',
1199 r'\example\\ example',
1200 'example.com',
1201 None),
1202
1203 'spaces_in_unquoted_local_part_collapsed':
1204 ('merwok wok @example.com',
1205 [errors.InvalidHeaderDefect]*2,
1206 '"merwok wok"@example.com',
1207 '',
1208 '"merwok wok"@example.com',
1209 'merwok wok',
1210 'example.com',
1211 None),
1212
1213 'spaces_around_dots_in_local_part_removed':
1214 ('merwok. wok . [email protected]',
1215 [errors.ObsoleteHeaderDefect],
1216 '[email protected]',
1217 '',
1218 '[email protected]',
1219 'merwok.wok.wok',
1220 'example.com',
1221 None),
1222
1223 'rfc2047_atom_is_decoded':
1224 ('=?utf-8?q?=C3=89ric?= <[email protected]>',
1225 [],
1226 'Éric <[email protected]>',
1227 'Éric',
1228 '[email protected]',
1229 'foo',
1230 'example.com',
1231 None),
1232
1233 'rfc2047_atom_in_phrase_is_decoded':
1234 ('The =?utf-8?q?=C3=89ric=2C?= Himself <[email protected]>',
1235 [],
1236 '"The Éric, Himself" <[email protected]>',
1237 'The Éric, Himself',
1238 '[email protected]',
1239 'foo',
1240 'example.com',
1241 None),
1242
1243 'rfc2047_atom_in_quoted_string_is_decoded':
1244 ('"=?utf-8?q?=C3=89ric?=" <[email protected]>',
1245 [errors.InvalidHeaderDefect,
1246 errors.InvalidHeaderDefect],
1247 'Éric <[email protected]>',
1248 'Éric',
1249 '[email protected]',
1250 'foo',
1251 'example.com',
1252 None),
1253
1254 'name_ending_with_dot_without_space':
1255 ('John X.<[email protected]>',
1256 [errors.ObsoleteHeaderDefect],
1257 '"John X." <[email protected]>',
1258 'John X.',
1259 '[email protected]',
1260 'jxd',
1261 'example.com',
1262 None),
1263
1264 'name_starting_with_dot':
1265 ('. Doe <[email protected]>',
1266 [errors.InvalidHeaderDefect, errors.ObsoleteHeaderDefect],
1267 '". Doe" <[email protected]>',
1268 '. Doe',
1269 '[email protected]',
1270 'jxd',
1271 'example.com',
1272 None),
1273
1274 # XXX: Need many more examples, and in particular some with names in
1275 # trailing comments, which aren't currently handled. comments in
1276 # general are not handled yet.
1277
1278 }
1279
1280 def example_as_address(self, source, defects, decoded, display_name,
1281 addr_spec, username, domain, comment):
1282 h = self.make_header('sender', source)
1283 self.assertEqual(h, decoded)
1284 self.assertDefectsEqual(h.defects, defects)
1285 a = h.address
1286 self.assertEqual(str(a), decoded)
1287 self.assertEqual(len(h.groups), 1)
1288 self.assertEqual([a], list(h.groups[0].addresses))
1289 self.assertEqual([a], list(h.addresses))
1290 self.assertEqual(a.display_name, display_name)
1291 self.assertEqual(a.addr_spec, addr_spec)
1292 self.assertEqual(a.username, username)
1293 self.assertEqual(a.domain, domain)
1294 # XXX: we have no comment support yet.
1295 #self.assertEqual(a.comment, comment)
1296
1297 example_broken_header_params = {
1298
1299 'just_dquote':
1300 ('"',
1301 [errors.InvalidHeaderDefect]*2,
1302 '<>',
1303 '',
1304 '<>',
1305 '',
1306 '',
1307 ),
1308
1309 }
1310
1311 def example_broken_header_as_address(
1312 self,
1313 source,
1314 defects,
1315 decoded,
1316 display_name,
1317 addr_spec,
1318 username,
1319 domain,
1320 ):
1321 h = self.make_header('sender', source)
1322 self.assertEqual(h, decoded)
1323 self.assertDefectsEqual(h.defects, defects)
1324 a = h.address
1325 self.assertEqual(str(a), decoded)
1326 self.assertEqual(len(h.groups), 1)
1327 self.assertEqual([a], list(h.groups[0].addresses))
1328 self.assertEqual([a], list(h.addresses))
1329 self.assertEqual(a.display_name, display_name)
1330 self.assertEqual(a.addr_spec, addr_spec)
1331 self.assertEqual(a.username, username)
1332 self.assertEqual(a.domain, domain)
1333
1334 def example_as_group(self, source, defects, decoded, display_name,
1335 addr_spec, username, domain, comment):
1336 source = 'foo: {};'.format(source)
1337 gdecoded = 'foo: {};'.format(decoded) if decoded else 'foo:;'
1338 h = self.make_header('to', source)
1339 self.assertEqual(h, gdecoded)
1340 self.assertDefectsEqual(h.defects, defects)
1341 self.assertEqual(h.groups[0].addresses, h.addresses)
1342 self.assertEqual(len(h.groups), 1)
1343 self.assertEqual(len(h.addresses), 1)
1344 a = h.addresses[0]
1345 self.assertEqual(str(a), decoded)
1346 self.assertEqual(a.display_name, display_name)
1347 self.assertEqual(a.addr_spec, addr_spec)
1348 self.assertEqual(a.username, username)
1349 self.assertEqual(a.domain, domain)
1350
1351 def test_simple_address_list(self):
1352 value = ('Fred <[email protected]>, [email protected], '
1353 '"Harry W. Hastings" <[email protected]>')
1354 h = self.make_header('to', value)
1355 self.assertEqual(h, value)
1356 self.assertEqual(len(h.groups), 3)
1357 self.assertEqual(len(h.addresses), 3)
1358 for i in range(3):
1359 self.assertEqual(h.groups[i].addresses[0], h.addresses[i])
1360 self.assertEqual(str(h.addresses[0]), 'Fred <[email protected]>')
1361 self.assertEqual(str(h.addresses[1]), '[email protected]')
1362 self.assertEqual(str(h.addresses[2]),
1363 '"Harry W. Hastings" <[email protected]>')
1364 self.assertEqual(h.addresses[2].display_name,
1365 'Harry W. Hastings')
1366
1367 def test_complex_address_list(self):
1368 examples = list(self.example_params.values())
1369 source = ('dummy list:;, another: (empty);,' +
1370 ', '.join([x[0] for x in examples[:4]]) + ', ' +
1371 r'"A \"list\"": ' +
1372 ', '.join([x[0] for x in examples[4:6]]) + ';,' +
1373 ', '.join([x[0] for x in examples[6:]])
1374 )
1375 # XXX: the fact that (empty) disappears here is a potential API design
1376 # bug. We don't currently have a way to preserve comments.
1377 expected = ('dummy list:;, another:;, ' +
1378 ', '.join([x[2] for x in examples[:4]]) + ', ' +
1379 r'"A \"list\"": ' +
1380 ', '.join([x[2] for x in examples[4:6]]) + ';, ' +
1381 ', '.join([x[2] for x in examples[6:]])
1382 )
1383
1384 h = self.make_header('to', source)
1385 self.assertEqual(h.split(','), expected.split(','))
1386 self.assertEqual(h, expected)
1387 self.assertEqual(len(h.groups), 7 + len(examples) - 6)
1388 self.assertEqual(h.groups[0].display_name, 'dummy list')
1389 self.assertEqual(h.groups[1].display_name, 'another')
1390 self.assertEqual(h.groups[6].display_name, 'A "list"')
1391 self.assertEqual(len(h.addresses), len(examples))
1392 for i in range(4):
1393 self.assertIsNone(h.groups[i+2].display_name)
1394 self.assertEqual(str(h.groups[i+2].addresses[0]), examples[i][2])
1395 for i in range(7, 7 + len(examples) - 6):
1396 self.assertIsNone(h.groups[i].display_name)
1397 self.assertEqual(str(h.groups[i].addresses[0]), examples[i-1][2])
1398 for i in range(len(examples)):
1399 self.assertEqual(str(h.addresses[i]), examples[i][2])
1400 self.assertEqual(h.addresses[i].addr_spec, examples[i][4])
1401
1402 def test_address_read_only(self):
1403 h = self.make_header('sender', '[email protected]')
1404 with self.assertRaises(AttributeError):
1405 h.address = 'foo'
1406
1407 def test_addresses_read_only(self):
1408 h = self.make_header('sender', '[email protected]')
1409 with self.assertRaises(AttributeError):
1410 h.addresses = 'foo'
1411
1412 def test_groups_read_only(self):
1413 h = self.make_header('sender', '[email protected]')
1414 with self.assertRaises(AttributeError):
1415 h.groups = 'foo'
1416
1417 def test_addresses_types(self):
1418 source = 'me <[email protected]>'
1419 h = self.make_header('to', source)
1420 self.assertIsInstance(h.addresses, tuple)
1421 self.assertIsInstance(h.addresses[0], Address)
1422
1423 def test_groups_types(self):
1424 source = 'me <[email protected]>'
1425 h = self.make_header('to', source)
1426 self.assertIsInstance(h.groups, tuple)
1427 self.assertIsInstance(h.groups[0], Group)
1428
1429 def test_set_from_Address(self):
1430 h = self.make_header('to', Address('me', 'foo', 'example.com'))
1431 self.assertEqual(h, 'me <[email protected]>')
1432
1433 def test_set_from_Address_list(self):
1434 h = self.make_header('to', [Address('me', 'foo', 'example.com'),
1435 Address('you', 'bar', 'example.com')])
1436 self.assertEqual(h, 'me <[email protected]>, you <[email protected]>')
1437
1438 def test_set_from_Address_and_Group_list(self):
1439 h = self.make_header('to', [Address('me', 'foo', 'example.com'),
1440 Group('bing', [Address('fiz', 'z', 'b.com'),
1441 Address('zif', 'f', 'c.com')]),
1442 Address('you', 'bar', 'example.com')])
1443 self.assertEqual(h, 'me <[email protected]>, bing: fiz <[email protected]>, '
1444 'zif <[email protected]>;, you <[email protected]>')
1445 self.assertEqual(h.fold(policy=policy.default.clone(max_line_length=40)),
1446 'to: me <[email protected]>,\n'
1447 ' bing: fiz <[email protected]>, zif <[email protected]>;,\n'
1448 ' you <[email protected]>\n')
1449
1450 def test_set_from_Group_list(self):
1451 h = self.make_header('to', [Group('bing', [Address('fiz', 'z', 'b.com'),
1452 Address('zif', 'f', 'c.com')])])
1453 self.assertEqual(h, 'bing: fiz <[email protected]>, zif <[email protected]>;')
1454
1455
1456 class TestAddressAndGroup(TestEmailBase):
1457
1458 def _test_attr_ro(self, obj, attr):
1459 with self.assertRaises(AttributeError):
1460 setattr(obj, attr, 'foo')
1461
1462 def test_address_display_name_ro(self):
1463 self._test_attr_ro(Address('foo', 'bar', 'baz'), 'display_name')
1464
1465 def test_address_username_ro(self):
1466 self._test_attr_ro(Address('foo', 'bar', 'baz'), 'username')
1467
1468 def test_address_domain_ro(self):
1469 self._test_attr_ro(Address('foo', 'bar', 'baz'), 'domain')
1470
1471 def test_group_display_name_ro(self):
1472 self._test_attr_ro(Group('foo'), 'display_name')
1473
1474 def test_group_addresses_ro(self):
1475 self._test_attr_ro(Group('foo'), 'addresses')
1476
1477 def test_address_from_username_domain(self):
1478 a = Address('foo', 'bar', 'baz')
1479 self.assertEqual(a.display_name, 'foo')
1480 self.assertEqual(a.username, 'bar')
1481 self.assertEqual(a.domain, 'baz')
1482 self.assertEqual(a.addr_spec, 'bar@baz')
1483 self.assertEqual(str(a), 'foo <bar@baz>')
1484
1485 def test_address_from_addr_spec(self):
1486 a = Address('foo', addr_spec='bar@baz')
1487 self.assertEqual(a.display_name, 'foo')
1488 self.assertEqual(a.username, 'bar')
1489 self.assertEqual(a.domain, 'baz')
1490 self.assertEqual(a.addr_spec, 'bar@baz')
1491 self.assertEqual(str(a), 'foo <bar@baz>')
1492
1493 def test_address_with_no_display_name(self):
1494 a = Address(addr_spec='bar@baz')
1495 self.assertEqual(a.display_name, '')
1496 self.assertEqual(a.username, 'bar')
1497 self.assertEqual(a.domain, 'baz')
1498 self.assertEqual(a.addr_spec, 'bar@baz')
1499 self.assertEqual(str(a), 'bar@baz')
1500
1501 def test_null_address(self):
1502 a = Address()
1503 self.assertEqual(a.display_name, '')
1504 self.assertEqual(a.username, '')
1505 self.assertEqual(a.domain, '')
1506 self.assertEqual(a.addr_spec, '<>')
1507 self.assertEqual(str(a), '<>')
1508
1509 def test_domain_only(self):
1510 # This isn't really a valid address.
1511 a = Address(domain='buzz')
1512 self.assertEqual(a.display_name, '')
1513 self.assertEqual(a.username, '')
1514 self.assertEqual(a.domain, 'buzz')
1515 self.assertEqual(a.addr_spec, '@buzz')
1516 self.assertEqual(str(a), '@buzz')
1517
1518 def test_username_only(self):
1519 # This isn't really a valid address.
1520 a = Address(username='buzz')
1521 self.assertEqual(a.display_name, '')
1522 self.assertEqual(a.username, 'buzz')
1523 self.assertEqual(a.domain, '')
1524 self.assertEqual(a.addr_spec, 'buzz')
1525 self.assertEqual(str(a), 'buzz')
1526
1527 def test_display_name_only(self):
1528 a = Address('buzz')
1529 self.assertEqual(a.display_name, 'buzz')
1530 self.assertEqual(a.username, '')
1531 self.assertEqual(a.domain, '')
1532 self.assertEqual(a.addr_spec, '<>')
1533 self.assertEqual(str(a), 'buzz <>')
1534
1535 def test_quoting(self):
1536 # Ideally we'd check every special individually, but I'm not up for
1537 # writing that many tests.
1538 a = Address('Sara J.', 'bad name', 'example.com')
1539 self.assertEqual(a.display_name, 'Sara J.')
1540 self.assertEqual(a.username, 'bad name')
1541 self.assertEqual(a.domain, 'example.com')
1542 self.assertEqual(a.addr_spec, '"bad name"@example.com')
1543 self.assertEqual(str(a), '"Sara J." <"bad name"@example.com>')
1544
1545 def test_il8n(self):
1546 a = Address('Éric', 'wok', 'exàmple.com')
1547 self.assertEqual(a.display_name, 'Éric')
1548 self.assertEqual(a.username, 'wok')
1549 self.assertEqual(a.domain, 'exàmple.com')
1550 self.assertEqual(a.addr_spec, 'wok@exàmple.com')
1551 self.assertEqual(str(a), 'Éric <wok@exàmple.com>')
1552
1553 # XXX: there is an API design issue that needs to be solved here.
1554 #def test_non_ascii_username_raises(self):
1555 # with self.assertRaises(ValueError):
1556 # Address('foo', 'wők', 'example.com')
1557
1558 def test_crlf_in_constructor_args_raises(self):
1559 cases = (
1560 dict(display_name='foo\r'),
1561 dict(display_name='foo\n'),
1562 dict(display_name='foo\r\n'),
1563 dict(domain='example.com\r'),
1564 dict(domain='example.com\n'),
1565 dict(domain='example.com\r\n'),
1566 dict(username='wok\r'),
1567 dict(username='wok\n'),
1568 dict(username='wok\r\n'),
1569 dict(addr_spec='[email protected]\r'),
1570 dict(addr_spec='[email protected]\n'),
1571 dict(addr_spec='[email protected]\r\n')
1572 )
1573 for kwargs in cases:
1574 with self.subTest(kwargs=kwargs), self.assertRaisesRegex(ValueError, "invalid arguments"):
1575 Address(**kwargs)
1576
1577 def test_non_ascii_username_in_addr_spec_raises(self):
1578 with self.assertRaises(ValueError):
1579 Address('foo', addr_spec='wő[email protected]')
1580
1581 def test_address_addr_spec_and_username_raises(self):
1582 with self.assertRaises(TypeError):
1583 Address('foo', username='bing', addr_spec='bar@baz')
1584
1585 def test_address_addr_spec_and_domain_raises(self):
1586 with self.assertRaises(TypeError):
1587 Address('foo', domain='bing', addr_spec='bar@baz')
1588
1589 def test_address_addr_spec_and_username_and_domain_raises(self):
1590 with self.assertRaises(TypeError):
1591 Address('foo', username='bong', domain='bing', addr_spec='bar@baz')
1592
1593 def test_space_in_addr_spec_username_raises(self):
1594 with self.assertRaises(ValueError):
1595 Address('foo', addr_spec="bad [email protected]")
1596
1597 def test_bad_addr_sepc_raises(self):
1598 with self.assertRaises(ValueError):
1599 Address('foo', addr_spec="name@ex[]ample.com")
1600
1601 def test_empty_group(self):
1602 g = Group('foo')
1603 self.assertEqual(g.display_name, 'foo')
1604 self.assertEqual(g.addresses, tuple())
1605 self.assertEqual(str(g), 'foo:;')
1606
1607 def test_empty_group_list(self):
1608 g = Group('foo', addresses=[])
1609 self.assertEqual(g.display_name, 'foo')
1610 self.assertEqual(g.addresses, tuple())
1611 self.assertEqual(str(g), 'foo:;')
1612
1613 def test_null_group(self):
1614 g = Group()
1615 self.assertIsNone(g.display_name)
1616 self.assertEqual(g.addresses, tuple())
1617 self.assertEqual(str(g), 'None:;')
1618
1619 def test_group_with_addresses(self):
1620 addrs = [Address('b', 'b', 'c'), Address('a', 'b','c')]
1621 g = Group('foo', addrs)
1622 self.assertEqual(g.display_name, 'foo')
1623 self.assertEqual(g.addresses, tuple(addrs))
1624 self.assertEqual(str(g), 'foo: b <b@c>, a <b@c>;')
1625
1626 def test_group_with_addresses_no_display_name(self):
1627 addrs = [Address('b', 'b', 'c'), Address('a', 'b','c')]
1628 g = Group(addresses=addrs)
1629 self.assertIsNone(g.display_name)
1630 self.assertEqual(g.addresses, tuple(addrs))
1631 self.assertEqual(str(g), 'None: b <b@c>, a <b@c>;')
1632
1633 def test_group_with_one_address_no_display_name(self):
1634 addrs = [Address('b', 'b', 'c')]
1635 g = Group(addresses=addrs)
1636 self.assertIsNone(g.display_name)
1637 self.assertEqual(g.addresses, tuple(addrs))
1638 self.assertEqual(str(g), 'b <b@c>')
1639
1640 def test_display_name_quoting(self):
1641 g = Group('foo.bar')
1642 self.assertEqual(g.display_name, 'foo.bar')
1643 self.assertEqual(g.addresses, tuple())
1644 self.assertEqual(str(g), '"foo.bar":;')
1645
1646 def test_display_name_blanks_not_quoted(self):
1647 g = Group('foo bar')
1648 self.assertEqual(g.display_name, 'foo bar')
1649 self.assertEqual(g.addresses, tuple())
1650 self.assertEqual(str(g), 'foo bar:;')
1651
1652 def test_set_message_header_from_address(self):
1653 a = Address('foo', 'bar', 'example.com')
1654 m = Message(policy=policy.default)
1655 m['To'] = a
1656 self.assertEqual(m['to'], 'foo <[email protected]>')
1657 self.assertEqual(m['to'].addresses, (a,))
1658
1659 def test_set_message_header_from_group(self):
1660 g = Group('foo bar')
1661 m = Message(policy=policy.default)
1662 m['To'] = g
1663 self.assertEqual(m['to'], 'foo bar:;')
1664 self.assertEqual(m['to'].addresses, g.addresses)
1665
1666 def test_address_comparison(self):
1667 a = Address('foo', 'bar', 'example.com')
1668 self.assertEqual(Address('foo', 'bar', 'example.com'), a)
1669 self.assertNotEqual(Address('baz', 'bar', 'example.com'), a)
1670 self.assertNotEqual(Address('foo', 'baz', 'example.com'), a)
1671 self.assertNotEqual(Address('foo', 'bar', 'baz'), a)
1672 self.assertFalse(a == object())
1673 self.assertTrue(a == ALWAYS_EQ)
1674
1675 def test_group_comparison(self):
1676 a = Address('foo', 'bar', 'example.com')
1677 g = Group('foo bar', [a])
1678 self.assertEqual(Group('foo bar', (a,)), g)
1679 self.assertNotEqual(Group('baz', [a]), g)
1680 self.assertNotEqual(Group('foo bar', []), g)
1681 self.assertFalse(g == object())
1682 self.assertTrue(g == ALWAYS_EQ)
1683
1684
1685 class TestFolding(TestHeaderBase):
1686
1687 def test_address_display_names(self):
1688 """Test the folding and encoding of address headers."""
1689 for name, result in (
1690 ('Foo Bar, France', '"Foo Bar, France"'),
1691 ('Foo Bar (France)', '"Foo Bar (France)"'),
1692 ('Foo Bar, España', 'Foo =?utf-8?q?Bar=2C_Espa=C3=B1a?='),
1693 ('Foo Bar (España)', 'Foo Bar =?utf-8?b?KEVzcGHDsWEp?='),
1694 ('Foo, Bar España', '=?utf-8?q?Foo=2C_Bar_Espa=C3=B1a?='),
1695 ('Foo, Bar [España]', '=?utf-8?q?Foo=2C_Bar_=5BEspa=C3=B1a=5D?='),
1696 ('Foo Bär, France', 'Foo =?utf-8?q?B=C3=A4r=2C?= France'),
1697 ('Foo Bär <France>', 'Foo =?utf-8?q?B=C3=A4r_=3CFrance=3E?='),
1698 (
1699 'Lôrem ipsum dôlôr sit amet, cônsectetuer adipiscing. '
1700 'Suspendisse pôtenti. Aliquam nibh. Suspendisse pôtenti.',
1701 '=?utf-8?q?L=C3=B4rem_ipsum_d=C3=B4l=C3=B4r_sit_amet=2C_c'
1702 '=C3=B4nsectetuer?=\n =?utf-8?q?_adipiscing=2E_Suspendisse'
1703 '_p=C3=B4tenti=2E_Aliquam_nibh=2E?=\n Suspendisse =?utf-8'
1704 '?q?p=C3=B4tenti=2E?=',
1705 ),
1706 ):
1707 h = self.make_header('To', Address(name, addr_spec='[email protected]'))
1708 self.assertEqual(h.fold(policy=policy.default),
1709 'To: %s <[email protected]>\n' % result)
1710
1711 def test_short_unstructured(self):
1712 h = self.make_header('subject', 'this is a test')
1713 self.assertEqual(h.fold(policy=policy.default),
1714 'subject: this is a test\n')
1715
1716 def test_long_unstructured(self):
1717 h = self.make_header('Subject', 'This is a long header '
1718 'line that will need to be folded into two lines '
1719 'and will demonstrate basic folding')
1720 self.assertEqual(h.fold(policy=policy.default),
1721 'Subject: This is a long header line that will '
1722 'need to be folded into two lines\n'
1723 ' and will demonstrate basic folding\n')
1724
1725 def test_unstructured_short_max_line_length(self):
1726 h = self.make_header('Subject', 'this is a short header '
1727 'that will be folded anyway')
1728 self.assertEqual(
1729 h.fold(policy=policy.default.clone(max_line_length=20)),
1730 textwrap.dedent("""\
1731 Subject: this is a
1732 short header that
1733 will be folded
1734 anyway
1735 """))
1736
1737 def test_fold_unstructured_single_word(self):
1738 h = self.make_header('Subject', 'test')
1739 self.assertEqual(h.fold(policy=policy.default), 'Subject: test\n')
1740
1741 def test_fold_unstructured_short(self):
1742 h = self.make_header('Subject', 'test test test')
1743 self.assertEqual(h.fold(policy=policy.default),
1744 'Subject: test test test\n')
1745
1746 def test_fold_unstructured_with_overlong_word(self):
1747 h = self.make_header('Subject', 'thisisaverylonglineconsistingofa'
1748 'singlewordthatwontfit')
1749 self.assertEqual(
1750 h.fold(policy=policy.default.clone(max_line_length=20)),
1751 'Subject:\n'
1752 ' =?utf-8?q?thisisa?=\n'
1753 ' =?utf-8?q?verylon?=\n'
1754 ' =?utf-8?q?glineco?=\n'
1755 ' =?utf-8?q?nsistin?=\n'
1756 ' =?utf-8?q?gofasin?=\n'
1757 ' =?utf-8?q?gleword?=\n'
1758 ' =?utf-8?q?thatwon?=\n'
1759 ' =?utf-8?q?tfit?=\n'
1760 )
1761
1762 def test_fold_unstructured_with_two_overlong_words(self):
1763 h = self.make_header('Subject', 'thisisaverylonglineconsistingofa'
1764 'singlewordthatwontfit plusanotherverylongwordthatwontfit')
1765 self.assertEqual(
1766 h.fold(policy=policy.default.clone(max_line_length=20)),
1767 'Subject:\n'
1768 ' =?utf-8?q?thisisa?=\n'
1769 ' =?utf-8?q?verylon?=\n'
1770 ' =?utf-8?q?glineco?=\n'
1771 ' =?utf-8?q?nsistin?=\n'
1772 ' =?utf-8?q?gofasin?=\n'
1773 ' =?utf-8?q?gleword?=\n'
1774 ' =?utf-8?q?thatwon?=\n'
1775 ' =?utf-8?q?tfit_pl?=\n'
1776 ' =?utf-8?q?usanoth?=\n'
1777 ' =?utf-8?q?erveryl?=\n'
1778 ' =?utf-8?q?ongword?=\n'
1779 ' =?utf-8?q?thatwon?=\n'
1780 ' =?utf-8?q?tfit?=\n'
1781 )
1782
1783 # XXX Need test for when max_line_length is less than the chrome size.
1784
1785 def test_fold_unstructured_with_slightly_long_word(self):
1786 h = self.make_header('Subject', 'thislongwordislessthanmaxlinelen')
1787 self.assertEqual(
1788 h.fold(policy=policy.default.clone(max_line_length=35)),
1789 'Subject:\n thislongwordislessthanmaxlinelen\n')
1790
1791 def test_fold_unstructured_with_commas(self):
1792 # The old wrapper would fold this at the commas.
1793 h = self.make_header('Subject', "This header is intended to "
1794 "demonstrate, in a fairly succinct way, that we now do "
1795 "not give a , special treatment in unstructured headers.")
1796 self.assertEqual(
1797 h.fold(policy=policy.default.clone(max_line_length=60)),
1798 textwrap.dedent("""\
1799 Subject: This header is intended to demonstrate, in a fairly
1800 succinct way, that we now do not give a , special treatment
1801 in unstructured headers.
1802 """))
1803
1804 def test_fold_address_list(self):
1805 h = self.make_header('To', '"Theodore H. Perfect" <[email protected]>, '
1806 '"My address is very long because my name is long" <[email protected]>, '
1807 '"Only A. Friend" <[email protected]>')
1808 self.assertEqual(h.fold(policy=policy.default), textwrap.dedent("""\
1809 To: "Theodore H. Perfect" <[email protected]>,
1810 "My address is very long because my name is long" <[email protected]>,
1811 "Only A. Friend" <[email protected]>
1812 """))
1813
1814 def test_fold_date_header(self):
1815 h = self.make_header('Date', 'Sat, 2 Feb 2002 17:00:06 -0800')
1816 self.assertEqual(h.fold(policy=policy.default),
1817 'Date: Sat, 02 Feb 2002 17:00:06 -0800\n')
1818
1819 def test_fold_overlong_words_using_RFC2047(self):
1820 h = self.make_header(
1821 'X-Report-Abuse',
1822 '<https://www.mailitapp.com/report_abuse.php?'
1823 'mid=xxx-xxx-xxxxxxxxxxxxxxxxxxxxxxxx==-xxx-xx-xx>')
1824 self.assertEqual(
1825 h.fold(policy=policy.default),
1826 'X-Report-Abuse: =?utf-8?q?=3Chttps=3A//www=2Emailitapp=2E'
1827 'com/report=5Fabuse?=\n'
1828 ' =?utf-8?q?=2Ephp=3Fmid=3Dxxx-xxx-xxxx'
1829 'xxxxxxxxxxxxxxxxxxxx=3D=3D-xxx-xx-xx?=\n'
1830 ' =?utf-8?q?=3E?=\n')
1831
1832 def test_message_id_header_is_not_folded(self):
1833 h = self.make_header(
1834 'Message-ID',
1835 '<[email protected]>')
1836 self.assertEqual(
1837 h.fold(policy=policy.default.clone(max_line_length=20)),
1838 'Message-ID: <[email protected]>\n')
1839
1840 # Test message-id isn't folded when id-right is no-fold-literal.
1841 h = self.make_header(
1842 'Message-ID',
1843 '<somemessageidlongerthan@[127.0.0.0.0.0.0.0.0.1]>')
1844 self.assertEqual(
1845 h.fold(policy=policy.default.clone(max_line_length=20)),
1846 'Message-ID: <somemessageidlongerthan@[127.0.0.0.0.0.0.0.0.1]>\n')
1847
1848 # Test message-id isn't folded when id-right is non-ascii characters.
1849 h = self.make_header('Message-ID', '<ईमेल@wők.com>')
1850 self.assertEqual(
1851 h.fold(policy=policy.default.clone(max_line_length=30)),
1852 'Message-ID: <ईमेल@wők.com>\n')
1853
1854 # Test message-id is folded without breaking the msg-id token into
1855 # encoded words, *even* if they don't fit into max_line_length.
1856 h = self.make_header('Message-ID', '<ईमेलfromMessage@wők.com>')
1857 self.assertEqual(
1858 h.fold(policy=policy.default.clone(max_line_length=20)),
1859 'Message-ID:\n <ईमेलfromMessage@wők.com>\n')
1860
1861 def test_fold_references(self):
1862 h = self.make_header(
1863 'References',
1864 '<[email protected]> '
1865 '<[email protected]>'
1866 )
1867 self.assertEqual(
1868 h.fold(policy=policy.default.clone(max_line_length=20)),
1869 'References: '
1870 '<[email protected]>\n'
1871 ' <[email protected]>\n')
1872
1873
1874 if __name__ == '__main__':
1875 unittest.main()