Skip to content

Commit 4b66b87

Browse files
asvetlovclaude
andauthored
gh-162606: Avoid find_unused_port() races in asyncio tests (#162607)
* gh-162606: Fix port races in asyncio connection-refused tests test_create_connection_local_addr_skip_different_family and test_sock_client_fail expected a connect to an "unused" port to be refused, but the port was not reserved, so a parallel test could start listening on it and the connect would succeed. Keep a bound, non-listening socket open for the duration of each test instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gh-162606: Avoid find_unused_port() races in more asyncio tests Bind servers to port 0 instead of picking a port first and binding it later, retry test_create_connection_local_addr on EADDRINUSE, and keep the port of test_open_connection_happy_eyeball_refcycles reserved on both loopback addresses so the connection is reliably refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gh-162606: Remove unused import in test_proactor_events Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * gh-162606: Accept TimeoutError for non-listening ports on macOS macOS and iOS fail a connect to a bound but non-listening port with ETIMEDOUT immediately instead of ECONNREFUSED. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7a065be commit 4b66b87

6 files changed

Lines changed: 72 additions & 53 deletions

File tree

‎Lib/test/test_asyncio/test_events.py‎

Lines changed: 31 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -795,36 +795,48 @@ def test_create_ssl_unix_connection(self):
795795

796796
def test_create_connection_local_addr(self):
797797
with test_utils.run_test_server() as httpd:
798-
port = socket_helper.find_unused_port()
799-
f = self.loop.create_connection(
800-
lambda: MyProto(loop=self.loop),
801-
*httpd.address, local_addr=(httpd.address[0], port))
802-
tr, pr = self.loop.run_until_complete(f)
798+
# The port can be taken by another process before we bind it.
799+
for try_count in range(5):
800+
port = socket_helper.find_unused_port()
801+
f = self.loop.create_connection(
802+
lambda: MyProto(loop=self.loop),
803+
*httpd.address, local_addr=(httpd.address[0], port))
804+
try:
805+
tr, pr = self.loop.run_until_complete(f)
806+
except OSError as ex:
807+
if ex.errno != errno.EADDRINUSE or try_count == 4:
808+
raise
809+
else:
810+
break
803811
expected = pr.transport.get_extra_info('sockname')[1]
804812
self.assertEqual(port, expected)
805813
tr.close()
806814

807815
@socket_helper.skip_if_tcp_blackhole
808816
def test_create_connection_local_addr_skip_different_family(self):
809817
# See https://github.com/python/cpython/issues/86508
810-
port1 = socket_helper.find_unused_port()
811-
port2 = socket_helper.find_unused_port()
812-
getaddrinfo_orig = self.loop.getaddrinfo
818+
# A bound but non-listening socket reserves a port that refuses
819+
# connections (macOS times them out immediately instead);
820+
# find_unused_port() could be grabbed by another test.
821+
with socket.socket() as sock:
822+
sock.bind(('127.0.0.1', 0))
823+
port = sock.getsockname()[1]
824+
getaddrinfo_orig = self.loop.getaddrinfo
813825

814-
async def getaddrinfo(host, port, *args, **kwargs):
815-
if port == port2:
816-
return [(socket.AF_INET6, socket.SOCK_STREAM, 0, '', ('::1', 0, 0, 0)),
817-
(socket.AF_INET, socket.SOCK_STREAM, 0, '', ('127.0.0.1', 0))]
818-
return await getaddrinfo_orig(host, port, *args, **kwargs)
826+
async def getaddrinfo(host, port, *args, **kwargs):
827+
if host == 'localhost':
828+
return [(socket.AF_INET6, socket.SOCK_STREAM, 0, '', ('::1', 0, 0, 0)),
829+
(socket.AF_INET, socket.SOCK_STREAM, 0, '', ('127.0.0.1', 0))]
830+
return await getaddrinfo_orig(host, port, *args, **kwargs)
819831

820-
self.loop.getaddrinfo = getaddrinfo
832+
self.loop.getaddrinfo = getaddrinfo
821833

822-
f = self.loop.create_connection(
823-
lambda: MyProto(loop=self.loop),
824-
'localhost', port1, local_addr=('localhost', port2))
834+
f = self.loop.create_connection(
835+
lambda: MyProto(loop=self.loop),
836+
'127.0.0.1', port, local_addr=('localhost', 0))
825837

826-
with self.assertRaises(OSError):
827-
self.loop.run_until_complete(f)
838+
with self.assertRaises((ConnectionRefusedError, TimeoutError)):
839+
self.loop.run_until_complete(f)
828840

829841
@socket_helper.skip_if_tcp_blackhole
830842
def test_create_connection_local_addr_nomatch_family(self):

‎Lib/test/test_asyncio/test_proactor_events.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
from asyncio.proactor_events import _ProactorDuplexPipeTransport
1414
from asyncio.proactor_events import _ProactorDatagramTransport
1515
from test.support import os_helper
16-
from test.support import socket_helper
1716
from test.test_asyncio import utils as test_utils
1817

1918

@@ -1071,9 +1070,8 @@ def run_loop(self, coro):
10711070
def prepare(self):
10721071
sock = self.make_socket()
10731072
proto = self.MyProto(self.loop)
1074-
port = socket_helper.find_unused_port()
10751073
srv_sock = self.make_socket(cleanup=False)
1076-
srv_sock.bind(('127.0.0.1', port))
1074+
srv_sock.bind(('127.0.0.1', 0))
10771075
server = self.run_loop(self.loop.create_server(
10781076
lambda: proto, sock=srv_sock))
10791077
self.run_loop(self.loop.sock_connect(sock, srv_sock.getsockname()))

‎Lib/test/test_asyncio/test_sendfile.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,9 +176,9 @@ def reduce_send_buffer_size(self, sock, transport=None):
176176

177177
def prepare_socksendfile(self):
178178
proto = MyProto(self.loop)
179-
port = socket_helper.find_unused_port()
180179
srv_sock = self.make_socket(cleanup=False)
181-
srv_sock.bind((socket_helper.HOST, port))
180+
srv_sock.bind((socket_helper.HOST, 0))
181+
port = srv_sock.getsockname()[1]
182182
server = self.run_loop(self.loop.create_server(
183183
lambda: proto, sock=srv_sock))
184184
self.reduce_receive_buffer_size(srv_sock)
@@ -308,7 +308,6 @@ class SendfileMixin(SendfileBase):
308308
# Note: sendfile via SSL transport is equal to sendfile fallback
309309

310310
def prepare_sendfile(self, *, is_ssl=False, close_after=0):
311-
port = socket_helper.find_unused_port()
312311
srv_proto = MySendfileProto(loop=self.loop,
313312
close_after=close_after)
314313
if is_ssl:
@@ -320,7 +319,8 @@ def prepare_sendfile(self, *, is_ssl=False, close_after=0):
320319
srv_ctx = None
321320
cli_ctx = None
322321
srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
323-
srv_sock.bind((socket_helper.HOST, port))
322+
srv_sock.bind((socket_helper.HOST, 0))
323+
port = srv_sock.getsockname()[1]
324324
server = self.run_loop(self.loop.create_server(
325325
lambda: srv_proto, sock=srv_sock, ssl=srv_ctx))
326326
self.reduce_receive_buffer_size(srv_sock)

‎Lib/test/test_asyncio/test_sock_lowlevel.py‎

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -530,21 +530,19 @@ def test_unix_sock_client_ops(self):
530530
self._basetest_sock_recv_into(httpd, sock)
531531

532532
def test_sock_client_fail(self):
533-
# Make sure that we will get an unused port
534-
address = None
535-
try:
536-
s = socket.socket()
533+
# Keep the port bound but not listening so that no other process
534+
# can take it and connections to it are refused (macOS times them
535+
# out immediately instead).
536+
with socket.socket() as s:
537537
s.bind(('127.0.0.1', 0))
538538
address = s.getsockname()
539-
finally:
540-
s.close()
541539

542-
sock = socket.socket()
543-
sock.setblocking(False)
544-
with self.assertRaises(ConnectionRefusedError):
545-
self.loop.run_until_complete(
546-
self.loop.sock_connect(sock, address))
547-
sock.close()
540+
sock = socket.socket()
541+
sock.setblocking(False)
542+
with self.assertRaises((ConnectionRefusedError, TimeoutError)):
543+
self.loop.run_until_complete(
544+
self.loop.sock_connect(sock, address))
545+
sock.close()
548546

549547
def test_sock_accept(self):
550548
listener = socket.socket()

‎Lib/test/test_asyncio/test_streams.py‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1289,23 +1289,21 @@ async def outer():
12891289
self.assertEqual(messages, [])
12901290

12911291
def _basetest_unhandled_exceptions(self, handle_echo):
1292-
port = socket_helper.find_unused_port()
1293-
12941292
messages = []
12951293
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
12961294

1297-
async def client():
1298-
rd, wr = await asyncio.open_connection('localhost', port)
1295+
async def client(addr):
1296+
rd, wr = await asyncio.open_connection(*addr)
12991297
wr.write(b'test msg')
13001298
await wr.drain()
13011299
wr.close()
13021300
await wr.wait_closed()
13031301

13041302
async def main():
13051303
server = await asyncio.start_server(
1306-
handle_echo, 'localhost', port)
1304+
handle_echo, socket_helper.HOSTv4, 0)
13071305
await server.start_serving()
1308-
await client()
1306+
await client(server.sockets[0].getsockname())
13091307
server.close()
13101308
await server.wait_closed()
13111309

