Skip to content

chore(wait): replace manual StrategyTarget mocks with generated mockery mocks#3603

Open
mateenali66 wants to merge 2 commits into
testcontainers:mainfrom
mateenali66:feat/issue-2765-generated-mocks-wait
Open

chore(wait): replace manual StrategyTarget mocks with generated mockery mocks#3603
mateenali66 wants to merge 2 commits into
testcontainers:mainfrom
mateenali66:feat/issue-2765-generated-mocks-wait

Conversation

@mateenali66

Copy link
Copy Markdown

Part of #2765. Replaces the manual StrategyTarget mock structs in exec_test.go, exit_test.go, and health_test.go with the generated mockStrategyTarget from strategytarget_mock_test.go. Tests moved to package wait_test for consistency with the generated mock.

@mateenali66 mateenali66 requested a review from a team as a code owner March 24, 2026 20:12
@netlify

netlify Bot commented Mar 24, 2026

Copy link
Copy Markdown

Deploy Preview for testcontainers-go ready!

Name Link
🔨 Latest commit 77c1ac7
🔍 Latest deploy log https://app.netlify.com/projects/testcontainers-go/deploys/6a31fd17eafd9a000888a260
😎 Deploy Preview https://deploy-preview-3603--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

coderabbitai Bot commented Mar 24, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 70ad5bc7-9d31-4530-b5a0-acfdc48d4308

📥 Commits

Reviewing files that changed from the base of the PR and between 728129a and 77c1ac7.

📒 Files selected for processing (2)
  • wait/exit_test.go
  • wait/health_test.go
💤 Files with no reviewable changes (2)
  • wait/health_test.go
  • wait/exit_test.go

Summary by CodeRabbit

  • Tests
    • Refactored test infrastructure for improved maintainability and reliability.

This release includes internal test improvements with no user-facing changes.

Walkthrough

Two wait-strategy test files (exit_test.go, health_test.go) are converted from internal package (package wait) to external package (package wait_test). Local stub types (exitStrategyTarget, healthStrategyTarget) are deleted and replaced with newMockStrategyTarget/newStateTarget helpers backed by testify mocks. Strategy constructors are now called with the wait. qualifier.

Changes

Wait Strategy Test Migration

Layer / File(s) Summary
Exit strategy test: external package + mock target
wait/exit_test.go
Package declaration changed to wait_test, exitStrategyTarget stub removed, TestWaitForExit rewritten to use newMockStrategyTarget with a State expectation returning &container.State{Running: false}, and strategy constructed via wait.NewExitStrategy().
Health strategy tests: external package, newStateTarget helper, mock-driven state
wait/health_test.go
Package declaration changed to wait_test, healthStrategyTarget stub and mutex-based setState goroutine removed, newStateTarget(t, state) helper added, and all test cases (timeout, healthy, nil-Health with time-based RunAndReturn, OOMKilled, exited, dead) rewritten using newStateTarget/newMockStrategyTarget with wait.NewHealthStrategy().

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 Hoppity-hop, the stubs must go,
No more mutex tricks to stage the show.
With mocks and helpers, clean and bright,
External packages feel just right.
The rabbit cheers each wait.New* call —
Less boilerplate for one and all! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.25% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: replacing manual StrategyTarget mocks with generated mockery mocks in the wait package.
Description check ✅ Passed The description relates to the changeset by explaining the refactoring work: replacing manual mocks with generated ones and moving tests to wait_test package.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
wait/exec_test.go (1)

69-76: Consider using RunAndReturn() for clearer intent with dynamic return values.

The current Return() pattern with a function argument works correctly because mockery-generated mocks have special handling that checks if the return value is a function matching the method signature and executes it. However, RunAndReturn() is more explicit and idiomatic for this use case:

 	target.On("Exec", mock.Anything, mock.Anything, mock.Anything).RunAndReturn(
 		func(ctx context.Context, cmd []string, opts ...tcexec.ProcessOption) (int, io.Reader, error) {
 			if time.Now().After(successAfter) {
 				return 0, nil, nil
 			}
 			return 10, nil, nil
 		},
 	)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@wait/exec_test.go` around lines 69 - 76, Replace the current mock setup that
uses Return with a clearer RunAndReturn call: on the mock `target` where you
call On("Exec", mock.Anything, mock.Anything, mock.Anything) switch from
.Return(func(ctx context.Context, cmd []string, opts ...tcexec.ProcessOption)
(int, io.Reader, error) { ... }) to .RunAndReturn(func(ctx context.Context, cmd
[]string, opts ...tcexec.ProcessOption) (int, io.Reader, error) { ... }); keep
the same function signature and the dynamic successAfter logic so the mock
executes that function at call time instead of relying on Return's special-case
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@wait/exec_test.go`:
- Around line 88-96: The mock setup for target.On("Exec", ...) incorrectly uses
Return() with a function literal so the function isn't executed for each call;
change this to use RunAndReturn() on the mock so the provided func(ctx
context.Context, cmd []string, opts ...tcexec.ProcessOption) (int, io.Reader,
error) is invoked at call time, preserve the logic that sleeps, checks ctx.Err()
and returns accordingly, and keep the same argument matchers (mock.Anything,
mock.Anything, mock.Anything) and return-value types to match the Exec method
signature.

