use std::{net::IpAddr, time::Duration};
use futures_util::StreamExt;
use massping::DualstackPinger;
use tokio::time;
#[tokio::test(flavor = "current_thread")]
async fn stream_terminates_after_single_ping() {
let pinger = DualstackPinger::new().unwrap();
let localhost: IpAddr = "127.0.0.1".parse().unwrap();
let mut stream = pinger.measure_many([localhost].into_iter());
let mut count = 0;
let result = time::timeout(Duration::from_secs(5), async {
while let Some((addr, rtt)) = stream.next().await {
assert_eq!(addr, localhost);
assert!(rtt < Duration::from_secs(1), "RTT too high: {rtt:?}");
count += 1;
}
})
.await;
assert!(
result.is_ok(),
"stream did not terminate - hung in while let loop"
);
assert_eq!(count, 1, "expected exactly 1 ping response");
}
#[tokio::test(flavor = "current_thread")]
async fn stream_terminates_after_multiple_pings() {
let pinger = DualstackPinger::new().unwrap();
let addresses: Vec<IpAddr> = vec![
"127.0.0.1".parse().unwrap(),
"127.0.0.2".parse().unwrap(),
"127.0.0.3".parse().unwrap(),
];
let mut stream = pinger.measure_many(addresses.iter().copied());
let mut count = 0;
let result = time::timeout(Duration::from_secs(5), async {
while let Some((_addr, rtt)) = stream.next().await {
assert!(rtt < Duration::from_secs(1), "RTT too high: {rtt:?}");
count += 1;
}
})
.await;
assert!(
result.is_ok(),
"stream did not terminate - hung in while let loop"
);
assert_eq!(count, 3, "expected exactly 3 ping responses");
}
#[tokio::test(flavor = "current_thread")]
async fn stream_terminates_with_empty_input() {
let pinger = DualstackPinger::new().unwrap();
let addresses: Vec<IpAddr> = vec![];
let mut stream = pinger.measure_many(addresses.into_iter());
let result = time::timeout(Duration::from_secs(1), async {
let first = stream.next().await;
assert!(first.is_none(), "expected None for empty address list");
})
.await;
assert!(result.is_ok(), "stream did not terminate for empty input");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn stream_terminates_multi_thread() {
let pinger = DualstackPinger::new().unwrap();
let localhost: IpAddr = "127.0.0.1".parse().unwrap();
let mut stream = pinger.measure_many([localhost].into_iter());
let mut count = 0;
let result = time::timeout(Duration::from_secs(5), async {
while let Some((addr, rtt)) = stream.next().await {
assert_eq!(addr, localhost);
assert!(rtt < Duration::from_secs(1), "RTT too high: {rtt:?}");
count += 1;
}
})
.await;
assert!(
result.is_ok(),
"stream did not terminate - hung in while let loop"
);
assert_eq!(count, 1, "expected exactly 1 ping response");
}