#![cfg(test)]
use std::sync::Arc;
use std::sync::OnceLock;
use dbnexus::{DbConfig, DbPool};
use tokio::sync::Mutex;
use testcontainers::core::IntoContainerPort;
use testcontainers::runners::AsyncRunner;
use testcontainers::ImageExt;
use testcontainers_modules::postgres::Postgres;
static TC_CONTAINER: OnceLock<testcontainers::ContainerAsync<Postgres>> = OnceLock::new();
static TC_URL: OnceLock<String> = OnceLock::new();
fn docker_available() -> bool {
std::process::Command::new("docker")
.arg("info")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn start_testcontainers_pg() -> String {
std::thread::scope(|s| {
let handle = s.spawn(|| {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("failed to build tokio runtime for testcontainers");
rt.block_on(async {
let image = Postgres::default().with_tag("16-alpine");
let container = image
.start()
.await
.expect("failed to start testcontainers PostgreSQL");
let port = container
.get_host_port_ipv4(5432.tcp())
.await
.expect("failed to get postgres port");
let url = format!("postgres://postgres:postgres@127.0.0.1:{port}/postgres");
use dbnexus::sea_orm::{ConnectOptions, ConnectionTrait, Database};
let mut opt = ConnectOptions::new(&url);
opt.sqlx_logging(false);
let conn = Database::connect(opt)
.await
.expect("failed to connect to testcontainers PostgreSQL for migration");
let migration_files = [
"migrations/postgres/001_initial_schema.sql",
"migrations/postgres/002_add_crawl_url_fields.sql",
"migrations/postgres/003_add_acquire_next_indexes.sql",
"migrations/postgres/004_drop_feature_flags.sql",
"migrations/postgres/005_deprecate_legacy_api_keys.sql",
"migrations/postgres/006_add_message_queue.sql",
"migrations/postgres/007_add_retention_indexes.sql",
"migrations/postgres/008_add_searxng_instances.sql",
"migrations/postgres/009_add_crawl_task_url_unique.sql",
];
for file in &migration_files {
let sql = std::fs::read_to_string(file)
.unwrap_or_else(|e| panic!("failed to read migration {file}: {e}"));
conn.execute_unprepared(&sql)
.await
.unwrap_or_else(|e| panic!("failed to run migration {file}: {e}"));
}
let _ = TC_CONTAINER.set(container);
eprintln!(
"[testcontainers] PostgreSQL started at 127.0.0.1:{} with migrations applied",
port
);
url
})
});
handle.join().expect("testcontainers thread panicked")
})
}
fn ensure_testcontainers_url() -> Option<&'static str> {
if !docker_available() {
return None;
}
TC_URL.get_or_init(start_testcontainers_pg);
TC_URL.get().map(|s| s.as_str())
}
pub fn resolve_test_database_url() -> Option<String> {
if let Ok(url) = std::env::var("TEST_DATABASE_URL") {
return Some(url);
}
if let Ok(url) = std::env::var("DATABASE_URL") {
return Some(url);
}
ensure_testcontainers_url().map(|s| s.to_string())
}
pub fn skip_if_no_test_db() -> bool {
if resolve_test_database_url().is_none() {
eprintln!(
"[skip] No test database available (TEST_DATABASE_URL not set and Docker unavailable)"
);
return true;
}
false
}
pub fn create_test_db_pool() -> Arc<DbPool> {
build_independent_test_db_pool()
}
pub fn build_independent_test_db_pool() -> Arc<DbPool> {
std::thread::scope(|s| {
let handle = s.spawn(|| {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("failed to build tokio runtime for DbPool construction");
let _guard = rt.enter();
let url = resolve_test_database_url().expect(
"No test database available: set TEST_DATABASE_URL or ensure Docker is running",
);
rt.block_on(async {
DbPool::with_config(DbConfig {
url,
pool_config: dbnexus::PoolConfig {
max_connections: TEST_POOL_MAX_CONNECTIONS,
min_connections: 0,
acquire_timeout: TEST_POOL_ACQUIRE_TIMEOUT_MS,
..dbnexus::PoolConfig::default()
},
..Default::default()
})
.await
})
.expect("failed to create DbPool for test")
});
Arc::new(handle.join().expect("DbPool construction thread panicked"))
})
}
const TEST_POOL_MAX_CONNECTIONS: u32 = 4;
const TEST_POOL_ACQUIRE_TIMEOUT_MS: u64 = 30_000;
pub fn acquire_next_test_mutex() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
#[cfg(feature = "auth")]
pub struct GarrisonGlobalStateGuard {
_dao_guard: tokio::sync::MutexGuard<'static, ()>,
_audit_guard: tokio::sync::MutexGuard<'static, ()>,
}
#[cfg(not(feature = "auth"))]
pub struct NoopGarrisonGuard;
#[cfg(feature = "auth")]
pub async fn acquire_garrison_global_state() -> GarrisonGlobalStateGuard {
let dao_guard = crate::infrastructure::auth::garrison_dao::test_mutex()
.lock()
.await;
crate::infrastructure::auth::garrison_dao::reset_garrison_dao_for_test();
let audit_guard = crate::infrastructure::auth::garrison_listener::test_mutex()
.lock()
.await;
crate::infrastructure::auth::garrison_listener::reset_audit_service_for_test();
GarrisonGlobalStateGuard {
_dao_guard: dao_guard,
_audit_guard: audit_guard,
}
}
#[cfg(not(feature = "auth"))]
pub async fn acquire_garrison_global_state() -> NoopGarrisonGuard {
NoopGarrisonGuard
}