How to use initReplicaSet method of org.testcontainers.containers.MongoDBContainer class

Best Testcontainers-java code snippet using org.testcontainers.containers.MongoDBContainer.initReplicaSet

Source:MongoDbContainer.java Github

copy

Full Screen

...36 }37 @Override38 protected void containerIsStarted(InspectContainerResponse containerInfo) {39 try {40 initReplicaSet();41 }42 catch (Exception e) {43 e.printStackTrace();44 throw new RuntimeException(e);45 }46 }47 private String[] buildMongoEvalCommand(final String command) {48 if (Arrays.asList(getCommandParts()).contains("--auth")) {49 Map<String, String> envMap = getEnvMap();50 String username = envMap.getOrDefault("MONGO_INITDB_ROOT_USERNAME", "admin");51 String password = envMap.getOrDefault("MONGO_INITDB_ROOT_PASSWORD", "admin");52 return new String[]{"mongo", "-u", username, "-p", password, "--eval", command};53 }54 else {55 return new String[]{"mongo", "--eval", command};56 }57 }58 private void checkMongoNodeExitCode(final Container.ExecResult execResult) {59 if (execResult.getExitCode() != CONTAINER_EXIT_CODE_OK) {60 final String errorMessage = String.format("An error occurred: %s\n%s", execResult.getStdout(), execResult.getStderr());61 LOGGER.error(errorMessage);62 throw new ReplicaSetInitializationException(errorMessage);63 }64 }65 private String buildMongoWaitCommand() {66 return String.format(67 "var attempt = 0; " +68 "while (%s) " +69 "{ " +70 "if (attempt > %d) {quit(1);} " +71 "print('%s ' + attempt); sleep(100); attempt++; " +72 " }",73 "db.runCommand( { isMaster: 1 } ).ismaster==false",74 AWAIT_INIT_REPLICA_SET_ATTEMPTS,75 "An attempt to await for a single node replica set initialization:"76 );77 }78 private void checkMongoNodeExitCodeAfterWaiting(79 final Container.ExecResult execResultWaitForMaster80 ) {81 if (execResultWaitForMaster.getExitCode() != CONTAINER_EXIT_CODE_OK) {82 final String errorMessage = String.format(83 "A single node replica set was not initialized in a set timeout: %d attempts",84 AWAIT_INIT_REPLICA_SET_ATTEMPTS85 );86 LOGGER.error(errorMessage);87 throw new ReplicaSetInitializationException(errorMessage);88 }89 }90 private void initReplicaSet() throws IOException, InterruptedException {91 LOGGER.debug("Initializing a single node replica set...");92 final ExecResult execResultInitRs = execInContainer(buildMongoEvalCommand("rs.initiate();"));93 LOGGER.debug(execResultInitRs.getStdout());94 checkMongoNodeExitCode(execResultInitRs);95 LOGGER.debug(96 "Awaiting for a single node replica set initialization up to {} attempts",97 AWAIT_INIT_REPLICA_SET_ATTEMPTS98 );99 final ExecResult execResultWaitForMaster = execInContainer(100 buildMongoEvalCommand(buildMongoWaitCommand())101 );102 LOGGER.debug(execResultWaitForMaster.getStdout());103 checkMongoNodeExitCodeAfterWaiting(execResultWaitForMaster);104 }...

Full Screen

Full Screen

initReplicaSet

Using AI Code Generation

copy

Full Screen

1 import org.testcontainers.containers.MongoDBContainer2 import org.testcontainers.utility.DockerImageName3 def mongoDbContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.4.0"))4 mongoDbContainer.start()5 mongoDbContainer.initReplicaSet()6 mongoDbContainer.stop()7[Image] [GitHub](github.com/testcontainers/test...) 8### [testcontainers/testcontainers-java](github.com/testcontainers/test...)9[Image] [GitHub](github.com/testcontainers/test...) 10### [testcontainers/testcontainers-java](github.com/testcontainers/test...)11[Image] [GitHub](github.com/testcontainers/test...) 12### [testcontainers/testcontainers-java](github.com/testcontainers/test...)

Full Screen

Full Screen

initReplicaSet

Using AI Code Generation

copy

Full Screen

