sharenet/backend/crates/postgres/tests/integration_test_setup.rs

43 lines
No EOL
1.2 KiB
Rust

/*
* This file is part of Sharenet.
*
* Sharenet is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
*
* You may obtain a copy of the license at:
* https://creativecommons.org/licenses/by-nc-sa/4.0/
*
* Copyright (c) 2024 Continuist <continuist02@gmail.com>
*/
use sqlx::PgPool;
use sqlx::postgres::PgPoolOptions;
use std::env;
pub async fn setup_test_database() -> PgPool {
let database_url = env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres:postgres@localhost:5432/sharenet_test".to_string());
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("Failed to connect to test database");
// Run migrations
sqlx::migrate!("../../migrations")
.run(&pool)
.await
.expect("Failed to run migrations");
pool
}
pub async fn cleanup_test_data(pool: &PgPool) {
sqlx::query("DELETE FROM products").execute(pool).await.ok();
sqlx::query("DELETE FROM users").execute(pool).await.ok();
}
pub fn get_test_database_url() -> String {
env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres:postgres@localhost:5432/sharenet_test".to_string())
}