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