-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_client_functional.py
4241 lines (3214 loc) · 134 KB
/
test_client_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
# HTTP client functional tests against aiohttp.web server
import asyncio
import datetime
import http.cookies
import io
import json
import pathlib
import socket
import ssl
import sys
import tarfile
import time
import zipfile
from typing import (
Any,
AsyncIterator,
Awaitable,
Callable,
Dict,
List,
NoReturn,
Optional,
Type,
Union,
)
from unittest import mock
import pytest
import trustme
from multidict import MultiDict
from pytest_mock import MockerFixture
from yarl import URL
import aiohttp
from aiohttp import Fingerprint, ServerFingerprintMismatch, hdrs, web
from aiohttp.abc import AbstractResolver, ResolveResult
from aiohttp.client_exceptions import (
ClientResponseError,
InvalidURL,
InvalidUrlClientError,
InvalidUrlRedirectClientError,
NonHttpUrlClientError,
NonHttpUrlRedirectClientError,
SocketTimeoutError,
TooManyRedirects,
)
from aiohttp.client_reqrep import ClientRequest
from aiohttp.connector import Connection
from aiohttp.http_writer import StreamWriter
from aiohttp.pytest_plugin import AiohttpClient, AiohttpServer
from aiohttp.test_utils import TestClient, TestServer, unused_port
from aiohttp.typedefs import Handler, Query
@pytest.fixture
def here() -> pathlib.Path:
return pathlib.Path(__file__).parent
@pytest.fixture
def fname(here: pathlib.Path) -> pathlib.Path:
return here / "conftest.py"
async def test_keepalive_two_requests_success(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_route("GET", "/", handler)
connector = aiohttp.TCPConnector(limit=1)
client = await aiohttp_client(app, connector=connector)
resp1 = await client.get("/")
await resp1.read()
resp2 = await client.get("/")
await resp2.read()
assert client._session.connector is not None
assert 1 == len(client._session.connector._conns)
async def test_keepalive_after_head_requests_success(
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")
cnt_conn_reuse = 0
async def on_reuseconn(session: object, ctx: object, params: object) -> None:
nonlocal cnt_conn_reuse
cnt_conn_reuse += 1
trace_config = aiohttp.TraceConfig()
trace_config._on_connection_reuseconn.append(on_reuseconn)
app = web.Application()
app.router.add_route("GET", "/", handler)
app.router.add_route("HEAD", "/", handler)
connector = aiohttp.TCPConnector(limit=1)
client = await aiohttp_client(
app, connector=connector, trace_configs=[trace_config]
)
resp1 = await client.head("/")
await resp1.read()
resp2 = await client.get("/")
await resp2.read()
assert 1 == cnt_conn_reuse
@pytest.mark.parametrize("status", (101, 204, 304))
async def test_keepalive_after_empty_body_status(
aiohttp_client: AiohttpClient, status: int
) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
return web.Response(status=status)
cnt_conn_reuse = 0
async def on_reuseconn(session: object, ctx: object, params: object) -> None:
nonlocal cnt_conn_reuse
cnt_conn_reuse += 1
trace_config = aiohttp.TraceConfig()
trace_config._on_connection_reuseconn.append(on_reuseconn)
app = web.Application()
app.router.add_route("GET", "/", handler)
connector = aiohttp.TCPConnector(limit=1)
client = await aiohttp_client(
app, connector=connector, trace_configs=[trace_config]
)
resp1 = await client.get("/")
await resp1.read()
resp2 = await client.get("/")
await resp2.read()
assert cnt_conn_reuse == 1
@pytest.mark.parametrize("status", (101, 204, 304))
async def test_keepalive_after_empty_body_status_stream_response(
aiohttp_client: AiohttpClient, status: int
) -> None:
async def handler(request: web.Request) -> web.StreamResponse:
stream_response = web.StreamResponse(status=status)
await stream_response.prepare(request)
return stream_response
cnt_conn_reuse = 0
async def on_reuseconn(session: object, ctx: object, params: object) -> None:
nonlocal cnt_conn_reuse
cnt_conn_reuse += 1
trace_config = aiohttp.TraceConfig()
trace_config._on_connection_reuseconn.append(on_reuseconn)
app = web.Application()
app.router.add_route("GET", "/", handler)
connector = aiohttp.TCPConnector(limit=1)
client = await aiohttp_client(
app, connector=connector, trace_configs=[trace_config]
)
resp1 = await client.get("/")
await resp1.read()
resp2 = await client.get("/")
await resp2.read()
assert cnt_conn_reuse == 1
async def test_keepalive_response_released(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_route("GET", "/", handler)
connector = aiohttp.TCPConnector(limit=1)
client = await aiohttp_client(app, connector=connector)
resp1 = await client.get("/")
resp1.release()
resp2 = await client.get("/")
resp2.release()
assert client._session.connector is not None
assert 1 == len(client._session.connector._conns)
async def test_upgrade_connection_not_released_after_read(
aiohttp_client: AiohttpClient,
) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
return web.Response(
status=101, headers={"Connection": "Upgrade", "Upgrade": "tcp"}
)
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
await resp.read()
assert resp.connection is not None
assert not resp.closed
async def test_keepalive_server_force_close_connection(
aiohttp_client: AiohttpClient,
) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
response = web.Response(body=b"OK")
response.force_close()
return response
app = web.Application()
app.router.add_route("GET", "/", handler)
connector = aiohttp.TCPConnector(limit=1)
client = await aiohttp_client(app, connector=connector)
resp1 = await client.get("/")
resp1.close()
resp2 = await client.get("/")
resp2.close()
assert client._session.connector is not None
assert 0 == len(client._session.connector._conns)
async def test_keepalive_timeout_async_sleep() -> 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_route("GET", "/", handler)
runner = web.AppRunner(app, tcp_keepalive=True, keepalive_timeout=0.001)
await runner.setup()
port = unused_port()
site = web.TCPSite(runner, host="localhost", port=port)
await site.start()
try:
async with aiohttp.ClientSession() as sess:
resp1 = await sess.get(f"http://localhost:{port}/")
await resp1.read()
# wait for server keepalive_timeout
await asyncio.sleep(0.01)
resp2 = await sess.get(f"http://localhost:{port}/")
await resp2.read()
finally:
await asyncio.gather(runner.shutdown(), site.stop())
@pytest.mark.skipif(
sys.version_info[:2] == (3, 11),
reason="https://github.com/pytest-dev/pytest/issues/10763",
)
async def test_keepalive_timeout_sync_sleep() -> 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_route("GET", "/", handler)
runner = web.AppRunner(app, tcp_keepalive=True, keepalive_timeout=0.001)
await runner.setup()
port = unused_port()
site = web.TCPSite(runner, host="localhost", port=port)
await site.start()
try:
async with aiohttp.ClientSession() as sess:
resp1 = await sess.get(f"http://localhost:{port}/")
await resp1.read()
# wait for server keepalive_timeout
# time.sleep is a more challenging scenario than asyncio.sleep
time.sleep(0.01)
resp2 = await sess.get(f"http://localhost:{port}/")
await resp2.read()
finally:
await asyncio.gather(runner.shutdown(), site.stop())
async def test_release_early(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_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.closed
await resp.wait_for_close()
assert client._session.connector is not None
assert 1 == len(client._session.connector._conns)
async def test_HTTP_304(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
return web.Response(status=304)
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.status == 304
content = await resp.read()
assert content == b""
async def test_stream_request_on_server_eof(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(text="OK", status=200)
app = web.Application()
app.add_routes([web.get("/", handler)])
app.add_routes([web.put("/", handler)])
client = await aiohttp_client(app)
async def data_gen() -> AsyncIterator[bytes]:
for _ in range(2):
yield b"just data"
await asyncio.sleep(0.1)
assert client.session.connector is not None
async with client.put("/", data=data_gen()) as resp:
assert 200 == resp.status
assert len(client.session.connector._acquired) == 1
conn = next(iter(client.session.connector._acquired))
async with client.get("/") as resp:
assert 200 == resp.status
# First connection should have been closed, otherwise server won't know if it
# received the full message.
conns = next(iter(client.session.connector._conns.values()))
assert len(conns) == 1
assert conns[0][0] is not conn
async def test_stream_request_on_server_eof_nested(
aiohttp_client: AiohttpClient,
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(text="OK", status=200)
app = web.Application()
app.add_routes([web.get("/", handler)])
app.add_routes([web.put("/", handler)])
client = await aiohttp_client(app)
async def data_gen() -> AsyncIterator[bytes]:
for _ in range(2):
yield b"just data"
await asyncio.sleep(0.1)
assert client.session.connector is not None
async with client.put("/", data=data_gen()) as resp:
first_conn = next(iter(client.session.connector._acquired))
assert 200 == resp.status
async with client.get("/") as resp2:
assert 200 == resp2.status
# Should be 2 separate connections
conns = next(iter(client.session.connector._conns.values()))
assert len(conns) == 1
assert first_conn is not None
assert not first_conn.is_connected()
assert first_conn is not conns[0][0]
async def test_HTTP_304_WITH_BODY(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
return web.Response(body=b"test", status=304)
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await client.get("/")
assert resp.status == 304
content = await resp.read()
assert content == b""
async def test_auto_header_user_agent(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert "aiohttp" in request.headers["user-agent"]
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert 200 == resp.status
async def test_skip_auto_headers_user_agent(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert hdrs.USER_AGENT not in request.headers
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/", skip_auto_headers=["user-agent"]) as resp:
assert 200 == resp.status
async def test_skip_default_auto_headers_user_agent(
aiohttp_client: AiohttpClient,
) -> None:
async def handler(request: web.Request) -> web.Response:
assert hdrs.USER_AGENT not in request.headers
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app, skip_auto_headers=["user-agent"])
async with client.get("/") as resp:
assert 200 == resp.status
async def test_skip_auto_headers_content_type(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert hdrs.CONTENT_TYPE not in request.headers
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/", skip_auto_headers=["content-type"]) as resp:
assert 200 == resp.status
async def test_post_data_bytesio(aiohttp_client: AiohttpClient) -> None:
data = b"some buffer"
async def handler(request: web.Request) -> web.Response:
assert len(data) == request.content_length
val = await request.read()
assert data == val
return web.Response()
app = web.Application()
app.router.add_route("POST", "/", handler)
client = await aiohttp_client(app)
with io.BytesIO(data) as file_handle:
async with client.post("/", data=file_handle) as resp:
assert 200 == resp.status
async def test_post_data_with_bytesio_file(aiohttp_client: AiohttpClient) -> None:
data = b"some buffer"
async def handler(request: web.Request) -> web.Response:
post_data = await request.post()
assert ["file"] == list(post_data.keys())
file_field = post_data["file"]
assert isinstance(file_field, web.FileField)
assert data == file_field.file.read()
return web.Response()
app = web.Application()
app.router.add_route("POST", "/", handler)
client = await aiohttp_client(app)
with io.BytesIO(data) as file_handle:
async with client.post("/", data={"file": file_handle}) as resp:
assert 200 == resp.status
async def test_post_data_stringio(aiohttp_client: AiohttpClient) -> None:
data = "some buffer"
async def handler(request: web.Request) -> web.Response:
assert len(data) == request.content_length
assert request.headers["CONTENT-TYPE"] == "text/plain; charset=utf-8"
val = await request.text()
assert data == val
return web.Response()
app = web.Application()
app.router.add_route("POST", "/", handler)
client = await aiohttp_client(app)
async with client.post("/", data=io.StringIO(data)) as resp:
assert 200 == resp.status
async def test_post_data_textio_encoding(aiohttp_client: AiohttpClient) -> None:
data = "текст"
async def handler(request: web.Request) -> web.Response:
assert request.headers["CONTENT-TYPE"] == "text/plain; charset=koi8-r"
val = await request.text()
assert data == val
return web.Response()
app = web.Application()
app.router.add_route("POST", "/", handler)
client = await aiohttp_client(app)
pl = aiohttp.TextIOPayload(io.StringIO(data), encoding="koi8-r")
async with client.post("/", data=pl) as resp:
assert 200 == resp.status
async def test_post_data_zipfile_filelike(aiohttp_client: AiohttpClient) -> None:
data = b"This is a zip file payload text file."
async def handler(request: web.Request) -> web.Response:
val = await request.read()
assert data == val, "Transmitted zipfile member failed to match original data."
return web.Response()
app = web.Application()
app.router.add_route("POST", "/", handler)
client = await aiohttp_client(app)
buf = io.BytesIO()
with zipfile.ZipFile(file=buf, mode="w") as zf:
with zf.open("payload1.txt", mode="w") as zip_filelike_writing:
zip_filelike_writing.write(data)
buf.seek(0)
zf = zipfile.ZipFile(file=buf, mode="r")
resp = await client.post("/", data=zf.open("payload1.txt"))
assert 200 == resp.status
async def test_post_data_tarfile_filelike(aiohttp_client: AiohttpClient) -> None:
data = b"This is a tar file payload text file."
async def handler(request: web.Request) -> web.Response:
val = await request.read()
assert data == val, "Transmitted tarfile member failed to match original data."
return web.Response()
app = web.Application()
app.router.add_route("POST", "/", handler)
client = await aiohttp_client(app)
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as tf:
ti = tarfile.TarInfo(name="payload1.txt")
ti.size = len(data)
tf.addfile(tarinfo=ti, fileobj=io.BytesIO(data))
# Random-access tarfile.
buf.seek(0)
tf = tarfile.open(fileobj=buf, mode="r:")
resp = await client.post("/", data=tf.extractfile("payload1.txt"))
assert 200 == resp.status
# Streaming tarfile.
buf.seek(0)
tf = tarfile.open(fileobj=buf, mode="r|")
for entry in tf:
resp = await client.post("/", data=tf.extractfile(entry))
assert 200 == resp.status
async def test_ssl_client(
aiohttp_server: AiohttpServer,
ssl_ctx: ssl.SSLContext,
aiohttp_client: AiohttpClient,
client_ssl_ctx: ssl.SSLContext,
) -> None:
connector = aiohttp.TCPConnector(ssl=client_ssl_ctx)
async def handler(request: web.Request) -> web.Response:
return web.Response(text="Test message")
app = web.Application()
app.router.add_route("GET", "/", handler)
server = await aiohttp_server(app, ssl=ssl_ctx)
client = await aiohttp_client(server, connector=connector)
resp = await client.get("/")
assert 200 == resp.status
txt = await resp.text()
assert txt == "Test message"
async def test_ssl_client_alpn(
aiohttp_server: AiohttpServer,
aiohttp_client: AiohttpClient,
ssl_ctx: ssl.SSLContext,
) -> None:
async def handler(request: web.Request) -> web.Response:
assert request.transport is not None
sslobj = request.transport.get_extra_info("ssl_object")
return web.Response(text=sslobj.selected_alpn_protocol())
app = web.Application()
app.router.add_route("GET", "/", handler)
ssl_ctx.set_alpn_protocols(("http/1.1",))
server = await aiohttp_server(app, ssl=ssl_ctx)
connector = aiohttp.TCPConnector(ssl=False)
client = await aiohttp_client(server, connector=connector)
resp = await client.get("/")
assert resp.status == 200
txt = await resp.text()
assert txt == "http/1.1"
async def test_tcp_connector_fingerprint_ok(
aiohttp_server: AiohttpServer,
aiohttp_client: AiohttpClient,
ssl_ctx: ssl.SSLContext,
tls_certificate_fingerprint_sha256: bytes,
) -> None:
tls_fingerprint = Fingerprint(tls_certificate_fingerprint_sha256)
async def handler(request: web.Request) -> web.Response:
return web.Response(text="Test message")
connector = aiohttp.TCPConnector(ssl=tls_fingerprint)
app = web.Application()
app.router.add_route("GET", "/", handler)
server = await aiohttp_server(app, ssl=ssl_ctx)
client = await aiohttp_client(server, connector=connector)
async with client.get("/") as resp:
assert resp.status == 200
async def test_tcp_connector_fingerprint_fail(
aiohttp_server: AiohttpServer,
aiohttp_client: AiohttpClient,
ssl_ctx: ssl.SSLContext,
tls_certificate_fingerprint_sha256: bytes,
) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
bad_fingerprint = b"\x00" * len(tls_certificate_fingerprint_sha256)
connector = aiohttp.TCPConnector(ssl=Fingerprint(bad_fingerprint))
app = web.Application()
app.router.add_route("GET", "/", handler)
server = await aiohttp_server(app, ssl=ssl_ctx)
client = await aiohttp_client(server, connector=connector)
with pytest.raises(ServerFingerprintMismatch) as cm:
await client.get("/")
exc = cm.value
assert exc.expected == bad_fingerprint
assert exc.got == tls_certificate_fingerprint_sha256
async def test_format_task_get(aiohttp_server: AiohttpServer) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(body=b"OK")
app = web.Application()
app.router.add_route("GET", "/", handler)
server = await aiohttp_server(app)
client = aiohttp.ClientSession()
task = asyncio.create_task(client.get(server.make_url("/")))
assert f"{task}".startswith("<Task pending")
resp = await task
resp.close()
await client.close()
async def test_str_params(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert "q=t est" in request.rel_url.query_string
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/", params="q=t+est") as resp:
assert 200 == resp.status
async def test_params_and_query_string(aiohttp_client: AiohttpClient) -> None:
"""Test combining params with an existing query_string."""
async def handler(request: web.Request) -> web.Response:
assert request.rel_url.query_string == "q=abc&q=test&d=dog"
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/?q=abc", params="q=test&d=dog") as resp:
assert resp.status == 200
@pytest.mark.parametrize("params", [None, "", {}, MultiDict()])
async def test_empty_params_and_query_string(
aiohttp_client: AiohttpClient, params: Query
) -> None:
"""Test combining empty params with an existing query_string."""
async def handler(request: web.Request) -> web.Response:
assert request.rel_url.query_string == "q=abc"
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/?q=abc", params=params) as resp:
assert resp.status == 200
async def test_drop_params_on_redirect(aiohttp_client: AiohttpClient) -> None:
async def handler_redirect(request: web.Request) -> web.Response:
return web.Response(status=301, headers={"Location": "/ok?a=redirect"})
async def handler_ok(request: web.Request) -> web.Response:
assert request.rel_url.query_string == "a=redirect"
return web.Response(status=200)
app = web.Application()
app.router.add_route("GET", "/ok", handler_ok)
app.router.add_route("GET", "/redirect", handler_redirect)
client = await aiohttp_client(app)
async with client.get("/redirect", params={"a": "initial"}) as resp:
assert resp.status == 200
async def test_drop_fragment_on_redirect(aiohttp_client: AiohttpClient) -> None:
async def handler_redirect(request: web.Request) -> web.Response:
return web.Response(status=301, headers={"Location": "/ok#fragment"})
async def handler_ok(request: web.Request) -> web.Response:
return web.Response(status=200)
app = web.Application()
app.router.add_route("GET", "/ok", handler_ok)
app.router.add_route("GET", "/redirect", handler_redirect)
client = await aiohttp_client(app)
async with client.get("/redirect") as resp:
assert resp.status == 200
assert resp.url.path == "/ok"
async def test_drop_fragment(aiohttp_client: AiohttpClient) -> None:
async def handler_ok(request: web.Request) -> web.Response:
return web.Response(status=200)
app = web.Application()
app.router.add_route("GET", "/ok", handler_ok)
client = await aiohttp_client(app)
async with client.get("/ok#fragment") as resp:
assert resp.status == 200
assert resp.url.path == "/ok"
async def test_history(aiohttp_client: AiohttpClient) -> None:
async def handler_redirect(request: web.Request) -> web.Response:
return web.Response(status=301, headers={"Location": "/ok"})
async def handler_ok(request: web.Request) -> web.Response:
return web.Response(status=200)
app = web.Application()
app.router.add_route("GET", "/ok", handler_ok)
app.router.add_route("GET", "/redirect", handler_redirect)
client = await aiohttp_client(app)
async with client.get("/ok") as resp:
assert len(resp.history) == 0
assert resp.status == 200
async with client.get("/redirect") as resp_redirect:
assert len(resp_redirect.history) == 1
assert resp_redirect.history[0].status == 301
assert resp_redirect.status == 200
async def test_keepalive_closed_by_server(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
body = await request.read()
assert b"" == body
resp = web.Response(body=b"OK")
resp.force_close()
return resp
app = web.Application()
app.router.add_route("GET", "/", handler)
connector = aiohttp.TCPConnector(limit=1)
client = await aiohttp_client(app, connector=connector)
resp1 = await client.get("/")
val1 = await resp1.read()
assert val1 == b"OK"
resp2 = await client.get("/")
val2 = await resp2.read()
assert val2 == b"OK"
assert client._session.connector is not None
assert 0 == len(client._session.connector._conns)
async def test_wait_for(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response(body=b"OK")
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
resp = await asyncio.wait_for(client.get("/"), 10)
assert resp.status == 200
txt = await resp.text()
assert txt == "OK"
async def test_raw_headers(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert resp.status == 200
raw_headers = tuple((bytes(h), bytes(v)) for h, v in resp.raw_headers)
assert raw_headers == (
(b"Content-Length", b"0"),
(b"Date", mock.ANY),
(b"Server", mock.ANY),
)
async def test_host_header_first(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
assert list(request.headers)[0] == hdrs.HOST
return web.Response()
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert resp.status == 200
async def test_empty_header_values(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.Response:
resp = web.Response()
resp.headers["X-Empty"] = ""
return resp
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
async with client.get("/") as resp:
assert resp.status == 200
raw_headers = tuple((bytes(h), bytes(v)) for h, v in resp.raw_headers)
assert raw_headers == (
(b"X-Empty", b""),
(b"Content-Length", b"0"),
(b"Date", mock.ANY),
(b"Server", mock.ANY),
)
async def test_204_with_gzipped_content_encoding(aiohttp_client: AiohttpClient) -> None:
async def handler(request: web.Request) -> web.StreamResponse:
resp = web.StreamResponse(status=204)
resp.content_length = 0
resp.content_type = "application/json"
# resp.enable_compression(web.ContentCoding.gzip)
resp.headers["Content-Encoding"] = "gzip"
await resp.prepare(request)
return resp
app = web.Application()
app.router.add_route("DELETE", "/", handler)
client = await aiohttp_client(app)
async with client.delete("/") as resp:
assert resp.status == 204
assert resp.closed
async def test_timeout_on_reading_headers(
aiohttp_client: AiohttpClient, mocker: MockerFixture
) -> None:
async def handler(request: web.Request) -> NoReturn:
await asyncio.sleep(0.1)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
client = await aiohttp_client(app)
with pytest.raises(asyncio.TimeoutError):
await client.get("/", timeout=aiohttp.ClientTimeout(total=0.01))
async def test_timeout_on_conn_reading_headers(
aiohttp_client: AiohttpClient, mocker: MockerFixture
) -> None:
# tests case where user did not set a connection timeout
async def handler(request: web.Request) -> NoReturn:
await asyncio.sleep(0.1)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
conn = aiohttp.TCPConnector()
client = await aiohttp_client(app, connector=conn)
with pytest.raises(asyncio.TimeoutError):
await client.get("/", timeout=aiohttp.ClientTimeout(total=0.01))
async def test_timeout_on_session_read_timeout(
aiohttp_client: AiohttpClient, mocker: MockerFixture
) -> None:
async def handler(request: web.Request) -> NoReturn:
await asyncio.sleep(0.1)
assert False
app = web.Application()
app.router.add_route("GET", "/", handler)
conn = aiohttp.TCPConnector()
client = await aiohttp_client(
app, connector=conn, timeout=aiohttp.ClientTimeout(sock_read=0.01)
)
with pytest.raises(asyncio.TimeoutError):
await client.get("/")
async def test_read_timeout_between_chunks(
aiohttp_client: AiohttpClient, mocker: MockerFixture
) -> None:
async def handler(request: web.Request) -> web.StreamResponse:
resp = aiohttp.web.StreamResponse()