health_check test

This commit is contained in:
2025-09-16 23:13:56 +02:00
parent 3721de1e97
commit 244ee3f677
5 changed files with 1782 additions and 2 deletions

1721
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -3,4 +3,16 @@ name = "zero2prod"
version = "0.1.0"
edition = "2024"
[lib]
path = "src/lib.rs"
[[bin]]
path = "src/main.rs"
name = "zero2prod"
[dependencies]
axum = "0.8.4"
reqwest = "0.12.23"
tokio = { version = "1", features = ["full"] }
tower = "0.5.2"

17
src/lib.rs Normal file
View File

@@ -0,0 +1,17 @@
use axum::{Router, http::StatusCode, response::IntoResponse, routing::get};
pub async fn run() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app()).await.unwrap();
}
async fn health_check() -> impl IntoResponse {
StatusCode::OK
}
pub fn app() -> Router {
Router::new().route("/health_check", get(health_check))
}

View File

@@ -1,3 +1,6 @@
fn main() {
println!("Hello, world!");
use zero2prod::run;
#[tokio::main]
async fn main() {
run().await;
}

27
tests/health_check.rs Normal file
View File

@@ -0,0 +1,27 @@
use tokio::net::TcpListener;
use zero2prod::app;
#[tokio::test]
async fn health_check_works() {
let addr = spawn_app().await;
let client = reqwest::Client::new();
let response = client
.get(&format!("http://{}/health_check", addr))
.send()
.await
.expect("Failed to execute request");
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
async fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app()).await.unwrap();
});
addr.to_string()
}