From 636e4215cfc089d9ff34e944596f1dd4bad76db1 Mon Sep 17 00:00:00 2001 From: Yago Iglesias Date: Sat, 26 Aug 2023 18:17:09 +0200 Subject: [PATCH] feat: use random port instead of 8000 --- src/lib.rs | 5 +++-- src/main.rs | 5 ++++- tests/health_check.rs | 13 +++++++++---- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 3d51a3d..df91374 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,5 @@ use actix_web::{dev::Server, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; +use std::net::TcpListener; async fn greet(req: HttpRequest) -> impl Responder { let name = req.match_info().get("name").unwrap_or("World"); @@ -9,14 +10,14 @@ async fn health_check() -> impl Responder { HttpResponse::Ok() } -pub fn run() -> Result { +pub fn run(listener: TcpListener) -> Result { let server = HttpServer::new(|| { App::new() .route("/", web::get().to(greet)) .route("/health_check", web::get().to(health_check)) .route("/{name}", web::get().to(greet)) }) - .bind("127.0.0.1:8000")? + .listen(listener)? .run(); Ok(server) diff --git a/src/main.rs b/src/main.rs index 9bee6b8..87b5e07 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,9 @@ +use std::net::TcpListener; + use zero2prod::run; #[tokio::main] async fn main() -> Result<(), std::io::Error> { - run()?.await + let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port"); + run(listener)?.await } diff --git a/tests/health_check.rs b/tests/health_check.rs index bc575eb..5ef520a 100644 --- a/tests/health_check.rs +++ b/tests/health_check.rs @@ -1,16 +1,21 @@ -fn spawn_app() { - let server = zero2prod::run().expect("Failed to bind address"); +use std::net::TcpListener; + +fn spawn_app() -> String { + let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind random port"); + let port = listener.local_addr().unwrap().port(); + let server = zero2prod::run(listener).expect("Failed to bind address"); tokio::spawn(server); + format!("http://127.0.0.1:{port}") } #[tokio::test] async fn health_check_works() { // Arrange - spawn_app(); + let address = spawn_app(); // Act let client = reqwest::Client::new(); let response = client - .get("http://localhost:8000/health_check") + .get(format!("{address}/health_check")) .send() .await .expect("Failed to execute request.");