test: refactor tests

This commit is contained in:
Kristofers Solo
2024-03-23 14:33:46 +02:00
parent c79eca74ee
commit ff20460c13
5 changed files with 16 additions and 38 deletions

View File

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