internal/deps/worker_test.go

344 lines · 11864 bytes

  1package deps
  2
  3import (
  4	"context"
  5	"os"
  6	"os/exec"
  7	"path/filepath"
  8	"strings"
  9	"testing"
 10
 11	"gitbay.org/gitbay/internal/config"
 12	"gitbay.org/gitbay/internal/store"
 13)
 14
 15func testWorker(t *testing.T) (*Worker, store.Repo) {
 16	t.Helper()
 17	st, err := store.Open(filepath.Join(t.TempDir(), "gitbay.db"))
 18	if err != nil {
 19		t.Fatal(err)
 20	}
 21	t.Cleanup(func() { st.Close() })
 22	if err := st.MigrateUp(); err != nil {
 23		t.Fatal(err)
 24	}
 25	owner, err := st.CreateUser("alice", false)
 26	if err != nil {
 27		t.Fatal(err)
 28	}
 29	if err := st.AddEmail(owner, "alice@example.com", "admin", true); err != nil {
 30		t.Fatal(err)
 31	}
 32	id, err := st.CreateRepo("user", owner, "thing", "public")
 33	if err != nil {
 34		t.Fatal(err)
 35	}
 36	repo, err := st.RepoByID(id)
 37	if err != nil {
 38		t.Fatal(err)
 39	}
 40	if err := st.EnableDepCheck(repo.ID); err != nil {
 41		t.Fatal(err)
 42	}
 43	cfg := config.Default()
 44	cfg.Server.SiteURL = "https://gitbay.test"
 45	cfg.Mail.SMTPHost = "localhost:587"
 46	return &Worker{St: st, Cfg: cfg}, repo
 47}
 48
 49func reports(pairs ...string) []store.DepReport {
 50	var out []store.DepReport
 51	for i := 0; i < len(pairs); i += 3 {
 52		out = append(out, store.DepReport{
 53			Ecosystem: EcoGo, Name: pairs[i], Current: pairs[i+1], Latest: pairs[i+2]})
 54	}
 55	return out
 56}
 57
 58func TestReconcileIssueLifecycle(t *testing.T) {
 59	w, repo := testWorker(t)
 60
 61	// Nothing behind: no issue, no mail.
 62	if err := w.reconcile(repo, nil); err != nil {
 63		t.Fatal(err)
 64	}
 65	if check, _ := w.St.DepCheckFor(repo.ID); check.IssueNumber != 0 {
 66		t.Fatalf("issue %d opened with nothing behind", check.IssueNumber)
 67	}
 68
 69	// Something falls behind: one issue, one notification.
 70	if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.1.0")); err != nil {
 71		t.Fatal(err)
 72	}
 73	check, err := w.St.DepCheckFor(repo.ID)
 74	if err != nil || check.IssueNumber == 0 {
 75		t.Fatalf("no issue opened: %v", err)
 76	}
 77	issue, err := w.St.IssueByNumber(repo.ID, check.IssueNumber)
 78	if err != nil {
 79		t.Fatal(err)
 80	}
 81	if issue.Author != store.BotUsername {
 82		t.Errorf("issue author = %q, want %q", issue.Author, store.BotUsername)
 83	}
 84	if issue.Title != IssueTitle {
 85		t.Errorf("issue title = %q", issue.Title)
 86	}
 87	if !strings.Contains(issue.Body, "github.com/a/b") || !strings.Contains(issue.Body, "v1.1.0") {
 88		t.Errorf("issue body missing the dependency:\n%s", issue.Body)
 89	}
 90	mail, err := w.St.DueMail(10)
 91	if err != nil {
 92		t.Fatal(err)
 93	}
 94	if len(mail) != 1 || mail[0].Recipient != "alice@example.com" {
 95		t.Fatalf("mail = %+v, want one to the owner", mail)
 96	}
 97
 98	// Same set again: the issue is left alone and nobody is mailed twice.
 99	if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.1.0")); err != nil {
