mirror of
https://github.com/EZ-Api/ez-api.git
synced 2026-01-13 17:47:51 +00:00
81 lines
2.4 KiB
Go
81 lines
2.4 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/ez-api/ez-api/internal/model"
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func TestMaster_ListSelfLogs_FiltersByMaster(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())
|
|
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatalf("open sqlite: %v", err)
|
|
}
|
|
if err := db.AutoMigrate(&model.Master{}, &model.Key{}, &model.LogRecord{}); err != nil {
|
|
t.Fatalf("migrate: %v", err)
|
|
}
|
|
|
|
m1 := &model.Master{Name: "m1", Group: "g", Status: "active", Epoch: 1, MasterKeyDigest: "d1"}
|
|
m2 := &model.Master{Name: "m2", Group: "g", Status: "active", Epoch: 1, MasterKeyDigest: "d2"}
|
|
if err := db.Create(m1).Error; err != nil {
|
|
t.Fatalf("create m1: %v", err)
|
|
}
|
|
if err := db.Create(m2).Error; err != nil {
|
|
t.Fatalf("create m2: %v", err)
|
|
}
|
|
k1 := &model.Key{MasterID: m1.ID, TokenHash: "h1", Group: "g", Status: "active", IssuedAtEpoch: 1}
|
|
k2 := &model.Key{MasterID: m2.ID, TokenHash: "h2", Group: "g", Status: "active", IssuedAtEpoch: 1}
|
|
if err := db.Create(k1).Error; err != nil {
|
|
t.Fatalf("create k1: %v", err)
|
|
}
|
|
if err := db.Create(k2).Error; err != nil {
|
|
t.Fatalf("create k2: %v", err)
|
|
}
|
|
|
|
if err := db.Create(&model.LogRecord{Group: "rg", KeyID: k1.ID, ModelName: "ns.m", StatusCode: 200, LatencyMs: 10}).Error; err != nil {
|
|
t.Fatalf("create log1: %v", err)
|
|
}
|
|
if err := db.Create(&model.LogRecord{Group: "rg", KeyID: k2.ID, ModelName: "ns.m", StatusCode: 400, LatencyMs: 20}).Error; err != nil {
|
|
t.Fatalf("create log2: %v", err)
|
|
}
|
|
|
|
mh := &MasterHandler{db: db}
|
|
|
|
withMaster := func(next gin.HandlerFunc) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
c.Set("master", m1)
|
|
next(c)
|
|
}
|
|
}
|
|
|
|
r := gin.New()
|
|
r.GET("/v1/logs", withMaster(mh.ListSelfLogs))
|
|
|
|
rr := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/v1/logs", nil)
|
|
r.ServeHTTP(rr, req)
|
|
if rr.Code != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d body=%s", rr.Code, rr.Body.String())
|
|
}
|
|
var resp ListLogsResponse
|
|
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
|
t.Fatalf("unmarshal: %v", err)
|
|
}
|
|
if resp.Total != 1 || len(resp.Items) != 1 {
|
|
t.Fatalf("expected 1 item, got total=%d len=%d body=%s", resp.Total, len(resp.Items), rr.Body.String())
|
|
}
|
|
if resp.Items[0].KeyID != k1.ID {
|
|
t.Fatalf("expected key_id %d, got %+v", k1.ID, resp.Items[0])
|
|
}
|
|
}
|