-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathtest_web_functional.py
2352 lines (1774 loc) · 71.7 KB
/
test_web_functional.py
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 io
import json
import pathlib
import socket
import sys
import zlib
from typing import AsyncIterator, Awaitable, Callable, Dict, List, NoReturn, Optional
from unittest import mock
import pytest
from multidict import CIMultiDictProxy, MultiDict
from pytest_mock import MockerFixture
from yarl import URL
import aiohttp
from aiohttp import (
FormData,
HttpVersion,
HttpVersion10,
HttpVersion11,
TraceConfig,
multipart,
web,
)
from aiohttp.abc import AbstractResolver, ResolveResult
from aiohttp.hdrs import CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING
from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer
from aiohttp.test_utils import make_mocked_coro
from aiohttp.typedefs import Handler, Middleware
from aiohttp.web_protocol import RequestHandler
try:
import brotlicffi as brotli
except ImportError:
import brotli
try:
import ssl
except ImportError:
ssl = None # type: ignore[assignment]
@pytest.fixture
def here() -> pathlib.Path:
return pathlib.Path(__file__).parent
@pytest.fixture
def fname(here: pathlib.Path) -> pathlib.Path:
return here / "conftest.py"
def new_dummy_form() -> FormData:
form = FormData()
form.add_field("name", b"123")
return form
async def test_simple_get(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
return web.Response(body=b"OK")
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
txt = await resp.text()
assert "OK" == txt
resp.release()
async def test_simple_get_with_text(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
return web.Response(text="OK", headers={"content-type": "text/plain"})
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
txt = await resp.text()
assert "OK" == txt
resp.release()
async def test_handler_returns_not_response(
aiohttp_server: AiohttpServer, aiohttp_client: AiohttpClient
) -> None:
asyncio.get_event_loop().set_debug(True)
logger = mock.Mock()
async def handler(request: web.Request) -> str:
return "abc"
app = web.Application()
app.router.add_get("/", handler) # type: ignore[arg-type]
server = await aiohttp_server(app, logger=logger)
client = await aiohttp_client(server)
async with client.get("/") as resp:
assert resp.status == 500
async def test_handler_returns_none(
aiohttp_server: AiohttpServer, aiohttp_client: AiohttpClient
) -> None:
asyncio.get_event_loop().set_debug(True)
logger = mock.Mock()
async def handler(request: web.Request) -> None:
return None
app = web.Application()
app.router.add_get("/", handler) # type: ignore[arg-type]
server = await aiohttp_server(app, logger=logger)
client = await aiohttp_client(server)
async with client.get("/") as resp:
assert resp.status == 500
async def test_handler_returns_not_response_after_100expect(
aiohttp_server: AiohttpServer, aiohttp_client: AiohttpClient
) -> None:
async def handler(request: web.Request) -> NoReturn:
raise Exception("foo")
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
async with client.get("/", expect100=True) as resp:
assert resp.status == 500
async def test_head_returns_empty_body(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(body=b"test")
app = web.Application()
app.router.add_head("/", handler)
client = await aiohttp_client(app, version=HttpVersion11)
resp = await client.head("/")
assert 200 == resp.status
txt = await resp.text()
assert "" == txt
# The Content-Length header should be set to 4 which is
# the length of the response body if it would have been
# returned by a GET request.
assert resp.headers["Content-Length"] == "4"
@pytest.mark.parametrize("status", (201, 204, 404))
async def test_default_content_type_no_body(
aiohttp_client: AiohttpClient, status: int
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(status=status)
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert resp.status == status
assert await resp.read() == b""
assert "Content-Type" not in resp.headers
async def test_response_before_complete(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(body=b"OK")
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
data = b"0" * 1024 * 1024
resp = await client.post("/", data=data)
assert 200 == resp.status
text = await resp.text()
assert "OK" == text
resp.release()
@pytest.mark.skipif(sys.version_info < (3, 11), reason="Needs Task.cancelling()")
async def test_cancel_shutdown(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
t = asyncio.create_task(request.protocol.shutdown())
# Ensure it's started waiting
await asyncio.sleep(0)
t.cancel()
# Cancellation should not be suppressed
with pytest.raises(asyncio.CancelledError):
await t
# Repeat for second waiter in shutdown()
with mock.patch.object(request.protocol, "_request_in_progress", False):
with mock.patch.object(request.protocol, "_current_request", None):
t = asyncio.create_task(request.protocol.shutdown())
await asyncio.sleep(0)
t.cancel()
with pytest.raises(asyncio.CancelledError):
await t
return web.Response(body=b"OK")
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert resp.status == 200
txt = await resp.text()
assert txt == "OK"
async def test_post_form(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
data = await request.post()
assert {"a": "1", "b": "2", "c": ""} == data
return web.Response(body=b"OK")
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data={"a": "1", "b": "2", "c": ""})
assert 200 == resp.status
txt = await resp.text()
assert "OK" == txt
resp.release()
async def test_post_text(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
data = await request.text()
assert "русский" == data
data2 = await request.text()
assert data == data2
return web.Response(text=data)
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data="русский")
assert 200 == resp.status
txt = await resp.text()
assert "русский" == txt
resp.release()
async def test_post_json(aiohttp_client: AiohttpClient) -> None:
dct = {"key": "текст"}
async def handler(request: web.Request) -> web.Response:
data = await request.json()
assert dct == data
data2 = await request.json(loads=json.loads)
assert data == data2
resp = web.Response()
resp.content_type = "application/json"
resp.body = json.dumps(data).encode("utf8")
return resp
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
headers = {"Content-Type": "application/json"}
resp = await client.post("/", data=json.dumps(dct), headers=headers)
assert 200 == resp.status
data = await resp.json()
assert dct == data
resp.release()
async def test_multipart(aiohttp_client: AiohttpClient) -> None:
with multipart.MultipartWriter() as writer:
writer.append("test")
writer.append_json({"passed": True})
async def handler(request: web.Request) -> web.Response:
reader = await request.multipart()
assert isinstance(reader, multipart.MultipartReader)
part = await reader.next()
assert isinstance(part, multipart.BodyPartReader)
thing = await part.text()
assert thing == "test"
part = await reader.next()
assert isinstance(part, multipart.BodyPartReader)
assert part.headers["Content-Type"] == "application/json"
json_thing = await part.json()
assert json_thing == {"passed": True}
resp = web.Response()
resp.content_type = "application/json"
resp.body = b""
return resp
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data=writer)
assert 200 == resp.status
resp.release()
async def test_multipart_empty(aiohttp_client: AiohttpClient) -> None:
with multipart.MultipartWriter() as writer:
pass
async def handler(request: web.Request) -> web.Response:
reader = await request.multipart()
assert isinstance(reader, multipart.MultipartReader)
async for part in reader:
assert False, f"Unexpected part found in reader: {part!r}"
return web.Response()
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data=writer)
assert 200 == resp.status
resp.release()
async def test_multipart_content_transfer_encoding(
aiohttp_client: AiohttpClient,
) -> None:
# For issue #1168
with multipart.MultipartWriter() as writer:
writer.append(
b"\x00" * 10,
headers={"Content-Transfer-Encoding": "binary"},
)
async def handler(request: web.Request) -> web.Response:
reader = await request.multipart()
assert isinstance(reader, multipart.MultipartReader)
part = await reader.next()
assert isinstance(part, multipart.BodyPartReader)
assert part.headers["Content-Transfer-Encoding"] == "binary"
thing = await part.read()
assert thing == b"\x00" * 10
resp = web.Response()
resp.content_type = "application/json"
resp.body = b""
return resp
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data=writer)
assert 200 == resp.status
resp.release()
async def test_render_redirect(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
raise web.HTTPMovedPermanently(location="/path")
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/", allow_redirects=False)
assert 301 == resp.status
txt = await resp.text()
assert "301: Moved Permanently" == txt
assert "/path" == resp.headers["location"]
resp.release()
async def test_post_single_file(aiohttp_client: AiohttpClient) -> None:
here = pathlib.Path(__file__).parent
def check_file(fs: aiohttp.web_request.FileField) -> None:
fullname = here / fs.filename
with fullname.open("rb") as f:
test_data = f.read()
data = fs.file.read()
assert test_data == data
async def handler(request: web.Request) -> web.Response:
data = await request.post()
assert ["data.unknown_mime_type"] == list(data.keys())
for fs in data.values():
assert isinstance(fs, aiohttp.web_request.FileField)
check_file(fs)
fs.file.close()
resp = web.Response(body=b"OK")
return resp
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
fname = here / "data.unknown_mime_type"
with fname.open("rb") as fd:
resp = await client.post("/", data=[fd])
assert 200 == resp.status
resp.release()
async def test_files_upload_with_same_key(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
data = await request.post()
files = data.getall("file")
file_names = set()
for _file in files:
assert isinstance(_file, aiohttp.web_request.FileField)
assert not _file.file.closed
if _file.filename == "test1.jpeg":
assert _file.file.read() == b"binary data 1"
if _file.filename == "test2.jpeg":
assert _file.file.read() == b"binary data 2"
file_names.add(_file.filename)
_file.file.close()
assert len(files) == 2
assert file_names == {"test1.jpeg", "test2.jpeg"}
resp = web.Response(body=b"OK")
return resp
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
data = FormData()
data.add_field(
"file", b"binary data 1", content_type="image/jpeg", filename="test1.jpeg"
)
data.add_field(
"file", b"binary data 2", content_type="image/jpeg", filename="test2.jpeg"
)
resp = await client.post("/", data=data)
assert 200 == resp.status
resp.release()
async def test_post_files(aiohttp_client: AiohttpClient) -> None:
here = pathlib.Path(__file__).parent
def check_file(fs: aiohttp.web_request.FileField) -> None:
fullname = here / fs.filename
with fullname.open("rb") as f:
test_data = f.read()
data = fs.file.read()
assert test_data == data
async def handler(request: web.Request) -> web.Response:
data = await request.post()
assert ["data.unknown_mime_type", "conftest.py"] == list(data.keys())
for fs in data.values():
assert isinstance(fs, aiohttp.web_request.FileField)
check_file(fs)
fs.file.close()
resp = web.Response(body=b"OK")
return resp
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
with (here / "data.unknown_mime_type").open("rb") as f1:
with (here / "conftest.py").open("rb") as f2:
resp = await client.post("/", data=[f1, f2])
assert 200 == resp.status
resp.release()
async def test_release_post_data(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
await request.release()
chunk = await request.content.readany()
assert chunk == b""
return web.Response()
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data="post text")
assert 200 == resp.status
resp.release()
async def test_post_form_with_duplicate_keys(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
data = await request.post()
lst = list(data.items())
assert [("a", "1"), ("a", "2")] == lst
return web.Response()
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data=MultiDict([("a", "1"), ("a", "2")]))
assert 200 == resp.status
resp.release()
def test_repr_for_application() -> None:
app = web.Application()
assert f"<Application 0x{id(app):x}>" == repr(app)
async def test_expect_default_handler_unknown(aiohttp_client: AiohttpClient) -> None:
# Test default Expect handler for unknown Expect value.
# A server that does not understand or is unable to comply with any of
# the expectation values in the Expect field of a request MUST respond
# with appropriate error status. The server MUST respond with a 417
# (Expectation Failed) status if any of the expectations cannot be met
# or, if there are other problems with the request, some other 4xx
# status.
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.20
async def handler(request: web.Request) -> web.Response:
assert False
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", headers={"Expect": "SPAM"})
assert 417 == resp.status
resp.release()
async def test_100_continue(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
data = await request.post()
assert b"123" == data["name"]
return web.Response()
form = FormData()
form.add_field("name", b"123")
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data=form, expect100=True)
assert 200 == resp.status
resp.release()
async def test_100_continue_custom(aiohttp_client: AiohttpClient) -> None:
expect_received = False
async def handler(request: web.Request) -> web.Response:
data = await request.post()
assert b"123" == data["name"]
return web.Response()
async def expect_handler(request: web.Request) -> None:
nonlocal expect_received
expect_received = True
assert request.version == HttpVersion11
await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n")
app = web.Application()
app.router.add_post("/", handler, expect_handler=expect_handler)
client = await aiohttp_client(app)
resp = await client.post("/", data=new_dummy_form(), expect100=True)
assert 200 == resp.status
assert expect_received
resp.release()
async def test_100_continue_custom_response(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
data = await request.post()
assert b"123", data["name"]
return web.Response()
async def expect_handler(request: web.Request) -> None:
assert request.version == HttpVersion11
if auth_err:
raise web.HTTPForbidden()
await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n")
app = web.Application()
app.router.add_post("/", handler, expect_handler=expect_handler)
client = await aiohttp_client(app)
auth_err = False
resp = await client.post("/", data=new_dummy_form(), expect100=True)
assert 200 == resp.status
resp.release()
auth_err = True
resp = await client.post("/", data=new_dummy_form(), expect100=True)
assert 403 == resp.status
resp.release()
async def test_expect_handler_custom_response(aiohttp_client: AiohttpClient) -> None:
cache = {"foo": "bar"}
async def handler(request: web.Request) -> web.Response:
return web.Response(text="handler")
async def expect_handler(request: web.Request) -> Optional[web.Response]:
k = request.headers["X-Key"]
cached_value = cache.get(k)
return web.Response(text=cached_value) if cached_value else None
app = web.Application()
# expect_handler is only typed on add_route().
app.router.add_route("POST", "/", handler, expect_handler=expect_handler)
client = await aiohttp_client(app)
async with client.post("/", expect100=True, headers={"X-Key": "foo"}) as resp:
assert resp.status == 200
assert await resp.text() == "bar"
async with client.post("/", expect100=True, headers={"X-Key": "spam"}) as resp:
assert resp.status == 200
assert await resp.text() == "handler"
async def test_100_continue_for_not_found(aiohttp_client: AiohttpClient) -> None:
app = web.Application()
client = await aiohttp_client(app)
resp = await client.post("/not_found", data="data", expect100=True)
assert 404 == resp.status
resp.release()
async def test_100_continue_for_not_allowed(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/", expect100=True)
assert 405 == resp.status
resp.release()
async def test_http11_keep_alive_default(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app, version=HttpVersion11)
resp = await client.get("/")
assert 200 == resp.status
assert resp.version == HttpVersion11
assert "Connection" not in resp.headers
resp.release()
async def test_http10_keep_alive_default(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app, version=HttpVersion10)
async with client.get("/") as resp:
assert 200 == resp.status
assert resp.version == HttpVersion10
assert resp.headers["Connection"] == "keep-alive"
async def test_http10_keep_alive_with_headers_close(
aiohttp_client: AiohttpClient,
) -> None:
async def handler(request: web.Request) -> web.Response:
await request.read()
return web.Response(body=b"OK")
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app, version=HttpVersion10)
headers = {"Connection": "close"}
resp = await client.get("/", headers=headers)
assert 200 == resp.status
assert resp.version == HttpVersion10
assert "Connection" not in resp.headers
resp.release()
async def test_http10_keep_alive_with_headers(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
await request.read()
return web.Response(body=b"OK")
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app, version=HttpVersion10)
headers = {"Connection": "keep-alive"}
resp = await client.get("/", headers=headers)
assert 200 == resp.status
assert resp.version == HttpVersion10
assert resp.headers["Connection"] == "keep-alive"
resp.release()
async def test_upload_file(aiohttp_client: AiohttpClient) -> None:
here = pathlib.Path(__file__).parent
fname = here / "aiohttp.png"
with fname.open("rb") as f:
data = f.read()
async def handler(request: web.Request) -> web.Response:
form = await request.post()
form_file = form["file"]
assert isinstance(form_file, aiohttp.web_request.FileField)
raw_data = form_file.file.read()
form_file.file.close()
assert data == raw_data
return web.Response()
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data={"file": io.BytesIO(data)})
assert 200 == resp.status
resp.release()
async def test_upload_file_object(aiohttp_client: AiohttpClient) -> None:
here = pathlib.Path(__file__).parent
fname = here / "aiohttp.png"
with fname.open("rb") as f:
data = f.read()
async def handler(request: web.Request) -> web.Response:
form = await request.post()
form_file = form["file"]
assert isinstance(form_file, aiohttp.web_request.FileField)
raw_data = form_file.file.read()
form_file.file.close()
assert data == raw_data
return web.Response()
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
with fname.open("rb") as f:
resp = await client.post("/", data={"file": f})
assert 200 == resp.status
resp.release()
@pytest.mark.parametrize(
"method", ["get", "post", "options", "post", "put", "patch", "delete"]
)
async def test_empty_content_for_query_without_body(
method: str, aiohttp_client: AiohttpClient
) -> None:
async def handler(request: web.Request) -> web.Response:
assert not request.body_exists
assert not request.can_read_body
return web.Response()
app = web.Application()
app.router.add_route(method, "/", handler)
client = await aiohttp_client(app)
resp = await client.request(method, "/")
assert 200 == resp.status
async def test_empty_content_for_query_with_body(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert request.body_exists
assert request.can_read_body
body = await request.read()
return web.Response(body=body)
app = web.Application()
app.router.add_post("/", handler)
client = await aiohttp_client(app)
resp = await client.post("/", data=b"data")
assert 200 == resp.status
resp.release()
async def test_get_with_empty_arg(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert "arg" in request.query
assert "" == request.query["arg"]
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/?arg")
assert 200 == resp.status
resp.release()
async def test_large_header(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
headers = {"Long-Header": "ab" * 8129}
resp = await client.get("/", headers=headers)
assert 400 == resp.status
resp.release()
async def test_large_header_allowed(
aiohttp_client: AiohttpClient, aiohttp_server: AiohttpServer
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response()
app = web.Application()
app.router.add_post("/", handler)
server = await aiohttp_server(app, max_field_size=81920)
client = await aiohttp_client(server)
headers = {"Long-Header": "ab" * 8129}
resp = await client.post("/", headers=headers)
assert 200 == resp.status
resp.release()
async def test_get_with_empty_arg_with_equal(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert "arg" in request.query
assert "" == request.query["arg"]
return web.Response()
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/?arg=")
assert 200 == resp.status
resp.release()
async def test_response_with_async_gen(
aiohttp_client: AiohttpClient, fname: pathlib.Path
) -> None:
with fname.open("rb") as f:
data = f.read()
data_size = len(data)
async def stream(f_name: pathlib.Path) -> AsyncIterator[bytes]:
with f_name.open("rb") as f:
data = f.read(100)
while data:
yield data
data = f.read(100)
async def handler(request: web.Request) -> web.Response:
headers = {"Content-Length": str(data_size)}
return web.Response(body=stream(fname), headers=headers)
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
resp_data = await resp.read()
assert resp_data == data
assert resp.headers.get("Content-Length") == str(len(resp_data))
resp.release()
async def test_response_with_async_gen_no_params(
aiohttp_client: AiohttpClient, fname: pathlib.Path
) -> None:
with fname.open("rb") as f:
data = f.read()
data_size = len(data)
async def stream() -> AsyncIterator[bytes]:
with fname.open("rb") as f:
data = f.read(100)
while data:
yield data
data = f.read(100)
async def handler(request: web.Request) -> web.Response:
headers = {"Content-Length": str(data_size)}
return web.Response(body=stream(), headers=headers)
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
resp_data = await resp.read()
assert resp_data == data
assert resp.headers.get("Content-Length") == str(len(resp_data))
resp.release()
async def test_response_with_file(
aiohttp_client: AiohttpClient, fname: pathlib.Path
) -> None:
outer_file_descriptor = None
with fname.open("rb") as f:
data = f.read()
async def handler(request: web.Request) -> web.Response:
nonlocal outer_file_descriptor
outer_file_descriptor = fname.open("rb")
return web.Response(body=outer_file_descriptor)
app = web.Application()
app.router.add_get("/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert 200 == resp.status
resp_data = await resp.read()
expected_content_disposition = 'attachment; filename="conftest.py"'
assert resp_data == data
assert resp.headers.get("Content-Type") in (
"application/octet-stream",
"text/x-python",
"text/plain",
)
assert resp.headers.get("Content-Length") == str(len(resp_data))
assert resp.headers.get("Content-Disposition") == expected_content_disposition