1The MongoDBContainer class has a constructor that takes a Docker image name as a parameter. This class also has a static method getDefaultImage() that returns the default Docker image name. So, you can use the following code to create a MongoDBContainer object:2MongoDBContainer mongo = new MongoDBContainer(3 MongoDBContainer.getDefaultImage());4The following code shows how to use the start() method of the MongoDBContainer class to start a MongoDB container:5mongo.start();6The following code shows how to use the getReplicaSetUrl() method of the MongoDBContainer class to get the replica set URL:7String replicaSetUrl = mongo.getReplicaSetUrl();8The following code shows how to use the getShardUrl() method of the MongoDBContainer class to get the shard URL:9String shardUrl = mongo.getShardUrl();10The following code shows how to use the getDatabaseName() method of the MongoDBContainer class to get the database name:11String databaseName = mongo.getDatabaseName();12The following code shows how to use the getReplicaSetName() method of the MongoDBContainer class to get the replica set name:13String replicaSetName = mongo.getReplicaSetName();14The following code shows how to use the getShardName() method of the MongoDBContainer class to get the shard name:15String shardName = mongo.getShardName();16The following code shows how to use the getUsername() method of the MongoDBContainer class to get the username:17String username = mongo.getUsername();18The following code shows how to use the getPassword() method of the MongoDBContainer class to get the password:19String password = mongo.getPassword();20The following code shows how to use the getMongoClient() method of the MongoDBContainer class to get the MongoDB client:

Full Screen

Full Screen

initReplicaSet

Using AI Code Generation

copy

Full Screen

1import org.testcontainers.containers.MongoDBContainer2import org.testcontainers.containers.wait.strategy.Wait3import org.testcontainers.utility.DockerImageName4import java.time.Duration5val mongoDBContainer = MongoDBContainer(DockerImageName.parse("mongo:4.4.4"))6mongoDBContainer.waitingFor(Wait.forLogMessage(".*waiting for connections on port.*", 1))7mongoDBContainer.start()8mongoDBContainer.initReplicaSet()9println(mongoDBContainer.replicaSetStatus)10mongoDBContainer.stop()

Full Screen

Full Screen

initReplicaSet

Using AI Code Generation

copy

Full Screen

1 public void testReplicaSet() {2 MongoDBContainer container = new MongoDBContainer()3 .withInitScript("init.js")4 .withReplicaSet("test_rs");5 container.start();6 MongoClient mongoClient = MongoClients.create(container.getReplicaSetUrl());7 MongoDatabase db = mongoClient.getDatabase("test");8 MongoCollection<Document> collection = db.getCollection("test");9 collection.insertOne(new Document("test", "test"));10 assertThat(collection.countDocuments()).isEqualTo(1);11 container.stop();12 }13}

Full Screen

Full Screen

initReplicaSet

Using AI Code Generation

copy

Full Screen

1public class MongoDbContainerTest {2 private static final String MONGO_DB_IMAGE = "mongo:4.0.0";3 private static final String MONGO_DB_INIT_SCRIPT = "init-mongo.js";4 public static MongoDBContainer mongoDBContainer = new MongoDBContainer(MONGO_DB_IMAGE)5 .withInitScript(MONGO_DB_INIT_SCRIPT);6 public void testMongoDb() {7 MongoClient mongoClient = new MongoClient(mongoDBContainer.getContainerIpAddress(), mongoDBContainer.getFirstMappedPort());8 MongoDatabase db = mongoClient.getDatabase("test");9 MongoCollection<Document> collection = db.getCollection("test");10 Document document = new Document();11 document.put("name", "test");12 collection.insertOne(document);13 Document result = collection.find().first();14 assertNotNull(result);15 assertEquals("test", result.get("name"));16 }17}18rs.initiate({19 { _id: 0, host : "localhost:27017" }20});21public class MongoDbContainerTest {22 private static final String MONGO_DB_IMAGE = "mongo:4.0.0";23 public static MongoDBContainer mongoDBContainer = new MongoDBContainer(MONGO_DB_IMAGE)24 .initReplicaSet();25 public void testMongoDb() {26 MongoClient mongoClient = new MongoClient(mongoDBContainer.getContainerIpAddress(), mongoDBContainer.getFirstMappedPort());27 MongoDatabase db = mongoClient.getDatabase("test");28 MongoCollection<Document> collection = db.getCollection("test");29 Document document = new Document();30 document.put("name", "test");31 collection.insertOne(document);32 Document result = collection.find().first();33 assertNotNull(result);34 assertEquals("test", result.get("name"));35 }36}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-java automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful