Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Test that a stopped stand-in frees its port where the server is, without racing other tests (#136)

BFlat8c3532d94c42
diff --git a/crates/engine/src/tools/standin_tools/tests.rs b/crates/engine/src/tools/standin_tools/tests.rs
index c56292b5..a434862a 100644
--- a/crates/engine/src/tools/standin_tools/tests.rs
+++ b/crates/engine/src/tools/standin_tools/tests.rs
@@ -123,8 +123,8 @@ fn build_start_request_show_stop_through_the_engine() {
let stopped = call(&e, "web_standin_stop", json!({"id": id})).unwrap();
assert_eq!(stopped["result"]["stopped"][0]["requests_answered"], 8);
- let port: u16 = url.rsplit(':').next().unwrap().parse().unwrap();
- assert!(TcpStream::connect(("127.0.0.1", port)).is_err(), "the port is free");
+ // That its port is freed is tested where the server is (`dropping_a_server_frees_its_port`):
+ // here, among tests that all take free ports, another one may be handed it at once.
assert_eq!(call(&e, "web_standin_show", json!({})).unwrap()["result"]["servers"], json!([]));
});
}
diff --git a/crates/platform/src/standin_server.rs b/crates/platform/src/standin_server.rs
index 9f4d9f40..08e8c431 100644
--- a/crates/platform/src/standin_server.rs
+++ b/crates/platform/src/standin_server.rs
@@ -530,6 +530,21 @@ mod tests {
send(port, format!("GET {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{extra}\r\n").as_bytes())
}
+ /// Dropping a server frees its port for the next one. (Another test's listener can be handed
+ /// a freed ephemeral port at once, so the port is tried for a moment rather than once.)
+ #[test]
+ fn dropping_a_server_frees_its_port() {
+ let srv = start();
+ let port = srv.port;
+ assert!(get(port, "/", "").starts_with("HTTP/1.1 200"));
+ drop(srv);
+ let until = std::time::Instant::now() + Duration::from_secs(2);
+ while std::net::TcpListener::bind(("127.0.0.1", port)).is_err() {
+ assert!(std::time::Instant::now() < until, "port {port} is still held");
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ }
+
#[test]
fn answers_with_method_path_query_and_body() {
let srv = start();