-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathtest_multipart.py
More file actions
1709 lines (1450 loc) · 68.9 KB
/
test_multipart.py
File metadata and controls
1709 lines (1450 loc) · 68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import functools
import io
import os
import unittest
import zlib
from unittest import mock
import aiohttp.multipart
from aiohttp import helpers
from aiohttp.hdrs import (CONTENT_DISPOSITION, CONTENT_ENCODING,
CONTENT_TRANSFER_ENCODING, CONTENT_TYPE)
from aiohttp.helpers import parse_mimetype
from aiohttp.multipart import (content_disposition_filename,
parse_content_disposition)
def run_in_loop(f):
@functools.wraps(f)
def wrapper(testcase, *args, **kwargs):
coro = asyncio.coroutine(f)
future = asyncio.wait_for(coro(testcase, *args, **kwargs), timeout=5)
return testcase.loop.run_until_complete(future)
return wrapper
class MetaAioTestCase(type):
def __new__(cls, name, bases, attrs):
for key, obj in attrs.items():
if key.startswith('test_'):
attrs[key] = run_in_loop(obj)
return super().__new__(cls, name, bases, attrs)
class TestCase(unittest.TestCase, metaclass=MetaAioTestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
def tearDown(self):
self.loop.close()
def future(self, obj):
fut = helpers.create_future(self.loop)
fut.set_result(obj)
return fut
class Response(object):
def __init__(self, headers, content):
self.headers = headers
self.content = content
class Stream(object):
def __init__(self, content):
self.content = io.BytesIO(content)
@asyncio.coroutine
def read(self, size=None):
return self.content.read(size)
def at_eof(self):
return self.content.tell() == len(self.content.getbuffer())
@asyncio.coroutine
def readline(self):
return self.content.readline()
def unread_data(self, data):
self.content = io.BytesIO(data + self.content.read())
class StreamWithShortenRead(Stream):
def __init__(self, content):
self._first = True
super().__init__(content)
@asyncio.coroutine
def read(self, size=None):
if size is not None and self._first:
self._first = False
size = size // 2
return (yield from super().read(size))
class MultipartResponseWrapperTestCase(TestCase):
def setUp(self):
super().setUp()
wrapper = aiohttp.multipart.MultipartResponseWrapper(mock.Mock(),
mock.Mock())
self.wrapper = wrapper
def test_at_eof(self):
self.wrapper.at_eof()
self.assertTrue(self.wrapper.resp.content.at_eof.called)
def test_next(self):
self.wrapper.stream.next.return_value = self.future(b'')
self.wrapper.stream.at_eof.return_value = False
yield from self.wrapper.next()
self.assertTrue(self.wrapper.stream.next.called)
def test_release(self):
self.wrapper.resp.release.return_value = self.future(None)
yield from self.wrapper.release()
self.assertTrue(self.wrapper.resp.release.called)
def test_release_when_stream_at_eof(self):
self.wrapper.resp.release.return_value = self.future(None)
self.wrapper.stream.next.return_value = self.future(b'')
self.wrapper.stream.at_eof.return_value = True
yield from self.wrapper.next()
self.assertTrue(self.wrapper.stream.next.called)
self.assertTrue(self.wrapper.resp.release.called)
class PartReaderTestCase(TestCase):
def setUp(self):
super().setUp()
self.boundary = b'--:'
def test_next(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'Hello, world!\r\n--:'))
result = yield from obj.next()
self.assertEqual(b'Hello, world!', result)
self.assertTrue(obj.at_eof())
def test_next_next(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'Hello, world!\r\n--:'))
result = yield from obj.next()
self.assertEqual(b'Hello, world!', result)
self.assertTrue(obj.at_eof())
result = yield from obj.next()
self.assertIsNone(result)
def test_read(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'Hello, world!\r\n--:'))
result = yield from obj.read()
self.assertEqual(b'Hello, world!', result)
self.assertTrue(obj.at_eof())
def test_read_chunk_at_eof(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'--:'))
obj._at_eof = True
result = yield from obj.read_chunk()
self.assertEqual(b'', result)
def test_read_chunk_without_content_length(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'Hello, world!\r\n--:'))
c1 = yield from obj.read_chunk(8)
c2 = yield from obj.read_chunk(8)
c3 = yield from obj.read_chunk(8)
self.assertEqual(c1 + c2, b'Hello, world!')
self.assertEqual(c3, b'')
def test_read_incomplete_chunk(self):
stream = Stream(b'')
def prepare(data):
f = helpers.create_future(self.loop)
f.set_result(data)
return f
with mock.patch.object(stream, 'read', side_effect=[
prepare(b'Hello, '),
prepare(b'World'),
prepare(b'!\r\n--:'),
prepare(b'')
]):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, stream)
c1 = yield from obj.read_chunk(8)
self.assertEqual(c1, b'Hello, ')
c2 = yield from obj.read_chunk(8)
self.assertEqual(c2, b'World')
c3 = yield from obj.read_chunk(8)
self.assertEqual(c3, b'!')
def test_read_all_at_once(self):
stream = Stream(b'Hello, World!\r\n--:--\r\n')
obj = aiohttp.multipart.BodyPartReader(self.boundary, {}, stream)
result = yield from obj.read_chunk()
self.assertEqual(b'Hello, World!', result)
result = yield from obj.read_chunk()
self.assertEqual(b'', result)
self.assertTrue(obj.at_eof())
def test_read_incomplete_body_chunked(self):
stream = Stream(b'Hello, World!\r\n-')
obj = aiohttp.multipart.BodyPartReader(self.boundary, {}, stream)
result = b''
with self.assertRaises(AssertionError):
for _ in range(4):
result += yield from obj.read_chunk(7)
self.assertEqual(b'Hello, World!\r\n-', result)
def test_read_boundary_with_incomplete_chunk(self):
stream = Stream(b'')
def prepare(data):
f = helpers.create_future(self.loop)
f.set_result(data)
return f
with mock.patch.object(stream, 'read', side_effect=[
prepare(b'Hello, World'),
prepare(b'!\r\n'),
prepare(b'--:'),
prepare(b'')
]):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, stream)
c1 = yield from obj.read_chunk(12)
self.assertEqual(c1, b'Hello, World')
c2 = yield from obj.read_chunk(8)
self.assertEqual(c2, b'!')
c3 = yield from obj.read_chunk(8)
self.assertEqual(c3, b'')
def test_multi_read_chunk(self):
stream = Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--')
obj = aiohttp.multipart.BodyPartReader(self.boundary, {}, stream)
result = yield from obj.read_chunk(8)
self.assertEqual(b'Hello,', result)
result = yield from obj.read_chunk(8)
self.assertEqual(b'', result)
self.assertTrue(obj.at_eof())
def test_read_chunk_properly_counts_read_bytes(self):
expected = b'.' * 10
size = len(expected)
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {'CONTENT-LENGTH': size},
StreamWithShortenRead(expected + b'\r\n--:--'))
result = bytearray()
while True:
chunk = yield from obj.read_chunk()
if not chunk:
break
result.extend(chunk)
self.assertEqual(size, len(result))
self.assertEqual(b'.' * size, result)
self.assertTrue(obj.at_eof())
def test_read_does_reads_boundary(self):
stream = Stream(b'Hello, world!\r\n--:')
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, stream)
result = yield from obj.read()
self.assertEqual(b'Hello, world!', result)
self.assertEqual(b'', (yield from stream.read()))
self.assertEqual([b'--:'], list(obj._unread))
def test_multiread(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--'))
result = yield from obj.read()
self.assertEqual(b'Hello,', result)
result = yield from obj.read()
self.assertEqual(b'', result)
self.assertTrue(obj.at_eof())
def test_read_multiline(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'Hello\n,\r\nworld!\r\n--:--'))
result = yield from obj.read()
self.assertEqual(b'Hello\n,\r\nworld!', result)
result = yield from obj.read()
self.assertEqual(b'', result)
self.assertTrue(obj.at_eof())
def test_read_respects_content_length(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {'CONTENT-LENGTH': 100500},
Stream(b'.' * 100500 + b'\r\n--:--'))
result = yield from obj.read()
self.assertEqual(b'.' * 100500, result)
self.assertTrue(obj.at_eof())
def test_read_with_content_encoding_gzip(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_ENCODING: 'gzip'},
Stream(b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x0b\xc9\xccMU'
b'(\xc9W\x08J\xcdI\xacP\x04\x00$\xfb\x9eV\x0e\x00\x00\x00'
b'\r\n--:--'))
result = yield from obj.read(decode=True)
self.assertEqual(b'Time to Relax!', result)
def test_read_with_content_encoding_deflate(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_ENCODING: 'deflate'},
Stream(b'\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00\r\n--:--'))
result = yield from obj.read(decode=True)
self.assertEqual(b'Time to Relax!', result)
def test_read_with_content_encoding_identity(self):
thing = (b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x0b\xc9\xccMU'
b'(\xc9W\x08J\xcdI\xacP\x04\x00$\xfb\x9eV\x0e\x00\x00\x00'
b'\r\n')
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_ENCODING: 'identity'},
Stream(thing + b'--:--'))
result = yield from obj.read(decode=True)
self.assertEqual(thing[:-2], result)
def test_read_with_content_encoding_unknown(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_ENCODING: 'snappy'},
Stream(b'\x0e4Time to Relax!\r\n--:--'))
with self.assertRaises(RuntimeError):
yield from obj.read(decode=True)
def test_read_with_content_transfer_encoding_base64(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TRANSFER_ENCODING: 'base64'},
Stream(b'VGltZSB0byBSZWxheCE=\r\n--:--'))
result = yield from obj.read(decode=True)
self.assertEqual(b'Time to Relax!', result)
def test_read_with_content_transfer_encoding_quoted_printable(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TRANSFER_ENCODING: 'quoted-printable'},
Stream(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'
b' =D0=BC=D0=B8=D1=80!\r\n--:--'))
result = yield from obj.read(decode=True)
self.assertEqual(b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,'
b' \xd0\xbc\xd0\xb8\xd1\x80!', result)
def test_read_with_content_transfer_encoding_binary(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TRANSFER_ENCODING: 'binary'},
Stream(b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,'
b' \xd0\xbc\xd0\xb8\xd1\x80!\r\n--:--'))
result = yield from obj.read(decode=True)
self.assertEqual(b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,'
b' \xd0\xbc\xd0\xb8\xd1\x80!', result)
def test_read_with_content_transfer_encoding_unknown(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TRANSFER_ENCODING: 'unknown'},
Stream(b'\x0e4Time to Relax!\r\n--:--'))
with self.assertRaises(RuntimeError):
yield from obj.read(decode=True)
def test_read_text(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, Stream(b'Hello, world!\r\n--:--'))
result = yield from obj.text()
self.assertEqual('Hello, world!', result)
def test_read_text_encoding(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {},
Stream('Привет, Мир!\r\n--:--'.encode('cp1251')))
result = yield from obj.text(encoding='cp1251')
self.assertEqual('Привет, Мир!', result)
def test_read_text_guess_encoding(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'text/plain;charset=cp1251'},
Stream('Привет, Мир!\r\n--:--'.encode('cp1251')))
result = yield from obj.text()
self.assertEqual('Привет, Мир!', result)
def test_read_text_compressed(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_ENCODING: 'deflate',
CONTENT_TYPE: 'text/plain'},
Stream(b'\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00\r\n--:--'))
result = yield from obj.text()
self.assertEqual('Time to Relax!', result)
def test_read_text_while_closed(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'text/plain'}, Stream(b''))
obj._at_eof = True
result = yield from obj.text()
self.assertEqual('', result)
def test_read_json(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'application/json'},
Stream(b'{"test": "passed"}\r\n--:--'))
result = yield from obj.json()
self.assertEqual({'test': 'passed'}, result)
def test_read_json_encoding(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'application/json'},
Stream('{"тест": "пассед"}\r\n--:--'.encode('cp1251')))
result = yield from obj.json(encoding='cp1251')
self.assertEqual({'тест': 'пассед'}, result)
def test_read_json_guess_encoding(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'application/json; charset=cp1251'},
Stream('{"тест": "пассед"}\r\n--:--'.encode('cp1251')))
result = yield from obj.json()
self.assertEqual({'тест': 'пассед'}, result)
def test_read_json_compressed(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_ENCODING: 'deflate',
CONTENT_TYPE: 'application/json'},
Stream(b'\xabV*I-.Q\xb2RP*H,.NMQ\xaa\x05\x00\r\n--:--'))
result = yield from obj.json()
self.assertEqual({'test': 'passed'}, result)
def test_read_json_while_closed(self):
stream = Stream(b'')
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'application/json'}, stream)
obj._at_eof = True
result = yield from obj.json()
self.assertEqual(None, result)
def test_read_form(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},
Stream(b'foo=bar&foo=baz&boo=zoo\r\n--:--'))
result = yield from obj.form()
self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],
result)
def test_read_form_encoding(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {CONTENT_TYPE: 'application/x-www-form-urlencoded'},
Stream('foo=bar&foo=baz&boo=zoo\r\n--:--'.encode('cp1251')))
result = yield from obj.form(encoding='cp1251')
self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],
result)
def test_read_form_guess_encoding(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary,
{CONTENT_TYPE: 'application/x-www-form-urlencoded; charset=utf-8'},
Stream('foo=bar&foo=baz&boo=zoo\r\n--:--'.encode('utf-8')))
result = yield from obj.form()
self.assertEqual([('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')],
result)
def test_read_form_while_closed(self):
stream = Stream(b'')
obj = aiohttp.multipart.BodyPartReader(
self.boundary,
{CONTENT_TYPE: 'application/x-www-form-urlencoded'}, stream)
obj._at_eof = True
result = yield from obj.form()
self.assertEqual(None, result)
def test_release(self):
stream = Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--')
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, stream)
yield from obj.release()
self.assertTrue(obj.at_eof())
self.assertEqual(b'\r\nworld!\r\n--:--', stream.content.read())
self.assertEqual([b'--:\r\n'], list(obj._unread))
def test_release_respects_content_length(self):
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {'CONTENT-LENGTH': 100500},
Stream(b'.' * 100500 + b'\r\n--:--'))
result = yield from obj.release()
self.assertIsNone(result)
self.assertTrue(obj.at_eof())
def test_release_release(self):
stream = Stream(b'Hello,\r\n--:\r\n\r\nworld!\r\n--:--')
obj = aiohttp.multipart.BodyPartReader(
self.boundary, {}, stream)
yield from obj.release()
yield from obj.release()
self.assertEqual(b'\r\nworld!\r\n--:--', stream.content.read())
self.assertEqual([b'--:\r\n'], list(obj._unread))
def test_filename(self):
part = aiohttp.multipart.BodyPartReader(
self.boundary,
{CONTENT_DISPOSITION: 'attachment; filename=foo.html'},
None)
self.assertEqual('foo.html', part.filename)
class MultipartReaderTestCase(TestCase):
def test_from_response(self):
resp = Response({CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n\r\nhello\r\n--:--'))
res = aiohttp.multipart.MultipartReader.from_response(resp)
self.assertIsInstance(res,
aiohttp.multipart.MultipartResponseWrapper)
self.assertIsInstance(res.stream,
aiohttp.multipart.MultipartReader)
def test_bad_boundary(self):
resp = Response(
{CONTENT_TYPE: 'multipart/related;boundary=' + 'a' * 80},
Stream(b''))
with self.assertRaises(ValueError):
aiohttp.multipart.MultipartReader.from_response(resp)
def test_dispatch(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n\r\necho\r\n--:--'))
res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})
self.assertIsInstance(res, reader.part_reader_cls)
def test_dispatch_bodypart(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n\r\necho\r\n--:--'))
res = reader._get_part_reader({CONTENT_TYPE: 'text/plain'})
self.assertIsInstance(res, reader.part_reader_cls)
def test_dispatch_multipart(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'----:--\r\n'
b'\r\n'
b'test\r\n'
b'----:--\r\n'
b'\r\n'
b'passed\r\n'
b'----:----\r\n'
b'--:--'))
res = reader._get_part_reader(
{CONTENT_TYPE: 'multipart/related;boundary=--:--'})
self.assertIsInstance(res, reader.__class__)
def test_dispatch_custom_multipart_reader(self):
class CustomReader(aiohttp.multipart.MultipartReader):
pass
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'----:--\r\n'
b'\r\n'
b'test\r\n'
b'----:--\r\n'
b'\r\n'
b'passed\r\n'
b'----:----\r\n'
b'--:--'))
reader.multipart_reader_cls = CustomReader
res = reader._get_part_reader(
{CONTENT_TYPE: 'multipart/related;boundary=--:--'})
self.assertIsInstance(res, CustomReader)
def test_emit_next(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n\r\necho\r\n--:--'))
res = yield from reader.next()
self.assertIsInstance(res, reader.part_reader_cls)
def test_invalid_boundary(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'---:\r\n\r\necho\r\n---:--'))
with self.assertRaises(ValueError):
yield from reader.next()
def test_release(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/mixed;boundary=":"'},
Stream(b'--:\r\n'
b'Content-Type: multipart/related;boundary=--:--\r\n'
b'\r\n'
b'----:--\r\n'
b'\r\n'
b'test\r\n'
b'----:--\r\n'
b'\r\n'
b'passed\r\n'
b'----:----\r\n'
b'--:--'))
yield from reader.release()
self.assertTrue(reader.at_eof())
def test_release_release(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n\r\necho\r\n--:--'))
yield from reader.release()
self.assertTrue(reader.at_eof())
yield from reader.release()
self.assertTrue(reader.at_eof())
def test_release_next(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n\r\necho\r\n--:--'))
yield from reader.release()
self.assertTrue(reader.at_eof())
res = yield from reader.next()
self.assertIsNone(res)
def test_second_next_releases_previous_object(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n'
b'\r\n'
b'test\r\n'
b'--:\r\n'
b'\r\n'
b'passed\r\n'
b'--:--'))
first = yield from reader.next()
self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)
second = yield from reader.next()
self.assertTrue(first.at_eof())
self.assertFalse(second.at_eof())
def test_release_without_read_the_last_object(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n'
b'\r\n'
b'test\r\n'
b'--:\r\n'
b'\r\n'
b'passed\r\n'
b'--:--'))
first = yield from reader.next()
second = yield from reader.next()
third = yield from reader.next()
self.assertTrue(first.at_eof())
self.assertTrue(second.at_eof())
self.assertTrue(second.at_eof())
self.assertIsNone(third)
def test_read_chunk_by_length_doesnt_breaks_reader(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n'
b'Content-Length: 4\r\n\r\n'
b'test'
b'\r\n--:\r\n'
b'Content-Length: 6\r\n\r\n'
b'passed'
b'\r\n--:--'))
body_parts = []
while True:
read_part = b''
part = yield from reader.next()
if part is None:
break
while not part.at_eof():
read_part += yield from part.read_chunk(3)
body_parts.append(read_part)
self.assertListEqual(body_parts, [b'test', b'passed'])
def test_read_chunk_from_stream_doesnt_breaks_reader(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'--:\r\n'
b'\r\n'
b'chunk'
b'\r\n--:\r\n'
b'\r\n'
b'two_chunks'
b'\r\n--:--'))
body_parts = []
while True:
read_part = b''
part = yield from reader.next()
if part is None:
break
while not part.at_eof():
chunk = yield from part.read_chunk(5)
self.assertTrue(chunk)
read_part += chunk
body_parts.append(read_part)
self.assertListEqual(body_parts, [b'chunk', b'two_chunks'])
def test_reading_skips_prelude(self):
reader = aiohttp.multipart.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(b'Multi-part data is not supported.\r\n'
b'\r\n'
b'--:\r\n'
b'\r\n'
b'test\r\n'
b'--:\r\n'
b'\r\n'
b'passed\r\n'
b'--:--'))
first = yield from reader.next()
self.assertIsInstance(first, aiohttp.multipart.BodyPartReader)
second = yield from reader.next()
self.assertTrue(first.at_eof())
self.assertFalse(second.at_eof())
class BodyPartWriterTestCase(unittest.TestCase):
def setUp(self):
self.part = aiohttp.multipart.BodyPartWriter(b'')
def test_guess_content_length(self):
self.part.headers[CONTENT_TYPE] = 'text/plain; charset=utf-8'
self.assertIsNone(self.part._guess_content_length({}))
self.assertIsNone(self.part._guess_content_length(object()))
self.assertEqual(3,
self.part._guess_content_length(io.BytesIO(b'foo')))
self.assertEqual(3,
self.part._guess_content_length(io.StringIO('foo')))
self.assertEqual(6,
self.part._guess_content_length(io.StringIO('мяу')))
self.assertEqual(3, self.part._guess_content_length(b'bar'))
self.assertEqual(12, self.part._guess_content_length('пассед'))
with open(__file__, 'rb') as f:
self.assertEqual(os.fstat(f.fileno()).st_size,
self.part._guess_content_length(f))
def test_guess_content_type(self):
default = 'application/octet-stream'
self.assertEqual(default, self.part._guess_content_type(b'foo'))
self.assertEqual('text/plain; charset=utf-8',
self.part._guess_content_type('foo'))
here = os.path.dirname(__file__)
filename = os.path.join(here, 'software_development_in_picture.jpg')
with open(filename, 'rb') as f:
self.assertEqual('image/jpeg',
self.part._guess_content_type(f))
def test_guess_filename(self):
class Named:
name = 'foo'
self.assertIsNone(self.part._guess_filename({}))
self.assertIsNone(self.part._guess_filename(object()))
self.assertIsNone(self.part._guess_filename(io.BytesIO(b'foo')))
self.assertIsNone(self.part._guess_filename(Named()))
with open(__file__, 'rb') as f:
self.assertEqual(os.path.basename(f.name),
self.part._guess_filename(f))
def test_autoset_content_disposition(self):
self.part.obj = open(__file__, 'rb')
self.addCleanup(self.part.obj.close)
self.part._fill_headers_with_defaults()
self.assertIn(CONTENT_DISPOSITION, self.part.headers)
fname = os.path.basename(self.part.obj.name)
self.assertEqual(
'attachment; filename="{0}"; filename*=utf-8\'\'{0}'.format(fname),
self.part.headers[CONTENT_DISPOSITION])
def test_set_content_disposition(self):
self.part.set_content_disposition('attachment', foo='bar')
self.assertEqual(
'attachment; foo="bar"',
self.part.headers[CONTENT_DISPOSITION])
def test_set_content_disposition_bad_type(self):
with self.assertRaises(ValueError):
self.part.set_content_disposition('foo bar')
with self.assertRaises(ValueError):
self.part.set_content_disposition('тест')
with self.assertRaises(ValueError):
self.part.set_content_disposition('foo\x00bar')
with self.assertRaises(ValueError):
self.part.set_content_disposition('')
def test_set_content_disposition_bad_param(self):
with self.assertRaises(ValueError):
self.part.set_content_disposition('inline', **{'foo bar': 'baz'})
with self.assertRaises(ValueError):
self.part.set_content_disposition('inline', **{'тест': 'baz'})
with self.assertRaises(ValueError):
self.part.set_content_disposition('inline', **{'': 'baz'})
with self.assertRaises(ValueError):
self.part.set_content_disposition('inline',
**{'foo\x00bar': 'baz'})
def test_serialize_bytes(self):
self.assertEqual(b'foo', next(self.part._serialize_bytes(b'foo')))
def test_serialize_str(self):
self.assertEqual(b'foo', next(self.part._serialize_str('foo')))
def test_serialize_str_custom_encoding(self):
self.part.headers[CONTENT_TYPE] = \
'text/plain;charset=cp1251'
self.assertEqual('привет'.encode('cp1251'),
next(self.part._serialize_str('привет')))
def test_serialize_io(self):
self.assertEqual(b'foo',
next(self.part._serialize_io(io.BytesIO(b'foo'))))
self.assertEqual(b'foo',
next(self.part._serialize_io(io.StringIO('foo'))))
def test_serialize_io_chunk(self):
flo = io.BytesIO(b'foobarbaz')
self.part._chunk_size = 3
self.assertEqual([b'foo', b'bar', b'baz'],
list(self.part._serialize_io(flo)))
def test_serialize_json(self):
self.assertEqual(b'{"\\u043f\\u0440\\u0438\\u0432\\u0435\\u0442":'
b' "\\u043c\\u0438\\u0440"}',
next(self.part._serialize_json({'привет': 'мир'})))
def test_serialize_form(self):
data = [('foo', 'bar'), ('foo', 'baz'), ('boo', 'zoo')]
self.assertEqual(b'foo=bar&foo=baz&boo=zoo',
next(self.part._serialize_form(data)))
def test_serialize_form_dict(self):
data = {'hello': 'мир'}
self.assertEqual(b'hello=%D0%BC%D0%B8%D1%80',
next(self.part._serialize_form(data)))
def test_serialize_multipart(self):
multipart = aiohttp.multipart.MultipartWriter(boundary=':')
multipart.append('foo-bar-baz')
multipart.append_json({'test': 'passed'})
self.assertEqual(
[b'--:\r\n',
b'Content-Type: text/plain; charset=utf-8\r\n'
b'Content-Length: 11',
b'\r\n\r\n',
b'foo-bar-baz',
b'\r\n',
b'--:\r\n',
b'Content-Type: application/json',
b'\r\n\r\n',
b'{"test": "passed"}',
b'\r\n',
b'--:--\r\n',
b''],
list(self.part._serialize_multipart(multipart))
)
def test_serialize_default(self):
with self.assertRaises(TypeError):
self.part.obj = object()
list(self.part.serialize())
with self.assertRaises(TypeError):
next(self.part._serialize_default(object()))
def test_serialize_with_content_encoding_gzip(self):
part = aiohttp.multipart.BodyPartWriter(
'Time to Relax!', {CONTENT_ENCODING: 'gzip'})
stream = part.serialize()
self.assertEqual(b'Content-Encoding: gzip\r\n'
b'Content-Type: text/plain; charset=utf-8',
next(stream))
self.assertEqual(b'\r\n\r\n', next(stream))
result = b''.join(stream)
decompressor = zlib.decompressobj(wbits=16+zlib.MAX_WBITS)
data = decompressor.decompress(result)
self.assertEqual(b'Time to Relax!', data)
self.assertIsNone(next(stream, None))
def test_serialize_with_content_encoding_deflate(self):
part = aiohttp.multipart.BodyPartWriter(
'Time to Relax!', {CONTENT_ENCODING: 'deflate'})
stream = part.serialize()
self.assertEqual(b'Content-Encoding: deflate\r\n'
b'Content-Type: text/plain; charset=utf-8',
next(stream))
self.assertEqual(b'\r\n\r\n', next(stream))
thing = b'\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00\r\n'
self.assertEqual(thing, b''.join(stream))
self.assertIsNone(next(stream, None))
def test_serialize_with_content_encoding_identity(self):
thing = b'\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00'
part = aiohttp.multipart.BodyPartWriter(
thing, {CONTENT_ENCODING: 'identity'})
stream = part.serialize()
self.assertEqual(b'Content-Encoding: identity\r\n'
b'Content-Type: application/octet-stream\r\n'
b'Content-Length: 16',
next(stream))
self.assertEqual(b'\r\n\r\n', next(stream))
self.assertEqual(thing, next(stream))
self.assertEqual(b'\r\n', next(stream))
self.assertIsNone(next(stream, None))
def test_serialize_with_content_encoding_unknown(self):
part = aiohttp.multipart.BodyPartWriter(
'Time to Relax!', {CONTENT_ENCODING: 'snappy'})
with self.assertRaises(RuntimeError):
list(part.serialize())
def test_serialize_with_content_transfer_encoding_base64(self):
part = aiohttp.multipart.BodyPartWriter(
'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'base64'})
stream = part.serialize()
self.assertEqual(b'Content-Transfer-Encoding: base64\r\n'
b'Content-Type: text/plain; charset=utf-8',
next(stream))
self.assertEqual(b'\r\n\r\n', next(stream))
self.assertEqual(b'VGltZSB0byBSZWxh', next(stream))
self.assertEqual(b'eCE=', next(stream))
self.assertEqual(b'\r\n', next(stream))
self.assertIsNone(next(stream, None))
def test_serialize_io_with_content_transfer_encoding_base64(self):
part = aiohttp.multipart.BodyPartWriter(
io.BytesIO(b'Time to Relax!'),
{CONTENT_TRANSFER_ENCODING: 'base64'})
part._chunk_size = 6
stream = part.serialize()
self.assertEqual(b'Content-Transfer-Encoding: base64\r\n'
b'Content-Type: application/octet-stream',
next(stream))
self.assertEqual(b'\r\n\r\n', next(stream))
self.assertEqual(b'VGltZSB0', next(stream))
self.assertEqual(b'byBSZWxh', next(stream))
self.assertEqual(b'eCE=', next(stream))
self.assertEqual(b'\r\n', next(stream))
self.assertIsNone(next(stream, None))
def test_serialize_with_content_transfer_encoding_quote_printable(self):
part = aiohttp.multipart.BodyPartWriter(
'Привет, мир!', {CONTENT_TRANSFER_ENCODING: 'quoted-printable'})
stream = part.serialize()
self.assertEqual(b'Content-Transfer-Encoding: quoted-printable\r\n'
b'Content-Type: text/plain; charset=utf-8',
next(stream))
self.assertEqual(b'\r\n\r\n', next(stream))
self.assertEqual(b'=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,'
b' =D0=BC=D0=B8=D1=80!', next(stream))
self.assertEqual(b'\r\n', next(stream))
self.assertIsNone(next(stream, None))
def test_serialize_with_content_transfer_encoding_binary(self):
part = aiohttp.multipart.BodyPartWriter(
'Привет, мир!'.encode('utf-8'),
{CONTENT_TRANSFER_ENCODING: 'binary'})
stream = part.serialize()
self.assertEqual(b'Content-Transfer-Encoding: binary\r\n'
b'Content-Type: application/octet-stream',
next(stream))
self.assertEqual(b'\r\n\r\n', next(stream))
self.assertEqual(b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,'
b' \xd0\xbc\xd0\xb8\xd1\x80!', next(stream))
self.assertEqual(b'\r\n', next(stream))
self.assertIsNone(next(stream, None))
def test_serialize_with_content_transfer_encoding_unknown(self):
part = aiohttp.multipart.BodyPartWriter(
'Time to Relax!', {CONTENT_TRANSFER_ENCODING: 'unknown'})
with self.assertRaises(RuntimeError):
list(part.serialize())
def test_filename(self):
self.part.set_content_disposition('related', filename='foo.html')
self.assertEqual('foo.html', self.part.filename)
class MultipartWriterTestCase(unittest.TestCase):
def setUp(self):
self.writer = aiohttp.multipart.MultipartWriter(boundary=':')
def test_default_subtype(self):
mtype, stype, *_ = parse_mimetype(
self.writer.headers.get(CONTENT_TYPE))
self.assertEqual('multipart', mtype)
self.assertEqual('mixed', stype)
def test_bad_boundary(self):
with self.assertRaises(ValueError):
aiohttp.multipart.MultipartWriter(boundary='тест')
def test_default_headers(self):
self.assertEqual({CONTENT_TYPE: 'multipart/mixed; boundary=":"'},
self.writer.headers)
def test_iter_parts(self):
self.writer.append('foo')
self.writer.append('bar')