test: add health check test

This commit is contained in:
2025-06-22 13:51:51 +03:00
parent 85765bb3b0
commit 813346a340
13 changed files with 715 additions and 34 deletions

View File

@@ -0,0 +1,17 @@
use crate::helpers::spawn_app;
use reqwest::Client;
#[tokio::test]
async fn health_check() {
let app = spawn_app().await;
let url = format!("{}/health_check", &app.addr);
let client = Client::new();
let response = client
.get(&url)
.send()
.await
.expect("Failed to execute request");
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}

View File

@@ -0,0 +1,85 @@
use once_cell::sync::Lazy;
use server::{
configuration::{DatabaseSettings, get_config},
startup::{Application, get_connection_pool},
telemetry::{get_subscriber, init_subscriber},
};
use sqlx::{Connection, Executor, PgConnection, PgPool};
use std::{env::current_dir, net::SocketAddr};
use uuid::Uuid;
static TRACING: Lazy<()> = Lazy::new(|| {
let default_filter_level = "trace";
let subscriber_name = "test";
if std::env::var("TEST_LOG").is_ok() {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::stdout);
init_subscriber(subscriber);
} else {
let subscriber = get_subscriber(default_filter_level, subscriber_name, std::io::sink);
init_subscriber(subscriber);
}
});
pub struct TestApp {
pub _pool: PgPool,
pub addr: SocketAddr,
}
pub async fn spawn_app() -> TestApp {
Lazy::force(&TRACING);
let config = {
let path = current_dir()
.expect("Failed to determine current directory")
.parent()
.map(|p| p.join("config"));
let mut c = get_config(path).expect("Failed to read configuration.");
c.database.database_name = Uuid::new_v4().to_string();
c.application.port = 0;
c
};
configure_database(&config.database).await;
let application = Application::build(&config)
.await
.expect("Failed to build application.");
let addr = application.addr();
let _ = tokio::spawn(application.start()).await;
TestApp {
_pool: get_connection_pool(&config.database),
addr,
}
}
async fn configure_database(config: &DatabaseSettings) -> PgPool {
let mut connection = PgConnection::connect_with(&config.without_db())
.await
.expect("Failed to connect to Postgres.");
connection
.execute(
format!(
r#"
CREATE DATABASE "{}"
"#,
config.database_name
)
.as_str(),
)
.await
.expect("Failed to create database.");
let pool = PgPool::connect_with(config.with_db())
.await
.expect("Failed to connect to Postgres.");
sqlx::migrate!("../migrations")
.run(&pool)
.await
.expect("Failed to migrate database");
pool
}

2
server/tests/api/main.rs Normal file
View File

@@ -0,0 +1,2 @@
mod health_check;
mod helpers;