57 lines
1.5 KiB
Rust
57 lines
1.5 KiB
Rust
// tests/common/mod.rs
|
|
use dotenvy;
|
|
use sqlx::{postgres::PgPoolOptions, PgPool};
|
|
use std::env;
|
|
use std::path::Path;
|
|
|
|
pub async fn setup_test_db() -> PgPool {
|
|
// Get path to server directory
|
|
let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set");
|
|
let env_path = Path::new(&manifest_dir).join(".env_test");
|
|
|
|
// Load environment variables
|
|
dotenvy::from_path(env_path).ok();
|
|
|
|
// Create connection pool
|
|
let database_url = env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set");
|
|
let pool = PgPoolOptions::new()
|
|
.max_connections(5)
|
|
.connect(&database_url)
|
|
.await
|
|
.expect("Failed to create pool");
|
|
|
|
// Run migrations
|
|
sqlx::migrate!()
|
|
.run(&pool)
|
|
.await
|
|
.expect("Migrations failed");
|
|
|
|
// Insert default profile if it doesn't exist
|
|
let profile = sqlx::query!(
|
|
r#"
|
|
INSERT INTO profiles (name)
|
|
VALUES ('default')
|
|
ON CONFLICT (name) DO NOTHING
|
|
RETURNING id
|
|
"#
|
|
)
|
|
.fetch_optional(&pool)
|
|
.await
|
|
.expect("Failed to insert test profile");
|
|
|
|
let profile_id = if let Some(profile) = profile {
|
|
profile.id
|
|
} else {
|
|
// If the profile already exists, fetch its ID
|
|
sqlx::query!(
|
|
"SELECT id FROM profiles WHERE name = 'default'"
|
|
)
|
|
.fetch_one(&pool)
|
|
.await
|
|
.expect("Failed to fetch default profile ID")
|
|
.id
|
|
};
|
|
|
|
pool
|
|
}
|