diff --git a/Cargo.lock b/Cargo.lock index e5660c8caa..22c655b73d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6106,6 +6106,7 @@ dependencies = [ "zenoh-stats", "zenoh-sync", "zenoh-task", + "zenoh-test", "zenoh-transport", "zenoh-util", ] @@ -6232,6 +6233,7 @@ dependencies = [ "zenoh", "zenoh-config", "zenoh-macros", + "zenoh-test", "zenoh-util", ] @@ -6704,6 +6706,17 @@ dependencies = [ "zenoh-runtime", ] +[[package]] +name = "zenoh-test" +version = "1.9.0" +dependencies = [ + "tokio", + "zenoh", + "zenoh-config", + "zenoh-core", + "zenoh-link", +] + [[package]] name = "zenoh-transport" version = "1.9.0" @@ -6736,6 +6749,7 @@ dependencies = [ "zenoh-stats", "zenoh-sync", "zenoh-task", + "zenoh-test", "zenoh-util", ] diff --git a/Cargo.toml b/Cargo.toml index 7b5d8ed54d..1f8562eb47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ members = [ "commons/zenoh-stats", "commons/zenoh-sync", "commons/zenoh-task", + "commons/zenoh-test", "commons/zenoh-util", "examples", "io/zenoh-link", @@ -244,6 +245,7 @@ zenoh-shm = { version = "=1.9.0", path = "commons/zenoh-shm" } zenoh-stats = { version = "=1.9.0", path = "commons/zenoh-stats" } zenoh-sync = { version = "=1.9.0", path = "commons/zenoh-sync" } zenoh-task = { version = "=1.9.0", path = "commons/zenoh-task" } +zenoh-test = { version = "=1.9.0", path = "commons/zenoh-test" } zenoh-transport = { version = "=1.9.0", path = "io/zenoh-transport", default-features = false } zenoh-util = { version = "=1.9.0", path = "commons/zenoh-util" } zenoh_backend_traits = { version = "=1.9.0", path = "plugins/zenoh-backend-traits", default-features = false } diff --git a/commons/zenoh-test/Cargo.toml b/commons/zenoh-test/Cargo.toml new file mode 100644 index 0000000000..e203f15a3f --- /dev/null +++ b/commons/zenoh-test/Cargo.toml @@ -0,0 +1,19 @@ +[package] +edition = "2021" +name = "zenoh-test" +publish = false +version = "1.9.0" + +[features] +internal = ["zenoh-config/internal", "zenoh/internal"] +unstable = ["zenoh-config/unstable", "zenoh/unstable"] + +[dependencies] +tokio = { workspace = true, features = ["rt", "time"] } +zenoh = { workspace = true, features = ["internal", "unstable"] } +zenoh-config = { workspace = true } +zenoh-core = { workspace = true } +zenoh-link = { workspace = true } + +[package.metadata.cargo-machete] +ignored = ["tokio"] diff --git a/commons/zenoh-test/README.md b/commons/zenoh-test/README.md new file mode 100644 index 0000000000..92a393cc4d --- /dev/null +++ b/commons/zenoh-test/README.md @@ -0,0 +1,137 @@ +# Zenoh Test Utilities + +`zenoh-test` is a workspace crate that provides shared test utilities for the +Zenoh project. It centralises session lifecycle management so that every +integration test in the workspace can reuse the same patterns without +duplicating boilerplate. + +## Why this crate exists + +Historically, Zenoh tests used fixed TCP ports and each test file carried its +own copy of helpers. This caused: + +1. **Port collisions** when running tests in parallel. +2. **System Conflicts**: Hardcoded ports might conflict with other running services. +3. **Maintenance overhead** from scattered, duplicated utility code. + +`zenoh-test` can help by providing: + +* **Dynamic port allocation** — bind to `tcp/127.0.0.1:0` and let the OS + assign an available port. +* **Automatic locator resolution** — after a listener starts, the actual + assigned endpoint is retrieved and passed to connectors. +* **Easier teardown** — provides a simple way to close all sessions at once. + +## Public API + +### Free functions + +| Function | Description | +|---|---| +| `get_free_tcp_port()` | Binds to a random TCP port and returns the port number. ⚠️ Susceptible to TOCTOU races; prefer port `0` listeners when possible. | +| `get_free_udp_port()` | Binds to a random UDP port and returns the port number. ⚠️ Susceptible to TOCTOU races; prefer port `0` listeners when possible. | +| `get_tcp_locator(&session)` | Returns the first `tcp/` endpoint from a session's locators. | +| `get_locators_from_session(&session)` | Returns all locators from a session (async). | +| `get_locators_from_session_sync(&session)` | Returns all locators from a session (blocking). | +| `close_session(s1, s2)` | Closes two sessions in order. Prefer `TestSessions::close()` for new code. | +| `TIMEOUT` | Default 60-second timeout used by `ztimeout!`. | + +### `TestSessions` + +A struct that tracks listener and connector sessions and provides convenience +methods for common test topologies. + +## Usage Examples + +### 1. Simple Peer-to-Peer + +Use `open_pairs()` to create a listener and a connector in one call. +*Reference: `zenoh_session_unicast` in `session.rs`* + +```rust +let mut test_sessions = TestSessions::new(); +let (peer01, peer02) = test_sessions.open_pairs().await; + +// … run assertions … + +test_sessions.close().await; +``` + +### 2. One Listener, Multiple Connectors + +Open a listener, then attach multiple connectors. Connectors automatically +connect to the most recently opened listener. +*Reference: `test_link_events` in `connectivity.rs`* + +```rust +let mut test_sessions = TestSessions::new(); + +let session1 = test_sessions.open_listener().await; +let session2 = test_sessions.open_connector().await; +let session3 = test_sessions.open_connector().await; + +test_sessions.close().await; +``` + +### 3. Custom Configurations + +Retrieve a default config, customise it, then open the session. +*Reference: `zenoh_unicity_brokered` in `unicity.rs`* + +```rust +let mut test_sessions = TestSessions::new(); + +let mut config = test_sessions.get_listener_config("tcp/127.0.0.1:0", 1); +config.set_mode(Some(WhatAmI::Router)).unwrap(); +let router = test_sessions.open_listener_with_cfg(config).await; + +let mut config = test_sessions.get_connector_config(); +config.set_mode(Some(WhatAmI::Client)).unwrap(); +let client = test_sessions.open_connector_with_cfg(config).await; + +test_sessions.close().await; +``` + +### 4. Advanced: Manual Topology + +For complex topologies where multiple listeners need to be interconnected +manually, use the free functions to discover assigned ports. +*Reference: `test_liveliness_subget_router_middle` in `liveliness.rs`* + +```rust +use zenoh_test::{get_tcp_locator, get_locators_from_session}; + +let router = { + let mut c = zenoh_config::Config::default(); + c.listen.endpoints.set(vec!["tcp/127.0.0.1:0".parse().unwrap()]).unwrap(); + c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let _ = c.set_mode(Some(WhatAmI::Router)); + ztimeout!(zenoh::open(c)).unwrap() +}; + +// Get the actual assigned endpoint +let router_endpoint = get_tcp_locator(&router).await; + +// Use it to configure another session +let mut c2 = zenoh_config::Config::default(); +c2.connect.endpoints.set(vec![router_endpoint]).unwrap(); +// … +``` + +### 5. (Not Recommended) Pre-allocating Free Ports + +In rare cases where you must know the endpoint *before* creating the session, +use `get_free_tcp_port()`. +*Reference: `router_linkstate` in `routing.rs`* + +> **Warning**: This is susceptible to TOCTOU race conditions. Another process +> could bind to the "free" port before Zenoh does. + +```rust +let locator = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); + +let node = Node { + listen: vec![locator.clone()], + // … +}; +``` diff --git a/zenoh/tests/common/mod.rs b/commons/zenoh-test/src/lib.rs similarity index 56% rename from zenoh/tests/common/mod.rs rename to commons/zenoh-test/src/lib.rs index 555bafc8e8..df85a63983 100644 --- a/zenoh/tests/common/mod.rs +++ b/commons/zenoh-test/src/lib.rs @@ -11,8 +11,32 @@ // Contributors: // ZettaScale Zenoh Team, // -#![allow(dead_code)] // because every test doesn't use the whole common features -use std::{net::TcpListener, time::Duration}; + +//! Shared test utilities for the Zenoh workspace. +//! +//! This crate provides [`TestSessions`], a helper that manages the lifecycle of +//! Zenoh sessions used in integration tests: +//! +//! * Dynamic port allocation (`tcp/127.0.0.1:0`) to avoid port collisions during +//! parallel test execution. +//! * Automatic locator resolution after a listener binds to port `0`. +//! * Deterministic teardown — connectors are closed before listeners. +//! +//! # Quick start +//! +//! ```rust,ignore +//! use zenoh_test::TestSessions; +//! +//! let mut test_sessions = TestSessions::new(); +//! let (listener, connector) = test_sessions.open_pairs().await; +//! // … run assertions … +//! test_sessions.close().await; +//! ``` + +use std::{ + net::{TcpListener, UdpSocket}, + time::Duration, +}; #[cfg(feature = "internal")] use zenoh::internal::runtime::{Runtime, RuntimeBuilder}; @@ -21,27 +45,69 @@ use zenoh_config::{ModeDependentValue, WhatAmI}; use zenoh_core::ztimeout; use zenoh_link::EndPoint; -const TIMEOUT: Duration = Duration::from_secs(60); +/// Default timeout applied to async operations via [`ztimeout!`]. +pub const TIMEOUT: Duration = Duration::from_secs(60); /// Binds to a random TCP port on loopback and returns the assigned port number. -/// The port is briefly released before Zenoh binds it; races are negligible on localhost. -pub fn get_free_port() -> u16 { +/// +/// The socket is dropped (and the port released) before the caller can use it, +/// so there is a tiny theoretical race. In practice this is negligible on +/// localhost because tests bind immediately after calling this function. +pub fn get_free_tcp_port() -> u16 { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); listener.local_addr().unwrap().port() } +/// Binds to a random UDP port on loopback and returns the assigned port number. +/// +/// The socket is dropped (and the port released) before the caller can use it, +/// so there is a tiny theoretical race. In practice this is negligible on +/// localhost because tests bind immediately after calling this function. +pub fn get_free_udp_port() -> u16 { + let socket = UdpSocket::bind("127.0.0.1:0").unwrap(); + socket.local_addr().unwrap().port() +} + /// Returns the first TCP [`EndPoint`] exposed by `session`. /// -/// Combines [`TestSessions::get_locators_from_session`] with a TCP filter so callers -/// get a ready-to-use connect address after opening a listener with port `0`. +/// This is a convenience wrapper around [`get_locators_from_session`] that +/// filters for the `tcp/` protocol — handy when a listener was opened with +/// `tcp/127.0.0.1:0` and you need the resolved address for a connector. pub async fn get_tcp_locator(session: &Session) -> EndPoint { - TestSessions::get_locators_from_session(session) + get_locators_from_session(session) .await .into_iter() .find(|ep| ep.to_string().starts_with("tcp/")) .expect("Expected a TCP listener endpoint from session") } +/// Queries `session` for its current locators (async version). +pub async fn get_locators_from_session(session: &Session) -> Vec { + session + .info() + .locators() + .await + .into_iter() + .map(|l| l.to_endpoint()) + .collect() +} + +/// Queries `session` for its current locators (blocking version). +pub fn get_locators_from_session_sync(session: &Session) -> Vec { + session + .info() + .locators() + .wait() + .into_iter() + .map(|l| l.to_endpoint()) + .collect() +} + +/// Closes two sessions in order, printing progress to stdout. +/// +/// This is a standalone helper kept for backward compatibility with tests that +/// manage sessions outside of [`TestSessions`]. Prefer +/// [`TestSessions::close`] for new code. pub async fn close_session(peer01: Session, peer02: Session) { println!("[ ][01d] Closing peer01 session"); ztimeout!(peer01.close()).unwrap(); @@ -49,13 +115,33 @@ pub async fn close_session(peer01: Session, peer02: Session) { ztimeout!(peer02.close()).unwrap(); } +/// Manages session lifecycle for integration tests. +/// +/// `TestSessions` keeps track of every listener and connector it opens so that +/// [`close`](Self::close) can tear them down in the right order (connectors +/// first, then listeners). +/// +/// # Locator tracking +/// +/// Each call to [`open_listener`](Self::open_listener) or +/// [`open_listener_with_cfg`](Self::open_listener_with_cfg) **replaces** the +/// internally stored locators with the ones from the newly opened listener. +/// If you need locators from a previously opened listener, call +/// [`get_locators_from_session`] directly. pub struct TestSessions { locators: Vec, listener_sessions: Vec, connector_sessions: Vec, } +impl Default for TestSessions { + fn default() -> Self { + Self::new() + } +} + impl TestSessions { + /// Creates an empty `TestSessions` with no sessions and no stored locators. pub fn new() -> Self { TestSessions { locators: vec![], @@ -64,35 +150,38 @@ impl TestSessions { } } + /// Builds a listener [`Config`](zenoh_config::Config) that listens on + /// `link_num` copies of `endpoint` (typically `"tcp/127.0.0.1:0"`). + /// + /// Multicast scouting is disabled and `max_links` is set to `link_num`. pub fn get_listener_config(&self, endpoint: &str, link_num: usize) -> zenoh_config::Config { let endpoints: Vec = (0..link_num).map(|_| endpoint.parse().unwrap()).collect(); let mut config = zenoh_config::Config::default(); - // Disable multicast by default config.scouting.multicast.set_enabled(Some(false)).unwrap(); - // Listen to port 0 to get a random port config.listen.endpoints.set(endpoints).unwrap(); - // Configure link_num config.transport.unicast.set_max_links(link_num).unwrap(); config } + /// Builds a connector [`Config`](zenoh_config::Config) that connects to + /// the given `locators`. + /// + /// Multicast scouting is disabled and `max_links` matches the number of + /// locators. pub fn get_connector_config_with_endpoint( &self, locators: Vec, ) -> zenoh_config::Config { println!("Connecting to {:?}", locators); let mut config = zenoh_config::Config::default(); - // Disable multicast by default config.scouting.multicast.set_enabled(Some(false)).unwrap(); - // Configure link_num config .transport .unicast .set_max_links(locators.len()) .unwrap(); - // Connect to the locator config .connect .set_endpoints(ModeDependentValue::Unique(locators)) @@ -101,65 +190,50 @@ impl TestSessions { config } + /// Builds a connector config using the internally stored locators + /// (set by the most recent [`open_listener`](Self::open_listener) call). pub fn get_connector_config(&self) -> zenoh_config::Config { self.get_connector_config_with_endpoint(self.locators.clone()) } + /// Returns a clone of the internally stored locators. pub fn locators(&self) -> Vec { self.locators.clone() } - pub async fn get_locators_from_session(session: &Session) -> Vec { - session - .info() - .locators() - .await - .into_iter() - .map(|l| l.to_endpoint()) - .collect() - } - - pub fn get_locators_from_session_sync(session: &Session) -> Vec { - session - .info() - .locators() - .wait() - .into_iter() - .map(|l| l.to_endpoint()) - .collect() - } - + /// Opens a listener session with the given config, stores it, and updates + /// the internal locators. pub async fn open_listener_with_cfg(&mut self, config: zenoh_config::Config) -> Session { let session = ztimeout!(zenoh::open(config)).unwrap(); - // Extract the actual tcp endpoint that session is listening on - let locators = TestSessions::get_locators_from_session(&session).await; + let locators = get_locators_from_session(&session).await; println!("Listening to {:?}", locators); - // Store session and locator self.listener_sessions.push(session.clone()); self.locators = locators; session } + /// Opens a listener session with the given config (blocking version). pub fn open_listener_with_cfg_sync(&mut self, config: zenoh_config::Config) -> Session { let session = zenoh::open(config).wait().unwrap(); - // Extract the actual tcp endpoint that session is listening on - let locators = TestSessions::get_locators_from_session_sync(&session); + let locators = get_locators_from_session_sync(&session); println!("Listening to {:?}", locators); - // Store session and locator self.listener_sessions.push(session.clone()); self.locators = locators; session } + /// Opens a TCP listener on a random port (`tcp/127.0.0.1:0`). pub async fn open_listener(&mut self) -> Session { let config = self.get_listener_config("tcp/127.0.0.1:0", 1); self.open_listener_with_cfg(config).await } + /// Opens a connector session with the given config and tracks it for + /// later teardown. pub async fn open_connector_with_cfg(&mut self, config: zenoh_config::Config) -> Session { let session = ztimeout!(zenoh::open(config)).unwrap(); self.connector_sessions.push(session.clone()); @@ -167,6 +241,7 @@ impl TestSessions { session } + /// Opens a connector session with the given config (blocking version). pub fn open_connector_with_cfg_sync(&mut self, config: zenoh_config::Config) -> Session { let session = zenoh::open(config).wait().unwrap(); self.connector_sessions.push(session.clone()); @@ -174,17 +249,24 @@ impl TestSessions { session } + /// Opens a connector that connects to the internally stored locators. pub async fn open_connector(&mut self) -> Session { let config = self.get_connector_config(); self.open_connector_with_cfg(config).await } + /// Opens a listener + connector pair on a random TCP port. + /// + /// Returns `(listener_session, connector_session)`. pub async fn open_pairs(&mut self) -> (Session, Session) { let listener_session = self.open_listener().await; let connector_session = self.open_connector().await; (listener_session, connector_session) } + /// Opens a listener + client-mode connector pair on a random TCP port. + /// + /// Returns `(listener_session, client_session)`. pub async fn open_pairs_client(&mut self) -> (Session, Session) { let listener_session = self.open_listener().await; @@ -195,8 +277,12 @@ impl TestSessions { (listener_session, connector_session) } + /// Opens two sessions joined via multicast on `endpoint` (e.g. + /// `"udp/224.0.0.1:0"`). + /// + /// The first session binds to port `0`; the second session then binds to + /// the resolved port so both share the same multicast group. pub async fn open_pairs_multicast(&mut self, endpoint: &str) -> (Session, Session) { - // Open 1st listener with port 0 let config = self.get_listener_config(endpoint, 1); let session01 = ztimeout!(zenoh::open(config.clone())).unwrap(); self.listener_sessions.push(session01.clone()); @@ -209,7 +295,6 @@ impl TestSessions { .expect("Expected at least one UDP locator") .to_string(); println!("Connecting to {:?}", locator); - // Open 2nd listener with port got from 1st listener let config = self.get_listener_config(&locator, 1); let session02 = ztimeout!(zenoh::open(config)).unwrap(); self.listener_sessions.push(session02.clone()); @@ -217,21 +302,22 @@ impl TestSessions { (session01, session02) } + /// Opens a listener + connector pair at the **runtime** level. + /// + /// Useful for tests that need direct access to [`Runtime`] instead of + /// [`Session`]. #[cfg(feature = "internal")] pub async fn open_pairs_runtime(&mut self) -> (Runtime, Runtime) { - // Create listener runtime let config = self.get_listener_config("tcp/127.0.0.1:0", 1); let mut listener_runtime = RuntimeBuilder::new(config.into()).build().await.unwrap(); listener_runtime.start().await.unwrap(); - // Extract the actual tcp endpoint that listener_runtime is listening on let locators = listener_runtime .get_locators() .into_iter() .map(|l| l.to_endpoint()) .collect(); - // Create connector runtime let config = self.get_connector_config_with_endpoint(locators); let mut connector_runtime = RuntimeBuilder::new(config.into()).build().await.unwrap(); connector_runtime.start().await.unwrap(); @@ -239,28 +325,26 @@ impl TestSessions { (listener_runtime, connector_runtime) } + /// Closes all tracked sessions: connectors first, then listeners. pub async fn close(&mut self) { - // Close all the connector sessions for session in self.connector_sessions.drain(..) { println!("Closing connector session"); ztimeout!(session.close()).unwrap(); } - // Close all the listener sessions for session in self.listener_sessions.drain(..) { println!("Closing listener session"); ztimeout!(session.close()).unwrap(); } } + /// Closes all tracked sessions (blocking version). pub fn close_sync(&mut self) { - // Close all the connector sessions for session in self.connector_sessions.drain(..) { println!("Closing connector session"); session.close().wait().unwrap(); } - // Close all the listener sessions for session in self.listener_sessions.drain(..) { println!("Closing listener session"); session.close().wait().unwrap(); diff --git a/io/zenoh-transport/Cargo.toml b/io/zenoh-transport/Cargo.toml index 6798f3ea9f..eabf0bc2cc 100644 --- a/io/zenoh-transport/Cargo.toml +++ b/io/zenoh-transport/Cargo.toml @@ -93,4 +93,5 @@ zenoh-util = { workspace = true } [dev-dependencies] zenoh-protocol = { workspace = true, features = ["test"] } +zenoh-test = { workspace = true } zenoh-util = { workspace = true } diff --git a/io/zenoh-transport/tests/endpoints.rs b/io/zenoh-transport/tests/endpoints.rs index 09bde8d178..65cb4de960 100644 --- a/io/zenoh-transport/tests/endpoints.rs +++ b/io/zenoh-transport/tests/endpoints.rs @@ -20,6 +20,7 @@ use zenoh_protocol::{ network::NetworkMessageMut, }; use zenoh_result::ZResult; +use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, TransportPeerEventHandler, @@ -102,9 +103,15 @@ async fn endpoint_tcp() { zenoh_util::init_log_from_env_or("error"); // Define the locators let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 7000).parse().unwrap(), - format!("tcp/[::1]:{}", 7001).parse().unwrap(), - format!("tcp/localhost:{}", 7002).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("tcp/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(), ]; run(&endpoints).await; } @@ -115,9 +122,15 @@ async fn endpoint_udp() { zenoh_util::init_log_from_env_or("error"); // Define the locators let endpoints: Vec = vec![ - format!("udp/127.0.0.1:{}", 7010).parse().unwrap(), - format!("udp/[::1]:{}", 7011).parse().unwrap(), - format!("udp/localhost:{}", 7012).parse().unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("udp/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(), ]; run(&endpoints).await; } @@ -149,9 +162,13 @@ async fn endpoint_ws() { zenoh_util::init_log_from_env_or("error"); // Define the locators let endpoints: Vec = vec![ - format!("ws/127.0.0.1:{}", 7020).parse().unwrap(), - format!("ws/[::1]:{}", 7021).parse().unwrap(), - format!("ws/localhost:{}", 7022).parse().unwrap(), + format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("ws/[::1]:{}", get_free_tcp_port()).parse().unwrap(), + format!("ws/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(), ]; run(&endpoints).await; } @@ -176,10 +193,18 @@ async fn endpoint_tcp_udp() { zenoh_util::init_log_from_env_or("error"); // Define the locators let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 7030).parse().unwrap(), - format!("udp/127.0.0.1:{}", 7031).parse().unwrap(), - format!("tcp/[::1]:{}", 7032).parse().unwrap(), - format!("udp/[::1]:{}", 7033).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), ]; run(&endpoints).await; } @@ -198,10 +223,18 @@ async fn endpoint_tcp_udp_unix() { let _ = std::fs::remove_file(f1); // Define the locators let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 7040).parse().unwrap(), - format!("udp/127.0.0.1:{}", 7041).parse().unwrap(), - format!("tcp/[::1]:{}", 7042).parse().unwrap(), - format!("udp/[::1]:{}", 7043).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), format!("unixsock-stream/{f1}").parse().unwrap(), ]; run(&endpoints).await; @@ -222,8 +255,12 @@ async fn endpoint_tcp_unix() { let _ = std::fs::remove_file(f1); // Define the locators let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 7050).parse().unwrap(), - format!("tcp/[::1]:{}", 7051).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), format!("unixsock-stream/{f1}").parse().unwrap(), ]; run(&endpoints).await; @@ -243,8 +280,12 @@ async fn endpoint_udp_unix() { let f1 = "zenoh-test-unix-socket-4.sock"; let _ = std::fs::remove_file(f1); // Define the locators let endpoints: Vec = vec![ - format!("udp/127.0.0.1:{}", 7060).parse().unwrap(), - format!("udp/[::1]:{}", 7061).parse().unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), format!("unixsock-stream/{f1}").parse().unwrap(), ]; run(&endpoints).await; @@ -314,7 +355,9 @@ AXVFFIgCSluyrolaD6CWD9MqOex4YOfJR2bNxI7lFvuK4AwjyUJzT1U1HXib17mM -----END CERTIFICATE-----"; // Define the locators - let mut endpoint: EndPoint = format!("tls/localhost:{}", 7070).parse().unwrap(); + let mut endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( @@ -393,7 +436,9 @@ AXVFFIgCSluyrolaD6CWD9MqOex4YOfJR2bNxI7lFvuK4AwjyUJzT1U1HXib17mM -----END CERTIFICATE-----"; // Define the locators - let mut endpoint: EndPoint = format!("quic/localhost:{}", 7080).parse().unwrap(); + let mut endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( diff --git a/io/zenoh-transport/tests/multicast_compression.rs b/io/zenoh-transport/tests/multicast_compression.rs index 59e8ebb422..9eaea67687 100644 --- a/io/zenoh-transport/tests/multicast_compression.rs +++ b/io/zenoh-transport/tests/multicast_compression.rs @@ -37,6 +37,7 @@ mod tests { }, }; use zenoh_result::ZResult; + use zenoh_test::get_free_udp_port; use zenoh_transport::{ multicast::{TransportManagerBuilderMulticast, TransportMulticast}, unicast::TransportUnicast, @@ -312,10 +313,11 @@ mod tests { // Define the locator let endpoints: Vec = vec![ format!( - "udp/224.{}.{}.{}:21000", + "udp/224.{}.{}.{}:{}", rand::random::(), rand::random::(), - rand::random::() + rand::random::(), + get_free_udp_port() ) .parse() .unwrap(), diff --git a/io/zenoh-transport/tests/multicast_transport.rs b/io/zenoh-transport/tests/multicast_transport.rs index b9bec0510c..3380fccb19 100644 --- a/io/zenoh-transport/tests/multicast_transport.rs +++ b/io/zenoh-transport/tests/multicast_transport.rs @@ -38,6 +38,7 @@ mod tests { }, }; use zenoh_result::ZResult; + use zenoh_test::get_free_udp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, TransportPeerEventHandler, @@ -309,10 +310,11 @@ mod tests { // Define the locator let endpoints: Vec = vec![ format!( - "udp/224.{}.{}.{}:20000", + "udp/224.{}.{}.{}:{}", rand::random::(), rand::random::(), - rand::random::() + rand::random::(), + get_free_udp_port() ) .parse() .unwrap(), diff --git a/io/zenoh-transport/tests/transport_whitelist.rs b/io/zenoh-transport/tests/transport_whitelist.rs index 7151277391..495156cc92 100644 --- a/io/zenoh-transport/tests/transport_whitelist.rs +++ b/io/zenoh-transport/tests/transport_whitelist.rs @@ -20,6 +20,7 @@ use zenoh_protocol::{ network::NetworkMessageMut, }; use zenoh_result::ZResult; +use zenoh_test::get_free_tcp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, TransportPeerEventHandler, @@ -134,8 +135,12 @@ async fn transport_whitelist_tcp() { // Define the locators let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 17000).parse().unwrap(), - format!("tcp/[::1]:{}", 17001).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), ]; // Run run(&endpoints).await; diff --git a/io/zenoh-transport/tests/unicast_authenticator.rs b/io/zenoh-transport/tests/unicast_authenticator.rs index 4e70f2fd69..502ea3c49c 100644 --- a/io/zenoh-transport/tests/unicast_authenticator.rs +++ b/io/zenoh-transport/tests/unicast_authenticator.rs @@ -20,6 +20,7 @@ use zenoh_protocol::{ network::NetworkMessageMut, }; use zenoh_result::ZResult; +use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::{establishment::ext::auth::Auth, TransportUnicast}, @@ -593,7 +594,9 @@ async fn run_with_lowlatency_transport(endpoint: &EndPoint) { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn authenticator_tcp() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 8000).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run_with_universal_transport(&endpoint).await; } @@ -601,7 +604,9 @@ async fn authenticator_tcp() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn authenticator_tcp_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 8100).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run_with_lowlatency_transport(&endpoint).await; } @@ -609,7 +614,9 @@ async fn authenticator_tcp_with_lowlatency_transport() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn authenticator_udp() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("udp/127.0.0.1:{}", 8010).parse().unwrap(); + let endpoint: EndPoint = format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(); run_with_universal_transport(&endpoint).await; } @@ -617,7 +624,9 @@ async fn authenticator_udp() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn authenticator_udp_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("udp/127.0.0.1:{}", 8110).parse().unwrap(); + let endpoint: EndPoint = format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(); run_with_lowlatency_transport(&endpoint).await; } @@ -646,7 +655,9 @@ async fn authenticator_unixpipe_with_lowlatency_transport() { #[ignore] async fn authenticator_ws() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 8020).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run_with_universal_transport(&endpoint).await; } @@ -655,7 +666,9 @@ async fn authenticator_ws() { #[ignore] async fn authenticator_ws_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 8120).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run_with_lowlatency_transport(&endpoint).await; } @@ -754,7 +767,9 @@ R+IdLiXcyIkg0m9N8I17p0ljCSkbrgGMD3bbePRTfg== -----END CERTIFICATE-----"; // Define the locator - let mut endpoint: EndPoint = format!("tls/localhost:{}", 8030).parse().unwrap(); + let mut endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( @@ -854,7 +869,9 @@ R+IdLiXcyIkg0m9N8I17p0ljCSkbrgGMD3bbePRTfg== -----END CERTIFICATE-----"; // Define the locator - let mut endpoint: EndPoint = format!("quic/localhost:{}", 8041).parse().unwrap(); + let mut endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( diff --git a/io/zenoh-transport/tests/unicast_bind.rs b/io/zenoh-transport/tests/unicast_bind.rs index ba94f1aacb..5e193d27f9 100644 --- a/io/zenoh-transport/tests/unicast_bind.rs +++ b/io/zenoh-transport/tests/unicast_bind.rs @@ -17,6 +17,7 @@ use zenoh_core::ztimeout; use zenoh_link::EndPoint; use zenoh_protocol::core::{Address, WhatAmI, ZenohIdProto}; use zenoh_result::ZResult; +use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::{test_helpers::make_transport_manager_builder, TransportUnicast}, @@ -330,16 +331,20 @@ async fn openclose_tcp_only_connect_with_bind_and_interface() { zenoh_util::init_log_from_env_or("error"); - let bind_addr_str = format!("{}:{}", addrs[0], 13002); + let listen_port = get_free_tcp_port(); + let bind_port = get_free_tcp_port(); + let bind_addr_str = format!("{}:{}", addrs[0], bind_port); let bind_addr = Address::from(bind_addr_str.as_str()); - let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], 13001).parse().unwrap(); + let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], listen_port).parse().unwrap(); // declaring `bind` and `iface` simultaneously should be unsupported, and there for fail - let connect_endpoint: EndPoint = - format!("tcp/{}:{}#iface=lo;bind={}", addrs[0], 13001, bind_addr) - .parse() - .unwrap(); + let connect_endpoint: EndPoint = format!( + "tcp/{}:{}#iface=lo;bind={}", + addrs[0], listen_port, bind_addr + ) + .parse() + .unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, &bind_addr, false).await; @@ -352,16 +357,19 @@ async fn openclose_tcp_only_connect_with_bind_restriction() { zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], 13003).parse().unwrap(); - let bind_addr_str = format!("{}:{}", addrs[0], 13004); + let listen_port = get_free_tcp_port(); + let bind_port = get_free_tcp_port(); + let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], listen_port).parse().unwrap(); + let bind_addr_str = format!("{}:{}", addrs[0], bind_port); let bind_addr = Address::from(bind_addr_str.as_str()); // Bind to different port on same IP address // Expect this test to succeed - // When running the test multiple times locally a TcpStream does not get cleaned up - let connect_endpoint: EndPoint = format!("tcp/{}:{}#bind={}", addrs[0], 13003, bind_addr_str) - .parse() - .unwrap(); + let connect_endpoint: EndPoint = + format!("tcp/{}:{}#bind={}", addrs[0], listen_port, bind_addr_str) + .parse() + .unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, &bind_addr, false).await; @@ -380,16 +388,18 @@ async fn openclose_tcp_only_connect_with_bind_restriction_mismatch_protocols() { return; } - let bind_addr_str = format!("{}:{}", addrs_v6[0], 13006); + let listen_port = get_free_tcp_port(); + let bind_addr_str = format!("{}:{}", addrs_v6[0], get_free_tcp_port()); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], 13005).parse().unwrap(); + let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], listen_port).parse().unwrap(); // Connecting to an IPv4 endpoint while binding to an IPv6 address should fail. - let connect_endpoint: EndPoint = format!("tcp/{}:{}#bind={}", addrs[0], 13005, bind_addr_str) - .parse() - .unwrap(); + let connect_endpoint: EndPoint = + format!("tcp/{}:{}#bind={}", addrs[0], listen_port, bind_addr_str) + .parse() + .unwrap(); openclose_transport_expect_failure(&listen_endpoint, &connect_endpoint, false).await; } @@ -407,16 +417,18 @@ async fn openclose_udp_only_connect_with_bind_restriction_mismatch_protocols() { return; } - let bind_addr_str = format!("{}:{}", addrs_v6[0], 13006); + let listen_port = get_free_udp_port(); + let bind_addr_str = format!("{}:{}", addrs_v6[0], get_free_udp_port()); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], 13005).parse().unwrap(); + let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], listen_port).parse().unwrap(); // Connecting to an IPv4 endpoint while binding to an IPv6 address should fail. - let connect_endpoint: EndPoint = format!("udp/{}:{}#bind={}", addrs[0], 13005, bind_addr_str) - .parse() - .unwrap(); + let connect_endpoint: EndPoint = + format!("udp/{}:{}#bind={}", addrs[0], listen_port, bind_addr_str) + .parse() + .unwrap(); openclose_transport_expect_failure(&listen_endpoint, &connect_endpoint, false).await; } @@ -426,17 +438,21 @@ async fn openclose_udp_only_connect_with_bind_restriction_mismatch_protocols() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_udp_only_connect_with_bind_and_interface() { let addrs = get_ipv4_ipaddrs(None); - let bind_addr_str = format!("{}:{}", addrs[0], 13008); + let listen_port = get_free_udp_port(); + let bind_port = get_free_udp_port(); + let bind_addr_str = format!("{}:{}", addrs[0], bind_port); let bind_addr = Address::from(bind_addr_str.as_str()); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], 13007).parse().unwrap(); + let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], listen_port).parse().unwrap(); - let connect_endpoint: EndPoint = - format!("udp/{}:{}#iface=lo;bind={}", addrs[0], 13007, bind_addr_str) - .parse() - .unwrap(); + let connect_endpoint: EndPoint = format!( + "udp/{}:{}#iface=lo;bind={}", + addrs[0], listen_port, bind_addr_str + ) + .parse() + .unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, &bind_addr, false).await; @@ -446,16 +462,19 @@ async fn openclose_udp_only_connect_with_bind_and_interface() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_udp_only_connect_with_bind_restriction() { let addrs = get_ipv4_ipaddrs(None); - let bind_addr_str = format!("{}:{}", addrs[0], 13010); + let listen_port = get_free_udp_port(); + let bind_port = get_free_udp_port(); + let bind_addr_str = format!("{}:{}", addrs[0], bind_port); let bind_addr = Address::from(bind_addr_str.as_str()); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], 13009).parse().unwrap(); + let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], listen_port).parse().unwrap(); - let connect_endpoint: EndPoint = format!("udp/{}:{}#bind={}", addrs[0], 13009, bind_addr_str) - .parse() - .unwrap(); + let connect_endpoint: EndPoint = + format!("udp/{}:{}#bind={}", addrs[0], listen_port, bind_addr_str) + .parse() + .unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, &bind_addr, false).await; @@ -467,13 +486,14 @@ async fn openclose_quic_only_connect_with_bind_restriction() { use zenoh_link_commons::tls::config::*; zenoh_util::init_log_from_env_or("error"); - let bind_addr_str = format!("localhost:{}", 13012); + let connect_port = get_free_udp_port(); + let bind_addr_str = format!("localhost:{}", get_free_udp_port()); let bind_addr = Address::from(bind_addr_str.as_str()); let client_auth = "true"; // Define the client let mut connect_endpoint: EndPoint = - (format!("quic/localhost:{}#bind={}", 13011, bind_addr_str)) + (format!("quic/localhost:{}#bind={}", connect_port, bind_addr_str)) .parse() .unwrap(); connect_endpoint @@ -491,7 +511,9 @@ async fn openclose_quic_only_connect_with_bind_restriction() { .unwrap(); // Define the server - let mut listen_endpoint: EndPoint = (format!("quic/localhost:{}", 13011)).parse().unwrap(); + let mut listen_endpoint: EndPoint = (format!("quic/localhost:{}", connect_port)) + .parse() + .unwrap(); listen_endpoint .config_mut() .extend_from_iter( @@ -516,13 +538,14 @@ async fn openclose_tls_only_connect_with_bind_restriction() { use zenoh_link_commons::tls::config::*; zenoh_util::init_log_from_env_or("error"); - let bind_addr_str = format!("localhost:{}", 13014); + let connect_port = get_free_tcp_port(); + let bind_addr_str = format!("localhost:{}", get_free_tcp_port()); let bind_addr = Address::from(bind_addr_str.as_str()); let client_auth = "true"; // Define the client let mut connect_endpoint: EndPoint = - (format!("tls/localhost:{}#bind={}", 13013, bind_addr_str)) + (format!("tls/localhost:{}#bind={}", connect_port, bind_addr_str)) .parse() .unwrap(); connect_endpoint @@ -540,7 +563,8 @@ async fn openclose_tls_only_connect_with_bind_restriction() { .unwrap(); // Define the server - let mut listen_endpoint: EndPoint = (format!("tls/localhost:{}", 13013)).parse().unwrap(); + let mut listen_endpoint: EndPoint = + (format!("tls/localhost:{}", connect_port)).parse().unwrap(); listen_endpoint .config_mut() .extend_from_iter( diff --git a/io/zenoh-transport/tests/unicast_compression.rs b/io/zenoh-transport/tests/unicast_compression.rs index 445cffc1e4..5a2a60a03c 100644 --- a/io/zenoh-transport/tests/unicast_compression.rs +++ b/io/zenoh-transport/tests/unicast_compression.rs @@ -33,6 +33,7 @@ mod tests { network::{push::ext::QoSType, NetworkMessage, NetworkMessageMut, Push}, }; use zenoh_result::ZResult; + use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::{test_helpers::make_transport_manager_builder, TransportUnicast}, @@ -384,8 +385,12 @@ mod tests { // Define the locators let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 19000).parse().unwrap(), - format!("tcp/[::1]:{}", 19001).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), ]; // Define the reliability and congestion control let channel = [ @@ -408,7 +413,9 @@ mod tests { zenoh_util::init_log_from_env_or("error"); // Define the locators - let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", 19100).parse().unwrap()]; + let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap()]; // Define the reliability and congestion control let channel = [ Channel { @@ -431,8 +438,12 @@ mod tests { // Define the locator let endpoints: Vec = vec![ - format!("udp/127.0.0.1:{}", 19010).parse().unwrap(), - format!("udp/[::1]:{}", 19011).parse().unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), ]; // Define the reliability and congestion control let channel = [ @@ -455,7 +466,9 @@ mod tests { zenoh_util::init_log_from_env_or("error"); // Define the locator - let endpoints: Vec = vec![format!("udp/127.0.0.1:{}", 19110).parse().unwrap()]; + let endpoints: Vec = vec![format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap()]; // Define the reliability and congestion control let channel = [ Channel { diff --git a/io/zenoh-transport/tests/unicast_concurrent.rs b/io/zenoh-transport/tests/unicast_concurrent.rs index d769cdd118..00042db581 100644 --- a/io/zenoh-transport/tests/unicast_concurrent.rs +++ b/io/zenoh-transport/tests/unicast_concurrent.rs @@ -31,6 +31,7 @@ use zenoh_protocol::{ }, }; use zenoh_result::ZResult; +use zenoh_test::get_free_tcp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, TransportPeerEventHandler, @@ -318,26 +319,20 @@ async fn transport_concurrent(endpoint01: Vec, endpoint02: Vec = vec![ - format!("tcp/127.0.0.1:{}", 9000).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9001).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9002).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9003).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9004).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9005).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9006).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9007).parse().unwrap(), - ]; - let endpoint02: Vec = vec![ - format!("tcp/127.0.0.1:{}", 9010).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9011).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9012).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9013).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9014).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9015).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9016).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 9017).parse().unwrap(), - ]; + let endpoint01: Vec = (0..8) + .map(|_| { + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); + let endpoint02: Vec = (0..8) + .map(|_| { + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); transport_concurrent(endpoint01, endpoint02).await; } @@ -348,26 +343,20 @@ async fn transport_tcp_concurrent() { async fn transport_ws_concurrent() { zenoh_util::init_log_from_env_or("error"); - let endpoint01: Vec = vec![ - format!("ws/127.0.0.1:{}", 9020).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9021).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9022).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9023).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9024).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9025).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9026).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9027).parse().unwrap(), - ]; - let endpoint02: Vec = vec![ - format!("ws/127.0.0.1:{}", 9030).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9031).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9032).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9033).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9034).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9035).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9036).parse().unwrap(), - format!("ws/127.0.0.1:{}", 9037).parse().unwrap(), - ]; + let endpoint01: Vec = (0..8) + .map(|_| { + format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); + let endpoint02: Vec = (0..8) + .map(|_| { + format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); transport_concurrent(endpoint01, endpoint02).await; } diff --git a/io/zenoh-transport/tests/unicast_fragmentation.rs b/io/zenoh-transport/tests/unicast_fragmentation.rs index b40a0a82e9..4ad3a2c29f 100644 --- a/io/zenoh-transport/tests/unicast_fragmentation.rs +++ b/io/zenoh-transport/tests/unicast_fragmentation.rs @@ -30,6 +30,7 @@ use zenoh_protocol::{ network::{push::ext::QoSType, NetworkMessage, NetworkMessageExt, NetworkMessageMut, Push}, }; use zenoh_result::ZResult; +use zenoh_test::get_free_tcp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::{test_helpers::make_transport_manager_builder, TransportUnicast}, @@ -306,7 +307,9 @@ async fn fragmentation_unicast_tcp_only() { zenoh_util::init_log_from_env_or("error"); // Define the locators - let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", 16800).parse().unwrap()]; + let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap()]; // Run run_single(&endpoints, &endpoints).await; } diff --git a/io/zenoh-transport/tests/unicast_intermittent.rs b/io/zenoh-transport/tests/unicast_intermittent.rs index 155930ba89..614d769a80 100644 --- a/io/zenoh-transport/tests/unicast_intermittent.rs +++ b/io/zenoh-transport/tests/unicast_intermittent.rs @@ -32,6 +32,7 @@ use zenoh_protocol::{ }, }; use zenoh_result::ZResult; +use zenoh_test::get_free_tcp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::{test_helpers::make_transport_manager_builder, TransportUnicast}, @@ -403,7 +404,9 @@ async fn lowlatency_transport_intermittent(endpoint: &EndPoint) { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn transport_tcp_intermittent() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 12000).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); universal_transport_intermittent(&endpoint).await; } @@ -411,7 +414,9 @@ async fn transport_tcp_intermittent() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn transport_tcp_intermittent_for_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 12100).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); lowlatency_transport_intermittent(&endpoint).await; } @@ -420,7 +425,9 @@ async fn transport_tcp_intermittent_for_lowlatency_transport() { #[ignore] async fn transport_ws_intermittent() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 12010).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); universal_transport_intermittent(&endpoint).await; } @@ -429,7 +436,9 @@ async fn transport_ws_intermittent() { #[ignore] async fn transport_ws_intermittent_for_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 12110).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); lowlatency_transport_intermittent(&endpoint).await; } diff --git a/io/zenoh-transport/tests/unicast_multilink.rs b/io/zenoh-transport/tests/unicast_multilink.rs index 354ae8cce5..ff44f60b55 100644 --- a/io/zenoh-transport/tests/unicast_multilink.rs +++ b/io/zenoh-transport/tests/unicast_multilink.rs @@ -19,6 +19,7 @@ mod tests { use zenoh_link::EndPoint; use zenoh_protocol::core::{WhatAmI, ZenohIdProto}; use zenoh_result::ZResult; + use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, DummyTransportPeerEventHandler, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, @@ -480,7 +481,9 @@ mod tests { async fn multilink_tcp_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 18000).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); multilink_transport(&endpoint).await; } @@ -489,7 +492,9 @@ mod tests { async fn multilink_udp_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("udp/127.0.0.1:{}", 18010).parse().unwrap(); + let endpoint: EndPoint = format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(); multilink_transport(&endpoint).await; } @@ -499,7 +504,9 @@ mod tests { async fn multilink_ws_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 18020).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); multilink_transport(&endpoint).await; } @@ -609,7 +616,9 @@ Ck0v2xSPAiVjg6w65rUQeW6uB5m0T2wyj+wm0At8vzhZPlgS1fKhcmT2dzOq3+oN R+IdLiXcyIkg0m9N8I17p0ljCSkbrgGMD3bbePRTfg== -----END CERTIFICATE-----"; - let mut endpoint: EndPoint = format!("tls/localhost:{}", 18030).parse().unwrap(); + let mut endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( @@ -707,7 +716,9 @@ R+IdLiXcyIkg0m9N8I17p0ljCSkbrgGMD3bbePRTfg== -----END CERTIFICATE-----"; // Define the locator - let mut endpoint: EndPoint = format!("quic/localhost:{}", 18040).parse().unwrap(); + let mut endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( diff --git a/io/zenoh-transport/tests/unicast_openclose.rs b/io/zenoh-transport/tests/unicast_openclose.rs index a8d7513ba0..0b998c5a10 100644 --- a/io/zenoh-transport/tests/unicast_openclose.rs +++ b/io/zenoh-transport/tests/unicast_openclose.rs @@ -17,6 +17,7 @@ use zenoh_core::ztimeout; use zenoh_link::EndPoint; use zenoh_protocol::core::{WhatAmI, ZenohIdProto}; use zenoh_result::ZResult; +use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::{test_helpers::make_transport_manager_builder, TransportUnicast}, @@ -524,7 +525,9 @@ async fn openclose_universal_transport_tls( #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tcp_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 13000).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_universal_transport(&endpoint).await; } @@ -532,7 +535,9 @@ async fn openclose_tcp_only() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tcp_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 13100).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_lowlatency_transport(&endpoint).await; } @@ -540,7 +545,9 @@ async fn openclose_tcp_only_with_lowlatency_transport() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_udp_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("udp/127.0.0.1:{}", 13010).parse().unwrap(); + let endpoint: EndPoint = format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(); openclose_universal_transport(&endpoint).await; } @@ -548,7 +555,9 @@ async fn openclose_udp_only() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_udp_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("udp/127.0.0.1:{}", 13110).parse().unwrap(); + let endpoint: EndPoint = format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(); openclose_lowlatency_transport(&endpoint).await; } @@ -557,7 +566,9 @@ async fn openclose_udp_only_with_lowlatency_transport() { #[ignore] async fn openclose_ws_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 13020).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_universal_transport(&endpoint).await; } @@ -566,7 +577,9 @@ async fn openclose_ws_only() { #[ignore] async fn openclose_ws_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 13120).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_lowlatency_transport(&endpoint).await; } @@ -606,56 +619,72 @@ async fn openclose_unix_only() { #[cfg(feature = "transport_tls")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tls_only() { - let endpoint: EndPoint = format!("tls/localhost:{}", 13030).parse().unwrap(); + let endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, false, false).await; } #[cfg(feature = "transport_tls")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tls_only_with_mtls() { - let endpoint: EndPoint = format!("tls/localhost:{}", 13031).parse().unwrap(); + let endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, false, true).await; } #[cfg(feature = "transport_tls")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tls_only_with_no_common_name() { - let endpoint: EndPoint = format!("tls/localhost:{}", 13032).parse().unwrap(); + let endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, true, false).await; } #[cfg(feature = "transport_tls")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tls_only_with_mtls_and_no_common_name() { - let endpoint: EndPoint = format!("tls/localhost:{}", 13033).parse().unwrap(); + let endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, true, true).await; } #[cfg(feature = "transport_quic")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_quic_only() { - let endpoint: EndPoint = format!("quic/localhost:{}", 13040).parse().unwrap(); + let endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, false, false).await; } #[cfg(feature = "transport_quic")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_quic_only_with_mtls() { - let endpoint: EndPoint = format!("quic/localhost:{}", 13041).parse().unwrap(); + let endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, false, true).await; } #[cfg(feature = "transport_quic")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_quic_only_with_no_common_name() { - let endpoint: EndPoint = format!("quic/localhost:{}", 13042).parse().unwrap(); + let endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, true, false).await; } #[cfg(feature = "transport_quic")] #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_quic_only_with_mtls_and_no_common_name() { - let endpoint: EndPoint = format!("quic/localhost:{}", 13043).parse().unwrap(); + let endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); openclose_universal_transport_tls(endpoint, true, true).await; } @@ -665,12 +694,13 @@ async fn openclose_quic_only_with_mtls_and_no_common_name() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tcp_only_connect_with_interface_restriction() { let addrs = get_ipv4_ipaddrs(None); + let port = get_free_tcp_port(); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], 13001).parse().unwrap(); + let listen_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], port).parse().unwrap(); - let connect_endpoint: EndPoint = format!("tcp/{}:{}#iface=lo", addrs[0], 13001) + let connect_endpoint: EndPoint = format!("tcp/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); @@ -684,14 +714,15 @@ async fn openclose_tcp_only_connect_with_interface_restriction() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_tcp_only_listen_with_interface_restriction() { let addrs = get_ipv4_ipaddrs(None); + let port = get_free_tcp_port(); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("tcp/{}:{}#iface=lo", addrs[0], 13002) + let listen_endpoint: EndPoint = format!("tcp/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); - let connect_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], 13002).parse().unwrap(); + let connect_endpoint: EndPoint = format!("tcp/{}:{}", addrs[0], port).parse().unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, false).await; @@ -703,12 +734,13 @@ async fn openclose_tcp_only_listen_with_interface_restriction() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_udp_only_connect_with_interface_restriction() { let addrs = get_ipv4_ipaddrs(None); + let port = get_free_udp_port(); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], 13004).parse().unwrap(); + let listen_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], port).parse().unwrap(); - let connect_endpoint: EndPoint = format!("udp/{}:{}#iface=lo", addrs[0], 13004) + let connect_endpoint: EndPoint = format!("udp/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); @@ -722,13 +754,14 @@ async fn openclose_udp_only_connect_with_interface_restriction() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn openclose_udp_only_listen_with_interface_restriction() { let addrs = get_ipv4_ipaddrs(None); + let port = get_free_udp_port(); zenoh_util::init_log_from_env_or("error"); - let listen_endpoint: EndPoint = format!("udp/{}:{}#iface=lo", addrs[0], 13005) + let listen_endpoint: EndPoint = format!("udp/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); - let connect_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], 13005).parse().unwrap(); + let connect_endpoint: EndPoint = format!("udp/{}:{}", addrs[0], port).parse().unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, false).await; @@ -751,9 +784,10 @@ async fn openclose_quic_only_connect_with_interface_restriction() { zenoh_util::init_log_from_env_or("error"); let addrs = get_ipv4_ipaddrs(None); + let port = get_free_udp_port(); let (ca, cert, key) = get_tls_certs(); - let mut listen_endpoint: EndPoint = format!("quic/{}:{}", addrs[0], 13006).parse().unwrap(); + let mut listen_endpoint: EndPoint = format!("quic/{}:{}", addrs[0], port).parse().unwrap(); listen_endpoint .config_mut() .extend_from_iter( @@ -767,7 +801,7 @@ async fn openclose_quic_only_connect_with_interface_restriction() { ) .unwrap(); - let connect_endpoint: EndPoint = format!("quic/{}:{}#iface=lo", addrs[0], 13006) + let connect_endpoint: EndPoint = format!("quic/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); @@ -784,9 +818,10 @@ async fn openclose_quic_only_listen_with_interface_restriction() { zenoh_util::init_log_from_env_or("error"); let addrs = get_ipv4_ipaddrs(None); + let port = get_free_udp_port(); let (ca, cert, key) = get_tls_certs(); - let mut listen_endpoint: EndPoint = format!("quic/{}:{}#iface=lo", addrs[0], 13007) + let mut listen_endpoint: EndPoint = format!("quic/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); listen_endpoint @@ -802,7 +837,7 @@ async fn openclose_quic_only_listen_with_interface_restriction() { ) .unwrap(); - let connect_endpoint: EndPoint = format!("quic/{}:{}", addrs[0], 13007).parse().unwrap(); + let connect_endpoint: EndPoint = format!("quic/{}:{}", addrs[0], port).parse().unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, false).await; @@ -817,9 +852,10 @@ async fn openclose_tls_only_connect_with_interface_restriction() { zenoh_util::init_log_from_env_or("error"); let addrs = get_ipv4_ipaddrs(None); + let port = get_free_tcp_port(); let (ca, cert, key) = get_tls_certs(); - let mut listen_endpoint: EndPoint = format!("tls/{}:{}", addrs[0], 13008).parse().unwrap(); + let mut listen_endpoint: EndPoint = format!("tls/{}:{}", addrs[0], port).parse().unwrap(); listen_endpoint .config_mut() .extend_from_iter( @@ -833,7 +869,7 @@ async fn openclose_tls_only_connect_with_interface_restriction() { ) .unwrap(); - let connect_endpoint: EndPoint = format!("tls/{}:{}#iface=lo", addrs[0], 13008) + let connect_endpoint: EndPoint = format!("tls/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); @@ -850,9 +886,10 @@ async fn openclose_tls_only_listen_with_interface_restriction() { zenoh_util::init_log_from_env_or("error"); let addrs = get_ipv4_ipaddrs(None); + let port = get_free_tcp_port(); let (ca, cert, key) = get_tls_certs(); - let mut listen_endpoint: EndPoint = format!("tls/{}:{}#iface=lo", addrs[0], 13009) + let mut listen_endpoint: EndPoint = format!("tls/{}:{}#iface=lo", addrs[0], port) .parse() .unwrap(); listen_endpoint @@ -868,7 +905,7 @@ async fn openclose_tls_only_listen_with_interface_restriction() { ) .unwrap(); - let connect_endpoint: EndPoint = format!("tls/{}:{}", addrs[0], 13009).parse().unwrap(); + let connect_endpoint: EndPoint = format!("tls/{}:{}", addrs[0], port).parse().unwrap(); // should not connect to local interface and external address openclose_transport(&listen_endpoint, &connect_endpoint, false).await; diff --git a/io/zenoh-transport/tests/unicast_priorities.rs b/io/zenoh-transport/tests/unicast_priorities.rs index dcbb3d3272..404b353a03 100644 --- a/io/zenoh-transport/tests/unicast_priorities.rs +++ b/io/zenoh-transport/tests/unicast_priorities.rs @@ -32,6 +32,7 @@ use zenoh_protocol::{ }, }; use zenoh_result::ZResult; +use zenoh_test::get_free_tcp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, TransportPeerEventHandler, @@ -316,7 +317,9 @@ async fn run(endpoints: &[EndPoint]) { async fn priorities_tcp_only() { zenoh_util::init_log_from_env_or("error"); // Define the locators - let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", 10000).parse().unwrap()]; + let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap()]; // Run run(&endpoints).await; } @@ -340,7 +343,9 @@ async fn conduits_unixpipe_only() { async fn priorities_ws_only() { zenoh_util::init_log_from_env_or("error"); // Define the locators - let endpoints: Vec = vec![format!("ws/127.0.0.1:{}", 10010).parse().unwrap()]; + let endpoints: Vec = vec![format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap()]; // Run run(&endpoints).await; } diff --git a/io/zenoh-transport/tests/unicast_shm.rs b/io/zenoh-transport/tests/unicast_shm.rs index 1a1e7c75e0..0e636c765d 100644 --- a/io/zenoh-transport/tests/unicast_shm.rs +++ b/io/zenoh-transport/tests/unicast_shm.rs @@ -39,6 +39,7 @@ mod tests { }, ShmBufInner, }; + use zenoh_test::get_free_tcp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, TransportPeerEventHandler, @@ -333,7 +334,9 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn transport_tcp_shm() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 14002).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run(&endpoint, false).await; } @@ -341,7 +344,9 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn transport_tcp_shm_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 14001).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run(&endpoint, true).await; } @@ -349,7 +354,9 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn transport_ws_shm() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 14010).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run(&endpoint, false).await; } @@ -357,7 +364,9 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn transport_ws_shm_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 14011).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); run(&endpoint, true).await; } diff --git a/io/zenoh-transport/tests/unicast_simultaneous.rs b/io/zenoh-transport/tests/unicast_simultaneous.rs index 2bd4b302a5..ace2b352d1 100644 --- a/io/zenoh-transport/tests/unicast_simultaneous.rs +++ b/io/zenoh-transport/tests/unicast_simultaneous.rs @@ -30,6 +30,7 @@ mod tests { network::{push::ext::QoSType, NetworkMessage, NetworkMessageMut, Push}, }; use zenoh_result::ZResult; + use zenoh_test::get_free_tcp_port; use zenoh_transport::{ multicast::TransportMulticast, unicast::TransportUnicast, TransportEventHandler, TransportManager, TransportMulticastEventHandler, TransportPeer, TransportPeerEventHandler, @@ -287,18 +288,20 @@ mod tests { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn transport_tcp_simultaneous() { zenoh_util::init_log_from_env_or("error"); - let endpoint01: Vec = vec![ - format!("tcp/127.0.0.1:{}", 15000).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 15001).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 15002).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 15003).parse().unwrap(), - ]; - let endpoint02: Vec = vec![ - format!("tcp/127.0.0.1:{}", 15010).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 15011).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 15012).parse().unwrap(), - format!("tcp/127.0.0.1:{}", 15013).parse().unwrap(), - ]; + let endpoint01: Vec = (0..4) + .map(|_| { + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); + let endpoint02: Vec = (0..4) + .map(|_| { + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); transport_simultaneous(endpoint01, endpoint02).await; } @@ -330,18 +333,20 @@ mod tests { async fn transport_ws_simultaneous() { zenoh_util::init_log_from_env_or("error"); - let endpoint01: Vec = vec![ - format!("ws/127.0.0.1:{}", 15020).parse().unwrap(), - format!("ws/127.0.0.1:{}", 15021).parse().unwrap(), - format!("ws/127.0.0.1:{}", 15022).parse().unwrap(), - format!("ws/127.0.0.1:{}", 15023).parse().unwrap(), - ]; - let endpoint02: Vec = vec![ - format!("ws/127.0.0.1:{}", 15030).parse().unwrap(), - format!("ws/127.0.0.1:{}", 15031).parse().unwrap(), - format!("ws/127.0.0.1:{}", 15032).parse().unwrap(), - format!("ws/127.0.0.1:{}", 15033).parse().unwrap(), - ]; + let endpoint01: Vec = (0..4) + .map(|_| { + format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); + let endpoint02: Vec = (0..4) + .map(|_| { + format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap() + }) + .collect(); transport_simultaneous(endpoint01, endpoint02).await; } diff --git a/io/zenoh-transport/tests/unicast_time.rs b/io/zenoh-transport/tests/unicast_time.rs index e3196226a3..d357640ff8 100644 --- a/io/zenoh-transport/tests/unicast_time.rs +++ b/io/zenoh-transport/tests/unicast_time.rs @@ -21,6 +21,7 @@ use zenoh_core::ztimeout; use zenoh_link::EndPoint; use zenoh_protocol::core::{WhatAmI, ZenohIdProto}; use zenoh_result::ZResult; +use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::{test_helpers::make_transport_manager_builder, TransportUnicast}, @@ -228,7 +229,9 @@ async fn time_lowlatency_transport(endpoint: &EndPoint) { #[ignore] async fn time_tcp_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 13000).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); time_universal_transport(&endpoint).await; } @@ -237,7 +240,9 @@ async fn time_tcp_only() { #[ignore] async fn time_tcp_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", 13100).parse().unwrap(); + let endpoint: EndPoint = format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); time_lowlatency_transport(&endpoint).await; } @@ -246,7 +251,9 @@ async fn time_tcp_only_with_lowlatency_transport() { #[ignore] async fn time_udp_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("udp/127.0.0.1:{}", 13010).parse().unwrap(); + let endpoint: EndPoint = format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(); time_universal_transport(&endpoint).await; } @@ -255,7 +262,9 @@ async fn time_udp_only() { #[ignore] async fn time_udp_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("udp/127.0.0.1:{}", 13110).parse().unwrap(); + let endpoint: EndPoint = format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(); time_lowlatency_transport(&endpoint).await; } @@ -264,7 +273,9 @@ async fn time_udp_only_with_lowlatency_transport() { #[ignore] async fn time_ws_only() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 13020).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); time_universal_transport(&endpoint).await; } @@ -273,7 +284,9 @@ async fn time_ws_only() { #[ignore] async fn time_ws_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); - let endpoint: EndPoint = format!("ws/127.0.0.1:{}", 13120).parse().unwrap(); + let endpoint: EndPoint = format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(); time_lowlatency_transport(&endpoint).await; } @@ -391,7 +404,9 @@ Ck0v2xSPAiVjg6w65rUQeW6uB5m0T2wyj+wm0At8vzhZPlgS1fKhcmT2dzOq3+oN R+IdLiXcyIkg0m9N8I17p0ljCSkbrgGMD3bbePRTfg== -----END CERTIFICATE-----"; - let mut endpoint: EndPoint = format!("tls/localhost:{}", 13030).parse().unwrap(); + let mut endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( @@ -490,7 +505,9 @@ R+IdLiXcyIkg0m9N8I17p0ljCSkbrgGMD3bbePRTfg== -----END CERTIFICATE-----"; // Define the locator - let mut endpoint: EndPoint = format!("quic/localhost:{}", 13040).parse().unwrap(); + let mut endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( diff --git a/io/zenoh-transport/tests/unicast_transport.rs b/io/zenoh-transport/tests/unicast_transport.rs index 67ddc5e8ea..624099707e 100644 --- a/io/zenoh-transport/tests/unicast_transport.rs +++ b/io/zenoh-transport/tests/unicast_transport.rs @@ -30,6 +30,7 @@ use zenoh_protocol::{ network::{push::ext::QoSType, NetworkMessage, NetworkMessageMut, Push}, }; use zenoh_result::ZResult; +use zenoh_test::{get_free_tcp_port, get_free_udp_port}; use zenoh_transport::{ multicast::TransportMulticast, unicast::{test_helpers::make_transport_manager_builder, TransportUnicast}, @@ -618,8 +619,12 @@ async fn transport_unicast_tcp_only() { // Define the locators let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 16000).parse().unwrap(), - format!("tcp/[::1]:{}", 16001).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), ]; // Define the reliability and congestion control let channel = [ @@ -642,7 +647,9 @@ async fn transport_unicast_tcp_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); // Define the locators - let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", 16100).parse().unwrap()]; + let endpoints: Vec = vec![format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap()]; // Define the reliability and congestion control let channel = [ Channel { @@ -665,8 +672,12 @@ async fn transport_unicast_udp_only() { // Define the locator let endpoints: Vec = vec![ - format!("udp/127.0.0.1:{}", 16010).parse().unwrap(), - format!("udp/[::1]:{}", 16011).parse().unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), ]; // Define the reliability and congestion control let channel = [ @@ -688,7 +699,9 @@ async fn transport_unicast_udp_only() { async fn transport_unicast_udp_reliable() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let endpoint: EndPoint = format!("udp/localhost:{}?rel=1", 16105).parse().unwrap(); + let endpoint: EndPoint = format!("udp/localhost:{}?rel=1", get_free_udp_port()) + .parse() + .unwrap(); // Define the reliability and congestion control let channel = [ @@ -720,7 +733,9 @@ async fn transport_unicast_udp_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let endpoints: Vec = vec![format!("udp/127.0.0.1:{}", 16110).parse().unwrap()]; + let endpoints: Vec = vec![format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap()]; // Define the reliability and congestion control let channel = [ Channel { @@ -795,8 +810,10 @@ async fn transport_unicast_ws_only() { // Define the locators let endpoints: Vec = vec![ - format!("ws/127.0.0.1:{}", 16020).parse().unwrap(), - format!("ws/[::1]:{}", 16021).parse().unwrap(), + format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("ws/[::1]:{}", get_free_tcp_port()).parse().unwrap(), ]; // Define the reliability and congestion control let channel = [ @@ -827,7 +844,9 @@ async fn transport_unicast_ws_only_with_lowlatency_transport() { zenoh_util::init_log_from_env_or("error"); // Define the locators - let endpoints: Vec = vec![format!("ws/127.0.0.1:{}", 16120).parse().unwrap()]; + let endpoints: Vec = vec![format!("ws/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap()]; // Define the reliability and congestion control let channel = [ Channel { @@ -909,10 +928,18 @@ async fn transport_unicast_tcp_udp() { // Define the locator let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 16030).parse().unwrap(), - format!("udp/127.0.0.1:{}", 16031).parse().unwrap(), - format!("tcp/[::1]:{}", 16032).parse().unwrap(), - format!("udp/[::1]:{}", 16033).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), ]; // Define the reliability and congestion control let channel = [ @@ -942,8 +969,12 @@ async fn transport_unicast_tcp_unix() { let _ = std::fs::remove_file(f1); // Define the locator let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 16040).parse().unwrap(), - format!("tcp/[::1]:{}", 16041).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), format!("unixsock-stream/{f1}").parse().unwrap(), ]; // Define the reliability and congestion control @@ -976,8 +1007,12 @@ async fn transport_unicast_udp_unix() { let _ = std::fs::remove_file(f1); // Define the locator let endpoints: Vec = vec![ - format!("udp/127.0.0.1:{}", 16050).parse().unwrap(), - format!("udp/[::1]:{}", 16051).parse().unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), format!("unixsock-stream/{f1}").parse().unwrap(), ]; // Define the reliability and congestion control @@ -1011,10 +1046,18 @@ async fn transport_unicast_tcp_udp_unix() { let _ = std::fs::remove_file(f1); // Define the locator let endpoints: Vec = vec![ - format!("tcp/127.0.0.1:{}", 16060).parse().unwrap(), - format!("udp/127.0.0.1:{}", 16061).parse().unwrap(), - format!("tcp/[::1]:{}", 16062).parse().unwrap(), - format!("udp/[::1]:{}", 16063).parse().unwrap(), + format!("tcp/127.0.0.1:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/127.0.0.1:{}", get_free_udp_port()) + .parse() + .unwrap(), + format!("tcp/[::1]:{}", get_free_tcp_port()) + .parse() + .unwrap(), + format!("udp/[::1]:{}", get_free_udp_port()) + .parse() + .unwrap(), format!("unixsock-stream/{f1}").parse().unwrap(), ]; // Define the reliability and congestion control @@ -1042,7 +1085,9 @@ async fn transport_unicast_tls_only_server() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let mut endpoint: EndPoint = format!("tls/localhost:{}", 16070).parse().unwrap(); + let mut endpoint: EndPoint = format!("tls/localhost:{}", get_free_tcp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( @@ -1087,7 +1132,9 @@ async fn transport_unicast_quic_only_server() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let mut endpoint: EndPoint = format!("quic/localhost:{}", 16080).parse().unwrap(); + let mut endpoint: EndPoint = format!("quic/localhost:{}", get_free_udp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( @@ -1135,7 +1182,8 @@ async fn transport_unicast_tls_only_mutual_success() { let client_auth = "true"; // Define the locator - let mut client_endpoint: EndPoint = ("tls/localhost:10461").parse().unwrap(); + let port = get_free_tcp_port(); + let mut client_endpoint: EndPoint = format!("tls/localhost:{port}").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter( @@ -1151,7 +1199,7 @@ async fn transport_unicast_tls_only_mutual_success() { .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = ("tls/localhost:10461").parse().unwrap(); + let mut server_endpoint: EndPoint = format!("tls/localhost:{port}").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1206,14 +1254,15 @@ async fn transport_unicast_tls_only_mutual_no_client_certs_failure() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let mut client_endpoint: EndPoint = ("tls/localhost:10462").parse().unwrap(); + let port = get_free_tcp_port(); + let mut client_endpoint: EndPoint = format!("tls/localhost:{port}").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter([(TLS_ROOT_CA_CERTIFICATE_RAW, SERVER_CA)].iter().copied()) .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = ("tls/localhost:10462").parse().unwrap(); + let mut server_endpoint: EndPoint = format!("tls/localhost:{port}").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1272,7 +1321,8 @@ fn transport_unicast_tls_only_mutual_wrong_client_certs_failure() { let client_auth = "true"; // Define the locator - let mut client_endpoint: EndPoint = ("tls/localhost:10463").parse().unwrap(); + let port = get_free_tcp_port(); + let mut client_endpoint: EndPoint = format!("tls/localhost:{port}").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter( @@ -1292,7 +1342,7 @@ fn transport_unicast_tls_only_mutual_wrong_client_certs_failure() { .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = ("tls/localhost:10463").parse().unwrap(); + let mut server_endpoint: EndPoint = format!("tls/localhost:{port}").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1351,7 +1401,8 @@ async fn transport_unicast_quic_only_mutual_success() { let client_auth = "true"; // Define the locator - let mut client_endpoint: EndPoint = ("quic/localhost:10461").parse().unwrap(); + let port = get_free_udp_port(); + let mut client_endpoint: EndPoint = format!("quic/localhost:{port}").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter( @@ -1367,7 +1418,7 @@ async fn transport_unicast_quic_only_mutual_success() { .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = ("quic/localhost:10461").parse().unwrap(); + let mut server_endpoint: EndPoint = format!("quic/localhost:{port}").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1422,14 +1473,15 @@ async fn transport_unicast_quic_only_mutual_no_client_certs_failure() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let mut client_endpoint: EndPoint = ("quic/localhost:10462").parse().unwrap(); + let port = get_free_udp_port(); + let mut client_endpoint: EndPoint = format!("quic/localhost:{port}").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter([(TLS_ROOT_CA_CERTIFICATE_RAW, SERVER_CA)].iter().copied()) .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = ("quic/localhost:10462").parse().unwrap(); + let mut server_endpoint: EndPoint = format!("quic/localhost:{port}").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1488,7 +1540,8 @@ fn transport_unicast_quic_only_mutual_wrong_client_certs_failure() { let client_auth = "true"; // Define the locator - let mut client_endpoint: EndPoint = ("quic/localhost:10463").parse().unwrap(); + let port = get_free_udp_port(); + let mut client_endpoint: EndPoint = format!("quic/localhost:{port}").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter( @@ -1508,7 +1561,7 @@ fn transport_unicast_quic_only_mutual_wrong_client_certs_failure() { .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = ("quic/localhost:10463").parse().unwrap(); + let mut server_endpoint: EndPoint = format!("quic/localhost:{port}").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1620,7 +1673,8 @@ fn transport_unicast_quic_datagram_only_mutual_wrong_client_certs_failure() { let client_auth = "true"; // Define the locator - let mut client_endpoint: EndPoint = "quic/localhost:10464?rel=0".parse().unwrap(); + let port = get_free_udp_port(); + let mut client_endpoint: EndPoint = format!("quic/localhost:{port}?rel=0").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter( @@ -1640,7 +1694,7 @@ fn transport_unicast_quic_datagram_only_mutual_wrong_client_certs_failure() { .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = "quic/localhost:10464?rel=0".parse().unwrap(); + let mut server_endpoint: EndPoint = format!("quic/localhost:{port}?rel=0").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1691,14 +1745,15 @@ async fn transport_unicast_quic_datagram_only_mutual_no_client_certs_failure() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let mut client_endpoint: EndPoint = "quic/localhost:10465?rel=0".parse().unwrap(); + let port = get_free_udp_port(); + let mut client_endpoint: EndPoint = format!("quic/localhost:{port}?rel=0").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter([(TLS_ROOT_CA_CERTIFICATE_RAW, SERVER_CA)].iter().copied()) .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = "quic/localhost:10465?rel=0".parse().unwrap(); + let mut server_endpoint: EndPoint = format!("quic/localhost:{port}?rel=0").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1757,7 +1812,8 @@ async fn transport_unicast_quic_datagram_only_mutual_success() { let client_auth = "true"; // Define the locator - let mut client_endpoint: EndPoint = "quic/localhost:10466?rel=0".parse().unwrap(); + let port = get_free_udp_port(); + let mut client_endpoint: EndPoint = format!("quic/localhost:{port}?rel=0").parse().unwrap(); client_endpoint .config_mut() .extend_from_iter( @@ -1773,7 +1829,7 @@ async fn transport_unicast_quic_datagram_only_mutual_success() { .unwrap(); // Define the locator - let mut server_endpoint: EndPoint = "quic/localhost:10466?rel=0".parse().unwrap(); + let mut server_endpoint: EndPoint = format!("quic/localhost:{port}?rel=0").parse().unwrap(); server_endpoint .config_mut() .extend_from_iter( @@ -1817,7 +1873,9 @@ async fn transport_unicast_quic_datagram_only_server() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let mut endpoint: EndPoint = "quic/localhost:10467?rel=0".parse().unwrap(); + let mut endpoint: EndPoint = format!("quic/localhost:{}?rel=0", get_free_udp_port()) + .parse() + .unwrap(); endpoint .config_mut() .extend_from_iter( @@ -1992,7 +2050,7 @@ fn quic_endpoint(locator: &str) -> EndPoint { async fn transport_unicast_multistream_quic_default() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10468"); + let endpoint_quic = quic_endpoint(&format!("quic/localhost:{}", get_free_udp_port())); let endpoint = std::slice::from_ref(&endpoint_quic); let is_multistream = run_multistream_test(endpoint, endpoint, false).await; assert!( @@ -2006,7 +2064,10 @@ async fn transport_unicast_multistream_quic_default() { async fn transport_unicast_multistream_quic_enabled() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10469?multistream=1"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?multistream=1", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_multistream = run_multistream_test(endpoint, endpoint, false).await; assert!(is_multistream, "'?multistream=1' should enable multistream"); @@ -2017,7 +2078,10 @@ async fn transport_unicast_multistream_quic_enabled() { async fn transport_unicast_multistream_quic_disabled() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10470?multistream=0"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?multistream=0", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_mutlistream = run_multistream_test(endpoint, endpoint, false).await; assert!( @@ -2031,7 +2095,7 @@ async fn transport_unicast_multistream_quic_disabled() { async fn transport_unicast_multistream_quic_auto_explicit() { zenoh_util::init_log_from_env_or("error"); - let port = 10471; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[quic_endpoint(&format!( "quic/localhost:{port}?multistream=1" @@ -2045,7 +2109,7 @@ async fn transport_unicast_multistream_quic_auto_explicit() { "'?multistream=1' with auto listener should enable multistream" ); - let port = 10472; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[quic_endpoint(&format!( "quic/localhost:{port}?multistream=0" @@ -2059,7 +2123,7 @@ async fn transport_unicast_multistream_quic_auto_explicit() { "'?multistream=0' with auto listener should disable multistream" ); - let port = 10473; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[quic_endpoint(&format!("quic/localhost:{port}"))], &[quic_endpoint(&format!( @@ -2073,7 +2137,7 @@ async fn transport_unicast_multistream_quic_auto_explicit() { "'?multistream=1' with auto connect should enable multistream" ); - let port = 10474; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[quic_endpoint(&format!("quic/localhost:{port}"))], &[quic_endpoint(&format!( @@ -2093,7 +2157,10 @@ async fn transport_unicast_multistream_quic_auto_explicit() { async fn transport_unicast_multistream_quic_auto() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10475?multistream=auto"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?multistream=auto", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_multistream = run_multistream_test(endpoint, endpoint, false).await; assert!( @@ -2107,7 +2174,7 @@ async fn transport_unicast_multistream_quic_auto() { fn transport_unicast_multistream_quic_incompatible() { zenoh_util::init_log_from_env_or("error"); - let port = 10476; + let port = get_free_udp_port(); let result = std::panic::catch_unwind(|| { tokio::runtime::Runtime::new() .unwrap() @@ -2126,7 +2193,7 @@ fn transport_unicast_multistream_quic_incompatible() { "incompatible multistream config should fail to connect" ); - let port = 10477; + let port = get_free_udp_port(); let result = std::panic::catch_unwind(|| { tokio::runtime::Runtime::new() .unwrap() @@ -2151,7 +2218,10 @@ fn transport_unicast_multistream_quic_incompatible() { async fn transport_unicast_multistream_quic_lowlatency() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10478?multistream=1"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?multistream=1", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_multistream = run_multistream_test(endpoint, endpoint, true).await; assert!( @@ -2159,7 +2229,10 @@ async fn transport_unicast_multistream_quic_lowlatency() { "lowlatency should not support priority-based multistream" ); - let endpoint_quic = quic_endpoint("quic/localhost:10479?multistream=0"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?multistream=0", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_multistream = run_multistream_test(endpoint, endpoint, true).await; assert!( @@ -2173,7 +2246,11 @@ async fn transport_unicast_multistream_quic_lowlatency() { async fn transport_unicast_multistream_udp_enabled() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10480?rel=1;multistream=1".parse().unwrap()]; + let endpoint = [ + format!("udp/localhost:{}?rel=1;multistream=1", get_free_udp_port()) + .parse() + .unwrap(), + ]; let is_multistream = run_multistream_test(&endpoint, &endpoint, false).await; assert!(is_multistream, "'?multistream=1' should enable multistream"); } @@ -2183,7 +2260,11 @@ async fn transport_unicast_multistream_udp_enabled() { async fn transport_unicast_multistream_udp_disabled() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10481?rel=1;multistream=0".parse().unwrap()]; + let endpoint = [ + format!("udp/localhost:{}?rel=1;multistream=0", get_free_udp_port()) + .parse() + .unwrap(), + ]; let is_mutlistream = run_multistream_test(&endpoint, &endpoint, false).await; assert!( !is_mutlistream, @@ -2196,7 +2277,7 @@ async fn transport_unicast_multistream_udp_disabled() { async fn transport_unicast_multistream_udp_auto_explicit() { zenoh_util::init_log_from_env_or("error"); - let port = 10482; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[format!("udp/localhost:{port}?rel=1;multistream=1") .parse() @@ -2210,7 +2291,7 @@ async fn transport_unicast_multistream_udp_auto_explicit() { "'?multistream=1' with auto listener should enable multistream" ); - let port = 10483; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[format!("udp/localhost:{port}?rel=1;multistream=0") .parse() @@ -2224,7 +2305,7 @@ async fn transport_unicast_multistream_udp_auto_explicit() { "'?multistream=0' with auto listener should disable multistream" ); - let port = 10484; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[format!("udp/localhost:{port}?rel=1").parse().unwrap()], &[format!("udp/localhost:{port}?rel=1;multistream=1") @@ -2238,7 +2319,7 @@ async fn transport_unicast_multistream_udp_auto_explicit() { "'?multistream=1' with auto connect should enable multistream" ); - let port = 10485; + let port = get_free_udp_port(); let is_mutlistream = run_multistream_test( &[format!("udp/localhost:{port}?rel=1").parse().unwrap()], &[format!("udp/localhost:{port}?rel=1;multistream=0") @@ -2258,9 +2339,12 @@ async fn transport_unicast_multistream_udp_auto_explicit() { async fn transport_unicast_multistream_udp_auto() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10486?rel=1;multistream=auto" - .parse() - .unwrap()]; + let endpoint = [format!( + "udp/localhost:{}?rel=1;multistream=auto", + get_free_udp_port() + ) + .parse() + .unwrap()]; let is_multistream = run_multistream_test(&endpoint, &endpoint, false).await; assert!( is_multistream, @@ -2273,7 +2357,7 @@ async fn transport_unicast_multistream_udp_auto() { fn transport_unicast_multistream_udp_incompatible() { zenoh_util::init_log_from_env_or("error"); - let port = 10487; + let port = get_free_udp_port(); let result = std::panic::catch_unwind(|| { tokio::runtime::Runtime::new() .unwrap() @@ -2292,7 +2376,7 @@ fn transport_unicast_multistream_udp_incompatible() { "incompatible multistream config should fail to connect" ); - let port = 10488; + let port = get_free_udp_port(); let result = std::panic::catch_unwind(|| { tokio::runtime::Runtime::new() .unwrap() @@ -2317,14 +2401,22 @@ fn transport_unicast_multistream_udp_incompatible() { async fn transport_unicast_multistream_udp_lowlatency() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10489?rel=1;multistream=1".parse().unwrap()]; + let endpoint = [ + format!("udp/localhost:{}?rel=1;multistream=1", get_free_udp_port()) + .parse() + .unwrap(), + ]; let is_multistream = run_multistream_test(&endpoint, &endpoint, true).await; assert!( !is_multistream, "lowlatency should not support priority-based multistream" ); - let endpoint = ["udp/localhost:10490?rel=1;multistream=0".parse().unwrap()]; + let endpoint = [ + format!("udp/localhost:{}?rel=1;multistream=0", get_free_udp_port()) + .parse() + .unwrap(), + ]; let is_multistream = run_multistream_test(&endpoint, &endpoint, true).await; assert!( !is_multistream, @@ -2337,7 +2429,9 @@ async fn transport_unicast_multistream_udp_lowlatency() { async fn transport_unicast_multistream_udp_default() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10491?rel=1".parse().unwrap()]; + let endpoint = [format!("udp/localhost:{}?rel=1", get_free_udp_port()) + .parse() + .unwrap()]; let is_multistream = run_multistream_test(&endpoint, &endpoint, false).await; assert!( is_multistream, @@ -2350,7 +2444,10 @@ async fn transport_unicast_multistream_udp_default() { async fn transport_unicast_mixedrel_quic() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10500?mixed_rel=1"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=1", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_mixed_rel = run_mixed_reliability_test(endpoint, endpoint, false).await; assert!(is_mixed_rel, "mixed_rel=1 should enable mixed reliability"); @@ -2361,7 +2458,7 @@ async fn transport_unicast_mixedrel_quic() { async fn transport_unicast_mixedrel_quic_default() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10501"); + let endpoint_quic = quic_endpoint(&format!("quic/localhost:{}", get_free_udp_port())); let endpoint = std::slice::from_ref(&endpoint_quic); let is_mixed_rel = run_mixed_reliability_test(endpoint, endpoint, false).await; assert!(!is_mixed_rel, "default should disable mixed reliability"); @@ -2372,7 +2469,10 @@ async fn transport_unicast_mixedrel_quic_default() { async fn transport_unicast_mixedrel_quic_auto() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10502?mixed_rel=auto"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=auto", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_mixed_rel = run_mixed_reliability_test(endpoint, endpoint, false).await; assert!( @@ -2386,7 +2486,11 @@ async fn transport_unicast_mixedrel_quic_auto() { async fn transport_unicast_mixedrel_udp() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10505?rel=1;mixed_rel=1".parse().unwrap()]; + let endpoint = [ + format!("udp/localhost:{}?rel=1;mixed_rel=1", get_free_udp_port()) + .parse() + .unwrap(), + ]; let is_mixed_rel = run_mixed_reliability_test(&endpoint, &endpoint, false).await; assert!(is_mixed_rel, "mixed_rel=1 should enable mixed reliability"); } @@ -2396,7 +2500,9 @@ async fn transport_unicast_mixedrel_udp() { async fn transport_unicast_mixedrel_udp_default() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10506?rel=1".parse().unwrap()]; + let endpoint = [format!("udp/localhost:{}?rel=1", get_free_udp_port()) + .parse() + .unwrap()]; let is_mixed_rel = run_mixed_reliability_test(&endpoint, &endpoint, false).await; assert!(!is_mixed_rel, "default should disable mixed reliability"); } @@ -2406,7 +2512,11 @@ async fn transport_unicast_mixedrel_udp_default() { async fn transport_unicast_mixedrel_udp_auto() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10507?rel=1;mixed_rel=auto".parse().unwrap()]; + let endpoint = [ + format!("udp/localhost:{}?rel=1;mixed_rel=auto", get_free_udp_port()) + .parse() + .unwrap(), + ]; let is_mixed_rel = run_mixed_reliability_test(&endpoint, &endpoint, false).await; assert!( is_mixed_rel, @@ -2419,7 +2529,10 @@ async fn transport_unicast_mixedrel_udp_auto() { async fn transport_unicast_mixedrel_quic_multistream() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic = quic_endpoint("quic/localhost:10510?mixed_rel=1"); + let endpoint_quic = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=1", + get_free_udp_port() + )); let endpoint = std::slice::from_ref(&endpoint_quic); let is_multistream = run_multistream_test(endpoint, endpoint, false).await; assert!( @@ -2433,7 +2546,11 @@ async fn transport_unicast_mixedrel_quic_multistream() { async fn transport_unicast_mixedrel_udp_multistream() { zenoh_util::init_log_from_env_or("error"); - let endpoint = ["udp/localhost:10515?rel=1;mixed_rel=1".parse().unwrap()]; + let endpoint = [ + format!("udp/localhost:{}?rel=1;mixed_rel=1", get_free_udp_port()) + .parse() + .unwrap(), + ]; let is_multistream = run_multistream_test(&endpoint, &endpoint, false).await; assert!( is_multistream, @@ -2446,16 +2563,22 @@ async fn transport_unicast_mixedrel_udp_multistream() { async fn transport_unicast_mixedrel_quic_multilink() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic_mixed_rel = quic_endpoint("quic/localhost:10520?mixed_rel=1"); - let endpoint_quic = quic_endpoint("quic/localhost:10521"); + let endpoint_quic_mixed_rel = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=1", + get_free_udp_port() + )); + let endpoint_quic = quic_endpoint(&format!("quic/localhost:{}", get_free_udp_port())); let endpoints = [endpoint_quic, endpoint_quic_mixed_rel]; let (router_manager, client_manager, client_transport) = test_multilink_max_links(&endpoints, &endpoints, false, 2).await; close_transport(router_manager, client_manager, client_transport, &endpoints).await; - let endpoint_quic_mixed_rel = quic_endpoint("quic/localhost:10522?mixed_rel=1"); - let endpoint_quic = quic_endpoint("quic/localhost:10523"); + let endpoint_quic_mixed_rel = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=1", + get_free_udp_port() + )); + let endpoint_quic = quic_endpoint(&format!("quic/localhost:{}", get_free_udp_port())); let endpoints = [endpoint_quic_mixed_rel, endpoint_quic]; let (router_manager, client_manager, client_transport) = @@ -2468,16 +2591,24 @@ async fn transport_unicast_mixedrel_quic_multilink() { async fn transport_unicast_mixedrel_udp_multilink() { zenoh_util::init_log_from_env_or("error"); - let endpoint_mixed_rel = "udp/localhost:10525?rel=1;mixed_rel=1".parse().unwrap(); - let endpoint = "udp/localhost:10526?rel=1".parse().unwrap(); + let endpoint_mixed_rel = format!("udp/localhost:{}?rel=1;mixed_rel=1", get_free_udp_port()) + .parse() + .unwrap(); + let endpoint = format!("udp/localhost:{}?rel=1", get_free_udp_port()) + .parse() + .unwrap(); let endpoints = [endpoint, endpoint_mixed_rel]; let (router_manager, client_manager, client_transport) = test_multilink_max_links(&endpoints, &endpoints, false, 2).await; close_transport(router_manager, client_manager, client_transport, &endpoints).await; - let endpoint_mixed_rel = "udp/localhost:10527?rel=1;mixed_rel=1".parse().unwrap(); - let endpoint = "udp/localhost:10528?rel=1".parse().unwrap(); + let endpoint_mixed_rel = format!("udp/localhost:{}?rel=1;mixed_rel=1", get_free_udp_port()) + .parse() + .unwrap(); + let endpoint = format!("udp/localhost:{}?rel=1", get_free_udp_port()) + .parse() + .unwrap(); let endpoints = [endpoint_mixed_rel, endpoint]; let (router_manager, client_manager, client_transport) = @@ -2490,16 +2621,22 @@ async fn transport_unicast_mixedrel_udp_multilink() { async fn transport_unicast_mixedrel_quic_multilink_limit() { zenoh_util::init_log_from_env_or("error"); - let endpoint_quic_mixed_rel = quic_endpoint("quic/localhost:10530?mixed_rel=1"); - let endpoint_quic = quic_endpoint("quic/localhost:10531"); + let endpoint_quic_mixed_rel = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=1", + get_free_udp_port() + )); + let endpoint_quic = quic_endpoint(&format!("quic/localhost:{}", get_free_udp_port())); let endpoints = [endpoint_quic, endpoint_quic_mixed_rel]; let (router_manager, client_manager, client_transport) = test_multilink_max_links(&endpoints, &endpoints, false, 2).await; close_transport(router_manager, client_manager, client_transport, &endpoints).await; - let endpoint_quic_mixed_rel = quic_endpoint("quic/localhost:10532?mixed_rel=1"); - let endpoint_quic = quic_endpoint("quic/localhost:10533"); + let endpoint_quic_mixed_rel = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=1", + get_free_udp_port() + )); + let endpoint_quic = quic_endpoint(&format!("quic/localhost:{}", get_free_udp_port())); let endpoints = [endpoint_quic_mixed_rel, endpoint_quic]; let (router_manager, client_manager, client_transport) = @@ -2512,16 +2649,24 @@ async fn transport_unicast_mixedrel_quic_multilink_limit() { async fn transport_unicast_mixedrel_udp_multilink_limit() { zenoh_util::init_log_from_env_or("error"); - let endpoint_mixed_rel = "udp/localhost:10535?rel=1;mixed_rel=1".parse().unwrap(); - let endpoint = "udp/localhost:10536?rel=1".parse().unwrap(); + let endpoint_mixed_rel = format!("udp/localhost:{}?rel=1;mixed_rel=1", get_free_udp_port()) + .parse() + .unwrap(); + let endpoint = format!("udp/localhost:{}?rel=1", get_free_udp_port()) + .parse() + .unwrap(); let endpoints = [endpoint, endpoint_mixed_rel]; let (router_manager, client_manager, client_transport) = test_multilink_max_links(&endpoints, &endpoints, false, 2).await; close_transport(router_manager, client_manager, client_transport, &endpoints).await; - let endpoint_mixed_rel = "udp/localhost:10537?rel=1;mixed_rel=1".parse().unwrap(); - let endpoint = "udp/localhost:10538?rel=1".parse().unwrap(); + let endpoint_mixed_rel = format!("udp/localhost:{}?rel=1;mixed_rel=1", get_free_udp_port()) + .parse() + .unwrap(); + let endpoint = format!("udp/localhost:{}?rel=1", get_free_udp_port()) + .parse() + .unwrap(); let endpoints = [endpoint_mixed_rel, endpoint]; let (router_manager, client_manager, client_transport) = @@ -2534,7 +2679,10 @@ async fn transport_unicast_mixedrel_udp_multilink_limit() { async fn transport_unicast_quic_mixedrel() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let endpoint = quic_endpoint("quic/localhost:10540?mixed_rel=1"); + let endpoint = quic_endpoint(&format!( + "quic/localhost:{}?mixed_rel=1", + get_free_udp_port() + )); // Define the reliability and congestion control let channel = [ @@ -2565,7 +2713,9 @@ async fn transport_unicast_quic_mixedrel() { async fn transport_unicast_udp_mixedrel() { zenoh_util::init_log_from_env_or("error"); // Define the locator - let endpoint: EndPoint = "udp/localhost:10545?rel=1;mixed_rel=1".parse().unwrap(); + let endpoint: EndPoint = format!("udp/localhost:{}?rel=1;mixed_rel=1", get_free_udp_port()) + .parse() + .unwrap(); // Define the reliability and congestion control let channel = [ @@ -2596,7 +2746,7 @@ async fn transport_unicast_udp_mixedrel() { async fn transport_unicast_mixedrel_udp_auto_explicit() { zenoh_util::init_log_from_env_or("error"); - let port = 10550; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[format!("udp/localhost:{port}?rel=1;mixed_rel=1") .parse() @@ -2612,7 +2762,7 @@ async fn transport_unicast_mixedrel_udp_auto_explicit() { "'?mixed_rel=1' with auto listener should enable mixed reliability" ); - let port = 10551; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[format!("udp/localhost:{port}?rel=1;mixed_rel=0") .parse() @@ -2628,7 +2778,7 @@ async fn transport_unicast_mixedrel_udp_auto_explicit() { "'?mixed_rel=0' with auto listener should disable mixed reliability" ); - let port = 10552; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[format!("udp/localhost:{port}?rel=1;mixed_rel=auto") .parse() @@ -2644,7 +2794,7 @@ async fn transport_unicast_mixedrel_udp_auto_explicit() { "'?mixed_rel=1' with auto connect should enable mixed reliability" ); - let port = 10553; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[format!("udp/localhost:{port}?rel=1;mixed_rel=auto") .parse() @@ -2666,7 +2816,7 @@ async fn transport_unicast_mixedrel_udp_auto_explicit() { async fn transport_unicast_mixedrel_quic_auto_explicit() { zenoh_util::init_log_from_env_or("error"); - let port = 10555; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[quic_endpoint(&format!("quic/localhost:{port}?mixed_rel=1"))], &[quic_endpoint(&format!( @@ -2680,7 +2830,7 @@ async fn transport_unicast_mixedrel_quic_auto_explicit() { "'?mixed_rel=1' with auto listener should enable mixed reliability" ); - let port = 10556; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[quic_endpoint(&format!("quic/localhost:{port}?mixed_rel=0"))], &[quic_endpoint(&format!( @@ -2694,7 +2844,7 @@ async fn transport_unicast_mixedrel_quic_auto_explicit() { "'?mixed_rel=0' with auto listener should disable mixed reliability" ); - let port = 10557; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[quic_endpoint(&format!( "quic/localhost:{port}?mixed_rel=auto" @@ -2708,7 +2858,7 @@ async fn transport_unicast_mixedrel_quic_auto_explicit() { "'?mixed_rel=1' with auto connect should enable mixed reliability" ); - let port = 10558; + let port = get_free_udp_port(); let is_mixedrel = run_mixed_reliability_test( &[quic_endpoint(&format!( "quic/localhost:{port}?mixed_rel=auto" diff --git a/zenoh-ext/Cargo.toml b/zenoh-ext/Cargo.toml index 6e7ee5d737..5115bf6bf9 100644 --- a/zenoh-ext/Cargo.toml +++ b/zenoh-ext/Cargo.toml @@ -54,6 +54,7 @@ zenoh-util = { workspace = true } [dev-dependencies] rand = { workspace = true } zenoh-config = { workspace = true } +zenoh-test = { workspace = true, features = ["internal", "unstable"] } [package.metadata.docs.rs] features = ["unstable"] diff --git a/zenoh-ext/tests/advanced.rs b/zenoh-ext/tests/advanced.rs index 10fd5967ef..5f4629610b 100644 --- a/zenoh-ext/tests/advanced.rs +++ b/zenoh-ext/tests/advanced.rs @@ -36,25 +36,21 @@ async fn test_advanced_history_inner( sub_ke: &str, pub_namespace: Option, sub_namespace: Option, - endpoint: &str, ) { + let mut test_sessions = zenoh_test::TestSessions::new(); const SLEEP: Duration = Duration::from_secs(1); zenoh_util::init_log_from_env_or("error"); let peer1 = { - let mut c = zenoh::Config::default(); - c.listen - .endpoints - .set(vec![endpoint.parse::().unwrap()]) - .unwrap(); + let mut c = test_sessions.get_listener_config("tcp/127.0.0.1:0", 1); c.scouting.multicast.set_enabled(Some(false)).unwrap(); c.timestamping .set_enabled(Some(ModeDependentValue::Unique(true))) .unwrap(); c.namespace = pub_namespace; let _ = c.set_mode(Some(WhatAmI::Peer)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_listener_with_cfg(c).await; tracing::info!("Peer (1) ZID: {}", s.zid()); s }; @@ -71,15 +67,11 @@ async fn test_advanced_history_inner( tokio::time::sleep(SLEEP).await; let peer2 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![endpoint.parse::().unwrap()]) - .unwrap(); + let mut c = test_sessions.get_connector_config(); c.scouting.multicast.set_enabled(Some(false)).unwrap(); c.namespace = sub_namespace; let _ = c.set_mode(Some(WhatAmI::Peer)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Peer (2) ZID: {}", s.zid()); s }; @@ -114,26 +106,17 @@ async fn test_advanced_history_inner( publ.undeclare().await.unwrap(); // sub.undeclare().await.unwrap(); - peer1.close().await.unwrap(); - peer2.close().await.unwrap(); + test_sessions.close().await; } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_advanced_history() { - test_advanced_history_inner( - "test/advanced/history", - "test/advanced/history", - None, - None, - "tcp/localhost:27050", - ) - .await; + test_advanced_history_inner("test/advanced/history", "test/advanced/history", None, None).await; test_advanced_history_inner( "test/advanced/history", "ns/test/advanced/history", Some(nonwild_ke!("ns").into()), None, - "tcp/localhost:27051", ) .await; test_advanced_history_inner( @@ -141,7 +124,6 @@ async fn test_advanced_history() { "test/advanced/history", None, Some(nonwild_ke!("ns").into()), - "tcp/localhost:27052", ) .await; test_advanced_history_inner( @@ -149,7 +131,6 @@ async fn test_advanced_history() { "test/advanced/history", Some(nonwild_ke!("ns").into()), Some(nonwild_ke!("ns").into()), - "tcp/localhost:27053", ) .await; } @@ -159,8 +140,8 @@ async fn test_advanced_retransmission_inner( sub_ke: &str, pub_namespace: Option, sub_namespace: Option, - endpoint: &str, ) { + let endpoint = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); const SLEEP: Duration = Duration::from_secs(1); const RECONNECT_SLEEP: Duration = Duration::from_secs(5); @@ -289,7 +270,6 @@ async fn test_advanced_retransmission() { "test/advanced/retransmission", None, None, - "tcp/localhost:27054", ) .await; test_advanced_retransmission_inner( @@ -297,7 +277,6 @@ async fn test_advanced_retransmission() { "ns/test/advanced/retransmission", Some(nonwild_ke!("ns").into()), None, - "tcp/localhost:27055", ) .await; test_advanced_retransmission_inner( @@ -305,7 +284,6 @@ async fn test_advanced_retransmission() { "test/advanced/retransmission", None, Some(nonwild_ke!("ns").into()), - "tcp/localhost:27056", ) .await; test_advanced_retransmission_inner( @@ -313,7 +291,6 @@ async fn test_advanced_retransmission() { "test/advanced/retransmission", Some(nonwild_ke!("ns").into()), Some(nonwild_ke!("ns").into()), - "tcp/localhost:27057", ) .await; } @@ -323,8 +300,8 @@ async fn test_advanced_retransmission_periodic_inner( sub_ke: &str, pub_namespace: Option, sub_namespace: Option, - endpoint: &str, ) { + let endpoint = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); const SLEEP: Duration = Duration::from_secs(1); const RECONNECT_SLEEP: Duration = Duration::from_secs(8); @@ -446,7 +423,6 @@ async fn test_advanced_retransmission_periodic() { "test/advanced/retransmission/periodic", None, None, - "tcp/localhost:27058", ) .await; test_advanced_retransmission_periodic_inner( @@ -454,7 +430,6 @@ async fn test_advanced_retransmission_periodic() { "ns/test/advanced/retransmission/periodic", Some(nonwild_ke!("ns").into()), None, - "tcp/localhost:27059", ) .await; test_advanced_retransmission_periodic_inner( @@ -462,7 +437,6 @@ async fn test_advanced_retransmission_periodic() { "test/advanced/retransmission/periodic", None, Some(nonwild_ke!("ns").into()), - "tcp/localhost:27060", ) .await; test_advanced_retransmission_periodic_inner( @@ -470,7 +444,6 @@ async fn test_advanced_retransmission_periodic() { "test/advanced/retransmission/periodic", Some(nonwild_ke!("ns").into()), Some(nonwild_ke!("ns").into()), - "tcp/localhost:27061", ) .await; } @@ -480,8 +453,8 @@ async fn test_advanced_sample_miss_inner( sub_ke: &str, pub_namespace: Option, sub_namespace: Option, - endpoint: &str, ) { + let endpoint = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); const SLEEP: Duration = Duration::from_secs(1); const RECONNECT_SLEEP: Duration = Duration::from_secs(5); @@ -599,7 +572,6 @@ async fn test_advanced_sample_miss() { "test/advanced/sample_miss", None, None, - "tcp/localhost:27062", ) .await; test_advanced_sample_miss_inner( @@ -607,7 +579,6 @@ async fn test_advanced_sample_miss() { "ns/test/advanced/sample_miss", Some(nonwild_ke!("ns").into()), None, - "tcp/localhost:27063", ) .await; test_advanced_sample_miss_inner( @@ -615,7 +586,6 @@ async fn test_advanced_sample_miss() { "test/advanced/sample_miss", None, Some(nonwild_ke!("ns").into()), - "tcp/localhost:27064", ) .await; test_advanced_sample_miss_inner( @@ -623,7 +593,6 @@ async fn test_advanced_sample_miss() { "test/advanced/sample_miss", Some(nonwild_ke!("ns").into()), Some(nonwild_ke!("ns").into()), - "tcp/localhost:27065", ) .await; } @@ -633,8 +602,8 @@ async fn test_advanced_retransmission_sample_miss_inner( sub_ke: &str, pub_namespace: Option, sub_namespace: Option, - endpoint: &str, ) { + let endpoint = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); const SLEEP: Duration = Duration::from_secs(1); const RECONNECT_SLEEP: Duration = Duration::from_secs(5); @@ -762,7 +731,6 @@ async fn test_advanced_retransmission_sample_miss() { "test/advanced/retransmission/sample_miss", None, None, - "tcp/localhost:27066", ) .await; test_advanced_retransmission_sample_miss_inner( @@ -770,7 +738,6 @@ async fn test_advanced_retransmission_sample_miss() { "ns/test/advanced/retransmission/sample_miss", Some(nonwild_ke!("ns").into()), None, - "tcp/localhost:27067", ) .await; test_advanced_retransmission_sample_miss_inner( @@ -778,7 +745,6 @@ async fn test_advanced_retransmission_sample_miss() { "test/advanced/retransmission/sample_miss", None, Some(nonwild_ke!("ns").into()), - "tcp/localhost:27068", ) .await; test_advanced_retransmission_sample_miss_inner( @@ -786,7 +752,6 @@ async fn test_advanced_retransmission_sample_miss() { "test/advanced/retransmission/sample_miss", Some(nonwild_ke!("ns").into()), Some(nonwild_ke!("ns").into()), - "tcp/localhost:27069", ) .await; } @@ -796,8 +761,8 @@ async fn test_advanced_late_joiner_inner( sub_ke: &str, pub_namespace: Option, sub_namespace: Option, - endpoint: &str, ) { + let endpoint = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); const SLEEP: Duration = Duration::from_secs(1); const RECONNECT_SLEEP: Duration = Duration::from_secs(8); @@ -903,7 +868,6 @@ async fn test_advanced_late_joiner() { "test/advanced/late_joiner", None, None, - "tcp/localhost:27070", ) .await; test_advanced_late_joiner_inner( @@ -911,7 +875,6 @@ async fn test_advanced_late_joiner() { "ns/test/advanced/late_joiner", Some(nonwild_ke!("ns").into()), None, - "tcp/localhost:27071", ) .await; test_advanced_late_joiner_inner( @@ -919,7 +882,6 @@ async fn test_advanced_late_joiner() { "test/advanced/late_joiner", None, Some(nonwild_ke!("ns").into()), - "tcp/localhost:27072", ) .await; test_advanced_late_joiner_inner( @@ -927,7 +889,6 @@ async fn test_advanced_late_joiner() { "test/advanced/late_joiner", Some(nonwild_ke!("ns").into()), Some(nonwild_ke!("ns").into()), - "tcp/localhost:27073", ) .await; } @@ -937,8 +898,8 @@ async fn test_advanced_retransmission_heartbeat_inner( sub_ke: &str, pub_namespace: Option, sub_namespace: Option, - endpoint: &str, ) { + let endpoint = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); const SLEEP: Duration = Duration::from_secs(1); const RECONNECT_SLEEP: Duration = Duration::from_secs(5); const HEARTBEAT_PERIOD: Duration = Duration::from_secs(4); @@ -1061,7 +1022,6 @@ async fn test_advanced_retransmission_heartbeat() { "test/advanced/retransmission/heartbeat", None, None, - "tcp/localhost:27074", ) .await; test_advanced_retransmission_heartbeat_inner( @@ -1069,7 +1029,6 @@ async fn test_advanced_retransmission_heartbeat() { "ns/test/advanced/retransmission/heartbeat", Some(nonwild_ke!("ns").into()), None, - "tcp/localhost:27075", ) .await; test_advanced_retransmission_heartbeat_inner( @@ -1077,7 +1036,6 @@ async fn test_advanced_retransmission_heartbeat() { "test/advanced/retransmission/heartbeat", None, Some(nonwild_ke!("ns").into()), - "tcp/localhost:27076", ) .await; test_advanced_retransmission_heartbeat_inner( @@ -1085,7 +1043,6 @@ async fn test_advanced_retransmission_heartbeat() { "test/advanced/retransmission/heartbeat", Some(nonwild_ke!("ns").into()), Some(nonwild_ke!("ns").into()), - "tcp/localhost:27077", ) .await; } @@ -1113,7 +1070,9 @@ async fn advanced_subscriber_does_not_prevent_session_to_be_closed_when_dropped( assert!(ztimeout!(subscriber.recv_async()).is_err()); } -async fn create_peer_pair(locator: &str) -> (Session, Session) { +async fn create_peer_pair() -> (Session, Session) { + let locator = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); + let locator = locator.as_str(); let peer1 = { let mut c = zenoh::Config::default(); c.listen @@ -1207,7 +1166,7 @@ fn create_callback() -> (impl Fn(T) + Send + Sync + 'static, Arc async fn test_callback_drop_on_undeclare_advanced_subscriber() { zenoh::init_log_from_env_or("error"); let ke = "test/undeclare/advanced_subscriber_callback_drop"; - let (session1, session2) = ztimeout!(create_peer_pair("tcp/127.0.0.1:27100")); + let (session1, session2) = ztimeout!(create_peer_pair()); let (cb, n) = create_callback::(); let subscriber = ztimeout!(session1.declare_subscriber(ke).advanced().callback(cb)).unwrap(); @@ -1280,7 +1239,8 @@ async fn test_callback_drop_on_undeclare_advanced_subscriber_local() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_callback_drop_on_undeclare_advanced_sample_miss_listener() { let ke = "test/undeclare/advanced_subscriber_sample_miss_listener_callback_drop"; - let locator = "tcp/127.0.0.1:27101"; + let locator = format!("tcp/127.0.0.1:{}", zenoh_test::get_free_tcp_port()); + let locator = locator.as_str(); const SLEEP: Duration = Duration::from_secs(1); const RECONNECT_SLEEP: Duration = Duration::from_secs(5); diff --git a/zenoh-ext/tests/liveliness.rs b/zenoh-ext/tests/liveliness.rs index cd5a776f55..56091a2757 100644 --- a/zenoh-ext/tests/liveliness.rs +++ b/zenoh-ext/tests/liveliness.rs @@ -12,11 +12,7 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -use zenoh::{ - config::{EndPoint, WhatAmI}, - sample::SampleKind, - Wait, -}; +use zenoh::{config::WhatAmI, sample::SampleKind, Wait}; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] #[allow(deprecated)] @@ -28,7 +24,7 @@ async fn test_liveliness_querying_subscriber_clique() { const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); - const PEER1_ENDPOINT: &str = "udp/localhost:47447"; + let mut test_sessions = zenoh_test::TestSessions::new(); const LIVELINESS_KEYEXPR_1: &str = "test/liveliness/querying-subscriber/brokered/1"; const LIVELINESS_KEYEXPR_2: &str = "test/liveliness/querying-subscriber/brokered/2"; @@ -37,27 +33,17 @@ async fn test_liveliness_querying_subscriber_clique() { zenoh_util::init_log_from_env_or("error"); let peer1 = { - let mut c = zenoh::Config::default(); - c.listen - .endpoints - .set(vec![PEER1_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_listener_config("udp/127.0.0.1:0", 1); let _ = c.set_mode(Some(WhatAmI::Peer)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_listener_with_cfg(c).await; tracing::info!("Peer (1) ZID: {}", s.zid()); s }; let peer2 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![PEER1_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Peer)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Peer (2) ZID: {}", s.zid()); s }; @@ -93,8 +79,7 @@ async fn test_liveliness_querying_subscriber_clique() { token2.undeclare().await.unwrap(); sub.undeclare().await.unwrap(); - peer1.close().await.unwrap(); - peer2.close().await.unwrap(); + test_sessions.close().await; } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -107,7 +92,7 @@ async fn test_liveliness_querying_subscriber_brokered() { const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); - const ROUTER_ENDPOINT: &str = "tcp/localhost:27449"; + let mut test_sessions = zenoh_test::TestSessions::new(); const LIVELINESS_KEYEXPR_1: &str = "test/liveliness/querying-subscriber/brokered/1"; const LIVELINESS_KEYEXPR_2: &str = "test/liveliness/querying-subscriber/brokered/2"; @@ -115,54 +100,34 @@ async fn test_liveliness_querying_subscriber_brokered() { zenoh_util::init_log_from_env_or("error"); - let router = { - let mut c = zenoh::Config::default(); - c.listen - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let _router = { + let mut c = test_sessions.get_listener_config("tcp/127.0.0.1:0", 1); let _ = c.set_mode(Some(WhatAmI::Router)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_listener_with_cfg(c).await; tracing::info!("Router ZID: {}", s.zid()); s }; let client1 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Client)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Client (1) ZID: {}", s.zid()); s }; let client2 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Client)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Client (2) ZID: {}", s.zid()); s }; let client3 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Client)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Client (3) ZID: {}", s.zid()); s }; @@ -198,10 +163,7 @@ async fn test_liveliness_querying_subscriber_brokered() { token2.undeclare().await.unwrap(); sub.undeclare().await.unwrap(); - router.close().await.unwrap(); - client1.close().await.unwrap(); - client2.close().await.unwrap(); - client3.close().await.unwrap(); + test_sessions.close().await; } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -214,7 +176,7 @@ async fn test_liveliness_fetching_subscriber_clique() { const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); - const PEER1_ENDPOINT: &str = "udp/localhost:47449"; + let mut test_sessions = zenoh_test::TestSessions::new(); const LIVELINESS_KEYEXPR_1: &str = "test/liveliness/querying-subscriber/brokered/1"; const LIVELINESS_KEYEXPR_2: &str = "test/liveliness/querying-subscriber/brokered/2"; @@ -223,27 +185,17 @@ async fn test_liveliness_fetching_subscriber_clique() { zenoh_util::init_log_from_env_or("error"); let peer1 = { - let mut c = zenoh::Config::default(); - c.listen - .endpoints - .set(vec![PEER1_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_listener_config("udp/127.0.0.1:0", 1); let _ = c.set_mode(Some(WhatAmI::Peer)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_listener_with_cfg(c).await; tracing::info!("Peer (1) ZID: {}", s.zid()); s }; let peer2 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![PEER1_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Peer)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Peer (2) ZID: {}", s.zid()); s }; @@ -283,8 +235,7 @@ async fn test_liveliness_fetching_subscriber_clique() { token2.undeclare().await.unwrap(); sub.undeclare().await.unwrap(); - peer1.close().await.unwrap(); - peer2.close().await.unwrap(); + test_sessions.close().await; } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -297,7 +248,7 @@ async fn test_liveliness_fetching_subscriber_brokered() { const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); - const ROUTER_ENDPOINT: &str = "tcp/localhost:47450"; + let mut test_sessions = zenoh_test::TestSessions::new(); const LIVELINESS_KEYEXPR_1: &str = "test/liveliness/querying-subscriber/brokered/1"; const LIVELINESS_KEYEXPR_2: &str = "test/liveliness/querying-subscriber/brokered/2"; @@ -305,54 +256,34 @@ async fn test_liveliness_fetching_subscriber_brokered() { zenoh_util::init_log_from_env_or("error"); - let router = { - let mut c = zenoh::Config::default(); - c.listen - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let _router = { + let mut c = test_sessions.get_listener_config("tcp/127.0.0.1:0", 1); let _ = c.set_mode(Some(WhatAmI::Router)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_listener_with_cfg(c).await; tracing::info!("Router ZID: {}", s.zid()); s }; let client1 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Client)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Client (1) ZID: {}", s.zid()); s }; let client2 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Client)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Client (2) ZID: {}", s.zid()); s }; let client3 = { - let mut c = zenoh::Config::default(); - c.connect - .endpoints - .set(vec![ROUTER_ENDPOINT.parse::().unwrap()]) - .unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); + let mut c = test_sessions.get_connector_config(); let _ = c.set_mode(Some(WhatAmI::Client)); - let s = ztimeout!(zenoh::open(c)).unwrap(); + let s = test_sessions.open_connector_with_cfg(c).await; tracing::info!("Client (3) ZID: {}", s.zid()); s }; @@ -392,8 +323,5 @@ async fn test_liveliness_fetching_subscriber_brokered() { token2.undeclare().await.unwrap(); sub.undeclare().await.unwrap(); - router.close().await.unwrap(); - client1.close().await.unwrap(); - client2.close().await.unwrap(); - client3.close().await.unwrap(); + test_sessions.close().await; } diff --git a/zenoh/Cargo.toml b/zenoh/Cargo.toml index 6593f7ee63..c25de5e59b 100644 --- a/zenoh/Cargo.toml +++ b/zenoh/Cargo.toml @@ -139,6 +139,7 @@ tracing-capture = { workspace = true } tracing-subscriber = { workspace = true } tracing-tunnel = { workspace = true } zenoh-protocol = { workspace = true, features = ["test"] } +zenoh-test = { workspace = true, features = ["internal", "unstable"] } [build-dependencies] rustc_version = { workspace = true } diff --git a/zenoh/src/tests/interceptor_cache.rs b/zenoh/src/tests/interceptor_cache.rs index 4667055660..3e94dd372e 100644 --- a/zenoh/src/tests/interceptor_cache.rs +++ b/zenoh/src/tests/interceptor_cache.rs @@ -112,33 +112,59 @@ use std::{any::Any, time::Duration}; use zenoh_config::{Config, InterceptorFlow, ZenohId}; use zenoh_core::ztimeout; -use crate::{config::WhatAmI, init_log_from_env_or, open}; +use crate::{config::WhatAmI, init_log_from_env_or, open, Session}; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); -async fn get_basic_router_config(port: u16) -> Config { +fn get_basic_router_config() -> Config { let mut config = Config::default(); config.set_mode(Some(WhatAmI::Router)).unwrap(); config .listen .endpoints - .set(vec![format!("tcp/127.0.0.1:{port}").parse().unwrap()]) + .set(vec!["tcp/127.0.0.1:0".parse().unwrap()]) .unwrap(); config.scouting.multicast.set_enabled(Some(false)).unwrap(); config } -async fn get_basic_client_config(port: u16) -> Config { +fn get_basic_client_config(endpoint: zenoh_link::EndPoint) -> Config { let mut config = Config::default(); config.set_mode(Some(WhatAmI::Client)).unwrap(); + config.connect.endpoints.set(vec![endpoint]).unwrap(); + config.scouting.multicast.set_enabled(Some(false)).unwrap(); config - .connect +} + +// Note that we can't use the API in zenoh-test, because the Session type is different. +// It's `zenoh::api::Session` inside zenoh-test, while it's `crate::Session` inside zenoh. +async fn get_tcp_locator(session: &Session) -> zenoh_link::EndPoint { + session + .info() + .locators() + .await + .into_iter() + .map(|l| l.to_endpoint()) + .find(|ep| ep.to_string().starts_with("tcp/")) + .expect("Expected a TCP listener endpoint from session") +} + +async fn open_router_and_client_configs(router_id: ZenohId) -> (Config, Session, Config, Config) { + let mut config_router = get_basic_router_config(); + config_router.set_id(Some(router_id)).unwrap(); + + let router = ztimeout!(open(config_router.clone())).unwrap(); + let router_endpoint = get_tcp_locator(&router).await; + config_router + .listen .endpoints - .set(vec![format!("tcp/127.0.0.1:{port}").parse().unwrap()]) + .set(vec![router_endpoint.clone()]) .unwrap(); - config.scouting.multicast.set_enabled(Some(false)).unwrap(); - config + let config_client1 = get_basic_client_config(router_endpoint.clone()); + let config_client2 = get_basic_client_config(router_endpoint); + + (config_router, router, config_client1, config_client2) } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] @@ -155,13 +181,9 @@ async fn test_interceptors_cache_update_ingress() { .insert(router_id, Box::new(f)); init_log_from_env_or("error"); - let mut config_router = get_basic_router_config(27701).await; - config_router.set_id(Some(router_id)).unwrap(); - - let config_client1 = get_basic_client_config(27701).await; - let config_client2 = get_basic_client_config(27701).await; + let (config_router, router, config_client1, config_client2) = + open_router_and_client_configs(router_id).await; - let router = ztimeout!(open(config_router.clone())).unwrap(); tokio::time::sleep(SLEEP).await; let session1 = ztimeout!(open(config_client1)).unwrap(); let session2 = ztimeout!(open(config_client2)).unwrap(); @@ -245,13 +267,8 @@ async fn test_interceptors_cache_update_egress() { .insert(router_id, Box::new(f)); init_log_from_env_or("error"); - let mut config_router = get_basic_router_config(27702).await; - config_router.set_id(Some(router_id)).unwrap(); - - let config_client1 = get_basic_client_config(27702).await; - let config_client2 = get_basic_client_config(27702).await; - - let router = ztimeout!(open(config_router.clone())).unwrap(); + let (config_router, router, config_client1, config_client2) = + open_router_and_client_configs(router_id).await; tokio::time::sleep(SLEEP).await; let session1 = ztimeout!(open(config_client1)).unwrap(); let session2 = ztimeout!(open(config_client2)).unwrap(); @@ -335,13 +352,8 @@ async fn test_interceptors_cache_update_egress_then_ingress() { .insert(router_id, Box::new(f)); init_log_from_env_or("error"); - let mut config_router = get_basic_router_config(27703).await; - config_router.set_id(Some(router_id)).unwrap(); - - let config_client1 = get_basic_client_config(27703).await; - let config_client2 = get_basic_client_config(27703).await; - - let router = ztimeout!(open(config_router.clone())).unwrap(); + let (config_router, router, config_client1, config_client2) = + open_router_and_client_configs(router_id).await; tokio::time::sleep(SLEEP).await; let session1 = ztimeout!(open(config_client1)).unwrap(); let session2 = ztimeout!(open(config_client2)).unwrap(); diff --git a/zenoh/src/tests/link_weights.rs b/zenoh/src/tests/link_weights.rs index ec66795114..9814bcf835 100644 --- a/zenoh/src/tests/link_weights.rs +++ b/zenoh/src/tests/link_weights.rs @@ -121,6 +121,7 @@ use std::time::Duration; use zenoh_config::ZenohId; use zenoh_core::ztimeout; +use zenoh_test::get_free_tcp_port; use crate::{config::WhatAmI, init_log_from_env_or, open, Config}; @@ -225,7 +226,7 @@ async fn create_net( net: Vec<(u16, Vec<(u16, Option)>)>, source: u16, dest: u16, - port_offset: u16, + _port_offset: u16, ) -> Net { let start_id = ZenohId::from_str("a").unwrap(); let end_id = ZenohId::from_str("b").unwrap(); @@ -247,15 +248,30 @@ async fn create_net( } } let mut routers = Vec::new(); + let mut router_ports = HashMap::new(); + + for (id, _) in &net { + let mut port = get_free_tcp_port(); + while router_ports.values().any(|p| *p == port) { + port = get_free_tcp_port(); + } + router_ports.insert(*id, port); + } for v in &net { let zid = ZenohId::from_str(&v.0.to_string()).unwrap(); let connect = v.1.iter() - .map(|(id, _)| id + port_offset) + .map(|(id, _)| { + *router_ports + .get(id) + .unwrap_or_else(|| panic!("Missing port for router {id}")) + }) .collect::>(); - let mut config = - get_basic_router_config(&[port_offset + v.0], &connect, WhatAmI::Router).await; + let listen_port = *router_ports + .get(&v.0) + .unwrap_or_else(|| panic!("Missing port for router {}", v.0)); + let mut config = get_basic_router_config(&[listen_port], &connect, WhatAmI::Router).await; config.set_id(Some(zid)).unwrap(); let weights = v.1.iter() @@ -277,9 +293,19 @@ async fn create_net( routers.push(router); } - let mut config_client_a = get_basic_client_config(source + port_offset).await; + let mut config_client_a = get_basic_client_config( + *router_ports + .get(&source) + .unwrap_or_else(|| panic!("Missing port for source router {source}")), + ) + .await; config_client_a.set_id(Some(start_id)).unwrap(); - let mut config_client_b = get_basic_client_config(dest + port_offset).await; + let mut config_client_b = get_basic_client_config( + *router_ports + .get(&dest) + .unwrap_or_else(|| panic!("Missing port for destination router {dest}")), + ) + .await; config_client_b.set_id(Some(end_id)).unwrap(); let session_a = ztimeout!(open(config_client_a)).unwrap(); diff --git a/zenoh/src/tests/session.rs b/zenoh/src/tests/session.rs index fbc9f9164a..6e72b36b62 100644 --- a/zenoh/src/tests/session.rs +++ b/zenoh/src/tests/session.rs @@ -16,6 +16,7 @@ mod runtime_state_weak_tests { use test_case::test_matrix; use zenoh_config::{ModeDependentValue, WhatAmI, WhatAmIMatcher}; use zenoh_link::EndPoint; + use zenoh_test::get_free_tcp_port; use crate::{ api::{config::Config, session::open}, @@ -142,8 +143,7 @@ mod runtime_state_weak_tests { // Helper to create a client and a peer that are connected. async fn create_clique(num: usize, mode: WhatAmI, gossip: bool) -> Vec { - let port_offset = calc_offset(mode, gossip); - let port = 12450 + port_offset; + let port = get_free_tcp_port(); let peer_endpoint = format!("tcp/127.0.0.1:{}", port); let main = create_session(mode, vec![peer_endpoint.parse().unwrap()], vec![], gossip).await; @@ -158,21 +158,6 @@ mod runtime_state_weak_tests { result } - fn calc_offset(mode: WhatAmI, gossip: bool) -> u16 { - let mode = match mode { - WhatAmI::Router => 0, - WhatAmI::Peer => 1, - WhatAmI::Client => 2, - }; - - let gossip = match gossip { - true => 0, - false => 1, - }; - - mode + gossip * 3 - } - #[test_matrix( [WhatAmI::Peer], [true, false] diff --git a/zenoh/tests/README.md b/zenoh/tests/README.md deleted file mode 100644 index cf4cf4b3f0..0000000000 --- a/zenoh/tests/README.md +++ /dev/null @@ -1,127 +0,0 @@ -# Zenoh Test Framework - -When testing the Zenoh protocol, we often need to establish a specific network topology. Typically, this involves creating a listener and multiple connectors to verify various functionalities. - -## Why Dynamic Ports? - -Historically, Zenoh tests used fixed TCP ports to facilitate connections. However, this approach presented several challenges: - -1. **Parallel Execution Collisions**: Running multiple tests simultaneously often led to port conflicts. -2. **System Conflicts**: Hardcoded ports might conflict with other services running on the host system. -3. **Maintenance Overhead**: Managing hardcoded ports across a growing test suite became increasingly difficult as they were scattered throughout the codebase. - -### The Dynamic Approach - -To resolve these issues, the test framework now utilizes dynamic port assignment. By binding to `port 0` (e.g., `tcp/127.0.0.1:0`), the operating system assigns an available random port. Once the listener is started, the assigned port is retrieved from the Zenoh session and passed to the connectors. - -## The `TestSessions` Utility - -To avoid repeating the boilerplate of dynamic port discovery and session management, we provide a `TestSessions` utility located in `zenoh/tests/common/mod.rs`. This utility: - -* Automatically manages connections between listeners and connectors. -* Tracks all sessions created during a test. -* Provides a simple way to close all sessions at once. - -## Usage Examples - -Here are the most common patterns for using the test framework: - -### 1. Simple Peer-to-Peer - -Use `open_pairs()` to quickly create a listener and a connector that is already connected to it. -*Reference test case: `zenoh_session_unicast` in `session.rs`* - -```rust -// Initialize the test context -let mut test_context = TestSessions::new(); - -// Open a pair of sessions: peer01 (listener) and peer02 (connector) -let (peer01, peer02) = test_context.open_pairs().await; - -// Perform test actions... - -// Clean up all sessions -test_context.close().await; -``` - -### 2. One Listener, Multiple Connectors - -Open a listener followed by multiple connectors. The connectors will automatically connect to the last opened listener by default. -*Reference test case: `test_link_events` in `connectivity.rs`* - -```rust -let mut test_context = TestSessions::new(); - -// Open a listener with default configuration -let session1 = test_context.open_listener().await; - -// Open multiple connectors (connected to session1) -let session2 = test_context.open_connector().await; -let session3 = test_context.open_connector().await; - -test_context.close().await; -``` - -### 3. Custom Configurations - -You can retrieve default configurations for listeners or connectors and modify them before opening the sessions. -*Reference test case: `zenoh_unicity_brokered` in `unicity.rs`* - -```rust -let mut test_context = TestSessions::new(); - -// Create a listener with a customized configuration -let mut config = test_context.get_listener_config("tcp/127.0.0.1:0", 1); -config.set_mode(Some(WhatAmI::Router)).unwrap(); -let router = test_context.open_listener_with_cfg(config).await; - -// Create connectors with custom modes -let mut config = test_context.get_connector_config(); -config.set_mode(Some(WhatAmI::Client)).unwrap(); -let s01 = test_context.open_connector_with_cfg(config.clone()).await; -let s02 = test_context.open_connector_with_cfg(config.clone()).await; - -test_context.close().await; -``` - -### 4. Advanced: Manual Topology - -For complex topologies where multiple listeners need to be interconnected manually, use the `get_tcp_locator` helper to retrieve assigned ports. -*Reference test case: `test_liveliness_subget_router_middle` in `liveliness.rs`* - -```rust -// Create a listener manually on port 0 -let router = { - let mut c = zenoh_config::Config::default(); - c.listen.endpoints.set(vec!["tcp/127.0.0.1:0".parse::().unwrap()]).unwrap(); - c.scouting.multicast.set_enabled(Some(false)).unwrap(); - let _ = c.set_mode(Some(WhatAmI::Router)); - ztimeout!(zenoh::open(c)).unwrap() -}; - -// Key Point: Get the actual assigned endpoint -let router_endpoint = get_tcp_locator(&router).await; - -// Use this endpoint to configure another session -let mut c2 = zenoh_config::Config::default(); -c2.connect.endpoints.set(vec![router_endpoint]).unwrap(); -// ... -``` - -### 5. (Not Recommended) Pre-allocating Free Ports - -In rare cases where you must know the endpoint *before* creating the session, you can use `get_free_port()`. -*Reference test case: `router_linkstate` in `routing.rs`* - -**Warning**: This is not recommended because it is susceptible to TOCTOU (Time-of-check to time-of-use) race conditions, where another process could bind to the "free" port before Zenoh does. - -```rust -// Get a system free port (potential race condition) -let locator1 = format!("tcp/127.0.0.1:{}", get_free_port()); - -// Use it for configuration... -let router1_node = Node { - listen: vec![locator1.clone()], - // ... -}; -``` diff --git a/zenoh/tests/acl.rs b/zenoh/tests/acl.rs index 62f1ee2665..c1d5865a93 100644 --- a/zenoh/tests/acl.rs +++ b/zenoh/tests/acl.rs @@ -14,18 +14,17 @@ #![cfg(feature = "unstable")] #![cfg(target_family = "unix")] -mod common; use std::{ sync::{atomic::AtomicBool, Arc, Mutex}, time::Duration, }; -use common::TestSessions; use tokio::runtime::Handle; use zenoh::{config::WhatAmI, sample::SampleKind}; use zenoh_config::Config; use zenoh_core::{zlock, ztimeout}; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); diff --git a/zenoh/tests/adminspace.rs b/zenoh/tests/adminspace.rs index 88a84313a7..b1e73ea136 100644 --- a/zenoh/tests/adminspace.rs +++ b/zenoh/tests/adminspace.rs @@ -12,14 +12,13 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; use std::time::Duration; -use common::TestSessions; use zenoh_config::WhatAmI; use zenoh_core::ztimeout; use zenoh_link::EndPoint; +use zenoh_test::get_locators_from_session; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_adminspace_wonly() { @@ -88,7 +87,7 @@ async fn test_adminspace_read() { let zid = router.zid(); // Resolve the actual TCP endpoint assigned by the OS - let router_locators = TestSessions::get_locators_from_session(&router).await; + let router_locators = get_locators_from_session(&router).await; let tcp_locator = router_locators .iter() .find(|ep| ep.to_string().starts_with("tcp/")) @@ -528,7 +527,7 @@ async fn test_adminspace_transports_and_links() { let zid1 = router1.zid(); // Resolve the actual TCP endpoint assigned by the OS, then append QoS metadata - let router1_tcp_addr = TestSessions::get_locators_from_session(&router1) + let router1_tcp_addr = get_locators_from_session(&router1) .await .into_iter() .find(|ep| ep.to_string().starts_with("tcp/")) @@ -827,7 +826,7 @@ async fn test_adminspace_regression_1() { let zid1 = router1.zid(); // Resolve the actual TCP endpoint assigned by the OS, then append QoS metadata - let router1_tcp_addr = TestSessions::get_locators_from_session(&router1) + let router1_tcp_addr = get_locators_from_session(&router1) .await .into_iter() .find(|ep| ep.to_string().starts_with("tcp/")) diff --git a/zenoh/tests/atexit.rs b/zenoh/tests/atexit.rs index 6d79348264..ae205117cc 100644 --- a/zenoh/tests/atexit.rs +++ b/zenoh/tests/atexit.rs @@ -12,8 +12,8 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; -use crate::common::TestSessions; + +use zenoh_test::TestSessions; fn run_in_separate_process(main_name: &str, must_panic: bool) { let output = std::process::Command::new(std::env::current_exe().unwrap()) diff --git a/zenoh/tests/authentication.rs b/zenoh/tests/authentication.rs index 9aa37ae0fc..71b9868131 100644 --- a/zenoh/tests/authentication.rs +++ b/zenoh/tests/authentication.rs @@ -13,7 +13,6 @@ // #![cfg(feature = "unstable")] -mod common; mod test { use std::{ @@ -32,8 +31,7 @@ mod test { }; use zenoh_config::{Config, EndPoint, ModeDependentValue}; use zenoh_core::{zlock, ztimeout}; - - use crate::common::TestSessions; + use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); diff --git a/zenoh/tests/callback_drop_on_undeclare.rs b/zenoh/tests/callback_drop_on_undeclare.rs index 3f59bfbc8c..aed17b47e5 100644 --- a/zenoh/tests/callback_drop_on_undeclare.rs +++ b/zenoh/tests/callback_drop_on_undeclare.rs @@ -12,8 +12,7 @@ // ZettaScale Zenoh Team, // #![cfg(any(feature = "unstable", feature = "internal"))] -#[path = "common/mod.rs"] -mod common; + use core::time::Duration; use std::sync::{atomic::AtomicBool, Arc}; @@ -27,8 +26,7 @@ use zenoh::{ }; use zenoh_config::Config; use zenoh_core::ztimeout; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); diff --git a/zenoh/tests/cancellation.rs b/zenoh/tests/cancellation.rs index 91c06de4e8..41aa283ba8 100644 --- a/zenoh/tests/cancellation.rs +++ b/zenoh/tests/cancellation.rs @@ -13,15 +13,13 @@ // #![cfg(feature = "unstable")] -mod common; use core::time::Duration; use std::sync::{atomic::AtomicBool, Arc}; use zenoh::handlers::CallbackDrop; use zenoh_core::ztimeout; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); diff --git a/zenoh/tests/connectivity.rs b/zenoh/tests/connectivity.rs index e93d8cc20a..9e317bbffe 100644 --- a/zenoh/tests/connectivity.rs +++ b/zenoh/tests/connectivity.rs @@ -12,10 +12,6 @@ // ZettaScale Zenoh Team, // -#[cfg(feature = "unstable")] -#[path = "common/mod.rs"] -mod common; - #[cfg(feature = "unstable")] mod tests { use std::{ @@ -25,8 +21,7 @@ mod tests { }; use zenoh::sample::SampleKind; - - use crate::common::TestSessions; + use zenoh_test::TestSessions; async fn collect_events(events: &flume::Receiver, timeout: Duration) -> Vec { let mut collected = Vec::new(); diff --git a/zenoh/tests/events.rs b/zenoh/tests/events.rs index faa58f5b04..497d90a05a 100644 --- a/zenoh/tests/events.rs +++ b/zenoh/tests/events.rs @@ -12,13 +12,12 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; + use std::time::Duration; use zenoh::{query::Reply, sample::SampleKind}; use zenoh_core::ztimeout; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(10); diff --git a/zenoh/tests/interceptors.rs b/zenoh/tests/interceptors.rs index cce9ab3d92..1bf74f5ee8 100644 --- a/zenoh/tests/interceptors.rs +++ b/zenoh/tests/interceptors.rs @@ -14,7 +14,6 @@ #![cfg(unix)] #![cfg(feature = "unstable")] -mod common; use std::{ collections::HashMap, @@ -24,12 +23,12 @@ use std::{ }, }; -use common::TestSessions; use nonempty_collections::nev; use zenoh::{key_expr::KeyExpr, query::ConsolidationMode, Wait}; use zenoh_config::{ Config, DownsamplingItemConf, DownsamplingMessage, DownsamplingRuleConf, InterceptorFlow, }; +use zenoh_test::TestSessions; // Tokio's time granularity on different platforms #[cfg(target_os = "windows")] diff --git a/zenoh/tests/liveliness.rs b/zenoh/tests/liveliness.rs index a99c3f2257..1ca949db7e 100644 --- a/zenoh/tests/liveliness.rs +++ b/zenoh/tests/liveliness.rs @@ -12,11 +12,9 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; use zenoh_core::ztimeout; - -use crate::common::{get_tcp_locator, TestSessions}; +use zenoh_test::{get_tcp_locator, TestSessions}; #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_liveliness_subscriber_clique() { diff --git a/zenoh/tests/low_pass.rs b/zenoh/tests/low_pass.rs index 3a2c74ba6b..292fca2fff 100644 --- a/zenoh/tests/low_pass.rs +++ b/zenoh/tests/low_pass.rs @@ -14,7 +14,7 @@ #![cfg(unix)] #![cfg(feature = "unstable")] -mod common; + use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, @@ -27,8 +27,7 @@ use zenoh::{bytes::ZBytes, Wait}; use zenoh_config::{ Config, InterceptorFlow, InterceptorLink, LowPassFilterConf, LowPassFilterMessage, }; - -use crate::common::TestSessions; +use zenoh_test::{get_locators_from_session_sync, TestSessions}; static SMALL_MSG_STR: &str = "S"; static BIG_MSG_STR: &str = "B"; @@ -448,7 +447,7 @@ fn lowpass_pub_sub_query_reply_test( let reader_session = test_context.open_listener_with_cfg_sync(reader_config); - let locators = TestSessions::get_locators_from_session_sync(&reader_session); + let locators = get_locators_from_session_sync(&reader_session); writer_config.connect.endpoints.set(locators).unwrap(); let _sub = reader_session diff --git a/zenoh/tests/matching.rs b/zenoh/tests/matching.rs index ef2cb26dc5..45bce70169 100644 --- a/zenoh/tests/matching.rs +++ b/zenoh/tests/matching.rs @@ -12,7 +12,6 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; use std::time::Duration; @@ -24,8 +23,7 @@ use zenoh::{ }; use zenoh_config::WhatAmI; use zenoh_core::ztimeout; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); const RECV_TIMEOUT: Duration = Duration::from_secs(1); diff --git a/zenoh/tests/namespace.rs b/zenoh/tests/namespace.rs index 2bde8cfbdb..9826fc4b4a 100644 --- a/zenoh/tests/namespace.rs +++ b/zenoh/tests/namespace.rs @@ -12,7 +12,6 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; use std::time::Duration; @@ -21,8 +20,7 @@ use zenoh_config::WhatAmI; use zenoh_core::ztimeout; use zenoh_keyexpr::{keyexpr, OwnedNonWildKeyExpr}; use zenoh_macros::{ke, nonwild_ke}; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); diff --git a/zenoh/tests/open_time.rs b/zenoh/tests/open_time.rs index 4547e90997..cbcbc0f2d8 100644 --- a/zenoh/tests/open_time.rs +++ b/zenoh/tests/open_time.rs @@ -14,7 +14,6 @@ #![cfg(feature = "unstable")] #![allow(unused)] -mod common; use std::{ future::IntoFuture, @@ -24,8 +23,7 @@ use std::{ use zenoh_config::Config; use zenoh_link::EndPoint; use zenoh_protocol::core::WhatAmI; - -use crate::common::TestSessions; +use zenoh_test::{get_locators_from_session, TestSessions}; const TIMEOUT_EXPECTED: Duration = Duration::from_secs(5); const SLEEP: Duration = Duration::from_millis(100); @@ -89,7 +87,7 @@ async fn time_open( let start = Instant::now(); let router = ztimeout_expected!(test_context.open_listener_with_cfg(router_config)); - let listener_endpoint = TestSessions::get_locators_from_session(&router) + let listener_endpoint = get_locators_from_session(&router) .await .into_iter() .find(|endpoint| endpoint.protocol().as_str() == listen_endpoint.protocol().as_str()) diff --git a/zenoh/tests/qos_overwrite.rs b/zenoh/tests/qos_overwrite.rs index 77341b3021..fefc52365f 100644 --- a/zenoh/tests/qos_overwrite.rs +++ b/zenoh/tests/qos_overwrite.rs @@ -14,7 +14,6 @@ #![cfg(feature = "unstable")] #![cfg(target_family = "unix")] -mod common; use std::time::Duration; @@ -24,8 +23,7 @@ use zenoh::{ Config, Session, Wait, }; use zenoh_config::{WhatAmI as ConfigWhatAmI, ZenohId}; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const SLEEP: Duration = Duration::from_secs(1); diff --git a/zenoh/tests/routing.rs b/zenoh/tests/routing.rs index 7bd91fa11b..c607e1bf31 100644 --- a/zenoh/tests/routing.rs +++ b/zenoh/tests/routing.rs @@ -12,7 +12,6 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; use std::{ sync::{ @@ -29,8 +28,7 @@ use zenoh_config::{Config, ModeDependentValue, WhatAmIMatcher}; use zenoh_core::ztimeout; use zenoh_link::EndPoint; use zenoh_result::bail; - -use crate::common::{get_free_port, get_tcp_locator}; +use zenoh_test::{get_free_tcp_port, get_tcp_locator}; const TIMEOUT: Duration = Duration::from_secs(10); const MSG_COUNT: usize = 50; @@ -474,7 +472,7 @@ impl Recipe { async fn gossip() -> Result<()> { zenoh::init_log_from_env_or("error"); - let locator = format!("tcp/127.0.0.1:{}", get_free_port()); + let locator = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); let ke = String::from("testKeyExprGossip"); let msg_size = 8; @@ -811,7 +809,7 @@ async fn gossip_regression_3() -> Result<()> { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn static_failover_brokering() -> Result<()> { zenoh::init_log_from_env_or("error"); - let locator = format!("tcp/127.0.0.1:{}", get_free_port()); + let locator = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); let ke = String::from("testKeyExprStaticFailoverBrokering"); let msg_size = 8; @@ -895,7 +893,7 @@ async fn three_node_combination() -> Result<()> { .map( |(node1_mode, node2_mode, msg_size, (delay1, delay2, delay3))| { idx += 1; - let locator = format!("tcp/127.0.0.1:{}", get_free_port()); + let locator = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); let ke_pubsub = format!("three_node_combination_keyexpr_pubsub_{idx}"); let ke_getqueryable = format!("three_node_combination_keyexpr_getqueryable_{idx}"); @@ -1071,7 +1069,7 @@ async fn two_node_combination() -> Result<()> { let ke_getliveliness = format!("two_node_combination_keyexpr_getliveliness_{idx}"); let (node1_listen_connect, node2_listen_connect) = { - let locator = format!("tcp/127.0.0.1:{}", get_free_port()); + let locator = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); let listen = vec![locator]; let connect = vec![]; @@ -1219,7 +1217,7 @@ async fn three_node_combination_multicast() -> Result<()> { .map( |(node1_mode, node2_mode, msg_size, (delay1, delay2, delay3))| { idx += 1; - let port = get_free_port(); + let port = get_free_tcp_port(); let unicast_locator = format!("tcp/127.0.0.1:{}", port); let multicast_locator = format!("udp/224.0.0.1:{}", port); @@ -1332,9 +1330,9 @@ async fn router_linkstate() -> Result<()> { .map(|d| (1024, d)) .map(|(msg_size, (delay1, delay2, delay3))| { idx += 1; - let locator1 = format!("tcp/127.0.0.1:{}", get_free_port()); - let locator2 = format!("tcp/127.0.0.1:{}", get_free_port()); - let locator3 = format!("tcp/127.0.0.1:{}", get_free_port()); + let locator1 = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); + let locator2 = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); + let locator3 = format!("tcp/127.0.0.1:{}", get_free_tcp_port()); let ke_pubsub = format!("router_linkstate_keyexpr_pubsub_{idx}"); let ke_getqueryable = format!("router_linkstate_keyexpr_getqueryable_{idx}"); diff --git a/zenoh/tests/session.rs b/zenoh/tests/session.rs index 0b3ea1018b..791ec4cab6 100644 --- a/zenoh/tests/session.rs +++ b/zenoh/tests/session.rs @@ -12,7 +12,6 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; use std::{ sync::{ @@ -32,10 +31,9 @@ use zenoh::{ Session, }; use zenoh_core::ztimeout; - #[cfg(feature = "internal")] -use crate::common::close_session; -use crate::common::TestSessions; +use zenoh_test::close_session; +use zenoh_test::{get_locators_from_session, TestSessions}; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); @@ -391,7 +389,7 @@ async fn test_session_from_cloned_config() { let sub_session = zenoh::open(sub_config).await.unwrap(); // Update pub_config (connector) - let locator = TestSessions::get_locators_from_session(&sub_session).await; + let locator = get_locators_from_session(&sub_session).await; pub_config.connect.endpoints.set(locator).unwrap(); // Create pub session diff --git a/zenoh/tests/shm.rs b/zenoh/tests/shm.rs index 69bc853501..d737e5944d 100644 --- a/zenoh/tests/shm.rs +++ b/zenoh/tests/shm.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // #![cfg(all(feature = "unstable", feature = "shared-memory",))] -mod common; + use std::{ sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, @@ -32,8 +32,7 @@ use zenoh::{ use zenoh_buffers::ZBuf; use zenoh_core::ztimeout; use zenoh_shm::api::buffer::traits::OwnedShmBuf; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); diff --git a/zenoh/tests/source_info.rs b/zenoh/tests/source_info.rs index 61cfecebed..5b9fe44c88 100644 --- a/zenoh/tests/source_info.rs +++ b/zenoh/tests/source_info.rs @@ -13,13 +13,12 @@ // #![cfg(feature = "unstable")] -mod common; + use core::time::Duration; use zenoh::sample::SourceInfo; use zenoh_core::ztimeout; - -use crate::common::TestSessions; +use zenoh_test::TestSessions; const TIMEOUT: Duration = Duration::from_secs(60); diff --git a/zenoh/tests/unicity.rs b/zenoh/tests/unicity.rs index d81a551f6b..ff9074c99e 100644 --- a/zenoh/tests/unicity.rs +++ b/zenoh/tests/unicity.rs @@ -12,7 +12,7 @@ // ZettaScale Zenoh Team, // #![cfg(feature = "unstable")] -mod common; + use std::{ sync::{ atomic::{AtomicUsize, Ordering}, @@ -25,8 +25,7 @@ use tokio::runtime::Handle; use zenoh::{key_expr::KeyExpr, qos::CongestionControl, Session}; use zenoh_config::WhatAmI; use zenoh_core::ztimeout; - -use crate::common::TestSessions; +use zenoh_test::{get_locators_from_session, TestSessions}; const TIMEOUT: Duration = Duration::from_secs(60); const SLEEP: Duration = Duration::from_secs(1); @@ -43,13 +42,13 @@ async fn open_p2p_sessions() -> (Session, Session, Session) { // Open session 02 (create 1 listener and connect to session 01) let mut s02_config = test_context.get_listener_config("tcp/127.0.0.1:0", 1); - let mut locators = TestSessions::get_locators_from_session(&s01).await; + let mut locators = get_locators_from_session(&s01).await; s02_config.connect.endpoints.set(locators.clone()).unwrap(); println!("[ ][02a] Opening s02 session"); let s02 = ztimeout!(zenoh::open(s02_config)).unwrap(); // Open session 03 (connect to session 01 and session02) - locators.extend(TestSessions::get_locators_from_session(&s02).await); + locators.extend(get_locators_from_session(&s02).await); let s03_config = test_context.get_connector_config_with_endpoint(locators); println!("[ ][03a] Opening s03 session"); let s03 = ztimeout!(zenoh::open(s03_config)).unwrap();