Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle OSError on failure to close socket instead of raising IndexError #114

Merged
merged 7 commits into from
Nov 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Loading