mirror of
https://github.com/Fishwaldo/huma.git
synced 2025-03-15 19:31:27 +00:00
fix: commit humatest module, whoops
This commit is contained in:
parent
aa079f8436
commit
3be7c8d70f
2 changed files with 69 additions and 0 deletions
34
humatest/humatest.go
Normal file
34
humatest/humatest.go
Normal file
|
@ -0,0 +1,34 @@
|
|||
// Package humatest provides testing utilities for testing Huma-powered
|
||||
// services.
|
||||
package humatest
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/danielgtaylor/huma"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"go.uber.org/zap/zaptest"
|
||||
"go.uber.org/zap/zaptest/observer"
|
||||
)
|
||||
|
||||
// NewRouter creates a new test router. It includes a logger attached to the
|
||||
// test so if it fails you will see additional output. There is no recovery
|
||||
// middleware so panics will get caught by the test runner.
|
||||
func NewRouter(t testing.TB) *huma.Router {
|
||||
r, _ := NewRouterObserver(t)
|
||||
return r
|
||||
}
|
||||
|
||||
// NewRouterObserver creates a new router and a log output observer for testing
|
||||
// log output at "debug" level and above during requests.
|
||||
func NewRouterObserver(t testing.TB) (*huma.Router, *observer.ObservedLogs) {
|
||||
core, logs := observer.New(zapcore.DebugLevel)
|
||||
l := zaptest.NewLogger(t, zaptest.WrapOptions(zap.WrapCore(func(zapcore.Core) zapcore.Core { return core })))
|
||||
|
||||
g := gin.New()
|
||||
g.Use(huma.LogMiddleware(l, nil))
|
||||
|
||||
return huma.NewRouterWithGin(g, &huma.OpenAPI{Title: "Test API", Version: "1.0.0"}), logs
|
||||
}
|
35
humatest/humatest_test.go
Normal file
35
humatest/humatest_test.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package humatest_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/danielgtaylor/huma/humatest"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Example() {
|
||||
// Normally you will have a T from your test runner.
|
||||
t := &testing.T{}
|
||||
|
||||
// Create the test router. Logs will be hidden unless the test fails.
|
||||
r := humatest.NewRouter(t)
|
||||
|
||||
// Set up routes & handlers.
|
||||
r.Resource("/test").Get("Test get", func() string {
|
||||
return "Hello, test!"
|
||||
})
|
||||
|
||||
// Make a test request.
|
||||
w := httptest.NewRecorder()
|
||||
req, _ := http.NewRequest(http.MethodGet, "/test", nil)
|
||||
r.ServeHTTP(w, req)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Equal(t, "Hello, test!", w.Body.String())
|
||||
}
|
||||
|
||||
func TestNewRouter(t *testing.T) {
|
||||
// Should not panic
|
||||
humatest.NewRouter(t)
|
||||
}
|
Loading…
Add table
Reference in a new issue