【发布时间】:2022-08-05 13:14:00
【问题描述】:
我有一个带有 actix_web 的 API,我正在尝试为它编写一些测试。
我希望所有测试在 get_pool 函数重置时共享同一个池,然后将一些数据播种到数据库中。
测试不需要按顺序执行。 结构是这样的
src/tests/mod.rs
lazy_static! {
static ref DATABASE_URL: String = std::env::var(\"TEST_DATABASE_URL\").unwrap();
static ref POOL: Mutex<Option<Pool<Postgres>>> = Mutex::new(None);
}
pub async fn get_service() -> impl Service<Request, Response = ServiceResponse, Error = Error> {
dotenv().ok();
let pool = {
let mut pool = POOL.lock().unwrap();
if pool.is_none() {
*pool = Some(get_pool().await);
}
pool.clone().unwrap()
};
let state = AppState::new(pool).await;
test::init_service(App::new().configure(routes::init_routes).app_data(state)).await
}
#[actix_web::test]
pub async fn test_index() {
let app = get_service().await;
let req = test::TestRequest::get().uri(\"/\").to_request();
let resp = test::call_service(&app, req).await;
assert_eq!(resp.status().as_u16(), 200);
}
测试在 50% 的时间内成功完成,但有时会出错
error communicating with database: IO driver has terminated
如果我使用cargo test -- --test-threads=1,则不会发生这种情况。
完整代码可以是found here。
-
您是否碰巧找到了解决方案?
-
您不能共享池。每次创建一个新池。我将播种移至另一个二进制文件,现在在 CI 测试之前运行货物种子
-
谢谢!我以前没有使用过 Pool,只有一个普通的 PgConnection。现在我已经更改了我的构造函数以创建一个池,而是使用
connect_lazy,因此它不会在该上下文中创建任何连接。这样,实际连接也只在它被使用的上下文中建立。
标签: database postgresql rust actix-web rust-sqlx