Skip to content

Add tx unit tests#2

Open
CaelRowley wants to merge 1 commit intomainfrom
tx-unit-tests-2
Open

Add tx unit tests#2
CaelRowley wants to merge 1 commit intomainfrom
tx-unit-tests-2

Conversation

@CaelRowley
Copy link
Owner

@CaelRowley CaelRowley commented Feb 2, 2026

Greptile Overview

Greptile Summary

This PR adds comprehensive unit tests for transaction handlers and improves test coverage for block handlers. It also includes a critical race condition fix in the server startup logic.

Key Changes

  • New transaction handler tests (pkg/handlers/tx_test.go): Added tests for GetTx and GetTxs endpoints including success and error cases
  • Enhanced block handler tests (pkg/handlers/block_test.go): Added error handling tests for invalid input and database errors
  • Race condition fix (pkg/server/server.go): Moved wg.Add() calls before goroutine launches to prevent race between Add and Done
  • Test improvements: Added missing error assertion in database test and minor code cleanup

Issues Found

  • Critical bug in pkg/handlers/tx_test.go:50 where mock returns value type instead of pointer type, causing test to fail
  • Error message typo in pkg/handlers/tx.go:22 says "blocks" instead of "txs"

Confidence Score: 2/5

  • This PR has a critical bug that will cause the new transaction tests to fail
  • The mock type mismatch in tx_test.go is a blocking issue that prevents the tests from passing. The race condition fix is excellent, but the test bug must be resolved before merging
  • pkg/handlers/tx_test.go must be fixed before merge - mock return type is incorrect

Important Files Changed

Filename Overview
pkg/handlers/tx_test.go Added transaction handler tests with critical mock return type bug that will cause test failures
pkg/server/server.go Fixed race condition by moving wg.Add() calls before goroutines
pkg/handlers/tx.go Error message typo in GetTxs handler says "blocks" instead of "txs"

Sequence Diagram

sequenceDiagram
    participant Client
    participant Router
    participant Handler
    participant MockDB
    participant TestRunner

    Note over TestRunner: New Transaction Tests Added
    
    TestRunner->>Handler: TestGetTx()
    Handler->>MockDB: Setup mock with GetTxByHash()
    MockDB-->>Handler: Return mock transaction
    Handler->>Router: Register /get-tx/{hash} route
    TestRunner->>Router: GET /get-tx/{hash}
    Router->>Handler: GetTx(w, r)
    Handler->>MockDB: GetTxByHash(hash)
    MockDB-->>Handler: Return *data.Transaction
    Handler-->>Router: JSON response
    Router-->>TestRunner: Assert HTTP 200 & transaction data
    
    TestRunner->>Handler: TestGetTxDBError()
    Handler->>MockDB: Setup mock to return error
    TestRunner->>Router: GET /get-tx/0xnonexistent
    Router->>Handler: GetTx(w, r)
    Handler->>MockDB: GetTxByHash("0xnonexistent")
    MockDB-->>Handler: Return error
    Handler-->>Router: HTTP 500 error
    Router-->>TestRunner: Assert HTTP 500
    
    Note over TestRunner: New Block Error Tests
    
    TestRunner->>Handler: TestGetBlockInvalidNumber()
    TestRunner->>Router: GET /get-block/notanumber
    Router->>Handler: GetBlock(w, r)
    Handler->>Handler: ParseUint fails
    Handler-->>Router: HTTP 400 error
    Router-->>TestRunner: Assert HTTP 400
    
    Note over TestRunner: Race Condition Fix
    
    TestRunner->>Handler: Server.Start()
    Handler->>Handler: wg.Add(1) BEFORE goroutine
    Handler->>Handler: Start goroutine
    Note right of Handler: Fix prevents race condition<br/>between Add and Done calls
Loading

(3/5) Reply to the agent's comments like "Can you suggest a fix for this @greptileai?" or ask follow-up questions!

Summary by CodeRabbit

  • Tests

    • Enhanced test coverage for block endpoint error handling and input validation
    • Added comprehensive transaction handler tests with database error scenarios
    • Improved database operation testing
  • Chores

    • Optimized server synchronization mechanisms

@gemini-code-assist
Copy link

Summary of Changes

Hello @CaelRowley, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the test coverage for the API handlers, particularly by introducing dedicated unit tests for transaction-related endpoints. It also refines existing block handler tests to better cover error conditions and includes minor but important fixes related to database connection error handling and goroutine synchronization, contributing to overall code robustness and reliability.

Highlights

  • New Transaction Handler Unit Tests: Introduced a new test file, pkg/handlers/tx_test.go, which contains comprehensive unit tests for the GetTx and GetTxs handlers. These tests cover successful data retrieval and various database error scenarios.
  • Enhanced Block Handler Error Testing: Added new test cases to pkg/handlers/block_test.go to specifically address error conditions for the GetBlock and GetBlocks handlers, including invalid input for block numbers and database connection errors.
  • Improved Goroutine Synchronization: Corrected the usage of sync.WaitGroup in pkg/server/server.go by moving wg.Add(1) calls to immediately before each goroutine is launched, ensuring proper synchronization and preventing potential race conditions or deadlocks.
  • Minor Test Assertion Refinement: Updated an assertion in pkg/handlers/handlers_test.go to use rr.Body.String() instead of string(rr.Body.Bytes()) for comparing HTTP response bodies, which is a more idiomatic and potentially safer way to handle string conversion from a bytes.Buffer.
  • Database Test Error Handling: Added an assert.NoError check in pkg/db/db_test.go to ensure that the GORM database connection is established without errors during testing.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds unit tests for the transaction handlers and improves test coverage for block handlers. The changes are well-structured and improve the robustness of the test suite. I've identified a couple of areas for improvement, mainly related to mock setups in the tests to make them more explicit and prevent potential panics. Additionally, there's a minor race condition fix in the server startup logic which is a great catch.

