Skip to content

Commit

Permalink
feat: use random port instead of 8000
Browse files Browse the repository at this point in the history
  • Loading branch information
Yag000 committed Aug 26, 2023
1 parent 6b08233 commit 636e421
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -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");
Expand All @@ -9,14 +10,14 @@ async fn health_check() -> impl Responder {
HttpResponse::Ok()
}

pub fn run() -> Result<Server, std::io::Error> {
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
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)
Expand Down
5 changes: 4 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -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
}
13 changes: 9 additions & 4 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -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.");
Expand Down

0 comments on commit 636e421

Please sign in to comment.