Files
dobotai-platform/internal/coverage/dispatcher_test.go
2026-07-27 11:54:34 +08:00

428 lines
12 KiB
Go

package coverage
import (
"context"
"errors"
"sync"
"testing"
"time"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
)
// stubNotificationRepository is a test double for NotificationRepository.
type stubNotificationRepository struct {
mu sync.Mutex
cases []PendingSupportCase
claimErr error
markErr error
markFailedCalls map[string]string // caseID -> failureCode
markNotifiedIDs []string
}
func (s *stubNotificationRepository) Claim(ctx context.Context, limit, maxAttempts int, staleBefore time.Time) ([]PendingSupportCase, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.claimErr != nil {
return nil, s.claimErr
}
// Return a copy of the current cases up to limit
available := make([]PendingSupportCase, len(s.cases))
copy(available, s.cases)
if len(available) > limit {
available = available[:limit]
}
s.cases = s.cases[len(available):]
return available, nil
}
func (s *stubNotificationRepository) MarkNotified(ctx context.Context, caseID string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.markErr != nil {
return s.markErr
}
s.markNotifiedIDs = append(s.markNotifiedIDs, caseID)
return nil
}
func (s *stubNotificationRepository) MarkFailed(ctx context.Context, caseID string, failureCode string) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.markErr != nil {
return s.markErr
}
if s.markFailedCalls == nil {
s.markFailedCalls = make(map[string]string)
}
s.markFailedCalls[caseID] = failureCode
return nil
}
// stubNotifier is a test double for Notifier.
type stubNotifier struct {
mu sync.Mutex
sendErr error
sent []SupportNotification
// failOn maps caseID -> error to simulate per-item failure.
failOn map[string]error
}
func (s *stubNotifier) Send(ctx context.Context, notif SupportNotification) error {
s.mu.Lock()
defer s.mu.Unlock()
if err, ok := s.failOn[notif.CaseID]; ok {
return err
}
if s.sendErr != nil {
return s.sendErr
}
s.sent = append(s.sent, notif)
return nil
}
// blockingNotifier blocks until ctx is done, then returns ctx.Err().
// Used for timeout tests.
type blockingNotifier struct {
mu sync.Mutex
blocked bool
}
func (b *blockingNotifier) Send(ctx context.Context, notif SupportNotification) error {
b.mu.Lock()
b.blocked = true
b.mu.Unlock()
<-ctx.Done()
return ctx.Err()
}
func makePendingCase(id string, attempts int) PendingSupportCase {
return PendingSupportCase{
SupportNotification: SupportNotification{
CaseID: id,
Question: "test question " + id,
SenderName: "Sender " + id,
Channel: "dingtalk",
ConversationType: core.ConversationGroup,
AskedAt: time.Unix(1, 0),
PreviousQuestions: []string{"previous question"},
FAQRecordID: "record-" + id,
},
Attempts: attempts,
}
}
// TestDispatcherEmptyQueue verifies that RunOnce on an empty queue returns
// a zero stats with no error.
func TestDispatcherEmptyQueue(t *testing.T) {
repo := &stubNotificationRepository{}
notifier := &stubNotifier{}
dispatcher, err := NewDispatcher(repo, notifier)
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
stats, err := dispatcher.RunOnce(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if stats.Claimed != 0 || stats.Notified != 0 || stats.Failed != 0 {
t.Fatalf("empty queue: got %+v, want all zero", stats)
}
}
// TestDispatcherAllSuccess verifies that all claimed cases are sent and
// marked as notified.
func TestDispatcherAllSuccess(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{
makePendingCase("case-1", 0),
makePendingCase("case-2", 0),
makePendingCase("case-3", 0),
},
}
notifier := &stubNotifier{}
dispatcher, err := NewDispatcher(repo, notifier, WithBatchSize(10))
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
stats, err := dispatcher.RunOnce(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if stats.Claimed != 3 {
t.Fatalf("Claimed = %d, want 3", stats.Claimed)
}
if stats.Notified != 3 {
t.Fatalf("Notified = %d, want 3", stats.Notified)
}
if stats.Failed != 0 {
t.Fatalf("Failed = %d, want 0", stats.Failed)
}
if len(notifier.sent) != 3 {
t.Fatalf("sent %d, want 3", len(notifier.sent))
}
if len(repo.markNotifiedIDs) != 3 {
t.Fatalf("markNotifiedIDs = %d, want 3", len(repo.markNotifiedIDs))
}
}
// TestDispatcherOneFailureContinues verifies that when one item fails,
// the dispatcher continues with the rest and marks the failed one.
func TestDispatcherOneFailureContinues(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{
makePendingCase("case-1", 0),
makePendingCase("case-2", 0), // will fail
makePendingCase("case-3", 0),
},
}
notifier := &stubNotifier{
failOn: map[string]error{
"case-2": errors.New("simulated send failure"),
},
}
dispatcher, err := NewDispatcher(repo, notifier, WithBatchSize(10))
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
stats, err := dispatcher.RunOnce(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if stats.Claimed != 3 {
t.Fatalf("Claimed = %d, want 3", stats.Claimed)
}
if stats.Notified != 2 {
t.Fatalf("Notified = %d, want 2", stats.Notified)
}
if stats.Failed != 1 {
t.Fatalf("Failed = %d, want 1", stats.Failed)
}
if notifier.sent[0].CaseID != "case-1" {
t.Fatalf("first sent = %s, want case-1", notifier.sent[0].CaseID)
}
if notifier.sent[1].CaseID != "case-3" {
t.Fatalf("second sent = %s, want case-3", notifier.sent[1].CaseID)
}
// case-2 must be marked as failed with stable code, not raw error
if code, ok := repo.markFailedCalls["case-2"]; !ok {
t.Fatal("case-2 must be marked as failed")
} else if code != "dingtalk_group_send_failed" {
t.Fatalf("failure code = %q, want dingtalk_group_send_failed", code)
}
// case-1 and case-3 must be marked notified
foundNotified := make(map[string]bool)
for _, id := range repo.markNotifiedIDs {
foundNotified[id] = true
}
if !foundNotified["case-1"] {
t.Fatal("case-1 must be marked notified")
}
if !foundNotified["case-3"] {
t.Fatal("case-3 must be marked notified")
}
}
// TestDispatcherFailureStableCodeOnly verifies that the raw error text is
// never written to the repository — only the stable failure code.
func TestDispatcherFailureStableCodeOnly(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{
makePendingCase("case-1", 0),
},
}
notifier := &stubNotifier{
failOn: map[string]error{
"case-1": errors.New("secret token xyz123 leaked in error"),
},
}
dispatcher, err := NewDispatcher(repo, notifier)
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
_, err = dispatcher.RunOnce(context.Background())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if code := repo.markFailedCalls["case-1"]; code != "dingtalk_group_send_failed" {
t.Fatalf("failure code = %q, want dingtalk_group_send_failed (raw error must never leak)", code)
}
}
// TestDispatcherMarkNotifiedErrorPropagation verifies that when
// MarkNotified fails, the error is returned to the caller.
func TestDispatcherMarkNotifiedErrorPropagation(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{makePendingCase("case-1", 0)},
markErr: errors.New("db unreachable"),
}
notifier := &stubNotifier{}
dispatcher, err := NewDispatcher(repo, notifier)
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
_, err = dispatcher.RunOnce(context.Background())
if err == nil {
t.Fatal("expected error from MarkNotified, got nil")
}
}
// TestDispatcherMarkFailedErrorPropagation verifies that when MarkFailed
// fails, the error is returned to the caller.
func TestDispatcherMarkFailedErrorPropagation(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{
makePendingCase("case-1", 0),
},
markErr: errors.New("db unreachable"),
}
notifier := &stubNotifier{
failOn: map[string]error{
"case-1": errors.New("send failed"),
},
}
dispatcher, err := NewDispatcher(repo, notifier)
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
_, err = dispatcher.RunOnce(context.Background())
if err == nil {
t.Fatal("expected error from MarkFailed, got nil")
}
}
// TestDispatcherClaimErrorPropagation verifies claim errors are returned.
func TestDispatcherClaimErrorPropagation(t *testing.T) {
repo := &stubNotificationRepository{
claimErr: errors.New("db unreachable"),
}
notifier := &stubNotifier{}
dispatcher, err := NewDispatcher(repo, notifier)
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
_, err = dispatcher.RunOnce(context.Background())
if err == nil {
t.Fatal("expected error from Claim, got nil")
}
}
// TestDispatcherPerItemTimeout verifies that the dispatcher applies a per-item
// timeout: when a notifier blocks forever, RunOnce completes within a
// reasonable time, Failed=1, and the stable failure code is used.
func TestDispatcherPerItemTimeout(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{makePendingCase("case-1", 0)},
}
notifier := &blockingNotifier{}
// Use a 50ms timeout so the test is not flaky but still fast.
dispatcher, err := NewDispatcher(repo, notifier, WithSendTimeout(50*time.Millisecond))
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
start := time.Now()
stats, err := dispatcher.RunOnce(context.Background())
elapsed := time.Since(start)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if stats.Failed != 1 {
t.Fatalf("Failed = %d, want 1", stats.Failed)
}
if stats.Claimed != 1 {
t.Fatalf("Claimed = %d, want 1", stats.Claimed)
}
// Verify the stable failure code was used
if code := repo.markFailedCalls["case-1"]; code != "dingtalk_group_send_failed" {
t.Fatalf("failure code = %q, want dingtalk_group_send_failed", code)
}
// RunOnce must complete in a reasonable time (not stuck forever).
// Use a generous upper bound: 5s is enough for any CI environment.
if elapsed > 5*time.Second {
t.Fatalf("RunOnce took %v, expected to complete within 5s", elapsed)
}
if !notifier.blocked {
t.Fatal("notifier was not called — timeout did not trigger")
}
}
// TestDispatcherContextCancel verifies the dispatcher respects context cancellation.
func TestDispatcherContextCancel(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{makePendingCase("case-1", 0)},
}
notifier := &stubNotifier{}
dispatcher, err := NewDispatcher(repo, notifier, WithSendTimeout(10*time.Second))
if err != nil {
t.Fatalf("NewDispatcher: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err = dispatcher.RunOnce(ctx)
if err == nil {
t.Fatal("expected context error, got nil")
}
}
// TestDispatcherConstructorValidation verifies constructor input validation.
func TestDispatcherConstructorValidation(t *testing.T) {
tests := []struct {
name string
opts []DispatcherOption
wantErr bool
}{
{"nil repo", nil, true},
{"nil notifier only", nil, true},
{"batch too small", []DispatcherOption{WithBatchSize(0)}, true},
{"batch too large", []DispatcherOption{WithBatchSize(101)}, true},
{"maxAttempts too small", []DispatcherOption{WithMaxAttempts(0)}, true},
{"maxAttempts too large", []DispatcherOption{WithMaxAttempts(11)}, true},
{"valid defaults", nil, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var repo *stubNotificationRepository
var notifier *stubNotifier
if tt.name != "nil repo" {
repo = &stubNotificationRepository{}
}
if tt.name != "nil notifier only" {
notifier = &stubNotifier{}
}
_, err := NewDispatcher(repo, notifier, tt.opts...)
if tt.wantErr && err == nil {
t.Fatal("expected error, got nil")
}
if !tt.wantErr && err != nil {
t.Fatalf("unexpected error: %v", err)
}
})
}
}
// TestDispatcherBatchSizeLimit verifies batch size is capped at 100.
func TestDispatcherBatchSizeLimit(t *testing.T) {
repo := &stubNotificationRepository{
cases: []PendingSupportCase{},
}
notifier := &stubNotifier{}
d, err := NewDispatcher(repo, notifier, WithBatchSize(100))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if d.BatchSize != 100 {
t.Fatalf("BatchSize = %d, want 100", d.BatchSize)
}
}