Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@ChengenH
Copy link

@ChengenH ChengenH commented Dec 8, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced error handling across multiple functions for improved readability and consistency.
  • Bug Fixes

    • Simplified error creation by replacing fmt.Errorf with errors.New in various methods, ensuring clearer error reporting.
    • Improved error checking mechanisms using errors.Is for better handling of wrapped errors.
  • Chores

    • Removed unused import statements for fmt in several files to streamline code.
  • Tests

    • Introduced unit tests for NewStack() and NewReturnStack() functions to ensure proper functionality and error handling.

@ChengenH ChengenH requested a review from a team as a code owner December 8, 2024 08:20
@ChengenH ChengenH requested review from GAtom22 and ramacarlucho and removed request for a team December 8, 2024 08:20
@CLAassistant
Copy link

CLAassistant commented Dec 8, 2024

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 8, 2024

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

Walkthrough

The changes in this pull request focus on modifying error handling across multiple files in the x/evm package. The updates involve replacing fmt.Errorf with errors.New for generating error messages, thereby standardizing the error creation process. This adjustment enhances readability and consistency in error handling without altering the overall logic or functionality of the affected methods. The changes span various components, including tracers, EIP validation, stack management, configuration, and message handling.

Changes

File Path Change Summary
x/evm/core/tracers/js/goja.go Changed error handling in fromBuf function from fmt.Errorf to errors.New. No other significant changes.
x/evm/core/vm/eips.go Updated error handling in ValidateEIPName function to use errors.New instead of fmt.Errorf. Added import for errors package.
x/evm/core/vm/stack.go Modified error handling in NewStack and NewReturnStack functions to use errors.New. No changes to stack functionality.
x/evm/types/config.go Changed error handling in Configure method of EVMConfigurator from fmt.Errorf to errors.New. Added import for errors package.
x/evm/types/config_testing.go Updated error handling in Configure method to use errors.New. Removed unused import of fmt.
x/evm/types/msg.go Replaced fmt.Errorf with errors.New in Sign method. Removed import of fmt.
x/evm/types/utils.go Updated UnwrapEthereumMsg function to use errors.New. Enhanced error message clarity in UnpackEthMsg with errorsmod.Wrapf.
x/evm/core/vm/stack_test.go Introduced unit tests for NewStack() and NewReturnStack() functions, covering both successful and error cases.
rpc/websockets.go Updated error handling in Start method to use errors.Is for checking http.ErrServerClosed.
server/json_rpc.go Modified error handling in StartJSONRPC function to use errors.Is for checking http.ErrServerClosed.
wallets/usbwallet/ledger.go Changed error handling in Open method to use errors.Is for checking errLedgerReplyInvalidHeader.
x/evm/core/tracers/native/revertreason.go Updated error handling in CaptureEnd method to use errors.Is for checking vm.ErrExecutionReverted.
x/evm/core/vm/instructions.go Modified error checks in multiple functions to use errors.Is for improved error handling.
x/evm/core/vm/interpreter.go Changed error handling in Run method to use errors.Is for checking errStopToken.

Possibly related PRs

Suggested reviewers

  • GAtom22
  • 0xstepit
  • Vvaradinov
  • ramacarlucho

Poem

🐰 In the code where errors dwell,
A change was made, and all is well.
From fmt to errors, clear and bright,
Simplified handling, a coding delight!
With each new line, our paths align,
In the world of code, we brightly shine! 🌟

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


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

🧹 Outside diff range and nitpick comments (3)
x/evm/types/utils.go (1)

73-73: LGTM! Consider standardizing error handling patterns

The change to errors.New is appropriate for static error messages. However, for consistency, consider using a custom error type or error wrapping for all error cases in this file.

Consider creating custom error types for common errors:

var (
    ErrNilTransaction = errors.New("invalid tx: nil")
    ErrInvalidTxType = func(t any) error { return fmt.Errorf("invalid tx type: %T", t) }
    ErrTxNotFound = func(hash string) error { return fmt.Errorf("eth tx not found: %s", hash) }
)
x/evm/types/msg.go (1)

230-230: LGTM! Consider adding error documentation

The change to errors.New is appropriate. The error handling throughout this file consistently uses error wrapping where context is needed.

Consider adding error documentation for common errors:

// Common errors returned by MsgEthereumTx methods
var (
    // ErrSenderNotDefined is returned when attempting to sign a transaction without a defined sender
    ErrSenderNotDefined = errors.New("sender address not defined for message")
)
x/evm/core/tracers/js/goja.go (1)

