Return valid json in Server fixture (#652)

fix: Server fixture now returns valid json

* return json instead of string
* removed trailing whitespace
* use a constant for the default port
* give binary a better name
This commit is contained in:
Hendrik Eeckhaut
2024-10-25 22:13:35 +02:00
committed by GitHub
parent 6344410cad
commit 30e4e37c0d
6 changed files with 84 additions and 13 deletions

View File

@@ -14,9 +14,14 @@ hyper-util = { workspace = true, features = ["full"] }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
tokio-util = { workspace = true, features = ["compat", "io"] }
tower-service = { version = "0.3" }
serde_json = { workspace = true }
tlsn-server-fixture-certs = { workspace = true }
[[bin]]
name = "main"
name = "tlsn-server-fixture"
path = "src/main.rs"
[dev-dependencies]
axum-test = { version = "16.2.0" }
http-body-util = { workspace = true }
tower = { version = "0.5.1" }

View File

@@ -44,4 +44,4 @@
"lastUpdatedAt": "2023-01-12T16:42:10Z",
"version": 1.2
}
}
}

View File

@@ -85,4 +85,4 @@
"editor": "AdminUser123"
}
}
}
}

View File

@@ -65,4 +65,4 @@
]
}
}
}
}

View File

@@ -5,9 +5,9 @@ use std::{
use axum::{
extract::{Query, State},
response::{Html, Json},
response::Html,
routing::get,
Router,
Json, Router,
};
use futures::{channel::oneshot, AsyncRead, AsyncWrite};
use futures_rustls::{
@@ -22,11 +22,14 @@ use hyper::{
};
use hyper_util::rt::TokioIo;
use serde_json::Value;
use tokio_util::compat::FuturesAsyncReadCompatExt;
use tower_service::Service;
use tlsn_server_fixture_certs::*;
pub const DEFAULT_FIXTURE_PORT: u16 = 3000;
struct AppState {
shutdown: Option<oneshot::Sender<()>>,
}
@@ -94,10 +97,18 @@ async fn bytes(
Ok(Bytes::from(vec![0x42u8; size]))
}
/// parse the JSON data from the file content
fn get_json_value(filecontent: &str) -> Result<Json<Value>, StatusCode> {
Ok(Json(serde_json::from_str(filecontent).map_err(|e| {
eprintln!("Failed to parse JSON data: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?))
}
async fn json(
State(state): State<Arc<Mutex<AppState>>>,
Query(params): Query<HashMap<String, String>>,
) -> Result<Json<&'static str>, StatusCode> {
) -> Result<Json<Value>, StatusCode> {
let size = params
.get("size")
.and_then(|size| size.parse::<usize>().ok())
@@ -108,9 +119,9 @@ async fn json(
}
match size {
1 => Ok(Json(include_str!("data/1kb.json"))),
4 => Ok(Json(include_str!("data/4kb.json"))),
8 => Ok(Json(include_str!("data/8kb.json"))),
1 => get_json_value(include_str!("data/1kb.json")),
4 => get_json_value(include_str!("data/4kb.json")),
8 => get_json_value(include_str!("data/8kb.json")),
_ => Err(StatusCode::NOT_FOUND),
}
}
@@ -125,3 +136,58 @@ async fn html(
Html(include_str!("data/4kb.html"))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{self, Request, StatusCode},
};
use http_body_util::BodyExt;
use serde_json::Value;
use tower::ServiceExt;
fn get_app() -> Router {
let (sender, _) = oneshot::channel();
let state = AppState {
shutdown: Some(sender),
};
app(state)
}
#[tokio::test]
async fn hello_world() {
let response = get_app()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&body[..], b"Hello, World!");
}
#[tokio::test]
async fn json() {
let response = get_app()
.oneshot(
Request::builder()
.method(http::Method::GET)
.uri("/formats/json")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
let body: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(
body.get("id").unwrap().as_number().unwrap().as_u64(),
Some(1234567890)
);
}
}

View File

@@ -1,12 +1,12 @@
use std::{env, io};
use tlsn_server_fixture::bind;
use tlsn_server_fixture::{bind, DEFAULT_FIXTURE_PORT};
use tokio::net::TcpListener;
use tokio_util::compat::TokioAsyncWriteCompatExt;
#[tokio::main]
async fn main() -> io::Result<()> {
let port = env::var("PORT").unwrap_or_else(|_| "3000".to_string());
let port = env::var("PORT").unwrap_or_else(|_| DEFAULT_FIXTURE_PORT.to_string());
let listener = TcpListener::bind(&format!("0.0.0.0:{port}")).await?;
loop {