Files
VLoop/backend/internal/worker/notificationworker_integration_test.go
huanghaosheng 151faf25fa refactor(notification): 通知实体抽成独立包
`video` 与 `worker` 各有一份 `notifications` 表的实体。
两份定义会漂移,所以合并到 `internal/notification`。
新增 `entity.go` 保存唯一一份列标签。

`worker`、`ssehub`、`comment_repo`、`db` 与两个集成测试改为引用新包。
`db` 包不再 import `worker`。
去重键仍是 `*string`,因此 NULL 才能共存。

验证:go test -count=1 ./... 全绿;集成测试三包全绿。
2026-10-30 23:48:43 +08:00

185 lines
5.6 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.
//go:build integration
package worker
import (
"context"
"encoding/json"
"os"
"strings"
"sync"
"testing"
"feedsystem_video_go/internal/middleware/rabbitmq"
"feedsystem_video_go/internal/notification"
amqp "github.com/rabbitmq/amqp091-go"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
// 通知去重的正确性完全落在数据库唯一索引上,因此只能在真实 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/worker/
type fakeHub struct {
mu sync.Mutex
pushes []*notification.Notification
}
func (h *fakeHub) Push(userID uint, n *notification.Notification) {
h.mu.Lock()
defer h.mu.Unlock()
h.pushes = append(h.pushes, n)
}
func (h *fakeHub) count() int {
h.mu.Lock()
defer h.mu.Unlock()
return len(h.pushes)
}
type testVideoRow struct {
ID uint `gorm:"primaryKey"`
AuthorID uint `gorm:"column:author_id;not null"`
}
func (testVideoRow) TableName() string { return "videos" }
func newWorkerTestDB(t *testing.T) *gorm.DB {
t.Helper()
dsn := os.Getenv("MYSQL_TEST_DSN")
if dsn == "" {
t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)")
}
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(&notification.Notification{}, &testVideoRow{}); err != nil {
t.Fatalf("drop tables: %v", err)
}
if err := db.AutoMigrate(&testVideoRow{}, &notification.Notification{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return db
}
func likeDelivery(t *testing.T, eventID string, userID, videoID uint) amqp.Delivery {
t.Helper()
body, err := json.Marshal(rabbitmq.LikeEvent{
EventID: eventID,
Action: "like",
UserID: userID,
VideoID: videoID,
})
if err != nil {
t.Fatalf("marshal event: %v", err)
}
return amqp.Delivery{Body: body, RoutingKey: rabbitmq.LikeLikeRK}
}
// 同一条事件被投递两次(MQ 假失败、重试、重放都会产生这种情形),
// 收件人只能看到一条通知、只收到一次 SSE 推送。
func TestNotificationWorker_DuplicateDeliveryWritesOneRow(t *testing.T) {
db := newWorkerTestDB(t)
if err := db.Create(&testVideoRow{ID: 10, AuthorID: 2}).Error; err != nil {
t.Fatalf("seed video: %v", err)
}
hub := &fakeHub{}
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, hub)
ctx := context.Background()
d := likeDelivery(t, "intent-0009", 1, 10)
for i := 0; i < 3; i++ {
if err := w.process(ctx, d); err != nil {
t.Fatalf("第 %d 次处理: %v", i+1, err)
}
}
var count int64
db.Model(&notification.Notification{}).Count(&count)
if count != 1 {
t.Fatalf("notifications 行数 = %d, want 1(同一意图键必须去重)", count)
}
if got := hub.count(); got != 1 {
t.Fatalf("SSE 推送次数 = %d, want 1(只有真的插入才推送)", got)
}
}
// 没有 event_id 的事件(旧版本发布的消息,或事件体里没有该字段)
// 不参与判重:宁可多一条通知,也不要因为"键为空"把不同事件判成同一条。
func TestNotificationWorker_MissingEventIDDoesNotDedupe(t *testing.T) {
db := newWorkerTestDB(t)
if err := db.Create(&testVideoRow{ID: 11, AuthorID: 2}).Error; err != nil {
t.Fatalf("seed video: %v", err)
}
hub := &fakeHub{}
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, hub)
ctx := context.Background()
d := likeDelivery(t, "", 1, 11)
for i := 0; i < 2; i++ {
if err := w.process(ctx, d); err != nil {
t.Fatalf("第 %d 次处理: %v", i+1, err)
}
}
var count int64
db.Model(&notification.Notification{}).Count(&count)
if count != 2 {
t.Fatalf("notifications 行数 = %d, want 2(无意图键时不判重)", count)
}
}
// 自己给自己的视频点赞不该产生通知,且不得写行。
func TestNotificationWorker_SelfActionWritesNothing(t *testing.T) {
db := newWorkerTestDB(t)
if err := db.Create(&testVideoRow{ID: 12, AuthorID: 7}).Error; err != nil {
t.Fatalf("seed video: %v", err)
}
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, &fakeHub{})
ctx := context.Background()
if err := w.process(ctx, likeDelivery(t, "intent-0010", 7, 12)); err != nil {
t.Fatalf("process: %v", err)
}
var count int64
db.Model(&notification.Notification{}).Count(&count)
if count != 0 {
t.Fatalf("notifications 行数 = %d, want 0", count)
}
}
// 重试队列回源时会把 routing key 改写成队列名(`like.like` → `notification.like`)。
// 这个用例用改写后的 routing key 复现该场景,断言仍然正常写入:
// 它守护的是"分派依据是队列 + body.action,不是 routing key"。
func TestNotificationWorker_RewrittenRoutingKeyStillWorks(t *testing.T) {
db := newWorkerTestDB(t)
if err := db.Create(&testVideoRow{ID: 13, AuthorID: 2}).Error; err != nil {
t.Fatalf("seed video: %v", err)
}
hub := &fakeHub{}
w := NewNotificationWorker(nil, nil, db, rabbitmq.NotificationLikeQueue, hub)
d := likeDelivery(t, "intent-0011", 1, 13)
d.RoutingKey = rabbitmq.NotificationLikeQueue // 第二次投递时的 routing key
if err := w.process(context.Background(), d); err != nil {
t.Fatalf("process: %v", err)
}
var count int64
db.Model(&notification.Notification{}).Count(&count)
if count != 1 {
t.Fatalf("notifications 行数 = %d, want 1(routing key 被改写不应影响分派)", count)
}
}