【问题标题】:Error communicating with database: IO driver has terminated与数据库通信时出错:IO 驱动程序已终止
【发布时间】: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


【解决方案1】:

这个问题已经解决了吗? 我有同样的问题,然后我发现了这个问题:https://github.com/launchbadge/sqlx/issues/1869

请尝试,.test_before_acquire(true)

【讨论】:

    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多