package trafficusage import ( "context" "errors" "testing" "time" "git.5iot.com/iotlcm-public/iotlcm-admin-svr/internal/consts" "git.5iot.com/iotlcm-public/iotlcm-admin-svr/internal/model" ) func TestStartMonthlyPublishesShanghaiMonth(t *testing.T) { originalNow := monthlyUsageNow originalRunID := monthlyUsageRunID originalEnabled := monthlyUsageRabbitEnabled originalPublish := monthlyUsagePublish t.Cleanup(func() { monthlyUsageNow = originalNow monthlyUsageRunID = originalRunID monthlyUsageRabbitEnabled = originalEnabled monthlyUsagePublish = originalPublish }) monthlyUsageNow = func() time.Time { return time.Date(2026, time.August, 31, 23, 30, 0, 0, time.UTC) } monthlyUsageRunID = func() string { return "test-run" } monthlyUsageRabbitEnabled = func(context.Context) bool { return true } var publishedQueue string var published model.TrafficUsageMonthlyStartMessage monthlyUsagePublish = func(_ context.Context, queue string, data any) error { publishedQueue = queue published = data.(model.TrafficUsageMonthlyStartMessage) return nil } if err := NewTrafficUsageMonthlySync().StartMonthly(context.Background()); err != nil { t.Fatalf("StartMonthly() error = %v", err) } if publishedQueue != consts.QueueTrafficUsageMonthlyStart { t.Fatalf("queue = %q, want %q", publishedQueue, consts.QueueTrafficUsageMonthlyStart) } if published.RunID != "current-month-usage-20260901-test-run" { t.Fatalf("runId = %q", published.RunID) } if published.Operation != monthlyUsageFullSyncOperation { t.Fatalf("operation = %q", published.Operation) } if published.QueryMonth != "202609" { t.Fatalf("queryMonth = %q, want 202609", published.QueryMonth) } if published.TriggeredAt != "2026-09-01T07:30:00+08:00" { t.Fatalf("triggeredAt = %q", published.TriggeredAt) } } func TestStartMonthlyReturnsPublishError(t *testing.T) { originalEnabled := monthlyUsageRabbitEnabled originalPublish := monthlyUsagePublish t.Cleanup(func() { monthlyUsageRabbitEnabled = originalEnabled monthlyUsagePublish = originalPublish }) monthlyUsageRabbitEnabled = func(context.Context) bool { return true } monthlyUsagePublish = func(context.Context, string, any) error { return errors.New("broker unavailable") } if err := NewTrafficUsageMonthlySync().StartMonthly(context.Background()); err == nil { t.Fatal("StartMonthly() error = nil, want publish error") } } func TestStartMonthlySkipsWhenRabbitMQDisabled(t *testing.T) { originalEnabled := monthlyUsageRabbitEnabled originalPublish := monthlyUsagePublish t.Cleanup(func() { monthlyUsageRabbitEnabled = originalEnabled monthlyUsagePublish = originalPublish }) monthlyUsageRabbitEnabled = func(context.Context) bool { return false } called := false monthlyUsagePublish = func(context.Context, string, any) error { called = true return nil } if err := NewTrafficUsageMonthlySync().StartMonthly(context.Background()); err == nil { t.Fatal("StartMonthly() error = nil, want disabled error") } if called { t.Fatal("publisher called while RabbitMQ is disabled") } }