func TestGetTxDBError(t *testing.T) {
recorder := httptest.NewRecorder()
mockDB := new(MockDB)
mockDB.On("GetTxByHash", "0xnonexistent").Return(nil, fmt.Errorf("record not found"))

Choose a reason for hiding this comment

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

medium

The mock for GetTxByHash is returning an untyped nil. While testify/mock is often smart enough to handle this, it's safer and more explicit to return a typed nil. This prevents potential panics if the mock implementation were to change and try to assert the type of the first argument. Using (*data.Transaction)(nil) makes the mock setup more robust.

Suggested change
mockDB.On("GetTxByHash", "0xnonexistent").Return(nil, fmt.Errorf("record not found"))
mockDB.On("GetTxByHash", "0xnonexistent").Return((*data.Transaction)(nil), fmt.Errorf("record not found"))

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

3 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

func TestGetTx(t *testing.T) {
recorder := httptest.NewRecorder()
mockDB := new(MockDB)
mockDB.On("GetTxByHash", mockTxs[0].Hash).Return(mockTxs[0], nil)
Copy link

Choose a reason for hiding this comment

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

GetTxByHash returns *data.Transaction, but mock returns value type data.Transaction

Suggested change
mockDB.On("GetTxByHash", mockTxs[0].Hash).Return(mockTxs[0], nil)
mockDB.On("GetTxByHash", mockTxs[0].Hash).Return(&mockTxs[0], nil)
Prompt To Fix With AI
This is a comment left during a code review.
Path: pkg/handlers/tx_test.go
Line: 50:50

Comment:
`GetTxByHash` returns `*data.Transaction`, but mock returns value type `data.Transaction`

```suggestion
	mockDB.On("GetTxByHash", mockTxs[0].Hash).Return(&mockTxs[0], nil)
```

How can I resolve this? If you propose a fix, please make it concise.

@greptile-apps
Copy link

greptile-apps bot commented Feb 2, 2026

Additional Comments (1)

pkg/handlers/tx.go
Error message says "blocks" but should say "txs"

		return fmt.Errorf("failed to get txs: %w", err)
Prompt To Fix With AI
This is a comment left during a code review.
Path: pkg/handlers/tx.go
Line: 22:22

Comment:
Error message says "blocks" but should say "txs"

```suggestion
		return fmt.Errorf("failed to get txs: %w", err)
```

How can I resolve this? If you propose a fix, please make it concise.

@CaelRowley
Copy link
Owner Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Feb 2, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link

coderabbitai bot commented Feb 2, 2026

📝 Walkthrough

Walkthrough

This pull request adds comprehensive error handling and input validation tests for block and transaction endpoints, refactors goroutine synchronization in the server module using WaitGroup, and improves a test utility assertion method.

Changes

Cohort / File(s) Summary
Test Additions - Block Handlers
pkg/handlers/block_test.go
Introduces tests for invalid numeric path parameters, database errors when fetching single blocks, and database errors when fetching multiple blocks, with proper HTTP status code validation.
Test Additions - Transaction Handlers
pkg/handlers/tx_test.go
New test file covering single and multiple transaction retrieval, including database error scenarios, using mocked database and chi router utilities.
Test Utilities & Assertions
pkg/handlers/handlers_test.go
Refactors response body assertion to use rr.Body.String() instead of string(rr.Body.Bytes()) for improved clarity.
Database Tests
pkg/db/db_test.go
Adds error assertion after gorm.Open in TestRunMigrations to validate successful database connection initialization.
Server Synchronization
pkg/server/server.go
Refactors WaitGroup lifecycle by moving all wg.Add(1) calls to occur before goroutine spawning, consolidating synchronization logic while maintaining error reporting behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Tests bloom like clover in the spring,
Block handlers and transactions now take wing,
Goroutines synchronized with care,
Error paths caught with watchful stare! ✨🌱

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Title check ⚠️ Warning The title 'Add tx unit tests' directly addresses only the transaction handler tests, but the PR also includes block handler tests, database test improvements, and a race condition fix in server startup logic. Revise the title to reflect all major changes, such as 'Add tx unit tests and improve test coverage' or 'Add tx/block tests and fix server race condition'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Docstrings were successfully generated.
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch tx-unit-tests-2

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/server/server.go (1)

98-98: ⚠️ Potential issue | 🟠 Major

Add StartEventHandler goroutine to WaitGroup for graceful shutdown.

The StartEventHandler goroutine at line 98 is not tracked by the WaitGroup like the other two goroutines in the same context. Although Close() will eventually signal the goroutine to exit by closing the Kafka producer's events channel, there is no explicit synchronization. The goroutine could still be running when the server shutdown sequence returns, creating a potential race condition.

Add wg.Add(1) before the goroutine and defer wg.Done() inside it to ensure it completes before shutdown finishes:

diff
-		go s.pubsub.GetPublisher().StartEventHandler()
+		wg.Add(1)
+		go func() {
+			defer wg.Done()
+			s.pubsub.GetPublisher().StartEventHandler()
+		}()

@coderabbitai
Copy link

coderabbitai bot commented Feb 2, 2026

Caution

Docstrings generation - FAILED

No docstrings were generated.

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.

1 participant