Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0444be0

Browse files
committedMar 14, 2025··
Reraise OSError as ClientConnectionError when failing to explictly close connector socket
This is a followup to #10464 to handle the case where socket.close() can also raise. This matches the logic we have in aiohappyeyeballs: https://github.com/aio-libs/aiohappyeyeballs/blob/e3bd5bdf44f5d187802de6dcb08d27e1ca6da048/src/aiohappyeyeballs/impl.py#L227 fixes #10506
1 parent 754b72f commit 0444be0

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed
 

‎aiohttp/connector.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1143,7 +1143,10 @@ async def _wrap_create_connection(
11431143
# Will be hit if an exception is thrown before the event loop takes the socket.
11441144
# In that case, proactively close the socket to guard against event loop leaks.
11451145
# For example, see https://github.com/MagicStack/uvloop/issues/653.
1146-
sock.close()
1146+
try:
1147+
sock.close()
1148+
except OSError as exc:
1149+
raise client_error(req.connection_key, exc) from exc
11471150

11481151
def _warn_about_tls_in_tls(
11491152
self,

‎tests/test_connector.py

+27
Original file line numberDiff line numberDiff line change
@@ -669,6 +669,33 @@ async def test_tcp_connector_closes_socket_on_error(
669669
await conn.close()
670670

671671

672+
async def test_tcp_connector_closes_socket_on_error_results_in_another_error(
673+
loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock
674+
) -> None:
675+
"""Test that when error occurs while closing the socket."""
676+
req = ClientRequest("GET", URL("https://127.0.0.1:443"), loop=loop)
677+
start_connection.return_value.close.side_effect = OSError(
678+
1, "error from closing socket"
679+
)
680+
681+
conn = aiohttp.TCPConnector()
682+
with (
683+
mock.patch.object(
684+
conn._loop,
685+
"create_connection",
686+
autospec=True,
687+
spec_set=True,
688+
side_effect=ValueError,
689+
),
690+
pytest.raises(aiohttp.ClientConnectionError, match="error from closing socket"),
691+
):
692+
await conn.connect(req, [], ClientTimeout())
693+
694+
assert start_connection.return_value.close.called
695+
696+
await conn.close()
697+
698+
672699
async def test_tcp_connector_server_hostname_default(
673700
loop: asyncio.AbstractEventLoop, start_connection: mock.AsyncMock
674701
) -> None:

0 commit comments

Comments
 (0)
Please sign in to comment.