@@ -1329,13 +1327,11 @@ async def handle_echo(reader, writer):
13291327
def test_unhandled_exception_sync_callback(self):
13301328
# An exception raised by a plain-function client_connected_cb is
13311329
# reported like the coroutine case and the transport is closed.
1332-
port = socket_helper.find_unused_port()
1333-
13341330
messages = []
13351331
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
13361332

1337-
async def client():
1338-
rd, wr = await asyncio.open_connection('localhost', port)
1333+
async def client(addr):
1334+
rd, wr = await asyncio.open_connection(*addr)
13391335
async with asyncio.timeout(60):
13401336
data = await rd.read()
13411337
self.assertEqual(data, b'') # the server closed the connection
@@ -1347,9 +1343,9 @@ def handle_echo(reader, writer):
13471343
raise Exception('test')
13481344

13491345
server = await asyncio.start_server(
1350-
handle_echo, 'localhost', port)
1346+
handle_echo, socket_helper.HOSTv4, 0)
13511347
await server.start_serving()
1352-
await client()
1348+
await client(server.sockets[0].getsockname())
13531349
server.close()
13541350
await server.wait_closed()
13551351

@@ -1359,7 +1355,22 @@ def handle_echo(reader, writer):
13591355
'Unhandled exception in client_connected_cb')
13601356

