refactor(api): introduce v1 response contract

This commit is contained in:
2026-07-21 13:45:04 +08:00
parent 1d35fcf4a1
commit 7803b2faf0
13 changed files with 303 additions and 48 deletions

View File

@@ -0,0 +1,40 @@
package auth_test
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"senlinai-agent/backend/internal/logic/auth"
)
func TestRequireUserReturnsStableErrorWhenBearerTokenIsMissing(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(auth.RequireUser(func(string) (uint, error) { return 0, nil }))
router.GET("/private", func(c *gin.Context) { c.Status(http.StatusOK) })
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/private", nil))
require.Equal(t, http.StatusUnauthorized, recorder.Code)
require.JSONEq(t, `{"error":{"code":"missing_bearer_token","message":"请先登录后再操作"}}`, recorder.Body.String())
}
func TestRequireUserReturnsStableErrorWhenBearerTokenIsInvalid(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(auth.RequireUser(func(string) (uint, error) { return 0, errors.New("invalid") }))
router.GET("/private", func(c *gin.Context) { c.Status(http.StatusOK) })
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/private", nil)
req.Header.Set("Authorization", "Bearer invalid")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusUnauthorized, recorder.Code)
require.JSONEq(t, `{"error":{"code":"invalid_bearer_token","message":"登录状态无效或已过期,请重新登录"}}`, recorder.Body.String())
}