Skip to content

Conversation

@mdelapenya
Copy link
Member

  • chore(inbucket): use Run function
  • chore(influxdb): use Run function
  • chore(mongodb): use Run function
  • chore(k3s): use Run function

What does this PR do?

Use the Run function in Inbucket, Influxdb, MongoDB and K3s modules

Why is it important?

Migrate modules to the new API

Related issues

mdelapenya and others added 4 commits October 3, 2025 18:18
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@mdelapenya mdelapenya requested a review from a team as a code owner October 6, 2025 17:34
@mdelapenya mdelapenya added the chore Changes that do not impact the existing functionality label Oct 6, 2025
@mdelapenya mdelapenya self-assigned this Oct 6, 2025
@netlify
Copy link

netlify bot commented Oct 6, 2025

Deploy Preview for testcontainers-go ready!

Name Link
🔨 Latest commit 687c1b8
🔍 Latest deploy log https://app.netlify.com/projects/testcontainers-go/deploys/68e406ef7e8aca0008d5c759
😎 Deploy Preview https://deploy-preview-3413--testcontainers-go.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link

coderabbitai bot commented Oct 6, 2025

Summary by CodeRabbit

  • New Features
    • More reliable startup with enhanced health checks and consolidated configuration across Inbucket, InfluxDB, K3s, and MongoDB.
    • MongoDB now auto-populates credentials from environment and improves replica set initialization.
  • Refactor
    • Unified container startup to a modular options approach for consistent behavior and simpler customization.
  • Improvements
    • Clearer, service-specific error messages during startup.
    • Minor command/flag formatting correction for K3s to improve TLS SAN handling.
  • Compatibility
    • No breaking changes to primary public interfaces; existing usage should continue to work.

Walkthrough

Replaces per-module ContainerRequest/GenericContainer construction with composed testcontainers.ContainerCustomizer options passed to testcontainers.Run for inbucket, influxdb, k3s, and mongodb; MongoDB additionally moves auth/replica-set setup to option-based customizers with post-run inspection and deferred initialization. (42 words)

Changes

Cohort / File(s) Summary
Option-based Run migration
modules/inbucket/inbucket.go, modules/influxdb/influxdb.go, modules/k3s/k3s.go
Replace manual ContainerRequest/GenericContainer construction with a slice of testcontainers.ContainerCustomizer (WithExposedPorts/WithEnv/WithWaitStrategy/etc.), append incoming opts, and call testcontainers.Run(ctx, img, moduleOpts...). Update error messages to “run : %w”.
InfluxDB option helpers
modules/influxdb/influxdb.go
Convert per-field customization helpers (WithUsername/WithPassword/WithDatabase/WithConfigFile, withV2 variants, WithInitDb) to return testcontainers.WithEnv/WithFiles/WithAdditionalWaitStrategy instead of mutating a ContainerRequest.
MongoDB refactor & deferred replica-set
modules/mongodb/mongodb.go
Migrate Run to compose testcontainers options and call Run; convert env/file/entrypoint/command mutations to WithEnv/WithFiles/WithCmdArgs/WithEntrypoint; introduce deferred replica-set/configure options, post-run inspection for credentials/state, and improved error wrapping.
Run API adoption in k3s/inbucket
modules/k3s/k3s.go, modules/inbucket/inbucket.go
Compose HostConfig/Env/Cmd/WaitStrategy via moduleOpts, remove static ContainerRequest, and call testcontainers.Run. Minor command formatting fix (TLS SAN flag spacing).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as Caller
  participant M as Module (inbucket/influxdb/k3s)
  participant TC as testcontainers.Run
  participant C as Container

  U->>M: Run(ctx, img, opts...)
  M->>M: Build moduleOpts (WithExposedPorts/WithEnv/WithWaitStrategy + opts)
  M->>TC: Run(ctx, img, moduleOpts...)
  TC-->>C: Create & start container
  C-->>M: Return container handle
  M-->>U: Return wrapper
Loading
sequenceDiagram
  autonumber
  actor U as Caller
  participant MM as MongoDB Module
  participant TC as testcontainers.Run
  participant C as Container
  participant I as Inspect

  U->>MM: Run(ctx, img, opts...)
  MM->>MM: Compose moduleOpts (env/auth/entrypoint/replica-set customizers)
  MM->>TC: Run(ctx, img, moduleOpts...)
  TC-->>C: Container ready (wait strategies satisfied)
  MM->>I: Inspect container for env/credentials/state
  I-->>MM: Derived credentials/state
  alt Replica set requested
    MM->>C: Trigger deferred replica-set init (via option/lifecycle)
    C-->>MM: Replica state updated
  end
  MM-->>U: Return MongoDB wrapper
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • stevenh

Poem

