Files
yhy-mager/backend/internal/httpapi/suffixes_test.go
lianjianwei2024 dd9d5470c2 feat: add suffix management module under business admin
- migration 000017: suffix_dirs tree (info-price style, two-root sidebar),
  suffix_groups, suffixes, per-directory columns with value flag, cells,
  row anchors and template files (stored under PACKAGE_STORAGE_ROOT)
- Go API /api/v1/suffix-admin/*: tree/page/CRUD/reorder for dirs, groups,
  suffixes and columns; cell upsert; anchor toggle; template upload with
  sha256 verification, scoped download/delete; admin session required
- RequiredSchemaVersion 16 -> 17
- Vue panel /suffixes (menu below payment plans): two roots (basic setup +
  info-price directory tree), grouped suffix sheet with template upload,
  add-column dialog with 值设置 checkbox (value cells store {anchor,value});
  removed attribute-table/field-mapping/column-sort/value-setting toolbar
- tests: integration test (MYSQL_TEST_DSN gated) + 3 vitest cases
2026-10-30 11:32:22 +08:00

240 lines
9.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package httpapi
import (
"bytes"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
)
// 后缀管理全链路:分组/后缀/目录树/列(值设置)/单元格/锚定/模板上传下载删除。
// 需要真实 MySQL:MYSQL_TEST_DSN 未设置时跳过(与 business_integration_test 同口径)。
func TestSuffixAdminIntegration(t *testing.T) {
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN is not set")
}
db, err := sql.Open("mysql", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
if err = db.Ping(); err != nil {
t.Fatal(err)
}
for _, table := range []string{"suffix_files", "suffix_dir_anchors", "suffix_cells", "suffix_columns", "suffixes", "suffix_groups", "suffix_dirs"} {
if _, err = db.Exec("DELETE FROM " + table); err != nil {
t.Fatalf("清理 %s: %v", table, err)
}
}
// 只清测试自己的管理员与会话,绝不动共享开发库里的真实账号。
if _, err = db.Exec("DELETE FROM sessions WHERE admin_id IN (SELECT id FROM admins WHERE username='suffixtest')"); err != nil {
t.Fatalf("清理测试会话: %v", err)
}
if _, err = db.Exec("DELETE FROM admins WHERE username='suffixtest'"); err != nil {
t.Fatalf("清理测试管理员: %v", err)
}
if _, err = db.Exec("INSERT INTO suffix_dirs(parent_id,name,sort_order) VALUES(NULL,'按信息价的目录',0)"); err != nil {
t.Fatalf("播种根目录: %v", err)
}
hash, _ := bcrypt.GenerateFromPassword([]byte("test-pass-123"), bcrypt.DefaultCost)
if _, err = db.Exec("INSERT INTO admins(username,email,password_hash,role,active) VALUES('suffixtest','suffixtest@local.dev',?,'admin',1)", string(hash)); err != nil {
t.Fatalf("建管理员: %v", err)
}
router := NewRouter()
RegisterBusiness(router, db)
t.Setenv("PACKAGE_STORAGE_ROOT", t.TempDir())
do := func(method, path, body string) *httptest.ResponseRecorder {
var reader *strings.Reader
if body == "" {
reader = strings.NewReader("")
} else {
reader = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, reader)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
// 登录拿会话
w := do(http.MethodPost, "/api/v1/auth/login", `{"username":"suffixtest","password":"test-pass-123"}`)
if w.Code != 200 {
t.Fatalf("登录 status=%d body=%s", w.Code, w.Body.String())
}
cookie := ""
for _, c := range w.Result().Cookies() {
if c.Name == "lp_session" {
cookie = c.Name + "=" + c.Value
}
}
if cookie == "" {
t.Fatal("登录未返回会话 Cookie")
}
authed := func(method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Cookie", cookie)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
getJSON := func(w *httptest.ResponseRecorder) map[string]any {
var out map[string]any
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil {
t.Fatalf("响应不是 JSON: %s", w.Body.String())
}
return out
}
// 未登录应 401
if w = do(http.MethodGet, "/api/v1/suffix-admin/tree", ""); w.Code != 401 {
t.Fatalf("未登录访问 tree status=%d, want 401", w.Code)
}
// 分组 + 后缀
w = authed(http.MethodPost, "/api/v1/suffix-admin/groups", `{"name":"广东省"}`)
if w.Code != 201 {
t.Fatalf("建分组 status=%d body=%s", w.Code, w.Body.String())
}
groupID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPost, "/api/v1/suffix-admin/groups", `{"name":"广东省"}`)
if w.Code != 409 {
t.Fatalf("重名分组 status=%d, want 409", w.Code)
}
w = authed(http.MethodPost, "/api/v1/suffix-admin/suffixes", fmt.Sprintf(`{"group_id":%d}`, groupID))
if w.Code != 201 {
t.Fatalf("建后缀 status=%d body=%s", w.Code, w.Body.String())
}
suffixID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPut, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d", suffixID), `{"name":"cos4"}`)
if w.Code != 200 {
t.Fatalf("改后缀名 status=%d body=%s", w.Code, w.Body.String())
}
// 目录树:根 + 子目录 + 改名 + 删除保护
w = authed(http.MethodGet, "/api/v1/suffix-admin/tree", "")
dirs := getJSON(w)["data"].(map[string]any)["dirs"].([]any)
root := dirs[0].(map[string]any)
rootID := uint64(root["id"].(float64))
if root["name"] != "按信息价的目录" {
t.Fatalf("根目录名=%v", root["name"])
}
w = authed(http.MethodPost, "/api/v1/suffix-admin/dirs", fmt.Sprintf(`{"parent_id":%d,"name":"一、黑色及有色"}`, rootID))
if w.Code != 201 {
t.Fatalf("建子目录 status=%d body=%s", w.Code, w.Body.String())
}
dirID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPost, "/api/v1/suffix-admin/dirs", fmt.Sprintf(`{"parent_id":0,"name":"第二个根"}`))
if w.Code != 403 {
t.Fatalf("建第二根 status=%d, want 403", w.Code)
}
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d", rootID), "")
if w.Code != 403 {
t.Fatalf("删根 status=%d, want 403", w.Code)
}
// 列(值设置勾选)+ 单元格 + 锚定
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"招标人","is_value":false}`)
if w.Code != 201 {
t.Fatalf("建普通列 status=%d body=%s", w.Code, w.Body.String())
}
plainColID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"工料机类型","is_value":true}`)
if w.Code != 201 {
t.Fatalf("建值列 status=%d body=%s", w.Code, w.Body.String())
}
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID), `{"name":"招标人","is_value":false}`)
if w.Code != 409 {
t.Fatalf("同目录重名列 status=%d, want 409", w.Code)
}
w = authed(http.MethodPut, "/api/v1/suffix-admin/cells",
fmt.Sprintf(`{"dir_id":%d,"suffix_id":%d,"column_id":%d,"value":"普通文本"}`, dirID, suffixID, plainColID))
if w.Code == 404 || w.Code == 400 {
t.Fatalf("存普通单元格被拒 status=%d body=%s", w.Code, w.Body.String())
}
// 工作区载荷
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
page := getJSON(w)["data"].(map[string]any)
cols := page["columns"].([]any)
if len(cols) != 2 {
t.Fatalf("列数=%d, want 2", len(cols))
}
if !cols[1].(map[string]any)["is_value"].(bool) {
t.Fatal("第二列应为值列")
}
// 锚定开与关
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
fmt.Sprintf(`{"suffix_id":%d,"on":true}`, suffixID))
if w.Code != 200 {
t.Fatalf("锚定 status=%d", w.Code)
}
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
sfx := getJSON(w)["data"].(map[string]any)["suffixes"].([]any)
if !sfx[0].(map[string]any)["anchor"].(bool) {
t.Fatal("锚定后 anchor 应为 true")
}
// 模板上传(内容与哈希校验)→ 概览 → 删除
content := []byte("COS4-skeleton-demo")
sum := sha256.Sum256(content)
b64 := base64.StdEncoding.EncodeToString(content)
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d/files", suffixID),
fmt.Sprintf(`{"file_name":"骨架.cos4","size":%d,"sha256":"%s","content_base64":"%s"}`,
len(content), hex.EncodeToString(sum[:]), b64))
if w.Code != 201 {
t.Fatalf("传模板 status=%d body=%s", w.Code, w.Body.String())
}
fileID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
badSum := sha256.Sum256([]byte("tampered"))
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d/files", suffixID),
fmt.Sprintf(`{"file_name":"坏.cos4","size":%d,"sha256":"%s","content_base64":"%s"}`,
len(content), hex.EncodeToString(badSum[:]), b64))
if w.Code != 400 {
t.Fatalf("哈希不符 status=%d, want 400", w.Code)
}
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/files/%d/download", fileID), "")
if w.Code != 200 || !bytes.Contains(w.Body.Bytes(), content) {
t.Fatalf("下载 status=%d body=%q", w.Code, w.Body.String())
}
w = authed(http.MethodGet, "/api/v1/suffix-admin/overview", "")
groups := getJSON(w)["data"].(map[string]any)["groups"].([]any)
files := groups[0].(map[string]any)["suffixes"].([]any)[0].(map[string]any)["files"].([]any)
if len(files) != 1 {
t.Fatalf("概览文件数=%d, want 1", len(files))
}
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/files/%d", fileID), "")
if w.Code != 200 {
t.Fatalf("删模板 status=%d", w.Code)
}
// 删目录(级联)与删分组(级联文件)
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d", dirID), "")
if w.Code != 200 {
t.Fatalf("删目录 status=%d", w.Code)
}
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/groups/%d", groupID), "")
if w.Code != 200 {
t.Fatalf("删分组 status=%d", w.Code)
}
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM suffix_files").Scan(&count); err != nil || count != 0 {
t.Fatalf("文件残留 count=%d err=%v", count, err)
}
}