package stats import ( "context" "encoding/json" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/spf13/viper" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "nixcn-cms/internal/authtoken" "nixcn-cms/testutil" ) func init() { gin.SetMode(gin.TestMode) } func issueToken(t *testing.T, userId uuid.UUID) string { t.Helper() tok := &authtoken.Token{Application: viper.GetString("server.application")} access, _, err := tok.IssueTokens(context.Background(), testutil.TestClientID, userId) require.NoError(t, err) return access } func newStatsRouter(t *testing.T) *gin.Engine { t.Helper() r := gin.New() ApiHandler(r.Group("/stats")) return r } func TestGlobalStatsHandler(t *testing.T) { testutil.SetupWithAuth(t) admin := testutil.SeedUser(t, testutil.RandomEmail(), 40) token := issueToken(t, admin.UserId) r := newStatsRouter(t) req := httptest.NewRequest(http.MethodGet, "/stats/global", nil) req.Header.Set("Authorization", "Bearer "+token) w := httptest.NewRecorder() r.ServeHTTP(w, req) assert.Equal(t, http.StatusOK, w.Code) var resp map[string]any require.NoError(t, json.Unmarshal(w.Body.Bytes(), &resp)) data, ok := resp["data"].(map[string]any) require.True(t, ok) _, hasTotalUsers := data["total_users"] assert.True(t, hasTotalUsers) } func TestGlobalStatsHandlerNoAuth(t *testing.T) { testutil.Setup(t) r := newStatsRouter(t) req := httptest.NewRequest(http.MethodGet, "/stats/global", nil) w := httptest.NewRecorder() r.ServeHTTP(w, req) assert.Equal(t, http.StatusUnauthorized, w.Code) }