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
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions adapters/humachi/humachi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ import (
"time"

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/humatest"
"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
)

var lastModified = time.Now()
Expand Down Expand Up @@ -314,6 +316,43 @@ func BenchmarkRawChiFast(b *testing.B) {
}
}

func TestChiRouterPrefix(t *testing.T) {
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"}}
api = New(r, config)
})

type TestOutput struct {
Body struct {
Field string `json:"field"`
}
}

// Register a simple hello world operation in the API.
huma.Get(api, "/test", func(ctx context.Context, input *struct{}) (*TestOutput, error) {
return &TestOutput{}, nil
})

// Create a test API around the underlying router to make easier requests.
tapi := humatest.Wrap(t, New(mux, huma.DefaultConfig("Test", "1.0.0")))

// The top-level router should respond to the full path even though the
// operation was registered with just `/test`.
resp := tapi.Get("/api/test")
assert.Equal(t, http.StatusOK, resp.Code)

// The transformer should generate links with the full URL path.
assert.Contains(t, resp.Header().Get("Link"), "/api/schemas/TestOutputBody.json")

// The docs HTML should point to the full URL including base path.
resp = tapi.Get("/api/docs")
assert.Equal(t, http.StatusOK, resp.Code)
assert.Contains(t, resp.Body.String(), "/api/openapi.yaml")
}

// func BenchmarkHumaV1Chi(t *testing.B) {
// type GreetingInput struct {
// ID string `path:"id"`
Expand Down
39 changes: 0 additions & 39 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ import (
"testing"

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humachi"
"github.com/danielgtaylor/huma/v2/humatest"
"github.com/go-chi/chi/v5"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -89,40 +87,3 @@ func TestContextValue(t *testing.T) {
resp := api.Get("/test")
assert.Equal(t, http.StatusNoContent, resp.Code)
}

func TestChiRouterPrefix(t *testing.T) {
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"}}
api = humachi.New(r, config)
})

type TestOutput struct {
Body struct {
Field string `json:"field"`
}
}

// Register a simple hello world operation in the API.
huma.Get(api, "/test", func(ctx context.Context, input *struct{}) (*TestOutput, error) {
return &TestOutput{}, nil
})

// Create a test API around the underlying router to make easier requests.
tapi := humatest.Wrap(t, humachi.New(mux, huma.DefaultConfig("Test", "1.0.0")))

// The top-level router should respond to the full path even though the
// operation was registered with just `/test`.
resp := tapi.Get("/api/test")
assert.Equal(t, http.StatusOK, resp.Code)

// The transformer should generate links with the full URL path.
assert.Contains(t, resp.Header().Get("Link"), "/api/schemas/TestOutputBody.json")

// The docs HTML should point to the full URL including base path.
resp = tapi.Get("/api/docs")
assert.Equal(t, http.StatusOK, resp.Code)
assert.Contains(t, resp.Body.String(), "/api/openapi.yaml")
}
3 changes: 1 addition & 2 deletions autoregister_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"net/http"

"github.com/danielgtaylor/huma/v2"
"github.com/go-chi/chi/v5"
)

// Item represents a single item with a unique ID.
Expand Down Expand Up @@ -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

api := NewExampleAPI(router, huma.DefaultConfig("My Service", "1.0.0"))

// Create the item handler and register all of its operations.
Expand Down
12 changes: 5 additions & 7 deletions huma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,17 @@ import (
"testing"
"time"

"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humachi"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/danielgtaylor/huma/v2/humatest"
)

var NewExampleAdapter = humatest.NewAdapter
var NewExampleAPI = humachi.New
var NewExampleAPI = humago.New

// Recoverer is a really simple recovery middleware we can use during tests.
func Recoverer(next http.Handler) http.Handler {
Expand Down Expand Up @@ -1899,13 +1898,12 @@ Content of example2.txt.
},
} {
t.Run(feature.Name, func(t *testing.T) {
r := chi.NewRouter()
r.Use(Recoverer)
r := http.NewServeMux()
config := huma.DefaultConfig("Features Test API", "1.0.0")
if feature.Transformers != nil {
config.Transformers = append(config.Transformers, feature.Transformers...)
}
api := humatest.Wrap(t, humachi.New(r, config))
api := humatest.Wrap(t, humago.New(r, config))
feature.Register(t, api)

var body io.Reader = nil
Expand All @@ -1917,7 +1915,7 @@ Content of example2.txt.
req.Header.Set(k, v)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
Recoverer(r).ServeHTTP(w, req)
b, _ := api.OpenAPI().YAML()
t.Log(string(b))
b, _ = httputil.DumpResponse(w.Result(), true)
Expand Down
17 changes: 10 additions & 7 deletions humacli/humacli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@ import (
"log"
"net/http"
"os"
"syscall"
"testing"
"time"

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humachi"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/danielgtaylor/huma/v2/humacli"
"github.com/go-chi/chi/v5"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
)
Expand All @@ -33,8 +31,8 @@ func ExampleCLI() {
opts.Debug, opts.Host, opts.Port)

// Set up the router & API
router := chi.NewRouter()
api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("My API", "1.0.0"))

huma.Register(api, huma.Operation{
OperationID: "hello",
Expand All @@ -47,7 +45,7 @@ func ExampleCLI() {

srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", opts.Host, opts.Port),
Handler: router,
Handler: mux,
// TODO: Set up timeouts!
}

Expand Down Expand Up @@ -214,9 +212,14 @@ func TestCLIShutdown(t *testing.T) {
})
})

p, err := os.FindProcess(os.Getpid())
if err != nil {
t.Fatalf("failed to find process: %v", os.Getpid())
}

go func() {
time.Sleep(10 * time.Millisecond)
syscall.Kill(syscall.Getpid(), syscall.SIGINT)
p.Signal(os.Interrupt)
}()

cli.Root().SetArgs([]string{})
Expand Down
3 changes: 1 addition & 2 deletions resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"strings"

"github.com/danielgtaylor/huma/v2"
"github.com/go-chi/chi/v5"
)

// Step 1: Create your input struct where you want to do additional validation.
Expand All @@ -35,7 +34,7 @@ func (b *ExampleInputBody) Resolve(ctx huma.Context, prefix *huma.PathBuffer) []

func ExampleResolver() {
// Create the API.
r := chi.NewRouter()
r := http.NewServeMux()
api := NewExampleAPI(r, huma.DefaultConfig("Example API", "1.0.0"))

huma.Register(api, huma.Operation{
Expand Down
7 changes: 3 additions & 4 deletions sse/sse_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@ import (
"net/http"

"github.com/danielgtaylor/huma/v2"
"github.com/danielgtaylor/huma/v2/adapters/humachi"
"github.com/danielgtaylor/huma/v2/adapters/humago"
"github.com/danielgtaylor/huma/v2/sse"
"github.com/go-chi/chi/v5"
)

func ExampleRegister_sse() {
Expand All @@ -25,8 +24,8 @@ func ExampleRegister_sse() {
type UserDeletedEvent UserEvent

// 2. Set up the API.
router := chi.NewMux()
api := humachi.New(router, huma.DefaultConfig("My API", "1.0.0"))
mux := http.NewServeMux()
api := humago.New(mux, huma.DefaultConfig("My API", "1.0.0"))

// 3. Register an SSE operation.
sse.Register(api, huma.Operation{
Expand Down
Loading