Skip to content

Implement arguments aware overridable. #247

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mneverov
Copy link

@mneverov mneverov commented Apr 15, 2025

Currently, a mock "reset" is supported via allowOverride parameter. Consider an example when a mock is called multiple times with different arguments:

func f() {
    mock.Foo("foo")
    mock.Foo("bar")
    mock.Foo("baz")
}

In this case if only one call needs to be overridden it is impossible to use allowOverride as it resets all the calls.
This PR adds a new param which is set up via WithOverridableExpectationsArgsAware. When provided, only expectations with matching argument matchers will be overridden, see the test examples.

Additional context:
reset feature request, override expectations feature request
Related recent control over expectations feature request

Summary by CodeRabbit

  • New Features
    • Added support for argument-aware overriding of mock expectations, allowing only expectations with matching arguments to be overridden.
    • Introduced a new controller option to enable argument-aware overridable expectations.
  • Tests
    • Added new tests to verify argument-aware overriding behavior and ensure correct handling of multiple expectations with distinct or matching arguments.
    • Provided an example demonstrating the new argument-aware overriding feature.

@CLAassistant
Copy link

CLAassistant commented Apr 15, 2025

CLA assistant check
All committers have signed the CLA.

Copy link

coderabbitai bot commented Apr 15, 2025

Walkthrough

This update introduces argument-aware overriding for expected calls in the gomock framework. A new boolean field, allowOverrideArgsAware, is added to the callSet struct, and a corresponding constructor is provided. When enabled, this feature allows only those expected calls with matching arguments to be overridden, rather than overriding all calls for a method. New controller options and tests are added to support and verify this behavior. Example and test files are updated to demonstrate and validate the argument-aware overriding mechanism.

Changes

File(s) Change Summary
gomock/callset.go Added allowOverrideArgsAware field to callSet, new constructor, and logic in Add for argument-aware overriding.
gomock/controller.go Introduced overridableExpectationsArgsAwareOption and WithOverridableExpectationsArgsAware for argument-aware control.
gomock/callset_test.go Added test for argument-aware overriding: verifies only matching-argument calls are overridden.
gomock/example_test.go Added example demonstrating argument-aware overriding using the new controller option.
gomock/overridable_controller_test.go Added tests to verify argument-aware overriding and matcher equality behavior.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test/Example
    participant Controller
    participant CallSet

    Test->>Controller: Create Controller (WithOverridableExpectationsArgsAware)
    Controller->>CallSet: Initialize with allowOverrideArgsAware=true

    Test->>Controller: Set expectation (method, args1)
    Controller->>CallSet: Add(method, args1)
    CallSet->>CallSet: Remove existing call with matching args1

    Test->>Controller: Set expectation (method, args2)
    Controller->>CallSet: Add(method, args2)
    CallSet->>CallSet: Remove existing call with matching args2

    Test->>Controller: Set expectation (method, args1) again
    Controller->>CallSet: Add(method, args1)
    CallSet->>CallSet: Remove previous call with args1 only

    Test->>Controller: Call method with args1
    Controller->>CallSet: Match expectation for args1 (most recent)
Loading

Poem

In the warren of code, a new path appears,
Where arguments matter—let’s all give three cheers!
Override with precision, not sweeping the floor,
Only matching old calls, we gently outscore.
With tests and examples, we hop on our way,
Argument-aware bunnies, coding all day!
🐇✨

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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 (3)
gomock/callset.go (1)

86-93: Efficient implementation of argument-aware overriding

The implementation correctly identifies and removes only the calls with matching arguments before adding the new call. This provides the expected behavior where only expectations with matching arguments are overridden.

One suggestion to consider:

-		calls := cs.expected[key]
-		for i, c := range calls {
-			if slices.Equal(c.args, call.args) {
-				cs.expected[key] = append(calls[:i], calls[i+1:]...)
-			}
-		}
+		// Filter out any calls with matching arguments
+		calls := cs.expected[key]
+		filteredCalls := make([]*Call, 0, len(calls))
+		for _, c := range calls {
+			if !slices.Equal(c.args, call.args) {
+				filteredCalls = append(filteredCalls, c)
+			}
+		}
+		cs.expected[key] = filteredCalls

This alternative approach uses a filter pattern that avoids in-place slice modifications, which can be error-prone when modifying a slice you're iterating over. However, your current implementation is also correct.

gomock/overridable_controller_test.go (2)

59-77: Good test for argument matcher equality in overriding behavior.

This test correctly demonstrates that expectations with different argument matchers can coexist without overriding each other. The test shows that specific argument matchers (exact string "foo") and generic matchers (gomock.Any()) are treated as distinct expectations, allowing both to be satisfied in the expected order.

However, consider adding another test case that demonstrates what happens when you override a generic matcher with a specific one and vice versa. This would provide additional clarity on the precedence rules when multiple matchers could potentially match the same arguments.


36-77: Consider adding edge case tests for argument-aware overriding.

The current tests cover the basic functionality well, but consider adding tests for edge cases such as:

  1. What happens with multiple identical argument matchers and Times(n) expectations?
  2. Interaction with ordered/unordered expectations
  3. Behavior when overriding expectations with partial argument matcher matches (e.g., multiple arguments where only some match)

These additional tests would help ensure the feature is robust across different usage patterns.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6568d88 and 0a9ff02.

📒 Files selected for processing (5)
  • gomock/callset.go (4 hunks)
  • gomock/callset_test.go (1 hunks)
  • gomock/controller.go (1 hunks)
  • gomock/example_test.go (1 hunks)
  • gomock/overridable_controller_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
gomock/callset.go (1)
gomock/call.go (1)
  • Call (25-45)
gomock/overridable_controller_test.go (1)
gomock/controller.go (2)
  • NewController (84-104)
  • WithOverridableExpectationsArgsAware (127-129)
🔇 Additional comments (7)
gomock/example_test.go (1)

71-94: Great example for the new feature!

This example clearly demonstrates how the new argument-aware overridable expectations feature works. It shows that when using WithOverridableExpectationsArgsAware(), only the expectations with matching arguments ("foo") are overridden, resulting in the second expectation's behavior ("I'm NOT sleepy") taking precedence.

gomock/controller.go (1)

123-133: Proper implementation of the controller option

The implementation follows the established pattern for controller options in the codebase. The documentation comment clearly explains the purpose and behavior of this option, which will help users understand when to use it.

gomock/callset_test.go (1)

63-86: Comprehensive test for argument-aware override behavior

This test effectively verifies the key functionality of the new feature by:

  1. Adding a call with argument "foo"
  2. Adding a call with argument "bar"
  3. Re-adding a call with argument "foo"
  4. Confirming that only the matching "foo" call is overridden while the "bar" call remains

The assertions correctly validate that the total number of expected calls remains 2, showing that only the matching call was replaced.

gomock/callset.go (3)

21-21: Appropriate use of standard library

Good choice using the slices package for equality comparison. This is more efficient and less error-prone than implementing a custom comparison.


35-37: Clear documentation for new field

The comment explains the purpose of the field well, which will help future maintainers understand the code.


63-71: Good initialization of the new call set type

Creating a separate constructor function is consistent with the existing pattern in the codebase. Setting allowOverride: false explicitly makes it clear that the two override modes are mutually exclusive.

gomock/overridable_controller_test.go (1)

36-57: Well-structured test for argument-aware overriding base case.

This test case effectively demonstrates the new argument-aware overriding functionality. It properly shows that with the WithOverridableExpectationsArgsAware() option, only expectations with matching arguments are overridden, while others remain intact. The test verifies both the overridden and non-overridden expectations, providing complete coverage of the feature's core behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants