Skip to content

Commit 0f0b2c3

Browse files
author
Miloš Vučenović
committed
Test simulating uds ping-pong server/client
This one should reproduce async-rs#248 bug to prevent further regressions.
1 parent 98c79f4 commit 0f0b2c3

File tree

1 file changed

+56
-1
lines changed

1 file changed

+56
-1
lines changed

tests/uds.rs

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
#![cfg(unix)]
22

33
use async_std::io;
4-
use async_std::os::unix::net::UnixDatagram;
4+
use async_std::os::unix::net::{UnixDatagram, UnixListener, UnixStream};
5+
use async_std::prelude::*;
56
use async_std::task;
67

8+
use tempdir::TempDir;
9+
10+
use std::time::Duration;
11+
712
const JULIUS_CAESAR: &[u8] = b"
813
Friends, Romans, countrymen - lend me your ears!
914
I come not to praise Caesar, but to bury him.
@@ -39,3 +44,53 @@ fn into_raw_fd() -> io::Result<()> {
3944
Ok(())
4045
})
4146
}
47+
48+
const PING: &[u8] = b"ping";
49+
const PONG: &[u8] = b"pong";
50+
const TEST_TIMEOUT: std::time::Duration = Duration::from_secs(3);
51+
52+
#[test]
53+
fn socket_ping_pong() {
54+
let tmp_dir = TempDir::new("socket_ping_pong").expect("Temp dir not created");
55+
let sock_path = tmp_dir.as_ref().join("sock");
56+
let iter_cnt = 16;
57+
58+
let listener =
59+
task::block_on(async { UnixListener::bind(&sock_path).await.expect("Socket bind") });
60+
61+
let server_handle = std::thread::spawn(move || {
62+
task::block_on(async { ping_pong_server(listener, iter_cnt).await }).unwrap()
63+
});
64+
65+
let client_handle = std::thread::spawn(move || {
66+
task::block_on(async { ping_pong_client(&sock_path, iter_cnt).await }).unwrap()
67+
});
68+
69+
client_handle.join().unwrap();
70+
server_handle.join().unwrap();
71+
}
72+
73+
async fn ping_pong_server(listener: UnixListener, iterations: u32) -> std::io::Result<()> {
74+
let mut incoming = listener.incoming();
75+
let mut buf = [0; 1024];
76+
for _ix in 0..iterations {
77+
if let Some(s) = incoming.next().await {
78+
let mut s = s?;
79+
let n = s.read(&mut buf[..]).await?;
80+
assert_eq!(&buf[..n], PING);
81+
s.write_all(&PONG).await?;
82+
}
83+
}
84+
Ok(())
85+
}
86+
87+
async fn ping_pong_client(socket: &std::path::PathBuf, iterations: u32) -> std::io::Result<()> {
88+
let mut buf = [0; 1024];
89+
for _ix in 0..iterations {
90+
let mut socket = UnixStream::connect(&socket).await?;
91+
socket.write_all(&PING).await?;
92+
let n = async_std::io::timeout(TEST_TIMEOUT, socket.read(&mut buf[..])).await?;
93+
assert_eq!(&buf[..n], PONG);
94+
}
95+
Ok(())
96+
}

0 commit comments

Comments
 (0)