Skip to content

Commit 53b3869

Browse files
committed
feat(module/mongodb): Add support for initialization scripts
Running initialization scripts in MongoDB causes the container to restart, which previously required manual WaitStrategy adjustment. This commit adds 'withInitScript(String)' to automatically handle the script copy and adjust the WaitStrategy to expect two startup log messages. Fixes #3066
1 parent 15b9397 commit 53b3869

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

modules/mongodb/src/main/java/org/testcontainers/containers/MongoDBContainer.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,4 +223,26 @@ void withSharding() {
223223
setEntrypoint("sh");
224224
}
225225
}
226+
227+
/**
228+
* Executes a MongoDB initialization script from the classpath during startup.
229+
* <p>
230+
* The script will be copied to {@code /docker-entrypoint-initdb.d/init.js}.
231+
* This method also adjusts the {@link org.testcontainers.containers.wait.strategy.WaitStrategy}
232+
* to expect the "waiting for connections" log message twice, as the execution of an init script
233+
* causes MongoDB to restart.
234+
*
235+
* @param scriptPath the path to the init script file on the classpath
236+
* @return this container instance
237+
*/
238+
public MongoDBContainer withInitScript(String scriptPath) {
239+
withCopyFileToContainer(
240+
MountableFile.forClasspathResource(scriptPath),
241+
"/docker-entrypoint-initdb.d/init.js"
242+
);
243+
244+
this.waitStrategy = Wait.forLogMessage("(?i).*waiting for connections.*", 2);
245+
246+
return this;
247+
}
226248
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package org.testcontainers.containers;
2+
3+
import org.junit.jupiter.api.Test;
4+
import org.testcontainers.utility.MountableFile;
5+
6+
import java.time.Duration;
7+
8+
import static org.assertj.core.api.Assertions.assertThat;
9+
10+
class MongoDBInitScriptTest {
11+
12+
@Test
13+
void testWithInitScript() {
14+
// Start the container using try-with-resources to ensure it closes automatically
15+
try (MongoDBContainer mongoDB = new MongoDBContainer("mongo:4.0.10")
16+
// Configure the init script. This triggers a restart inside the container,
17+
// so the container must wait for the second "waiting for connections" log message.
18+
.withInitScript("init.js")
19+
.withStartupTimeout(Duration.ofSeconds(30))) {
20+
21+
mongoDB.start();
22+
23+
// Assert that the container started successfully
24+
assertThat(mongoDB.isRunning()).isTrue();
25+
}
26+
}
27+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
db.createCollection("test_collection");

0 commit comments

Comments
 (0)