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

Chi is a dep even for pure go implementations, refactor its usage in the main package to pure go. #661

Merged
merged 3 commits into from
Dec 2, 2024

Conversation

fwilkerson
Copy link
Contributor

@fwilkerson fwilkerson commented Nov 27, 2024

For starters, this project is awesome. I wish it existed in 2020 when I was over hauling an app.

I noticed chi in my deps when I was playing around with this, gave me an excuse to look into your code base. After this change I confirmed chi is removed from my deps. I didn't see a great place for TestChiRouterPrefix, I went with adapters as that felt fitting. However, you all only have benches in there at the moment and it's not broken into it's own test package.

If you have some idea's, I'd be happy put them in place.

Summary by CodeRabbit

  • New Features

    • Enhanced testing capabilities for the Huma API framework.
    • Added a new test function to verify API routing behavior.
  • Bug Fixes

    • Streamlined test files by removing outdated tests and imports, improving clarity and efficiency.
  • Refactor

    • Replaced the HTTP router implementation across multiple test files, ensuring compatibility with the updated adapter while maintaining core functionality.
    • Updated API initialization to utilize the new adapter consistently across tests.

Copy link

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in this pull request involve modifications to several test files related to the Huma API framework. Key updates include the introduction of a new test function in humachi_test.go, which enhances testing for routing with a Chi router. In contrast, api_test.go removes references to the Chi router, simplifying its structure. Other files, such as autoregister_test.go, huma_test.go, and resolver_test.go, switch from using the Chi router to the standard library's http.ServeMux, ensuring compatibility with the new routing approach while maintaining existing functionalities.

Changes

File Path Change Summary
adapters/humachi/humachi_test.go Added new test function TestChiRouterPrefix to enhance testing for the Huma API framework.
api_test.go Removed TestChiRouterPrefix function and imports related to the Chi router, streamlining the test file.
autoregister_test.go Changed router instantiation from chi.NewMux() to http.NewServeMux() in ExampleAutoRegister.
huma_test.go Replaced humachi adapter with humago and changed router from chi.NewRouter() to http.NewServeMux().
resolver_test.go Altered router implementation from chi.NewRouter() to http.NewServeMux(), maintaining existing logic.
humacli/humacli_test.go Updated adapter from humachi to humago and changed router from chi.NewRouter() to http.NewServeMux().
sse/sse_example_test.go Changed adapter from humachi to humago and updated API initialization to use http.NewServeMux().

Possibly related PRs

Poem

🐰 In the garden where tests do play,
New routes and functions come out to stay.
With humago's charm and a mux so fine,
Our API dances, all in a line!
Hooray for the changes, let testing commence,
A hop and a skip, in code we make sense! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fd7b757 and 8a5c77e.

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

@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 and nitpick comments (2)
autoregister_test.go (1)

42-42: LGTM! Good move towards standard library.

The switch to http.NewServeMux() aligns well with the goal of removing Chi dependencies and simplifying the implementation. While http.ServeMux has fewer features than Chi, it's sufficient for these tests and reduces external dependencies.

adapters/humachi/humachi_test.go (1)

319-354: Good test coverage, consider these enhancements

The test effectively verifies router prefix handling, but could be enhanced for more comprehensive coverage:

  1. Add assertions for the response body content
  2. Use a test-specific server URL instead of hardcoded "http://localhost:8888/api"
  3. Consider using table-driven tests for different path scenarios

