Debian Codegraph @

tests/test_response_parser.py

raw
1 # Copyright (c) 2014, Menno Smits
2 # Released subject to the New BSD License
3 # Please see http://en.wikipedia.org/wiki/BSD_licenses
4
5 """
6 Unit tests for the FetchTokeniser and FetchParser classes
7 """
8
9 import unittest
10 from datetime import datetime
11 from unittest.mock import patch
12
13 from imapclient.datetime_util import datetime_to_native
14 from imapclient.exceptions import ProtocolError
15 from imapclient.fixed_offset import FixedOffset
16 from imapclient.response_parser import (
17 parse_fetch_response,
18 parse_message_list,
19 parse_response,
20 )
21 from imapclient.response_types import Address, Envelope
22
23 # TODO: test invalid dates and times
24
25
26 CRLF = b"\r\n"
27
28
29 class TestParseResponse(unittest.TestCase):
30 def test_unquoted(self):
31 self._test(b"FOO", b"FOO")
32 self._test(b"F.O:-O_0;", b"F.O:-O_0;")
33 self._test(rb"\Seen", rb"\Seen")
34
35 def test_string(self):
36 self._test(b'"TEST"', b"TEST")
37
38 def test_int(self):
39 self._test(b"45", 45)
40
41 def test_int_zero(self):
42 self._test(b"0", 0)
43
44 def test_not_an_int(self):
45 self._test(b"0123", b"0123")
46
47 def test_nil(self):
48 self._test(b"NIL", None)
49
50 def test_empty_tuple(self):
51 self._test(b"()", ())
52
53 def test_tuple(self):
54 self._test(b'(123 "foo" GeE)', (123, b"foo", b"GeE"))
55
56 def test_int_and_tuple(self):
57 self._test(b'1 (123 "foo")', (1, (123, b"foo")), wrap=False)
58
59 def test_nested_tuple(self):
60 self._test(b'(123 "foo" ("more" NIL) 66)', (123, b"foo", (b"more", None), 66))
61
62 def test_deeper_nest_tuple(self):
63 self._test(
64 b'(123 "foo" ((0 1 2) "more" NIL) 66)',
65 (123, b"foo", ((0, 1, 2), b"more", None), 66),
66 )
67
68 def test_complex_mixed(self):
69 self._test(
70 b'((FOO "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23) '
71 b'("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") '
72 b'"<hi.there>" "foo" "BASE64" 4554 73) "MIXED")',
73 (
74 (
75 b"FOO",
76 b"PLAIN",
77 (b"CHARSET", b"US-ASCII"),
78 None,
79 None,
80 b"7BIT",
81 1152,
82 23,
83 ),
84 (
85 b"TEXT",
86 b"PLAIN",
87 (b"CHARSET", b"US-ASCII", b"NAME", b"cc.diff"),
88 b"<hi.there>",
89 b"foo",
90 b"BASE64",
91 4554,
92 73,
93 ),
94 b"MIXED",
95 ),
96 )
97
98 def test_envelopey(self):
99 self._test(
100 b'(UID 5 ENVELOPE ("internal_date" "subject" '
101 b'(("name" NIL "address1" "domain1.com")) '
102 b'((NIL NIL "address2" "domain2.com")) '
103 b'(("name" NIL "address3" "domain3.com")) '
104 b'((NIL NIL "address4" "domain4.com")) '
105 b'NIL NIL "<reply-to-id>" "<msg_id>"))',
106 (
107 b"UID",
108 5,
109 b"ENVELOPE",
110 (
111 b"internal_date",
112 b"subject",
113 ((b"name", None, b"address1", b"domain1.com"),),
114 ((None, None, b"address2", b"domain2.com"),),
115 ((b"name", None, b"address3", b"domain3.com"),),
116 ((None, None, b"address4", b"domain4.com"),),
117 None,
118 None,
119 b"<reply-to-id>",
120 b"<msg_id>",
121 ),
122 ),
123 )
124
125 def test_envelopey_quoted(self):
126 self._test(
127 b'(UID 5 ENVELOPE ("internal_date" "subject with \\"quotes\\"" '
128 b'(("name" NIL "address1" "domain1.com")) '
129 b'((NIL NIL "address2" "domain2.com")) '
130 b'(("name" NIL "address3" "domain3.com")) '
131 b'((NIL NIL "address4" "domain4.com")) '
132 b'NIL NIL "<reply-to-id>" "<msg_id>"))',
133 (
134 b"UID",
135 5,
136 b"ENVELOPE",
137 (
138 b"internal_date",
139 b'subject with "quotes"',
140 ((b"name", None, b"address1", b"domain1.com"),),
141 ((None, None, b"address2", b"domain2.com"),),
142 ((b"name", None, b"address3", b"domain3.com"),),
143 ((None, None, b"address4", b"domain4.com"),),
144 None,
145 None,
146 b"<reply-to-id>",
147 b"<msg_id>",
148 ),
149 ),
150 )
151
152 def test_literal(self):
153 literal_text = add_crlf(b"012\n" b"abc def XYZ\n")
154 self._test([(b"{18}", literal_text)], literal_text)
155
156 def test_literal_with_more(self):
157 literal_text = add_crlf(b"012\n" b"abc def XYZ\n")
158 response = [(b'(12 "foo" {18}', literal_text), b")"]
159 self._test(response, (12, b"foo", literal_text))
160
161 def test_quoted_specials(self):
162 self._test(rb'"\"foo bar\""', b'"foo bar"')
163 self._test(rb'"foo \"bar\""', b'foo "bar"')
164 self._test(rb'"foo\\bar"', rb"foo\bar")
165
166 def test_square_brackets(self):
167 self._test(b"foo[bar rrr]", b"foo[bar rrr]")
168 self._test(b'"foo[bar rrr]"', b"foo[bar rrr]")
169 self._test(b"[foo bar]def", b"[foo bar]def")
170 self._test(b"(foo [bar rrr])", (b"foo", b"[bar rrr]"))
171 self._test(b"(foo foo[bar rrr])", (b"foo", b"foo[bar rrr]"))
172
173 def test_incomplete_tuple(self):
174 self._test_parse_error(b"abc (1 2", r'Tuple incomplete before "\(1 2"')
175
176 def test_bad_literal(self):
177 self._test_parse_error(
178 [(b"{99}", b"abc")], "Expecting literal of size 99, got 3"
179 )
180
181 def test_bad_quoting(self):
182 self._test_parse_error(b'"abc next', """No closing '"'""")
183
184 def _test(self, to_parse, expected, wrap=True):
185 if wrap:
186 # convenience - expected value should be wrapped in another tuple
187 expected = (expected,)
188 if not isinstance(to_parse, list):
189 to_parse = [to_parse]
190 output = parse_response(to_parse)
191 self.assertSequenceEqual(output, expected)
192
193 def _test_parse_error(self, to_parse, expected_msg):
194 if not isinstance(to_parse, list):
195 to_parse = [to_parse]
196 self.assertRaisesRegex(ProtocolError, expected_msg, parse_response, to_parse)
197
198
199 class TestParseMessageList(unittest.TestCase):
200 def test_basic(self):
201 out = parse_message_list([b"1 2 3"])
202 self.assertSequenceEqual(out, [1, 2, 3])
203 self.assertEqual(out.modseq, None)
204
205 def test_one_id(self):
206 self.assertSequenceEqual(parse_message_list([b"4"]), [4])
207
208 def test_modseq(self):
209 out = parse_message_list([b"1 2 3 (modseq 999)"])
210 self.assertSequenceEqual(out, [1, 2, 3])
211 self.assertEqual(out.modseq, 999)
212
213 def test_modseq_no_space(self):
214 out = parse_message_list([b"1 2 3(modseq 999)"])
215 self.assertSequenceEqual(out, [1, 2, 3])
216 self.assertEqual(out.modseq, 999)
217
218 def test_modseq_interleaved(self):
219 # Unlikely but test it anyway.
220 out = parse_message_list([b"1 2 (modseq 9) 3 4"])
221 self.assertSequenceEqual(out, [1, 2, 3, 4])
222 self.assertEqual(out.modseq, 9)
223
224
225 class TestParseFetchResponse(unittest.TestCase):
226 def test_basic(self):
227 self.assertEqual(parse_fetch_response([b"4 ()"]), {4: {b"SEQ": 4}})
228
229 def test_none_special_case(self):
230 self.assertEqual(parse_fetch_response([None]), {})
231
232 def test_bad_msgid(self):
233 self.assertRaises(ProtocolError, parse_fetch_response, [b"abc ()"])
234
235 def test_bad_data(self):
236 self.assertRaises(ProtocolError, parse_fetch_response, [b"2 WHAT"])
237
238 def test_missing_data(self):
239 self.assertRaises(ProtocolError, parse_fetch_response, [b"2"])
240
241 def test_simple_pairs(self):
242 self.assertEqual(
243 parse_fetch_response([b'23 (ABC 123 StUfF "hello")']),
244 {23: {b"ABC": 123, b"STUFF": b"hello", b"SEQ": 23}},
245 )
246
247 def test_odd_pairs(self):
248 self.assertRaises(ProtocolError, parse_fetch_response, [b"(ONE)"])
249 self.assertRaises(ProtocolError, parse_fetch_response, [b"(ONE TWO THREE)"])
250
251 def test_UID(self):
252 self.assertEqual(parse_fetch_response([b"23 (UID 76)"]), {76: {b"SEQ": 23}})
253 self.assertEqual(parse_fetch_response([b"23 (uiD 76)"]), {76: {b"SEQ": 23}})
254
255 def test_not_uid_is_key(self):
256 self.assertEqual(
257 parse_fetch_response([b"23 (UID 76)"], uid_is_key=False),
258 {23: {b"UID": 76, b"SEQ": 23}},
259 )
260
261 def test_bad_UID(self):
262 self.assertRaises(ProtocolError, parse_fetch_response, [b"(UID X)"])
263
264 def test_FLAGS(self):
265 self.assertEqual(
266 parse_fetch_response([rb"23 (FLAGS (\Seen Stuff))"]),
267 {23: {b"SEQ": 23, b"FLAGS": (rb"\Seen", b"Stuff")}},
268 )
269
270 def test_multiple_messages(self):
271 self.assertEqual(
272 parse_fetch_response([b"2 (FLAGS (Foo Bar)) ", b"7 (FLAGS (Baz Sneeve))"]),
273 {
274 2: {b"FLAGS": (b"Foo", b"Bar"), b"SEQ": 2},
275 7: {b"FLAGS": (b"Baz", b"Sneeve"), b"SEQ": 7},
276 },
277 )
278
279 def test_same_message_appearing_multiple_times(self):
280 # This can occur when server sends unsolicited FETCH responses
281 # (e.g. RFC 4551)
282 self.assertEqual(
283 parse_fetch_response([b"2 (FLAGS (Foo Bar)) ", b"2 (MODSEQ 4)"]),
284 {2: {b"FLAGS": (b"Foo", b"Bar"), b"SEQ": 2, b"MODSEQ": 4}},
285 )
286
287 def test_literals(self):
288 self.assertEqual(
289 parse_fetch_response(
290 [
291 (b"1 (RFC822.TEXT {4}", b"body"),
292 (b" RFC822 {21}", b"Subject: test\r\n\r\nbody"),
293 b")",
294 ]
295 ),
296 {
297 1: {
298 b"RFC822.TEXT": b"body",
299 b"RFC822": b"Subject: test\r\n\r\nbody",
300 b"SEQ": 1,
301 }
302 },
303 )
304
305 def test_literals_and_keys_with_square_brackets(self):
306 self.assertEqual(
307 parse_fetch_response([(b"1 (BODY[TEXT] {11}", b"Hi there.\r\n"), b")"]),
308 {1: {b"BODY[TEXT]": b"Hi there.\r\n", b"SEQ": 1}},
309 )
310
311 def test_BODY_HEADER_FIELDS(self):
312 header_text = b"Subject: A subject\r\nFrom: Some one <[email protected]>\r\n\r\n"
313 self.assertEqual(
314 parse_fetch_response(
315 [
316 (
317 b"123 (UID 31710 BODY[HEADER.FIELDS (from subject)] {57}",
318 header_text,
319 ),
320 b")",
321 ]
322 ),
323 {31710: {b"BODY[HEADER.FIELDS (FROM SUBJECT)]": header_text, b"SEQ": 123}},
324 )
325
326 def test_BODY(self):
327 self.check_BODYish_single_part(b"BODY")
328 self.check_BODYish_multipart(b"BODY")
329 self.check_BODYish_nested_multipart(b"BODY")
330
331 def test_BODYSTRUCTURE(self):
332 self.check_BODYish_single_part(b"BODYSTRUCTURE")
333 self.check_BODYish_nested_multipart(b"BODYSTRUCTURE")
334
335 def check_BODYish_single_part(self, respType):
336 text = (
337 b"123 (UID 317 "
338 + respType
339 + b'("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 16 1))'
340 )
341 parsed = parse_fetch_response([text])
342 self.assertEqual(
343 parsed,
344 {
345 317: {
346 respType: (
347 b"TEXT",
348 b"PLAIN",
349 (b"CHARSET", b"us-ascii"),
350 None,
351 None,
352 b"7BIT",
353 16,
354 1,
355 ),
356 b"SEQ": 123,
357 }
358 },
359 )
360 self.assertFalse(parsed[317][respType].is_multipart)
361
362 def check_BODYish_multipart(self, respType):
363 text = (
364 b"123 (UID 269 " + respType + b" "
365 b'(("TEXT" "HTML" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 55 3)'
366 b'("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 26 1) "MIXED"))'
367 )
368 parsed = parse_fetch_response([text])
369 self.assertEqual(
370 parsed,
371 {
372 269: {
373 respType: (
374 [
375 (
376 b"TEXT",
377 b"HTML",
378 (b"CHARSET", b"us-ascii"),
379 None,
380 None,
381 b"QUOTED-PRINTABLE",
382 55,
383 3,
384 ),
385 (
386 b"TEXT",
387 b"PLAIN",
388 (b"CHARSET", b"us-ascii"),
389 None,
390 None,
391 b"7BIT",
392 26,
393 1,
394 ),
395 ],
396 b"MIXED",
397 ),
398 b"SEQ": 123,
399 }
400 },
401 )
402 self.assertTrue(parsed[269][respType].is_multipart)
403
404 def check_BODYish_nested_multipart(self, respType):
405 text = (
406 b"1 (" + respType + b"("
407 b"("
408 b'("text" "html" ("charset" "utf-8") NIL NIL "7bit" 97 3 NIL NIL NIL NIL)'
409 b'("text" "plain" ("charset" "utf-8") NIL NIL "7bit" 62 3 NIL NIL NIL NIL)'
410 b'"alternative" ("boundary" "===============8211050864078048428==") NIL NIL NIL'
411 b")"
412 b'("text" "plain" ("charset" "utf-8") NIL NIL "7bit" 16 1 NIL ("attachment" ("filename" "attachment.txt")) NIL NIL) '
413 b'"mixed" ("boundary" "===============0373402508605428821==") NIL NIL NIL))'
414 )
415
416 parsed = parse_fetch_response([text])
417 self.assertEqual(
418 parsed,
419 {
420 1: {
421 respType: (
422 [
423 (
424 [
425 (
426 b"text",
427 b"html",
428 (b"charset", b"utf-8"),
429 None,
430 None,
431 b"7bit",
432 97,
433 3,
434 None,
435 None,
436 None,
437 None,
438 ),
439 (
440 b"text",
441 b"plain",
442 (b"charset", b"utf-8"),
443 None,
444 None,
445 b"7bit",
446 62,
447 3,
448 None,
449 None,
450 None,
451 None,
452 ),
453 ],
454 b"alternative",
455 (b"boundary", b"===============8211050864078048428=="),
456 None,
457 None,
458 None,
459 ),
460 (
461 b"text",
462 b"plain",
463 (b"charset", b"utf-8"),
464 None,
465 None,
466 b"7bit",
467 16,
468 1,
469 None,
470 (b"attachment", (b"filename", b"attachment.txt")),
471 None,
472 None,
473 ),
474 ],
475 b"mixed",
476 (b"boundary", b"===============0373402508605428821=="),
477 None,
478 None,
479 None,
480 ),
481 b"SEQ": 1,
482 }
483 },
484 )
485 self.assertTrue(parsed[1][respType].is_multipart)
486 self.assertTrue(parsed[1][respType][0][0].is_multipart)
487 self.assertFalse(parsed[1][respType][0][0][0][0].is_multipart)
488
489 def test_partial_fetch(self):
490 body = b"01234567890123456789"
491 self.assertEqual(
492 parse_fetch_response([(b"123 (UID 367 BODY[]<0> {20}", body), b")"]),
493 {367: {b"BODY[]<0>": body, b"SEQ": 123}},
494 )
495
496 def test_ENVELOPE(self):
497 envelope_str = (
498 b"1 (ENVELOPE ( "
499 b'"Sun, 24 Mar 2013 22:06:10 +0200" '
500 b'"subject" '
501 b'(("name" NIL "address1" "domain1.com")) ' # from (name and address)
502 b'((NIL NIL "address2" "domain2.com")) ' # sender (just address)
503 b'(("name" NIL "address3" "domain3.com") NIL) ' # reply to
504 b"NIL" # to (no address)
505 b'((NIL NIL "address4" "domain4.com") ' # cc
506 b'("person" NIL "address4b" "domain4b.com")) '
507 b"NIL " # bcc
508 b'"<reply-to-id>" '
509 b'"<msg_id>"))'
510 )
511
512 output = parse_fetch_response([envelope_str], normalise_times=False)
513
514 self.assertEqual(
515 output[1][b"ENVELOPE"],
516 Envelope(
517 datetime(2013, 3, 24, 22, 6, 10, tzinfo=FixedOffset(120)),
518 b"subject",
519 (Address(b"name", None, b"address1", b"domain1.com"),),
520 (Address(None, None, b"address2", b"domain2.com"),),
521 (Address(b"name", None, b"address3", b"domain3.com"),),
522 None,
523 (
524 Address(None, None, b"address4", b"domain4.com"),
525 Address(b"person", None, b"address4b", b"domain4b.com"),
526 ),
527 None,
528 b"<reply-to-id>",
529 b"<msg_id>",
530 ),
531 )
532
533 def test_ENVELOPE_with_no_date(self):
534 envelope_str = (
535 b"1 (ENVELOPE ( "
536 b"NIL "
537 b'"subject" '
538 b"NIL "
539 b"NIL "
540 b"NIL "
541 b"NIL "
542 b"NIL "
543 b"NIL "
544 b'"<reply-to-id>" '
545 b'"<msg_id>"))'
546 )
547
548 output = parse_fetch_response([envelope_str], normalise_times=False)
549
550 self.assertEqual(
551 output[1][b"ENVELOPE"],
552 Envelope(
553 None,
554 b"subject",
555 None,
556 None,
557 None,
558 None,
559 None,
560 None,
561 b"<reply-to-id>",
562 b"<msg_id>",
563 ),
564 )
565
566 def test_ENVELOPE_with_invalid_date(self):
567 envelope_str = (
568 b"1 (ENVELOPE ( "
569 b'"wtf" ' # bad date
570 b'"subject" '
571 b"NIL NIL NIL NIL NIL NIL "
572 b'"<reply-to-id>" "<msg_id>"))'
573 )
574
575 output = parse_fetch_response([envelope_str], normalise_times=False)
576
577 self.assertEqual(
578 output[1][b"ENVELOPE"],
579 Envelope(
580 None,
581 b"subject",
582 None,
583 None,
584 None,
585 None,
586 None,
587 None,
588 b"<reply-to-id>",
589 b"<msg_id>",
590 ),
591 )
592
593 def test_ENVELOPE_with_empty_addresses(self):
594 envelope_str = (
595 b"1 (ENVELOPE ( "
596 b"NIL "
597 b'"subject" '
598 b'(("name" NIL "address1" "domain1.com") NIL) '
599 b'(NIL (NIL NIL "address2" "domain2.com")) '
600 b'(("name" NIL "address3" "domain3.com") NIL ("name" NIL "address3b" "domain3b.com")) '
601 b"NIL"
602 b'((NIL NIL "address4" "domain4.com") '
603 b'("person" NIL "address4b" "domain4b.com")) '
604 b'NIL "<reply-to-id>" "<msg_id>"))'
605 )
606
607 output = parse_fetch_response([envelope_str], normalise_times=False)
608
609 self.assertEqual(
610 output[1][b"ENVELOPE"],
611 Envelope(
612 None,
613 b"subject",
614 (Address(b"name", None, b"address1", b"domain1.com"),),
615 (Address(None, None, b"address2", b"domain2.com"),),
616 (
617 Address(b"name", None, b"address3", b"domain3.com"),
618 Address(b"name", None, b"address3b", b"domain3b.com"),
619 ),
620 None,
621 (
622 Address(None, None, b"address4", b"domain4.com"),
623 Address(b"person", None, b"address4b", b"domain4b.com"),
624 ),
625 None,
626 b"<reply-to-id>",
627 b"<msg_id>",
628 ),
629 )
630
631 def test_INTERNALDATE(self):
632 out = parse_fetch_response(
633 [b'1 (INTERNALDATE " 9-Feb-2007 17:08:08 -0430")'], normalise_times=False
634 )
635 self.assertEqual(
636 out[1][b"INTERNALDATE"],
637 datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4 * 60 - 30)),
638 )
639
640 def test_INTERNALDATE_normalised(self):
641 output = parse_fetch_response(
642 [b'3 (INTERNALDATE " 9-Feb-2007 17:08:08 -0430")']
643 )
644 dt = output[3][b"INTERNALDATE"]
645 self.assertTrue(dt.tzinfo is None) # Returned date should be in local timezone
646 expected_dt = datetime_to_native(
647 datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4 * 60 - 30))
648 )
649 self.assertEqual(dt, expected_dt)
650
651 def test_INTERNALDATE_NIL(self):
652 out = parse_fetch_response([b"1 (INTERNALDATE NIL)"])
653 self.assertEqual(out[1][b"INTERNALDATE"], None)
654
655 def test_mixed_types(self):
656 self.assertEqual(
657 parse_fetch_response(
658 [
659 (
660 b'1 (INTERNALDATE " 9-Feb-2007 17:08:08 +0100" RFC822 {21}',
661 b"Subject: test\r\n\r\nbody",
662 ),
663 b")",
664 ]
665 ),
666 {
667 1: {
668 b"INTERNALDATE": datetime_to_native(
669 datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(60))
670 ),
671 b"RFC822": b"Subject: test\r\n\r\nbody",
672 b"SEQ": 1,
673 }
674 },
675 )
676
677 def test_Address_str(self):
678 self.assertEqual(
679 str(Address(b"Mary Jane", None, b"mary", b"jane.org")),
680 "Mary Jane <[email protected]>",
681 )
682
683 self.assertEqual(
684 str(Address("Mary Jane", None, "mary", "jane.org")),
685 "Mary Jane <[email protected]>",
686 )
687
688 self.assertEqual(
689 str(Address("Anonymous", None, "undisclosed-recipients", None)),
690 "Anonymous <undisclosed-recipients>",
691 )
692
693 self.assertEqual(
694 str(Address(None, None, None, "undisclosed-recipients")),
695 "undisclosed-recipients",
696 )
697
698 @patch("imapclient.util.logger")
699 def test_Address_str_ignores_encoding_error(self, mock_logger):
700 self.assertEqual(
701 str(
702 Address(
703 b"Russian \xc2\xeb\xe0\xe4\xe8\xec\xe8\xf0",
704 None,
705 b"g\xe9rard",
706 "domain.org",
707 )
708 ),
709 "Russian <[email protected]>",
710 )
711 # Ensure warning has been triggered twice, for name and mailbox bytes
712 self.assertEqual(mock_logger.warning.call_count, 2)
713
714
715 def add_crlf(text):
716 return CRLF.join(text.splitlines()) + CRLF