package qawemail import ( "context" "errors" "fmt" "os" "strings" "sync" "testing" "time" "github.com/jackc/pgx/v5/pgxpool" postgresstore "knowledge-governance/internal/platform/postgres" ) // countingMailer records real deliveries instead of talking to SMTP. It is shared by the // concurrency case, so every observation happens under the mutex. type countingMailer struct { mu sync.Mutex calls int delay time.Duration err error subjects []string to [][]string cc [][]string html []string messageIDs []string } func (m *countingMailer) Send(_ context.Context, _ SMTPConfig, msg Message) (string, error) { if m.delay > 0 { time.Sleep(m.delay) } m.mu.Lock() defer m.mu.Unlock() m.calls++ if m.err != nil { return "", m.err } id := fmt.Sprintf("", m.calls) m.subjects = append(m.subjects, msg.Subject) m.to = append(m.to, msg.To) m.cc = append(m.cc, msg.Cc) m.html = append(m.html, msg.HTML) m.messageIDs = append(m.messageIDs, id) return id, nil } func (m *countingMailer) count() int { m.mu.Lock() defer m.mu.Unlock() return m.calls } func weeklyMailFixture(t *testing.T) (*Store, *pgxpool.Pool, *countingMailer) { t.Helper() mailer := &countingMailer{} store, pool := weeklyMailFixtureWith(t, mailer) return store, pool, mailer } // weeklyMailFixtureWith applies the real schema to an explicitly disposable database. Refusing to // run without KG_WEEKLY_MAIL_TEST_DSN keeps CI honest: a skip there is not a pass. func weeklyMailFixtureWith(t *testing.T, mailer Mailer) (*Store, *pgxpool.Pool) { t.Helper() dsn := os.Getenv("KG_WEEKLY_MAIL_TEST_DSN") if dsn == "" { t.Skip("显式一次性周报邮件数据库未提供(KG_WEEKLY_MAIL_TEST_DSN):跳过不等于通过") } // The name is the only proof this is disposable; never touch a governance database. if !strings.Contains(dsn, "/kg_weekly_mail_test_") || strings.Contains(dsn, "/governance?") { t.Fatal("拒绝非一次性周报测试库") } ctx := context.Background() pool, err := pgxpool.New(ctx, dsn) if err != nil { // Deliberately do not print the DSN (it carries a password). t.Fatal("测试库连接参数无效(详情省略)") } t.Cleanup(pool.Close) if err := postgresstore.ApplyMigrations(ctx, pool); err != nil { t.Fatal(err) } store := NewStore(pool, "fixture-weekly-resend", os.Getenv("KG_WEEKLY_MAIL_TEST_KEY"), mailer) for _, statement := range []string{ `DELETE FROM qa_weekly_email_sends WHERE tenant_key=$1`, `DELETE FROM qa_weekly_confirmations WHERE tenant_key=$1`, `DELETE FROM qa_weekly_email_settings WHERE tenant_key=$1`, `DELETE FROM qa_ops_weekly_drafts WHERE tenant_key=$1`, } { if _, err := pool.Exec(ctx, statement, store.tenant); err != nil { t.Fatal(err) } } return store, pool } func seedWeeklyDraft(t *testing.T, pool *pgxpool.Pool, tenant, week string, revision int64, markdown string) { t.Helper() if _, err := pool.Exec(context.Background(), `INSERT INTO qa_ops_weekly_drafts(tenant_key,week,revision,markdown,seed,updated_by,updated_at) VALUES($1,$2,$3,$4,'{}'::jsonb,'fixture-admin',now()) ON CONFLICT (tenant_key,week) DO UPDATE SET revision=excluded.revision,markdown=excluded.markdown`, tenant, week, revision, markdown); err != nil { t.Fatal(err) } } func enabledWeeklySettings(t *testing.T, store *Store, weekday, hour int) Settings { t.Helper() settings, err := store.SaveSettings(context.Background(), "fixture-admin", SettingsInput{ BaseRevision: 0, Host: "localhost", Port: 465, Username: "kb@example.com", Password: "app-password", From: "kb@example.com", Recipients: []string{"lead@example.com", "pm@example.com"}, Cc: []string{"qa@example.com"}, Review: "owner@example.com", Weekday: weekday, Hour: hour, Enabled: true, }) if err != nil { t.Fatal(err) } return settings } func weekLocal(t *testing.T, year int, month time.Month, day, hour int) time.Time { t.Helper() return time.Date(year, month, day, hour, 5, 0, 0, time.FixedZone("CST", 8*3600)) } // A: the reported week closes at the end of its own Sunday; the 周日23点 configuration must mail // that week inside the slot instead of waiting for the next Monday (where the slot is gone). func TestAutoSendAtSundaySlotMailsTheWeekThatEndsThatDay(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) md := "# 知识库周报 2026-W45\n\n## 二、核心指标\n\n正确率:91.20%\n" seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) if _, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin"); err != nil { t.Fatal(err) } enabledWeeklySettings(t, store, 7, 23) // 周六同一小时、周日22点:都还没到配置时点,不许提前发。 if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 7, 23)); err != nil || result.State != "not_due" { t.Fatalf("周六不是配置发送日,必须 not_due,got %+v %v", result, err) } if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 22)); err != nil || result.State != "not_due" { t.Fatalf("到点前必须 not_due,got %+v %v", result, err) } if mailer.count() != 0 { t.Fatal("到点前不得投递") } sent, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)) if err != nil || sent.State != "sent" || sent.Week != "2026-W45" { t.Fatalf("周日23点必须发出当周 2026-W45,got %+v %v", sent, err) } if mailer.count() != 1 || sent.MessageID == "" { t.Fatalf("应只投递一次并记录 message_id,calls=%d message_id=%q", mailer.count(), sent.MessageID) } message := mailer.to[0] if len(message) != 2 || message[0] != "lead@example.com" { t.Fatalf("自动发送必须用正式收件人而不是测试地址:%v", message) } if len(mailer.cc[0]) != 1 || mailer.cc[0][0] != "qa@example.com" { t.Fatalf("自动发送必须带上抄送:%v", mailer.cc[0]) } // 同一时段重复触发幂等;周一00:00已不在时段内,绝不能补发。 again, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)) if err != nil || again.State != "already_sent" { t.Fatalf("同一时段重复触发必须 already_sent,got %+v %v", again, err) } if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 9, 0)); err != nil || result.State != "not_due" { t.Fatalf("周一00:00已过时段,必须 not_due,got %+v %v", result, err) } if mailer.count() != 1 { t.Fatalf("重复/越界触发造成了重复投递:calls=%d", mailer.count()) } var sentRows int if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM qa_weekly_email_sends WHERE tenant_key=$1 AND status='sent'`, store.tenant).Scan(&sentRows); err != nil { t.Fatal(err) } if sentRows != 1 { t.Fatalf("sends 表应只有一条 sent,got %d", sentRows) } } // A: an unconfirmed week, a changed body and a future week must never be mailed automatically. func TestAutoSendRefusesUnconfirmedChangedAndFutureWeeks(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) enabledWeeklySettings(t, store, 7, 23) seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, "# 知识库周报 2026-W45\n\n正确率:91.20%\n") // 未确认:不能发。 if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "nothing_confirmed" { t.Fatalf("未确认的周报必须 nothing_confirmed,got %+v %v", result, err) } if _, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin"); err != nil { t.Fatal(err) } // 已确认后改正文:确认失效,不能发。 seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 17, "# 知识库周报 2026-W45\n\n正确率:92.00%\n") if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "nothing_confirmed" { t.Fatalf("正文变化后必须 nothing_confirmed,got %+v %v", result, err) } // 未来周(W46)即使已确认也不能在 W45 的时段被自动投递。 seedWeeklyDraft(t, pool, store.tenant, "2026-W46", 1, "# 知识库周报 2026-W46\n") if _, err := store.Confirm(context.Background(), "2026-W46", "fixture-admin"); err != nil { t.Fatal(err) } if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "nothing_confirmed" { t.Fatalf("未来周不得被自动发送,got %+v %v", result, err) } if mailer.count() != 0 { t.Fatalf("不该有任何投递,calls=%d", mailer.count()) } } // Monday slots keep their old meaning: mail the week that ended, not the one that just began. func TestAutoSendOnMondayStillMailsThePreviousCompleteWeek(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, "# 知识库周报 2026-W45\n\n正确率:91.20%\n") if _, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin"); err != nil { t.Fatal(err) } enabledWeeklySettings(t, store, 1, 9) result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 9, 9)) if err != nil || result.State != "sent" || result.Week != "2026-W45" { t.Fatalf("周一09点应发送上一完整周 W45,got %+v %v", result, err) } if mailer.count() != 1 { t.Fatalf("calls=%d, want 1", mailer.count()) } } // B/C: the manual resend uses the frozen confirmed revision and is idempotent. func TestManualResendSendsFrozenRevisionOnceAndReadsBackMessageID(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) md := "# 知识库周报 2026-W45\n\n## 二、核心指标\n\n正确率:91.20%\n" seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") if err != nil { t.Fatal(err) } enabledWeeklySettings(t, store, 7, 23) png := []byte("\x89PNG\r\n\x1a\nweekly-dashboard-fixture") if err := store.SaveDashboardImage(context.Background(), "2026-W45", png); err != nil { t.Fatal(err) } now := weekLocal(t, 2026, 11, 9, 0) // 周一00:32,真实故障时刻 preview, err := store.PreviewSend(context.Background(), "2026-W45", 16, confirmation.BodySHA256, now) if err != nil { t.Fatal(err) } if preview.Status != "ready" || preview.Recipients != 2 || preview.Cc != 1 || preview.Revision != 16 { t.Fatalf("补发预览必须给出真实收件人数与版本:%+v", preview) } if mailer.count() != 0 { t.Fatal("预览不得投递") } sent, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now) if err != nil || sent.Status != "sent" { t.Fatalf("正式补发必须成功:%+v %v", sent, err) } if sent.MessageID == "" || sent.Recipients != 2 || sent.Cc != 1 { t.Fatalf("补发结果缺少 message_id 或收件人数:%+v", sent) } if mailer.count() != 1 { t.Fatalf("calls=%d, want 1", mailer.count()) } if strings.Contains(mailer.subjects[0], "测试发送") || strings.Contains(mailer.subjects[0], "2026-W45") == false { t.Fatalf("正式补发主题不对:%q", mailer.subjects[0]) } if len(mailer.to[0]) != 2 || mailer.to[0][0] == "owner@example.com" { t.Fatalf("正式补发必须发给正式收件人,而不是 review 地址:%v", mailer.to[0]) } if !strings.Contains(mailer.html[0], "91.20%") || !strings.Contains(mailer.html[0], "cid:weekly-dashboard@knowledge-governance") { t.Fatal("正式补发必须使用冻结的已确认正文和看板图片") } var status, messageID string var revision int64 if err := pool.QueryRow(context.Background(), `SELECT status,message_id,draft_revision FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status, &messageID, &revision); err != nil { t.Fatal(err) } if status != "sent" || messageID != sent.MessageID || revision != 16 { t.Fatalf("发送记录必须可读回真实结果:status=%q message_id=%q revision=%d", status, messageID, revision) } // 重复点击:幂等,不再投递,并读回同一条 message_id。 again, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now) if err != nil || again.Status != "already_sent" || again.MessageID != sent.MessageID { t.Fatalf("重复补发必须 already_sent 且回同一 message_id:%+v %v", again, err) } if mailer.count() != 1 { t.Fatalf("重复补发造成了重复投递:calls=%d", mailer.count()) } // 版本或正文不匹配:拒绝,不投递。 if _, err := store.SendManual(context.Background(), "2026-W45", 15, confirmation.BodySHA256, "fixture-admin", now); !errors.Is(err, ErrNotCurrent) { t.Fatalf("错误版本必须 ErrNotCurrent,got %v", err) } if _, err := store.SendManual(context.Background(), "2026-W45", 16, strings.Repeat("0", 64), "fixture-admin", now); !errors.Is(err, ErrNotCurrent) { t.Fatalf("错误正文 hash 必须 ErrNotCurrent,got %v", err) } seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 17, md+"\n改过的正文\n") if _, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now); !errors.Is(err, ErrNotCurrent) { t.Fatalf("正文已改必须 ErrNotCurrent,got %v", err) } if mailer.count() != 1 { t.Fatalf("被拒绝的补发不得投递:calls=%d", mailer.count()) } } // B: the manual window — no future week, and the running week only after its configured slot. func TestManualResendWindowRejectsFutureAndTooEarlyWeeks(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, "# 知识库周报 2026-W45\n") seedWeeklyDraft(t, pool, store.tenant, "2026-W46", 1, "# 知识库周报 2026-W46\n") confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") if err != nil { t.Fatal(err) } enabledWeeklySettings(t, store, 7, 23) // 未来周 W46(即便已确认)明确拒绝。 if _, err := store.Confirm(context.Background(), "2026-W46", "fixture-admin"); err != nil { t.Fatal(err) } var hash46 string if err := pool.QueryRow(context.Background(), `SELECT body_sha256 FROM qa_weekly_confirmations WHERE tenant_key=$1 AND week='2026-W46'`, store.tenant).Scan(&hash46); err != nil { t.Fatal(err) } if _, err := store.SendManual(context.Background(), "2026-W46", 1, hash46, "fixture-admin", weekLocal(t, 2026, 11, 8, 23)); !errors.Is(err, ErrFutureWeek) { t.Fatalf("未来周必须 ErrFutureWeek,got %v", err) } // 当前周 W45 在 22:05 尚未到配置时点:拒绝。 if _, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 8, 22)); !errors.Is(err, ErrSlotPending) { t.Fatalf("当前周未到配置时点必须 ErrSlotPending,got %v", err) } // 到点后允许。 if result, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 8, 23)); err != nil || result.Status != "sent" { t.Fatalf("到点后当前周应允许补发:%+v %v", result, err) } // 未确认的周没有 confirmation:拒绝。 seedWeeklyDraft(t, pool, store.tenant, "2026-W44", 3, "# 知识库周报 2026-W44\n") if _, err := store.SendManual(context.Background(), "2026-W44", 3, strings.Repeat("a", 64), "fixture-admin", weekLocal(t, 2026, 11, 9, 0)); !errors.Is(err, ErrNotCurrent) { t.Fatalf("未确认周必须 ErrNotCurrent,got %v", err) } if mailer.count() != 1 { t.Fatalf("被拒绝的补发不得投递:calls=%d", mailer.count()) } } // C: automatic and manual paths racing on the same week+revision deliver exactly once. func TestConcurrentAutoAndManualSendDeliverOnce(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") if err != nil { t.Fatal(err) } enabledWeeklySettings(t, store, 7, 23) mailer.delay = 150 * time.Millisecond now := weekLocal(t, 2026, 11, 8, 23) var wg sync.WaitGroup states := make([]string, 6) for i := 0; i < 6; i++ { wg.Add(1) go func(index int) { defer wg.Done() if index%2 == 0 { result, callErr := store.SendDue(context.Background(), now) if callErr != nil { states[index] = "error:" + callErr.Error() return } states[index] = result.State return } result, callErr := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", now) if callErr != nil { states[index] = "error:" + callErr.Error() return } states[index] = result.Status }(i) } wg.Wait() if mailer.count() != 1 { t.Fatalf("并发自动/手动必须只投递一次,calls=%d states=%v", mailer.count(), states) } var sentRows int if err := pool.QueryRow(context.Background(), `SELECT count(*) FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45' AND status='sent'`, store.tenant).Scan(&sentRows); err != nil { t.Fatal(err) } if sentRows != 1 { t.Fatalf("sends 表必须有且只有一条 sent:%d states=%v", sentRows, states) } } // C: a send whose outcome is unknown stays unknown — never blindly retried, never marked sent. func TestUnknownSendingIsNotResentAndNotMarkedSent(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") if err != nil { t.Fatal(err) } enabledWeeklySettings(t, store, 7, 23) if _, err := pool.Exec(context.Background(), `INSERT INTO qa_weekly_email_sends(tenant_key,week,draft_revision,body_sha256,status,attempts,created_at,updated_at) VALUES($1,'2026-W45',16,$2,'sending',1,now(),now())`, store.tenant, confirmation.BodySHA256); err != nil { t.Fatal(err) } if _, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)); !errors.Is(err, ErrSendInFlight) { t.Fatalf("结果未知的 sending 必须拒绝重发,got %v", err) } if result, err := store.SendDue(context.Background(), weekLocal(t, 2026, 11, 8, 23)); err != nil || result.State != "in_flight" { t.Fatalf("自动路径必须识别 in_flight,got %+v %v", result, err) } if mailer.count() != 0 { t.Fatalf("未知结果不得盲重发:calls=%d", mailer.count()) } var status string if err := pool.QueryRow(context.Background(), `SELECT status FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status); err != nil { t.Fatal(err) } if status != "sending" { t.Fatalf("未知结果不得被改写:status=%q", status) } } // C: a failed attempt is recorded as failed (never sent) and is the only reclaimable state. func TestFailedSendIsRecordedThenRetriedOnce(t *testing.T) { store, pool, mailer := weeklyMailFixture(t) md := "# 知识库周报 2026-W45\n\n正确率:91.20%\n" seedWeeklyDraft(t, pool, store.tenant, "2026-W45", 16, md) confirmation, err := store.Confirm(context.Background(), "2026-W45", "fixture-admin") if err != nil { t.Fatal(err) } enabledWeeklySettings(t, store, 7, 23) mailer.err = errors.New("smtp 连接失败: dial tcp: connection refused") failed, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)) if err != nil { t.Fatal(err) } if failed.Status != "failed" || failed.MessageID != "" { t.Fatalf("SMTP 失败必须如实记录为 failed:%+v", failed) } var status, lastError string if err := pool.QueryRow(context.Background(), `SELECT status,last_error FROM qa_weekly_email_sends WHERE tenant_key=$1 AND week='2026-W45'`, store.tenant).Scan(&status, &lastError); err != nil { t.Fatal(err) } if status != "failed" || lastError == "" { t.Fatalf("失败记录不得假写 sent:status=%q last_error=%q", status, lastError) } mailer.err = nil retried, err := store.SendManual(context.Background(), "2026-W45", 16, confirmation.BodySHA256, "fixture-admin", weekLocal(t, 2026, 11, 9, 0)) if err != nil || retried.Status != "sent" || retried.MessageID == "" { t.Fatalf("failed 记录应允许一次真实重试:%+v %v", retried, err) } if mailer.count() != 2 { t.Fatalf("calls=%d, want 2", mailer.count()) } }