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

feat: [indexer] add test cases to block_update_indexer_block_process_strategy #8735

Conversation

cryptomatictrader
Copy link
Contributor

@cryptomatictrader cryptomatictrader commented Sep 27, 2024

This PR adds TestBlockUpdateIndexerBlockProcessStrategyTestSuite which verifies the block update indexer strategy for processing created pools. The test suite initializes all supported pools (concentrated, cfmm, cosmwasm) via s.App.PrepareAllSupportedPools(), creating pool IDs 1-5. Test cases inject pool creation data and validate expected behavior of the pair publisher.

Scenarios tested:

  • Happy path: single pool creation: should perform publishing
  • Happy path: multiple pool creation: should perform publishing
  • No pool creation: nothing is published
  • Pool creation data without a match: nothing is published

@cryptomatictrader cryptomatictrader added V:state/compatible/backport State machine compatible PR, should be backported A:no-changelog A:backport/v26.x backport patches to v26.x branch labels Sep 27, 2024
@cryptomatictrader cryptomatictrader self-assigned this Sep 27, 2024
Copy link
Contributor

coderabbitai bot commented Sep 27, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces a mock implementation of the PairPublisher interface for testing purposes and enhances the block update indexer strategy in the Osmosis blockchain application. It includes a new mock struct to simulate PairPublisher behavior, updates to the pool publishing logic to filter by creation status, and a comprehensive test suite that validates the handling of pool creation events.

Changes

Files Change Summary
ingest/indexer/domain/mocks/pair_publisher_mock.go Introduced MockPairPublisher struct with fields to track operation states and a method PublishPoolPairs for simulating the publishing of pool pairs in tests.
ingest/indexer/domain/mocks/publisher_mock.go Enhanced PublisherMock struct by adding fields to track method call counts and removing commented-out fields, improving its functionality for testing purposes.
ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy.go Added logic in publishCreatedPools method to filter pools based on their creation status, ensuring only newly created pools are published.
ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go Introduced a test suite for the block update indexer strategy, validating the handling of pool creation events through multiple test cases using the testify package.
ingest/indexer/service/blockprocessor/full_indexer_block_process_strategy_test.go Established a test suite for FullIndexerBlockProcessStrategy, including tests for PublishAllSupplies and ProcessPools methods to ensure correct functionality in various scenarios.

Possibly related PRs

Suggested labels

C:docs

Suggested reviewers

  • PaddyMc

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

@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

🧹 Outside diff range and nitpick comments (3)
ingest/indexer/service/blockprocessor/export_test.go (1)

8-15: LGTM: Function implementation is correct. Consider adding a comment.

The NewBlockUpdatesIndexerBlockProcessStrategy function is well-implemented and follows Go best practices. It's concise, does a single job, and is likely used for dependency injection in tests, which is excellent.

Consider adding a brief comment explaining the purpose of this function, especially since it's in an export_test.go file. For example:

// NewBlockUpdatesIndexerBlockProcessStrategy creates a new blockUpdatesIndexerBlockProcessStrategy
// with the given dependencies. This function is exported for testing purposes.
func NewBlockUpdatesIndexerBlockProcessStrategy(
    blockUpdateProcessUtils commondomain.BlockUpdateProcessUtilsI,
    client domain.Publisher,
    poolExtractor commondomain.PoolExtractor,
    poolPairPublisher domain.PairPublisher,
) *blockUpdatesIndexerBlockProcessStrategy {
    // ... (rest of the function remains the same)
}
ingest/indexer/domain/mocks/pair_publisher_mock.go (1)

13-19: LGTM: Well-structured mock with a minor suggestion.

The MockPairPublisher struct is well-designed with fields that allow for flexible testing scenarios. It can simulate errors, track method calls, and count various aspects of the publishing process.

Consider expanding the comment to provide more detail about the struct's purpose and usage:

- // MockPairPublisher is a mock implementation of the PairPublisherI interface.
+ // MockPairPublisher is a mock implementation of the PairPublisher interface.
+ // It allows for simulating various scenarios in tests, including error conditions,
+ // tracking method calls, and counting published pools and their creation data.
ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go (1)

34-148: LGTM: Comprehensive test cases with a minor suggestion.

The TestProcessBlock function is well-structured with table-driven tests covering various scenarios for pool creation and publishing. The test cases include happy paths, edge cases, and scenarios with no pool creation. The use of mocks for dependencies allows for isolated testing of the block processing strategy.

