-
-
Notifications
You must be signed in to change notification settings - Fork 251
Add support for MongoDBContainer credentials #1070
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cristianrgreco
merged 13 commits into
testcontainers:main
from
digital88:mongo-credentials
Jul 23, 2025
Merged
Changes from 5 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
31854b5
mongodb-container-2
digital88 7f47bef
fixed rs with credentials
digital88 cd717aa
fix tests in podman
digital88 cc8d765
Merge branch 'main' into mongo-credentials
digital88 0155eb4
Merge branch 'main' into mongo-credentials
digital88 e4db8df
Merge branch 'main' into fork/digital88/mongo-credentials
cristianrgreco 78a2e85
fixes after review
digital88 098d2fb
TC patch version up
digital88 4dd3ee4
fixed lockfile and test
digital88 747377b
Refactor tests + update docs
cristianrgreco 9d0a117
Refactor tests + update docs
cristianrgreco 4317a39
Fix docs
cristianrgreco 20086b1
Fix docs
cristianrgreco File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,68 +1,85 @@ | ||
| import { AbstractStartedContainer, ExecResult, GenericContainer, StartedTestContainer, Wait } from "testcontainers"; | ||
| import { satisfies } from "compare-versions"; | ||
| import { AbstractStartedContainer, GenericContainer, StartedTestContainer, Wait } from "testcontainers"; | ||
|
|
||
| const MONGODB_PORT = 27017; | ||
|
|
||
| export class MongoDBContainer extends GenericContainer { | ||
| private username = ""; | ||
| private password = ""; | ||
|
|
||
| constructor(image: string) { | ||
| super(image); | ||
| this.withExposedPorts(MONGODB_PORT) | ||
| .withCommand(["--replSet", "rs0"]) | ||
| .withWaitStrategy(Wait.forLogMessage(/.*waiting for connections.*/i)) | ||
| .withStartupTimeout(120_000); | ||
| } | ||
|
|
||
| public override async start(): Promise<StartedMongoDBContainer> { | ||
| return new StartedMongoDBContainer(await super.start()); | ||
| this.withExposedPorts(MONGODB_PORT).withStartupTimeout(120_000); | ||
| } | ||
|
|
||
| protected override async containerStarted(startedTestContainer: StartedTestContainer): Promise<void> { | ||
| await this.initReplicaSet(startedTestContainer); | ||
| public withUsername(username: string): this { | ||
| if (username === "") throw new Error("Username should not be empty."); | ||
| this.username = username; | ||
| return this; | ||
| } | ||
|
|
||
| private async initReplicaSet(startedTestContainer: StartedTestContainer) { | ||
| await this.executeMongoEvalCommand(startedTestContainer, "rs.initiate();"); | ||
| await this.executeMongoEvalCommand(startedTestContainer, this.buildMongoWaitCommand()); | ||
| public withPassword(password: string): this { | ||
| if (password === "") throw new Error("Password should not be empty."); | ||
| this.password = password; | ||
| return this; | ||
| } | ||
|
|
||
| private async executeMongoEvalCommand(startedTestContainer: StartedTestContainer, command: string) { | ||
| const execResult = await startedTestContainer.exec(this.buildMongoEvalCommand(command)); | ||
| this.checkMongoNodeExitCode(execResult); | ||
| public override async start(): Promise<StartedMongoDBContainer> { | ||
| const cmdArgs = ["--replSet", "rs0", "--bind_ip_all"]; | ||
digital88 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| this.withHealthCheck({ | ||
digital88 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| test: ["CMD-SHELL", this.buildMongoEvalCommand(this.initRsAndWait())], | ||
| interval: 250, | ||
| timeout: 60000, | ||
| retries: 1000, | ||
| }).withWaitStrategy(Wait.forHealthCheck()); | ||
| if (this.username && this.password) { | ||
| cmdArgs.push("--keyFile", "/data/db/key.txt"); | ||
| this.withEnvironment({ | ||
| MONGO_INITDB_ROOT_USERNAME: this.username, | ||
| MONGO_INITDB_ROOT_PASSWORD: this.password, | ||
| }) | ||
| .withCopyContentToContainer([ | ||
| { | ||
| content: "1111111111", | ||
| mode: 0o400, | ||
| target: "/data/db/key.txt", | ||
| }, | ||
| ]) | ||
| .withCommand(cmdArgs); | ||
| } else { | ||
| this.withCommand(cmdArgs); | ||
| } | ||
| return new StartedMongoDBContainer(await super.start(), this.username, this.password); | ||
| } | ||
|
|
||
| private buildMongoEvalCommand(command: string) { | ||
| return [this.getMongoCmdBasedOnImageTag(), "--eval", command]; | ||
| const useMongosh = satisfies(this.imageName.tag, ">=5.0.0"); | ||
| const args = []; | ||
| if (useMongosh) args.push("mongosh"); | ||
| else args.push("mongo", "admin"); | ||
| if (this.username && this.password) args.push("-u", this.username, "-p", this.password); | ||
| args.push("--host", "localhost", "--quiet", "--eval", command); | ||
digital88 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| return args.join(" "); | ||
| } | ||
|
|
||
| private getMongoCmdBasedOnImageTag() { | ||
| return parseInt(this.imageName.tag[0]) >= 5 ? "mongosh" : "mongo"; | ||
| } | ||
|
|
||
| private checkMongoNodeExitCode(execResult: ExecResult) { | ||
| const { exitCode, output } = execResult; | ||
| if (execResult.exitCode !== 0) { | ||
| throw new Error(`Error running mongo command. Exit code ${exitCode}: ${output}`); | ||
| } | ||
| } | ||
|
|
||
| private buildMongoWaitCommand() { | ||
| return ` | ||
| var attempt = 0; | ||
| while(db.runCommand({isMaster: 1}).ismaster==false) { | ||
| if (attempt > 60) { | ||
| quit(1); | ||
| } | ||
| print(attempt); sleep(100); attempt++; | ||
| } | ||
| `; | ||
| private initRsAndWait() { | ||
| return `'try { rs.initiate(); } catch (e){} while (db.runCommand({isMaster: 1}).ismaster==false) { sleep(100); }'`; | ||
| } | ||
| } | ||
|
|
||
| export class StartedMongoDBContainer extends AbstractStartedContainer { | ||
| constructor(startedTestContainer: StartedTestContainer) { | ||
| private readonly username: string = ""; | ||
| private readonly password: string = ""; | ||
|
|
||
| constructor(startedTestContainer: StartedTestContainer, username: string, password: string) { | ||
| super(startedTestContainer); | ||
| this.username = username; | ||
| this.password = password; | ||
| } | ||
|
|
||
| public getConnectionString(): string { | ||
| if (this.username && this.password) | ||
| return `mongodb://${this.username}:${this.password}@${this.getHost()}:${this.getMappedPort(MONGODB_PORT)}?authSource=admin`; | ||
| return `mongodb://${this.getHost()}:${this.getMappedPort(MONGODB_PORT)}`; | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.