Skip to content

Commit a8ee5e5

Browse files
authored
add integration tests for TcpStream::connect (#99)
1 parent aeb6fd0 commit a8ee5e5

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

examples/tcp_stream_client.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
use wstd::io::{self, AsyncRead, AsyncWrite};
2+
use wstd::net::TcpStream;
3+
4+
#[wstd::main]
5+
async fn main() -> io::Result<()> {
6+
let mut args = std::env::args();
7+
8+
let _ = args.next();
9+
10+
let addr = args.next().ok_or_else(|| {
11+
io::Error::new(
12+
std::io::ErrorKind::InvalidInput,
13+
"address argument required",
14+
)
15+
})?;
16+
17+
let mut stream = TcpStream::connect(addr).await?;
18+
19+
stream.write_all(b"ping\n").await?;
20+
21+
let mut reply = Vec::new();
22+
stream.read_to_end(&mut reply).await?;
23+
24+
Ok(())
25+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
use anyhow::{Context, Result};
2+
use std::net::{Shutdown, TcpListener};
3+
use std::process::{Command, Stdio};
4+
5+
#[test_log::test]
6+
fn tcp_stream_client() -> Result<()> {
7+
use std::io::{Read, Write};
8+
9+
let server = TcpListener::bind("127.0.0.1:8082").context("binding temporary test server")?;
10+
let addr = server
11+
.local_addr()
12+
.context("getting local listener address")?;
13+
14+
let child = Command::new("wasmtime")
15+
.arg("run")
16+
.arg("-Sinherit-network")
17+
.arg(test_programs::TCP_STREAM_CLIENT)
18+
.arg(addr.to_string())
19+
.stdout(Stdio::piped())
20+
.spawn()
21+
.context("spawning wasmtime component")?;
22+
23+
let (mut server_stream, _addr) = server
24+
.accept()
25+
.context("accepting TCP connection from component")?;
26+
27+
let mut buf = [0u8; 5];
28+
server_stream
29+
.read_exact(&mut buf)
30+
.context("reading ping message")?;
31+
assert_eq!(&buf, b"ping\n", "expected ping from component");
32+
33+
server_stream
34+
.write_all(b"pong\n")
35+
.context("writing reply")?;
36+
server_stream.flush().context("flushing")?;
37+
38+
server_stream
39+
.shutdown(Shutdown::Both)
40+
.context("shutting down connection")?;
41+
42+
let output = child
43+
.wait_with_output()
44+
.context("waiting for component exit")?;
45+
46+
assert!(
47+
output.status.success(),
48+
"\nComponent exited abnormally (stderr:\n{})",
49+
String::from_utf8_lossy(&output.stderr)
50+
);
51+
52+
Ok(())
53+
}

0 commit comments

Comments
 (0)