Skip to content
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

API Mock Improvements #394

Merged
merged 1 commit into from
Jan 7, 2025
Merged

API Mock Improvements #394

merged 1 commit into from
Jan 7, 2025

Conversation

neekolas
Copy link
Contributor

@neekolas neekolas commented Jan 6, 2025

TL;DR

Added key package validation to the message publishing flow tests and updated test infrastructure to pass mocks to the caller.

Closes

#360

What changed?

  • Added new test cases for key package validation success and failure scenarios
  • Introduced ApiServerMocks structure to handle validation service mocking
  • Updated test utility functions to return mock instances
  • Added validation service expectations in test cases

How to test?

  1. Run the test suite with go test ./pkg/api/message/...
  2. Verify key package validation tests pass
  3. Confirm both success and failure scenarios are properly handled
  4. Check that mock expectations are met during test execution

Why make this change?

To ensure key packages are properly validated before being published to the network, preventing invalid or malformed key packages from entering the system. This adds an important security layer to the message publishing flow.

Summary by CodeRabbit

  • Tests

    • Enhanced test coverage for key package validation in the publishing process.
    • Updated test setup functions to include additional mock server functionality.
    • Improved test utility functions to return more comprehensive mock objects.
  • Refactor

    • Introduced ApiServerMocks struct to group related mock dependencies.
    • Modified function signatures in test utility methods to support more detailed mock returns.

The changes primarily focus on improving test infrastructure and mock management across various API test files.

Copy link

coderabbitai bot commented Jan 6, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes primarily involve updates to test utility functions across multiple packages. A new ApiServerMocks struct has been introduced in the pkg/testutils/api/api.go file to consolidate mock dependencies for API server testing. This change impacts several test files, requiring modifications to function signatures and return value handling. The updates standardize the way mock objects are created and passed in test setups, improving the consistency of test infrastructure across different packages.

Changes

File Change Summary
pkg/testutils/api/api.go - Added new ApiServerMocks struct
- Updated NewTestAPIServer and NewTestReplicationAPIClient to return ApiServerMocks
pkg/api/message/publish_test.go - Added new key package validation test cases
- Updated test function calls to handle new return values
pkg/api/message/subscribe_test.go - Modified setupTest function signature to return ApiServerMocks
- Updated test calls to accommodate new return value
pkg/api/payer/clientManager_test.go - Updated NewTestAPIServer function calls to handle additional return value
pkg/api/payer/publish_test.go - Modified NewTestAPIServer function call to capture additional return value
pkg/api/query_test.go - Adjusted variable unpacking in NewTestReplicationAPIClient calls

Sequence Diagram

sequenceDiagram
    participant Test as Test Function
    participant TestUtils as TestUtils.NewTestAPIServer
    participant Mocks as ApiServerMocks
    
    Test->>TestUtils: Call with test context
    TestUtils-->>Mocks: Create mock objects
    TestUtils-->>Test: Return API Server, DB, Mocks, Cleanup Function
    Test->>Test: Use returned components for testing
Loading

The sequence diagram illustrates the new pattern of test utility function calls, showing how the ApiServerMocks are now created and returned alongside other test setup components.

Possibly related PRs

  • Add key package validation #393: The main PR introduces new test cases for the PublishPayerEnvelopes method, which is directly related to the changes made in the service that now includes key package validation, enhancing the testing of this functionality.

Suggested reviewers

  • mkysel

📜 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 0ef8fb1 and 97d1580.

📒 Files selected for processing (6)
  • pkg/api/message/publish_test.go (6 hunks)
  • pkg/api/message/subscribe_test.go (8 hunks)
  • pkg/api/payer/clientManager_test.go (1 hunks)
  • pkg/api/payer/publish_test.go (1 hunks)
  • pkg/api/query_test.go (10 hunks)
  • pkg/testutils/api/api.go (2 hunks)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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
Contributor Author

neekolas commented Jan 6, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@neekolas neekolas changed the title Pass mocks back to test API API Mock Improvements Jan 6, 2025
@neekolas neekolas marked this pull request as ready for review January 6, 2025 19:51
@neekolas neekolas requested a review from a team as a code owner January 6, 2025 19:51
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 (6)
pkg/api/payer/clientManager_test.go (1)

23-25: Consider utilizing the returned mocks for enhanced testing

The test is currently discarding the returned ApiServerMocks with _. Consider utilizing these mocks to add more comprehensive test cases that verify interactions with the registry, validation service, and message publisher.

pkg/testutils/api/api.go (1)

126-132: Consider adding mock verification in cleanup

While the implementation is correct, consider adding mock verification in the cleanup function to ensure all expected mock interactions occurred.

 return svr, db, allMocks, func() {
+    mockRegistry.AssertExpectations(t)
+    mockValidationService.AssertExpectations(t)
+    mockMessagePublisher.AssertExpectations(t)
     cancel()
     svr.Close()
     dbCleanup()
 }
pkg/api/payer/publish_test.go (1)

109-109: Consider utilizing the returned mocks for better test coverage

The test discards the returned ApiServerMocks. Consider using these mocks to verify interactions with the originator server and enhance test coverage.

pkg/api/message/publish_test.go (1)

118-194: Consider extracting common test setup code

The key package validation tests have duplicated setup code. Consider extracting the common setup into a helper function to improve maintainability.

