64 lines
2.0 KiB
Go
64 lines
2.0 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
"go.uber.org/zap/zapcore"
|
|
"go.uber.org/zap/zaptest/observer"
|
|
)
|
|
|
|
func TestRequestLoggerUsesStatusLevelAndDurationMilliseconds(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
core, logs := observer.New(zapcore.DebugLevel)
|
|
router := gin.New()
|
|
router.Use(RequestLogger(zap.New(core)))
|
|
router.GET("/bad", func(c *gin.Context) { c.Status(http.StatusBadRequest) })
|
|
|
|
request := httptest.NewRequest(http.MethodGet, "/bad", nil)
|
|
response := httptest.NewRecorder()
|
|
router.ServeHTTP(response, request)
|
|
|
|
entries := logs.All()
|
|
if len(entries) != 1 || entries[0].Level != zapcore.WarnLevel {
|
|
t.Fatalf("log entries = %+v, want one warning", entries)
|
|
}
|
|
if _, exists := entries[0].ContextMap()["duration_ms"]; !exists {
|
|
t.Fatalf("duration_ms is missing from request log")
|
|
}
|
|
}
|
|
|
|
func TestCORSAllowsAllOriginsAndAnswersPreflight(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
router := gin.New()
|
|
router.Use(CORS())
|
|
router.GET("/ping", func(c *gin.Context) { c.Status(http.StatusOK) })
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/ping", nil)
|
|
req.Header.Set("Origin", "https://crm.example.com")
|
|
rec := httptest.NewRecorder()
|
|
router.ServeHTTP(rec, req)
|
|
|
|
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "*" {
|
|
t.Fatalf("Access-Control-Allow-Origin = %q, want *", got)
|
|
}
|
|
if got := rec.Header().Get("Access-Control-Allow-Headers"); got != "*" {
|
|
t.Fatalf("Access-Control-Allow-Headers = %q, want *", got)
|
|
}
|
|
|
|
preflight := httptest.NewRequest(http.MethodOptions, "/ping", nil)
|
|
preflight.Header.Set("Origin", "https://crm.example.com")
|
|
preflightRec := httptest.NewRecorder()
|
|
router.ServeHTTP(preflightRec, preflight)
|
|
|
|
if preflightRec.Code != http.StatusNoContent {
|
|
t.Fatalf("preflight status = %d, want %d", preflightRec.Code, http.StatusNoContent)
|
|
}
|
|
if got := preflightRec.Header().Get("Access-Control-Allow-Origin"); got != "*" {
|
|
t.Fatalf("preflight Access-Control-Allow-Origin = %q, want *", got)
|
|
}
|
|
}
|