Skip to content

Commit f8cef18

Browse files
committed
tcp_tester: try to connect multiple times
On slow hosts (i.e. running with nested virt), when the server is inside the guest, the client may fail to connect because the first is not yet ready. Make the test attempt to connect multiple times, waiting a second between attempts. Signed-off-by: Sergio Lopez <[email protected]>
1 parent 4b08116 commit f8cef18

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

tests/test_cases/src/tcp_tester.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::io::{ErrorKind, Read, Write};
22
use std::mem;
33
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, TcpListener, TcpStream};
4+
use std::thread;
45
use std::time::Duration;
56

67
fn expect_msg(stream: &mut TcpStream, expected: &[u8]) {
@@ -25,6 +26,23 @@ fn set_timeouts(stream: &mut TcpStream) {
2526
.unwrap();
2627
}
2728

29+
fn connect(port: u16) -> TcpStream {
30+
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
31+
let mut tries = 0;
32+
loop {
33+
match TcpStream::connect(&addr) {
34+
Ok(stream) => return stream,
35+
Err(err) => {
36+
if tries == 5 {
37+
panic!("Couldn't connect to server after 5 attempts: {err}");
38+
}
39+
tries += 1;
40+
thread::sleep(Duration::from_secs(1));
41+
}
42+
}
43+
}
44+
}
45+
2846
#[derive(Debug, Copy, Clone)]
2947
pub struct TcpTester {
3048
port: u16,
@@ -51,8 +69,7 @@ impl TcpTester {
5169
}
5270

5371
pub fn run_client(&self) {
54-
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), self.port);
55-
let mut stream = TcpStream::connect(&addr).unwrap();
72+
let mut stream = connect(self.port);
5673
set_timeouts(&mut stream);
5774
expect_msg(&mut stream, b"ping!");
5875
expect_wouldblock(&mut stream);

0 commit comments

Comments
 (0)