Home > Back-end >  testcontainers mysql DB failed when population DB
testcontainers mysql DB failed when population DB

Time:01-21

I am trying to run integration tests with testcontainers. Lunch the testconiners with follow properties:

 MySQLContainer database = (MySQLContainer) new MySQLContainer("mysql:8.0.27")
                .withUsername("test")
                .withPassword("test")
                .withEnv("MYSQL_ROOT_PASSWORD", "test")
                .withReuse(true);
        database.withInitScript("init.sql");
        database.start();

but it fails when run the script: Access denied for user 'test'@'%' to database 'test_scheme'

the init.sql script contains command for creating several DB

CREATE SCHEMA IF NOT EXISTS test_scheme
CREATE SCHEMA IF NOT EXISTS onothere_scheme

CodePudding user response:

Judging by the error message, you are connecting as user 'test', not 'root'. In that case you will have to add something like this to your init script:

GRANT ALL PRIVILEGES ON test_scheme.* TO 'test'@'%'

Since you are only using this for testing purposes, granting all privileges should be fine. Of course you could reduce this if you want to enable only read access, for instance.

You could also avoid this completely by connecting as the root user, who has access to all schemas by default.

CodePudding user response:

The below works:

@Test
public void testExplicitInitScript() throws Exception {
    try (MySQLContainer<?> container = new MySQLContainer<>(DockerImageName.parse("mysql:8.0.24"))
            .withUsername("root").withPassword("")
            .withInitScript("init_mysql.sql")
            .withLogConsumer(new Slf4jLogConsumer(log))) {
        container.start();

    }
}

src/test/resources/init_mysql.sql

CREATE SCHEMA IF NOT EXISTS test_scheme
CREATE SCHEMA IF NOT EXISTS onothere_scheme
  •  Tags:  
  • Related