The assertions effectively verify the expected behavior in terms of publishing calls and pool creation data. This comprehensive approach ensures robust testing of the block update indexer strategy.

Consider adding a test case for error handling, such as when s.App.ConcentratedLiquidityKeeper.GetPools(s.Ctx) or other similar calls might return an error. This would ensure the strategy handles potential errors gracefully.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 09ff5a2 and 6d7ecd3.

📒 Files selected for processing (3)
  • ingest/indexer/domain/mocks/pair_publisher_mock.go (1 hunks)
  • ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go (1 hunks)
  • ingest/indexer/service/blockprocessor/export_test.go (1 hunks)
🔇 Additional comments (8)
ingest/indexer/service/blockprocessor/export_test.go (2)

1-1: LGTM: Package declaration is correct.

The package name blockprocessor matches the directory name, which is a good Go practice.


3-6: LGTM: Import statements are appropriate.

The imports are relevant to the function being implemented. Using an alias for the common domain package is a good practice to avoid name conflicts and improve readability.

ingest/indexer/domain/mocks/pair_publisher_mock.go (3)

1-9: LGTM: Package declaration and imports are appropriate.

The package name "mocks" is suitable for a mock implementation, and the imports cover the necessary dependencies for the mock PairPublisher.


11-11: Excellent use of interface assertion.

The line var _ indexerdomain.PairPublisher = &MockPairPublisher{} ensures at compile-time that MockPairPublisher implements the PairPublisher interface. This is a crucial practice for maintaining type safety and catching implementation errors early.


1-30: Summary: Well-implemented mock supporting PR objectives

This MockPairPublisher implementation aligns well with the PR objectives, providing a flexible tool for testing the block update indexer strategy. It allows for simulating various scenarios mentioned in the PR summary, such as single and multiple pool creations, as well as error conditions.

The mock's ability to track the number of published pools and pools with creation data will be particularly useful for the test cases described in the PR objectives, including the "Happy Path" scenarios for single and multiple pool creations, and the "No Pool Creation" scenario.

Overall, this mock implementation contributes significantly to enhancing the testing framework for the block update indexer strategy, supporting robust validation of pool creation processes within the Osmosis ecosystem.

ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go (3)

3-15: LGTM: Imports are well-organized and appropriate.

The imports are correctly structured, following Go conventions with standard library imports first, followed by third-party and local packages. All imports appear to be necessary for the test file.


17-32: LGTM: Test suite structure is well-defined.

The test suite is correctly structured using the testify framework. The BlockUpdateIndexerBlockProcessStrategyTestSuite embeds ConcentratedKeeperTestHelper, which should provide necessary setup utilities. The suite runner function TestBlockUpdateIndexerBlockProcessStrategyTestSuite is properly implemented to execute the suite.


1-148: Overall, excellent test implementation with comprehensive coverage.

This test file for the block update indexer strategy is well-structured, follows good testing practices, and provides comprehensive coverage of various scenarios. The use of table-driven tests and mocks enhances maintainability and allows for isolated testing of the block processing strategy.

The test cases effectively validate the behavior of the indexer in different situations, including single and multiple pool creations, no pool creation, and mismatched pool creation data. This thorough approach helps ensure the robustness of the block update indexer strategy.

Comment on lines 21 to 30
func (m *MockPairPublisher) PublishPoolPairs(ctx sdk.Context, pools []poolmanagertypes.PoolI, createdPoolIDs map[uint64]commondomain.PoolCreation) error {
m.PublishPoolPairsCalled = true
m.NumPoolsPublished += len(pools)
for _, pool := range pools {
if _, ok := createdPoolIDs[pool.GetId()]; ok {
m.NumPoolsWithCreationData++
}
}
return m.PublishPoolPairsError
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

LGTM: Well-implemented mock method with a suggestion for improvement.

The PublishPoolPairs method is correctly implemented and provides useful information for test assertions. It updates internal counters and flags based on the input, which is valuable for verifying the mock's behavior in tests.

For improved robustness, consider adding a nil check for the pools slice:

 func (m *MockPairPublisher) PublishPoolPairs(ctx sdk.Context, pools []poolmanagertypes.PoolI, createdPoolIDs map[uint64]commondomain.PoolCreation) error {
 	m.PublishPoolPairsCalled = true
-	m.NumPoolsPublished += len(pools)
+	if pools != nil {
+		m.NumPoolsPublished += len(pools)
+	}
 	for _, pool := range pools {
 		if _, ok := createdPoolIDs[pool.GetId()]; ok {
 			m.NumPoolsWithCreationData++
 		}
 	}
 	return m.PublishPoolPairsError
 }

This change ensures that the method behaves correctly even if nil is passed for the pools slice.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (m *MockPairPublisher) PublishPoolPairs(ctx sdk.Context, pools []poolmanagertypes.PoolI, createdPoolIDs map[uint64]commondomain.PoolCreation) error {
m.PublishPoolPairsCalled = true
m.NumPoolsPublished += len(pools)
for _, pool := range pools {
if _, ok := createdPoolIDs[pool.GetId()]; ok {
m.NumPoolsWithCreationData++
}
}
return m.PublishPoolPairsError
}
func (m *MockPairPublisher) PublishPoolPairs(ctx sdk.Context, pools []poolmanagertypes.PoolI, createdPoolIDs map[uint64]commondomain.PoolCreation) error {
m.PublishPoolPairsCalled = true
if pools != nil {
m.NumPoolsPublished += len(pools)
}
for _, pool := range pools {
if _, ok := createdPoolIDs[pool.GetId()]; ok {
m.NumPoolsWithCreationData++
}
}
return m.PublishPoolPairsError
}

@cryptomatictrader cryptomatictrader requested review from p0mvn and removed request for p0mvn September 27, 2024 18:13
@cryptomatictrader
Copy link
Contributor Author

Got some ideas to improve the test cases. Marked it as draft.

@cryptomatictrader cryptomatictrader marked this pull request as draft September 27, 2024 19:38
@cryptomatictrader cryptomatictrader marked this pull request as ready for review September 27, 2024 22:29
Copy link
Contributor

@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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6d7ecd3 and 7f2d000.

📒 Files selected for processing (3)
  • ingest/indexer/domain/mocks/pair_publisher_mock.go (1 hunks)
  • ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go (1 hunks)
  • ingest/indexer/service/blockprocessor/export_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • ingest/indexer/domain/mocks/pair_publisher_mock.go
  • ingest/indexer/service/blockprocessor/export_test.go
🔇 Additional comments (4)
ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go (4)

3-15: LGTM: Imports are appropriate and concise.

The imports cover all necessary packages for testing, including the Osmosis-specific packages required for the test suite. No unused imports are present.


17-32: LGTM: Well-structured test suite following best practices.

The test suite is properly defined using testify/suite and includes the necessary ConcentratedKeeperTestHelper for Osmosis-specific testing setup. The main test function correctly uses suite.Run() to execute the suite.


34-97: LGTM: Comprehensive test cases with good coverage.

The test cases are well-structured using a table-driven approach. They cover various scenarios including:

  1. Single pool creation
  2. Multiple pool creations
  3. No pool creation
  4. Pool creation data without a match

Each case checks for the expected publishing behavior and pool data, providing good coverage of the functionality.


1-155: Overall, excellent test suite with comprehensive coverage.

This test file introduces a well-structured and thorough test suite for the block update indexer strategy. It covers various scenarios, uses best practices for Go testing (including table-driven tests), and provides good isolation through appropriate mocking. The tests are clear, maintainable, and should provide robust validation of the indexer's behavior.

A minor suggestion for improvement has been made regarding the extraction of setup code, but this is a refinement rather than a necessary change. Great job on implementing these tests!

Comment on lines 99 to 155
for _, test := range tests {
s.Run(test.name, func() {
s.Setup()

// Initialized chain pools
s.PrepareAllSupportedPools()

// Get all chain pools from state for asserting later
// pool id 1 created below
concentratedPools, err := s.App.ConcentratedLiquidityKeeper.GetPools(s.Ctx)
s.Require().NoError(err)
// pool id 2, 3 created below
cfmmPools, err := s.App.GAMMKeeper.GetPools(s.Ctx)
s.Require().NoError(err)
// pool id 4, 5 created below
cosmWasmPools, err := s.App.CosmwasmPoolKeeper.GetPoolsWithWasmKeeper(s.Ctx)
s.Require().NoError(err)
blockPools := commondomain.BlockPools{
ConcentratedPools: concentratedPools,
CFMMPools: cfmmPools,
CosmWasmPools: cosmWasmPools,
}

// Mock out block updates process utils
blockUpdatesProcessUtilsMock := &sqsmocks.BlockUpdateProcessUtilsMock{}

// Mock out pool extractor
poolsExtracter := &commonmocks.PoolsExtractorMock{
BlockPools: blockPools,
CreatedPoolIDs: test.createdPoolIDs,
}

// Mock out publisher
publisherMock := &indexermocks.PublisherMock{}

// Mock out pair publisher
pairPublisherMock := &indexermocks.MockPairPublisher{}

bprocess := blockprocessor.NewBlockUpdatesIndexerBlockProcessStrategy(blockUpdatesProcessUtilsMock, publisherMock, poolsExtracter, pairPublisherMock)

err = bprocess.PublishCreatedPools(s.Ctx)
s.Require().NoError(err)

// Check that the pair publisher is called correctly
s.Require().Equal(test.expectedPublishPoolPairsCalled, pairPublisherMock.PublishPoolPairsCalled)
if test.expectedPublishPoolPairsCalled {
// Check that the number of pools published
s.Require().Equal(test.expectedNumPoolsPublished, pairPublisherMock.NumPoolsPublished)
// Check that the pools and created pool IDs are set correctly
s.Require().Equal(blockPools.GetAll(), pairPublisherMock.CalledWithPools)
s.Require().Equal(test.createdPoolIDs, pairPublisherMock.CalledWithCreatedPoolIDs)
// Check that the number of pools with creation data
s.Require().Equal(test.expectedNumPoolsWithCreationData, pairPublisherMock.NumPoolsWithCreationData)
}
})
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

LGTM: Well-implemented test with thorough setup and assertions.

The test implementation is solid, with proper setup of the Osmosis app, mocking of dependencies, and comprehensive assertions. It follows the Arrange-Act-Assert pattern, which enhances readability and maintainability.

Consider extracting the setup of mocks and the Osmosis app into a separate method to reduce duplication and improve readability. This could look like:

func (s *BlockUpdateIndexerBlockProcessStrategyTestSuite) setupTest(createdPoolIDs map[uint64]commondomain.PoolCreation) (blockprocessor.BlockUpdatesIndexerBlockProcessStrategy, *indexermocks.MockPairPublisher) {
    s.Setup()
    s.PrepareAllSupportedPools()
    
    // ... (rest of the setup code)
    
    return bprocess, pairPublisherMock
}

Then, in each test case, you could simply call:

bprocess, pairPublisherMock := s.setupTest(test.createdPoolIDs)

This would make the test cases more focused on the specific scenario being tested.

@cryptomatictrader cryptomatictrader changed the title feat: add test cases to block_update_indexer_block_process_strategy feat: [indexer] add test cases to block_update_indexer_block_process_strategy Sep 28, 2024
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (2)
ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy.go (2)

54-60: LGTM: Filtering logic implemented correctly.

The new filtering logic ensures that only newly created pools are processed, which aligns with the function's purpose. This implementation is correct and efficient.

Consider pre-allocating the filteredPools slice to potentially improve performance:

- filteredPools := []poolmanagertypes.PoolI{}
+ filteredPools := make([]poolmanagertypes.PoolI, 0, len(createdPoolIDs))

This pre-allocation can be more efficient when the number of created pools is large, as it avoids potential reallocation during appends.


68-68: LGTM: PublishPoolPairs now uses filtered pools correctly.

The update to use filteredPools in the PublishPoolPairs call is correct and consistent with the new filtering logic.

Consider wrapping the error returned from PublishPoolPairs with additional context:

- if err := f.poolPairPublisher.PublishPoolPairs(ctx, filteredPools, createdPoolIDs); err != nil {
-   return err
- }
+ if err := f.poolPairPublisher.PublishPoolPairs(ctx, filteredPools, createdPoolIDs); err != nil {
+   return fmt.Errorf("failed to publish pool pairs: %w", err)
+ }

This would provide more context if an error occurs, making debugging easier.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7193265 and 265a87b.

📒 Files selected for processing (2)
  • ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy.go (2 hunks)
  • ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy_test.go
🔇 Additional comments (3)
ingest/indexer/service/blockprocessor/block_updates_indexer_block_process_strategy.go (3)

8-8: LGTM: Import statement added correctly.

The new import for poolmanagertypes is necessary for the changes in the publishCreatedPools method and follows the correct project structure.


62-65: LGTM: Early return logic added appropriately.

The new early return condition prevents unnecessary processing when no pools pass the filter. This is a good practice for improving efficiency and code clarity.


Line range hint 1-71: Overall assessment: Changes improve efficiency and correctness.

The modifications to the publishCreatedPools method effectively implement the filtering of newly created pools before publishing. This aligns well with the PR objectives and enhances the overall functionality of the block update indexer strategy.

Key improvements:

  1. Efficient filtering of newly created pools.
  2. Early return to avoid unnecessary processing.
  3. Correct usage of filtered pools in the publishing step.

These changes contribute to a more robust and efficient implementation of the block processing strategy.

Comment on lines 60 to 70
PoolId: 1,
BlockHeight: 12345,
BlockTime: time.Now(),
TxnHash: "txhash1",
},
2: {
PoolId: 2,
BlockHeight: 12346,
BlockTime: time.Now(),
TxnHash: "txhash2",
},
Copy link
Member

Choose a reason for hiding this comment

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

nit: vars could be created and shared with the other PR about "full indexer strategy"

…#8736)

* add test cases to full_indexer_block_process_strategy

* add vars to test file to avoid code dup
Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (6)
ingest/indexer/domain/mocks/publisher_mock.go (3)

30-31: LGTM! Consider a minor consistency improvement.

The changes to PublishPair and PublishBlock methods correctly implement the counter increments, enhancing the mock's tracking capabilities. The existing functionality is preserved, ensuring backward compatibility.

For consistency, consider moving the counter increment to the beginning of each method. This ensures the count is incremented even if there's a panic later in the method (although unlikely in this simple implementation).

Here's a suggested modification for both methods:

 func (p *PublisherMock) PublishPair(ctx context.Context, pair indexerdomain.Pair) error {
+	p.NumPublishPairCalls++
 	p.CalledWithPair = pair
-	p.NumPublishPairCalls++
 	return p.ForcePairError
 }

Also applies to: 37-38


45-45: LGTM! Consider the same minor consistency improvement.

The changes to PublishTokenSupply, PublishTokenSupplyOffset, and PublishTransaction methods correctly implement the counter increments, consistent with the previous methods. This enhances the mock's tracking capabilities while preserving existing functionality.

As suggested for the previous methods, consider moving the counter increment to the beginning of each method for consistency and to ensure the count is incremented even in the unlikely event of a panic.

Here's a suggested modification for all three methods:

 func (p *PublisherMock) PublishTokenSupply(ctx context.Context, tokenSupply indexerdomain.TokenSupply) error {
+	p.NumPublishTokenSupplyCalls++
 	p.CalledWithTokenSupply = tokenSupply
-	p.NumPublishTokenSupplyCalls++
 	return p.ForceTokenSupplyError
 }

 func (p *PublisherMock) PublishTokenSupplyOffset(ctx context.Context, tokenSupplyOffset indexerdomain.TokenSupplyOffset) error {
+	p.NumPublishTokenSupplyOffsetCalls++
 	p.CalledWithTokenSupplyOffset = tokenSupplyOffset
-	p.NumPublishTokenSupplyOffsetCalls++
 	return p.ForceTokenSupplyOffsetError
 }

 func (p *PublisherMock) PublishTransaction(ctx context.Context, txn indexerdomain.Transaction) error {
+	p.NumPublishTransactionCalls++
 	p.CalledWithTransaction = txn
-	p.NumPublishTransactionCalls++
 	return p.ForceTransactionError
 }

Also applies to: 52-52, 58-59


Line range hint 1-63: Overall, excellent enhancements to the PublisherMock!

These changes significantly improve the mock's functionality for testing purposes. The addition of counters for each publish method allows for more precise assertions in tests, enabling verification of both the arguments passed and the number of times each method is called.

While the changes don't directly implement the test cases mentioned in the PR objectives (which are likely in a separate file), they provide the necessary tools to support those test cases. The enhanced mock will be particularly useful for scenarios like:

  1. Verifying single and multiple pool creations (by checking NumPublishPairCalls).
  2. Ensuring no publishing occurs when no pools are created.
  3. Handling cases where pool creation data doesn't match existing pools.

To fully align with the PR objectives, ensure that the test suite TestBlockUpdateIndexerBlockProcessStrategyTestSuite (mentioned in the PR summary) utilizes these new capabilities of the PublisherMock.

Consider documenting these new capabilities in the package documentation or in a README file to help other developers understand and utilize the enhanced mock effectively in their tests.

ingest/indexer/service/blockprocessor/full_indexer_block_process_strategy_test.go (3)

56-59: Initialize Chain Pools in Setup Method

The s.PrepareAllSupportedPools() method is being called within each test case. Consider moving this initialization to a SetupTest() method to reduce redundancy and ensure consistent test setup.


127-135: Expand Test Cases for Edge Conditions

In the "happy path with one pool creation" scenario, only a single pool creation is tested. To enhance test coverage, consider adding cases for edge conditions such as zero pools, maximum pool IDs, or invalid data to ensure the system handles these scenarios gracefully.


216-217: Consistent Naming for Mock Objects

The pairPublisherMock is inconsistently named compared to other mocks like publisherMock. For consistency and readability, consider renaming it to pairPublisherMock throughout or aligning the naming convention used for other mocks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 265a87b and 6d60078.

📒 Files selected for processing (2)
  • ingest/indexer/domain/mocks/publisher_mock.go (1 hunks)
  • ingest/indexer/service/blockprocessor/full_indexer_block_process_strategy_test.go (1 hunks)
🔇 Additional comments (5)
ingest/indexer/domain/mocks/publisher_mock.go (1)

11-25: Excellent enhancement to the PublisherMock struct!

The addition of counters for each publish method (e.g., NumPublishPairCalls, NumPublishBlockCalls, etc.) significantly improves the mock's functionality. These counters allow for more precise assertions in tests, enabling verification of not just the arguments passed to these methods, but also the number of times each method is called. This enhancement will lead to more robust and comprehensive tests.

ingest/indexer/service/blockprocessor/full_indexer_block_process_strategy_test.go (4)

97-98: Assert Published Token Supply Contents

While the test checks the number of calls to PublishTokenSupply and PublishTokenSupplyOffset, it doesn't verify the actual contents published. Consider adding assertions to validate that the correct token supplies with expected values are being published.


236-238: Verify Creation Data Accuracy

The test asserts the equality of test.createdPoolIDs and pairPublisherMock.CalledWithCreatedPoolIDs, but it doesn't delve into the correctness of the data within these IDs. Enhance the test by verifying that each pool's creation data matches expected values to ensure data integrity.


41-101: TestPublishAllSupplies Functionality is Correct

The TestPublishAllSupplies method effectively validates that the correct number of token supplies and offsets are published based on the primed data. The test logic is sound and covers the expected scenarios.


103-243: Comprehensive Testing in TestProcessPools

The TestProcessPools method provides thorough coverage for various scenarios, including single and multiple pool creations, absence of pool creation data, and unmatched pool IDs. The tests are well-structured and validate the expected behaviors accurately.

Comment on lines +94 to +95
blockProcessor := blockprocessor.NewFullIndexerBlockProcessStrategy(publisherMock, keepers, poolsExtracter, pairPublisherMock)

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use Interface Types for Dependencies

When creating the blockProcessor, you're directly injecting concrete types for publisherMock, keepers, poolsExtracter, and pairPublisherMock. To enhance modularity and testability, consider defining interfaces for these dependencies and using those interfaces in the constructor of FullIndexerBlockProcessStrategy.

@cryptomatictrader cryptomatictrader merged commit 01f4c8c into main Oct 3, 2024
1 check passed
@cryptomatictrader cryptomatictrader deleted the calvin/add_test_cases_to_block_update_indexer_block_process_strategy branch October 3, 2024 18:39
mergify bot pushed a commit that referenced this pull request Oct 3, 2024
…strategy (#8735)

* add test cases to block_update_indexer_block_process_strat

* enhanced pair publisher mock

* renamed some vars

* optimization - should publish newly created pool only

* updated comments after test case updated

* feat: [indexer] add test cases to full_indexer_block_process_strategy (#8736)

* add test cases to full_indexer_block_process_strategy

* add vars to test file to avoid code dup

* promote common vars for test purposes

(cherry picked from commit 01f4c8c)
cryptomatictrader added a commit that referenced this pull request Oct 3, 2024
…strategy (#8735) (#8752)

* add test cases to block_update_indexer_block_process_strat

* enhanced pair publisher mock

* renamed some vars

* optimization - should publish newly created pool only

* updated comments after test case updated

* feat: [indexer] add test cases to full_indexer_block_process_strategy (#8736)

* add test cases to full_indexer_block_process_strategy

* add vars to test file to avoid code dup

* promote common vars for test purposes

(cherry picked from commit 01f4c8c)

Co-authored-by: Calvin <calvinchso@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A:backport/v26.x backport patches to v26.x branch A:no-changelog V:state/compatible/backport State machine compatible PR, should be backported
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants