diff --git a/swarmctl/src/login.rs b/swarmctl/src/login.rs index 1ad87461a..e0f8ef1d1 100644 --- a/swarmctl/src/login.rs +++ b/swarmctl/src/login.rs @@ -383,19 +383,52 @@ mod tests { const AUTH: &str = "https://auth.example.test"; #[tokio::test] - async fn the_callback_listens_on_the_requested_port_or_a_free_one() { + async fn port_0_gives_a_free_loopback_port() { let free = callback_listener(0).await.expect("binds"); - let port = free.local_addr().expect("address").port(); - assert_ne!(port, 0); - drop(free); - let named = callback_listener(port).await.expect("binds the named port"); - assert_eq!(named.local_addr().expect("address").port(), port); - assert!(named.local_addr().expect("address").ip().is_loopback()); - // A port in use is an error naming it, not a silent other port. + let addr = free.local_addr().expect("address"); + assert_ne!(addr.port(), 0); + assert!(addr.ip().is_loopback()); + } + + /// The listener stays open while the named port is asked for, so no other + /// test can take the port in between: the error is certain. + #[tokio::test] + async fn a_port_in_use_is_an_error_naming_it_not_a_silent_other_port() { + let held = callback_listener(0).await.expect("binds"); + let port = held.local_addr().expect("address").port(); let err = callback_listener(port).await.expect_err("in use"); assert!(format!("{err:#}").contains(&port.to_string()), "{err:#}"); } + /// A named port has to be free first, and a number just released can be + /// taken by another test's bind before this one asks for it. That is the + /// one error to retry; any other error, or the wrong port, fails at once. + #[tokio::test] + async fn the_callback_listens_on_the_named_port() { + let in_use = |e: &anyhow::Error| { + e.chain().any(|c| { + c.downcast_ref::() + .is_some_and(|io| io.kind() == std::io::ErrorKind::AddrInUse) + }) + }; + for _ in 0..20 { + let free = callback_listener(0).await.expect("binds"); + let port = free.local_addr().expect("address").port(); + drop(free); + match callback_listener(port).await { + Ok(named) => { + let addr = named.local_addr().expect("address"); + assert_eq!(addr.port(), port); + assert!(addr.ip().is_loopback()); + return; + } + Err(e) if in_use(&e) => {} + Err(e) => panic!("the named port: {e:#}"), + } + } + panic!("every port released was taken again before it was asked for"); + } + /// RFC 7636 appendix B. #[test] fn the_challenge_matches_the_rfc_vector() {