8000 test: add test for encoding.go by keke-ka · Pull Request #3018 · evmos/evmos · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

test: add test for encoding.go #3018

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

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft

test: add test for encoding.go #3018

wants to merge 10 commits into from

Conversation

keke-ka
Copy link
Contributor
@keke-ka keke-ka commented Dec 9, 2024

Description

Closes: #XXXX


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

  • tackled an existing issue or discussed with a team member
  • left instructions on how to review the changes
  • targeted the correct branch (see PR Targeting)

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.

I have...

  • added a relevant changelog entry to the Unreleased section in CHANGELOG.md
  • confirmed all author checklist items have been addressed
  • confirmed that this PR does not change production code
  • reviewed content
  • tested instructions (if applicable)
  • confirmed all CI checks have passed

Summary by CodeRabbit

  • New Features
    • Introduced a new testing framework for EIP-712 typed data encoding.
    • Implemented comprehensive tests for message encoding and sign documents.
  • Bug Fixes
    • Enhanced error handling during the encoding process.

@keke-ka keke-ka requested a review from a team as a code owner December 9, 2024 04:01
@keke-ka keke-ka requested review from MalteHerrmann and 0xstepit and removed request for a team December 9, 2024 04:02
@CLAassistant
Copy link
CLAassistant commented Dec 9, 2024

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor
coderabbitai bot commented Dec 9, 2024

Caution

Review failed

The head commit changed during the review from 6716885 to 9814b0b.

Walkthrough

The pull request introduces a new test file, encoding_test.go, which focuses on testing the encoding of EIP-712 typed data within the Cosmos SDK framework. It sets up necessary configurations, including address prefixes and codec initializations, and defines a test function that verifies the encoding of a banktypes.MsgSend message and its corresponding sign document. This setup ensures the correct functioning of the encoding process for EIP-712.

Changes

File Change Summary
ethereum/eip712/encoding_test.go - New package declaration: package eip712_test
- Declared variables: var aminoCodec *codec.LegacyAmino, var interfaceRegistry types.InterfaceRegistry
- Added functions: func initAddressConfig(), func initCodecs(), func TestGetEIP712TypedDataForMsg_AminoSuccess(t *testing.T)

Poem

In the land where codes do play,
A rabbit hops, brightening the day.
With EIP-712, a test takes flight,
Encoding messages, all done right!
Hooray for codecs, let’s cheer and sing,
For every byte, a joyful spring! 🐰✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

level=warning msg="[config_reader] The configuration option run.skip-dirs is deprecated, please use issues.exclude-dirs."
level=warning msg="[config_reader] The configuration option linters.gofumpt.lang-version is deprecated, please use global run.go."


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
@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: 2

🧹 Outside diff range and nitpick comments (1)
ethereum/eip712/encoding_test.go (1)

17-20: Consider using a test fixture instead of global variables

Global variables in tests can make them harder to maintain and potentially cause issues with parallel test execution. Consider using a test fixture struct:

-var (
-	aminoCodec        *codec.LegacyAmino
-	interfaceRegistry types.InterfaceRegistry
-)

+type testFixture struct {
+	aminoCodec        *codec.LegacyAmino
+	interfaceRegistry types.InterfaceRegistry
+}
+
+func newTestFixture() *testFixture {
+	return &testFixture{
+		aminoCodec:        codec.NewLegacyAmino(),
+		interfaceRegistry: types.NewInterfaceRegistry(),
+	}
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 06920d4 and 1d7dc1e.

📒 Files selected for processing (1)
  • ethereum/eip712/encoding_test.go (1 hunks)
🔇 Additional comments (2)
ethereum/eip712/encoding_test.go (2)

44-69: 🛠️ Refactor suggestion

Enhance test coverage and structure

The test function needs several improvements:

  1. Remove debug Printf statement
  2. Add table-driven tests for different scenarios< 8000 /li>
  3. Add error cases
  4. Validate the actual EIP712 typed data structure
-func TestGetEIP712TypedDataForMsg_AminoSuccess(t *testing.T) {
+func TestGetEIP712TypedDataForMsg(t *testing.T) {
+	tests := []struct {
+		name    string
+		msg     sdk.Msg
+		signDoc legacytx.StdSignDoc
+		wantErr bool
+	}{
+		{
+			name: "valid MsgSend",
+			msg: banktypes.MsgSend{
+				FromAddress: "cosmos1qperwt9wrnkg6kzfj7s9wf69w5gk3ya6r7l273",
+				ToAddress:   "cosmos1q5x4yng8x6f5v45m59wvndkgj7c32c7dpw2crz",
+				Amount:      sdk.Coins{sdk.NewInt64Coin("stake", 1000)},
+			},
+			signDoc: legacytx.StdSignDoc{
+				AccountNumber: 1,
+				ChainID:      "evmos_9001-1",
+				Sequence:     1,
+				Fee:          json.RawMessage(`{"amount":[{"denom":"stake","amount":"10"}],"gas":"200000"}`),
+				Memo:         "test memo",
+			},
+			wantErr: false,
+		},
+		// Add more test cases here
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			fixture := newTestFixture()
+			require.NoError(t, fixture.initCodecs(t))
+
+			msgBytes, err := fixture.aminoCodec.MarshalJSON(tt.msg)
+			if tt.wantErr {
+				require.Error(t, err)
+				return
+			}
+			require.NoError(t, err)
+
+			tt.signDoc.Msgs = []json.RawMessage{msgBytes}
+			signDocBytes, err := fixture.aminoCodec.MarshalJSON(tt.signDoc)
+			require.NoError(t, err)
+
+			// Validate the actual EIP712 typed data structure
+			typedData, err := eip712.GetEIP712TypedDataForMsg(signDocBytes)
+			require.NoError(t, err)
+			require.NotNil(t, typedData)
+			// Add specific assertions for the typedData structure
+		})
+	}
+}

