testcontainers / testcontainers-rs

A library for integration-testing against docker containers from within Rust.
https://rust.testcontainers.org
Apache License 2.0
697 stars 133 forks source link

Is there an alternative to the withInitScript method as in the Java implementation? #669

Closed oscles closed 2 months ago

oscles commented 2 months ago
static {
    postgreSQLContainer = new PostgreSQLContainer("postgres:9.6.8")
            .withDatabaseName("integration-tests-db")
            .withUsername("sa")
            .withPassword("sa");
    postgreSQLContainer
            .withInitScript("some/location/on/classpath/someScript.sql");
    postgreSQLContainer.start();
}
DDtKey commented 2 months ago

Hi @oscles 👋

I think with_mount + exec (or even with_cmd) might do the trick for you. Or creating a wrapper (e.g PostgresWithInitScript::new(script)) that executes your script against database using crate you wish (e.g sqlx or postgres) right after start of the container.

But this particular functionality is missing, at least for now.

oscles commented 2 months ago

Hi @oscles 👋

I think with_mount + exec (or even with_cmd) might do the trick for you. Or creating a wrapper (e.g PostgresWithInitScript::new(script)) that executes your script against database using crate you wish (e.g sqlx or postgres) right after start of the container.

But this particular functionality is missing, at least for now.

Thank you @DDtKey for the idea this was my implementation, I had to use a timer because it failed giving an error in the connection because it executed the code before the container was mounted.:

let container = GenericImage::new("postgres", "latest")
            .with_exposed_port(container_port)
            .with_env_var("POSTGRES_DB", "trans_national")
            .with_env_var("POSTGRES_USER", "trans_national")
            .with_env_var("POSTGRES_PASSWORD", "trans_national")
            .with_mount(Mount::bind_mount(host_path, "/docker-entrypoint-initdb.d"))
            .start()
            .await
            .unwrap();
DDtKey commented 2 months ago

WaitFor is only responsible for waiting conditions to be met (on application side, to allow using container) Did you try to use something other than timeout? It might be better to depend on log output, see the Postgres module example https://github.com/testcontainers/testcontainers-rs-modules-community/blob/484b23df4e540981f88b5b06fb14e93bcb4ab4bf/src/postgres/mod.rs#L86-L90

oscles commented 2 months ago

WaitFor is only responsible for waiting conditions to be met (on application side, to allow using container) Did you try to use something other than timeout? It might be better to depend on log output, see the Postgres module example https://github.com/testcontainers/testcontainers-rs-modules-community/blob/484b23df4e540981f88b5b06fb14e93bcb4ab4bf/src/postgres/mod.rs#L86-L90

Thank you