Files
yhy-mager/backend/internal/httpapi/suffixes_test.go
lianjianwei2024 5fdac9902d
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat(suffix): 支持根目录重命名、列宽保存、锚定值与文件发布
2026-10-31 09:17:28 +08:00

430 lines
18 KiB
Go
Raw Permalink 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"
"path/filepath"
"strconv"
"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", "suffix_col_widths"} {
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)
storageRoot := t.TempDir()
t.Setenv("PACKAGE_STORAGE_ROOT", storageRoot)
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,"name":"cos4"}`, 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.MethodPost, "/api/v1/suffix-admin/groups", `{"name":"广西自治区","first_suffix_name":"xml"}`)
if w.Code != 201 {
t.Fatalf("建组带后缀 status=%d body=%s", w.Code, w.Body.String())
}
gx := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
sx := getJSON(w)["data"].(map[string]any)["suffixes"].([]any)
if len(sx) != 1 || sx[0].(map[string]any)["name"] != "xml" {
t.Fatalf("首后缀自动行不符: %v", sx)
}
_ = gx
// 同名再建 → 自动 -1
w = authed(http.MethodPost, "/api/v1/suffix-admin/suffixes", fmt.Sprintf(`{"group_id":%d,"name":"cos4"}`, groupID))
if w.Code != 201 {
t.Fatalf("同名后缀 status=%d body=%s", w.Code, w.Body.String())
}
if got := getJSON(w)["data"].(map[string]any)["name"]; got != "cos4-1" {
t.Fatalf("同名自动 -1: got %v", got)
}
// 空名 → 400
w = authed(http.MethodPost, "/api/v1/suffix-admin/suffixes", fmt.Sprintf(`{"group_id":%d,"name":""}`, groupID))
if w.Code != 400 {
t.Fatalf("空名 status=%d, want 400", w.Code)
}
// 目录树:根 + 子目录 + 改名 + 删除保护
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.MethodPut, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d", rootID), `{"name":"建设项目"}`)
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)
if dirs[0].(map[string]any)["name"] != "建设项目" {
t.Fatalf("改根名后=%v", dirs[0].(map[string]any)["name"])
}
// 列(值设置勾选)+ 单元格 + 锚定
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())
}
valueColID := 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":false}`)
if w.Code != 409 {
t.Fatalf("同目录重名列 status=%d, want 409", w.Code)
}
// 精准插入:插到 招标人 之后
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns", dirID),
fmt.Sprintf(`{"name":"插队列","is_value":false,"after_id":%d}`, plainColID))
if w.Code != 201 {
t.Fatalf("精准插列 status=%d body=%s", w.Code, w.Body.String())
}
insertedID := uint64(getJSON(w)["data"].(map[string]any)["id"].(float64))
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
pageCols := getJSON(w)["data"].(map[string]any)["columns"].([]any)
if pageCols[1].(map[string]any)["id"].(float64) != float64(insertedID) {
t.Fatal("精准插列应落在 招标人 之后(第2位)")
}
// 列排序:插队列移回末位 → 顺序变为 招标人,工料机类型,插队列
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
fmt.Sprintf(`{"ids":[%d,%d,%d]}`, plainColID, valueColID, insertedID))
if w.Code != 200 {
t.Fatalf("列排序 status=%d body=%s", w.Code, w.Body.String())
}
// 漏传列:没传的按原顺序补到末尾 → 顺序不变(招标人,工料机类型,插队列)
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
fmt.Sprintf(`{"ids":[%d,%d]}`, plainColID, valueColID))
if w.Code != 200 {
t.Fatalf("漏传列补尾 status=%d body=%s", w.Code, w.Body.String())
}
// 外列 → 404
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/columns/order", dirID),
`{"ids":[999999]}`)
if w.Code != 404 {
t.Fatalf("外列 status=%d, want 404", w.Code)
}
w = authed(http.MethodGet, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/page", dirID), "")
orderedCols := getJSON(w)["data"].(map[string]any)["columns"].([]any)
if orderedCols[0].(map[string]any)["name"] != "招标人" || orderedCols[1].(map[string]any)["name"] != "工料机类型" || orderedCols[2].(map[string]any)["name"] != "插队列" {
t.Fatalf("排序后顺序不符: %v", orderedCols)
}
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) != 3 {
t.Fatalf("列数=%d, want 3", len(cols))
}
// 排序后顺序:招标人,工料机类型,插队列;第二列=值列
if !cols[1].(map[string]any)["is_value"].(bool) {
t.Fatal("第二列应为值列")
}
// 列重命名:成功、同目录重名 409、空名 400
w = authed(http.MethodPatch, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), `{"name":"招标单位"}`)
if w.Code != 200 {
t.Fatalf("重命名列 status=%d body=%s", w.Code, w.Body.String())
}
if name := getJSON(w)["data"].(map[string]any)["name"].(string); name != "招标单位" {
t.Fatalf("重命名后 name=%q, want 招标单位", name)
}
w = authed(http.MethodPatch, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), `{"name":"工料机类型"}`)
if w.Code != 409 {
t.Fatalf("重名列 status=%d, want 409", w.Code)
}
w = authed(http.MethodPatch, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), `{"name":" "}`)
if w.Code != 400 {
t.Fatalf("空名列 status=%d, want 400", w.Code)
}
// 列有值不可删除:普通列已存「普通文本」
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), "")
if w.Code != 409 {
t.Fatalf("删有值列 status=%d, want 409", w.Code)
}
// 空列可直接删除
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", insertedID), "")
if w.Code != 200 {
t.Fatalf("删空列 status=%d body=%s", w.Code, w.Body.String())
}
// 清空单元格后即可删除
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 != 200 {
t.Fatalf("清空单元格 status=%d body=%s", w.Code, w.Body.String())
}
w = authed(http.MethodDelete, fmt.Sprintf("/api/v1/suffix-admin/columns/%d", plainColID), "")
if w.Code != 200 {
t.Fatalf("清空后删列 status=%d body=%s", w.Code, w.Body.String())
}
// 固定列列宽:默认值(后缀 50)→ 保存 → 回读;非法参数拒绝
w = authed(http.MethodGet, "/api/v1/suffix-admin/col-widths", "")
if w.Code != 200 {
t.Fatalf("读列宽 status=%d body=%s", w.Code, w.Body.String())
}
widths := getJSON(w)["data"].(map[string]any)["widths"].(map[string]any)
if widths["basic"].(map[string]any)["suffix"].(float64) != 50 {
t.Fatalf("basic.suffix 默认应为 50,got %v", widths["basic"].(map[string]any)["suffix"])
}
if _, has := widths["basic"].(map[string]any)["files"]; !has {
t.Fatal("basic 固定列应含 files")
}
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"workspace","key":"ops","width":66}`)
if w.Code != 200 {
t.Fatalf("存列宽 status=%d body=%s", w.Code, w.Body.String())
}
w = authed(http.MethodGet, "/api/v1/suffix-admin/col-widths", "")
widths = getJSON(w)["data"].(map[string]any)["widths"].(map[string]any)
if widths["workspace"].(map[string]any)["ops"].(float64) != 66 {
t.Fatalf("workspace.ops 应为 66,got %v", widths["workspace"].(map[string]any)["ops"])
}
if widths["workspace"].(map[string]any)["suffix"].(float64) != 50 {
t.Fatalf("未保存过的 workspace.suffix 应仍为默认 50,got %v", widths["workspace"].(map[string]any)["suffix"])
}
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"nope","key":"ops","width":66}`)
if w.Code != 400 {
t.Fatalf("非法 scope status=%d, want 400", w.Code)
}
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"basic","key":"files","width":9999}`)
if w.Code != 400 {
t.Fatalf("列宽越界 status=%d, want 400", w.Code)
}
w = authed(http.MethodPut, "/api/v1/suffix-admin/col-widths", `{"scope":"basic","key":"nope","width":10}`)
if w.Code != 400 {
t.Fatalf("未知列 key status=%d, want 400", w.Code)
}
// 锚定行存值:保存 → 回读;空值清除;超长拒绝
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
fmt.Sprintf(`{"suffix_id":%d,"value":"3"}`, 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)
cos4 := func() map[string]any {
for _, line := range sfx {
if line.(map[string]any)["name"] == "cos4" {
return line.(map[string]any)
}
}
t.Fatal("找不到 cos4 行")
return nil
}()
if cos4["anchor_value"].(string) != "3" {
t.Fatalf("锚定后 anchor_value=%q, want 3", cos4["anchor_value"])
}
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
fmt.Sprintf(`{"suffix_id":%d,"value":""}`, 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)
for _, line := range sfx {
if line.(map[string]any)["name"] == "cos4" && line.(map[string]any)["anchor_value"].(string) != "" {
t.Fatal("清空后 anchor_value 应为空")
}
}
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/dirs/%d/anchor", dirID),
fmt.Sprintf(`{"suffix_id":%d,"value":"%s"}`, suffixID, strings.Repeat("长", 191)))
if w.Code != 400 {
t.Fatalf("超长锚定值 status=%d, want 400", w.Code)
}
// 模板上传(内容与哈希校验)→ 概览 → 删除
content := []byte("COS4-skeleton-demo")
sum := sha256.Sum256(content)
b64 := base64.StdEncoding.EncodeToString(content)
// 扩展名与本行后缀不符 → 400
w = authed(http.MethodPost, fmt.Sprintf("/api/v1/suffix-admin/suffixes/%d/files", suffixID),
fmt.Sprintf(`{"file_name":"骨架.xml","size":%d,"sha256":"%s","content_base64":"%s"}`,
len(content), hex.EncodeToString(sum[:]), b64))
if w.Code != 400 {
t.Fatalf("扩展名不符 status=%d, want 400", w.Code)
}
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))
// 附件必须落盘在 attachments/<后缀id>/ 下
storedName := getJSON(w)["data"].(map[string]any)["file_name"].(string)
if _, err := os.Stat(filepath.Join(storageRoot, "attachments", strconv.FormatUint(suffixID, 10), storedName)); err != nil {
t.Fatalf("附件未落在 attachments 目录: %v", err)
}
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)
var files []any
for _, line := range groups[0].(map[string]any)["suffixes"].([]any) {
m := line.(map[string]any)
if m["name"] == "cos4" {
files = m["files"].([]any)
break
}
}
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)
}
}