Files
zero2prod/tests/api/helpers.rs
2025-08-24 11:31:03 +02:00

75 lines
2.2 KiB
Rust

use once_cell::sync::Lazy;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use uuid::Uuid;
use zero2prod::{
configuration::{DatabaseSettings, get_configuration},
startup::Application,
telemetry::init_subscriber,
};
static TRACING: Lazy<()> = Lazy::new(|| {
if std::env::var("TEST_LOG").is_ok() {
init_subscriber(std::io::stdout);
} else {
init_subscriber(std::io::sink);
}
});
pub struct TestApp {
pub address: String,
pub connection_pool: PgPool,
}
impl TestApp {
pub async fn spawn() -> Self {
Lazy::force(&TRACING);
let mut configuration = get_configuration().expect("Failed to read configuration");
configuration.database.database_name = Uuid::new_v4().to_string();
configuration.application.port = 0;
let connection_pool = configure_database(&configuration.database).await;
let application = Application::build(configuration)
.await
.expect("Failed to build application");
let address = application.address();
let app = TestApp {
address,
connection_pool,
};
tokio::spawn(application.run_until_stopped());
app
}
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
reqwest::Client::new()
.post(format!("http://{}/subscriptions", self.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request")
}
}
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_ref())
.await
.expect("Failed to create the database");
let connection_pool = PgPool::connect_with(config.with_db())
.await
.expect("Failed to connect to Postgres");
sqlx::migrate!("./migrations")
.run(&connection_pool)
.await
.expect("Failed to migrate the database");
connection_pool
}