13611357
def test_open_connection_happy_eyeball_refcycles(self):
1362-
port = socket_helper.find_unused_port()
1358+
# Keep the port bound but not listening on both loopback addresses
1359+
# that "localhost" may resolve to, so connections fail.
1360+
reserved = []
1361+
self.addCleanup(lambda: [s.close() for s in reserved])
1362+
sock4 = socket.socket()
1363+
reserved.append(sock4)
1364+
sock4.bind((socket_helper.HOSTv4, 0))
1365+
port = sock4.getsockname()[1]
1366+
if socket_helper.IPV6_ENABLED:
1367+
sock6 = socket.socket(socket.AF_INET6)
1368+
reserved.append(sock6)
1369+
try:
1370+
sock6.bind((socket_helper.HOSTv6, port))
1371+
except OSError:
1372+
self.skipTest(f'cannot bind {socket_helper.HOSTv6} port {port}')
1373+
13631374
async def main():
13641375
exc = None
13651376
try:

‎Lib/test/test_asyncio/test_unix_events.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -563,9 +563,9 @@ def run_loop(self, coro):
563563
def prepare(self):
564564
sock = self.make_socket()
565565
proto = self.MyProto(self.loop)
566-
port = socket_helper.find_unused_port()
567566
srv_sock = self.make_socket(cleanup=False)
568-
srv_sock.bind((socket_helper.HOST, port))
567+
srv_sock.bind((socket_helper.HOST, 0))
568+
port = srv_sock.getsockname()[1]
569569
server = self.run_loop(self.loop.create_server(
570570
lambda: proto, sock=srv_sock))
571571
self.run_loop(self.loop.sock_connect(sock, (socket_helper.HOST, port)))

0 commit comments

Comments
 (0)