207 lines
9.4 KiB
Go
207 lines
9.4 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strconv"
|
|
"testing"
|
|
|
|
"droboticflow/internal/domain"
|
|
"droboticflow/internal/store"
|
|
)
|
|
|
|
type dictionaryImportFixture struct {
|
|
t *testing.T
|
|
handler http.Handler
|
|
dataStore store.Store
|
|
adminCookie *http.Cookie
|
|
org domain.OrganizationRecord
|
|
viewerUser domain.UserRecord
|
|
project *domain.ProjectRecord
|
|
}
|
|
|
|
func newDictionaryImportFixture(t *testing.T) *dictionaryImportFixture {
|
|
t.Setenv("DROBOTICFLOW_REQUIRE_SESSION_AUTH", "true")
|
|
dataStore := store.NewMemoryStore()
|
|
handler := NewHandler(dataStore, nil)
|
|
rootCookie := bootstrapSuperAdminSession(t, handler)
|
|
organization := adminCreateOrganization(t, handler, rootCookie, "Dict Import", "dict-import")
|
|
admin := adminCreateUser(t, handler, rootCookie, organization.ID, "字典管理员", "dict-import-admin@example.com", domain.UserRoleAdmin, "dict-password")
|
|
adminCookie := loginSession(t, handler, admin.Phone, "dict-password")
|
|
viewer := adminCreateUser(t, handler, rootCookie, organization.ID, "普通成员", "dict-import-viewer@example.com", domain.UserRoleAnnotator, "viewer-password")
|
|
project, err := dataStore.CreateProject(t.Context(), domain.CreateProjectInput{OrganizationID: organization.ID, Name: "字典导入项目"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return &dictionaryImportFixture{t: t, handler: handler, dataStore: dataStore, adminCookie: adminCookie, org: organization, viewerUser: viewer, project: project}
|
|
}
|
|
|
|
func (f *dictionaryImportFixture) importLabels(cookie *http.Cookie, path string, body string) (*httptest.ResponseRecorder, map[string]any) {
|
|
f.t.Helper()
|
|
recorder := serveJSONWithCookie(f.handler, http.MethodPost, path, []byte(body), cookie)
|
|
decoded := map[string]any{}
|
|
_ = json.Unmarshal(recorder.Body.Bytes(), &decoded)
|
|
return recorder, decoded
|
|
}
|
|
|
|
func (f *dictionaryImportFixture) projectSelection(kind string) []string {
|
|
f.t.Helper()
|
|
path := "/api/projects/" + f.project.ID + "/slice-labels"
|
|
if kind == "discard_reason" {
|
|
path = "/api/projects/" + f.project.ID + "/discard-reason-labels"
|
|
} else if kind == "action" {
|
|
path = "/api/projects/" + f.project.ID + "/annotation-labels"
|
|
}
|
|
recorder := serveJSONWithCookie(f.handler, http.MethodGet, path, nil, f.adminCookie)
|
|
if recorder.Code != http.StatusOK {
|
|
f.t.Fatalf("get selection kind=%s code=%d body=%s", kind, recorder.Code, recorder.Body.String())
|
|
}
|
|
decoded := map[string]any{}
|
|
if err := json.Unmarshal(recorder.Body.Bytes(), &decoded); err != nil {
|
|
f.t.Fatal(err)
|
|
}
|
|
raw, _ := decoded["labelIds"].([]any)
|
|
ids := make([]string, 0, len(raw))
|
|
for _, id := range raw {
|
|
ids = append(ids, id.(string))
|
|
}
|
|
return ids
|
|
}
|
|
|
|
func TestProjectDictionaryLabelsImportCreatesReusesAndSkips(t *testing.T) {
|
|
f := newDictionaryImportFixture(t)
|
|
// Pre-existing active org term: import must reuse it, never duplicate.
|
|
existing := serveJSONWithCookie(f.handler, http.MethodPost, "/api/annotation-labels", []byte(`{"kind":"slice","code":"pre","name":"拿取前","status":"active"}`), f.adminCookie)
|
|
if existing.Code != http.StatusCreated {
|
|
t.Fatalf("seed label code=%d body=%s", existing.Code, existing.Body.String())
|
|
}
|
|
recorder, decoded := f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import",
|
|
`{"kind":"slice","names":["拿取前"," 商品 检查 ","商品检查","","重复A","重复A","重复A"]}`)
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("import code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
// 拿取前 → reused; " 商品 检查 " collapses to "商品 检查" (inner space kept,
|
|
// matching the frontend name key); 商品检查 and the deduped 重复A are created.
|
|
if int(decoded["created"].(float64)) != 3 || int(decoded["reused"].(float64)) != 1 {
|
|
t.Fatalf("import counts created=%v reused=%v skipped=%v", decoded["created"], decoded["reused"], decoded["skipped"])
|
|
}
|
|
skipped, _ := decoded["skipped"].([]any)
|
|
if len(skipped) != 0 {
|
|
t.Fatalf("fresh import should skip nothing, got %v", skipped)
|
|
}
|
|
ids := f.projectSelection("slice")
|
|
if len(ids) != 4 {
|
|
t.Fatalf("selection should hold four slice names, got %v", ids)
|
|
}
|
|
// Re-importing the same names: everything already selected, nothing created.
|
|
recorder, decoded = f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import",
|
|
`{"kind":"slice","names":["拿取前","商品检查"]}`)
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("re-import code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
if int(decoded["created"].(float64)) != 0 || int(decoded["reused"].(float64)) != 0 {
|
|
t.Fatalf("re-import counts created=%v reused=%v", decoded["created"], decoded["reused"])
|
|
}
|
|
skipped, _ = decoded["skipped"].([]any)
|
|
if len(skipped) != 2 {
|
|
t.Fatalf("re-import should skip both, got %v", skipped)
|
|
}
|
|
if len(f.projectSelection("slice")) != 4 {
|
|
t.Fatalf("re-import changed selection size: %v", f.projectSelection("slice"))
|
|
}
|
|
}
|
|
|
|
func TestProjectDictionaryLabelsImportKeepsKindsIsolatedAndNeverRevivesInactive(t *testing.T) {
|
|
f := newDictionaryImportFixture(t)
|
|
// Inactive historical slice term: same name must import as a NEW term.
|
|
inactive := serveJSONWithCookie(f.handler, http.MethodPost, "/api/annotation-labels", []byte(`{"kind":"slice","code":"hist","name":"旧名称","status":"inactive"}`), f.adminCookie)
|
|
if inactive.Code != http.StatusCreated {
|
|
t.Fatalf("seed inactive code=%d body=%s", inactive.Code, inactive.Body.String())
|
|
}
|
|
recorder, decoded := f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import",
|
|
`{"kind":"discard_reason","names":["旧名称","其他","画面模糊"]}`)
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("import discard code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
if int(decoded["created"].(float64)) != 3 {
|
|
t.Fatalf("discard import created=%v", decoded["created"])
|
|
}
|
|
if len(f.projectSelection("slice")) != 0 {
|
|
t.Fatalf("discard import leaked into slice dictionary: %v", f.projectSelection("slice"))
|
|
}
|
|
items, err := f.dataStore.ListAnnotationLabels(t.Context(), f.org.ID)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sliceCount, discardCount, otherRequiresNote := 0, 0, false
|
|
for _, item := range items {
|
|
switch {
|
|
case dictionaryKind(item.Kind) == "slice":
|
|
sliceCount++
|
|
case dictionaryKind(item.Kind) == "discard_reason":
|
|
discardCount++
|
|
if item.Name == "其他" && item.RequiresNote {
|
|
otherRequiresNote = true
|
|
}
|
|
}
|
|
}
|
|
if sliceCount != 1 || discardCount != 3 {
|
|
t.Fatalf("org pool slice=%d discard=%d", sliceCount, discardCount)
|
|
}
|
|
if !otherRequiresNote {
|
|
t.Fatal("discard 其他 must default to requiresNote")
|
|
}
|
|
// Same name into the slice dictionary creates a separate active term.
|
|
recorder, decoded = f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import",
|
|
`{"kind":"slice","names":["旧名称"]}`)
|
|
if recorder.Code != http.StatusOK || int(decoded["created"].(float64)) != 1 {
|
|
t.Fatalf("inactive-revival import code=%d created=%v body=%s", recorder.Code, decoded["created"], recorder.Body.String())
|
|
}
|
|
items, err = f.dataStore.ListAnnotationLabels(t.Context(), f.org.ID)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
sliceActive, sliceInactive := 0, 0
|
|
for _, item := range items {
|
|
if dictionaryKind(item.Kind) == "slice" {
|
|
if item.Status == domain.AnnotationLabelActive {
|
|
sliceActive++
|
|
} else {
|
|
sliceInactive++
|
|
}
|
|
}
|
|
}
|
|
if sliceActive != 1 || sliceInactive != 1 {
|
|
t.Fatalf("slice pool should hold one active new term and one inactive original, got active=%d inactive=%d", sliceActive, sliceInactive)
|
|
}
|
|
}
|
|
|
|
func TestProjectDictionaryLabelsImportGuards(t *testing.T) {
|
|
f := newDictionaryImportFixture(t)
|
|
viewerCookie := loginSession(t, f.handler, f.viewerUser.Phone, "viewer-password")
|
|
if recorder, _ := f.importLabels(viewerCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import", `{"kind":"slice","names":["越权"]}`); recorder.Code != http.StatusForbidden {
|
|
t.Fatalf("viewer import code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
if recorder, _ := f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import", `{"kind":"mood","names":["心情"]}`); recorder.Code != http.StatusBadRequest {
|
|
t.Fatalf("bad kind code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
if recorder, _ := f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import", `{"kind":"slice","names":[" ",""]}`); recorder.Code != http.StatusBadRequest {
|
|
t.Fatalf("empty names code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
if recorder, _ := f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import", `{"kind":"slice","names":[]}`); recorder.Code != http.StatusBadRequest {
|
|
t.Fatalf("no names code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
overflow := make([]string, dictionaryImportMaxNames+1)
|
|
for index := range overflow {
|
|
overflow[index] = "超量名称" + strconv.Itoa(index)
|
|
}
|
|
body, _ := json.Marshal(map[string]any{"kind": "slice", "names": overflow})
|
|
if recorder, _ := f.importLabels(f.adminCookie, "/api/projects/"+f.project.ID+"/dictionary-labels/import", string(body)); recorder.Code != http.StatusBadRequest {
|
|
t.Fatalf("overflow code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
if recorder, _ := f.importLabels(f.adminCookie, "/api/projects/missing-project/dictionary-labels/import", `{"kind":"slice","names":["不存在"]}`); recorder.Code != http.StatusNotFound {
|
|
t.Fatalf("missing project code=%d body=%s", recorder.Code, recorder.Body.String())
|
|
}
|
|
}
|