Error communicating with database: IO driver has terminated

Viewed 137

I have an API with actix_web and I'm trying to write some tests for it.

I want all the tests to share the same pool as the get_pool function resets and then seeds some data into the db.

The tests do not need to be executed in order. The structure is something like this

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);
}

The tests finish successfully 50% of the time but sometimes error with

error communicating with database: IO driver has terminated

This does not happen if I use cargo test -- --test-threads=1.

The full code can be found here.

1 Answers
Related