From e3efacd05d8a74b2f753dd8afbfe62baa1e0770e Mon Sep 17 00:00:00 2001 From: Dirk Engling Date: Fri, 30 Oct 2026 01:44:40 +0100 Subject: Check for free port in the udp integration test, also speed it up by a bit --- tests/integration/harness.py | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) (limited to 'tests/integration/harness.py') diff --git a/tests/integration/harness.py b/tests/integration/harness.py index 122c36d..b98ce83 100644 --- a/tests/integration/harness.py +++ b/tests/integration/harness.py @@ -49,12 +49,26 @@ def bdecode(data): return value(0)[1] -def free_port(): - probe = socket.socket() - probe.bind(("127.0.0.1", 0)) - port = probe.getsockname()[1] - probe.close() - return port +def free_port(attempts=50): + """A port free for both protocols, because the tracker binds both. + + Asking the kernel for a free tcp port says nothing about the udp port of + the same number, and anything on the machine holding that one makes the + tracker exit at once with "Address already in use". + """ + for _ in range(attempts): + tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + tcp.bind(("127.0.0.1", 0)) + udp.bind(("127.0.0.1", tcp.getsockname()[1])) + return tcp.getsockname()[1] + except OSError: + continue + finally: + tcp.close() + udp.close() + raise AssertionError("no port free for both tcp and udp after %d tries" % attempts) class Tracker: -- cgit v1.3