diff --git a/src/lib.rs b/src/lib.rs index 05d1c13..1bff894 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,16 +1,17 @@ -use actix_web::{web, App, HttpResponse, HttpServer, Responder}; +use actix_web::{web, App, HttpResponse, HttpServer}; +use actix_web::dev::Server; -async fn healthcheck_route() -> impl Responder{ +async fn healthcheck_route() -> HttpResponse { return HttpResponse::Ok().finish() } - -pub async fn run() -> Result<(), std::io::Error>{ - HttpServer::new(||{ +pub fn run() -> Result{ + let server = HttpServer::new(||{ App::new() - .route("/healthcheck", web::get().to(healthcheck_route)) + .route("/health_check", web::get().to(healthcheck_route)) }) .bind("127.0.0.1:8000")? - .run() - .await + .run(); + + Ok(server) } diff --git a/src/main.rs b/src/main.rs index 0aa7bbe..8ea4e9f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,5 +2,7 @@ use email_newsletter_api::run; #[tokio::main] async fn main() -> Result<(), std::io::Error>{ - run().await + // Move the error up the call stack + // otherwise await for the HttpServer + run()?.await } diff --git a/tests/health_check.rs b/tests/health_check.rs index afa898a..9c2690b 100644 --- a/tests/health_check.rs +++ b/tests/health_check.rs @@ -1,6 +1,10 @@ +// tokio spins up a new async runtime every time +// at the beginning of each test case and shutdown at +// the end of each test case +// the spawn_app() function therefore only survives as long as the runtime #[tokio::test] async fn health_check_works(){ - spawn_app().await.expect("Failed to spawn our app."); + spawn_app(); let client = reqwest::Client::new(); @@ -10,6 +14,11 @@ async fn health_check_works(){ assert_eq!(Some(0), response.content_length()); } -async fn spawn_app() -> Result<(), std::io::Error> { - email_newsletter_api::run().await +fn spawn_app() { + let server = email_newsletter_api::run().expect("Failed to bind address"); + // run() returns an instance of HttpServer that will run forever. + // We don't want this behavior + // Therefore we want to spawn our server, run our test logic + // and then tear down the entire test suite + let _ = tokio::spawn(server); }