Here's a suggested enhancement:

 func TestChiRouterPrefix(t *testing.T) {
+    testCases := []struct {
+        name           string
+        path           string
+        expectedStatus int
+        expectedBody   string
+    }{
+        {
+            name:           "base path",
+            path:           "/api/test",
+            expectedStatus: http.StatusOK,
+            expectedBody:   `{"field":""}`,
+        },
+        {
+            name:           "docs path",
+            path:           "/api/docs",
+            expectedStatus: http.StatusOK,
+        },
+    }
+
     mux := chi.NewMux()
     var api huma.API
     mux.Route("/api", func(r chi.Router) {
         config := huma.DefaultConfig("My API", "1.0.0")
-        config.Servers = []*huma.Server{{URL: "http://localhost:8888/api"}}
+        config.Servers = []*huma.Server{{URL: "http://test-server/api"}}
         api = New(r, config)
     })
     
     // ... rest of the setup code ...
 
     tapi := humatest.Wrap(t, New(mux, huma.DefaultConfig("Test", "1.0.0")))
 
-    resp := tapi.Get("/api/test")
-    assert.Equal(t, http.StatusOK, resp.Code)
-    assert.Contains(t, resp.Header().Get("Link"), "/api/schemas/TestOutputBody.json")
-
-    resp = tapi.Get("/api/docs")
-    assert.Equal(t, http.StatusOK, resp.Code)
-    assert.Contains(t, resp.Body.String(), "/api/openapi.yaml")
+    for _, tc := range testCases {
+        t.Run(tc.name, func(t *testing.T) {
+            resp := tapi.Get(tc.path)
+            assert.Equal(t, tc.expectedStatus, resp.Code)
+            
+            if tc.expectedBody != "" {
+                assert.JSONEq(t, tc.expectedBody, resp.Body.String())
+            }
+            
+            if tc.path == "/api/test" {
+                assert.Contains(t, resp.Header().Get("Link"), 
+                    "/api/schemas/TestOutputBody.json")
+            } else if tc.path == "/api/docs" {
+                assert.Contains(t, resp.Body.String(), "/api/openapi.yaml")
+            }
+        })
+    }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bfe8892 and b6cb420.

📒 Files selected for processing (5)
  • adapters/humachi/humachi_test.go (2 hunks)
  • api_test.go (0 hunks)
  • autoregister_test.go (1 hunks)
  • huma_test.go (3 hunks)
  • resolver_test.go (1 hunks)
💤 Files with no reviewable changes (1)
  • api_test.go
🔇 Additional comments (6)
resolver_test.go (1)

37-37: LGTM! Router change aligns with PR objectives.

The switch to http.NewServeMux() successfully removes the Chi dependency while maintaining the test's functionality. This change simplifies the codebase by using the standard library's router implementation.

Let's verify the consistency of router usage across the codebase:

adapters/humachi/humachi_test.go (2)

16-16: LGTM: Appropriate test dependencies added

The addition of humatest and testify/assert packages is appropriate for the new test function.

Also applies to: 18-18


Line range hint 23-318: LGTM: Appropriate placement of Chi-dependent benchmarks

The benchmark tests are correctly placed in the humachi adapter package, which is the designated location for Chi-specific implementations. This aligns with the PR's objective of removing Chi dependencies from the main package while maintaining the ability to benchmark Chi router performance.

huma_test.go (3)

25-25: LGTM! Import and variable changes align with PR objectives.

The changes correctly replace the Chi router dependency with the pure Go implementation by:

  1. Importing the humago adapter
  2. Updating NewExampleAPI to use humago.New

Also applies to: 30-30


1901-1906: LGTM! Router initialization properly migrated to pure Go.

The changes correctly:

  1. Use standard library's http.NewServeMux instead of Chi router
  2. Initialize the API with the humago adapter while maintaining the existing configuration

1918-1918: LGTM! Middleware integration maintained with new router.

The Recoverer middleware is properly integrated with the new router implementation, maintaining the existing error handling functionality.

@@ -40,7 +39,7 @@ func (s *ItemsHandler) RegisterListItems(api huma.API) {

func ExampleAutoRegister() {
// Create the router and API.
router := chi.NewMux()
router := http.NewServeMux()
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Router initialization is inconsistent across test files

The verification reveals inconsistent router initialization patterns across test files:

  • autoregister_test.go uses http.NewServeMux()
  • sse/sse_example_test.go uses chi.NewMux()
  • humacli/humacli_test.go uses chi.NewRouter()

Additionally, Chi router imports are still present in multiple test files:

  • adapters/adapters_test.go
  • adapters/humachi/humachi_test.go
  • humacli/humacli_test.go
  • sse/sse_example_test.go

These inconsistencies should be addressed to maintain uniformity across the test suite.

🔗 Analysis chain

Verify consistent router changes across test files.

Let's ensure this router change is consistently applied across all test files to maintain uniformity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining Chi router usage in test files
# and verify consistency of http.NewServeMux usage

echo "Checking for any remaining Chi router imports or usage in test files..."
rg -l 'github.com/go-chi/chi' '*_test.go'

echo "Verifying consistent router initialization in test files..."
rg -A 1 'router :=' '*_test.go'

Length of output: 457


Script:

#!/bin/bash
# Let's first find all test files in the repository
echo "Finding all test files..."
fd "_test\.go$"

# Then check for Chi router imports and usage
echo -e "\nChecking for Chi router imports in test files..."
rg -l "github.com/go-chi/chi" $(fd "_test\.go$")

# Finally check router initialization patterns
echo -e "\nChecking router initialization patterns in test files..."
rg -C 2 "router\s*:=\s*" $(fd "_test\.go$")

Length of output: 3596

@fwilkerson
Copy link
Contributor Author

Took care of the two spots the rabbit pointed out and added an optional commit to remove the use of syscall which won't compile on a windows machine.

Copy link

codecov bot commented Dec 2, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 92.76%. Comparing base (bfe8892) to head (8a5c77e).
Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #661      +/-   ##
==========================================
- Coverage   93.04%   92.76%   -0.29%     
==========================================
  Files          22       22              
  Lines        4905     4905              
==========================================
- Hits         4564     4550      -14     
- Misses        298      308      +10     
- Partials       43       47       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Owner

@danielgtaylor danielgtaylor left a comment

Choose a reason for hiding this comment

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

Thank you, this is great! I think moving the Chi-specific prefix test into the adapters is fine 👍

@danielgtaylor danielgtaylor merged commit 4f98ee6 into danielgtaylor:main Dec 2, 2024
4 of 5 checks passed
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.

2 participants