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

test: add more tests and sentinel errors #66

Merged
merged 6 commits into from
Feb 25, 2025
Merged

Conversation

facundomedica
Copy link
Contributor

@facundomedica facundomedica commented Feb 21, 2025

Overview

The sentinel errors are kept very generic, as there are some cases in which an execution layer would return errors and in others it would not (like initial height being 0).

Closes #16
Partially closes #17

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced validations and error handling for blockchain setup and transaction operations, offering clearer, immediate feedback when inputs are invalid.
    • Improved transaction processing, including more robust injection and execution pathways.
    • Introduction of structured error messages for various blockchain operations.
  • Tests

    • Expanded test coverage with comprehensive scenarios—including concurrent operations—to ensure greater system stability and reliability.

Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

This pull request enhances the blockchain executor by improving validation and error handling. In test/dummy.go, methods for chain initialization, transaction injection, retrieval, and execution have been updated with comprehensive input checks and error returns. The test suite in test/dummy_test.go now includes additional scenarios covering initialization, transaction execution, and concurrency. Moreover, a new types/errors.go file standardizes error declarations for blockchain operations, including chain, transaction, and block finalization errors.

Changes

File(s) Change Summary
test/dummy.go Updated InitChain with regex-based chain ID validation and checks for initial height and genesis time; added new methods GetTxs and InjectTx; modified ExecuteTxs and simplified SetFinal error handling.
test/dummy_test.go Refactored test methods from standalone functions to suite methods; added new tests: TestExecuteTxsComprehensive, TestInitChain, and TestGetTxsWithConcurrency to cover various input scenarios and concurrent tx injection.
types/errors.go Introduced a new file defining structured error variables for blockchain operations including chain initialization, transaction execution, block finalization, and transaction pool errors.

Possibly related PRs

Suggested labels

testing

Suggested reviewers

  • facundomedica
  • gupadhyaya
  • MSevey
  • yarikbratashchuk
  • tuxcanfly

Poem

I'm a little rabbit hopping through the code,
Skipping over bugs on a validated road.
With chain IDs and tests all set just right,
I nibble carrots at each commit's light.
In fields of logic and error-free delight,
My floppy ears cheer every new update bright!
Happy hops and checks, day and night!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 088492f and 17858ea.

📒 Files selected for processing (1)
  • types/errors.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • types/errors.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.

@RollkitBot RollkitBot requested review from a team, tuxcanfly, MSevey and Manav-Aggarwal and removed request for a team February 21, 2025 10:30
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 comments (1)
test/dummy.go (1)

60-95: 🛠️ Refactor suggestion

Add documentation for the ExecuteTxs method.

The method implementation is solid with comprehensive validation. However, it needs documentation to comply with Go's best practices and fix the pipeline failures.

Apply this diff to add documentation:

+// ExecuteTxs executes a list of transactions at the specified block height and timestamp.
+// It validates the previous state root, timestamp, block height, and transaction size.
+// Returns the new state root and maximum allowed transaction size, or an error if validation fails.
 func (e *DummyExecutor) ExecuteTxs(ctx context.Context, txs []types.Tx, blockHeight uint64, timestamp time.Time, prevStateRoot types.Hash) (types.Hash, uint64, error) {
🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 60-60: exported: exported method DummyExecutor.ExecuteTxs should have comment or be unexported

(revive)

🪛 GitHub Check: lint / golangci-lint

[failure] 60-60:
exported: exported method DummyExecutor.ExecuteTxs should have comment or be unexported (revive)

🧹 Nitpick comments (4)
test/dummy.go (2)

15-15: Consider making the regex pattern more restrictive.

The current regex pattern allows any alphanumeric character followed by alphanumeric characters or hyphens. Consider adding an upper limit to the pattern length and restricting the trailing character to prevent ending with a hyphen.

Apply this diff to improve the regex pattern:

-var validChainIDRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9-]*`)
+var validChainIDRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9-]{0,30}[a-zA-Z0-9]$`)

109-123: Consider adding capacity hint to slice allocation.

The implementation of GetTxs and InjectTx is correct. However, for better performance when dealing with large transaction volumes, consider pre-allocating the slice with a capacity hint.

Apply this diff to optimize slice allocation:

