Skip to content

Commit

Permalink
Return valid json in Server fixture (#652)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
heeckhau authored Oct 25, 2024
1 parent 6344410 commit 30e4e37
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 13 deletions.
9 changes: 7 additions & 2 deletions crates/server-fixture/server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
2 changes: 1 addition & 1 deletion crates/server-fixture/server/src/data/1kb.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,4 @@
"lastUpdatedAt": "2023-01-12T16:42:10Z",
"version": 1.2
}
}
}
2 changes: 1 addition & 1 deletion crates/server-fixture/server/src/data/4kb.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,4 @@
"editor": "AdminUser123"
}
}
}
}
2 changes: 1 addition & 1 deletion crates/server-fixture/server/src/data/8kb.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,4 @@
]
}
}
}
}
78 changes: 72 additions & 6 deletions crates/server-fixture/server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand All @@ -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<()>>,
}
Expand Down Expand Up @@ -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())
Expand All @@ -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),
}
}
Expand All @@ -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)
);
}
}
4 changes: 2 additions & 2 deletions crates/server-fixture/server/src/main.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down

0 comments on commit 30e4e37

Please sign in to comment.