60 lines
1.8 KiB
Rust
60 lines
1.8 KiB
Rust
|
use once_cell::sync::Lazy;
|
||
|
use sqlx::PgPool;
|
||
|
use std::net::TcpListener;
|
||
|
use tracing::Level;
|
||
|
use whitelist_api::{
|
||
|
configuration::{get_configuration, AppConfig},
|
||
|
telemetry::{get_subscriber, init_subscriber},
|
||
|
};
|
||
|
|
||
|
static TRACING: Lazy<()> = Lazy::new(|| {
|
||
|
if std::env::var("TEST_LOG").is_ok() {
|
||
|
let subscriber = match std::env::var("TEST_LOG") {
|
||
|
Ok(log_level) => get_subscriber(
|
||
|
"test".into(),
|
||
|
log_level.to_lowercase().into(),
|
||
|
std::io::stdout,
|
||
|
),
|
||
|
Err(e) => {
|
||
|
tracing::error!("Failed to get log level from environment variable `TEST_LOG`! Error: {e}");
|
||
|
get_subscriber("test".into(), "debug".into(), std::io::stdout)
|
||
|
}
|
||
|
};
|
||
|
init_subscriber(subscriber);
|
||
|
} else {
|
||
|
let subscriber = get_subscriber("test".into(), "debug".into(), std::io::sink);
|
||
|
init_subscriber(subscriber);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
#[derive(Debug)]
|
||
|
pub struct TestApp {
|
||
|
pub address: String,
|
||
|
pub config: AppConfig,
|
||
|
pub client: reqwest::Client,
|
||
|
}
|
||
|
|
||
|
impl TestApp {
|
||
|
#[tracing::instrument(name = "Spawning test application" level = Level::DEBUG)]
|
||
|
pub async fn spawn(connection_pool: &PgPool) -> TestApp {
|
||
|
Lazy::force(&TRACING);
|
||
|
|
||
|
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port!");
|
||
|
let port = listener.local_addr().unwrap().port();
|
||
|
let address = format!("http://127.0.0.1:{}", port);
|
||
|
|
||
|
let configuration = get_configuration().expect("Failed to read configuration!");
|
||
|
|
||
|
let server =
|
||
|
whitelist_api::run(listener, connection_pool.clone()).expect("Failed to bind address!");
|
||
|
|
||
|
let _ = tokio::spawn(server);
|
||
|
|
||
|
TestApp {
|
||
|
address,
|
||
|
config: configuration.application,
|
||
|
client: reqwest::Client::new(),
|
||
|
}
|
||
|
}
|
||
|
}
|