54 lines
1.7 KiB
Go
54 lines
1.7 KiB
Go
|
|
//go:build integration
|
|||
|
|
|
|||
|
|
package video
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"context"
|
|||
|
|
"testing"
|
|||
|
|
"time"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
// 派生计数没有对账就只能靠"写路径永远正确"来保证,而写路径会崩、
|
|||
|
|
// 会被手工改库、会在回滚期间落后。这个用例先用直插行制造漂移,
|
|||
|
|
// 再断言 Reconcile 把两列拉回 COUNT,并且可以安全重跑。
|
|||
|
|
func TestReconcile_FixesDrift(t *testing.T) {
|
|||
|
|
db := newTestDB(t)
|
|||
|
|
ctx := context.Background()
|
|||
|
|
v := seedVideo(t, db, 0) // likes_count=0, popularity=0,行数为 0
|
|||
|
|
|
|||
|
|
now := time.Now().UTC()
|
|||
|
|
for _, account := range []uint{1, 2} {
|
|||
|
|
if err := db.Create(&Like{VideoID: v.ID, AccountID: account, CreatedAt: now}).Error; err != nil {
|
|||
|
|
t.Fatalf("seed like %d: %v", account, err)
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
if err := db.Create(&Comment{Username: "alice", VideoID: v.ID, AuthorID: 1, Content: "x", CreatedAt: now}).Error; err != nil {
|
|||
|
|
t.Fatalf("seed comment: %v", err)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
checked, fixed, err := NewCounterReconciler(db).Reconcile(ctx, 10)
|
|||
|
|
if err != nil {
|
|||
|
|
t.Fatalf("Reconcile: %v", err)
|
|||
|
|
}
|
|||
|
|
if checked != 1 || fixed != 1 {
|
|||
|
|
t.Fatalf("checked=%d fixed=%d, want 1/1(这条视频的两个计数都偏了)", checked, fixed)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
var got Video
|
|||
|
|
if err := db.First(&got, v.ID).Error; err != nil {
|
|||
|
|
t.Fatalf("reload video: %v", err)
|
|||
|
|
}
|
|||
|
|
if got.LikesCount != 2 || got.Popularity != 3 {
|
|||
|
|
t.Fatalf("likes_count=%d popularity=%d, want 2/3(点赞 2 + 评论 1)", got.LikesCount, got.Popularity)
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// fixOne 是"锁行 + 重算",可以安全重跑:修好之后再跑不应再发现漂移。
|
|||
|
|
checked, fixed, err = NewCounterReconciler(db).Reconcile(ctx, 10)
|
|||
|
|
if err != nil {
|
|||
|
|
t.Fatalf("第二次 Reconcile: %v", err)
|
|||
|
|
}
|
|||
|
|
if checked != 0 || fixed != 0 {
|
|||
|
|
t.Fatalf("第二次 checked=%d fixed=%d, want 0/0", checked, fixed)
|
|||
|
|
}
|
|||
|
|
}
|