droboticflow/internal/api/unified_dictionary_mongo_test.go

79 lines
2.8 KiB
Go

package api
import (
"context"
"droboticflow/internal/domain"
"droboticflow/internal/store"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// Explicit isolated database only; exercises an old inactive unique-key owner
// against the real Mongo unique index without touching business collections.
func TestUnifiedDictionaryMongoLifecycle(t *testing.T) {
if os.Getenv("UNIFIED_DICTIONARY_MONGO_TEST") != "1" {
t.Skip("isolated Mongo opt-in")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
c, e := mongo.Connect(ctx, options.Client().ApplyURI(os.Getenv("MONGO_URI")))
if e != nil {
t.Fatal("Mongo connection")
}
defer c.Disconnect(context.Background())
name := fmt.Sprintf("unified_dictionary_test_%d", time.Now().UnixNano())
if !strings.HasPrefix(name, "unified_dictionary_test_") || name == os.Getenv("MONGO_DB") {
t.Fatal("database scope")
}
db := c.Database(name)
defer db.Drop(context.Background())
s := store.NewMongoStore(db)
_, e = db.Collection("annotationLabels").Indexes().CreateOne(ctx, mongo.IndexModel{Keys: bson.D{{Key: "organizationId", Value: 1}, {Key: "nameKey", Value: 1}}, Options: options.Index().SetName("organizationId_nameKey_unique").SetUnique(true).SetPartialFilterExpression(bson.M{"nameKey": bson.M{"$type": "string"}})})
if e != nil {
t.Fatal(e)
}
for _, kind := range []string{"action", "slice", "discard_reason"} {
old := domain.AnnotationLabelRecord{ID: "old-" + kind, OrganizationID: "org", Kind: kind, Code: "old-" + kind, Name: "历史名称", NameKey: domain.DictionaryNameKey(kind, "历史名称"), Status: domain.AnnotationLabelInactive, Version: 7, History: []domain.AnnotationLabelRevision{{Version: 7, Name: "历史名称", Status: domain.AnnotationLabelInactive}}}
if _, e = db.Collection("annotationLabels").InsertOne(ctx, old); e != nil {
t.Fatal(e)
}
var wins atomic.Int32
var wg sync.WaitGroup
for i := 0; i < 12; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
fresh := old
fresh.ID = fmt.Sprintf("new-%s-%d", kind, i)
fresh.Code = fresh.ID
fresh.Status = domain.AnnotationLabelActive
fresh.Version = 1
fresh.History = nil
e := s.UpsertAnnotationLabel(ctx, fresh)
if e == nil {
wins.Add(1)
} else if !errors.Is(e, store.ErrAnnotationLabelNameConflict) {
t.Errorf("unexpected: %v", e)
}
}(i)
}
wg.Wait()
if wins.Load() != 1 {
t.Fatalf("%s created %d duplicates", kind, wins.Load())
}
kept, e := s.GetAnnotationLabel(ctx, old.ID)
if e != nil || kept.Status != domain.AnnotationLabelInactive || kept.Version != 7 || kept.Name != old.Name || len(kept.History) != 1 {
t.Fatalf("changed history %s", kind)
}
}
}