@@ -18,6 +18,7 @@ async def test_available_connections_reassigned():
1818
1919 After reading/closing first request:
2020 Expected: 1 active, 1 queued, 1 connection
21+ Only 1 request should be assigned to the freed-up connection
2122 """
2223 network_backend = httpcore .AsyncMockBackend (
2324 [
@@ -83,23 +84,29 @@ async def test_available_connections_reassigned():
8384 == "<AsyncConnectionPool [Requests: 1 active, 2 queued | Connections: 1 active, 0 idle]>"
8485 )
8586
87+ # Monkey patch connection's handle_async_request to intercept ConnectionNotAvailable
88+ for connection in pool ._connections :
89+ original_handle = connection .handle_async_request
90+
91+ async def monitored_handle_async_request (request ):
92+ try :
93+ return await original_handle (request )
94+ except httpcore .ConnectionNotAvailable : # pragma: nocover
95+ pytest .fail ( # pragma: nocover
96+ "ConnectionNotAvailable was raised on connection, "
97+ "indicating that multiple requests were assigned to a single HTTP/1.1 connection"
98+ )
99+
100+ connection .handle_async_request = monitored_handle_async_request # type: ignore[method-assign]
101+
86102 # Read and close the first response
87103 await response1 .aread ()
88104 await response1 .aclose ()
89105
90106 # Give a short time for the pool to assign the freed-up connection to the queued request
91- await anyio .sleep (0.01 )
92-
93- # After finishing the first request, the pool automatically assigns requests
94- # from the request queue to available connections.
95- # At this point, we should have:
96- # - 1 active request (request2 should become active)
97- # - 1 queued request (request3 should remain queued)
98- # - 1 connection (same connection, now available for request2)
99- assert (
100- repr (pool )
101- == "<AsyncConnectionPool [Requests: 1 active, 1 queued | Connections: 1 active, 0 idle]>"
102- )
107+ # This will trigger the ConnectionNotAvailable if multiple requests are assigned to the same connection
108+ await anyio .sleep (0.05 )
103109
104- # cancel taskgroup to avoid a hanging test
110+ # Cancel taskgroup to avoid a hanging test
111+ # (since request2 is never closed, and hence the task for request3 cannot start)
105112 tg .cancel_scope .cancel ()
0 commit comments