test-context icon indicating copy to clipboard operation
test-context copied to clipboard

lifetime error in async context

Open alextes opened this issue 9 months ago • 1 comments

error[E0195]: lifetime parameters or bounds on associated function `setup` do not match the trait declaration
  --> src/db.rs:58:18
   |
58 |         async fn setup() -> TestDb {
   |                  ^^^^^^^ lifetimes do not match associated function in trait

error[E0195]: lifetime parameters or bounds on method `teardown` do not match the trait declaration
  --> src/db.rs:62:18
   |
62 |         async fn teardown(self) {
   |                  ^^^^^^^^^^^^^^ lifetimes do not match method in trait

For more information about this error, try `rustc --explain E0195`.
error: could not compile `eth-analysis` (lib test) due to 2 previous errors

maybe something in the PgPool that trips it up. v0.1.6 works fine, but 0.2, 0.3, 0.4 all fail.

full code:

pub struct TestDb {
        pub pool: PgPool,
        name: String,
    }

    #[async_trait]
    impl AsyncTestContext for TestDb {
        async fn setup() -> TestDb {
            TestDb::new().await
        }

        async fn teardown(self) {
            self.pool.close().await;
            let mut connection = get_test_db_connection().await;
            sqlx::query(&format!("DROP DATABASE {}", self.name))
                .execute(&mut connection)
                .await
                .unwrap();
        }
    }

    impl TestDb {
        pub async fn new() -> Self {
            let name = format!("testdb_{}", nanoid!(10, &ALPHABET));

            let mut connection = get_test_db_connection().await;
            sqlx::query(&format!("CREATE DATABASE {name}"))
                .execute(&mut connection)
                .await
                .unwrap();

            let pool = PgPoolOptions::new()
                .max_connections(1)
                .connect(&ENV_CONFIG.db_url.replace("testdb", &name))
                .await
                .unwrap();

            sqlx::migrate!("./migrations").run(&pool).await.unwrap();

            Self { pool, name }
        }
    }

alextes avatar May 11 '25 16:05 alextes

Can you give me some more details? What library are you using and what version of it? I understand it's sqlx? Then, it might be that the PgPool is implemented using some tricky references with tricky lifetimes and its somehow not fully owning itself, which sounds weird by itself already mh

JasterV avatar May 15 '25 09:05 JasterV

I just spent quite some time on this, fixed it and now accidentally stumble upon this issue. For me, removing #[async_trait] solved the issue.

b-kamphorst avatar Jul 04 '25 11:07 b-kamphorst

🙈 ty ty

alextes avatar Jul 04 '25 11:07 alextes