Files
packages/middlewares/logger/logger_test.go
2025-12-08 15:12:06 +08:00

63 lines
1.1 KiB
Go

package logger
import (
"errors"
"net/http"
"testing"
"time"
"gitea.loveuer.com/yizhisec/packages/logger"
"github.com/gin-gonic/gin"
)
func TestLogger(t *testing.T) {
gin.SetMode(gin.TestMode)
app := gin.New()
app.Use(New())
app.GET("/200", func(c *gin.Context) {
c.JSON(200, gin.H{"hello": "world"})
})
app.GET("/400", func(c *gin.Context) {
c.JSON(400, gin.H{"hello": "world"})
})
app.GET("/500", func(c *gin.Context) {
logger.ErrorCtx(c.Request.Context(), "oops")
c.JSON(500, gin.H{"hello": "world"})
})
ok := make(chan struct{})
svc := http.Server{
Handler: app,
Addr: "127.0.0.1:8080",
}
go func() {
ok <- struct{}{}
if err := svc.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
t.Error(err)
}
}()
<-ok
time.Sleep(200 * time.Millisecond)
justErr := func(_ any, e error) error {
return e
}
err := errors.Join(
justErr(http.Get("http://127.0.0.1:8080/200")),
justErr(http.Get("http://127.0.0.1:8080/400")),
justErr(http.Get("http://127.0.0.1:8080/500")),
)
if err != nil {
t.Error(err)
}
err = svc.Shutdown(t.Context())
if err != nil {
t.Error(err)
}
}