Skip to content

Commit

Permalink
Bind the server to a random port in tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Mulder90 committed Feb 11, 2024
1 parent 6db3f96 commit 395a87f
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
6 changes: 4 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use std::net::TcpListener;

use actix_web::{dev::Server, web, App, HttpResponse, HttpServer, Responder};

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("/health_check", web::get().to(health_check)))
.bind("127.0.0.1:8000")?
.listen(listener)?
.run();
Ok(server)
}
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:8000").expect("Failed to bind address");
run(listener)?.await
}
14 changes: 9 additions & 5 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
use std::net::TcpListener;

#[tokio::test]
async fn health_check_works() {
// Arrange
spawn_app();

let address = spawn_app();
let client = reqwest::Client::new();

// Act
let response = client
.get("http://127.0.0.1:8000/health_check")
.get(&format!("{}/health_check", &address))
.send()
.await
.expect("Faied to execute request.");
Expand All @@ -17,7 +18,10 @@ async fn health_check_works() {
assert_eq!(Some(0), response.content_length());
}

fn spawn_app() {
let server = zero2prod::run().expect("Failder to bind address");
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("Failder to bind address");
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}

0 comments on commit 395a87f

Please sign in to comment.