Skip to content

Commit c58af7c

Browse files
committed
add a post test to show request Body impl also works
1 parent 76a0733 commit c58af7c

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

test-programs/src/bin/http_post.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
use std::error::Error;
2+
use wstd::http::{Client, HeaderValue, Method, Request};
3+
use wstd::io::AsyncRead;
4+
5+
#[wstd::main]
6+
async fn main() -> Result<(), Box<dyn Error>> {
7+
let mut request = Request::new(Method::POST, "https://postman-echo.com/post".parse()?);
8+
request.headers_mut().insert(
9+
"content-type",
10+
HeaderValue::from_str("application/json; charset=utf-8")?,
11+
);
12+
13+
let mut response = Client::new()
14+
.send(request.set_body("{\"test\": \"data\"}"))
15+
.await?;
16+
17+
let content_type = response
18+
.headers()
19+
.get("Content-Type")
20+
.ok_or_else(|| "response expected to have Content-Type header")?;
21+
assert_eq!(content_type, "application/json; charset=utf-8");
22+
23+
let mut body_buf = Vec::new();
24+
response.body().read_to_end(&mut body_buf).await?;
25+
26+
let val: serde_json::Value = serde_json::from_slice(&body_buf)?;
27+
let body_url = val
28+
.get("url")
29+
.ok_or_else(|| "body json has url")?
30+
.as_str()
31+
.ok_or_else(|| "body json url is str")?;
32+
assert!(
33+
body_url.contains("postman-echo.com/post"),
34+
"expected body url to contain the authority and path, got: {body_url}"
35+
);
36+
37+
let posted_json = val
38+
.get("json")
39+
.ok_or_else(|| "body json has 'json' key")?
40+
.as_object()
41+
.ok_or_else(|| format!("body json 'json' is object. got {val:?}"))?;
42+
43+
assert_eq!(posted_json.len(), 1);
44+
assert_eq!(
45+
posted_json
46+
.get("test")
47+
.ok_or_else(|| "returned json has 'test' key")?
48+
.as_str()
49+
.ok_or_else(|| "returned json 'test' key should be str value")?,
50+
"data"
51+
);
52+
53+
Ok(())
54+
}

tests/test-programs.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,13 @@ fn http_get() -> Result<()> {
127127
run_in_wasmtime(&wasm, None)
128128
}
129129

130+
#[test]
131+
fn http_post() -> Result<()> {
132+
println!("testing {}", test_programs_artifacts::HTTP_POST);
133+
let wasm = std::fs::read(test_programs_artifacts::HTTP_POST).context("read wasm")?;
134+
run_in_wasmtime(&wasm, None)
135+
}
136+
130137
#[test]
131138
fn http_first_byte_timeout() -> Result<()> {
132139
println!(

0 commit comments

Comments
 (0)