A rabbit taps the docker drum, hop-run, hop-run 🥕
Options stitched like clover leaves, one by one.
Ports pop open, waits align, neat and bright,
Mongo nods, replicas wake under moonlight.
I nudge “Run” with a whisker — containers done.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 69.23% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed The title follows conventional commit style and clearly indicates that the PR updates the inbucket, influxdb, mongodb, and k3s modules to use the new Run function API.
Description Check ✅ Passed The description outlines the modules updated, summarizes the changes to use the Run function, and states the rationale for migrating to the new API, which aligns with the changeset.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 140f71a and 687c1b8.

📒 Files selected for processing (1)
  • modules/influxdb/influxdb.go (9 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
modules/influxdb/influxdb.go (4)
options.go (7)
  • ContainerCustomizer (22-24)
  • WithExposedPorts (454-459)
  • WithEnv (75-85)
  • WithWaitStrategy (366-368)
  • CustomizeRequestOption (28-28)
  • WithFiles (524-529)
  • WithAdditionalWaitStrategy (371-373)
modules/inbucket/inbucket.go (1)
  • Run (38-60)
container.go (2)
  • Container (41-73)
  • ContainerFile (110-115)
generic.go (1)
  • GenericContainerRequest (21-27)
🔇 Additional comments (11)
modules/influxdb/influxdb.go (11)

30-56: LGTM! Clean migration to the Run-based API.

The refactor successfully replaces manual GenericContainerRequest construction with composed options. The pattern matches the established approach in other modules (e.g., inbucket), ensuring consistency across the codebase. Default configuration is properly layered before user options, allowing overrides as needed.


72-88: LGTM! Option functions properly refactored.

These functions correctly use testcontainers.WithEnv to compose environment configuration declaratively rather than mutating the request directly.


90-96: LGTM! Proper use of WithFiles API.

The function correctly uses testcontainers.WithFiles to compose file configuration, replacing direct field mutation.


99-113: LGTM! Proper validation and composition.

The helper validates required parameters before applying configuration via WithEnv. This maintains safety while adapting to the new option-based pattern.


116-120: LGTM! Clean wrapper.


130-155: LGTM! Proper conflict detection.

The function correctly validates inputs, detects conflicting secret-based options, and composes configuration via WithEnv. The check at lines 145–148 is safe because withV2 initializes req.Env, and reading from nil maps in Go returns zero values without panicking.


158-183: LGTM! Safe conflict detection.

The function checks for conflicting direct-auth options before calling withV2. Although req.Env might be nil at line 168, reading from a nil map in Go safely returns the zero value, so the check evaluates correctly.


186-196: LGTM! Proper validation and composition.


199-213: LGTM! Conflict detection implemented correctly.


216-230: LGTM! Conflict detection works as intended.


236-251: LGTM! Proper composition of file copying and wait strategies.

The function correctly uses WithFiles to stage initialization scripts and WithAdditionalWaitStrategy to layer additional health checks on top of the base wait strategy.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
modules/influxdb/influxdb.go (2)

254-258: Don’t clobber existing wait strategies in WithInitDb

WithInitDb overwrites req.WaitingFor, dropping any waits set earlier (including user-supplied ones). Compose with the existing strategy instead.

Apply:

- req.WaitingFor = wait.ForAll(
-   wait.ForLog("Server shutdown completed"),
-   waitForHTTPHealth(),
- )
+ req.WaitingFor = wait.ForAll(
+   req.WaitingFor,
+   wait.ForLog("Server shutdown completed"),
+   waitForHTTPHealth(),
+ )

72-91: Prevent potential nil map writes in env helper options

Helpers (WithUsername/WithPassword/WithDatabase) assign to req.Env without ensuring it’s initialized. Guard req.Env to avoid panics if these are used without a preceding WithEnv.

Example fix:

 return func(req *testcontainers.GenericContainerRequest) error {
-  req.Env["INFLUXDB_USER"] = username
+  if req.Env == nil {
+    req.Env = map[string]string{}
+  }
+  req.Env["INFLUXDB_USER"] = username
   return nil
 }

Apply similarly to password and database helpers.

Also applies to: 79-84

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 924dab6 and 1ace0ec.

📒 Files selected for processing (4)
  • modules/inbucket/inbucket.go (1 hunks)
  • modules/influxdb/influxdb.go (1 hunks)
  • modules/k3s/k3s.go (1 hunks)
  • modules/mongodb/mongodb.go (5 hunks)
🧰 Additional context used
🧬 Code graph analysis (4)
modules/influxdb/influxdb.go (3)
options.go (4)
  • ContainerCustomizer (22-24)
  • WithExposedPorts (454-459)
  • WithEnv (75-85)
  • WithWaitStrategy (366-368)
modules/k3s/k3s.go (1)
  • Run (58-99)
modules/inbucket/inbucket.go (1)
  • Run (38-60)
modules/inbucket/inbucket.go (3)
options.go (3)
  • ContainerCustomizer (22-24)
  • WithExposedPorts (454-459)
  • WithWaitStrategy (366-368)
wait/host_port.go (1)
  • ForListeningPort (67-69)
modules/k3s/k3s.go (1)
  • Run (58-99)
modules/mongodb/mongodb.go (3)
options.go (8)
  • WithExposedPorts (454-459)
  • WithWaitStrategy (366-368)
  • WithEnv (75-85)
  • CustomizeRequestOption (28-28)
  • WithFiles (524-529)
  • WithEntrypoint (438-443)
  • WithCmdArgs (470-475)
  • WithAdditionalLifecycleHooks (497-502)
container.go (2)
  • Container (41-73)
  • ContainerFile (110-115)
lifecycle.go (2)
  • ContainerLifecycleHooks (43-55)
  • ContainerHook (38-38)
modules/k3s/k3s.go (3)
options.go (6)
  • ContainerCustomizer (22-24)
  • WithExposedPorts (454-459)
  • WithHostConfigModifier (88-94)
  • WithCmd (462-467)
  • WithEnv (75-85)
  • WithWaitStrategy (366-368)
modules/inbucket/inbucket.go (1)
  • Run (38-60)
generic.go (1)
  • Run (122-149)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: lint (modules/k3s) / lint: modules/k3s
  • GitHub Check: Analyze (go)
🔇 Additional comments (5)
modules/inbucket/inbucket.go (1)

39-50: Migration to Run() looks correct

Ports and waits are set appropriately, and user options are appended after module defaults. Error wrapping is consistent.

Also applies to: 55-57

modules/influxdb/influxdb.go (1)

31-46: Run() migration LGTM

Options assembly, waits, and error context look good. Health check strategy matches v1.8 /health behavior.

Also applies to: 51-53

modules/k3s/k3s.go (1)

64-96: Run()-based initialization looks solid

Privileged host config, cmd/env, waits, and option composition are correct. Error context updated appropriately.

modules/mongodb/mongodb.go (2)

43-50: Run() migration and post‑run env refresh look good

Option composition, waits, and error contexts are consistent. Post‑run inspect to populate credentials/replicaSet is a nice touch.

Also applies to: 52-65


75-84: go.mod version OK for strings.CutPrefix
go.mod specifies go 1.24.0, which meets the ≥1.20 requirement for strings.CutPrefix.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
modules/influxdb/influxdb.go (1)

115-125: Simplify the error handling.

The error check and return can be simplified by directly returning the result of withV2.

Apply this diff:

 func WithV2(org, bucket string) testcontainers.CustomizeRequestOption {
 	return func(req *testcontainers.GenericContainerRequest) error {
-		err := withV2(req, org, bucket)
-		if err != nil {
-			return err
-		}
-
-		return nil
+		return withV2(req, org, bucket)
 	}
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ace0ec and 140f71a.

📒 Files selected for processing (1)
  • modules/influxdb/influxdb.go (9 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
modules/influxdb/influxdb.go (1)
options.go (7)
  • ContainerCustomizer (22-24)
  • WithExposedPorts (454-459)
  • WithEnv (75-85)
  • WithWaitStrategy (366-368)
  • CustomizeRequestOption (28-28)
  • WithFiles (524-529)
  • WithAdditionalWaitStrategy (371-373)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: test (1.24.x, modules/inbucket) / test: modules/inbucket/1.24.x
  • GitHub Check: test (1.24.x, modules/k3s) / test: modules/k3s/1.24.x
  • GitHub Check: test (1.25.x, modules/k3s) / test: modules/k3s/1.25.x
  • GitHub Check: test (1.24.x, modules/mongodb) / test: modules/mongodb/1.24.x
  • GitHub Check: test (1.24.x, modules/influxdb) / test: modules/influxdb/1.24.x
  • GitHub Check: Analyze (go)
🔇 Additional comments (3)
modules/influxdb/influxdb.go (3)

30-56: LGTM! Clean migration to the new Run API.

The refactoring correctly:

  • Builds a slice of default options (exposed ports, environment variables, wait strategy)
  • Appends user-provided options to allow customization/override
  • Delegates container creation to testcontainers.Run
  • Maintains proper error handling with a descriptive error message

72-96: LGTM! Consistent refactoring of option functions.

All four functions (WithUsername, WithPassword, WithDatabase, WithConfigFile) correctly migrate to the new API by returning testcontainers.WithEnv() or testcontainers.WithFiles() instead of directly modifying the request. The refactoring is clean and preserves the original behavior.


98-113: LGTM! All V2 configuration options correctly refactored.

All the V2-related option functions (withV2, WithV2Auth, WithV2SecretsAuth, WithV2Retention, WithV2AdminToken, WithV2SecretsAdminToken, WithInitDb) have been correctly migrated to the new API:

  • Input validation logic is preserved
  • Conflict detection between mutually exclusive options (e.g., direct auth vs. file-based auth) works correctly since options are applied sequentially
  • All functions now return testcontainers.WithEnv() or compose multiple helpers (WithFiles, WithAdditionalWaitStrategy)
  • Error handling is consistent throughout

Also applies to: 135-160, 163-188, 191-201, 204-235, 241-256

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore Changes that do not impact the existing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant