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(baseapp): integrate the appdata.Listener in baseapp #21965

Merged
merged 5 commits into from
Oct 3, 2024

Conversation

cool-develope
Copy link
Contributor

@cool-develope cool-develope commented Sep 28, 2024

Description

Closes: #21526


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features

    • Enhanced handling of block finalization events with improved transaction and event processing.
    • Introduced new data structures for transactions and events to provide a more structured approach.
    • Improved event tracking by appending indices to transactions and events for better traceability.
  • Bug Fixes

    • Addressed issues related to transaction handling by iterating through requests more effectively.

Copy link
Contributor

coderabbitai bot commented Sep 28, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request enhance the functionality of the FinalizeBlock method and related components within the BaseApp. Modifications include the addition of transaction indexing in the internalFinalizeBlock method, which improves tracking of transaction execution order. The application hash is also correctly set after block finalization. Additionally, the event handling mechanisms are updated to include indexing for events during the block processing lifecycle, ensuring better traceability and management of events.

Changes

Files Change Summary
baseapp/abci.go Enhanced FinalizeBlock and internalFinalizeBlock methods to include transaction indexing and correct application hash setting.
baseapp/baseapp.go Updated preBlock, beginBlock, and endBlock methods to append event indexing logic.
baseapp/streaming.go Modified ListenFinalizeBlock to enhance transaction processing and event handling with new data structures.
baseapp/abci_test.go Added new test cases and improved error handling and assertions for ABCI functionality.
baseapp/streaming_test.go Introduced new mock listener and test cases to verify event handling and data capturing during block processing.

Assessment against linked issues

Objective Addressed Explanation
Correctly convert data from FinalizeBlockRequest into appdata.StartBlockData and appdata.TxData (#[21526])
Convert events from FinalizeBlockResponse into appdata.EventData (#[21526])
Call the appropriate StartBlock, OnTx, and OnEvent functions on Listener (#[21526])
Extract TxIndex, MsgIndex, and EventIndex attributes for appdata.Event (#[21526]) Unclear if all indices are properly extracted.

Possibly related PRs

Suggested labels

C:server/v2, C:server/v2 cometbft, C:server/v2 stf, C:schema, backport/v0.52.x

Suggested reviewers

  • tac0turtle
  • julienrbrt
  • testinginprod
  • aaronc
  • kocubinski

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.

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

@cool-develope your pull request is missing a changelog!

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

🧹 Outside diff range and nitpick comments (1)
baseapp/streaming.go (1)

175-176: Set appropriate BlockStage for events.

Currently, BlockStage is set to appdata.UnknownBlockStage. If you know the specific block stage during which these events occur, consider setting it to the appropriate constant to improve event classification.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7fe95fc and 77e3325.

📒 Files selected for processing (1)
  • baseapp/streaming.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
baseapp/streaming.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

Comment on lines 152 to 156
if err := p.listener.StartBlock(appdata.StartBlockData{
Height: uint64(req.Height),
HeaderBytes: nil, // TODO: need to define a header struct including enc/decoding
HeaderJSON: nil, // TODO: need to define a header json struct
}); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address TODOs for HeaderBytes and HeaderJSON in StartBlockData.

The HeaderBytes and HeaderJSON fields are currently set to nil, with TODO comments indicating the need to define a header struct including encoding and decoding. Implementing these fields is important for proper handling of header information in the listener.

Would you like assistance in defining the header struct and implementing the necessary encoding/decoding functions?

Comment on lines 160 to 170
if p.listener.OnTx != nil {
for i, tx := range req.Txs {
if err := p.listener.OnTx(appdata.TxData{
TxIndex: int32(i),
Bytes: func() ([]byte, error) { return tx, nil },
JSON: nil, // TODO: need to define a tx json struct
}); err != nil {
return err
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement JSON representation for transactions in TxData.

In the OnTx listener invocation, the JSON field of TxData is set to nil, with a TODO comment indicating the need to define a JSON struct for transactions. Providing a JSON representation of transactions may be important for downstream processing or indexing.

Do you need help in defining the transaction JSON struct and implementing its encoding?

Comment on lines 171 to 190
if p.listener.OnEvent != nil {
events := make([]appdata.Event, len(res.Events))
for i, event := range res.Events {
events[i] = appdata.Event{
BlockStage: appdata.UnknownBlockStage,
Type: event.Type,
Data: nil,
Attributes: func() ([]appdata.EventAttribute, error) {
attrs := make([]appdata.EventAttribute, len(event.Attributes))
for j, attr := range event.Attributes {
attrs[j] = appdata.EventAttribute{
Key: attr.Key,
Value: attr.Value,
}
}
return attrs, nil
},
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Events are constructed but not processed; missing call to OnEvent method.

After constructing the events slice from res.Events, the code does not invoke any method to process these events. This may result in events not being properly handled by the listener.

You may need to call p.listener.OnEvent with the constructed events slice to ensure events are processed correctly. For example:

if err := p.listener.OnEvent(events); err != nil {
    return err
}

@cool-develope cool-develope marked this pull request as ready for review October 3, 2024 00:18
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: 4

🧹 Outside diff range and nitpick comments (10)
baseapp/streaming.go (2)

147-197: LGTM with a suggestion for simplification

The eventToAppDataEvent function correctly converts abci.Event to appdata.Event, handling various attributes and block stages. However, the attribute conversion could be simplified.

Consider simplifying the attribute conversion by removing the closure:

 appdataEvent := appdata.Event{
     Type: event.Type,
-    Attributes: func() ([]appdata.EventAttribute, error) {
-        attrs := make([]appdata.EventAttribute, len(event.Attributes))
-        for j, attr := range event.Attributes {
-            attrs[j] = appdata.EventAttribute{
-                Key:   attr.Key,
-                Value: attr.Value,
-            }
-        }
-        return attrs, nil
-    },
+    Attributes: make([]appdata.EventAttribute, len(event.Attributes)),
 }
+for j, attr := range event.Attributes {
+    appdataEvent.Attributes[j] = appdata.EventAttribute{
+        Key:   attr.Key,
+        Value: attr.Value,
+    }
+}

This change simplifies the code without altering its functionality.


210-248: LGTM: Comprehensive implementation of listener calls

The ListenFinalizeBlock method now correctly implements StartBlock, OnTx, and OnEvent listener calls with proper error handling. The event handling is comprehensive, including both block and transaction events.

Consider adding a comment explaining the +1 adjustment for TxIndex, MsgIndex, and EventIndex. For example:

// Add 1 to convert from 0-based to 1-based indexing
appdataEvent.TxIndex = int32(txIndex + 1)

This will help clarify the reasoning behind the adjustment.

baseapp/abci.go (1)

Line range hint 835-852: Improvement: Added transaction index to response events

The changes in this section enhance the internalFinalizeBlock function by adding a transaction index to the response events. This is a valuable addition as it allows for easier tracking and referencing of transactions within a block.

However, there are a couple of points to consider:

  1. The txIndex variable is declared implicitly in the for loop. While this is valid Go syntax, it might be more explicit to declare it before the loop for clarity.

  2. The conversion of txIndex to a string is done for each event attribute. This could be optimized by converting once before the inner loop.

Consider the following optimizations:

for txIndex, rawTx := range req.Txs {
    response := app.deliverTx(rawTx)

    // check after every tx if we should abort
    select {
    case <-ctx.Done():
        return nil, ctx.Err()
    default:
        // continue
    }

    // Convert txIndex to string once
    txIndexStr := strconv.Itoa(txIndex)

    // append the tx index to the response.Events
    for i, event := range response.Events {
        response.Events[i].Attributes = append(event.Attributes,
            abci.EventAttribute{Key: "tx_index", Value: txIndexStr})
    }

    txResults = append(txResults, response)
}

This refactoring improves readability and potentially performance by converting the index to a string only once per transaction.

baseapp/abci_test.go (7)

Line range hint 683-750: Consider adding edge case tests for TestABCI_VoteExtensions

While the test covers standard scenarios, adding tests for edge cases—such as missing vote extensions, invalid signatures, or unexpected data formats—would improve the robustness of the test suite and ensure the application handles all possible scenarios correctly.


Line range hint 751-770: Correct error message capitalization

Per the Uber Go Style Guide, error messages should not be capitalized. Update the error messages to begin with a lowercase letter for consistency.

Apply this diff to correct the error messages:

-	require.NoError(t, err, "Some error")
+	require.NoError(t, err, "some error")

Line range hint 783-800: Add a comment to explain TestABCI_PrepareProposal_FailReCheckTx

Including a brief comment above the test function improves readability and helps other developers understand the purpose of the test.

Apply this diff to add the comment:

+// TestABCI_PrepareProposal_FailReCheckTx verifies that transactions failing ReCheckTx are not included in PrepareProposal.
 func TestABCI_PrepareProposal_FailReCheckTx(t *testing.T) {
     // Test implementation...
 }

Line range hint 920-940: Use t.Run for subtests in table-driven tests

To enhance test reporting and isolation, wrap each iteration in t.Run with the test case name. This practice allows for better identification of failing cases.

Apply this diff to modify the test:

 for _, tc := range testCases {
-	// Existing code...
+	t.Run(tc.name, func(t *testing.T) {
+		// Existing code...
+	})
 }

Line range hint 980-1050: Avoid non-deterministic random values in tests

Using non-deterministic random values can lead to flaky tests. Seed the random number generator or use fixed values to ensure consistent test results.

Apply this diff to seed the random number generator:

 func TestBaseApp_VoteExtensions(t *testing.T) {
+	rand.Seed(1) // Seed the RNG for deterministic results
 	ctrl := gomock.NewController(t)
 	valStore := mock.NewMockValidatorStore(ctrl)
     // Rest of the test code...

Line range hint 1150-1170: Handle potential errors in marshalDelimitedFn function

While using protoio.NewDelimitedWriter, consider checking for errors that may arise during message writing to enhance error handling robustness.

Apply this diff to handle possible errors:

 func marshalDelimitedFn(msg proto.Message) ([]byte, error) {
 	var buf bytes.Buffer
-	protoio.NewDelimitedWriter(&buf).WriteMsg(msg)
+	if err := protoio.NewDelimitedWriter(&buf).WriteMsg(msg); err != nil {
+		return nil, err
+	}
 	return buf.Bytes(), nil
 }

Line range hint 1250-1270: Improve variable naming for clarity

Consider renaming variables like ve and vres to more descriptive names, such as voteExtension and verifyResponse, to enhance code readability.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 77e3325 and 9666e38.

📒 Files selected for processing (5)
  • baseapp/abci.go (3 hunks)
  • baseapp/abci_test.go (1 hunks)
  • baseapp/baseapp.go (4 hunks)
  • baseapp/streaming.go (2 hunks)
  • baseapp/streaming_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
baseapp/abci.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

baseapp/abci_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

baseapp/baseapp.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

baseapp/streaming.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

baseapp/streaming_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

🔇 Additional comments (10)
baseapp/streaming.go (3)

203-207: LGTM: Well-documented test helper function

The NewListenerWrapper function is a simple and clear implementation for creating a listenerWrapper instance. It's properly documented as being used only for testing purposes.


213-214: Address TODOs for HeaderBytes and HeaderJSON in StartBlockData

The HeaderBytes and HeaderJSON fields are currently set to nil, with TODO comments indicating the need to define a header struct including encoding and decoding. Implementing these fields is important for proper handling of header information in the listener.


224-224: Implement JSON representation for transactions in TxData

In the OnTx listener invocation, the JSON field of TxData is set to nil, with a TODO comment indicating the need to define a JSON struct for transactions. Providing a JSON representation of transactions may be important for downstream processing or indexing.

baseapp/baseapp.go (5)

721-729: Improved event traceability with indexing

The addition of "event_index" and "mode" attributes to all events in the preBlock function enhances event traceability. This change allows for better tracking and ordering of events during the PreBlock phase.


751-751: Consistent event indexing in BeginBlock

The addition of the "event_index" attribute to BeginBlock events maintains consistency with the preBlock function changes. This ensures uniform event tracking across different phases of block processing.


814-814: Consistent event indexing across all block phases

The addition of the "event_index" attribute to EndBlock events completes the implementation of consistent event indexing across all block processing phases (PreBlock, BeginBlock, and EndBlock). This uniformity enhances the overall traceability and analysis of events throughout the block lifecycle.


1165-1170: Comprehensive event indexing including message events

The createEvents function now includes "event_index" attributes for all events, including the message event. The indexing scheme (0 for the message event, 1 and onwards for other events) ensures clear ordering and easy identification of the primary message event. This change complements the event indexing implemented in the block processing phases, providing a comprehensive event tracking system.


Line range hint 721-1170: Summary: Comprehensive event indexing system implemented

The changes in this file introduce a robust event indexing system across various stages of block processing and message handling. Key improvements include:

  1. Consistent addition of "event_index" attributes in PreBlock, BeginBlock, and EndBlock functions.
  2. Implementation of event indexing in the createEvents function, ensuring all events, including message events, are properly indexed.
  3. Maintenance of a consistent indexing scheme across different parts of the code.

These enhancements significantly improve event traceability and provide better tools for analyzing the sequence and origin of events throughout the block lifecycle. The implementation is consistent and well-integrated with the existing codebase.

baseapp/abci.go (1)

Line range hint 1-1252: Overall assessment: Positive improvement with minor optimization opportunities

The changes made to the baseapp/abci.go file, specifically in the internalFinalizeBlock function, represent a positive improvement to the transaction processing pipeline. By adding transaction indices to the response events, the code enhances the traceability and referencing capabilities of transactions within a block.

While the implementation is functionally correct, there are minor optimization opportunities as mentioned in the previous comment. These optimizations could potentially improve performance and code readability slightly.

No other significant changes were observed in the provided diff for this file. The modifications are focused and appear to achieve their intended purpose without introducing any apparent issues or breaking existing functionality.

baseapp/abci_test.go (1)

Line range hint 1051-1070: Check for errors when seeding the random number generator

Ensure that the seed operation does not introduce any errors or unintended side effects in the tests.

No code changes are required, but please confirm that the seeding does not affect other tests or parts of the codebase.

Comment on lines +162 to +190
func newMockAppDataListener() *mockAppDataListener {
listener := &mockAppDataListener{}

// Initialize the Listener with custom behavior to store data
listener.Listener = appdata.Listener{
StartBlock: func(data appdata.StartBlockData) error {
listener.startBlockData = append(listener.startBlockData, data) // Store StartBlockData
return nil
},
OnTx: func(data appdata.TxData) error {
listener.txData = append(listener.txData, data) // Store TxData
return nil
},
OnEvent: func(data appdata.EventData) error {
listener.eventData = append(listener.eventData, data) // Store EventData
return nil
},
OnKVPair: func(data appdata.KVPairData) error {
listener.kvPairData = append(listener.kvPairData, data) // Store KVPairData
return nil
},
Commit: func(data appdata.CommitData) (func() error, error) {
listener.commitData = append(listener.commitData, data) // Store CommitData
return nil, nil
},
}

return listener
}
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

Simplify the newMockAppDataListener function and closures

In newMockAppDataListener, the closures capture the listener variable. To avoid potential confusion and ensure correct behavior, you can assign the function fields after initializing the struct.

Modify the function to initialize the struct and then assign the methods:

func newMockAppDataListener() *mockAppDataListener {
	listener := &mockAppDataListener{}

	listener.StartBlock = func(data appdata.StartBlockData) error {
		listener.startBlockData = append(listener.startBlockData, data)
		return nil
	}
	// Similarly assign other methods: OnTx, OnEvent, OnKVPair, Commit

	return listener
}

This avoids embedding the interface and makes the code clearer.

Comment on lines +12 to +17
"cosmossdk.io/schema/appdata"
storetypes "cosmossdk.io/store/types"

"github.com/cosmos/cosmos-sdk/baseapp"
baseapptestutil "github.com/cosmos/cosmos-sdk/baseapp/testutil"
sdk "github.com/cosmos/cosmos-sdk/types"
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

Organize import statements according to Go conventions

The import statements should be grouped into standard library packages, third-party packages, and local packages, each separated by a blank line.

Consider reorganizing the imports:

 import (
 	"context"
 	"fmt"
 	"testing"

 	abci "github.com/cometbft/cometbft/api/cometbft/abci/v1"
 	tmproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
 	"github.com/stretchr/testify/require"

+	"cosmossdk.io/schema/appdata"
+	storetypes "cosmossdk.io/store/types"

 	"github.com/cosmos/cosmos-sdk/baseapp"
 	baseapptestutil "github.com/cosmos/cosmos-sdk/baseapp/testutil"
 	sdk "github.com/cosmos/cosmos-sdk/types"
 )

-	"cosmossdk.io/schema/appdata"
-	storetypes "cosmossdk.io/store/types"

This improves readability and conforms to the Go import grouping conventions.

Committable suggestion was skipped due to low confidence.

Comment on lines +152 to +160
type mockAppDataListener struct {
appdata.Listener

startBlockData []appdata.StartBlockData
txData []appdata.TxData
eventData []appdata.EventData
kvPairData []appdata.KVPairData
commitData []appdata.CommitData
}
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

Avoid embedding interfaces; implement methods explicitly

Embedding an interface (appdata.Listener) in mockAppDataListener can lead to confusion. It's clearer to implement the interface methods explicitly.

Refactor mockAppDataListener to implement the appdata.Listener interface without embedding:

 type mockAppDataListener struct {
-	appdata.Listener

 	startBlockData []appdata.StartBlockData
 	txData         []appdata.TxData
 	eventData      []appdata.EventData
 	kvPairData     []appdata.KVPairData
 	commitData     []appdata.CommitData
 }

Then define the methods required by appdata.Listener on mockAppDataListener.

Committable suggestion was skipped due to low confidence.

Comment on lines +192 to +333
txCount := 5
txs := make([][]byte, txCount)

for i := 0; i < txCount; i++ {
tx := newTxCounter(t, suite.txConfig, suite.ac, int64(i), int64(i))

txBytes, err := suite.txConfig.TxEncoder()(tx)
require.NoError(t, err)

sKey := []byte(fmt.Sprintf("distKey%d", i))
sVal := []byte(fmt.Sprintf("distVal%d", i))
store := getFinalizeBlockStateCtx(suite.baseApp).KVStore(distKey1)
store.Set(sKey, sVal)

txs[i] = txBytes
}

_, err = suite.baseApp.FinalizeBlock(&abci.FinalizeBlockRequest{Height: 1, Txs: txs})
require.NoError(t, err)
_, err = suite.baseApp.Commit()
require.NoError(t, err)

// StartBlockData
require.Len(t, mockListener.startBlockData, 1)
require.Equal(t, uint64(1), mockListener.startBlockData[0].Height)
// TxData
txData := mockListener.txData
require.Len(t, txData, len(txs))
for i := 0; i < txCount; i++ {
require.Equal(t, int32(i), txData[i].TxIndex)
txBytes, err := txData[i].Bytes()
require.NoError(t, err)
require.Equal(t, txs[i], txBytes)
}
// KVPairData
require.Len(t, mockListener.kvPairData, 1)
updates := mockListener.kvPairData[0].Updates
for i := 0; i < txCount; i++ {
require.Equal(t, []byte(distKey1.Name()), updates[i].Actor)
require.Len(t, updates[i].StateChanges, 1)
sKey := []byte(fmt.Sprintf("distKey%d", i))
sVal := []byte(fmt.Sprintf("distVal%d", i))
require.Equal(t, sKey, updates[i].StateChanges[0].Key)
require.Equal(t, sVal, updates[i].StateChanges[0].Value)
}
// CommitData
require.Len(t, mockListener.commitData, 1)
// EventData
require.Len(t, mockListener.eventData, 1)
events := mockListener.eventData[0].Events
require.Len(t, events, 3+txCount*3)

for i := 0; i < 3; i++ {
require.Equal(t, int32(0), events[i].TxIndex)
require.Equal(t, int32(0), events[i].MsgIndex)
require.Equal(t, int32(1), events[i].EventIndex)
attrs, err := events[i].Attributes()
require.NoError(t, err)
require.Len(t, attrs, 2)
switch i {
case 0:
require.Equal(t, appdata.PreBlockStage, events[i].BlockStage)
require.Equal(t, "pre-block", events[i].Type)
case 1:
require.Equal(t, appdata.BeginBlockStage, events[i].BlockStage)
require.Equal(t, "begin-block", events[i].Type)
case 2:
require.Equal(t, appdata.EndBlockStage, events[i].BlockStage)
require.Equal(t, "end-block", events[i].Type)
}
}

for i := 3; i < 3+txCount*3; i++ {
require.Equal(t, appdata.TxProcessingStage, events[i].BlockStage)
require.Equal(t, int32(i/3), events[i].TxIndex)
switch i % 3 {
case 0:
require.Equal(t, "ante_handler", events[i].Type)
require.Equal(t, int32(0), events[i].MsgIndex)
require.Equal(t, int32(0), events[i].EventIndex)
attrs, err := events[i].Attributes()
require.NoError(t, err)
require.Len(t, attrs, 2)
case 1:
require.Equal(t, "message", events[i].Type)
require.Equal(t, int32(1), events[i].MsgIndex)
require.Equal(t, int32(1), events[i].EventIndex)
attrs, err := events[i].Attributes()
require.NoError(t, err)
require.Len(t, attrs, 5)
case 2:
require.Equal(t, "message", events[i].Type)
require.Equal(t, int32(1), events[i].MsgIndex)
require.Equal(t, int32(2), events[i].EventIndex)
attrs, err := events[i].Attributes()
require.NoError(t, err)
require.Len(t, attrs, 4)
}
}
}
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

Enhance test coverage and assertion clarity

In TestAppDataListener, consider the following improvements:

  • Test Edge Cases: Include tests for edge cases such as zero transactions, error handling in listener methods, and unusual event sequences.
  • Use Descriptive Variable Names: Replace generic names like i with more descriptive names where appropriate for better readability.
  • Assertion Messages: Add custom messages to assertions to clarify the purpose of each test and make debugging easier.

Review and update the test function to enhance coverage and maintainability:

 for txIndex := 0; txIndex < txCount; txIndex++ {
 	require.Equal(t, int32(txIndex), txData[txIndex].TxIndex, "TxIndex should match the transaction index")
 	txBytes, err := txData[txIndex].Bytes()
 	require.NoError(t, err)
 	require.Equal(t, txs[txIndex], txBytes, "Transaction bytes should match the original txBytes")
 }

Adding descriptive messages and variable names improves the clarity of the tests.

Committable suggestion was skipped due to low confidence.

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

ACK!

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Oct 3, 2024
@cool-develope cool-develope added this pull request to the merge queue Oct 3, 2024
Merged via the queue into main with commit 80726f7 Oct 3, 2024
72 of 75 checks passed
@cool-develope cool-develope deleted the baseapp/listener branch October 3, 2024 13:14
mergify bot pushed a commit that referenced this pull request Oct 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Complete main/0.52 indexer BaseApp Integration
6 participants