-func (e *DummyExecutor) GetTxs(context.Context) ([]types.Tx, error) {
+// GetTxs returns a copy of all injected transactions.
+func (e *DummyExecutor) GetTxs(context.Context) ([]types.Tx, error) {
 	e.mu.RLock()
 	defer e.mu.RUnlock()

-	txs := make([]types.Tx, len(e.injectedTxs))
+	txs := make([]types.Tx, len(e.injectedTxs), cap(e.injectedTxs))
 	copy(txs, e.injectedTxs)
 	return txs, nil
 }

-func (e *DummyExecutor) InjectTx(tx types.Tx) {
+// InjectTx adds a new transaction to the pool of injected transactions.
+func (e *DummyExecutor) InjectTx(tx types.Tx) {
test/dummy_test.go (2)

67-123: Add edge cases for transaction size and block height.

The test cases are well-structured, but consider adding:

  • Transaction exceeding maxBytes
  • Zero block height
  • Multiple empty transactions in a batch

Apply this diff to add more test cases:

 		{
+			name:          "transaction too large",
+			txs:           []types.Tx{bytes.Repeat([]byte("x"), 1000001)},
+			blockHeight:   1,
+			timestamp:     time.Now().UTC(),
+			prevStateRoot: types.Hash{1, 2, 3},
+			expectedErr:   types.ErrTxTooLarge,
+		},
+		{
+			name:          "zero block height",
+			txs:           []types.Tx{[]byte("tx1")},
+			blockHeight:   0,
+			timestamp:     time.Now().UTC(),
+			prevStateRoot: types.Hash{1, 2, 3},
+			expectedErr:   types.ErrInvalidBlockHeight,
+		},
+		{
 			name:          "empty transaction",

199-230: Consider adding variable transaction sizes in concurrent test.

The concurrent test effectively verifies transaction uniqueness and thread safety. Consider adding variable transaction sizes to stress test the system more thoroughly.

Apply this diff to enhance the test:

 				for j := 0; j < txsPerGoroutine; j++ {
-					tx := types.Tx([]byte(fmt.Sprintf("tx-%d-%d", id, j)))
+					// Create transactions with varying sizes
+					size := (j % 5) * 100 // Sizes: 0, 100, 200, 300, 400 bytes
+					data := fmt.Sprintf("tx-%d-%d-%s", id, j, strings.Repeat("x", size))
+					tx := types.Tx([]byte(data))
 					s.TxInjector.InjectTx(tx)
 				}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6a7ddd0 and 3d9a5fe.

📒 Files selected for processing (3)
  • test/dummy.go (3 hunks)
  • test/dummy_test.go (4 hunks)
  • types/errors.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
types/errors.go

[warning] 6-6: exported: comment on exported var ErrZeroInitialHeight should be of the form "ErrZeroInitialHeight ..."

(revive)


[warning] 8-8: exported: exported var ErrEmptyChainID should have comment or be unexported

(revive)


[warning] 13-13: exported: comment on exported var ErrEmptyStateRoot should be of the form "ErrEmptyStateRoot ..."

(revive)


[warning] 20-20: exported: comment on exported var ErrBlockNotFound should be of the form "ErrBlockNotFound ..."

(revive)


[warning] 25-25: exported: comment on exported var ErrTxAlreadyExists should be of the form "ErrTxAlreadyExists ..."

(revive)


[warning] 30-30: exported: comment on exported var ErrContextCanceled should be of the form "ErrContextCanceled ..."

(revive)

test/dummy.go

[warning] 60-60: exported: exported method DummyExecutor.ExecuteTxs should have comment or be unexported

(revive)

🪛 GitHub Check: lint / golangci-lint
types/errors.go

[failure] 6-6:
exported: comment on exported var ErrZeroInitialHeight should be of the form "ErrZeroInitialHeight ..." (revive)


[failure] 8-8:
exported: exported var ErrEmptyChainID should have comment or be unexported (revive)


[failure] 13-13:
exported: comment on exported var ErrEmptyStateRoot should be of the form "ErrEmptyStateRoot ..." (revive)


[failure] 20-20:
exported: comment on exported var ErrBlockNotFound should be of the form "ErrBlockNotFound ..." (revive)


[failure] 25-25:
exported: comment on exported var ErrTxAlreadyExists should be of the form "ErrTxAlreadyExists ..." (revive)


[failure] 30-30:
exported: comment on exported var ErrContextCanceled should be of the form "ErrContextCanceled ..." (revive)

test/dummy.go

[failure] 60-60:
exported: exported method DummyExecutor.ExecuteTxs should have comment or be unexported (revive)

🪛 GitHub Actions: CI and Release
types/errors.go

[error] 6-6: exported: comment on exported var ErrZeroInitialHeight should be of the form "ErrZeroInitialHeight ..." (revive)

🔇 Additional comments (4)
test/dummy.go (2)

34-58: LGTM! Comprehensive validation in InitChain.

The validation checks in InitChain are thorough and well-structured, covering all edge cases:

  • Zero initial height
  • Empty chain ID
  • Invalid chain ID format
  • Future genesis time
  • Chain ID length
🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 34-34: exported: exported method DummyExecutor.InitChain should have comment or be unexported

(revive)

🪛 GitHub Check: lint / golangci-lint

[failure] 34-34:
exported: exported method DummyExecutor.InitChain should have comment or be unexported (revive)


97-107: LGTM! Simplified error handling.

Good use of the sentinel error types.ErrBlockNotFound instead of a formatted error message.

🧰 Tools
🪛 golangci-lint (1.62.2)

[warning] 97-97: exported: exported method DummyExecutor.SetFinal should have comment or be unexported

(revive)

🪛 GitHub Check: lint / golangci-lint

[failure] 97-97:
exported: exported method DummyExecutor.SetFinal should have comment or be unexported (revive)

test/dummy_test.go (2)

31-65: LGTM! Well-structured test with clear assertions.

The test effectively verifies transaction removal behavior with appropriate assertions at each step.


125-197: LGTM! Comprehensive test cases for chain initialization.

The test cases thoroughly cover all validation scenarios in InitChain, including edge cases for chain ID format and length.

facundomedica and others added 2 commits February 21, 2025 11:34
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@tac0turtle tac0turtle enabled auto-merge February 25, 2025 08:35
@tac0turtle tac0turtle added this pull request to the merge queue Feb 25, 2025
Merged via the queue into main with commit 15978b7 Feb 25, 2025
11 checks passed
@tac0turtle tac0turtle deleted the facu/add-tests-errors branch February 25, 2025 10:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

Define sentinel errors Implement smoke tests
3 participants