-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathtest_connection_pool.py
830 lines (711 loc) · 28 KB
/
test_connection_pool.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
import logging
import typing
import hpack
import hyperframe.frame
import pytest
from tests import concurrency
import httpcore
def test_connection_pool_with_keepalive():
"""
By default HTTP/1.1 requests should be returned to the connection pool.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with httpcore.ConnectionPool(
network_backend=network_backend,
) as pool:
# Sending an intial request, which once complete will return to the pool, IDLE.
with pool.stream("GET", "https://example.com/") as response:
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 1]>"
]
assert (
repr(pool)
== "<ConnectionPool [Requests: 1 active, 0 queued | Connections: 1 active, 0 idle]>"
)
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 1]>"
]
assert (
repr(pool)
== "<ConnectionPool [Requests: 0 active, 0 queued | Connections: 0 active, 1 idle]>"
)
# Sending a second request to the same origin will reuse the existing IDLE connection.
with pool.stream("GET", "https://example.com/") as response:
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 2]>"
]
assert (
repr(pool)
== "<ConnectionPool [Requests: 1 active, 0 queued | Connections: 1 active, 0 idle]>"
)
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 2]>"
]
assert (
repr(pool)
== "<ConnectionPool [Requests: 0 active, 0 queued | Connections: 0 active, 1 idle]>"
)
# Sending a request to a different origin will not reuse the existing IDLE connection.
with pool.stream("GET", "http://example.com/") as response:
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 2]>",
"<HTTPConnection ['http://example.com:80', HTTP/1.1, ACTIVE, Request Count: 1]>",
]
assert (
repr(pool)
== "<ConnectionPool [Requests: 1 active, 0 queued | Connections: 1 active, 1 idle]>"
)
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 2]>",
"<HTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>",
]
assert (
repr(pool)
== "<ConnectionPool [Requests: 0 active, 0 queued | Connections: 0 active, 2 idle]>"
)
def test_connection_pool_with_close():
"""
HTTP/1.1 requests that include a 'Connection: Close' header should
not be returned to the connection pool.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with httpcore.ConnectionPool(network_backend=network_backend) as pool:
# Sending an intial request, which once complete will not return to the pool.
with pool.stream(
"GET", "https://example.com/", headers={"Connection": "close"}
) as response:
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 1]>"
]
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == []
def test_connection_pool_with_http2():
"""
Test a connection pool with HTTP/2 requests.
"""
network_backend = httpcore.MockBackend(
buffer=[
hyperframe.frame.SettingsFrame().serialize(),
hyperframe.frame.HeadersFrame(
stream_id=1,
data=hpack.Encoder().encode(
[
(b":status", b"200"),
(b"content-type", b"plain/text"),
]
),
flags=["END_HEADERS"],
).serialize(),
hyperframe.frame.DataFrame(
stream_id=1, data=b"Hello, world!", flags=["END_STREAM"]
).serialize(),
hyperframe.frame.HeadersFrame(
stream_id=3,
data=hpack.Encoder().encode(
[
(b":status", b"200"),
(b"content-type", b"plain/text"),
]
),
flags=["END_HEADERS"],
).serialize(),
hyperframe.frame.DataFrame(
stream_id=3, data=b"Hello, world!", flags=["END_STREAM"]
).serialize(),
],
http2=True,
)
with httpcore.ConnectionPool(
network_backend=network_backend,
) as pool:
# Sending an intial request, which once complete will return to the pool, IDLE.
response = pool.request("GET", "https://example.com/")
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/2, IDLE, Request Count: 1]>"
]
# Sending a second request to the same origin will reuse the existing IDLE connection.
response = pool.request("GET", "https://example.com/")
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/2, IDLE, Request Count: 2]>"
]
def test_connection_pool_with_http2_goaway():
"""
Test a connection pool with HTTP/2 requests, that cleanly disconnects
with a GoAway frame after the first request.
"""
network_backend = httpcore.MockBackend(
buffer=[
hyperframe.frame.SettingsFrame().serialize(),
hyperframe.frame.HeadersFrame(
stream_id=1,
data=hpack.Encoder().encode(
[
(b":status", b"200"),
(b"content-type", b"plain/text"),
]
),
flags=["END_HEADERS"],
).serialize(),
hyperframe.frame.DataFrame(
stream_id=1, data=b"Hello, world!", flags=["END_STREAM"]
).serialize(),
hyperframe.frame.GoAwayFrame(
stream_id=0, error_code=0, last_stream_id=1
).serialize(),
b"",
],
http2=True,
)
with httpcore.ConnectionPool(
network_backend=network_backend,
) as pool:
# Sending an intial request, which once complete will return to the pool, IDLE.
response = pool.request("GET", "https://example.com/")
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/2, IDLE, Request Count: 1]>"
]
# Sending a second request to the same origin will require a new connection.
# The original connection has now been closed.
response = pool.request("GET", "https://example.com/")
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/2, IDLE, Request Count: 1]>",
]
def test_trace_request():
"""
The 'trace' request extension allows for a callback function to inspect the
internal events that occur while sending a request.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
called = []
def trace(name, kwargs):
called.append(name)
with httpcore.ConnectionPool(network_backend=network_backend) as pool:
pool.request("GET", "https://example.com/", extensions={"trace": trace})
assert called == [
"connection.connect_tcp.started",
"connection.connect_tcp.complete",
"connection.start_tls.started",
"connection.start_tls.complete",
"http11.send_request_headers.started",
"http11.send_request_headers.complete",
"http11.send_request_body.started",
"http11.send_request_body.complete",
"http11.receive_response_headers.started",
"http11.receive_response_headers.complete",
"http11.receive_response_body.started",
"http11.receive_response_body.complete",
"http11.response_closed.started",
"http11.response_closed.complete",
]
def test_debug_request(caplog):
"""
The 'trace' request extension allows for a callback function to inspect the
internal events that occur while sending a request.
"""
caplog.set_level(logging.DEBUG)
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with httpcore.ConnectionPool(network_backend=network_backend) as pool:
pool.request("GET", "http://example.com/")
assert caplog.record_tuples == [
(
"httpcore.connection",
logging.DEBUG,
"connect_tcp.started host='example.com' port=80 local_address=None timeout=None socket_options=None",
),
(
"httpcore.connection",
logging.DEBUG,
"connect_tcp.complete return_value=<httpcore.MockStream>",
),
(
"httpcore.http11",
logging.DEBUG,
"send_request_headers.started request=<Request [b'GET']>",
),
("httpcore.http11", logging.DEBUG, "send_request_headers.complete"),
(
"httpcore.http11",
logging.DEBUG,
"send_request_body.started request=<Request [b'GET']>",
),
("httpcore.http11", logging.DEBUG, "send_request_body.complete"),
(
"httpcore.http11",
logging.DEBUG,
"receive_response_headers.started request=<Request [b'GET']>",
),
(
"httpcore.http11",
logging.DEBUG,
"receive_response_headers.complete return_value="
"(b'HTTP/1.1', 200, b'OK', [(b'Content-Type', b'plain/text'), (b'Content-Length', b'13')])",
),
(
"httpcore.http11",
logging.DEBUG,
"receive_response_body.started request=<Request [b'GET']>",
),
("httpcore.http11", logging.DEBUG, "receive_response_body.complete"),
("httpcore.http11", logging.DEBUG, "response_closed.started"),
("httpcore.http11", logging.DEBUG, "response_closed.complete"),
("httpcore.connection", logging.DEBUG, "close.started"),
("httpcore.connection", logging.DEBUG, "close.complete"),
]
def test_connection_pool_with_http_exception():
"""
HTTP/1.1 requests that result in an exception during the connection should
not be returned to the connection pool.
"""
network_backend = httpcore.MockBackend([b"Wait, this isn't valid HTTP!"])
called = []
def trace(name, kwargs):
called.append(name)
with httpcore.ConnectionPool(network_backend=network_backend) as pool:
# Sending an initial request, which once complete will not return to the pool.
with pytest.raises(Exception):
pool.request(
"GET", "https://example.com/", extensions={"trace": trace}
)
info = [repr(c) for c in pool.connections]
assert info == []
assert called == [
"connection.connect_tcp.started",
"connection.connect_tcp.complete",
"connection.start_tls.started",
"connection.start_tls.complete",
"http11.send_request_headers.started",
"http11.send_request_headers.complete",
"http11.send_request_body.started",
"http11.send_request_body.complete",
"http11.receive_response_headers.started",
"http11.receive_response_headers.failed",
]
def test_connection_pool_with_connect_exception():
"""
HTTP/1.1 requests that result in an exception during connection should not
be returned to the connection pool.
"""
class FailedConnectBackend(httpcore.MockBackend):
def connect_tcp(
self,
host: str,
port: int,
timeout: typing.Optional[float] = None,
local_address: typing.Optional[str] = None,
socket_options: typing.Optional[
typing.Iterable[httpcore.SOCKET_OPTION]
] = None,
) -> httpcore.NetworkStream:
raise httpcore.ConnectError("Could not connect")
network_backend = FailedConnectBackend([])
called = []
def trace(name, kwargs):
called.append(name)
with httpcore.ConnectionPool(network_backend=network_backend) as pool:
# Sending an initial request, which once complete will not return to the pool.
with pytest.raises(Exception):
pool.request(
"GET", "https://example.com/", extensions={"trace": trace}
)
info = [repr(c) for c in pool.connections]
assert info == []
assert called == [
"connection.connect_tcp.started",
"connection.connect_tcp.failed",
]
def test_connection_pool_with_immediate_expiry():
"""
Connection pools with keepalive_expiry=0.0 should immediately expire
keep alive connections.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with httpcore.ConnectionPool(
keepalive_expiry=0.0,
network_backend=network_backend,
) as pool:
# Sending an intial request, which once complete will not return to the pool.
with pool.stream("GET", "https://example.com/") as response:
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 1]>"
]
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == []
def test_connection_pool_with_no_keepalive_connections_allowed():
"""
When 'max_keepalive_connections=0' is used, IDLE connections should not
be returned to the pool.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with httpcore.ConnectionPool(
max_keepalive_connections=0, network_backend=network_backend
) as pool:
# Sending an intial request, which once complete will not return to the pool.
with pool.stream("GET", "https://example.com/") as response:
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['https://example.com:443', HTTP/1.1, ACTIVE, Request Count: 1]>"
]
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == []
def test_connection_pool_concurrency():
"""
HTTP/1.1 requests made in concurrency must not ever exceed the maximum number
of allowable connection in the pool.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
def fetch(pool, domain, info_list):
with pool.stream("GET", f"http://{domain}/") as response:
info = [repr(c) for c in pool.connections]
info_list.append(info)
response.read()
with httpcore.ConnectionPool(
max_connections=1, network_backend=network_backend
) as pool:
info_list: typing.List[str] = []
with concurrency.open_nursery() as nursery:
for domain in ["a.com", "b.com", "c.com", "d.com", "e.com"]:
nursery.start_soon(fetch, pool, domain, info_list)
for item in info_list:
# Check that each time we inspected the connection pool, only a
# single connection was established at any one time.
assert len(item) == 1
# Each connection was to a different host, and only sent a single
# request on that connection.
assert item[0] in [
"<HTTPConnection ['http://a.com:80', HTTP/1.1, ACTIVE, Request Count: 1]>",
"<HTTPConnection ['http://b.com:80', HTTP/1.1, ACTIVE, Request Count: 1]>",
"<HTTPConnection ['http://c.com:80', HTTP/1.1, ACTIVE, Request Count: 1]>",
"<HTTPConnection ['http://d.com:80', HTTP/1.1, ACTIVE, Request Count: 1]>",
"<HTTPConnection ['http://e.com:80', HTTP/1.1, ACTIVE, Request Count: 1]>",
]
def test_connection_pool_concurrency_same_domain_closing():
"""
HTTP/1.1 requests made in concurrency must not ever exceed the maximum number
of allowable connection in the pool.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"Connection: close\r\n",
b"\r\n",
b"Hello, world!",
]
)
def fetch(pool, domain, info_list):
with pool.stream("GET", f"https://{domain}/") as response:
info = [repr(c) for c in pool.connections]
info_list.append(info)
response.read()
with httpcore.ConnectionPool(
max_connections=1, network_backend=network_backend, http2=True
) as pool:
info_list: typing.List[str] = []
with concurrency.open_nursery() as nursery:
for domain in ["a.com", "a.com", "a.com", "a.com", "a.com"]:
nursery.start_soon(fetch, pool, domain, info_list)
for item in info_list:
# Check that each time we inspected the connection pool, only a
# single connection was established at any one time.
assert len(item) == 1
# Only a single request was sent on each connection.
assert (
item[0]
== "<HTTPConnection ['https://a.com:443', HTTP/1.1, ACTIVE, Request Count: 1]>"
)
def test_connection_pool_concurrency_same_domain_keepalive():
"""
HTTP/1.1 requests made in concurrency must not ever exceed the maximum number
of allowable connection in the pool.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
* 5
)
def fetch(pool, domain, info_list):
with pool.stream("GET", f"https://{domain}/") as response:
info = [repr(c) for c in pool.connections]
info_list.append(info)
response.read()
with httpcore.ConnectionPool(
max_connections=1, network_backend=network_backend, http2=True
) as pool:
info_list: typing.List[str] = []
with concurrency.open_nursery() as nursery:
for domain in ["a.com", "a.com", "a.com", "a.com", "a.com"]:
nursery.start_soon(fetch, pool, domain, info_list)
for item in info_list:
# Check that each time we inspected the connection pool, only a
# single connection was established at any one time.
assert len(item) == 1
# The connection sent multiple requests.
assert item[0] in [
"<HTTPConnection ['https://a.com:443', HTTP/1.1, ACTIVE, Request Count: 1]>",
"<HTTPConnection ['https://a.com:443', HTTP/1.1, ACTIVE, Request Count: 2]>",
"<HTTPConnection ['https://a.com:443', HTTP/1.1, ACTIVE, Request Count: 3]>",
"<HTTPConnection ['https://a.com:443', HTTP/1.1, ACTIVE, Request Count: 4]>",
"<HTTPConnection ['https://a.com:443', HTTP/1.1, ACTIVE, Request Count: 5]>",
]
assert (
repr(pool)
== "<ConnectionPool [Requests: 0 active, 0 queued | Connections: 0 active, 0 idle]>"
)
def test_unsupported_protocol():
with httpcore.ConnectionPool() as pool:
with pytest.raises(httpcore.UnsupportedProtocol):
pool.request("GET", "ftp://www.example.com/")
with pytest.raises(httpcore.UnsupportedProtocol):
pool.request("GET", "://www.example.com/")
def test_connection_pool_closed_while_request_in_flight():
"""
Closing a connection pool while a request/response is still in-flight
should raise an error.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with httpcore.ConnectionPool(
network_backend=network_backend,
) as pool:
# Send a request, and then close the connection pool while the
# response has not yet been streamed.
with pool.stream("GET", "https://example.com/") as response:
pool.close()
with pytest.raises(httpcore.ReadError):
response.read()
def test_connection_pool_timeout():
"""
Ensure that exceeding max_connections can cause a request to timeout.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
with httpcore.ConnectionPool(
network_backend=network_backend, max_connections=1
) as pool:
# Send a request to a pool that is configured to only support a single
# connection, and then ensure that a second concurrent request
# fails with a timeout.
with pool.stream("GET", "https://example.com/"):
with pytest.raises(httpcore.PoolTimeout):
extensions = {"timeout": {"pool": 0.0001}}
pool.request("GET", "https://example.com/", extensions=extensions)
def test_connection_pool_timeout_zero():
"""
A pool timeout of 0 shouldn't raise a PoolTimeout if there's
no need to wait on a new connection.
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
b"HTTP/1.1 200 OK\r\n",
b"Content-Type: plain/text\r\n",
b"Content-Length: 13\r\n",
b"\r\n",
b"Hello, world!",
]
)
# Use a pool timeout of zero.
extensions = {"timeout": {"pool": 0}}
# A connection pool configured to allow only one connection at a time.
with httpcore.ConnectionPool(
network_backend=network_backend, max_connections=1
) as pool:
# Two consecutive requests with a pool timeout of zero.
# Both succeed without raising a timeout.
response = pool.request(
"GET", "https://example.com/", extensions=extensions
)
assert response.status == 200
assert response.content == b"Hello, world!"
response = pool.request(
"GET", "https://example.com/", extensions=extensions
)
assert response.status == 200
assert response.content == b"Hello, world!"
# A connection pool configured to allow only one connection at a time.
with httpcore.ConnectionPool(
network_backend=network_backend, max_connections=1
) as pool:
# Two concurrent requests with a pool timeout of zero.
# Only the first will succeed without raising a timeout.
with pool.stream(
"GET", "https://example.com/", extensions=extensions
) as response:
# The first response hasn't yet completed.
with pytest.raises(httpcore.PoolTimeout):
# So a pool timeout occurs.
pool.request("GET", "https://example.com/", extensions=extensions)
# The first response now completes.
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
def test_http11_upgrade_connection():
"""
HTTP "101 Switching Protocols" indicates an upgraded connection.
We should return the response, so that the network stream
may be used for the upgraded connection.
https://httpwg.org/specs/rfc9110.html#status.101
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/101
"""
network_backend = httpcore.MockBackend(
[
b"HTTP/1.1 101 Switching Protocols\r\n",
b"Connection: upgrade\r\n",
b"Upgrade: custom\r\n",
b"\r\n",
b"...",
]
)
called = []
def trace(name, kwargs):
called.append(name)
with httpcore.ConnectionPool(
network_backend=network_backend, max_connections=1
) as pool:
with pool.stream(
"GET",
"wss://example.com/",
headers={"Connection": "upgrade", "Upgrade": "custom"},
extensions={"trace": trace},
) as response:
assert response.status == 101
network_stream = response.extensions["network_stream"]
content = network_stream.read(max_bytes=1024)
assert content == b"..."
assert called == [
"connection.connect_tcp.started",
"connection.connect_tcp.complete",
"connection.start_tls.started",
"connection.start_tls.complete",
"http11.send_request_headers.started",
"http11.send_request_headers.complete",
"http11.send_request_body.started",
"http11.send_request_body.complete",
"http11.receive_response_headers.started",
"http11.receive_response_headers.complete",
"http11.response_closed.started",
"http11.response_closed.complete",
]