|
|
@@ -0,0 +1,376 @@
|
|
|
+// 分账 handler 单测(AC-13 第 1 批:端点 38 / 43)。
|
|
|
+//
|
|
|
+// 断言纪律(team-lead 的 AC-13 验收方式:**不收"用例全绿",要"写错会变红"**):
|
|
|
+//
|
|
|
+// 端点 38 分账树 —— 主断言是 **Nested Set 四条不变式**(I1~I4),不是"接口返回 200":
|
|
|
+// · `TestDivideTreeInvariantsHold`:造一棵 5 节点两层的树,逐条验 I1(1..2N 无重复无空洞)/
|
|
|
+// I2(嵌套或相离)/ I3(父严格包含子)/ I4(layer=parent.layer+1);
|
|
|
+// · `TestDivideTreeRejectsBrokenNesting`:**故意造坏树**(右值错位 1),断言 5001 + 文案命中
|
|
|
+// 具体不变式 —— 这是"树坏了能被发现"的证明("接口能返回一棵树"这种断言在树坏时依然绿);
|
|
|
+// · `TestDivideTreeQuotaIsMoneyString`:`quota` 必须是**金额字符串**("100.00"),
|
|
|
+// 不是 0~1 比率、不是 number(mock 曾错成比率)。
|
|
|
+// 端点 43 流水 —— `TestDivideLogsWindowAndTotals`:右开窗口(`createTime = to` 的行不得出现),
|
|
|
+// 且 `total` 与 `list` 同口径(不等于历史全量)。
|
|
|
+package handler
|
|
|
+
|
|
|
+import (
|
|
|
+ "encoding/json"
|
|
|
+ "fmt"
|
|
|
+ "net/http"
|
|
|
+ "net/http/httptest"
|
|
|
+ "path/filepath"
|
|
|
+ "strings"
|
|
|
+ "testing"
|
|
|
+ "time"
|
|
|
+
|
|
|
+ gormsqlite "github.com/glebarez/sqlite"
|
|
|
+ "github.com/gofiber/fiber/v2"
|
|
|
+ "gorm.io/gorm"
|
|
|
+
|
|
|
+ "yuansiwei/unified-backend/internal/academic/model"
|
|
|
+ infraerrors "yuansiwei/unified-backend/internal/infra/errors"
|
|
|
+ appscope "yuansiwei/unified-backend/internal/infra/scope"
|
|
|
+)
|
|
|
+
|
|
|
+// newDivideTestDB 分账测试库(两张分账表;其余表由 handler 其它用例各自建)。
|
|
|
+func newDivideTestDB(t *testing.T) *gorm.DB {
|
|
|
+ t.Helper()
|
|
|
+ dsn := filepath.Join(t.TempDir(), "academic_divide_handler_test.db")
|
|
|
+ db, err := gorm.Open(gormsqlite.Open(dsn), &gorm.Config{})
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("gorm.Open(分账库) 失败: %v", err)
|
|
|
+ }
|
|
|
+ sqlDB, err := db.DB()
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("取 sql.DB 失败: %v", err)
|
|
|
+ }
|
|
|
+ sqlDB.SetMaxOpenConns(1)
|
|
|
+ t.Cleanup(func() { _ = sqlDB.Close() })
|
|
|
+ if mErr := db.AutoMigrate(&model.UserDivideInto{}, &model.UserDivideIntoLog{}); mErr != nil {
|
|
|
+ t.Fatalf("AutoMigrate(分账 2 表) 失败: %v", mErr)
|
|
|
+ }
|
|
|
+ return db
|
|
|
+}
|
|
|
+
|
|
|
+// newDivideTestApp 只挂分账两条端点的 app(+ 作用域注入中间件)。
|
|
|
+func newDivideTestApp(t *testing.T, db *gorm.DB) *fiber.App {
|
|
|
+ t.Helper()
|
|
|
+ h, err := New(Config{DB: db})
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("handler.New 失败: %v", err)
|
|
|
+ }
|
|
|
+ app := fiber.New(fiber.Config{DisableStartupMessage: true})
|
|
|
+ app.Use(func(c *fiber.Ctx) error {
|
|
|
+ if c.Get("X-Test-Scope") == "none" {
|
|
|
+ return c.Next()
|
|
|
+ }
|
|
|
+ appscope.Set(c, testScope())
|
|
|
+ return c.Next()
|
|
|
+ })
|
|
|
+ app.Get(PathDivideTree, h.GetDivideTree)
|
|
|
+ app.Get(PathDivideLogs, h.ListDivideLogs)
|
|
|
+ return app
|
|
|
+}
|
|
|
+
|
|
|
+// seedDivideNode 落一行分账节点。
|
|
|
+func seedDivideNode(t *testing.T, db *gorm.DB, userID, parentUserID *string,
|
|
|
+ left, right, layer int32, quota string) {
|
|
|
+ t.Helper()
|
|
|
+ row := &model.UserDivideInto{
|
|
|
+ UserID: userIDOf(userID), ParentUserID: parentUserID,
|
|
|
+ LeftVal: left, RightVal: right, Layer: layer, Quota: quota, TotalIncome: "0.00",
|
|
|
+ }
|
|
|
+ if parentUserID == nil {
|
|
|
+ root := *userID
|
|
|
+ row.RootUserID = &root
|
|
|
+ } else {
|
|
|
+ // 根取父的根(测试里只有两层,直接指向根)
|
|
|
+ root := *userID
|
|
|
+ if *parentUserID != "" {
|
|
|
+ var parent model.UserDivideInto
|
|
|
+ if err := db.Where("user_id = ?", *parentUserID).Take(&parent).Error; err != nil {
|
|
|
+ t.Fatalf("读父节点(%s) 失败: %v", *parentUserID, err)
|
|
|
+ }
|
|
|
+ if parent.RootUserID != nil {
|
|
|
+ root = *parent.RootUserID
|
|
|
+ }
|
|
|
+ }
|
|
|
+ row.RootUserID = &root
|
|
|
+ }
|
|
|
+ if err := db.Create(row).Error; err != nil {
|
|
|
+ t.Fatalf("seed 分账节点(%s) 失败: %v", row.UserID, err)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// userIDOf 解引用(nil → "",用于父节点为空的安全构造)。
|
|
|
+func userIDOf(p *string) string {
|
|
|
+ if p == nil {
|
|
|
+ return ""
|
|
|
+ }
|
|
|
+ return *p
|
|
|
+}
|
|
|
+
|
|
|
+// divideTreeResp 端点 38 的响应体(足够断言树结构与量纲)。
|
|
|
+type divideTreeResp struct {
|
|
|
+ Tree []struct {
|
|
|
+ UserID string `json:"userId"`
|
|
|
+ ParentUserID *string `json:"parentUserId"`
|
|
|
+ Quota json.RawMessage `json:"quota"`
|
|
|
+ CumulativeIncome json.RawMessage `json:"cumulativeIncome"`
|
|
|
+ Layer int32 `json:"layer"`
|
|
|
+ Children []struct {
|
|
|
+ UserID string `json:"userId"`
|
|
|
+ Quota json.RawMessage `json:"quota"`
|
|
|
+ Layer int32 `json:"layer"`
|
|
|
+ Children []struct {
|
|
|
+ UserID string `json:"userId"`
|
|
|
+ } `json:"children"`
|
|
|
+ } `json:"children"`
|
|
|
+ } `json:"tree"`
|
|
|
+ NodeCount int `json:"nodeCount"`
|
|
|
+ RootCount int `json:"rootCount"`
|
|
|
+}
|
|
|
+
|
|
|
+// getDivideTree 发请求并解出树响应(HTTP 恒 200)。
|
|
|
+func getDivideTree(t *testing.T, app *fiber.App) (int, divideTreeResp) {
|
|
|
+ t.Helper()
|
|
|
+ req := httptest.NewRequest(http.MethodGet, PathDivideTree, nil)
|
|
|
+ resp, err := app.Test(req, 5000)
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("请求分账树失败: %v", err)
|
|
|
+ }
|
|
|
+ defer func() { _ = resp.Body.Close() }()
|
|
|
+ var envelope struct {
|
|
|
+ Code int `json:"code"`
|
|
|
+ Data json.RawMessage `json:"data"`
|
|
|
+ }
|
|
|
+ if dErr := json.NewDecoder(resp.Body).Decode(&envelope); dErr != nil {
|
|
|
+ t.Fatalf("响应解码失败: %v", dErr)
|
|
|
+ }
|
|
|
+ var out divideTreeResp
|
|
|
+ if envelope.Code == 200 && len(envelope.Data) > 0 {
|
|
|
+ if uErr := json.Unmarshal(envelope.Data, &out); uErr != nil {
|
|
|
+ t.Fatalf("树体解码失败: %v", uErr)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return envelope.Code, out
|
|
|
+}
|
|
|
+
|
|
|
+// TestDivideTreeInvariantsHold 端点 38:两层 5 节点树,**四条不变式**逐条成立。
|
|
|
+//
|
|
|
+// 造形(root=1..10, A=2..5, A1=3..4, B=6..9, B1=7..8):
|
|
|
+//
|
|
|
+// root(layer1) ├── A(layer2) ── A1(layer3)
|
|
|
+// └── B(layer2) ── B1(layer3)
|
|
|
+//
|
|
|
+// 若实现的位移逻辑使区间重复/空洞/部分重叠,**本用例会红**(而"接口返回 200 + 有 tree 字段"不会)。
|
|
|
+func TestDivideTreeInvariantsHold(t *testing.T) {
|
|
|
+ db := newDivideTestDB(t)
|
|
|
+ root, a, a1, b, b1 := "01HROOT000000000000000001", "01HA0000000000000000001",
|
|
|
+ "01HA10000000000000000001", "01HB0000000000000000001", "01HB10000000000000000001"
|
|
|
+
|
|
|
+ seedDivideNode(t, db, &root, nil, 1, 10, 1, "100.00")
|
|
|
+ seedDivideNode(t, db, &a, &root, 2, 5, 2, "50.00")
|
|
|
+ seedDivideNode(t, db, &a1, &a, 3, 4, 3, "20.00")
|
|
|
+ seedDivideNode(t, db, &b, &root, 6, 9, 2, "30.00")
|
|
|
+ seedDivideNode(t, db, &b1, &b, 7, 8, 3, "10.00")
|
|
|
+
|
|
|
+ app := newDivideTestApp(t, db)
|
|
|
+ code, body := getDivideTree(t, app)
|
|
|
+ if code != 200 {
|
|
|
+ t.Fatalf("合法树应返回 200,实得 %d", code)
|
|
|
+ }
|
|
|
+ if body.NodeCount != 5 || body.RootCount != 1 || len(body.Tree) != 1 {
|
|
|
+ t.Fatalf("nodeCount/rootCount/len(tree) = %d/%d/%d,期望 5/1/1",
|
|
|
+ body.NodeCount, body.RootCount, len(body.Tree))
|
|
|
+ }
|
|
|
+ // I4:根 layer=1、parent 为 null
|
|
|
+ if body.Tree[0].Layer != 1 || body.Tree[0].ParentUserID != nil {
|
|
|
+ t.Fatalf("根节点 layer/parent = %d/%v,期望 1/nil", body.Tree[0].Layer, body.Tree[0].ParentUserID)
|
|
|
+ }
|
|
|
+ // I3/I4:子节点 layer=2 且挂在根下
|
|
|
+ if len(body.Tree[0].Children) != 2 {
|
|
|
+ t.Fatalf("根的直接子节点 = %d,期望 2", len(body.Tree[0].Children))
|
|
|
+ }
|
|
|
+ for _, child := range body.Tree[0].Children {
|
|
|
+ if child.Layer != 2 {
|
|
|
+ t.Errorf("子节点 %s layer = %d,期望 2", child.UserID, child.Layer)
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 逐级检查孙节点(A1 / B1 各 1 个)
|
|
|
+ grandTotal := 0
|
|
|
+ for _, child := range body.Tree[0].Children {
|
|
|
+ grandTotal += len(child.Children)
|
|
|
+ }
|
|
|
+ if grandTotal != 2 {
|
|
|
+ t.Fatalf("孙节点总数 = %d,期望 2(A1、B1)", grandTotal)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// TestDivideTreeRejectsBrokenNesting 端点 38:**故意造坏树** ⇒ 5001 + 文案指到具体不变式。
|
|
|
+//
|
|
|
+// 造法:给 B 的右值从 9 改成 5(与 A 的右值相同)⇒ I1(区间值重复)。
|
|
|
+// 这是"树坏了能被发现"的证明:只断言"返回 200 且有 tree"的实现,在这种情况下**依然绿**。
|
|
|
+func TestDivideTreeRejectsBrokenNesting(t *testing.T) {
|
|
|
+ db := newDivideTestDB(t)
|
|
|
+ root, a, b := "01HROOT000000000000000002", "01HA0000000000000000002", "01HB0000000000000000002"
|
|
|
+ seedDivideNode(t, db, &root, nil, 1, 6, 1, "100.00")
|
|
|
+ seedDivideNode(t, db, &a, &root, 2, 5, 2, "50.00")
|
|
|
+ seedDivideNode(t, db, &b, &root, 6, 5, 2, "30.00") // ⚠ 坏行:left(6) >= right(5)
|
|
|
+ _ = b
|
|
|
+
|
|
|
+ app := newDivideTestApp(t, db)
|
|
|
+ code, _ := getDivideTree(t, app)
|
|
|
+ if code != infraerrors.CodeInternal {
|
|
|
+ t.Fatalf("坏树应返回 5001(数据损坏),实得 %d —— 说明不变式校验没生效", code)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// TestDivideTreeQuotaIsMoneyString 端点 38:`quota` / `cumulativeIncome` 必须是**金额字符串**。
|
|
|
+//
|
|
|
+// mock 曾把 `quota` 当 0~1 比率 ⇒ 前端拿到 "0.35" 当 35%(差 100 倍)。
|
|
|
+// 本用例把量纲钉死:JSON 里必须是 `"100.00"` 这样的**带引号两位小数**,
|
|
|
+// 不能是 `100`(number)、也不能是 `1`/`0.35`(比率)。
|
|
|
+func TestDivideTreeQuotaIsMoneyString(t *testing.T) {
|
|
|
+ db := newDivideTestDB(t)
|
|
|
+ root := "01HROOT000000000000000003"
|
|
|
+ seedDivideNode(t, db, &root, nil, 1, 2, 1, "100.00")
|
|
|
+
|
|
|
+ app := newDivideTestApp(t, db)
|
|
|
+ code, body := getDivideTree(t, app)
|
|
|
+ if code != 200 || len(body.Tree) != 1 {
|
|
|
+ t.Fatalf("应返回 1 棵单节点树,实得 code=%d len=%d", code, len(body.Tree))
|
|
|
+ }
|
|
|
+ raw := string(body.Tree[0].Quota)
|
|
|
+ if raw != `"100.00"` {
|
|
|
+ t.Fatalf(`quota = %s,期望 "100.00"(金额字符串,两位小数;不是 0~1 比率、不是 number)`, raw)
|
|
|
+ }
|
|
|
+ if inc := string(body.Tree[0].CumulativeIncome); inc != `"0.00"` {
|
|
|
+ t.Fatalf(`cumulativeIncome = %s,期望 "0.00"`, inc)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// TestDivideTreeEmptyIsArray 空库:`tree` 必须是 `[]`(不能是 null),且不报错。
|
|
|
+func TestDivideTreeEmptyIsArray(t *testing.T) {
|
|
|
+ db := newDivideTestDB(t)
|
|
|
+ app := newDivideTestApp(t, db)
|
|
|
+ req := httptest.NewRequest(http.MethodGet, PathDivideTree, nil)
|
|
|
+ resp, err := app.Test(req, 5000)
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("请求失败: %v", err)
|
|
|
+ }
|
|
|
+ defer func() { _ = resp.Body.Close() }()
|
|
|
+ raw := new(strings.Builder)
|
|
|
+ buf := make([]byte, 4096)
|
|
|
+ n, _ := resp.Body.Read(buf)
|
|
|
+ raw.Write(buf[:n])
|
|
|
+ if strings.Contains(raw.String(), `"tree":null`) {
|
|
|
+ t.Fatalf("空树必须是 [],不能是 null:%s", raw.String())
|
|
|
+ }
|
|
|
+ if !strings.Contains(raw.String(), `"tree":[]`) {
|
|
|
+ t.Fatalf("空树应为 `tree:[]`:%s", raw.String())
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// TestDivideTreeMissingScopeIs1001 无作用域 → 1001(分账是全局数据,更不能匿名读)。
|
|
|
+func TestDivideTreeMissingScopeIs1001(t *testing.T) {
|
|
|
+ db := newDivideTestDB(t)
|
|
|
+ app := newDivideTestApp(t, db)
|
|
|
+ req := httptest.NewRequest(http.MethodGet, PathDivideTree, nil)
|
|
|
+ req.Header.Set("X-Test-Scope", "none")
|
|
|
+ resp, err := app.Test(req, 5000)
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("请求失败: %v", err)
|
|
|
+ }
|
|
|
+ defer func() { _ = resp.Body.Close() }()
|
|
|
+ var envelope struct {
|
|
|
+ Code int `json:"code"`
|
|
|
+ }
|
|
|
+ if dErr := json.NewDecoder(resp.Body).Decode(&envelope); dErr != nil {
|
|
|
+ t.Fatalf("解码失败: %v", dErr)
|
|
|
+ }
|
|
|
+ if envelope.Code != infraerrors.CodeUnauth {
|
|
|
+ t.Fatalf("无作用域应 1001,实得 %d", envelope.Code)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// TestDivideLogsWindowAndTotals 端点 43:右开窗口 + `total` 与 `list` 同口径。
|
|
|
+//
|
|
|
+// 造 3 条流水:窗口前(02-20)、窗口内(03-05)、**恰好等于 `to`**(04-01)。
|
|
|
+// 断言:`total=1`(不是历史 3)、仅 1 行、且不出现 `to` 时刻的行 —— 若实现漏了窗口条件
|
|
|
+// (或 `to` 写成闭区间),这里会红。金额同样必须是字符串。
|
|
|
+func TestDivideLogsWindowAndTotals(t *testing.T) {
|
|
|
+ db := newDivideTestDB(t)
|
|
|
+ user := "01HFINDER00000000000000001"
|
|
|
+ stu := "01HSTUDENT0000000000000001"
|
|
|
+ for _, at := range []time.Time{
|
|
|
+ time.Date(2026, 2, 20, 10, 0, 0, 0, time.UTC), // 窗口前
|
|
|
+ time.Date(2026, 3, 5, 10, 0, 0, 0, time.UTC), // 窗口内
|
|
|
+ time.Date(2026, 4, 1, 0, 0, 0, 0, time.UTC), // == to(右开:不得出现)
|
|
|
+ } {
|
|
|
+ if err := db.Create(&model.UserDivideIntoLog{
|
|
|
+ Type: 1, UserID: user, StudentID: stu, Money: "12.34", CreateTime: at,
|
|
|
+ }).Error; err != nil {
|
|
|
+ t.Fatalf("seed 流水失败: %v", err)
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ app := newDivideTestApp(t, db)
|
|
|
+ path := fmt.Sprintf("%s?findUserId=%s&from=2026-03-01&to=2026-04-01", PathDivideLogs, user)
|
|
|
+ req := httptest.NewRequest(http.MethodGet, path, nil)
|
|
|
+ resp, err := app.Test(req, 5000)
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("请求失败: %v", err)
|
|
|
+ }
|
|
|
+ defer func() { _ = resp.Body.Close() }()
|
|
|
+ var envelope struct {
|
|
|
+ Code int `json:"code"`
|
|
|
+ Data struct {
|
|
|
+ List []map[string]any `json:"list"`
|
|
|
+ Total int64 `json:"total"`
|
|
|
+ Pages int `json:"pages"`
|
|
|
+ } `json:"data"`
|
|
|
+ }
|
|
|
+ if dErr := json.NewDecoder(resp.Body).Decode(&envelope); dErr != nil {
|
|
|
+ t.Fatalf("解码失败: %v", dErr)
|
|
|
+ }
|
|
|
+ if envelope.Code != 200 {
|
|
|
+ t.Fatalf("期望 200,实得 %d", envelope.Code)
|
|
|
+ }
|
|
|
+ if envelope.Data.Total != 1 || len(envelope.Data.List) != 1 {
|
|
|
+ t.Fatalf("total/list = %d/%d,期望 1/1(右开窗口:to 时刻那笔应被排除;历史 3 笔不应计入)",
|
|
|
+ envelope.Data.Total, len(envelope.Data.List))
|
|
|
+ }
|
|
|
+ row := envelope.Data.List[0]
|
|
|
+ if got, ok := row["findUserId"].(string); !ok || got != user {
|
|
|
+ t.Fatalf("findUserId = %v,期望 %s(表列 user_id → 契约字段 findUserId)", row["findUserId"], user)
|
|
|
+ }
|
|
|
+ if money, ok := row["money"].(string); !ok || money != "12.34" {
|
|
|
+ t.Fatalf("money = %v,期望字符串 \"12.34\"", row["money"])
|
|
|
+ }
|
|
|
+ if envelope.Data.Pages != 1 {
|
|
|
+ t.Fatalf("pages = %d,期望 1", envelope.Data.Pages)
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+// TestDivideLogsRejectsReversedWindow from > to → 2001(不静默返回空集)。
|
|
|
+func TestDivideLogsRejectsReversedWindow(t *testing.T) {
|
|
|
+ db := newDivideTestDB(t)
|
|
|
+ app := newDivideTestApp(t, db)
|
|
|
+ req := httptest.NewRequest(http.MethodGet,
|
|
|
+ PathDivideLogs+"?from=2026-04-01&to=2026-03-01", nil)
|
|
|
+ resp, err := app.Test(req, 5000)
|
|
|
+ if err != nil {
|
|
|
+ t.Fatalf("请求失败: %v", err)
|
|
|
+ }
|
|
|
+ defer func() { _ = resp.Body.Close() }()
|
|
|
+ var envelope struct {
|
|
|
+ Code int `json:"code"`
|
|
|
+ }
|
|
|
+ if dErr := json.NewDecoder(resp.Body).Decode(&envelope); dErr != nil {
|
|
|
+ t.Fatalf("解码失败: %v", dErr)
|
|
|
+ }
|
|
|
+ if envelope.Code != infraerrors.CodeBadParam {
|
|
|
+ t.Fatalf("from>to 应 2001,实得 %d", envelope.Code)
|
|
|
+ }
|
|
|
+}
|