gen isolated tables

This commit is contained in:
filipriec
2025-06-18 23:19:19 +02:00
parent e25213ed1b
commit 8414657224
2 changed files with 68 additions and 9 deletions

View File

@@ -1,24 +1,81 @@
// tests/table_definition/post_table_definition_test.rs
use crate::common::setup_isolated_db;
// Keep all your normal use statements
use common::proto::multieko2::table_definition::{
ColumnDefinition, PostTableDefinitionRequest, TableLink,
};
use rstest::{fixture, rstest};
use server::table_definition::handlers::post_table_definition;
use sqlx::{PgPool, Row};
use sqlx::{postgres::PgPoolOptions, Connection, Executor, PgConnection, PgPool, Row}; // Add PgConnection etc.
use tonic::Code;
// Add these two new use statements for the isolation logic
use rand::distr::Alphanumeric;
use rand::Rng;
use std::env;
use dotenvy;
use std::path::Path;
// ========= Fixtures =========
// ===================================================================
// SPECIALIZED SETUP FOR `table_definition` TESTS
// This setup logic is now local to this file and will not affect other tests.
// ===================================================================
async fn setup_isolated_gen_schema_db() -> PgPool {
// ---- ADD THIS BLOCK TO LOAD THE .env_test FILE ----
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");
dotenvy::from_path(env_path).ok();
// ----------------------------------------------------
let database_url = env::var("TEST_DATABASE_URL").expect("TEST_DATABASE_URL must be set");
let unique_schema_name = format!(
"test_{}",
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(12)
.map(char::from)
.collect::<String>()
);
let mut root_conn = PgConnection::connect(&database_url).await.unwrap();
root_conn
.execute(format!("CREATE SCHEMA \"{}\"", unique_schema_name).as_str())
.await
.unwrap();
let pool = PgPoolOptions::new()
.max_connections(5)
.after_connect(move |conn, _meta| {
let schema = unique_schema_name.clone();
Box::pin(async move {
conn.execute(format!("SET search_path = '{}'", schema).as_str())
.await?;
Ok(())
})
})
.connect(&database_url)
.await
.expect("Failed to create isolated pool");
sqlx::migrate!()
.run(&pool)
.await
.expect("Migrations failed in isolated schema");
sqlx::query!("INSERT INTO profiles (name) VALUES ('default') ON CONFLICT (name) DO NOTHING")
.execute(&pool)
.await
.expect("Failed to insert test profile in isolated schema");
pool
}
// ========= Fixtures for THIS FILE ONLY =========
/// THIS IS THE KEY CHANGE.
/// The `pool` fixture, which most of your tests already use,
/// will now provide a completely isolated database schema for every test.
#[fixture]
async fn pool() -> PgPool {
// Instead of the old setup, we call the new isolated setup.
setup_isolated_db().await
// This fixture now calls the LOCAL, SPECIALIZED setup function.
setup_isolated_gen_schema_db().await
}
#[fixture]