use sea_orm::Database; use erp_server_migration::MigratorTrait; use testcontainers_modules::postgres::Postgres; use testcontainers::runners::AsyncRunner; /// 测试数据库容器 — 启动真实 PostgreSQL 执行迁移后提供 DB 连接 pub struct TestDb { pub db: sea_orm::DatabaseConnection, _container: testcontainers::ContainerAsync, } impl TestDb { pub async fn new() -> Self { let postgres = Postgres::default() .with_db_name("erp_test") .with_user("test") .with_password("test"); let container = postgres .start() .await .expect("启动 PostgreSQL 容器失败"); let host_port = container .get_host_port_ipv4(5432) .await .expect("获取容器端口失败"); let url = format!("postgres://test:test@127.0.0.1:{}/erp_test", host_port); let db = Database::connect(&url) .await .expect("连接测试数据库失败"); // 运行所有迁移 erp_server_migration::Migrator::up(&db, None) .await .expect("执行数据库迁移失败"); Self { db, _container: container, } } }