100		t.Fatal(err)
101	}
102	if mail, _ := w.St.DueMail(10); len(mail) != 1 {
103		t.Errorf("unchanged set mailed again: %d messages", len(mail))
104	}
105
106	// The set changes: same issue, rewritten body, another notification.
107	if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.2.0")); err != nil {
108		t.Fatal(err)
109	}
110	after, _ := w.St.DepCheckFor(repo.ID)
111	if after.IssueNumber != check.IssueNumber {
112		t.Errorf("second issue opened: %d then %d", check.IssueNumber, after.IssueNumber)
113	}
114	issue, _ = w.St.IssueByNumber(repo.ID, check.IssueNumber)
115	if !strings.Contains(issue.Body, "v1.2.0") {
116		t.Errorf("issue body not rewritten:\n%s", issue.Body)
117	}
118	if mail, _ := w.St.DueMail(10); len(mail) != 2 {
119		t.Errorf("changed set produced %d messages, want 2", len(mail))
120	}
121
122	// Caught up: the issue closes and the reports are forgotten.
123	if err := w.reconcile(repo, nil); err != nil {
124		t.Fatal(err)
125	}
126	issue, _ = w.St.IssueByNumber(repo.ID, check.IssueNumber)
127	if issue.State != "closed" {
128		t.Errorf("issue state = %q, want closed", issue.State)
129	}
130	if left, _ := w.St.ReportedDeps(repo.ID); len(left) != 0 {
131		t.Errorf("reports left behind: %v", left)
132	}
133	if mail, _ := w.St.DueMail(10); len(mail) != 2 {
134		t.Errorf("closing mailed: %d messages", len(mail))
135	}
136}
137
138func TestReconcileOpensFreshIssueAfterClose(t *testing.T) {
139	w, repo := testWorker(t)
140	if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.1.0")); err != nil {
141		t.Fatal(err)
142	}
143	first, _ := w.St.DepCheckFor(repo.ID)
144	issue, _ := w.St.IssueByNumber(repo.ID, first.IssueNumber)
145
146	// The maintainer closes it. The worker does not reopen it; the next
147	// change gets its own issue.
148	if err := w.St.SetIssueState(issue.ID, "closed"); err != nil {
149		t.Fatal(err)
150	}
151	if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.3.0")); err != nil {
152		t.Fatal(err)
153	}
154	second, _ := w.St.DepCheckFor(repo.ID)
155	if second.IssueNumber == first.IssueNumber {
156		t.Fatalf("reused closed issue #%d", first.IssueNumber)
157	}
158	if reopened, _ := w.St.IssueByNumber(repo.ID, first.IssueNumber); reopened.State != "closed" {
159		t.Error("the closed issue was reopened")
160	}
161}
162
163func TestBehindQueriesRegistries(t *testing.T) {
164	srv, _ := fakeRegistry(t, map[string]string{
165		"/github.com/a/b/@latest": `{"Version":"v1.1.0"}`,
166		"/github.com/c/d/@latest": `{"Version":"v2.0.0"}`,
167	})
168	w, _ := testWorker(t)
169	w.Client = NewClient("test")
170	w.Client.Hosts = map[string]string{EcoGo: srv.URL}
171
172	got, err := w.behind(context.Background(), []Dep{
173		{Ecosystem: EcoGo, Name: "github.com/a/b", Current: "v1.0.0"}, // behind
174		{Ecosystem: EcoGo, Name: "github.com/c/d", Current: "v2.0.0"}, // current
175	})
176	if err != nil {
177		t.Fatal(err)
178	}
179	if len(got) != 1 || got[0].Name != "github.com/a/b" || got[0].Latest != "v1.1.0" {
180		t.Fatalf("behind = %+v", got)
181	}
182}
183
184func TestBehindToleratesOneFailureButNotAll(t *testing.T) {
185	srv, _ := fakeRegistry(t, map[string]string{"/github.com/a/b/@latest": `{"Version":"v1.1.0"}`})
186	w, _ := testWorker(t)
187	w.Client = NewClient("test")
188	w.Client.Hosts = map[string]string{EcoGo: srv.URL}
189	found := []Dep{
190		{Ecosystem: EcoGo, Name: "github.com/a/b", Current: "v1.0.0"},
191		{Ecosystem: EcoGo, Name: "github.com/gone/away", Current: "v1.0.0"}, // 404s
192	}
193	got, err := w.behind(context.Background(), found)
194	if err != nil {
195		t.Fatalf("one failed lookup failed the sweep: %v", err)
196	}
197	if len(got) != 1 {
198		t.Fatalf("behind = %+v", got)
199	}
200	if _, err := w.behind(context.Background(), found[1:]); err == nil {
201		t.Error("every lookup failing was reported as success")
202	}
203}
204
205func TestReconcileLeavesClosedIssueClosedOnUnchangedSet(t *testing.T) {
206	w, repo := testWorker(t)
207	behind := reports("github.com/a/b", "v1.0.0", "v1.1.0")
208	if err := w.reconcile(repo, behind); err != nil {
209		t.Fatal(err)
210	}
211	check, _ := w.St.DepCheckFor(repo.ID)
212	issue, _ := w.St.IssueByNumber(repo.ID, check.IssueNumber)
213	if err := w.St.SetIssueState(issue.ID, "closed"); err != nil {
214		t.Fatal(err)
215	}
216	// Nothing has changed, so closing the issue has to stick.
217	if err := w.reconcile(repo, behind); err != nil {
218		t.Fatal(err)
219	}
220	after, _ := w.St.DepCheckFor(repo.ID)
221	if after.IssueNumber != check.IssueNumber {
222		t.Fatalf("opened issue #%d on an unchanged set", after.IssueNumber)
223	}
224	if again, _ := w.St.IssueByNumber(repo.ID, check.IssueNumber); again.State != "closed" {
225		t.Error("the closed issue came back")
226	}
227}
228
229func TestReconcileAdvisoriesKeepsItsOwnIssue(t *testing.T) {
230	w, repo := testWorker(t)
231	if err := w.reconcile(repo, reports("github.com/a/b", "v1.0.0", "v1.1.0")); err != nil {
232		t.Fatal(err)
233	}
234	matched := []store.DepAdvisory{{Ecosystem: EcoGo, Name: "github.com/a/b", Version: "v1.0.0",
235		ID: "GO-1", Summary: "bad", Fixed: "1.1.0"}}
236	if err := w.reconcileAdvisories(repo, matched); err != nil {
237		t.Fatal(err)
238	}
239	check, _ := w.St.DepCheckFor(repo.ID)
240	if check.AdvisoryIssueNumber == 0 || check.AdvisoryIssueNumber == check.IssueNumber {
241		t.Fatalf("advisory issue #%d, updates issue #%d", check.AdvisoryIssueNumber, check.IssueNumber)
242	}
243	issue, _ := w.St.IssueByNumber(repo.ID, check.AdvisoryIssueNumber)
244	if issue.Title != AdvisoryTitle || !strings.Contains(issue.Body, "GO-1") {
245		t.Errorf("advisory issue = %q\n%s", issue.Title, issue.Body)
246	}
247	mail, _ := w.St.DueMail(10)
248	if len(mail) != 2 || !strings.Contains(mail[1].Subject, AdvisoryTitle) {
249		t.Fatalf("mail = %+v", mail)
250	}
251
252	// An upstream edit to the summary is not a change worth mailing.
253	edited := []store.DepAdvisory{matched[0]}
254	edited[0].Summary = "reworded"
255	if err := w.reconcileAdvisories(repo, edited); err != nil {
256		t.Fatal(err)
257	}
258	if mail, _ := w.St.DueMail(10); len(mail) != 2 {
259		t.Errorf("summary edit mailed: %d messages", len(mail))
260	}
261
262	// Fixed: the advisories issue closes, the updates issue stays open.
263	if err := w.reconcileAdvisories(repo, nil); err != nil {
264		t.Fatal(err)
265	}
266	if closed, _ := w.St.IssueByNumber(repo.ID, check.AdvisoryIssueNumber); closed.State != "closed" {
267		t.Errorf("advisory issue state = %q", closed.State)
268	}
269	if open, _ := w.St.IssueByNumber(repo.ID, check.IssueNumber); open.State != "open" {
270		t.Errorf("updates issue state = %q", open.State)
271	}
272	if left, _ := w.St.ReportedAdvisories(repo.ID); len(left) != 0 {
273		t.Errorf("advisories left behind: %v", left)
274	}
275}
276
277// A Go advisory for packages nothing imports opens no issue, and one
278// alongside an open advisory is counted rather than listed.
279func TestReconcileAdvisoriesNotImported(t *testing.T) {
280	w, repo := testWorker(t)
281	aside := store.DepAdvisory{Ecosystem: EcoGo, Name: "golang.org/x/crypto", Version: "v0.58.0",
282		ID: "GO-2026-5932", Summary: "openpgp is unmaintained", NotImported: true}
283	if err := w.reconcileAdvisories(repo, []store.DepAdvisory{aside}); err != nil {
284		t.Fatal(err)
285	}
286	if check, _ := w.St.DepCheckFor(repo.ID); check.AdvisoryIssueNumber != 0 {
287		t.Fatalf("opened #%d for an advisory nothing imports", check.AdvisoryIssueNumber)
288	}
289	if kept, _ := w.St.ReportedAdvisories(repo.ID); len(kept) != 1 || !kept[0].NotImported {
290		t.Fatalf("stored %+v", kept)
291	}
292	open := store.DepAdvisory{Ecosystem: EcoGo, Name: "golang.org/x/net", Version: "v0.1.0", ID: "GO-2", Summary: "reset"}
293	if err := w.reconcileAdvisories(repo, []store.DepAdvisory{aside, open}); err != nil {
294		t.Fatal(err)
295	}
296	check, _ := w.St.DepCheckFor(repo.ID)
297	issue, _ := w.St.IssueByNumber(repo.ID, check.AdvisoryIssueNumber)
298	if !strings.Contains(issue.Body, "GO-2:") || strings.Contains(issue.Body, "- GO-2026-5932:") ||
299		!strings.Contains(issue.Body, "no file here imports: GO-2026-5932") {
300		t.Errorf("issue:\n%s", issue.Body)
301	}
302}
303
304// GoImports reads every Go file's imports, tests included, and leaves out
305// vendor and testdata.
306func TestGoImports(t *testing.T) {
307	dir := t.TempDir()
308	run := func(args ...string) string {
309		t.Helper()
310		cmd := exec.Command("git", args...)
311		cmd.Dir = dir
312		cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
313			"GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.test", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.test")
314		out, err := cmd.CombinedOutput()
315		if err != nil {
316			t.Fatalf("git %v: %v\n%s", args, err, out)
317		}
318		return strings.TrimSpace(string(out))
319	}
320	files := map[string]string{
321		"main.go":       "package main\n\nimport (\n\t\"fmt\"\n\tx \"golang.org/x/crypto/ssh\"\n)\n",
322		"a_test.go":     "package main\n\nimport \"golang.org/x/net/html\"\n",
323		"vendor/v/v.go": "package v\n\nimport \"golang.org/x/crypto/openpgp\"\n",
324		"testdata/t.go": "package t\n\nimport \"golang.org/x/crypto/openpgp/armor\"\n",
325		"broken.go":     "this is not go",
326	}
327	for name, body := range files {
328		os.MkdirAll(filepath.Join(dir, filepath.Dir(name)), 0o755)
329		os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644)
330	}
331	run("init", "-q", "-b", "main")
332	run("add", ".")
333	run("commit", "-q", "-m", "x")
334	got, ok := GoImports(context.Background(), dir, run("rev-parse", "HEAD"))
335	if !ok {
336		t.Fatal("not ok")
337	}
338	for p, want := range map[string]bool{"fmt": true, "golang.org/x/crypto/ssh": true, "golang.org/x/net/html": true,
339		"golang.org/x/crypto/openpgp": false, "golang.org/x/crypto/openpgp/armor": false} {
340		if got[p] != want {
341			t.Errorf("%s: %v", p, got[p])
342		}
343	}
344}