internal/ci/sched_test.go
228 lines · 8291 bytes
1package ci
2
3import (
4 "os"
5 "os/exec"
6 "path/filepath"
7 "strings"
8 "testing"
9 "time"
10
11 "gitbay.org/gitbay/internal/config"
12 "gitbay.org/gitbay/internal/store"
13)
14
15// TestSchedulerRunDue drives one scheduler pass against a real store and
16// bare repo: a due entry queues a build, sets a pending status, and
17// advances next_run; entries whose job vanished are dropped.
18func TestSchedulerRunDue(t *testing.T) {
19 st, err := store.Open(":memory:")
20 if err != nil {
21 t.Fatal(err)
22 }
23 defer st.Close()
24 if err := st.MigrateUp(); err != nil {
25 t.Fatal(err)
26 }
27 uid, err := st.CreateUser("alice", false)
28 if err != nil {
29 t.Fatal(err)
30 }
31 _ = uid
32 repoID, err := st.CreateRepo("user", uid, "app", "public")
33 if err != nil {
34 t.Fatal(err)
35 }
36
37 // A bare repo whose main holds a ci.yml with one scheduled job.
38 work := t.TempDir()
39 env := append(os.Environ(),
40 "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
41 "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.test",
42 "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.test")
43 git := func(dir string, args ...string) {
44 t.Helper()
45 cmd := exec.Command("git", args...)
46 cmd.Dir = dir
47 cmd.Env = env
48 if out, err := cmd.CombinedOutput(); err != nil {
49 t.Fatalf("git %v: %v\n%s", args, err, out)
50 }
51 }
52 src := filepath.Join(work, "src")
53 os.MkdirAll(filepath.Join(src, ".gitbay"), 0o755)
54 os.WriteFile(filepath.Join(src, ".gitbay", "ci.yml"),
55 []byte("jobs:\n nightly:\n schedule: \"0 6 * * *\"\n steps: [echo hi]\n"), 0o644)
56 git(work, "init", "-q", "-b", "main", "src")
57 git(src, "add", ".")
58 git(src, "commit", "-q", "-m", "base")
59 bare := filepath.Join(work, "bare.git")
60 git(work, "clone", "-q", "--bare", src, "bare.git")
61
62 now := time.Now()
63 past := now.Add(-time.Hour).UTC().Format("2006-01-02T15:04:05Z")
64 if err := st.SyncSchedules(repoID, []store.Schedule{
65 {RepoID: repoID, Job: "nightly", Cron: "0 6 * * *", NextRun: past},
66 {RepoID: repoID, Job: "gone", Cron: "0 7 * * *", NextRun: past},
67 }); err != nil {
68 t.Fatal(err)
69 }
70
71 s := &Scheduler{St: st, SiteURL: "https://x.test",
72 RepoDir: func(owner, name string) string { return bare }}
73 s.RunDue(now)
74
75 builds, err := st.ListBuilds(repoID, store.BuildFilter{}, 10)
76 if err != nil || len(builds) != 1 {
77 t.Fatalf("builds after run: %v %v", builds, err)
78 }
79 if builds[0].Job != "nightly" || builds[0].Status != "pending" || builds[0].Ref != "main" {
80 t.Fatalf("queued build wrong: %+v", builds[0])
81 }
82 statuses, _ := st.ListCommitStatuses(repoID, builds[0].SHA)
83 if len(statuses) != 1 || statuses[0].Context != "ci/nightly" || statuses[0].State != "pending" {
84 t.Fatalf("status wrong: %+v", statuses)
85 }
86 // next_run advanced past now; the vanished job's entry is gone.
87 due, _ := st.DueSchedules(now.UTC().Format("2006-01-02T15:04:05Z"))
88 if len(due) != 0 {
89 t.Fatalf("still due after run: %+v", due)
90 }
91 all, _ := st.DueSchedules("9999-01-01T00:00:00Z")
92 if len(all) != 1 || all[0].Job != "nightly" {
93 t.Fatalf("schedule set after run: %+v", all)
94 }
95 // Cron fires in server-local time, stored as UTC.
96 cr, _ := ParseCron("0 6 * * *")
97 if want := cr.Next(now).UTC().Format("2006-01-02T15:04:05Z"); all[0].NextRun != want {
98 t.Fatalf("next_run = %s, want %s", all[0].NextRun, want)
99 }
100
101 // A second pass fires nothing: next_run is in the future.
102 s.RunDue(now)
103 if builds, _ = st.ListBuilds(repoID, store.BuildFilter{}, 10); len(builds) != 1 {
104 t.Fatalf("second pass queued extra builds: %+v", builds)
105 }
106
107 // Due again while the first build is still pending: nothing is
108 // queued, so a repository no runner serves holds one row per
109 // scheduled job, not one per tick (#206). Once that build finishes,
110 // the next tick queues again — a schedule re-runs an unchanged
111 // commit on purpose.
112 if err := st.SetScheduleNext(repoID, "nightly", past); err != nil {
113 t.Fatal(err)
114 }
115 s.RunDue(now)
116 if builds, _ = st.ListBuilds(repoID, store.BuildFilter{}, 10); len(builds) != 1 {
117 t.Fatalf("tick with the last build pending queued another: %+v", builds)
118 }
119 b, ok, err := st.ClaimBuild(nil, false)
120 if err != nil || !ok {
121 t.Fatalf("claim: %v ok=%v", err, ok)
122 }
123 if err := st.SetScheduleNext(repoID, "nightly", past); err != nil {
124 t.Fatal(err)
125 }
126 s.RunDue(now)
127 if builds, _ = st.ListBuilds(repoID, store.BuildFilter{}, 10); len(builds) != 1 {
128 t.Fatalf("tick with the last build running queued another: %+v", builds)
129 }
130 if err := st.FinishBuild(b.ID, "success"); err != nil {
131 t.Fatal(err)
132 }
133 if err := st.SetScheduleNext(repoID, "nightly", past); err != nil {
134 t.Fatal(err)
135 }
136 s.RunDue(now)
137 if builds, _ = st.ListBuilds(repoID, store.BuildFilter{}, 10); len(builds) != 2 {
138 t.Fatalf("tick after the last build finished did not queue: %+v", builds)
139 }
140}
141
142// The code scan has its own schedule: a due repository gets one build of
143// the instance's job, with no commit status, and none while one is pending
144// or while the instance has no image.
145func TestSchedulerQueuesSecurityScan(t *testing.T) {
146 st, err := store.Open(":memory:")
147 if err != nil {
148 t.Fatal(err)
149 }
150 defer st.Close()
151 if err := st.MigrateUp(); err != nil {
152 t.Fatal(err)
153 }
154 uid, _ := st.CreateUser("alice", false)
155 repoID, _ := st.CreateRepo("user", uid, "app", "public")
156 work := t.TempDir()
157 bare := filepath.Join(work, "bare.git")
158 for _, args := range [][]string{
159 {"init", "-q", "-b", "main", "src"},
160 {"-C", "src", "-c", "user.name=t", "-c", "user.email=t@example.test", "commit", "-q", "--allow-empty", "-m", "base"},
161 {"clone", "-q", "--bare", "src", "bare.git"},
162 } {
163 cmd := exec.Command("git", args...)
164 cmd.Dir = work
165 cmd.Env = append(os.Environ(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null")
166 if out, err := cmd.CombinedOutput(); err != nil {
167 t.Fatalf("git %v: %v\n%s", args, err, out)
168 }
169 }
170 now := time.Now()
171 if err := st.EnableSecurityScan(repoID, now.Add(-time.Minute).UTC().Format("2006-01-02T15:04:05Z")); err != nil {
172 t.Fatal(err)
173 }
174 s := &Scheduler{St: st, SiteURL: "https://x.test", RepoDir: func(owner, name string) string { return bare }}
175 s.RunDue(now)
176 if builds, _ := st.ListBuilds(repoID, store.BuildFilter{}, 10); len(builds) != 0 {
177 t.Fatalf("queued with no image: %+v", builds)
178 }
179
180 s.Security = config.Security{Image: "localhost/gitbay-security:1", Hour: 4, MostOften: "daily", LeastOften: "monthly", Default: "daily", Steps: []string{"true"}}
181 st.SetSecurityNext(repoID, now.Add(-time.Minute).UTC().Format("2006-01-02T15:04:05Z"))
182 s.RunDue(now)
183 builds, _ := st.ListBuilds(repoID, store.BuildFilter{}, 10)
184 if len(builds) != 1 || builds[0].Job != SecurityJob || builds[0].Image != "localhost/gitbay-security:1" {
185 t.Fatalf("builds = %+v", builds)
186 }
187 if statuses, _ := st.CommitStatusesFor(repoID, []string{builds[0].SHA}); len(statuses[builds[0].SHA]) != 0 {
188 t.Errorf("a status was set: %+v", statuses)
189 }
190 if sc, _ := st.SecurityScanFor(repoID); sc.NextRun <= now.UTC().Format("2006-01-02T15:04:05Z") {
191 t.Errorf("next run not advanced: %q", sc.NextRun)
192 }
193
194 // Due again while the first is pending: nothing more.
195 st.SetSecurityNext(repoID, now.Add(-time.Minute).UTC().Format("2006-01-02T15:04:05Z"))
196 s.RunDue(now)
197 if builds, _ := st.ListBuilds(repoID, store.BuildFilter{}, 10); len(builds) != 1 {
198 t.Errorf("queued over a pending scan: %d builds", len(builds))
199 }
200}
201
202func TestSecurityJobNameIsReserved(t *testing.T) {
203 if _, err := Parse([]byte("jobs:\n gitbay-security:\n steps: [echo]\n")); err == nil || !strings.Contains(err.Error(), "reserved") {
204 t.Fatalf("Parse = %v", err)
205 }
206}
207
208func TestSecurityNextRun(t *testing.T) {
209 sec := config.Default().Security
210 sec.Hour = 6
211 // Wednesday 2026-11-04 10:00 UTC.
212 after := time.Date(2026, 11, 4, 10, 0, 0, 0, time.UTC).In(time.FixedZone("UTC-6", -6*3600))
213 for chosen, want := range map[string]string{
214 "": "2026-11-05T06:00:00Z",
215 "daily": "2026-11-05T06:00:00Z",
216 "weekly": "2026-11-08T06:00:00Z",
217 "monthly": "2026-12-01T06:00:00Z",
218 } {
219 if got := SecurityNextRun(sec, chosen, after); got != want {
220 t.Errorf("%q: %s, want %s", chosen, got, want)
221 }
222 }
223 // A choice the instance no longer allows scans at the nearest allowed.
224 sec.LeastOften, sec.Default = "weekly", "weekly"
225 if got := SecurityNextRun(sec, "monthly", after); got != "2026-11-08T06:00:00Z" {
226 t.Errorf("monthly outside the range: %s", got)
227 }
228}