-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathtest_connection_pool.py
More file actions
605 lines (513 loc) · 19.9 KB
/
Copy pathtest_connection_pool.py
File metadata and controls
605 lines (513 loc) · 19.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
import logging
from typing import List, Optional
import pytest
from tests import concurrency
from httpcore import (
ConnectionPool,
ConnectError,
PoolTimeout,
ReadError,
UnsupportedProtocol,
)
from httpcore.backends.base import NetworkStream
from httpcore.backends.mock import MockBackend
def test_connection_pool_with_keepalive():
"""
By default HTTP/1.1 requests should be returned to the connection pool.
"""
network_backend = 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 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]>"
]
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]>"
]
# 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]>"
]
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]>"
]
# 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 ['http://example.com:80', HTTP/1.1, ACTIVE, Request Count: 1]>",
"<HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 2]>",
]
response.read()
assert response.status == 200
assert response.content == b"Hello, world!"
info = [repr(c) for c in pool.connections]
assert info == [
"<HTTPConnection ['http://example.com:80', HTTP/1.1, IDLE, Request Count: 1]>",
"<HTTPConnection ['https://example.com:443', HTTP/1.1, IDLE, Request Count: 2]>",
]
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 = 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 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_trace_request():
"""
The 'trace' request extension allows for a callback function to inspect the
internal events that occur while sending a request.
"""
network_backend = 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 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 = 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 ConnectionPool(network_backend=network_backend) as pool:
pool.request("GET", "http://example.com/")
assert caplog.record_tuples == [
(
"httpcore",
logging.DEBUG,
"connection.connect_tcp.started host='example.com' port=80 local_address=None timeout=None",
),
(
"httpcore",
logging.DEBUG,
"connection.connect_tcp.complete return_value=<httpcore.MockStream>",
),
(
"httpcore",
logging.DEBUG,
"http11.send_request_headers.started request=<Request [b'GET']>",
),
("httpcore", logging.DEBUG, "http11.send_request_headers.complete"),
(
"httpcore",
logging.DEBUG,
"http11.send_request_body.started request=<Request [b'GET']>",
),
("httpcore", logging.DEBUG, "http11.send_request_body.complete"),
(
"httpcore",
logging.DEBUG,
"http11.receive_response_headers.started request=<Request [b'GET']>",
),
(
"httpcore",
logging.DEBUG,
"http11.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",
logging.DEBUG,
"http11.receive_response_body.started request=<Request [b'GET']>",
),
("httpcore", logging.DEBUG, "http11.receive_response_body.complete"),
("httpcore", logging.DEBUG, "http11.response_closed.started"),
("httpcore", logging.DEBUG, "http11.response_closed.complete"),
("httpcore", logging.DEBUG, "connection.close.started"),
("httpcore", logging.DEBUG, "connection.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 = MockBackend([b"Wait, this isn't valid HTTP!"])
called = []
def trace(name, kwargs):
called.append(name)
with 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",
"http11.response_closed.started",
"http11.response_closed.complete",
]
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(MockBackend):
def connect_tcp(
self,
host: str,
port: int,
timeout: Optional[float] = None,
local_address: Optional[str] = None,
) -> NetworkStream:
raise ConnectError("Could not connect")
network_backend = FailedConnectBackend([])
called = []
def trace(name, kwargs):
called.append(name)
with 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 = 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 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 = 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 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 = 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 ConnectionPool(
max_connections=1, network_backend=network_backend
) as pool:
info_list: 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 = 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 ConnectionPool(
max_connections=1, network_backend=network_backend, http2=True
) as pool:
info_list: 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 = 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 ConnectionPool(
max_connections=1, network_backend=network_backend, http2=True
) as pool:
info_list: 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]>",
]
def test_unsupported_protocol():
with ConnectionPool() as pool:
with pytest.raises(UnsupportedProtocol):
pool.request("GET", "ftp://www.example.com/")
with pytest.raises(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 = 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 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(ReadError):
response.read()
def test_connection_pool_timeout():
"""
Ensure that exceeding max_connections can cause a request to timeout.
"""
network_backend = 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 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(PoolTimeout):
extensions = {"timeout": {"pool": 0.0001}}
pool.request("GET", "https://example.com/", extensions=extensions)
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 = MockBackend(
[
b"HTTP/1.1 101 Switching Protocols\r\n",
b"Connection: upgrade\r\n",
b"Upgrade: custom\r\n",
b"\r\n",
b"...",
]
)
with ConnectionPool(
network_backend=network_backend, max_connections=1
) as pool:
with pool.stream(
"GET",
"wss://example.com/",
headers={"Connection": "upgrade", "Upgrade": "custom"},
) as response:
assert response.status == 101
network_stream = response.extensions["network_stream"]
content = network_stream.read(max_bytes=1024)
assert content == b"..."