2

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
alakhpc
  • 21
  • 3
  • did you happen to find a solution to this one? – Marcus Ilgner Jun 07 '22 at 21:11
  • 2
    You can't share pools. Create a new pool each time. I moved my seeding to another binary and now run cargo seed before testing in CI – alakhpc Jun 08 '22 at 22:13
  • Thank you! I hadn't used a Pool before, only a regular PgConnection. Now I have changed my constructor to create a Pool instead, using `connect_lazy` so it doesn't create any connection in that context. That way, the actual connection is only established in the context it's being used, too. – Marcus Ilgner Jun 09 '22 at 20:21

1 Answers1

0

is this question already resolve? I had same problem, then I find this issue: https://github.com/launchbadge/sqlx/issues/1869

please try, .test_before_acquire(true).

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 09 '22 at 01:52