Let's verify the test coverage:


1-69: Verify test coverage across related packages

Since this is testing critical encoding functionality, we should ensure comprehensive coverage across related packages.

✅ Verification successful

Test coverage appears sufficient and well-structured

The verification shows that the test coverage for EIP712 encoding is comprehensive:

  • There are dedicated test suites (EIP712TestSuite) covering both current and legacy implementations
  • The new test TestGetEIP712TypedDataForMsg_AminoSuccess complements existing tests by covering Amino JSON marshaling
  • The encoding functionality is tested across both encoding.go and encoding_legacy.go with proper error handling

The test structure aligns well with the codebase's needs and doesn't require additional coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for similar encoding tests in related packages
echo "Searching for related encoding tests..."
rg --type go "TestGetEIP712" --stats
rg --type go "encoding.*_test" --stats

# Check for any TODOs or missing test coverage
echo "Checking for TODO comments in related files..."
rg --type go "TODO.*test" ethereum/

Length of output: 775


Script:

#!/bin/bash
# Let's check for all EIP712 related tests and their coverage
echo "Checking EIP712 related tests..."
rg --type go "func Test.*EIP712" -A 5

# Check for encoding related functions and their tests
echo "Checking encoding related functions..."
ast-grep --pattern 'func $_($$$) {
  $$$
  encoding.$$$
  $$$
}'

# Check for any existing test files in the ethereum/eip712 directory
echo "Checking test files in ethereum/eip712..."
fd -e go -e test.go$ ethereum/eip712/

# Look for related encoding test patterns
echo "Looking for encoding test patterns..."
rg --type go "MarshalJSON|UnmarshalJSON" "ethereum/eip712/" -B 1 -A 3

Length of output: 4672

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1d7dc1e and f0d1152.

📒 Files selected for processing (1)
  • ethereum/eip712/encoding_test.go (1 hunks)
🔇 Additional comments (3)
ethereum/eip712/encoding_test.go (3)

1-15: LGTM: Package declaration and imports are well-structured.

The package name follows Go test conventions, and imports are properly organized.


22-28: Improve configuration handling.

The previous review comment about improving configuration handling is still valid. The function modifies global SDK configuration which could affect other tests.


30-42: Refactor initialization for better separation of concerns.

The previous review comment about refactoring initialization is still valid. The function handles multiple initialization tasks without proper error handling.

@GAtom22
Copy link
Contributor
GAtom22 commented Dec 16, 2024

Thanks for the contribution @keke-ka!!
Can you please address the conversations?

@keke-ka
Copy link
Contributor Author
keke-ka commented Dec 19, 2024

Thanks for the contribution @keke-ka!! Can you please address the conversations?

ok, thank you for your notice, I just have time to fix it.

@GAtom22
Copy link
Contributor
GAtom22 commented Jan 2, 2025

@keke-ka the test is failing. Please address the error

Copy link
Contributor
@MalteHerrmann MalteHerrmann left a comment

Choose a reason for hiding this comment

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

The test is incomplete and not yet testing anything - also please refrain from re-setting all of the SDK config and rather use encoding.MakeConfig instead to get the amino codec.

Will mark as draft for the time being.

@MalteHerrmann MalteHerrmann marked this pull request as draft January 7, 2025 09:44
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.

7 participants
0