86-86: LGTM! Consider adding error documentation.

The change from fmt.Errorf to errors.New is appropriate since no string formatting is needed. This follows Go best practices for error creation.

Consider documenting the scenarios that can trigger this error by adding a comment above the function explaining what constitutes an "invalid buffer type". This would help developers understand and handle the error case better.

+// fromBuf converts a JavaScript value to a byte slice. It accepts:
+// - Uint8Array: converted to []byte directly
+// - String: converted from hex if allowString is true
+// - Array: converted to []byte if elements are valid
+// Returns "invalid buffer type" error for other types.
 func fromBuf(vm *goja.Runtime, bufType goja.Value, buf goja.Value, allowString bool) ([]byte, error) {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 06920d4 and 50000d8.

📒 Files selected for processing (7)
  • x/evm/core/tracers/js/goja.go (1 hunks)
  • x/evm/core/vm/eips.go (2 hunks)
  • x/evm/core/vm/stack.go (3 hunks)
  • x/evm/types/config.go (2 hunks)
  • x/evm/types/config_testing.go (1 hunks)
  • x/evm/types/msg.go (1 hunks)
  • x/evm/types/utils.go (2 hunks)
🔇 Additional comments (4)
x/evm/types/config.go (1)

13-13: LGTM: Appropriate use of errors.New

The change from fmt.Errorf to errors.New is correct here as the error message is static with no format parameters.

Also applies to: 23-23

x/evm/types/config_testing.go (1)

27-27: LGTM: Maintains consistency with config.go

The error message and usage of errors.New matches config.go, maintaining consistency across the codebase.

x/evm/core/vm/stack.go (1)

20-20: LGTM: Consistent error handling improvements

The changes appropriately replace fmt.Errorf with errors.New for static error messages in both NewStack and NewReturnStack functions. The error messages maintain their descriptive nature while following a consistent pattern for type assertion failures.

Also applies to: 43-43, 129-129

x/evm/core/vm/eips.go (1)

57-60: LGTM! Consider enhancing error tests

The changes to use errors.New for static error messages are appropriate.

Let's verify the test coverage for these error cases:

@0xstepit
Copy link
Contributor

0xstepit commented Dec 9, 2024

Hey @ChengenH, thanks for the contribution! Could you please sign the CLA?

@ChengenH
Copy link
Author

ChengenH commented Dec 9, 2024

CLA

Of course, but I have already signed the CLA

CLA assistant check All committers have signed the CLA.

@codecov
Copy link

codecov bot commented Dec 9, 2024

Codecov Report

Attention: Patch coverage is 87.50000% with 1 line in your changes missing coverage. Please review.

Project coverage is 23.51%. Comparing base (f097735) to head (07a113e).
Report is 412 commits behind head on main.

Files with missing lines Patch % Lines
x/evm/core/tracers/js/goja.go 0.00% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##             main    #3017       +/-   ##
===========================================
- Coverage   70.45%   23.51%   -46.94%     
===========================================
  Files         293      435      +142     
  Lines       22559    88845    +66286     
===========================================
+ Hits        15893    20895     +5002     
- Misses       5800    66265    +60465     
- Partials      866     1685      +819     
Files with missing lines Coverage Δ
x/evm/core/vm/eips.go 78.15% <100.00%> (ø)
x/evm/core/vm/stack.go 50.00% <100.00%> (ø)
x/evm/types/config_testing.go 61.90% <100.00%> (ø)
x/evm/types/msg.go 82.11% <100.00%> (+1.84%) ⬆️
x/evm/types/utils.go 59.70% <100.00%> (-0.91%) ⬇️
x/evm/core/tracers/js/goja.go 46.84% <0.00%> (ø)

... and 337 files with indirect coverage changes

@0xstepit
Copy link
Contributor

Hey @ChengenH could you please also address the linter issues?

@ChengenH
Copy link
Author

linter issues

I have added the test cases mentioned in the linter issues, please recheck.

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)
x/evm/core/vm/stack_test.go (2)

24-55: Consider using table-driven tests and cleanup

While the test cases are comprehensive, consider these improvements:

  1. Convert to table-driven tests for better maintainability
  2. Add cleanup to reset stackPool after the test

Example refactor:

 func TestNewStack(t *testing.T) {
-    stackPool = sync.Pool{
-        New: func() interface{} {
-            return &Stack{}
-        },
-    }
-
-    stack, err := NewStack()
-    if err != nil {
-        t.Errorf("Expected no error, got %v", err)
-    }
-    if stack == nil {
-        t.Errorf("Expected a non-nil Stack, got nil")
-    }
-
-    stackPool = sync.Pool{
-        New: func() interface{} {
-            return "not a Stack"
-        },
-    }
+    originalPool := stackPool
+    defer func() {
+        stackPool = originalPool
+    }()
+
+    tests := []struct {
+        name    string
+        poolNew func() interface{}
+        wantErr string
+    }{
+        {
+            name: "success",
+            poolNew: func() interface{} {
+                return &Stack{}
+            },
+        },
+        {
+            name: "type assertion failure",
+            poolNew: func() interface{} {
+                return "not a Stack"
+            },
+            wantErr: "type assertion failure: cannot get Stack pointer from stackPool",
+        },
+    }
+
+    for _, tt := range tests {
+        t.Run(tt.name, func(t *testing.T) {
+            stackPool = sync.Pool{New: tt.poolNew}
+            
+            stack, err := NewStack()
+            if tt.wantErr != "" {
+                if err == nil || err.Error() != tt.wantErr {
+                    t.Errorf("NewStack() error = %v, wantErr %v", err, tt.wantErr)
+                }
+                if stack != nil {
+                    t.Errorf("Expected nil Stack when error, got %v", stack)
+                }
+            } else {
+                if err != nil {
+                    t.Errorf("NewStack() unexpected error = %v", err)
+                }
+                if stack == nil {
+                    t.Errorf("Expected non-nil Stack")
+                }
+            }
+        })
+    }

57-88: Consider reducing test duplication

The TestNewReturnStack function is nearly identical to TestNewStack with just type differences. Consider extracting common test logic to reduce duplication.

Example approach using a generic test helper:

+func testPoolCreation[T any](t *testing.T, newFunc func() (*T, error), pool *sync.Pool, validObj T) {
+    originalPool := *pool
+    defer func() {
+        *pool = originalPool
+    }()
+
+    tests := []struct {
+        name    string
+        poolNew func() interface{}
+        wantErr string
+    }{
+        {
+            name: "success",
+            poolNew: func() interface{} {
+                return &validObj
+            },
+        },
+        {
+            name: "type assertion failure",
+            poolNew: func() interface{} {
+                return "not valid"
+            },
+            wantErr: fmt.Sprintf("type assertion failure: cannot get %T pointer from pool", validObj),
+        },
+    }
+
+    for _, tt := range tests {
+        t.Run(tt.name, func(t *testing.T) {
+            *pool = sync.Pool{New: tt.poolNew}
+            
+            result, err := newFunc()
+            if tt.wantErr != "" {
+                if err == nil || err.Error() != tt.wantErr {
+                    t.Errorf("error = %v, wantErr %v", err, tt.wantErr)
+                }
+                if result != nil {
+                    t.Errorf("Expected nil result when error, got %v", result)
+                }
+            } else {
+                if err != nil {
+                    t.Errorf("unexpected error = %v", err)
+                }
+                if result == nil {
+                    t.Errorf("Expected non-nil result")
+                }
+            }
+        })
+    }
+}
+
 func TestNewStack(t *testing.T) {
-    // Current implementation
+    testPoolCreation(t, NewStack, &stackPool, Stack{})
 }
 
 func TestNewReturnStack(t *testing.T) {
-    // Current implementation
+    testPoolCreation(t, NewReturnStack, &rStackPool, ReturnStack{})
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 50000d8 and 0e5f280.

📒 Files selected for processing (1)
  • x/evm/core/vm/stack_test.go (1 hunks)
🔇 Additional comments (1)
x/evm/core/vm/stack_test.go (1)

1-22: LGTM: License and imports are properly structured

The file includes the appropriate license header and necessary imports for testing.

…up to reset stackPool after the test.

Signed-off-by: ChengenH <[email protected]>
… are different from the project style

Signed-off-by: ChengenH <[email protected]>
@ChengenH ChengenH changed the title chore: use errors.New to replace fmt.Errorf with no parameters refactor: unify the error handling methods in the crypto package that are different from the project style & use errors.New to replace fmt.Errorf with no parameters Dec 13, 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 (1)
x/evm/core/vm/interpreter.go (1)

260-262: Excellent improvement in error handling robustness

The change from direct error comparison to errors.Is is a significant improvement that:

  • Enables detection of wrapped errors containing errStopToken
  • Follows Go 1.13+ error handling best practices
  • Makes the code more maintainable and future-proof

This change goes beyond the PR's original scope (replacing fmt.Errorf with errors.New) but adds valuable robustness to the error handling.

Consider applying similar errors.Is improvements to other error checks in the codebase for consistency.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 07a113e and a915dac.

📒 Files selected for processing (6)
  • rpc/websockets.go (2 hunks)
  • server/json_rpc.go (2 hunks)
  • wallets/usbwallet/ledger.go (1 hunks)
  • x/evm/core/tracers/native/revertreason.go (2 hunks)
  • x/evm/core/vm/instructions.go (5 hunks)
  • x/evm/core/vm/interpreter.go (2 hunks)
🔇 Additional comments (10)
x/evm/core/vm/instructions.go (4)

708-708: LGTM: Improved error handling in opCall

The change from direct error comparison to errors.Is() follows Go best practices for error handling and allows for proper detection of wrapped errors.


744-744: LGTM: Improved error handling in opCallCode

The change from direct error comparison to errors.Is() follows Go best practices for error handling and allows for proper detection of wrapped errors.


773-773: LGTM: Improved error handling in opDelegateCall

The change from direct error comparison to errors.Is() follows Go best practices for error handling and allows for proper detection of wrapped errors.


802-802: LGTM: Improved error handling in opStaticCall

The change from direct error comparison to errors.Is() follows Go best practices for error handling and allows for proper detection of wrapped errors.

x/evm/core/vm/interpreter.go (1)

20-20: LGTM: Import addition follows standard Go conventions

The addition of the errors package import follows standard Go import ordering (standard library imports first) and is necessary for the improved error handling implementation.

server/json_rpc.go (1)

6-6: LGTM! Improved error handling using errors.Is

The change from direct error comparison to errors.Is is a good improvement as it:

  • Handles wrapped errors correctly
  • Follows Go best practices for error handling
  • Makes the code more maintainable

Also applies to: 91-91

x/evm/core/tracers/native/revertreason.go (1)

22-22: LGTM! Enhanced error handling with errors.Is

The change from direct error comparison to errors.Is is a good improvement as it:

  • Handles wrapped errors correctly
  • Follows Go best practices for error handling
  • Makes the code more maintainable

Also applies to: 62-62

wallets/usbwallet/ledger.go (1)

93-93: LGTM! Better error handling using errors.Is

The change from direct error comparison to errors.Is is a good improvement as it:

  • Handles wrapped errors correctly
  • Follows Go best practices for error handling
  • Makes the code more maintainable
rpc/websockets.go (2)

9-9: LGTM: Import added for errors package

The addition of the errors import is necessary for the enhanced error handling using errors.Is.


110-110: LGTM: Improved error handling with errors.Is

The change from direct error comparison to errors.Is follows Go best practices for error handling. This improvement allows for proper detection of http.ErrServerClosed even when it's wrapped by middleware or other error chains.

@GAtom22
Copy link
Contributor

GAtom22 commented Dec 16, 2024

@ChengenH Thanks for the contribution! Please address the linter errors

@ChengenH
Copy link
Author

@ChengenH Thanks for the contribution! Please address the linter errors

Done

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

🧹 Nitpick comments (2)
x/evm/core/vm/stack_test.go (2)

24-75: Consider refactoring the helper function for better maintainability.

The runTest function could benefit from some refactoring to improve maintainability and reduce code duplication:

Consider splitting the function into smaller, more focused helpers:

-func runTest(t *testing.T, name string, newFunc func() interface{}, expectErr bool, errMsg string, testFunc interface{}, pool *sync.Pool) {
+// Generic test result checker
+func checkTestResult[T any](t *testing.T, result T, err error, expectErr bool, errMsg string) {
+	if expectErr {
+		if err == nil {
+			t.Errorf("Expected error, got nil")
+		} else if err.Error() != errMsg {
+			t.Errorf("Expected error message %q, got %q", errMsg, err.Error())
+		}
+		if result != nil {
+			t.Errorf("Expected nil result, got %v", result)
+		}
+		return
+	}
+	if err != nil {
+		t.Errorf("Expected no error, got %v", err)
+	}
+	if result == nil {
+		t.Errorf("Expected a non-nil result, got nil")
+	}
+}
+
+func runTest(t *testing.T, name string, newFunc func() interface{}, expectErr bool, errMsg string, testFunc interface{}, pool *sync.Pool) {
     t.Run(name, func(t *testing.T) {
         originalPool := *pool
         defer func() { *pool = originalPool }()
         pool.New = newFunc
 
         switch tf := testFunc.(type) {
         case func() (*Stack, error):
             stack, err := tf()
-            if expectErr {
-                if err == nil {
-                    t.Errorf("Expected error, got nil")
-                } else if err.Error() != errMsg {
-                    t.Errorf("Expected error message %q, got %q", errMsg, err.Error())
-                }
-                if stack != nil {
-                    t.Errorf("Expected nil Stack, got %v", stack)
-                }
-            } else {
-                if err != nil {
-                    t.Errorf("Expected no error, got %v", err)
-                }
-                if stack == nil {
-                    t.Errorf("Expected a non-nil Stack, got nil")
-                }
-            }
+            checkTestResult(t, stack, err, expectErr, errMsg)
         case func() (*ReturnStack, error):
             rStack, err := tf()
-            if expectErr {
-                if err == nil {
-                    t.Errorf("Expected error, got nil")
-                } else if err.Error() != errMsg {
-                    t.Errorf("Expected error message %q, got %q", errMsg, err.Error())
-                }
-                if rStack != nil {
-                    t.Errorf("Expected nil ReturnStack, got %v", rStack)
-                }
-            } else {
-                if err != nil {
-                    t.Errorf("Expected no error, got %v", err)
-                }
-                if rStack == nil {
-                    t.Errorf("Expected a non-nil ReturnStack, got nil")
-                }
-            }
+            checkTestResult(t, rStack, err, expectErr, errMsg)
         default:
             t.Fatalf("Unexpected test function signature")
         }
     })
 }

This refactoring:

  1. Extracts the common test result checking logic into a generic helper
  2. Reduces code duplication
  3. Makes the code more maintainable
  4. Improves readability

102-125: Consider reducing duplication between test functions.

While the implementation is correct, there's an opportunity to reduce duplication between TestNewStack and TestNewReturnStack.

Consider creating a generic test function:

+type stackTestCase struct {
+    name      string
+    newFunc   func() interface{}
+    expectErr bool
+    errMsg    string
+}
+
+func runStackTest(t *testing.T, tests []stackTestCase, newStackFunc interface{}, pool *sync.Pool) {
+    for _, tt := range tests {
+        runTest(t, tt.name, tt.newFunc, tt.expectErr, tt.errMsg, newStackFunc, pool)
+    }
+}
+
 func TestNewStack(t *testing.T) {
-    tests := []struct {
-        name      string
-        newFunc   func() interface{}
-        expectErr bool
-        errMsg    string
-    }{
+    tests := []stackTestCase{
         {
             name:      "Valid Stack allocation",
             newFunc:   func() interface{} { return &Stack{} },
             expectErr: false,
         },
         {
             name:      "Invalid Stack allocation",
             newFunc:   func() interface{} { return "not a Stack" },
             expectErr: true,
             errMsg:    "type assertion failure: cannot get Stack pointer from stackPool",
         },
     }
-    for _, tt := range tests {
-        runTest(t, tt.name, tt.newFunc, tt.expectErr, tt.errMsg, NewStack, &stackPool)
-    }
+    runStackTest(t, tests, NewStack, &stackPool)
 }

This would:

  1. Reduce code duplication
  2. Make it easier to add new stack-related tests
  3. Keep the test structure consistent
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a915dac and a45b24b.

📒 Files selected for processing (1)
  • x/evm/core/vm/stack_test.go (1 hunks)
🔇 Additional comments (2)
x/evm/core/vm/stack_test.go (2)

17-22: LGTM! Package declaration and imports are correct.

The package is correctly declared as vm_test and imports are minimal and appropriate for the test requirements.


77-100: LGTM! Well-structured table-driven tests.

The test implementation follows good practices:

  • Comprehensive test cases covering both success and failure scenarios
  • Clear test case names and structure
  • Error messages align with the project's unified error handling approach

@GAtom22
Copy link
Contributor

GAtom22 commented Dec 17, 2024

There are some compilation errors. Please address these

@hanchon hanchon marked this pull request as draft January 2, 2025 14:36
@ChengenH ChengenH closed this Feb 1, 2025
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.

4 participants