From 198976455e47ddf74736a9f819e3ec97ca4d8d68 Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Tue, 24 Nov 2026 12:11:07 -0800 Subject: [PATCH 1/2] test: reserve refusal endpoints across parallel tests Signed-off-by: Taylor Mutch --- TESTING.md | 12 +++ crates/openshell-core/Cargo.toml | 2 + crates/openshell-core/src/lib.rs | 2 + crates/openshell-core/src/test_support.rs | 84 +++++++++++++++++++ crates/openshell-credential-issuer/Cargo.toml | 1 + .../src/refresh/github_app.rs | 3 +- crates/openshell-driver-vault/Cargo.toml | 1 + crates/openshell-driver-vault/src/lib.rs | 5 +- crates/openshell-sandbox/Cargo.toml | 1 + crates/openshell-sandbox/src/perf.rs | 5 +- crates/openshell-server/Cargo.toml | 1 + .../src/compute/mutation_guard.rs | 2 +- crates/openshell-server/src/lib.rs | 2 +- .../src/persistence/postgres.rs | 54 +++++------- .../src/supervisor_session.rs | 10 +-- crates/openshell-supervisor/Cargo.toml | 1 + crates/openshell-supervisor/src/lib.rs | 7 +- .../src/otlp_relay/exporter.rs | 10 +-- tests/testkit/testkit/Cargo.toml | 3 + tests/testkit/testkit/tests/program.rs | 17 ++-- 20 files changed, 152 insertions(+), 71 deletions(-) create mode 100644 crates/openshell-core/src/test_support.rs diff --git a/TESTING.md b/TESTING.md index ec22cdba3a..4fe5d1ea6c 100644 --- a/TESTING.md +++ b/TESTING.md @@ -52,6 +52,18 @@ mise run test:rust # cargo test --workspace Rust validation checks tracked Cargo lockfiles; run `mise run rust:lockfiles:check` to check them directly. If one is stale, refresh it with Cargo using its adjacent manifest, review the diff, and commit the update. +### TCP ports in tests + +Let test servers bind port `0` and keep the resulting listener alive. Binding a +temporary listener, reading its port, and dropping it lets a parallel test claim +the port before the test uses it. + +For tests that need connection refusal, enable `openshell-core`'s `test-support` +feature in dev-dependencies and keep a `test_support::RefusingTcpPort` guard alive +through the request or child process. This fixture is not for handing a port to a +server later. When a separate process must bind a selected port, retry only bind +collisions with a fresh port and a bounded attempt count. + ### PostgreSQL-backed tests Tests that need a real PostgreSQL server, such as advisory-lock concurrency diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 55339e09b5..92e4cf25be 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -51,6 +51,8 @@ libc = "0.2" [features] default = ["telemetry"] +## Socket fixtures for tests in downstream crates. +test-support = [] ## Compile in anonymous telemetry emission support. On by default; disable with ## `--no-default-features` (plus any other features you need) for a build that ## contains no telemetry endpoint, no HTTP client, and no emission code at all. diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index ee524f84d7..32befa8169 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -68,6 +68,8 @@ pub mod secrets; pub mod settings; pub mod shell; pub mod telemetry; +#[cfg(any(test, feature = "test-support"))] +pub mod test_support; pub mod time; pub mod token_endpoint; pub mod token_grant_failure; diff --git a/crates/openshell-core/src/test_support.rs b/crates/openshell-core/src/test_support.rs new file mode 100644 index 0000000000..7514ce6d9f --- /dev/null +++ b/crates/openshell-core/src/test_support.rs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Socket fixtures shared by crate tests. + +use std::net::{SocketAddr, TcpListener, TcpStream}; + +/// A loopback TCP port that refuses connections for the lifetime of this guard. +/// +/// The port belongs to a connected client, keeping OS-assigned listeners in +/// parallel tests from being allocated the same port. Both ends stay alive. +/// A bound, unconnected socket is insufficient: on macOS it times out instead of +/// refusing. Do not use this fixture to hand a port to a server after dropping it: +/// closing the pair can leave the client's port in `TIME_WAIT`. +#[must_use = "keep the guard alive while testing connection refusal"] +pub struct RefusingTcpPort { + client: TcpStream, + _peer: TcpStream, +} + +impl RefusingTcpPort { + /// Reserve an OS-assigned port that refuses new connections. + /// + /// # Errors + /// + /// Returns an error if a loopback TCP pair cannot be created. + pub fn bind() -> std::io::Result { + let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?; + let client = crate::net::connect_std_tcp_nodelay_best_effort(listener.local_addr()?)?; + let (peer, _) = listener.accept()?; + peer.set_nodelay(true)?; + Ok(Self { + client, + _peer: peer, + }) + } + + /// The reserved loopback address. + /// + /// # Panics + /// + /// Panics if the connected socket has no local address. + #[must_use] + pub fn address(&self) -> SocketAddr { + self.client + .local_addr() + .expect("connected socket has a local address") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn refusing_port_stays_reserved() { + let port = RefusingTcpPort::bind().unwrap(); + let address = port.address(); + assert_eq!( + crate::net::connect_std_tcp_nodelay_best_effort(address) + .unwrap_err() + .kind(), + std::io::ErrorKind::ConnectionRefused + ); + // A socket without SO_REUSEADDR cannot take the connected client's port. + // On macOS an explicit SO_REUSEADDR bind can reuse connected ports. + assert_eq!( + tokio::net::TcpSocket::new_v4() + .unwrap() + .bind(address) + .unwrap_err() + .kind(), + std::io::ErrorKind::AddrInUse + ); + let listeners: Vec<_> = (0..64) + .map(|_| TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap()) + .collect(); + assert!( + listeners + .iter() + .all(|listener| listener.local_addr().unwrap() != address) + ); + } +} diff --git a/crates/openshell-credential-issuer/Cargo.toml b/crates/openshell-credential-issuer/Cargo.toml index 51b0b8cb3e..790ac8de1f 100644 --- a/crates/openshell-credential-issuer/Cargo.toml +++ b/crates/openshell-credential-issuer/Cargo.toml @@ -41,6 +41,7 @@ url = { workspace = true } test-support = [] [dev-dependencies] +openshell-core = { path = "../openshell-core", features = ["test-support"] } axum = { workspace = true } rcgen = { workspace = true } tokio-rustls = { workspace = true } diff --git a/crates/openshell-credential-issuer/src/refresh/github_app.rs b/crates/openshell-credential-issuer/src/refresh/github_app.rs index c790c24004..85a0dc4620 100644 --- a/crates/openshell-credential-issuer/src/refresh/github_app.rs +++ b/crates/openshell-credential-issuer/src/refresh/github_app.rs @@ -697,7 +697,8 @@ mod tests { assert!(failure.status.message().contains("timed out")); assert!(!failure.status.message().contains("secret")); - drop(listener); + let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); + let url = format!("http://{}/secret-path?secret-query=value", port.address()); let client = reqwest::Client::builder() .no_proxy() .timeout(Duration::from_secs(5)) diff --git a/crates/openshell-driver-vault/Cargo.toml b/crates/openshell-driver-vault/Cargo.toml index 93fcbc397b..a04586fb6b 100644 --- a/crates/openshell-driver-vault/Cargo.toml +++ b/crates/openshell-driver-vault/Cargo.toml @@ -34,6 +34,7 @@ tracing-subscriber = { workspace = true } url = { workspace = true } [dev-dependencies] +openshell-core = { path = "../openshell-core", features = ["test-support"] } rcgen = { workspace = true } tempfile = "3" tokio-rustls = { workspace = true } diff --git a/crates/openshell-driver-vault/src/lib.rs b/crates/openshell-driver-vault/src/lib.rs index cdfafc3ce1..c85628769e 100644 --- a/crates/openshell-driver-vault/src/lib.rs +++ b/crates/openshell-driver-vault/src/lib.rs @@ -1374,9 +1374,8 @@ mod tests { #[test] fn loopback_http_bypasses_system_proxy() { - let proxy_listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let proxy_address = proxy_listener.local_addr().unwrap(); - drop(proxy_listener); + let proxy_port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); + let proxy_address = proxy_port.address(); let output = std::process::Command::new(std::env::current_exe().unwrap()) .args([ diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index 0ccc79af88..6b2fc04549 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -78,6 +78,7 @@ socket2 = { workspace = true, features = ["all"] } tempfile = "3" [dev-dependencies] +openshell-core = { path = "../openshell-core", features = ["test-support"] } hyper-util = { workspace = true } openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } rcgen = { workspace = true } diff --git a/crates/openshell-sandbox/src/perf.rs b/crates/openshell-sandbox/src/perf.rs index 408d6d69a1..32264a2c38 100644 --- a/crates/openshell-sandbox/src/perf.rs +++ b/crates/openshell-sandbox/src/perf.rs @@ -435,9 +435,8 @@ mod tests { #[test] fn preparation_failure_does_not_wait_for_other_workers() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener"); - let address = listener.local_addr().expect("test listener address"); - drop(listener); + let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); + let address = port.address(); assert!(run_worker(Protocol::TcpStream, address, 1, 1, 2, 8).is_err()); } diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index a6ff3f7637..6823868e60 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -135,6 +135,7 @@ tonic-prost-build = { workspace = true } protoc-bin-vendored = { workspace = true } [dev-dependencies] +openshell-core = { path = "../openshell-core", features = ["test-support"] } openshell-credential-issuer = { path = "../openshell-credential-issuer", features = ["test-support"] } tracing-core = "0.1" rustls-pki-types = "1.9" diff --git a/crates/openshell-server/src/compute/mutation_guard.rs b/crates/openshell-server/src/compute/mutation_guard.rs index 7481fbc3b4..fdd74641d0 100644 --- a/crates/openshell-server/src/compute/mutation_guard.rs +++ b/crates/openshell-server/src/compute/mutation_guard.rs @@ -896,7 +896,7 @@ mod tests { const TIMEOUTS: &str = "openshell_server_mutation_lock_timeouts_total{scope=\"sandbox\"}"; const ERRORS: &str = "openshell_server_mutation_lock_errors_total{scope=\"sandbox\"}"; let metrics = MetricsCapture::install(); - let url = crate::persistence::PostgresStore::refusing_url_for_tests().await; + let (_port, url) = crate::persistence::PostgresStore::refusing_url_for_tests(); let store = crate::persistence::PostgresStore::connect_lazy_for_tests(&url, 1); let runtime = super::super::new_test_runtime_for_driver(Arc::new(Store::Postgres(store)), "test") diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 799c46e397..f72714380c 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4225,7 +4225,7 @@ mod tests { #[tokio::test] async fn connect_store_serves_probes_while_the_database_is_unreachable() { - let url = crate::persistence::PostgresStore::refusing_url_for_tests().await; + let (_port, url) = crate::persistence::PostgresStore::refusing_url_for_tests(); let health_address = reserved_loopback_address().await; let mut health = super::HealthListener::new(Some(health_address)); let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index b62144ae0d..55d19c0ac2 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -2759,15 +2759,13 @@ impl PostgresStore { } } - /// Test support only: a `PostgreSQL` URL on a loopback port where nothing - /// listens, so every connection attempt is refused. - pub(crate) async fn refusing_url_for_tests() -> String { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0") - .await - .expect("reserve a loopback port"); - let port = listener.local_addr().expect("loopback address").port(); - drop(listener); - format!("postgres://openshell@127.0.0.1:{port}/openshell") + /// Keep the guard alive while using the URL so every connection is refused. + pub(crate) fn refusing_url_for_tests() -> (openshell_core::test_support::RefusingTcpPort, String) + { + let port = openshell_core::test_support::RefusingTcpPort::bind() + .expect("reserve a refusing loopback port"); + let url = format!("postgres://openshell@{}/openshell", port.address()); + (port, url) } } @@ -2778,7 +2776,7 @@ mod tests { #[tokio::test] async fn connect_to_a_refusing_server_fails_unavailable_within_the_acquire_timeout() { - let url = PostgresStore::refusing_url_for_tests().await; + let (_port, url) = PostgresStore::refusing_url_for_tests(); let started = std::time::Instant::now(); let error = PostgresStore::connect(&url, None, None) @@ -2827,10 +2825,8 @@ mod tests { #[tokio::test] async fn lock_connection_timeout_is_contention_only_if_the_pool_filled_during_the_wait() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 2, - ); + let (_port, url) = PostgresStore::refusing_url_for_tests(); + let store = PostgresStore::connect_lazy_for_tests(&url, 2); let usage = &store.lock_usage; let is_contention = |error: PersistenceError| match error { PersistenceError::LockTimeout(detail) => { @@ -2873,10 +2869,8 @@ mod tests { async fn lock_connection_checkout_tracks_the_in_use_gauge() { const IN_USE: &str = "openshell_server_mutation_lock_connections_in_use"; let metrics = crate::gateway_metrics::MetricsCapture::install(); - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 2, - ); + let (_port, url) = PostgresStore::refusing_url_for_tests(); + let store = PostgresStore::connect_lazy_for_tests(&url, 2); let usage = &store.lock_usage; let first = LockConnectionCheckout::new(usage); @@ -2900,10 +2894,8 @@ mod tests { #[tokio::test] async fn lock_connection_timeout_without_time_to_connect_is_a_lock_timeout() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); + let (_port, url) = PostgresStore::refusing_url_for_tests(); + let store = PostgresStore::connect_lazy_for_tests(&url, 1); // The pool never fills, but an earlier wait left too little time to // open a connection. let start = store.lock_usage.snapshot(); @@ -2930,10 +2922,8 @@ mod tests { #[tokio::test] async fn refused_lock_connection_is_a_database_error_not_a_lock_timeout() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); + let (_port, url) = PostgresStore::refusing_url_for_tests(); + let store = PostgresStore::connect_lazy_for_tests(&url, 1); // SQLx retries a refused connection until the deadline, which leaves // ample time to open one. let deadline = @@ -2983,10 +2973,8 @@ mod tests { .with_writer(move || LogWriter(writer.clone())) .finish(), ); - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); + let (_port, url) = PostgresStore::refusing_url_for_tests(); + let store = PostgresStore::connect_lazy_for_tests(&url, 1); let available = u32::try_from(store.data_lock_slots.available_permits()) .expect("the slot count fits in u32"); let _held = Arc::clone(&store.data_lock_slots) @@ -3022,10 +3010,8 @@ mod tests { #[tokio::test(start_paused = true)] async fn failed_data_pool_lock_acquisition_returns_its_slot() { - let store = PostgresStore::connect_lazy_for_tests( - &PostgresStore::refusing_url_for_tests().await, - 1, - ); + let (_port, url) = PostgresStore::refusing_url_for_tests(); + let store = PostgresStore::connect_lazy_for_tests(&url, 1); let slots = store.data_lock_slots.available_permits(); // SQLx retries the refused connection until its 30-second acquire // timeout, so the acquisition's own deadline ends the wait first. diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index 0c39fdbf9f..7e2faa7d83 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -5140,13 +5140,6 @@ mod tests { owner } - fn closed_local_endpoint() -> String { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - drop(listener); - format!("http://{addr}") - } - fn peer_relay_open(channel_id: &str) -> RelayOpen { RelayOpen { channel_id: channel_id.to_string(), @@ -5613,7 +5606,8 @@ mod tests { let metrics = MetricsCapture::install(); let state = crate::grpc::test_support::test_server_state().await; seed_peer_token(&state); - let endpoint = closed_local_endpoint(); + let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); + let endpoint = format!("http://{}", port.address()); let err = forward_provider_status_query_to_owner( &state, diff --git a/crates/openshell-supervisor/Cargo.toml b/crates/openshell-supervisor/Cargo.toml index 6678a15b7b..3495c011bb 100644 --- a/crates/openshell-supervisor/Cargo.toml +++ b/crates/openshell-supervisor/Cargo.toml @@ -75,6 +75,7 @@ telemetry = ["openshell-core/telemetry"] bundled-ca-roots = ["openshell-supervisor-network/bundled-ca-roots"] [dev-dependencies] +openshell-core = { path = "../openshell-core", features = ["test-support"] } openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } openshell-sandbox-backend = { path = "../openshell-sandbox-backend", features = ["test-support"] } openshell-otel-test-support = { path = "../openshell-otel-test-support" } diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 3ec4035113..6278307846 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -4982,11 +4982,8 @@ mod tests { #[test] fn tcp_readiness_listener_accepts_ipv4_regardless_of_bindv6only() { - let port = std::net::TcpListener::bind("127.0.0.1:0") - .and_then(|reserved| reserved.local_addr()) - .expect("reserve loopback port") - .port(); - let listener = bind_readiness_tcp(port).expect("bind readiness listener"); + let listener = bind_readiness_tcp(0).expect("bind readiness listener"); + let port = listener.local_addr().expect("readiness address").port(); if listener.local_addr().expect("local address").is_ipv6() { assert!( !socket2::SockRef::from(&listener) diff --git a/crates/openshell-supervisor/src/otlp_relay/exporter.rs b/crates/openshell-supervisor/src/otlp_relay/exporter.rs index ec29acdfb3..9d5bf558dd 100644 --- a/crates/openshell-supervisor/src/otlp_relay/exporter.rs +++ b/crates/openshell-supervisor/src/otlp_relay/exporter.rs @@ -419,9 +419,8 @@ mod tests { #[tokio::test] async fn http_export_to_a_closed_port_fails_promptly() { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let endpoint = format!("http://{}", listener.local_addr().unwrap()); - drop(listener); + let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); + let endpoint = format!("http://{}", port.address()); let exporter = Exporter::new( &endpoint, OtlpProtocol::HttpProtobuf, @@ -614,9 +613,8 @@ mod tests { #[tokio::test] async fn export_to_a_closed_port_returns_status_promptly() { - let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); - let endpoint = format!("http://{}", listener.local_addr().unwrap()); - drop(listener); + let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); + let endpoint = format!("http://{}", port.address()); let exporter = Exporter::new(&endpoint, OtlpProtocol::Grpc, http::HeaderMap::new(), None).unwrap(); diff --git a/tests/testkit/testkit/Cargo.toml b/tests/testkit/testkit/Cargo.toml index a761272e5a..0d7434d709 100644 --- a/tests/testkit/testkit/Cargo.toml +++ b/tests/testkit/testkit/Cargo.toml @@ -42,3 +42,6 @@ libc = "0.2" [[test]] name = "program" harness = false + +[dev-dependencies] +openshell-core = { path = "../../../crates/openshell-core", default-features = false, features = ["test-support"] } diff --git a/tests/testkit/testkit/tests/program.rs b/tests/testkit/testkit/tests/program.rs index 6f03ffbec7..dbe19577f3 100644 --- a/tests/testkit/testkit/tests/program.rs +++ b/tests/testkit/testkit/tests/program.rs @@ -605,25 +605,24 @@ mod unix { /// Point the gateway lookup at a closed port, away from any registered /// gateways. - fn without_gateway(mut command: Command, config: &Path) -> Command { - let closed = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); - let endpoint = format!("http://{}", closed.local_addr().expect("address")); - drop(closed); + fn output_without_gateway(mut command: Command, config: &Path) -> Output { + let port = openshell_core::test_support::RefusingTcpPort::bind().expect("reserve port"); + let endpoint = format!("http://{}", port.address()); command .env("XDG_CONFIG_HOME", config) .env("OPENSHELL_GATEWAY_ENDPOINT", endpoint) .env_remove("OPENSHELL_GATEWAY") .env("OPENSHELL_BIN", config.join("no-openshell")); - command + output(command) } fn registered_tests_run_through_testkit() { let dir = tempfile::tempdir().expect("temp dir"); let (path, junit_arg) = junit(dir.path()); - let run = output(without_gateway( + let run = output_without_gateway( program("registered", &["run", "--junit", &junit_arg]), dir.path(), - )); + ); assert_eq!(run.status.code(), Some(1)); // `testkit::run` logs the description and the gateway. assert!(stderr(&run).contains("[registered_needs_a_gateway] Needs a gateway.")); @@ -642,10 +641,10 @@ mod unix { fn ready_fails_without_a_gateway() { let dir = tempfile::tempdir().expect("temp dir"); let started = Instant::now(); - let ready = output(without_gateway( + let ready = output_without_gateway( program("registered", &["ready", "--timeout", "1"]), dir.path(), - )); + ); assert_eq!(ready.status.code(), Some(2)); assert!(stderr(&ready).contains("not ready after 1s")); assert!(started.elapsed() < Duration::from_secs(10)); From 92f9336acdab95fc98937a816480ff65326e334e Mon Sep 17 00:00:00 2001 From: Taylor Mutch Date: Tue, 24 Nov 2026 12:34:22 -0800 Subject: [PATCH 2/2] test: use deterministic connection failure fixtures Signed-off-by: Taylor Mutch --- TESTING.md | 10 +-- crates/openshell-core/Cargo.toml | 2 - crates/openshell-core/src/lib.rs | 2 - crates/openshell-core/src/test_support.rs | 84 ------------------- crates/openshell-credential-issuer/Cargo.toml | 1 - .../src/refresh/github_app.rs | 5 +- crates/openshell-driver-vault/Cargo.toml | 1 - crates/openshell-driver-vault/src/lib.rs | 3 +- crates/openshell-sandbox/Cargo.toml | 1 - crates/openshell-sandbox/src/perf.rs | 3 +- crates/openshell-server/Cargo.toml | 1 - .../src/compute/mutation_guard.rs | 7 +- crates/openshell-server/src/lib.rs | 3 +- .../src/persistence/postgres.rs | 80 ++++++++++++------ .../src/supervisor_session.rs | 5 +- crates/openshell-supervisor/Cargo.toml | 1 - .../src/otlp_relay/exporter.rs | 18 ++-- tests/testkit/testkit/Cargo.toml | 3 - tests/testkit/testkit/tests/program.rs | 15 ++-- 19 files changed, 88 insertions(+), 157 deletions(-) delete mode 100644 crates/openshell-core/src/test_support.rs diff --git a/TESTING.md b/TESTING.md index 4fe5d1ea6c..3cfa928a89 100644 --- a/TESTING.md +++ b/TESTING.md @@ -58,11 +58,11 @@ Let test servers bind port `0` and keep the resulting listener alive. Binding a temporary listener, reading its port, and dropping it lets a parallel test claim the port before the test uses it. -For tests that need connection refusal, enable `openshell-core`'s `test-support` -feature in dev-dependencies and keep a `test_support::RefusingTcpPort` guard alive -through the request or child process. This fixture is not for handing a port to a -server later. When a separate process must bind a selected port, retry only bind -collisions with a fresh port and a bounded attempt count. +For a generic connection failure, use destination `127.0.0.1:0`: port zero cannot +host a TCP listener. The error kind differs by OS, so do not assert a specific +refusal error. For handshake or acquisition timeouts, keep a listener bound and +never serve its connections. When a separate process must bind a selected port, +retry only bind collisions with a fresh port and a bounded attempt count. ### PostgreSQL-backed tests diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 92e4cf25be..55339e09b5 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -51,8 +51,6 @@ libc = "0.2" [features] default = ["telemetry"] -## Socket fixtures for tests in downstream crates. -test-support = [] ## Compile in anonymous telemetry emission support. On by default; disable with ## `--no-default-features` (plus any other features you need) for a build that ## contains no telemetry endpoint, no HTTP client, and no emission code at all. diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 32befa8169..ee524f84d7 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -68,8 +68,6 @@ pub mod secrets; pub mod settings; pub mod shell; pub mod telemetry; -#[cfg(any(test, feature = "test-support"))] -pub mod test_support; pub mod time; pub mod token_endpoint; pub mod token_grant_failure; diff --git a/crates/openshell-core/src/test_support.rs b/crates/openshell-core/src/test_support.rs deleted file mode 100644 index 7514ce6d9f..0000000000 --- a/crates/openshell-core/src/test_support.rs +++ /dev/null @@ -1,84 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Socket fixtures shared by crate tests. - -use std::net::{SocketAddr, TcpListener, TcpStream}; - -/// A loopback TCP port that refuses connections for the lifetime of this guard. -/// -/// The port belongs to a connected client, keeping OS-assigned listeners in -/// parallel tests from being allocated the same port. Both ends stay alive. -/// A bound, unconnected socket is insufficient: on macOS it times out instead of -/// refusing. Do not use this fixture to hand a port to a server after dropping it: -/// closing the pair can leave the client's port in `TIME_WAIT`. -#[must_use = "keep the guard alive while testing connection refusal"] -pub struct RefusingTcpPort { - client: TcpStream, - _peer: TcpStream, -} - -impl RefusingTcpPort { - /// Reserve an OS-assigned port that refuses new connections. - /// - /// # Errors - /// - /// Returns an error if a loopback TCP pair cannot be created. - pub fn bind() -> std::io::Result { - let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?; - let client = crate::net::connect_std_tcp_nodelay_best_effort(listener.local_addr()?)?; - let (peer, _) = listener.accept()?; - peer.set_nodelay(true)?; - Ok(Self { - client, - _peer: peer, - }) - } - - /// The reserved loopback address. - /// - /// # Panics - /// - /// Panics if the connected socket has no local address. - #[must_use] - pub fn address(&self) -> SocketAddr { - self.client - .local_addr() - .expect("connected socket has a local address") - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn refusing_port_stays_reserved() { - let port = RefusingTcpPort::bind().unwrap(); - let address = port.address(); - assert_eq!( - crate::net::connect_std_tcp_nodelay_best_effort(address) - .unwrap_err() - .kind(), - std::io::ErrorKind::ConnectionRefused - ); - // A socket without SO_REUSEADDR cannot take the connected client's port. - // On macOS an explicit SO_REUSEADDR bind can reuse connected ports. - assert_eq!( - tokio::net::TcpSocket::new_v4() - .unwrap() - .bind(address) - .unwrap_err() - .kind(), - std::io::ErrorKind::AddrInUse - ); - let listeners: Vec<_> = (0..64) - .map(|_| TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).unwrap()) - .collect(); - assert!( - listeners - .iter() - .all(|listener| listener.local_addr().unwrap() != address) - ); - } -} diff --git a/crates/openshell-credential-issuer/Cargo.toml b/crates/openshell-credential-issuer/Cargo.toml index 790ac8de1f..51b0b8cb3e 100644 --- a/crates/openshell-credential-issuer/Cargo.toml +++ b/crates/openshell-credential-issuer/Cargo.toml @@ -41,7 +41,6 @@ url = { workspace = true } test-support = [] [dev-dependencies] -openshell-core = { path = "../openshell-core", features = ["test-support"] } axum = { workspace = true } rcgen = { workspace = true } tokio-rustls = { workspace = true } diff --git a/crates/openshell-credential-issuer/src/refresh/github_app.rs b/crates/openshell-credential-issuer/src/refresh/github_app.rs index 85a0dc4620..6b3e90e138 100644 --- a/crates/openshell-credential-issuer/src/refresh/github_app.rs +++ b/crates/openshell-credential-issuer/src/refresh/github_app.rs @@ -697,14 +697,13 @@ mod tests { assert!(failure.status.message().contains("timed out")); assert!(!failure.status.message().contains("secret")); - let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); - let url = format!("http://{}/secret-path?secret-query=value", port.address()); + let url = "http://127.0.0.1:0/secret-path?secret-query=value"; let client = reqwest::Client::builder() .no_proxy() .timeout(Duration::from_secs(5)) .build() .unwrap(); - let failure = transport_failure(client.get(&url).send().await.unwrap_err()); + let failure = transport_failure(client.get(url).send().await.unwrap_err()); assert_eq!(failure.failure_code, "github_token_endpoint_unavailable"); assert_eq!(failure.recovery_action, Recovery::Retry); assert!(failure.status.message().contains("connection failed")); diff --git a/crates/openshell-driver-vault/Cargo.toml b/crates/openshell-driver-vault/Cargo.toml index a04586fb6b..93fcbc397b 100644 --- a/crates/openshell-driver-vault/Cargo.toml +++ b/crates/openshell-driver-vault/Cargo.toml @@ -34,7 +34,6 @@ tracing-subscriber = { workspace = true } url = { workspace = true } [dev-dependencies] -openshell-core = { path = "../openshell-core", features = ["test-support"] } rcgen = { workspace = true } tempfile = "3" tokio-rustls = { workspace = true } diff --git a/crates/openshell-driver-vault/src/lib.rs b/crates/openshell-driver-vault/src/lib.rs index c85628769e..d42bc068df 100644 --- a/crates/openshell-driver-vault/src/lib.rs +++ b/crates/openshell-driver-vault/src/lib.rs @@ -1374,8 +1374,7 @@ mod tests { #[test] fn loopback_http_bypasses_system_proxy() { - let proxy_port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); - let proxy_address = proxy_port.address(); + let proxy_address = "127.0.0.1:0"; let output = std::process::Command::new(std::env::current_exe().unwrap()) .args([ diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index 6b2fc04549..0ccc79af88 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -78,7 +78,6 @@ socket2 = { workspace = true, features = ["all"] } tempfile = "3" [dev-dependencies] -openshell-core = { path = "../openshell-core", features = ["test-support"] } hyper-util = { workspace = true } openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } rcgen = { workspace = true } diff --git a/crates/openshell-sandbox/src/perf.rs b/crates/openshell-sandbox/src/perf.rs index 32264a2c38..762204585d 100644 --- a/crates/openshell-sandbox/src/perf.rs +++ b/crates/openshell-sandbox/src/perf.rs @@ -435,8 +435,7 @@ mod tests { #[test] fn preparation_failure_does_not_wait_for_other_workers() { - let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); - let address = port.address(); + let address = "127.0.0.1:0".parse().unwrap(); assert!(run_worker(Protocol::TcpStream, address, 1, 1, 2, 8).is_err()); } diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index 6823868e60..a6ff3f7637 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -135,7 +135,6 @@ tonic-prost-build = { workspace = true } protoc-bin-vendored = { workspace = true } [dev-dependencies] -openshell-core = { path = "../openshell-core", features = ["test-support"] } openshell-credential-issuer = { path = "../openshell-credential-issuer", features = ["test-support"] } tracing-core = "0.1" rustls-pki-types = "1.9" diff --git a/crates/openshell-server/src/compute/mutation_guard.rs b/crates/openshell-server/src/compute/mutation_guard.rs index fdd74641d0..40197ee568 100644 --- a/crates/openshell-server/src/compute/mutation_guard.rs +++ b/crates/openshell-server/src/compute/mutation_guard.rs @@ -896,12 +896,13 @@ mod tests { const TIMEOUTS: &str = "openshell_server_mutation_lock_timeouts_total{scope=\"sandbox\"}"; const ERRORS: &str = "openshell_server_mutation_lock_errors_total{scope=\"sandbox\"}"; let metrics = MetricsCapture::install(); - let (_port, url) = crate::persistence::PostgresStore::refusing_url_for_tests(); + let (_listener, url) = + crate::persistence::PostgresStore::unresponsive_url_for_tests().await; let store = crate::persistence::PostgresStore::connect_lazy_for_tests(&url, 1); let runtime = super::super::new_test_runtime_for_driver(Arc::new(Store::Postgres(store)), "test") .await; - // Leave enough time to open a lock connection, so the refusal is a + // Leave enough time to open a lock connection, so the acquisition failure is a // database error. runtime.set_mutation_lock_timeout_for_tests( crate::persistence::mutation_lock::LOCK_CONNECTION_MIN_BUDGET @@ -917,7 +918,7 @@ mod tests { "{detail}" ), Err(error) => panic!("expected a database error, got {error:?}"), - Ok(_) => panic!("nothing listens, yet the guard was acquired"), + Ok(_) => panic!("the database never answers, yet the guard was acquired"), } assert_eq!(metrics.value(TIMEOUTS), None); assert_eq!(metrics.value(ERRORS), Some(1)); diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index f72714380c..00d84dc081 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -4225,7 +4225,8 @@ mod tests { #[tokio::test] async fn connect_store_serves_probes_while_the_database_is_unreachable() { - let (_port, url) = crate::persistence::PostgresStore::refusing_url_for_tests(); + let (_listener, url) = + crate::persistence::PostgresStore::unresponsive_url_for_tests().await; let health_address = reserved_loopback_address().await; let mut health = super::HealthListener::new(Some(health_address)); let (stop, stopped) = tokio::sync::oneshot::channel::<()>(); diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index 55d19c0ac2..d212d85ba9 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -2759,13 +2759,16 @@ impl PostgresStore { } } - /// Keep the guard alive while using the URL so every connection is refused. - pub(crate) fn refusing_url_for_tests() -> (openshell_core::test_support::RefusingTcpPort, String) - { - let port = openshell_core::test_support::RefusingTcpPort::bind() - .expect("reserve a refusing loopback port"); - let url = format!("postgres://openshell@{}/openshell", port.address()); - (port, url) + /// Hold a listener that never answers the `PostgreSQL` handshake. + pub(crate) async fn unresponsive_url_for_tests() -> (tokio::net::TcpListener, String) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind a silent database endpoint"); + let url = format!( + "postgres://openshell@{}/openshell", + listener.local_addr().unwrap() + ); + (listener, url) } } @@ -2774,14 +2777,43 @@ mod tests { use super::super::mutation_lock::SSH_IDENTITY_LOCK_KEY; use super::*; + #[cfg(target_os = "linux")] #[tokio::test] async fn connect_to_a_refusing_server_fails_unavailable_within_the_acquire_timeout() { - let (_port, url) = PostgresStore::refusing_url_for_tests(); + // Linux refuses connections to a bound, non-listening socket. Keeping + // it bound also excludes listeners with SO_REUSEADDR enabled. + let socket = + socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None).unwrap(); + socket + .bind(&std::net::SocketAddr::from(([127, 0, 0, 1], 0)).into()) + .unwrap(); + let address = socket.local_addr().unwrap().as_socket().unwrap(); + assert!(tokio::net::TcpListener::bind(address).await.is_err()); + assert_eq!( + openshell_core::net::connect_tcp_nodelay_best_effort(address) + .await + .unwrap_err() + .kind(), + std::io::ErrorKind::ConnectionRefused + ); + let url = format!("postgres://openshell@{address}/openshell"); + let started = std::time::Instant::now(); + let error = PostgresStore::connect(&url, None, None).await.unwrap_err(); + assert!( + matches!(error, PersistenceError::Unavailable(_)), + "{error:?}" + ); + assert!(started.elapsed() < DATA_POOL_ACQUIRE_TIMEOUT + Duration::from_secs(3)); + } + + #[tokio::test] + async fn connect_to_an_unresponsive_server_fails_unavailable_within_the_acquire_timeout() { + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let started = std::time::Instant::now(); let error = PostgresStore::connect(&url, None, None) .await - .expect_err("nothing listens on the port"); + .expect_err("the database never answers"); assert!( matches!(error, PersistenceError::Unavailable(_)), @@ -2825,7 +2857,7 @@ mod tests { #[tokio::test] async fn lock_connection_timeout_is_contention_only_if_the_pool_filled_during_the_wait() { - let (_port, url) = PostgresStore::refusing_url_for_tests(); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let store = PostgresStore::connect_lazy_for_tests(&url, 2); let usage = &store.lock_usage; let is_contention = |error: PersistenceError| match error { @@ -2869,7 +2901,7 @@ mod tests { async fn lock_connection_checkout_tracks_the_in_use_gauge() { const IN_USE: &str = "openshell_server_mutation_lock_connections_in_use"; let metrics = crate::gateway_metrics::MetricsCapture::install(); - let (_port, url) = PostgresStore::refusing_url_for_tests(); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let store = PostgresStore::connect_lazy_for_tests(&url, 2); let usage = &store.lock_usage; @@ -2894,7 +2926,7 @@ mod tests { #[tokio::test] async fn lock_connection_timeout_without_time_to_connect_is_a_lock_timeout() { - let (_port, url) = PostgresStore::refusing_url_for_tests(); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let store = PostgresStore::connect_lazy_for_tests(&url, 1); // The pool never fills, but an earlier wait left too little time to // open a connection. @@ -2905,7 +2937,7 @@ mod tests { PersistenceError::LockTimeout(_) )); - // SQLx retries the refused connection until the deadline. + // The handshake stays pending until the acquisition deadline. let deadline = tokio::time::Instant::now() + LOCK_CONNECTION_MIN_BUDGET / 4; match store .acquire_mutation_locks(&MutationLockSet::default(), deadline) @@ -2915,17 +2947,17 @@ mod tests { assert_eq!(detail, "waiting for a mutation lock connection"); } Err(error) => panic!("expected a lock timeout, got {error:?}"), - Ok(_) => panic!("nothing listens, yet a lock connection opened"), + Ok(_) => panic!("the database never answers, yet a lock connection opened"), } assert_eq!(store.lock_usage.in_use.load(Ordering::Acquire), 0); } #[tokio::test] - async fn refused_lock_connection_is_a_database_error_not_a_lock_timeout() { - let (_port, url) = PostgresStore::refusing_url_for_tests(); + async fn unresponsive_lock_connection_is_a_database_error_not_a_lock_timeout() { + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let store = PostgresStore::connect_lazy_for_tests(&url, 1); - // SQLx retries a refused connection until the deadline, which leaves - // ample time to open one. + // Give acquisition enough budget to classify an unanswered handshake + // as a database error rather than lock contention. let deadline = tokio::time::Instant::now() + LOCK_CONNECTION_MIN_BUDGET + Duration::from_millis(300); match store @@ -2937,7 +2969,7 @@ mod tests { "{detail}" ), Err(error) => panic!("expected a database error, got {error:?}"), - Ok(_) => panic!("nothing listens, yet a lock connection opened"), + Ok(_) => panic!("the database never answers, yet a lock connection opened"), } assert_eq!(store.lock_usage.in_use.load(Ordering::Acquire), 0); } @@ -2973,7 +3005,7 @@ mod tests { .with_writer(move || LogWriter(writer.clone())) .finish(), ); - let (_port, url) = PostgresStore::refusing_url_for_tests(); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let store = PostgresStore::connect_lazy_for_tests(&url, 1); let available = u32::try_from(store.data_lock_slots.available_permits()) .expect("the slot count fits in u32"); @@ -2983,7 +3015,7 @@ mod tests { // The outer timeout turns a missing bound into a failure instead of a // hang. It also fails a data connection acquired before the slot: - // SQLx retries the refused connection until its 30-second acquire + // The handshake waits for the 30-second acquire // timeout, past this one. match tokio::time::timeout( MUTATION_LOCK_TIMEOUT * 2, @@ -3010,10 +3042,10 @@ mod tests { #[tokio::test(start_paused = true)] async fn failed_data_pool_lock_acquisition_returns_its_slot() { - let (_port, url) = PostgresStore::refusing_url_for_tests(); + let (_listener, url) = PostgresStore::unresponsive_url_for_tests().await; let store = PostgresStore::connect_lazy_for_tests(&url, 1); let slots = store.data_lock_slots.available_permits(); - // SQLx retries the refused connection until its 30-second acquire + // The handshake waits for the 30-second acquire // timeout, so the acquisition's own deadline ends the wait first. match tokio::time::timeout( MUTATION_LOCK_TIMEOUT * 2, @@ -3026,7 +3058,7 @@ mod tests { assert_eq!(detail, "waiting for a data-pool lock connection"); } Err(error) => panic!("expected a lock timeout, got {error:?}"), - Ok(_) => panic!("nothing listens, yet a data-pool lock was acquired"), + Ok(_) => panic!("the database never answers, yet a data-pool lock was acquired"), } assert_eq!( store.data_lock_slots.available_permits(), diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index 7e2faa7d83..f9f46b153b 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -5606,12 +5606,11 @@ mod tests { let metrics = MetricsCapture::install(); let state = crate::grpc::test_support::test_server_state().await; seed_peer_token(&state); - let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); - let endpoint = format!("http://{}", port.address()); + let endpoint = "http://127.0.0.1:0"; let err = forward_provider_status_query_to_owner( &state, - &owner_at(&endpoint), + &owner_at(endpoint), "sbx-peer", GetSandboxProviderStatusRequest::default(), ) diff --git a/crates/openshell-supervisor/Cargo.toml b/crates/openshell-supervisor/Cargo.toml index 3495c011bb..6678a15b7b 100644 --- a/crates/openshell-supervisor/Cargo.toml +++ b/crates/openshell-supervisor/Cargo.toml @@ -75,7 +75,6 @@ telemetry = ["openshell-core/telemetry"] bundled-ca-roots = ["openshell-supervisor-network/bundled-ca-roots"] [dev-dependencies] -openshell-core = { path = "../openshell-core", features = ["test-support"] } openshell-ocsf = { path = "../openshell-ocsf", features = ["test-support"] } openshell-sandbox-backend = { path = "../openshell-sandbox-backend", features = ["test-support"] } openshell-otel-test-support = { path = "../openshell-otel-test-support" } diff --git a/crates/openshell-supervisor/src/otlp_relay/exporter.rs b/crates/openshell-supervisor/src/otlp_relay/exporter.rs index 9d5bf558dd..3643914a29 100644 --- a/crates/openshell-supervisor/src/otlp_relay/exporter.rs +++ b/crates/openshell-supervisor/src/otlp_relay/exporter.rs @@ -418,11 +418,10 @@ mod tests { } #[tokio::test] - async fn http_export_to_a_closed_port_fails_promptly() { - let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); - let endpoint = format!("http://{}", port.address()); + async fn http_export_to_port_zero_fails_promptly() { + let endpoint = "http://127.0.0.1:0"; let exporter = Exporter::new( - &endpoint, + endpoint, OtlpProtocol::HttpProtobuf, http::HeaderMap::new(), None, @@ -433,7 +432,7 @@ mod tests { let error = exporter .export(Bytes::from(encoded_request("s", &[]))) .await - .expect_err("closed port fails"); + .expect_err("port zero fails"); assert!(matches!(error, ExportError::Http(_)), "{error}"); assert!(started.elapsed() < EXPORT_TIMEOUT); } @@ -612,17 +611,16 @@ mod tests { } #[tokio::test] - async fn export_to_a_closed_port_returns_status_promptly() { - let port = openshell_core::test_support::RefusingTcpPort::bind().unwrap(); - let endpoint = format!("http://{}", port.address()); + async fn export_to_port_zero_returns_status_promptly() { + let endpoint = "http://127.0.0.1:0"; let exporter = - Exporter::new(&endpoint, OtlpProtocol::Grpc, http::HeaderMap::new(), None).unwrap(); + Exporter::new(endpoint, OtlpProtocol::Grpc, http::HeaderMap::new(), None).unwrap(); let started = Instant::now(); let error = exporter .export(Bytes::from(encoded_request("s", &[]))) .await - .expect_err("closed port fails"); + .expect_err("port zero fails"); assert!(matches!(error, ExportError::Status(_)), "{error}"); assert!(started.elapsed() < EXPORT_TIMEOUT); } diff --git a/tests/testkit/testkit/Cargo.toml b/tests/testkit/testkit/Cargo.toml index 0d7434d709..a761272e5a 100644 --- a/tests/testkit/testkit/Cargo.toml +++ b/tests/testkit/testkit/Cargo.toml @@ -42,6 +42,3 @@ libc = "0.2" [[test]] name = "program" harness = false - -[dev-dependencies] -openshell-core = { path = "../../../crates/openshell-core", default-features = false, features = ["test-support"] } diff --git a/tests/testkit/testkit/tests/program.rs b/tests/testkit/testkit/tests/program.rs index dbe19577f3..2ee1903c4e 100644 --- a/tests/testkit/testkit/tests/program.rs +++ b/tests/testkit/testkit/tests/program.rs @@ -605,24 +605,23 @@ mod unix { /// Point the gateway lookup at a closed port, away from any registered /// gateways. - fn output_without_gateway(mut command: Command, config: &Path) -> Output { - let port = openshell_core::test_support::RefusingTcpPort::bind().expect("reserve port"); - let endpoint = format!("http://{}", port.address()); + fn without_gateway(mut command: Command, config: &Path) -> Command { + let endpoint = "http://127.0.0.1:0"; command .env("XDG_CONFIG_HOME", config) .env("OPENSHELL_GATEWAY_ENDPOINT", endpoint) .env_remove("OPENSHELL_GATEWAY") .env("OPENSHELL_BIN", config.join("no-openshell")); - output(command) + command } fn registered_tests_run_through_testkit() { let dir = tempfile::tempdir().expect("temp dir"); let (path, junit_arg) = junit(dir.path()); - let run = output_without_gateway( + let run = output(without_gateway( program("registered", &["run", "--junit", &junit_arg]), dir.path(), - ); + )); assert_eq!(run.status.code(), Some(1)); // `testkit::run` logs the description and the gateway. assert!(stderr(&run).contains("[registered_needs_a_gateway] Needs a gateway.")); @@ -641,10 +640,10 @@ mod unix { fn ready_fails_without_a_gateway() { let dir = tempfile::tempdir().expect("temp dir"); let started = Instant::now(); - let ready = output_without_gateway( + let ready = output(without_gateway( program("registered", &["ready", "--timeout", "1"]), dir.path(), - ); + )); assert_eq!(ready.status.code(), Some(2)); assert!(stderr(&ready).contains("not ready after 1s")); assert!(started.elapsed() < Duration::from_secs(10));