224 lines
8.1 KiB
Go
224 lines
8.1 KiB
Go
package v1
|
||
|
||
// ops_handler_test.go Issue#6·P2:/stats/biz(两维分布+双口径)+/stats/realtime
|
||
// (60s 窗口 Top5+名字)+/ops/system/overview(角色门+三态诚实)。sqlite 单测;
|
||
// LagReader 以函数注入,Kafka/Redis 真链路在 dev 实机冒烟。
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/glebarez/sqlite"
|
||
"gorm.io/gorm"
|
||
|
||
"go-sms/internal/middleware"
|
||
"go-sms/internal/model/entity"
|
||
)
|
||
|
||
// newOpsRouter 种子:今日 task(账号1:sms×2[1 条 business=video]+template×1;
|
||
// 账号100:sms×1);60s 内 detail 账号1×7+账号100×3(60s 外 2 条不计);
|
||
// 账号名 1=admin/100=cust100。同时挂 stats 与 ops(Health) 路由。
|
||
func newOpsRouter(t *testing.T, hd *HealthDeps) (*gin.Engine, *gorm.DB, func(*middleware.Claims)) {
|
||
t.Helper()
|
||
gin.SetMode(gin.TestMode)
|
||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if s, e := db.DB(); e == nil {
|
||
s.SetMaxOpenConns(1)
|
||
}
|
||
if err := db.AutoMigrate(&entity.MessageTask{}, &entity.MessageDetail{}, &entity.AccountUser{}); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
now := time.Now()
|
||
tasks := []entity.MessageTask{
|
||
{ID: 1, TaskNo: "T1", AccountID: 1, Business: "sms", SendType: 1, CreatedAt: now},
|
||
{ID: 2, TaskNo: "T2", AccountID: 1, Business: "sms", SendType: 1, CreatedAt: now},
|
||
{ID: 3, TaskNo: "T3", AccountID: 1, Business: "video", SendType: 1, CreatedAt: now},
|
||
{ID: 4, TaskNo: "T4", AccountID: 1, Business: "", SendType: 2, CreatedAt: now}, // 空 business→sms 兼容
|
||
{ID: 5, TaskNo: "T5", AccountID: 100, Business: "sms", SendType: 1, CreatedAt: now},
|
||
}
|
||
if err := db.Create(&tasks).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
mk := func(id, acc int64, created time.Time) entity.MessageDetail {
|
||
return entity.MessageDetail{SnowflakeModel: entity.SnowflakeModel{ID: id, CreatedAt: created},
|
||
TaskID: 1, AccountID: acc, ChannelID: 1, Mobile: "13000001111", Content: "t", Status: 2}
|
||
}
|
||
details := []entity.MessageDetail{
|
||
mk(11, 1, now.Add(-10*time.Second)), mk(12, 1, now.Add(-20*time.Second)),
|
||
mk(13, 1, now.Add(-30*time.Second)), mk(14, 1, now.Add(-40*time.Second)),
|
||
mk(15, 1, now.Add(-50*time.Second)), mk(16, 1, now.Add(-55*time.Second)),
|
||
mk(17, 1, now.Add(-58*time.Second)),
|
||
mk(21, 100, now.Add(-10*time.Second)), mk(22, 100, now.Add(-20*time.Second)),
|
||
mk(23, 100, now.Add(-30*time.Second)),
|
||
mk(31, 1, now.Add(-5*time.Minute)), mk(32, 100, now.Add(-5*time.Minute)), // 窗外不计
|
||
}
|
||
if err := db.Create(&details).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
accts := []entity.AccountUser{
|
||
{Model: entity.Model{ID: 1}, Username: "admin", Status: 1},
|
||
{Model: entity.Model{ID: 100}, Username: "cust100", Status: 1},
|
||
}
|
||
if err := db.Create(&accts).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
rg := gin.New()
|
||
api := rg.Group("/api/v1")
|
||
var claims *middleware.Claims
|
||
api.Use(func(c *gin.Context) {
|
||
if claims != nil {
|
||
c.Set(middleware.ContextKeyClaims, claims)
|
||
}
|
||
})
|
||
registerStatsRoutes(api, db)
|
||
if hd != nil {
|
||
hd.DB = db
|
||
registerOpsRoutes(api, Deps{Health: hd})
|
||
}
|
||
setClaims := func(cl *middleware.Claims) { claims = cl }
|
||
return rg, db, setClaims
|
||
}
|
||
|
||
func TestStatsBiz_PlatformAndCustomer(t *testing.T) {
|
||
rg, _, setClaims := newOpsRouter(t, nil)
|
||
setClaims(&middleware.Claims{AccountID: 1, Roles: []string{"admin"}})
|
||
w := httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/stats/biz?days=7", nil))
|
||
if w.Code != 200 {
|
||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||
}
|
||
var res struct {
|
||
Data statsBizDTO `json:"data"`
|
||
}
|
||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
got := map[string]int64{}
|
||
for _, r := range res.Data.ByBusiness {
|
||
got[r.Key] = r.Count
|
||
}
|
||
// 平台:sms=3(账号1×2+账号100)+video=1;空 business 归一为 sms。
|
||
if got["sms"] != 4 || got["video"] != 1 {
|
||
t.Errorf("by_business = %v, 期望 sms=3 video=1", got)
|
||
}
|
||
gotT := map[string]int64{}
|
||
for _, r := range res.Data.BySendType {
|
||
gotT[r.Key] = r.Count
|
||
}
|
||
if gotT["batch"] != 4 || gotT["personal"] != 1 {
|
||
t.Errorf("by_send_type = %v, 期望 batch=4 personal=1", gotT)
|
||
}
|
||
// 客户口径仅自己(账号100:sms×1)。
|
||
setClaims(&middleware.Claims{AccountID: 100, Roles: []string{"customer"}})
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/stats/biz", nil))
|
||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if len(res.Data.ByBusiness) != 1 || res.Data.ByBusiness[0].Key != "sms" || res.Data.ByBusiness[0].Count != 1 {
|
||
t.Errorf("customer by_business = %+v, 期望仅 sms=1", res.Data.ByBusiness)
|
||
}
|
||
}
|
||
|
||
func TestStatsRealtime_TopAccounts(t *testing.T) {
|
||
rg, _, setClaims := newOpsRouter(t, nil)
|
||
setClaims(&middleware.Claims{AccountID: 1, Roles: []string{"ops"}})
|
||
w := httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/stats/realtime", nil))
|
||
if w.Code != 200 {
|
||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||
}
|
||
var res struct {
|
||
Data statsRealtimeDTO `json:"data"`
|
||
}
|
||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
// 窗内 10 条(账号1×7+账号100×3)/60s ≈ 0.17;Top1=账号1 名 admin。
|
||
if res.Data.GlobalSubmitPs < 0.1 || res.Data.GlobalSubmitPs > 0.25 {
|
||
t.Errorf("global_submit_ps = %v, 期望 ≈0.17", res.Data.GlobalSubmitPs)
|
||
}
|
||
if len(res.Data.TopAccounts) != 2 || res.Data.TopAccounts[0].AccountID != 1 ||
|
||
res.Data.TopAccounts[0].Name != "admin" {
|
||
t.Errorf("top_accounts = %+v, 期望首名 admin(账号1)", res.Data.TopAccounts)
|
||
}
|
||
// 客户口径:仅自己(账号100 3 条)。
|
||
setClaims(&middleware.Claims{AccountID: 100, Roles: []string{"customer"}})
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/stats/realtime", nil))
|
||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if res.Data.GlobalSubmitPs < 0.03 || res.Data.GlobalSubmitPs > 0.07 {
|
||
t.Errorf("customer global = %v, 期望 ≈0.05", res.Data.GlobalSubmitPs)
|
||
}
|
||
}
|
||
|
||
func TestOpsOverview_GatesAndSubsystems(t *testing.T) {
|
||
hd := &HealthDeps{
|
||
Redis: nil, // 降级未启用 → down
|
||
Lag: func(ctx context.Context) (int64, error) { return 1204, nil },
|
||
StartTime: time.Now().Add(-3 * time.Hour),
|
||
HTTPAddr: ":8080",
|
||
}
|
||
rg, _, setClaims := newOpsRouter(t, hd)
|
||
setClaims(&middleware.Claims{AccountID: 1, Roles: []string{"admin"}})
|
||
w := httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/ops/system/overview", nil))
|
||
if w.Code != 200 {
|
||
t.Fatalf("code=%d body=%s", w.Code, w.Body.String())
|
||
}
|
||
var res struct {
|
||
Data struct {
|
||
UptimeS int64 `json:"uptime_s"`
|
||
Subsystems []subsystemDTO `json:"subsystems"`
|
||
} `json:"data"`
|
||
}
|
||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if len(res.Data.Subsystems) != 5 {
|
||
t.Fatalf("subsystems = %d, 期望 5", len(res.Data.Subsystems))
|
||
}
|
||
st := map[string]subsystemDTO{}
|
||
for _, s := range res.Data.Subsystems {
|
||
st[s.Name] = s
|
||
}
|
||
if st["gateway"].Status != "up" || st["mysql"].Status != "up" {
|
||
t.Errorf("gateway/mysql = %s/%s, 期望 up/up", st["gateway"].Status, st["mysql"].Status)
|
||
}
|
||
if st["consumer"].Status != "up" || st["kafka"].Detail != "lag 1,204" {
|
||
t.Errorf("consumer/kafka = %+v/%+v, 期望 up 且 lag 千分位", st["consumer"], st["kafka"])
|
||
}
|
||
if st["redis"].Status != "down" {
|
||
t.Errorf("redis(nil 降级) = %s, 期望 down(诚实标注)", st["redis"].Status)
|
||
}
|
||
// lag 超阈 → degraded。
|
||
hd.Lag = func(ctx context.Context) (int64, error) { return 15000, nil }
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/ops/system/overview", nil))
|
||
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
for _, s := range res.Data.Subsystems {
|
||
if s.Name == "kafka" && s.Status != "degraded" {
|
||
t.Errorf("kafka lag=15000 → %s, 期望 degraded", s.Status)
|
||
}
|
||
}
|
||
// 角色门:customer 403。
|
||
setClaims(&middleware.Claims{AccountID: 100, Roles: []string{"customer"}})
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/ops/system/overview", nil))
|
||
if w.Code != http.StatusForbidden {
|
||
t.Errorf("customer code=%d, 期望 403", w.Code)
|
||
}
|
||
}
|