-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathtest_payload.py
More file actions
1557 lines (1175 loc) · 51.7 KB
/
test_payload.py
File metadata and controls
1557 lines (1175 loc) · 51.7 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 array
import asyncio
import io
import json
import unittest.mock
from collections.abc import AsyncIterator, Iterator
from io import StringIO
from pathlib import Path
from typing import TextIO, Union
import pytest
from multidict import CIMultiDict
from aiohttp import payload
from aiohttp.abc import AbstractStreamWriter
from aiohttp.payload import READ_SIZE
class BufferWriter(AbstractStreamWriter):
"""Test writer that captures written bytes in a buffer."""
def __init__(self) -> None:
self.buffer = bytearray()
async def write(
self, chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]
) -> None:
self.buffer.extend(bytes(chunk))
async def write_eof(self, chunk: bytes = b"") -> None:
"""No-op for test writer."""
async def drain(self) -> None:
"""No-op for test writer."""
def enable_compression(
self, encoding: str = "deflate", strategy: int | None = None
) -> None:
"""Compression not implemented for test writer."""
def enable_chunking(self) -> None:
"""Chunking not implemented for test writer."""
async def write_headers(self, status_line: str, headers: CIMultiDict[str]) -> None:
"""Headers not captured for payload tests."""
@pytest.fixture(autouse=True)
def cleanup(
cleanup_payload_pending_file_closes: None,
) -> None:
"""Ensure all pending file close operations complete during test teardown."""
@pytest.fixture
def registry() -> Iterator[payload.PayloadRegistry]:
old = payload.PAYLOAD_REGISTRY
reg = payload.PAYLOAD_REGISTRY = payload.PayloadRegistry()
yield reg
payload.PAYLOAD_REGISTRY = old
class Payload(payload.Payload):
def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str:
assert False
async def write(self, writer: AbstractStreamWriter) -> None:
"""Dummy write."""
def test_register_type(registry: payload.PayloadRegistry) -> None:
class TestProvider:
pass
payload.register_payload(Payload, TestProvider)
p = payload.get_payload(TestProvider())
assert isinstance(p, Payload)
def test_register_unsupported_order(registry: payload.PayloadRegistry) -> None:
class TestProvider:
pass
with pytest.raises(ValueError):
payload.register_payload(
Payload, TestProvider, order=object() # type: ignore[arg-type]
)
def test_payload_ctor() -> None:
p = Payload("test", encoding="utf-8", filename="test.txt")
assert p._value == "test"
assert p._encoding == "utf-8"
assert p.size is None
assert p.filename == "test.txt"
assert p.content_type == "text/plain"
def test_payload_content_type() -> None:
p = Payload("test", headers={"content-type": "application/json"})
assert p.content_type == "application/json"
def test_bytes_payload_default_content_type() -> None:
p = payload.BytesPayload(b"data")
assert p.content_type == "application/octet-stream"
def test_bytes_payload_explicit_content_type() -> None:
p = payload.BytesPayload(b"data", content_type="application/custom")
assert p.content_type == "application/custom"
def test_bytes_payload_bad_type() -> None:
with pytest.raises(TypeError):
payload.BytesPayload(object()) # type: ignore[arg-type]
def test_bytes_payload_memoryview_correct_size() -> None:
mv = memoryview(array.array("H", [1, 2, 3]))
p = payload.BytesPayload(mv)
assert p.size == 6
def test_string_payload() -> None:
p = payload.StringPayload("test")
assert p.encoding == "utf-8"
assert p.content_type == "text/plain; charset=utf-8"
p = payload.StringPayload("test", encoding="koi8-r")
assert p.encoding == "koi8-r"
assert p.content_type == "text/plain; charset=koi8-r"
p = payload.StringPayload("test", content_type="text/plain; charset=koi8-r")
assert p.encoding == "koi8-r"
assert p.content_type == "text/plain; charset=koi8-r"
def test_string_io_payload() -> None:
s = StringIO("ű" * 5000)
p = payload.StringIOPayload(s)
assert p.encoding == "utf-8"
assert p.content_type == "text/plain; charset=utf-8"
assert p.size == 10000
def test_async_iterable_payload_default_content_type() -> None:
async def gen() -> AsyncIterator[bytes]:
yield b"abc" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
assert p.content_type == "application/octet-stream"
def test_async_iterable_payload_explicit_content_type() -> None:
async def gen() -> AsyncIterator[bytes]:
yield b"abc" # pragma: no cover
p = payload.AsyncIterablePayload(gen(), content_type="application/custom")
assert p.content_type == "application/custom"
def test_async_iterable_payload_not_async_iterable() -> None:
with pytest.raises(TypeError):
payload.AsyncIterablePayload(object()) # type: ignore[arg-type]
class MockStreamWriter(AbstractStreamWriter):
"""Mock stream writer for testing payload writes."""
def __init__(self) -> None:
self.written: list[bytes] = []
async def write(
self, chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"]
) -> None:
"""Store the chunk in the written list."""
self.written.append(bytes(chunk))
async def write_eof(self, chunk: bytes | None = None) -> None:
"""write_eof implementation - no-op for tests."""
async def drain(self) -> None:
"""Drain implementation - no-op for tests."""
def enable_compression(
self, encoding: str = "deflate", strategy: int | None = None
) -> None:
"""Enable compression - no-op for tests."""
def enable_chunking(self) -> None:
"""Enable chunking - no-op for tests."""
async def write_headers(self, status_line: str, headers: CIMultiDict[str]) -> None:
"""Write headers - no-op for tests."""
def get_written_bytes(self) -> bytes:
"""Return all written bytes as a single bytes object."""
return b"".join(self.written)
async def test_bytes_payload_write_with_length_no_limit() -> None:
"""Test BytesPayload writing with no content length limit."""
data = b"0123456789"
p = payload.BytesPayload(data)
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytes_payload_write_with_length_exact() -> None:
"""Test BytesPayload writing with exact content length."""
data = b"0123456789"
p = payload.BytesPayload(data)
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytes_payload_write_with_length_truncated() -> None:
"""Test BytesPayload writing with truncated content length."""
data = b"0123456789"
p = payload.BytesPayload(data)
writer = MockStreamWriter()
await p.write_with_length(writer, 5)
assert writer.get_written_bytes() == b"01234"
assert len(writer.get_written_bytes()) == 5
async def test_bytes_payload_write_progress_callback() -> None:
"""Test BytesPayload writing with progress callback."""
progress_callback = unittest.mock.Mock()
p = payload.BytesPayload(b"0123456789")
p.set_progress_callback(progress_callback)
writer = MockStreamWriter()
await p.write_with_length(writer, 5)
assert progress_callback.call_args_list == [
unittest.mock.call(0),
unittest.mock.call(5),
]
progress_callback.call_args_list.clear()
await p.write_with_length(writer, None)
assert progress_callback.call_args_list == [
unittest.mock.call(0),
unittest.mock.call(10),
]
async def test_iobase_payload_write_with_length_no_limit() -> None:
"""Test IOBasePayload writing with no content length limit."""
data = b"0123456789"
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_iobase_payload_write_with_length_exact() -> None:
"""Test IOBasePayload writing with exact content length."""
data = b"0123456789"
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_iobase_payload_write_with_length_truncated() -> None:
"""Test IOBasePayload writing with truncated content length."""
data = b"0123456789"
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, 5)
assert writer.get_written_bytes() == b"01234"
assert len(writer.get_written_bytes()) == 5
async def test_iobase_payload_write_progress_callback() -> None:
"""Test IOBasePayload writing with progress callback."""
progress_callback = unittest.mock.Mock()
p = payload.IOBasePayload(io.BytesIO(b"0123456789"))
p.set_progress_callback(progress_callback)
writer = MockStreamWriter()
await p.write_with_length(writer, 5)
assert progress_callback.call_args_list == [
unittest.mock.call(0),
unittest.mock.call(5),
]
progress_callback.call_args_list.clear()
await p.write_with_length(writer, None)
assert progress_callback.call_args_list == [
unittest.mock.call(0),
unittest.mock.call(10),
]
@pytest.mark.parametrize(
("content_length", "expected_calls"),
[
(
6,
[
unittest.mock.call(0),
unittest.mock.call(4),
unittest.mock.call(6),
],
),
(
10,
[
unittest.mock.call(0),
unittest.mock.call(4),
unittest.mock.call(8),
unittest.mock.call(10),
],
),
],
)
async def test_iobase_payload_write_chunked_progress_callback(
content_length, expected_calls
) -> None:
"""Test IOBasePayload writing in chunks with progress callback."""
# Mock the file-like object to track read calls
mock_file = unittest.mock.Mock(spec=io.BytesIO)
mock_file.tell.return_value = 0
mock_file.fileno.side_effect = AttributeError # Make size return None
mock_file.read.side_effect = [b"0123", b"4567", b"89"]
progress_callback = unittest.mock.Mock()
p = payload.IOBasePayload(mock_file)
writer = MockStreamWriter()
p.set_progress_callback(progress_callback)
await p.write_with_length(writer, content_length)
assert progress_callback.call_args_list == expected_calls
async def test_bytesio_payload_write_with_length_no_limit() -> None:
"""Test BytesIOPayload writing with no content length limit."""
data = b"0123456789"
p = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytesio_payload_write_with_length_exact() -> None:
"""Test BytesIOPayload writing with exact content length."""
data = b"0123456789"
p = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == 10
async def test_bytesio_payload_write_with_length_truncated() -> None:
"""Test BytesIOPayload writing with truncated content length."""
data = b"0123456789"
payload_bytesio = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await payload_bytesio.write_with_length(writer, 5)
assert writer.get_written_bytes() == b"01234"
assert len(writer.get_written_bytes()) == 5
async def test_bytesio_payload_write_with_length_remaining_zero() -> None:
"""Test BytesIOPayload with content_length smaller than first read chunk."""
data = b"0123456789" * 10 # 100 bytes
bio = io.BytesIO(data)
payload_bytesio = payload.BytesIOPayload(bio)
writer = MockStreamWriter()
# Mock the read method to return smaller chunks
original_read = bio.read
read_calls = 0
def mock_read(size: int | None = None) -> bytes:
nonlocal read_calls
read_calls += 1
if read_calls == 1:
# First call: return 3 bytes (less than content_length=5)
return original_read(3)
else:
# Subsequent calls return remaining data normally
return original_read(size)
with unittest.mock.patch.object(bio, "read", mock_read):
await payload_bytesio.write_with_length(writer, 5)
assert len(writer.get_written_bytes()) == 5
assert writer.get_written_bytes() == b"01234"
async def test_bytesio_payload_large_data_multiple_chunks() -> None:
"""Test BytesIOPayload with large data requiring multiple read chunks."""
chunk_size = 2**16 # 64KB (READ_SIZE)
data = b"x" * (chunk_size + 1000) # Slightly larger than READ_SIZE
payload_bytesio = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await payload_bytesio.write_with_length(writer, None)
assert writer.get_written_bytes() == data
assert len(writer.get_written_bytes()) == chunk_size + 1000
async def test_bytesio_payload_remaining_bytes_exhausted() -> None:
"""Test BytesIOPayload when remaining_bytes becomes <= 0."""
data = b"0123456789abcdef" * 1000 # 16000 bytes
payload_bytesio = payload.BytesIOPayload(io.BytesIO(data))
writer = MockStreamWriter()
await payload_bytesio.write_with_length(writer, 8000) # Exactly half the data
written = writer.get_written_bytes()
assert len(written) == 8000
assert written == data[:8000]
async def test_bytesio_payload_write_progress_callback() -> None:
"""Test BytesIOPayload writing with progress callback."""
progress_callback = unittest.mock.Mock()
p = payload.BytesIOPayload(io.BytesIO(b"0123456789abcdef" * 1000))
p.set_progress_callback(progress_callback)
writer = MockStreamWriter()
await p.write_with_length(writer, 5)
assert progress_callback.call_args_list == [
unittest.mock.call(0),
unittest.mock.call(5),
]
progress_callback.call_args_list.clear()
await p.write_with_length(writer, None)
assert progress_callback.call_args_list == [
unittest.mock.call(0),
unittest.mock.call(16000),
]
async def test_iobase_payload_exact_chunk_size_limit() -> None:
"""Test IOBasePayload with content length matching exactly one read chunk."""
chunk_size = 2**16 # 65536 bytes (READ_SIZE)
data = b"x" * chunk_size + b"extra" # Slightly larger than one read chunk
p = payload.IOBasePayload(io.BytesIO(data))
writer = MockStreamWriter()
await p.write_with_length(writer, chunk_size)
written = writer.get_written_bytes()
assert len(written) == chunk_size
assert written == data[:chunk_size]
async def test_iobase_payload_reads_in_chunks() -> None:
"""Test IOBasePayload reads data in chunks of READ_SIZE, not all at once."""
# Create a large file that's multiple times larger than READ_SIZE
large_data = b"x" * (READ_SIZE * 3 + 1000) # ~192KB + 1000 bytes
# Mock the file-like object to track read calls
mock_file = unittest.mock.Mock(spec=io.BytesIO)
mock_file.tell.return_value = 0
mock_file.fileno.side_effect = AttributeError # Make size return None
# Track the sizes of read() calls
read_sizes = []
def mock_read(size: int) -> bytes:
read_sizes.append(size)
# Return data based on how many times read was called
call_count = len(read_sizes)
if call_count == 1:
return large_data[:size]
elif call_count == 2:
return large_data[READ_SIZE : READ_SIZE + size]
elif call_count == 3:
return large_data[READ_SIZE * 2 : READ_SIZE * 2 + size]
else:
return large_data[READ_SIZE * 3 :]
mock_file.read.side_effect = mock_read
payload_obj = payload.IOBasePayload(mock_file)
writer = MockStreamWriter()
# Write with a large content_length
await payload_obj.write_with_length(writer, len(large_data))
# Verify that reads were limited to READ_SIZE
assert len(read_sizes) > 1 # Should have multiple reads
for read_size in read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
async def test_iobase_payload_large_content_length() -> None:
"""Test IOBasePayload with very large content_length doesn't read all at once."""
data = b"x" * (READ_SIZE + 1000)
# Create a custom file-like object that tracks read sizes
class TrackingBytesIO(io.BytesIO):
def __init__(self, data: bytes) -> None:
super().__init__(data)
self.read_sizes: list[int] = []
def read(self, size: int | None = -1) -> bytes:
self.read_sizes.append(size if size is not None else -1)
return super().read(size)
tracking_file = TrackingBytesIO(data)
payload_obj = payload.IOBasePayload(tracking_file)
writer = MockStreamWriter()
# Write with a very large content_length (simulating the bug scenario)
large_content_length = 10 * 1024 * 1024 # 10MB
await payload_obj.write_with_length(writer, large_content_length)
# Verify no single read exceeded READ_SIZE
for read_size in tracking_file.read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
# Verify the correct amount of data was written
assert writer.get_written_bytes() == data
async def test_textio_payload_reads_in_chunks() -> None:
"""Test TextIOPayload reads data in chunks of READ_SIZE, not all at once."""
# Create a large text file that's multiple times larger than READ_SIZE
large_text = "x" * (READ_SIZE * 3 + 1000) # ~192KB + 1000 chars
# Mock the file-like object to track read calls
mock_file = unittest.mock.Mock(spec=io.StringIO)
mock_file.tell.return_value = 0
mock_file.fileno.side_effect = AttributeError # Make size return None
mock_file.encoding = "utf-8"
# Track the sizes of read() calls
read_sizes = []
def mock_read(size: int) -> str:
read_sizes.append(size)
# Return data based on how many times read was called
call_count = len(read_sizes)
if call_count == 1:
return large_text[:size]
elif call_count == 2:
return large_text[READ_SIZE : READ_SIZE + size]
elif call_count == 3:
return large_text[READ_SIZE * 2 : READ_SIZE * 2 + size]
else:
return large_text[READ_SIZE * 3 :]
mock_file.read.side_effect = mock_read
payload_obj = payload.TextIOPayload(mock_file)
writer = MockStreamWriter()
# Write with a large content_length
await payload_obj.write_with_length(writer, len(large_text.encode("utf-8")))
# Verify that reads were limited to READ_SIZE
assert len(read_sizes) > 1 # Should have multiple reads
for read_size in read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
async def test_textio_payload_large_content_length() -> None:
"""Test TextIOPayload with very large content_length doesn't read all at once."""
text_data = "x" * (READ_SIZE + 1000)
# Create a custom file-like object that tracks read sizes
class TrackingStringIO(io.StringIO):
def __init__(self, data: str) -> None:
super().__init__(data)
self.read_sizes: list[int] = []
def read(self, size: int | None = -1) -> str:
self.read_sizes.append(size if size is not None else -1)
return super().read(size)
tracking_file = TrackingStringIO(text_data)
payload_obj = payload.TextIOPayload(tracking_file)
writer = MockStreamWriter()
# Write with a very large content_length (simulating the bug scenario)
large_content_length = 10 * 1024 * 1024 # 10MB
await payload_obj.write_with_length(writer, large_content_length)
# Verify no single read exceeded READ_SIZE
for read_size in tracking_file.read_sizes:
assert (
read_size <= READ_SIZE
), f"Read size {read_size} exceeds READ_SIZE {READ_SIZE}"
# Verify the correct amount of data was written
assert writer.get_written_bytes() == text_data.encode("utf-8")
async def test_async_iterable_payload_write_with_length_no_limit() -> None:
"""Test AsyncIterablePayload writing with no content length limit."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567"
yield b"89"
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == b"0123456789"
assert len(writer.get_written_bytes()) == 10
async def test_async_iterable_payload_write_with_length_exact() -> None:
"""Test AsyncIterablePayload writing with exact content length."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567"
yield b"89"
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == b"0123456789"
assert len(writer.get_written_bytes()) == 10
async def test_async_iterable_payload_write_with_length_truncated_mid_chunk() -> None:
"""Test AsyncIterablePayload writing with content length truncating mid-chunk."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567"
yield b"89" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, 6)
assert writer.get_written_bytes() == b"012345"
assert len(writer.get_written_bytes()) == 6
async def test_async_iterable_payload_write_with_length_truncated_at_chunk() -> None:
"""Test AsyncIterablePayload writing with content length truncating at chunk boundary."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567" # pragma: no cover
yield b"89" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write_with_length(writer, 4)
assert writer.get_written_bytes() == b"0123"
assert len(writer.get_written_bytes()) == 4
@pytest.mark.parametrize(
("content_length", "expected_calls"),
[
(
6,
[
unittest.mock.call(0),
unittest.mock.call(4),
unittest.mock.call(6),
],
),
(
None,
[
unittest.mock.call(0),
unittest.mock.call(4),
unittest.mock.call(8),
unittest.mock.call(10),
],
),
],
)
async def test_async_iterable_payload_write_chunked_progress_callback(
content_length, expected_calls
) -> None:
"""Test AsyncIterablePayload writing with content length truncating mid-chunk."""
async def gen() -> AsyncIterator[bytes]:
yield b"0123"
yield b"4567"
yield b"89"
progress_callback = unittest.mock.Mock()
p = payload.AsyncIterablePayload(gen())
p.set_progress_callback(progress_callback)
writer = MockStreamWriter()
await p.write_with_length(writer, content_length)
assert progress_callback.call_args_list == expected_calls
async def test_bytes_payload_backwards_compatibility() -> None:
"""Test BytesPayload.write() backwards compatibility delegates to write_with_length()."""
p = payload.BytesPayload(b"1234567890")
writer = MockStreamWriter()
await p.write(writer)
assert writer.get_written_bytes() == b"1234567890"
async def test_textio_payload_with_encoding() -> None:
"""Test TextIOPayload reading with encoding and size constraints."""
data = io.StringIO("hello world")
p = payload.TextIOPayload(data, encoding="utf-8")
writer = MockStreamWriter()
await p.write_with_length(writer, 8)
# Should write exactly 8 bytes: "hello wo"
assert writer.get_written_bytes() == b"hello wo"
async def test_textio_payload_as_bytes() -> None:
"""Test TextIOPayload.as_bytes method with different encodings."""
# Test with UTF-8 encoding
data = io.StringIO("Hello 世界")
p = payload.TextIOPayload(data, encoding="utf-8")
# Test as_bytes() method
result = await p.as_bytes()
assert result == "Hello 世界".encode()
# Test that position is restored for multiple reads
result2 = await p.as_bytes()
assert result2 == "Hello 世界".encode()
# Test with different encoding parameter (should use instance encoding)
result3 = await p.as_bytes(encoding="latin-1")
assert result3 == "Hello 世界".encode() # Should still use utf-8
# Test with different encoding in payload
data2 = io.StringIO("Hello World")
p2 = payload.TextIOPayload(data2, encoding="latin-1")
result4 = await p2.as_bytes()
assert result4 == b"Hello World" # latin-1 encoding
# Test with no explicit encoding (defaults to utf-8)
data3 = io.StringIO("Test データ")
p3 = payload.TextIOPayload(data3)
result5 = await p3.as_bytes()
assert result5 == "Test データ".encode()
# Test with encoding errors parameter
data4 = io.StringIO("Test")
p4 = payload.TextIOPayload(data4, encoding="ascii")
result6 = await p4.as_bytes(errors="strict")
assert result6 == b"Test"
async def test_bytesio_payload_backwards_compatibility() -> None:
"""Test BytesIOPayload.write() backwards compatibility delegates to write_with_length()."""
data = io.BytesIO(b"test data")
p = payload.BytesIOPayload(data)
writer = MockStreamWriter()
await p.write(writer)
assert writer.get_written_bytes() == b"test data"
async def test_async_iterable_payload_backwards_compatibility() -> None:
"""Test AsyncIterablePayload.write() backwards compatibility delegates to write_with_length()."""
async def gen() -> AsyncIterator[bytes]:
yield b"chunk1"
yield b"chunk2" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
writer = MockStreamWriter()
await p.write(writer)
assert writer.get_written_bytes() == b"chunk1chunk2"
async def test_async_iterable_payload_with_none_iterator() -> None:
"""Test AsyncIterablePayload with None iterator returns early without writing."""
async def gen() -> AsyncIterator[bytes]:
yield b"test" # pragma: no cover
p = payload.AsyncIterablePayload(gen())
# Manually set _iter to None to test the guard clause
p._iter = None
writer = MockStreamWriter()
# Should return early without writing anything
await p.write_with_length(writer, 10)
assert writer.get_written_bytes() == b""
async def test_async_iterable_payload_caching() -> None:
"""Test AsyncIterablePayload caching behavior."""
async def gen() -> AsyncIterator[bytes]:
yield b"Hello"
yield b" "
yield b"World"
p = payload.AsyncIterablePayload(gen())
# First call to as_bytes should consume iterator and cache
result1 = await p.as_bytes()
assert result1 == b"Hello World"
assert p._iter is None # Iterator exhausted
assert p._cached_chunks == [b"Hello", b" ", b"World"] # Chunks cached
assert p._consumed is False # Not marked as consumed to allow reuse
# Second call should use cache
result2 = await p.as_bytes()
assert result2 == b"Hello World"
assert p._cached_chunks == [b"Hello", b" ", b"World"] # Still cached
# decode should work with cached chunks
decoded = p.decode()
assert decoded == "Hello World"
# write_with_length should use cached chunks
writer = MockStreamWriter()
await p.write_with_length(writer, None)
assert writer.get_written_bytes() == b"Hello World"
# write_with_length with limit should respect it
writer2 = MockStreamWriter()
await p.write_with_length(writer2, 5)
assert writer2.get_written_bytes() == b"Hello"
async def test_async_iterable_payload_decode_without_cache() -> None:
"""Test AsyncIterablePayload decode raises error without cache."""
async def gen() -> AsyncIterator[bytes]:
yield b"test"
p = payload.AsyncIterablePayload(gen())
# decode should raise without cache
with pytest.raises(TypeError) as excinfo:
p.decode()
assert "Unable to decode - content not cached" in str(excinfo.value)
# After as_bytes, decode should work
await p.as_bytes()
assert p.decode() == "test"
async def test_async_iterable_payload_write_then_cache() -> None:
"""Test AsyncIterablePayload behavior when written before caching."""
async def gen() -> AsyncIterator[bytes]:
yield b"Hello"
yield b"World"
p = payload.AsyncIterablePayload(gen())
# First write without caching (streaming)
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == b"HelloWorld"
assert p._iter is None # Iterator exhausted
assert p._cached_chunks is None # No cache created
assert p._consumed is True # Marked as consumed
# Subsequent operations should handle exhausted iterator
result = await p.as_bytes()
assert result == b"" # Empty since iterator exhausted without cache
# Write should also be empty
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == b""
async def test_bytes_payload_reusability() -> None:
"""Test that BytesPayload can be written and read multiple times."""
data = b"test payload data"
p = payload.BytesPayload(data)
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == data
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == data
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == data
async def test_string_payload_reusability() -> None:
"""Test that StringPayload can be written and read multiple times."""
text = "test string data"
expected_bytes = text.encode("utf-8")
p = payload.StringPayload(text)
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == expected_bytes
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == expected_bytes
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == expected_bytes
async def test_bytes_io_payload_reusability() -> None:
"""Test that BytesIOPayload can be written and read multiple times."""
data = b"test bytesio payload"
bytes_io = io.BytesIO(data)
p = payload.BytesIOPayload(bytes_io)
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == data
# Second write_with_length (simulating redirect)
writer2 = MockStreamWriter()
await p.write_with_length(writer2, None)
assert writer2.get_written_bytes() == data
# Write with partial length
writer3 = MockStreamWriter()
await p.write_with_length(writer3, 5)
assert writer3.get_written_bytes() == b"test "
# Test as_bytes multiple times
bytes1 = await p.as_bytes()
bytes2 = await p.as_bytes()
bytes3 = await p.as_bytes()
assert bytes1 == bytes2 == bytes3 == data
async def test_string_io_payload_reusability() -> None:
"""Test that StringIOPayload can be written and read multiple times."""
text = "test stringio payload"
expected_bytes = text.encode("utf-8")
string_io = io.StringIO(text)
p = payload.StringIOPayload(string_io)
# Note: StringIOPayload reads all content in __init__ and becomes a StringPayload
# So it should be fully reusable
# First write_with_length
writer1 = MockStreamWriter()
await p.write_with_length(writer1, None)
assert writer1.get_written_bytes() == expected_bytes