mirror of
https://github.com/Fishwaldo/huma.git
synced 2025-03-15 11:21:42 +00:00
fix: test router log instantiation
This commit is contained in:
parent
56ec56a6cd
commit
0be6c2122f
2 changed files with 26 additions and 3 deletions
|
@ -26,13 +26,13 @@ func NewRouter(t testing.TB) *huma.Router {
|
|||
func NewRouterObserver(t testing.TB) (*huma.Router, *observer.ObservedLogs) {
|
||||
core, logs := observer.New(zapcore.DebugLevel)
|
||||
|
||||
router := huma.New("Test API", "1.0.0")
|
||||
router.Middleware(middleware.DefaultChain)
|
||||
|
||||
middleware.NewLogger = func() (*zap.Logger, error) {
|
||||
l := zaptest.NewLogger(t, zaptest.WrapOptions(zap.WrapCore(func(zapcore.Core) zapcore.Core { return core })))
|
||||
return l, nil
|
||||
}
|
||||
|
||||
router := huma.New("Test API", "1.0.0")
|
||||
router.Middleware(middleware.DefaultChain)
|
||||
|
||||
return router, logs
|
||||
}
|
||||
|
|
|
@ -7,6 +7,7 @@ import (
|
|||
|
||||
"github.com/danielgtaylor/huma"
|
||||
"github.com/danielgtaylor/huma/humatest"
|
||||
"github.com/danielgtaylor/huma/middleware"
|
||||
"github.com/danielgtaylor/huma/responses"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
@ -51,3 +52,25 @@ func TestPackage(t *testing.T) {
|
|||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Equal(t, "Hello, test!", w.Body.String())
|
||||
}
|
||||
|
||||
func TestCapturedLog(t *testing.T) {
|
||||
// Create the test router. Logs will be hidden unless the test fails.
|
||||
r, logs := humatest.NewRouterObserver(t)
|
||||
|
||||
// Set up routes & handlers.
|
||||
r.Resource("/test").Get("test", "Test get",
|
||||
responses.OK().ContentType("text/plain"),
|
||||
).Run(func(ctx huma.Context) {
|
||||
logger := middleware.GetLogger(ctx)
|
||||
logger.With("foo", "bar").Info("Just a test")
|
||||
ctx.Write([]byte(""))
|
||||
})
|
||||
|
||||
// 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, "Just a test", logs.All()[0].Message)
|
||||
assert.Equal(t, "bar", logs.All()[0].ContextMap()["foo"])
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue