优化
This commit is contained in:
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -73,3 +74,38 @@ func TestErrorAuditSkipsLogViewerFailureAlreadyLoggedByHandler(t *testing.T) {
|
||||
t.Fatalf("log viewer failure must not be emitted twice, got %s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorAuditEmitsPrivateMiddlewareErrorOnSuccessResponse(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&output, nil))
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(ErrorAudit(logger))
|
||||
engine.GET("/test", func(c *gin.Context) {
|
||||
c.Error(errors.New("operation audit persist: database unavailable"))
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{}, "msg": "成功"})
|
||||
})
|
||||
response := httptest.NewRecorder()
|
||||
engine.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/test", nil))
|
||||
if !strings.Contains(output.String(), "operation audit persist: database unavailable") {
|
||||
t.Fatalf("private middleware error was not logged: %s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorAuditEmitsOperationAuditFailureForSysErrorRoute(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&output, nil))
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(ErrorAudit(logger))
|
||||
engine.PUT("/sysError/updateSysError", func(c *gin.Context) {
|
||||
c.Set(ctxOperationAuditPersistFailedKey, true)
|
||||
c.Error(errors.New("operation audit persist: database unavailable"))
|
||||
c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{}, "msg": "成功"})
|
||||
})
|
||||
response := httptest.NewRecorder()
|
||||
engine.ServeHTTP(response, httptest.NewRequest(http.MethodPut, "/sysError/updateSysError", nil))
|
||||
if !strings.Contains(output.String(), "operation audit persist: database unavailable") {
|
||||
t.Fatalf("sysError operation audit failure was not logged: %s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user