mirror of
https://github.com/kristoferssolo/kristofersxyz-rs.git
synced 2025-10-21 20:10:36 +00:00
87 lines
2.3 KiB
Rust
87 lines
2.3 KiB
Rust
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);
|
|
}
|
|
});
|
|
|
|
#[derive(Debug)]
|
|
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();
|
|
|
|
tokio::spawn(application.start());
|
|
|
|
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
|
|
}
|