package dispatch import ( "context" "io" "log/slog" "sync" "testing" "time" "git.unkin.net/unkin/teabot/internal/config" "git.unkin.net/unkin/teabot/internal/docker" "git.unkin.net/unkin/teabot/internal/gitea" "git.unkin.net/unkin/teabot/internal/state" ) // fakeClient is a scripted GiteaClient. Each field is returned as-is; the // Get* methods serve follow-up context lookups. type fakeClient struct { issues []gitea.Issue pulls []gitea.PullRequest comments []gitea.Comment issueByI map[int64]gitea.Issue pullByI map[int64]gitea.PullRequest } func (f *fakeClient) ListIssues(_ context.Context, _ string, _ time.Time) ([]gitea.Issue, error) { return f.issues, nil } func (f *fakeClient) ListPulls(_ context.Context, _ string) ([]gitea.PullRequest, error) { return f.pulls, nil } func (f *fakeClient) ListComments(_ context.Context, _ string, _ time.Time) ([]gitea.Comment, error) { return f.comments, nil } func (f *fakeClient) GetIssueComments(_ context.Context, _ string, _ int64) ([]gitea.Comment, error) { return nil, nil } func (f *fakeClient) GetIssue(_ context.Context, _ string, index int64) (gitea.Issue, error) { return f.issueByI[index], nil } func (f *fakeClient) GetPull(_ context.Context, _ string, index int64) (gitea.PullRequest, error) { return f.pullByI[index], nil } func (f *fakeClient) GetPullDiff(_ context.Context, _ string, _ int64) (string, error) { return "diff", nil } // recordingRunner captures dispatched jobs; safe for concurrent use. type recordingRunner struct { mu sync.Mutex jobs []docker.Job } func (r *recordingRunner) Run(_ context.Context, j docker.Job) (docker.Result, error) { r.mu.Lock() r.jobs = append(r.jobs, j) r.mu.Unlock() return docker.Result{ExitCode: 0}, nil } func (r *recordingRunner) labels() []string { r.mu.Lock() defer r.mu.Unlock() out := make([]string, len(r.jobs)) for i, j := range r.jobs { out[i] = j.Label } return out } func testConfig() *config.Config { return &config.Config{ GiteaURL: "https://git.unkin.net", Repos: []string{"unkin/teabot"}, PollInterval: time.Second, MaxConcurrent: 2, JobTimeout: time.Minute, JobImage: "img:latest", ContainerHome: "/home/agent", Personalities: []config.Personality{ {Name: "impl", Role: config.RoleImplementer, Login: "implbot", Token: "it", TeaConfig: "/x/impl.yml"}, {Name: "rev", Role: config.RoleReviewer, Login: "revbot", Token: "rt", TeaConfig: "/x/rev.yml"}, }, } } func discardLogger() *slog.Logger { return slog.New(slog.NewTextHandler(io.Discard, nil)) } func newHarness(t *testing.T, fc *fakeClient) (*Dispatcher, *recordingRunner, *state.Store) { t.Helper() store, err := state.New(t.TempDir()) if err != nil { t.Fatal(err) } rr := &recordingRunner{} d := New(testConfig(), store, fc, rr, discardLogger()) return d, rr, store } func contains(list []string, s string) bool { for _, v := range list { if v == s { return true } } return false } func TestFirstPollSeedsWithoutDispatch(t *testing.T) { fc := &fakeClient{ issues: []gitea.Issue{{Index: 1, Title: "old", Poster: gitea.User{Login: "human"}}}, pulls: []gitea.PullRequest{{Index: 2, Title: "oldpr", Poster: gitea.User{Login: "human"}}}, comments: []gitea.Comment{{ID: 3, Poster: gitea.User{Login: "human"}}}, } d, rr, store := newHarness(t, fc) if err := d.PollOnce(context.Background(), true); err != nil { t.Fatal(err) } if got := rr.labels(); len(got) != 0 { t.Errorf("seeding poll dispatched jobs: %v", got) } if !store.Seeded("unkin/teabot") { t.Error("repo not marked seeded") } if !store.IssueProcessed("unkin/teabot", 1) || !store.PullProcessed("unkin/teabot", 2) { t.Error("existing items not recorded during seeding") } } func TestNewIssueDispatchesImplementer(t *testing.T) { fc := &fakeClient{} d, rr, store := newHarness(t, fc) // Seed with empty state. if err := d.PollOnce(context.Background(), true); err != nil { t.Fatal(err) } // Now a genuinely new human issue appears. fc.issues = []gitea.Issue{{Index: 10, Title: "please fix", Poster: gitea.User{Login: "human"}}} if err := d.PollOnce(context.Background(), true); err != nil { t.Fatal(err) } if !contains(rr.labels(), "unkin/teabot#issue-10") { t.Errorf("expected implementer job for issue 10, got %v", rr.labels()) } // The dispatched job must carry the implementer identity. if rr.jobs[0].GitUser != "implbot" { t.Errorf("job dispatched as %q, want implbot", rr.jobs[0].GitUser) } if !store.ActedOnIssue("unkin/teabot", 10) { t.Error("issue 10 should be marked acted-on") } // Polling again must NOT re-dispatch (dedup). before := len(rr.labels()) if err := d.PollOnce(context.Background(), true); err != nil { t.Fatal(err) } if len(rr.labels()) != before { t.Errorf("issue re-dispatched: %v", rr.labels()) } } func TestBotAuthoredIssueIgnored(t *testing.T) { fc := &fakeClient{} d, rr, _ := newHarness(t, fc) _ = d.PollOnce(context.Background(), true) // seed fc.issues = []gitea.Issue{{Index: 20, Poster: gitea.User{Login: "implbot"}}} _ = d.PollOnce(context.Background(), true) if len(rr.labels()) != 0 { t.Errorf("bot-authored issue triggered a job: %v", rr.labels()) } } func TestNewPullDispatchesReviewer(t *testing.T) { fc := &fakeClient{} d, rr, store := newHarness(t, fc) _ = d.PollOnce(context.Background(), true) // seed fc.pulls = []gitea.PullRequest{{Index: 30, Title: "add x", Poster: gitea.User{Login: "human"}}} _ = d.PollOnce(context.Background(), true) if !contains(rr.labels(), "unkin/teabot#pull-30") { t.Errorf("expected reviewer job for pull 30, got %v", rr.labels()) } if rr.jobs[0].GitUser != "revbot" { t.Errorf("PR job dispatched as %q, want revbot", rr.jobs[0].GitUser) } if !store.ActedOnPull("unkin/teabot", 30) { t.Error("pull 30 should be acted-on") } } func TestCommentFollowUpOnlyOnActedThreads(t *testing.T) { fc := &fakeClient{ issueByI: map[int64]gitea.Issue{40: {Index: 40, Title: "acted issue"}}, pullByI: map[int64]gitea.PullRequest{50: {Index: 50, Title: "acted pr"}}, } d, rr, store := newHarness(t, fc) _ = d.PollOnce(context.Background(), true) // seed // teabot has acted on issue 40 and pull 50. store.MarkIssue("unkin/teabot", 40) store.MarkPull("unkin/teabot", 50) issueURL := "https://git.unkin.net/api/v1/repos/unkin/teabot/issues/40" prURL := "https://git.unkin.net/api/v1/repos/unkin/teabot/pulls/50" unactedURL := "https://git.unkin.net/api/v1/repos/unkin/teabot/issues/999" fc.comments = []gitea.Comment{ {ID: 100, Poster: gitea.User{Login: "human"}, Body: "on acted issue", IssueURL: issueURL}, {ID: 101, Poster: gitea.User{Login: "human"}, Body: "on acted pr", PRURL: prURL}, {ID: 102, Poster: gitea.User{Login: "human"}, Body: "on unacted thread", IssueURL: unactedURL}, {ID: 103, Poster: gitea.User{Login: "implbot"}, Body: "bot comment on acted issue", IssueURL: issueURL}, } _ = d.PollOnce(context.Background(), true) labels := rr.labels() if !contains(labels, "unkin/teabot#issue-40-followup-100") { t.Errorf("missing issue follow-up: %v", labels) } if !contains(labels, "unkin/teabot#pull-50-followup-101") { t.Errorf("missing pull follow-up: %v", labels) } // Comment on an unacted thread must NOT dispatch. for _, l := range labels { if l == "unkin/teabot#issue-999-followup-102" { t.Error("dispatched follow-up for unacted thread") } } // Bot-authored comment (103) must NOT dispatch (loop prevention). if len(labels) != 2 { t.Errorf("expected exactly 2 follow-ups (issue+pull), got %v", labels) } if !store.CommentProcessed("unkin/teabot", 103) { t.Error("bot comment should still be recorded as processed") } } func TestFollowUpPersonalityRouting(t *testing.T) { fc := &fakeClient{ pullByI: map[int64]gitea.PullRequest{60: {Index: 60, Title: "pr"}}, } d, rr, store := newHarness(t, fc) _ = d.PollOnce(context.Background(), true) store.MarkPull("unkin/teabot", 60) fc.comments = []gitea.Comment{ {ID: 200, Poster: gitea.User{Login: "human"}, Body: "change please", PRURL: "https://git.unkin.net/api/v1/repos/unkin/teabot/pulls/60"}, } _ = d.PollOnce(context.Background(), true) if len(rr.jobs) != 1 { t.Fatalf("expected 1 job, got %d", len(rr.jobs)) } // A PR follow-up must be handled by the reviewer personality. if rr.jobs[0].GitUser != "revbot" { t.Errorf("PR follow-up dispatched as %q, want revbot", rr.jobs[0].GitUser) } }