In `@wait/health_test.go`:
- Around line 52-60: The mock currently uses Return(...) with a function literal
which will be returned as the value instead of being invoked; replace the
Return(...) call on the target mock for the "State" method with
RunAndReturn(...) so the provided function is executed each call. Specifically,
change target.On("State", mock.Anything).Return(func(_ context.Context)
(*container.State, error) { ... }) to target.On("State",
mock.Anything).RunAndReturn(func(ctx context.Context) (*container.State, error)
{ mtx.Lock(); defer mtx.Unlock(); s := *state; return &s, nil }) (i.e., provide
a function matching the State signature so the mock invokes it dynamically and
still returns a copy to avoid races).

---

Nitpick comments:
In `@wait/exec_test.go`:
- Around line 69-76: Replace the current mock setup that uses Return with a
clearer RunAndReturn call: on the mock `target` where you call On("Exec",
mock.Anything, mock.Anything, mock.Anything) switch from .Return(func(ctx
context.Context, cmd []string, opts ...tcexec.ProcessOption) (int, io.Reader,
error) { ... }) to .RunAndReturn(func(ctx context.Context, cmd []string, opts
...tcexec.ProcessOption) (int, io.Reader, error) { ... }); keep the same
function signature and the dynamic successAfter logic so the mock executes that
function at call time instead of relying on Return's special-case behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3d29c677-cdf8-4ba1-9558-0d9d20e64ca1

📥 Commits

Reviewing files that changed from the base of the PR and between ea9748b and 99389dc.

📒 Files selected for processing (3)
  • wait/exec_test.go
  • wait/exit_test.go
  • wait/health_test.go

Comment thread wait/exec_test.go Outdated
Comment thread wait/health_test.go Outdated
@mateenali66 mateenali66 changed the title test(wait): replace manual StrategyTarget mocks with generated mockery mocks chore(wait): replace manual StrategyTarget mocks with generated mockery mocks Apr 7, 2026
@mdelapenya

Copy link
Copy Markdown
Member

I sent you my review changes in mateenali66@39010f0 🙏

mdelapenya and others added 2 commits June 16, 2026 21:45
- Switch to package wait_test
- Replace hand-written mocks with mockStrategyTarget + typed EXPECT() chains
- Use anyContext matcher for context args
- Use moby/moby import paths (not docker/docker)
- Use typed container state constants
- Extract newStateTarget() helper in health_test.go
- Replace goroutine+mutex pattern in TestWaitForHealthWithNil with RunAndReturn closure

Addresses review feedback on PR testcontainers#3603.
Satisfies the thelper linter; newStateTarget is a test helper.

Signed-off-by: Mateen Anjum <mateenali66@gmail.com>
@mateenali66 mateenali66 force-pushed the feat/issue-2765-generated-mocks-wait branch from 728129a to 77c1ac7 Compare June 17, 2026 01:49
@mateenali66

Copy link
Copy Markdown
Author

thanks @mdelapenya. applied your commit on top of current main (the branch was conflicting against the moby/moby migration that landed since March), and added t.Helper() to newStateTarget so it passes the thelper linter. wait tests pass and golangci-lint v2.9.0 is clean on ./wait/... you can close your suggestions PR, the changes are in here now.

@mdelapenya mdelapenya self-assigned this Jun 17, 2026
@mdelapenya mdelapenya added the chore Changes that do not impact the existing functionality label Jun 17, 2026
@mdelapenya mdelapenya requested a review from Copilot June 17, 2026 18:03

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR updates the wait package tests to stop using hand-written StrategyTarget test doubles and instead rely on the generated mockStrategyTarget (mockery-based), aligning these tests with the external wait_test package pattern used elsewhere in the folder.

Changes:

  • Switched health_test.go and exit_test.go to package wait_test and updated imports accordingly.
  • Replaced manual StrategyTarget mock structs with the generated mockStrategyTarget and added a small helper (newStateTarget) for common State() setups.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
wait/health_test.go Migrates health strategy tests to wait_test and uses generated mockStrategyTarget (plus a helper) instead of a manual mock.
wait/exit_test.go Migrates exit strategy test to wait_test and uses generated mockStrategyTarget for State() behavior.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread wait/health_test.go
Comment on lines +1 to 3
package wait_test

import (
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.

3 participants