package main import ( "context" "errors" "log" "os" "strings" "sync" "testing" "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/questiontable" ) // --------------------------------------------------------------------------- // Test 1: disabled all blank returns nil/no error // --------------------------------------------------------------------------- func TestReadQuestionTableConfigDisabledAllBlank(t *testing.T) { t.Setenv("DINGTALK_QUESTION_TABLE_BASE_ID", "") t.Setenv("DINGTALK_QUESTION_TABLE_SHEET_ID", "") t.Setenv("DINGTALK_QUESTION_TABLE_OPERATOR_ID", "") cfg, err := readQuestionTableConfig() if err != nil { t.Fatalf("unexpected error: %v", err) } if cfg.BaseID != "" || cfg.SheetID != "" || cfg.OperatorID != "" { t.Errorf("expected empty config, got %+v", cfg) } } func TestBuildQuestionTableDispatcherDisabled(t *testing.T) { d, err := buildQuestionTableDispatcher(nil, "", "", questionTableConfig{}, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } if d != nil { t.Errorf("expected nil dispatcher for disabled config, got %v", d) } } // --------------------------------------------------------------------------- // Test 2: every partial combination errors and does not echo sentinel config values // --------------------------------------------------------------------------- func TestReadQuestionTableConfigPartialErrors(t *testing.T) { tests := []struct { name string baseID string sheetID string operator string }{ {"only base", "base-1", "", ""}, {"only sheet", "", "sheet-1", ""}, {"only operator", "", "", "op-1"}, {"base+sheet", "base-1", "sheet-1", ""}, {"base+operator", "base-1", "", "op-1"}, {"sheet+operator", "", "sheet-1", "op-1"}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { t.Setenv("DINGTALK_QUESTION_TABLE_BASE_ID", tc.baseID) t.Setenv("DINGTALK_QUESTION_TABLE_SHEET_ID", tc.sheetID) t.Setenv("DINGTALK_QUESTION_TABLE_OPERATOR_ID", tc.operator) _, err := readQuestionTableConfig() if err == nil { t.Fatal("expected error for partial config") } errStr := err.Error() // Must not echo any sentinel config value. for _, sentinel := range []string{"base-1", "sheet-1", "op-1"} { if strings.Contains(errStr, sentinel) { t.Errorf("error must not echo sentinel value %q: %q", sentinel, errStr) } } }) } } // --------------------------------------------------------------------------- // Test 3: enabled missing repo/client/secret fails closed; complete config builds // --------------------------------------------------------------------------- func TestBuildQuestionTableDispatcherEnabledMissingRepo(t *testing.T) { cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} _, err := buildQuestionTableDispatcher(nil, "cid", "secret", cfg, nil) if err == nil { t.Fatal("expected error when repo is nil") } if !strings.Contains(err.Error(), "repository is required") { t.Errorf("error = %v, want 'repository is required'", err) } } func TestBuildQuestionTableDispatcherEnabledMissingClientID(t *testing.T) { repo := &questionTableExportRepoStub{} cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} _, err := buildQuestionTableDispatcher(repo, "", "secret", cfg, nil) if err == nil { t.Fatal("expected error when client id is empty") } } func TestBuildQuestionTableDispatcherEnabledMissingSecret(t *testing.T) { repo := &questionTableExportRepoStub{} cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} _, err := buildQuestionTableDispatcher(repo, "cid", "", cfg, nil) if err == nil { t.Fatal("expected error when secret is empty") } } func TestBuildQuestionTableDispatcherEnabledCompleteConfig(t *testing.T) { repo := &questionTableExportRepoStub{} cfg := questionTableConfig{BaseID: "b1", SheetID: "sh1", OperatorID: "op1"} d, err := buildQuestionTableDispatcher(repo, "cid", "secret", cfg, nil) if err != nil { t.Fatalf("unexpected error: %v", err) } if d == nil { t.Fatal("expected non-nil dispatcher for complete config") } } // --------------------------------------------------------------------------- // Test 4: immediate run + periodic repeat + cancel stop // --------------------------------------------------------------------------- func TestRunQuestionTablePollerImmediateAndPeriodic(t *testing.T) { runner := &countingPollerRunner{} ctx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() runQuestionTablePoller(ctx, runner, 50*time.Millisecond) }() // Wait for at least 2 calls (immediate + one tick). time.Sleep(120 * time.Millisecond) cancel() wg.Wait() runner.mu.Lock() calls := runner.calls runner.mu.Unlock() if calls < 2 { t.Errorf("expected at least 2 calls, got %d", calls) } } func TestRunQuestionTablePollerCancelledContext(t *testing.T) { runner := &countingPollerRunner{} ctx, cancel := context.WithCancel(context.Background()) cancel() // already cancelled runQuestionTablePoller(ctx, runner, 50*time.Millisecond) runner.mu.Lock() calls := runner.calls runner.mu.Unlock() if calls != 0 { t.Errorf("expected 0 calls (cancelled context), got %d", calls) } } // --------------------------------------------------------------------------- // Test 5: continue after error and log/output security contract // --------------------------------------------------------------------------- func TestRunQuestionTablePollerContinuesAfterError(t *testing.T) { runner := &errorThenSuccessPoller{} ctx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() runQuestionTablePoller(ctx, runner, 30*time.Millisecond) }() time.Sleep(120 * time.Millisecond) cancel() wg.Wait() runner.mu.Lock() calls := runner.calls runner.mu.Unlock() if calls < 2 { t.Errorf("expected at least 2 calls after error, got %d", calls) } } // Test logging contract: the runOnce function in runQuestionTablePoller logs // only stable stage text for errors (never raw errors via %v) and only // Claimed/Exported/Failed integers for success. func TestPollerLoggingContract(t *testing.T) { // Behavioral log-capture test: runner returns an error containing unique // sentinel values; the captured log must contain the stable stage text // and none of those sentinels. sentinel := "s3nt1n3l-op3r4t0r-t0k3n-q" runner := &sentinelErrorPoller{errMsg: "questiontable dispatcher: " + sentinel} ctx, cancel := context.WithCancel(context.Background()) // Save and restore global log output. originalOutput := log.Writer() originalFlags := log.Flags() var buf strings.Builder log.SetOutput(&buf) log.SetFlags(0) defer func() { log.SetOutput(originalOutput) log.SetFlags(originalFlags) }() var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() runQuestionTablePoller(ctx, runner, 50*time.Millisecond) }() time.Sleep(120 * time.Millisecond) cancel() wg.Wait() output := buf.String() if !strings.Contains(output, "question table dispatch failed") { t.Errorf("log must contain stable stage text, got: %s", output) } if strings.Contains(output, sentinel) { t.Errorf("log must not contain sentinel %q, got: %s", sentinel, output) } } // sentinelErrorPoller always returns an error with the given message. type sentinelErrorPoller struct { errMsg string } func (r *sentinelErrorPoller) RunOnce(ctx context.Context) (questiontable.DispatcherStats, error) { return questiontable.DispatcherStats{}, errors.New(r.errMsg) } // --------------------------------------------------------------------------- // Test 6: nil/typed-nil runner and nonpositive interval safe // --------------------------------------------------------------------------- func TestRunQuestionTablePollerNilRunner(t *testing.T) { ctx := context.Background() // Should not panic, just return immediately. runQuestionTablePoller(ctx, nil, 50*time.Millisecond) // If we reach here without panic, test passes. } func TestRunQuestionTablePollerNonPositiveInterval(t *testing.T) { runner := &countingPollerRunner{} ctx := context.Background() runQuestionTablePoller(ctx, runner, 0) runQuestionTablePoller(ctx, runner, -1*time.Second) runner.mu.Lock() calls := runner.calls runner.mu.Unlock() if calls != 0 { t.Errorf("expected 0 calls for non-positive interval, got %d", calls) } } func TestRunQuestionTablePollerTypedNilInterface(t *testing.T) { // The runner is nil through the interface but not at the concrete type level. var typedNil *questiontable.Dispatcher = nil var runner questionTablePollerRunner = typedNil ctx := context.Background() // Should not panic, just return immediately. runQuestionTablePoller(ctx, runner, 50*time.Millisecond) } // --------------------------------------------------------------------------- // Test 7: main source wiring contract // --------------------------------------------------------------------------- func TestMainWiresQuestionTableEnvNames(t *testing.T) { mainData, err := os.ReadFile("main.go") if err != nil { t.Fatal(err) } syncData, err := os.ReadFile("question_table_sync.go") if err != nil { t.Fatal(err) } mainSource := string(mainData) syncSource := string(syncData) for _, fragment := range []string{ `"DINGTALK_QUESTION_TABLE_BASE_ID"`, `"DINGTALK_QUESTION_TABLE_SHEET_ID"`, `"DINGTALK_QUESTION_TABLE_OPERATOR_ID"`, } { if !strings.Contains(syncSource, fragment) { t.Errorf("question table config reader missing %q", fragment) } } for _, fragment := range []string{ `NewQuestionTableExportRepository`, `5*time.Second`, `"DingTalk question table dispatcher started"`, } { if !strings.Contains(mainSource, fragment) { t.Errorf("main wiring missing %q", fragment) } } shutdownAt := strings.Index(mainSource, "server.Shutdown(shutdownCtx)") waitAt := strings.Index(mainSource, "case <-questionTableDone:") if shutdownAt < 0 || waitAt < 0 || waitAt <= shutdownAt { t.Fatal("main must wait for question table poller after HTTP shutdown and before returning") } } // --------------------------------------------------------------------------- // Test doubles // --------------------------------------------------------------------------- // questionTableExportRepoStub implements questiontable.ExportRepository. type questionTableExportRepoStub struct{} func (r *questionTableExportRepoStub) Claim(ctx context.Context, limit int, maxAttempts int, staleBefore time.Time) ([]questiontable.PendingExport, error) { return nil, nil } func (r *questionTableExportRepoStub) MarkExported(ctx context.Context, exportID, location string) error { return nil } func (r *questionTableExportRepoStub) MarkFailed(ctx context.Context, exportID, failureCode string) error { return nil } // countingPollerRunner counts calls to RunOnce. type countingPollerRunner struct { mu sync.Mutex calls int } func (r *countingPollerRunner) RunOnce(ctx context.Context) (questiontable.DispatcherStats, error) { r.mu.Lock() r.calls++ r.mu.Unlock() return questiontable.DispatcherStats{}, nil } // errorThenSuccessPoller returns an error on the first call, then succeeds. type errorThenSuccessPoller struct { mu sync.Mutex calls int } func (r *errorThenSuccessPoller) RunOnce(ctx context.Context) (questiontable.DispatcherStats, error) { r.mu.Lock() r.calls++ call := r.calls r.mu.Unlock() if call == 1 { return questiontable.DispatcherStats{}, errors.New("questiontable dispatcher: claim failed") } return questiontable.DispatcherStats{Claimed: 1, Exported: 1}, nil }