pub async fn create_client_and_postgres<State>(
    state: State,
    setup_routes_fns: impl Into<VariadicRoutes<State>>
) -> TestResult<(Client, Arc<RwLock<ConnectionWrapInner<Postgres>>>)> where
    State: Send + Sync + 'static, 
This is supported on crate feature postgres only.
Expand description

Creates a test application with routes and mocks set up, and hands back a client which is already connected to the server.

This function also hands back a postgres transaction connection which is being used for the rest of the application, allowing easy rollback of everything.

Default database

By default, preroll’s postgres test functionality will try to connect to a database on localhost with a name matching {crate_name}-test, on the default postgres port 5432.

If necessary, the following env variable overrides are available:

  • TEST_DATABASE_HOST: Set the test database hostname.
  • TEST_DATABASE_PORT: Set the test database port.
  • TEST_DATABASE_NAME: Set the test database name.

If the crate name cannot be found from CARGO_PKG_NAME, then the name database_test will be used.

Important!

The RwLockWriteGuard returned from pg_conn.write().await MUST be dropped before running the test cases, or else there will be a writer conflict and the test will hang indefinitely.

Example:

use preroll::test_utils::{self, TestResult};

pub fn setup_routes(mut server: tide::Route<'_, std::sync::Arc<()>>) {
  // Normally imported from your service's crate (lib.rs).
}

#[async_std::main] // Would be #[async_std::test] instead.
async fn main() -> TestResult<()> {
    let (client, pg_conn) = test_utils::create_client_and_postgres((), setup_routes).await.unwrap();

    {
        let mut pg_conn = pg_conn.write().await;

        // ... (test setup) ...

        // The RwLockWriteGuard here MUST be dropped before running the test cases,
        // or else there is a writer conflict and the test hangs indefinitely.
        //
        // Note: this is done automatically at the end of the closure.
        // We are still explicitly dropping so as to avoid accidentally messing this up in the future.
        std::mem::drop(pg_conn);
    }

    // ... (test cases) ...

    Ok(())
}