+func setupKeyPackageTest(t *testing.T) (message_api.ReplicationApiClient, *apiTestUtils.ApiServerMocks, func(), *envelopes.ClientEnvelope) {
+    api, _, apiMocks, cleanup := apiTestUtils.NewTestReplicationAPIClient(t)
+    
+    clientEnv := envelopeTestUtils.CreateClientEnvelope(&envelopes.AuthenticatedData{
+        TargetTopic:      topic.NewTopic(topic.TOPIC_KIND_KEY_PACKAGES_V1, []byte{1, 2, 3}).Bytes(),
+        TargetOriginator: 100,
+        LastSeen:         &envelopes.VectorClock{},
+    })
+    clientEnv.Payload = &envelopes.ClientEnvelope_UploadKeyPackage{
+        UploadKeyPackage: &apiv1.UploadKeyPackageRequest{
+            KeyPackage: &apiv1.KeyPackageUpload{
+                KeyPackageTlsSerialized: []byte{1, 2, 3},
+            },
+        },
+    }
+    
+    return api, apiMocks, cleanup, clientEnv
+}

Then use it in the tests:

 func TestKeyPackageValidationSuccess(t *testing.T) {
-    api, _, apiMocks, cleanup := apiTestUtils.NewTestReplicationAPIClient(t)
+    api, apiMocks, cleanup, clientEnv := setupKeyPackageTest(t)
     defer cleanup()
-
-    clientEnv := envelopeTestUtils.CreateClientEnvelope(&envelopes.AuthenticatedData{
-        TargetTopic:      topic.NewTopic(topic.TOPIC_KIND_KEY_PACKAGES_V1, []byte{1, 2, 3}).Bytes(),
-        TargetOriginator: 100,
-        LastSeen:         &envelopes.VectorClock{},
-    })
-    clientEnv.Payload = &envelopes.ClientEnvelope_UploadKeyPackage{
-        UploadKeyPackage: &apiv1.UploadKeyPackageRequest{
-            KeyPackage: &apiv1.KeyPackageUpload{
-                KeyPackageTlsSerialized: []byte{1, 2, 3},
-            },
-        },
-    }
pkg/api/message/subscribe_test.go (2)

28-30: LGTM! Consider adding documentation.

The signature change aligns well with the PR objective of passing mocks back to test API. Consider adding a brief comment explaining the purpose of each return value for better maintainability.

+// setupTest initializes the test environment and returns:
+// - A ReplicationApiClient for making API calls
+// - A database connection for test data setup
+// - ApiServerMocks for verifying mock interactions
+// - A cleanup function to be deferred
 func setupTest(
 	t *testing.T,
 ) (message_api.ReplicationApiClient, *sql.DB, testUtilsApi.ApiServerMocks, func()) {

120-120: Consider leveraging the mock objects for enhanced test coverage.

While discarding the mock objects with _ is valid for these end-to-end style tests, you might want to consider adding new test cases that verify mock interactions. This could help catch integration issues earlier by ensuring the expected mock calls are made with the correct parameters.

Example approach for a new test case:

func TestSubscribeEnvelopesMockInteractions(t *testing.T) {
    client, _, mocks, cleanup := setupTest(t)
    defer cleanup()

    // Setup mock expectations
    mocks.MockRegistry.EXPECT().YourMethod().Return(nil)

    // Test your functionality
    stream, err := client.SubscribeEnvelopes(
        context.Background(),
        &message_api.SubscribeEnvelopesRequest{...},
    )
    require.NoError(t, err)

    // Verify mock interactions
    require.True(t, mocks.MockRegistry.AssertExpectations(t))
}

Also applies to: 141-141, 163-163, 185-185, 228-228, 250-250, 272-272

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b4f6507 and 0ef8fb1.

📒 Files selected for processing (6)
  • pkg/api/message/publish_test.go (6 hunks)
  • pkg/api/message/subscribe_test.go (8 hunks)
  • pkg/api/payer/clientManager_test.go (1 hunks)
  • pkg/api/payer/publish_test.go (1 hunks)
  • pkg/api/query_test.go (10 hunks)
  • pkg/testutils/api/api.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • pkg/api/query_test.go
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Graphite / mergeability_check
  • GitHub Check: Graphite / mergeability_check
🔇 Additional comments (3)
pkg/testutils/api/api.go (1)

68-72: LGTM! Well-structured mock consolidation

The new ApiServerMocks struct provides a clean way to organize and pass mock dependencies.

pkg/api/message/publish_test.go (2)

135-144: LGTM! Good mock expectations

The mock expectations are well-defined and properly verify the validation service behavior.


174-183: LGTM! Good error case handling

The test properly verifies the error case when key package validation fails.

Copy link
Contributor Author

neekolas commented Jan 7, 2025

Merge activity

  • Jan 7, 12:25 PM PST: A user started a stack merge that includes this pull request via Graphite.
  • Jan 7, 12:27 PM PST: Graphite rebased this pull request as part of a merge.
  • Jan 7, 12:28 PM PST: A user merged this pull request with Graphite.

@neekolas neekolas changed the base branch from 01-06-add_key_package_validation to graphite-base/394 January 7, 2025 20:25
@neekolas neekolas changed the base branch from graphite-base/394 to main January 7, 2025 20:25
@neekolas neekolas force-pushed the 01-06-pass_mocks_back_to_test_api branch from 0ef8fb1 to 97d1580 Compare January 7, 2025 20:26
@neekolas neekolas merged commit 8bd5a7a into main Jan 7, 2025
7 of 8 checks passed
@neekolas neekolas deleted the 01-06-pass_mocks_back_to_test_api branch January 7, 2025 20:28
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