From 1b7d919db687243b13d78b7498662a8f988b3a33 Mon Sep 17 00:00:00 2001 From: Elias Rohrer Date: Tue, 25 Nov 2025 13:21:45 +0100 Subject: [PATCH] Avoid listening port collision by letting OS assing ports Previously, we could in tests potentially run into listening port collisions resulting into `InvalidSocketAddress` errors. These errors could surface if we rolled port numbers that either collided with other concurrent tests *or* with other unrelated services running on localhost. Here, we simply let the OS assign us a free port number when setting up the testing nodes, which avoids such collisions altoghether (mod the potential TOCTOU race here, which we ignore for now). --- tests/common/mod.rs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/tests/common/mod.rs b/tests/common/mod.rs index b70d2d675..0795946a5 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -215,22 +215,18 @@ pub(crate) fn random_storage_path() -> PathBuf { temp_path } -pub(crate) fn random_port() -> u16 { - let mut rng = rng(); - rng.random_range(5000..32768) -} - pub(crate) fn random_listening_addresses() -> Vec { let num_addresses = 2; - let mut listening_addresses = Vec::with_capacity(num_addresses); + let mut listening_addresses = HashSet::new(); - for _ in 0..num_addresses { - let rand_port = random_port(); + while listening_addresses.len() < num_addresses { + let socket = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let rand_port = socket.local_addr().unwrap().port(); let address: SocketAddress = format!("127.0.0.1:{}", rand_port).parse().unwrap(); - listening_addresses.push(address); + listening_addresses.insert(address); } - listening_addresses + listening_addresses.into_iter().collect() } pub(crate) fn random_node_alias() -> Option {