package video import ( "strings" "testing" "feedsystem_video_go/internal/apierror" ) // 意图键是"一次用户想发一条评论"的唯一身份,它的格式一旦被放宽, // 判重就会静默失效(不同重试生成不同键 = 每次都是新意图)。因此这里 // 逐条钉住边界:长度上下限、允许字符、以及非法输入必须是 400 而不是 500。 func TestNewIntentKey_Format(t *testing.T) { t.Helper() seen := make(map[string]struct{}, 4) for i := 0; i < 4; i++ { key, err := NewIntentKey() if err != nil { t.Fatalf("NewIntentKey() error = %v", err) } if len(key) != 32 { t.Fatalf("NewIntentKey() len = %d, want 32 (16 字节 hex)", len(key)) } if err := validateIntentKey(key); err != nil { t.Fatalf("NewIntentKey() 生成了自己都不接受的键 %q: %v", key, err) } if _, dup := seen[key]; dup { t.Fatalf("NewIntentKey() 连续生成重复键 %q", key) } seen[key] = struct{}{} } } func TestResolveIntentKey_Table(t *testing.T) { ptr := func(s string) *string { return &s } tests := []struct { name string raw *string want string // 期望的原样返回;空串表示"应当生成新键" wantErr bool }{ {name: "nil 生成新键", raw: nil, want: ""}, {name: "空白生成新键", raw: ptr(" "), want: ""}, {name: "合法键原样返回", raw: ptr("abcdefgh"), want: "abcdefgh"}, {name: "首尾空白被裁掉", raw: ptr(" abcdefgh1234 "), want: "abcdefgh1234"}, {name: "恰好 64 字符可接受", raw: ptr(strings.Repeat("a", MaxIntentKeyLen)), want: strings.Repeat("a", MaxIntentKeyLen)}, {name: "7 字符过短", raw: ptr("abcdefg"), wantErr: true}, {name: "65 字符过长", raw: ptr(strings.Repeat("a", MaxIntentKeyLen+1)), wantErr: true}, {name: "含空格非法", raw: ptr("abc defgh"), wantErr: true}, {name: "含冒号非法", raw: ptr("abc:defgh"), wantErr: true}, {name: "含斜杠非法", raw: ptr("abc/defgh"), wantErr: true}, {name: "含中文非法", raw: ptr("意图键意图键"), wantErr: true}, {name: "允许连字符与下划线", raw: ptr("abc-def_gh"), want: "abc-def_gh"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Helper() got, err := ResolveIntentKey(tc.raw) if tc.wantErr { if err == nil { t.Fatalf("ResolveIntentKey(%v) 期望报错,得到 %q", tc.raw, got) } // 非法 request_id 是客户端的错,必须落 400;500 会让前端把 // "参数写错"显示成"服务端故障",也污染错误率指标。 if status := apierror.ClassifyHTTPStatus(err); status != 400 { t.Fatalf("ClassifyHTTPStatus(%v) = %d, want 400", err, status) } return } if err != nil { t.Fatalf("ResolveIntentKey(%v) error = %v", tc.raw, err) } if tc.want == "" { if len(got) != 32 { t.Fatalf("期望生成 32 字符新键,得到 %q", got) } return } if got != tc.want { t.Fatalf("ResolveIntentKey(%v) = %q, want %q", tc.raw, got, tc.want) } }) } } // 通知去重键的格式必须稳定:它同时是唯一索引值,写成别的形状会让 // "同一条评论的两次投递"算出两个键,去重直接失效。 func TestNotificationDedupeKey_Format(t *testing.T) { t.Helper() if got, want := NotificationDedupeKey("mention", "abc12345", 12), "mention:abc12345:12"; got != want { t.Fatalf("NotificationDedupeKey() = %q, want %q", got, want) } // 空意图键返回空串:该列可空,多个 NULL 共存,退化为"不去重", // 而不是把所有无键通知挤到同一个键上只留一条。 if got := NotificationDedupeKey("mention", "", 12); got != "" { t.Fatalf("空意图键应返回空串,得到 %q", got) } }