//go:build integration package video import ( "context" "os" "strings" "sync" "testing" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/logger" ) // 这些用例需要真实 MySQL:本仓库没有 DB mock,而"判重与写入是同一条 SQL" // 这个性质的正确性完全取决于 MySQL 的 ON DUPLICATE KEY 语义与 RowsAffected, // 用内存替身验证等于什么都没验证。 // // docker compose up -d mysql // MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \ // go test -tags integration -count=1 ./internal/video/ // testAccount 只是 comments 提及解析的目标表投影(FindAccountIDs 查 accounts)。 type testAccount struct { ID uint `gorm:"primaryKey"` Username string `gorm:"column:username;type:varchar(255);not null;uniqueIndex"` } func (testAccount) TableName() string { return "accounts" } func newTestDB(t *testing.T) *gorm.DB { t.Helper() dsn := os.Getenv("MYSQL_TEST_DSN") if dsn == "" { t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)") } // clientFoundRows 会让"行未变化"的 UPDATE 也返回 1 行受影响, // 从而把"重复插入"误判成"插入成功",去重静默失效。生产 DSN // (internal/db/db.go)同样不能打开它,那里另有单测钉住。 if strings.Contains(dsn, "clientFoundRows") { t.Fatalf("测试 DSN 不能带 clientFoundRows:它会破坏 RowsAffected 判重") } db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Silent), }) if err != nil { t.Fatalf("connect mysql: %v", err) } if err := db.Migrator().DropTable(&Comment{}, &Video{}, &NotificationRow{}, &testAccount{}); err != nil { t.Fatalf("drop tables: %v", err) } if err := db.AutoMigrate(&testAccount{}, &Video{}, &Comment{}, &NotificationRow{}); err != nil { t.Fatalf("migrate: %v", err) } return db } func seedVideo(t *testing.T, db *gorm.DB, popularity int64) *Video { t.Helper() v := &Video{ AuthorID: 1, Username: "author", Title: "t", PlayURL: "p", CoverURL: "c", Popularity: popularity, } if err := db.Create(v).Error; err != nil { t.Fatalf("seed video: %v", err) } return v } func intPtr(s string) *string { return &s } // 同一意图键第二次写入必须报告 created=false,并且不得再次加热度。 // 这条断言同时是 DSN 护栏:若 clientFoundRows 被打开,第二次插入会 // 报告 1 行受影响,热度变成 +2。 func TestP0_4_DuplicateInsertReportsZeroRows(t *testing.T) { db := newTestDB(t) repo := NewCommentRepository(db) ctx := context.Background() v := seedVideo(t, db, 0) first := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "好看", IdempotencyKey: intPtr("intent-0001")} created, err := repo.CreateIdempotentWithPopularity(ctx, first, 1) if err != nil { t.Fatalf("第一次写入: %v", err) } if !created { t.Fatal("第一次写入必须返回 created=true") } second := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "好看", IdempotencyKey: intPtr("intent-0001")} created, err = repo.CreateIdempotentWithPopularity(ctx, second, 1) if err != nil { t.Fatalf("第二次写入应静默去重而不是报错: %v", err) } if created { t.Fatal("同一意图键的第二次写入必须返回 created=false(否则热度会 +2)") } var count int64 db.Model(&Comment{}).Count(&count) if count != 1 { t.Fatalf("comments 行数 = %d, want 1", count) } var got Video if err := db.First(&got, v.ID).Error; err != nil { t.Fatalf("reload video: %v", err) } if got.Popularity != 1 { t.Fatalf("popularity = %d, want 1(只有首次写入加热度)", got.Popularity) } } // 并发下"先 SELECT 再 INSERT"必然漏判;本用例保证判重确实是数据库唯一索引 // 在做,而不是应用层的检查。同时钉住:并发里只有一个执行者加热度。 func TestP0_4_ConcurrentInsertSingleRow(t *testing.T) { db := newTestDB(t) repo := NewCommentRepository(db) ctx := context.Background() v := seedVideo(t, db, 0) const workers = 8 var wg sync.WaitGroup var mu sync.Mutex createdCount := 0 errs := make([]error, 0, workers) for i := 0; i < workers; i++ { wg.Add(1) go func() { defer wg.Done() c := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "并发", IdempotencyKey: intPtr("intent-0002")} created, err := repo.CreateIdempotentWithPopularity(ctx, c, 1) mu.Lock() defer mu.Unlock() if err != nil { errs = append(errs, err) return } if created { createdCount++ } }() } wg.Wait() if len(errs) > 0 { t.Fatalf("并发写入出现错误: %v", errs) } if createdCount != 1 { t.Fatalf("created 次数 = %d, want 1", createdCount) } var count int64 db.Model(&Comment{}).Count(&count) if count != 1 { t.Fatalf("comments 行数 = %d, want 1", count) } var got Video if err := db.First(&got, v.ID).Error; err != nil { t.Fatalf("reload video: %v", err) } if got.Popularity != 1 { t.Fatalf("popularity = %d, want 1", got.Popularity) } } // 存量行与旧 Worker 写入的行 idempotency_key 为 NULL,多个 NULL 必须共存, // 否则迁移一上线,第二条无键评论就会撞唯一索引。 func TestP0_4_LegacyNullKeysCoexist(t *testing.T) { db := newTestDB(t) repo := NewCommentRepository(db) ctx := context.Background() v := seedVideo(t, db, 0) for i := 0; i < 3; i++ { c := &Comment{Username: "u", VideoID: v.ID, AuthorID: 7, Content: "同一条内容"} created, err := repo.CreateIdempotentWithPopularity(ctx, c, 1) if err != nil { t.Fatalf("第 %d 条无键评论写入失败: %v", i+1, err) } if !created { t.Fatalf("第 %d 条无键评论应被插入(NULL 不参与判重)", i+1) } } var count int64 db.Model(&Comment{}).Count(&count) if count != 3 { t.Fatalf("comments 行数 = %d, want 3", count) } } // 提及通知必须带 CreatedAt,且重复投递不得产生第二行。 func TestP0_4_MentionNotificationDedupe(t *testing.T) { db := newTestDB(t) repo := NewCommentRepository(db) ctx := context.Background() mention := Mention{ RecipientID: 2, SenderID: 1, TargetID: 9, Content: "@b 在评论中提到了你", DedupeKey: NotificationDedupeKey("mention", "intent-0003", 2), } for i := 0; i < 2; i++ { if err := repo.CreateMentions(ctx, []Mention{mention}); err != nil { t.Fatalf("第 %d 次写入提及通知: %v", i+1, err) } } var rows []NotificationRow if err := db.Find(&rows).Error; err != nil { t.Fatalf("查询 notifications: %v", err) } if len(rows) != 1 { t.Fatalf("notifications 行数 = %d, want 1(去重键生效)", len(rows)) } if rows[0].CreatedAt.IsZero() { t.Fatal("CreatedAt 必须被显式写入(P2-16 ①)") } } func TestFindAccountIDs_BatchResolve(t *testing.T) { db := newTestDB(t) repo := NewCommentRepository(db) ctx := context.Background() if err := db.Create(&testAccount{Username: "alice"}).Error; err != nil { t.Fatalf("seed alice: %v", err) } if err := db.Create(&testAccount{Username: "bob"}).Error; err != nil { t.Fatalf("seed bob: %v", err) } ids, err := repo.FindAccountIDs(ctx, []string{"alice", "bob", "nobody"}) if err != nil { t.Fatalf("FindAccountIDs: %v", err) } if len(ids) != 2 { t.Fatalf("解析到 %d 个账号, want 2(不存在的用户名不应出现)", len(ids)) } if ids["alice"] == 0 || ids["bob"] == 0 || ids["alice"] == ids["bob"] { t.Fatalf("解析结果异常: %+v", ids) } }