Skip to content

Commit

Permalink
fix: handle OSError on failure to close socket instead of raising Ind…
Browse files Browse the repository at this point in the history
…exError (#114)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: J. Nick Koston <nick@koston.org>
  • Loading branch information
3 people authored Nov 30, 2024
1 parent fd90f56 commit c542f68
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/aiohappyeyeballs/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,11 +176,19 @@ async def _connect_sock(
except (RuntimeError, OSError) as exc:
my_exceptions.append(exc)
if sock is not None:
sock.close()
try:
sock.close()
except OSError as e:
my_exceptions.append(e)
raise
raise
except:
if sock is not None:
sock.close()
try:
sock.close()
except OSError as e:
my_exceptions.append(e)
raise
raise
finally:
exceptions = my_exceptions = None # type: ignore[assignment]
Expand Down
43 changes: 43 additions & 0 deletions tests/test_impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1825,3 +1825,46 @@ async def _sock_connect(
def test_python_38_compat() -> None:
"""Verify python < 3.8.2 compatibility."""
assert asyncio.futures.TimeoutError is asyncio.TimeoutError # type: ignore[attr-defined]


@pytest.mark.asyncio
@pytest.mark.parametrize(
"connect_side_effect",
[
OSError("during connect"),
asyncio.CancelledError("during connect"),
],
)
@patch_socket
async def test_single_addr_info_close_errors(
m_socket: ModuleType, connect_side_effect: BaseException
) -> None:
mock_socket = mock.MagicMock(
family=socket.AF_INET,
type=socket.SOCK_STREAM,
proto=socket.IPPROTO_TCP,
fileno=mock.MagicMock(return_value=1),
)
mock_socket.configure_mock(
**{
"connect.side_effect": connect_side_effect,
"close.side_effect": OSError("during close"),
}
)

def _socket(*args, **kw):
return mock_socket

m_socket.socket = _socket # type: ignore

addr_info = [
(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP,
"",
("107.6.106.82", 80),
)
]
with pytest.raises(OSError, match="during close"):
await start_connection(addr_info)

0 comments on commit c542f68

Please sign in to comment.