gunk-dev/the-valley

selfupdate_test.go

sourcec66fe008501cmain's published tip history
17.2 KiB
1package selfupdate
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "maps"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14)
15
16// acceptedRepos covers every form Validate accepts.
17var acceptedRepos = []string{
18 "https://github.com/example/the-valley",
19 "https://github.com/example/the-valley.git",
20 "ssh://git@github.com/example/the-valley",
21 "ssh://git@[::1]:2222/srv/the-valley.git",
22 "git://example.com/the-valley.git",
23 "file:///srv/git/the-valley.git",
24 "/srv/git/the-valley.git",
25 "git@valley-host:the-valley",
26 "me@host.example:~/the-valley.git",
27 "me@host.example:/srv/git/the-valley.git",
28 "https://example.com/a-b_c.d~e/f:g@h",
29}
30
31func TestValidateRepo(t *testing.T) {
32 for _, repo := range acceptedRepos {
33 if err := Validate(repo, "main"); err != nil {
34 t.Errorf("Validate(%q) refused: %v", repo, err)
35 }
36 }
37 for _, repo := range []string{
38 "",
39 "ext::sh -c touch% /tmp/pwned",
40 "ext::sh",
41 "fd::17",
42 "foo::bar",
43 "me@host::path",
44 "-uhttps://example.com/the-valley",
45 "--upload-pack=touch /tmp/pwned",
46 "/srv/git/the-valley.git?rev=0000000",
47 "/srv/git/the-valley.git#packages.x86_64-linux.evil",
48 "https://example.com/the-valley?ref=evil",
49 "/srv/git/my valley.git",
50 "/srv/git/valley%20repo.git",
51 "https://example.com/repo+name",
52 "https://example.com/repo;x",
53 "/srv/git/[valley].git",
54 "/srv/git/the-valley.git\n",
55 "http://example.com/the-valley",
56 "ftp://example.com/the-valley",
57 "file://relative/the-valley",
58 "ssh://-oProxyCommand=touch/the-valley",
59 "relative/the-valley",
60 "host:the-valley",
61 } {
62 err := Validate(repo, "main")
63 if err == nil {
64 t.Errorf("Validate(%q) accepted it", repo)
65 continue
66 }
67 if !strings.Contains(err.Error(), "valley.selfUpdate.repo") {
68 t.Errorf("Validate(%q) = %v; want the error to name valley.selfUpdate.repo", repo, err)
69 }
70 }
71 for _, branch := range []string{"", "-main", "a..b", "main branch", "main;x"} {
72 if err := Validate("/srv/git/the-valley.git", branch); err == nil || !strings.Contains(err.Error(), "valley.selfUpdate.branch") {
73 t.Errorf("Validate(branch %q) = %v; want a refusal naming valley.selfUpdate.branch", branch, err)
74 }
75 }
76}
77
78// TestRepoURL: ls-remote and nix read a repo by the same URL, the one the
79// flake ref carries, and user@host:path names what git itself would.
80func TestRepoURL(t *testing.T) {
81 sha := strings.Repeat("a", 40)
82 for repo, want := range map[string]string{
83 "/srv/git/the-valley.git": "file:///srv/git/the-valley.git",
84 "file:///srv/git/the-valley.git": "file:///srv/git/the-valley.git",
85 "https://github.com/example/the-valley": "https://github.com/example/the-valley",
86 "git@valley-host:the-valley": "ssh://git@valley-host/~/the-valley",
87 "me@host.example:/srv/git/the-valley.git": "ssh://me@host.example/srv/git/the-valley.git",
88 "me@host.example:~/the-valley.git": "ssh://me@host.example/~/the-valley.git",
89 "me@host.example:~you/the-valley.git": "ssh://me@host.example/~you/the-valley.git",
90 } {
91 if got := RepoURL(repo); got != want {
92 t.Errorf("RepoURL(%q) = %q, want %q", repo, got, want)
93 }
94 ref := "git+" + want + "?ref=refs/heads/main&rev=" + sha + "#packages.x86_64-linux.valley"
95 if got := FlakeRef(repo, "main", sha, "x86_64-linux"); got != ref {
96 t.Errorf("FlakeRef(%q) = %q, want %q", repo, got, ref)
97 }
98 }
99}
100
101// TestFlakeRefSurvivesNix: the installed nix parses each accepted repo's
102// flake ref and prints it back unchanged, so nix fetches the URL ls-remote
103// read. A nix build has no nix, so this runs only outside one.
104func TestFlakeRefSurvivesNix(t *testing.T) {
105 if _, err := exec.LookPath("nix"); err != nil {
106 t.Skip("nix not installed")
107 }
108 sha := strings.Repeat("a", 40)
109 for _, repo := range acceptedRepos {
110 ref, _, _ := strings.Cut(FlakeRef(repo, "main", sha, "x86_64-linux"), "#")
111 out, err := exec.Command("nix", "--extra-experimental-features", "nix-command flakes", "eval", "--raw", "--expr",
112 `builtins.flakeRefToString (builtins.parseFlakeRef "`+ref+`")`).CombinedOutput()
113 if err != nil {
114 t.Fatalf("nix eval of %q: %v\n%s", ref, err, out)
115 }
116 // nix prints git+git:// by its alias git://, the same URL.
117 if got := strings.Replace(ref, "git+git://", "git://", 1); string(out) != got {
118 t.Errorf("repo %q: nix turned %q into %q", repo, got, out)
119 }
120 }
121}
122
123// upstream is a bare repository standing for the-valley's, and a clone
124// that pushes commits to its main.
125type upstream struct {
126 t *testing.T
127 bare string
128 work string
129}
130
131func newUpstream(t *testing.T) *upstream {
132 dir := t.TempDir()
133 u := &upstream{t: t, bare: filepath.Join(dir, "the-valley.git"), work: filepath.Join(dir, "work")}
134 u.git(dir, "init", "--quiet", "--bare", u.bare)
135 u.git(dir, "init", "--quiet", u.work)
136 return u
137}
138
139// git runs git with no configuration but an identity of its own.
140func (u *upstream) git(dir string, args ...string) string {
141 u.t.Helper()
142 cmd := exec.Command("git", args...)
143 cmd.Dir = dir
144 cmd.Env = append(os.Environ(),
145 "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
146 "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@localhost",
147 "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@localhost")
148 out, err := cmd.CombinedOutput()
149 if err != nil {
150 u.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
151 }
152 return strings.TrimSpace(string(out))
153}
154
155// push commits to main and pushes it, returning the commit.
156func (u *upstream) push(msg string) string {
157 u.git(u.work, "commit", "--quiet", "--allow-empty", "-m", msg)
158 u.git(u.work, "push", "--quiet", u.bare, "HEAD:refs/heads/main")
159 return u.git(u.work, "rev-parse", "HEAD")
160}
161
162// fakeNix builds a valley for any commit as a small script under store, and
163// keeps the profile as a map. A commit in broken builds a valley that fails
164// one step of the smoke test, or fails to build at all.
165type fakeNix struct {
166 store string
167 profile map[string][]string
168 broken map[string]string // commit → "build", "version", "help" or "checks"
169 builds []string // the commits built, in order
170}
171
172func newFakeNix(t *testing.T) *fakeNix {
173 return &fakeNix{store: t.TempDir(), profile: map[string][]string{}, broken: map[string]string{}}
174}
175
176func (f *fakeNix) Build(_ context.Context, ref string) (string, error) {
177 _, rest, _ := strings.Cut(ref, "&rev=")
178 sha, _, _ := strings.Cut(rest, "#")
179 f.builds = append(f.builds, sha)
180 if f.broken[sha] == "build" {
181 return "", errors.New("nix build: exit status 1: error: builder failed")
182 }
183 version, help, checks := "0.1.0-"+sha[:7], "exit 0", `printf 'smoke-floor\nsmoke-project\n'`
184 switch f.broken[sha] {
185 case "version":
186 version = "0.1.0-0000000"
187 case "help":
188 help = "echo 'valley: broken' >&2; exit 1"
189 case "checks":
190 checks = "echo smoke-floor"
191 }
192 out := filepath.Join(f.store, fmt.Sprintf("%d-valley-%s", len(f.builds), version))
193 // A VALLEY_ variable from the running valley would stand in for the
194 // build's own, so the smoke test must not pass one on.
195 script := fmt.Sprintf(`#!/bin/sh
196if env | grep -q '^VALLEY_'; then echo "valley: inherited $(env | grep '^VALLEY_')" >&2; exit 1; fi
197case "$1" in
198--version) echo "valley %s" ;;
199help) %s ;;
200checks) [ -d "$4" ] && [ -d "$6" ] || exit 1; %s ;;
201*) exit 2 ;;
202esac
203`, version, help, checks)
204 if err := os.MkdirAll(filepath.Join(out, "bin"), 0o755); err != nil {
205 return "", err
206 }
207 if err := os.MkdirAll(filepath.Join(out, SmokePolicy, "instance"), 0o755); err != nil {
208 return "", err
209 }
210 if err := os.MkdirAll(filepath.Join(out, SmokePolicy, "project"), 0o755); err != nil {
211 return "", err
212 }
213 return out, os.WriteFile(filepath.Join(out, "bin", "valley"), []byte(script), 0o755)
214}
215
216func (f *fakeNix) Elements(context.Context) (map[string][]string, error) {
217 return maps.Clone(f.profile), nil
218}
219
220func (f *fakeNix) Remove(_ context.Context, name string) error {
221 delete(f.profile, name)
222 return nil
223}
224
225func (f *fakeNix) Add(_ context.Context, storePath string) error {
226 if _, ok := f.profile[Element]; ok {
227 return errors.New("nix profile add: a valley is installed already")
228 }
229 f.profile[Element] = []string{storePath}
230 return nil
231}
232
233// installed is the store path the profile's valley element holds.
234func (f *fakeNix) installed() string {
235 if p := f.profile[Element]; len(p) > 0 {
236 return p[0]
237 }
238 return ""
239}
240
241// fixture is an updater over a fresh upstream, fake nix and state
242// directory, with output collected in out.
243type fixture struct {
244 t *testing.T
245 up *upstream
246 nix *fakeNix
247 u *Updater
248 out *bytes.Buffer
249}
250
251func newFixture(t *testing.T) *fixture {
252 up, nix, out := newUpstream(t), newFakeNix(t), &bytes.Buffer{}
253 return &fixture{t: t, up: up, nix: nix, out: out, u: &Updater{
254 Repo: up.bare, Branch: "main", Dir: t.TempDir(), Out: out, Nix: nix, System: "x86_64-linux",
255 }}
256}
257
258// update runs Update and returns its error and what it printed.
259func (f *fixture) update(retry bool) (string, error) {
260 f.out.Reset()
261 err := f.u.Update(context.Background(), retry)
262 return f.out.String(), err
263}
264
265func (f *fixture) mustUpdate(retry bool) string {
266 f.t.Helper()
267 out, err := f.update(retry)
268 if err != nil {
269 f.t.Fatalf("Update: %v\n%s", err, out)
270 }
271 return out
272}
273
274func (f *fixture) state() State {
275 f.t.Helper()
276 st, err := Load(f.u.Dir)
277 if err != nil {
278 f.t.Fatal(err)
279 }
280 return st
281}
282
283// handInstalled puts a valley in the profile the way a person would, with
284// the version stamp in its store path's name.
285func (f *fixture) handInstalled(version string) string {
286 f.t.Helper()
287 path := filepath.Join(f.nix.store, "hand-valley-"+version)
288 if err := os.MkdirAll(path, 0o755); err != nil {
289 f.t.Fatal(err)
290 }
291 f.nix.profile[Element] = []string{path}
292 return path
293}
294
295func TestUpdateInstallsNewCommit(t *testing.T) {
296 // The running valley's wrapper sets these; the smoke test must not
297 // hand them to the build.
298 t.Setenv("VALLEY_VERIFICATION_SCHEMA", "/nix/store/old-schema.cue")
299 t.Setenv("VALLEY_VERSION", "0.1.0-1111111")
300 f := newFixture(t)
301 f.u.Version = "0.1.0-1111111"
302 hand := f.handInstalled("0.1.0-1111111")
303 f.nix.profile["other"] = []string{"/nix/store/other"}
304 c1 := f.up.push("one")
305
306 out := f.mustUpdate(false)
307 for _, want := range []string{"main is at " + c1[:7] + " (installed: valley 0.1.0-1111111)", "smoke test passed: valley 0.1.0-" + c1[:7], "installed " + c1[:7]} {
308 if !strings.Contains(out, want) {
309 t.Errorf("output lacks %q:\n%s", want, out)
310 }
311 }
312 st := f.state()
313 if st.Current == nil || st.Current.Commit != c1 || st.Current.StorePath != f.nix.installed() {
314 t.Errorf("current = %+v; want %s at %s", st.Current, c1, f.nix.installed())
315 }
316 if st.Previous == nil || st.Previous.StorePath != hand || st.Previous.Commit != "1111111" {
317 t.Errorf("previous = %+v; want the hand-installed %s", st.Previous, hand)
318 }
319 if got := f.nix.profile["other"]; len(got) != 1 {
320 t.Errorf("the other element was touched: %v", got)
321 }
322}
323
324func TestUpdateUpToDate(t *testing.T) {
325 f := newFixture(t)
326 c1 := f.up.push("one")
327 f.mustUpdate(false)
328
329 if out := f.mustUpdate(false); out != "" {
330 t.Errorf("an up-to-date run printed:\n%s", out)
331 }
332 f.u.Verbose = true
333 if out := f.mustUpdate(false); !strings.Contains(out, "main is at "+c1[:7]+": valley is up to date") {
334 t.Errorf("-v printed:\n%s", out)
335 }
336 if len(f.nix.builds) != 1 {
337 t.Errorf("built %d times; want once", len(f.nix.builds))
338 }
339
340 // Before self-update has installed anything, the running valley's
341 // version stamp says what is installed.
342 g := newFixture(t)
343 c := g.up.push("one")
344 g.u.Version = "0.1.0-" + c[:7]
345 if out := g.mustUpdate(false); out != "" || len(g.nix.builds) != 0 {
346 t.Errorf("the running valley is %s, and Update built %v and printed:\n%s", c[:7], g.nix.builds, out)
347 }
348 // A dirty build's stamp names no commit, so it is never up to date.
349 g.u.Version = "0.1.0-" + c[:7] + "-dirty"
350 g.mustUpdate(false)
351 if len(g.nix.builds) != 1 {
352 t.Errorf("the running valley is dirty, and Update built %v", g.nix.builds)
353 }
354}
355
356func TestFailedSmokeTestSkipped(t *testing.T) {
357 for _, kind := range []string{"build", "version", "help", "checks"} {
358 t.Run(kind, func(t *testing.T) {
359 f := newFixture(t)
360 f.up.push("one")
361 f.mustUpdate(false)
362 good := f.nix.installed()
363
364 c2 := f.up.push("two")
365 f.nix.broken[c2] = kind
366 out, err := f.update(false)
367 if err == nil {
368 t.Fatalf("a %s failure installed:\n%s", kind, out)
369 }
370 if !strings.Contains(out, c2[:7]+" failed; nothing installed") {
371 t.Errorf("output:\n%s", out)
372 }
373 if kind != "build" && !strings.Contains(err.Error(), "smoke test") {
374 t.Errorf("error = %v; want a smoke test failure", err)
375 }
376 if f.nix.installed() != good {
377 t.Errorf("the profile holds %s; want %s still", f.nix.installed(), good)
378 }
379 st := f.state()
380 if st.Failed == nil || st.Failed.Commit != c2 || st.Failed.Error == "" {
381 t.Errorf("failed = %+v; want %s recorded", st.Failed, c2)
382 }
383
384 out, err = f.update(false)
385 if err != nil || !strings.Contains(out, "skipping "+c2[:7]) {
386 t.Errorf("the second run: %v\n%s", err, out)
387 }
388 if len(f.nix.builds) != 2 {
389 t.Errorf("builds = %v; want the failed commit built once", f.nix.builds)
390 }
391 })
392 }
393}
394
395func TestRetry(t *testing.T) {
396 f := newFixture(t)
397 c1 := f.up.push("one")
398 f.nix.broken[c1] = "help"
399 if _, err := f.update(false); err == nil {
400 t.Fatal("a broken build installed")
401 }
402
403 // --retry builds a failed commit again, and it can fail again.
404 if _, err := f.update(true); err == nil {
405 t.Fatal("a broken build installed on retry")
406 }
407 delete(f.nix.broken, c1)
408 f.mustUpdate(true)
409 st := f.state()
410 if st.Current == nil || st.Current.Commit != c1 || st.Failed != nil {
411 t.Errorf("after a retry that passed: current %+v, failed %+v", st.Current, st.Failed)
412 }
413
414 // A failed commit is tried again, without --retry, once the branch
415 // moves past it.
416 c2 := f.up.push("two")
417 f.nix.broken[c2] = "help"
418 f.update(false)
419 c3 := f.up.push("three")
420 f.mustUpdate(false)
421 if got := f.nix.builds; len(got) != 5 || got[4] != c3 {
422 t.Errorf("builds = %v; want %s built last", got, c3)
423 }
424}
425
426func TestRollback(t *testing.T) {
427 f := newFixture(t)
428 if err := f.u.Rollback(context.Background()); err == nil || !strings.Contains(err.Error(), "nothing to roll back to") {
429 t.Errorf("Rollback with nothing installed = %v", err)
430 }
431 c1 := f.up.push("one")
432 f.mustUpdate(false)
433 first := f.nix.installed()
434 c2 := f.up.push("two")
435 f.mustUpdate(false)
436 second := f.nix.installed()
437
438 f.out.Reset()
439 if err := f.u.Rollback(context.Background()); err != nil {
440 t.Fatal(err)
441 }
442 st := f.state()
443 if f.nix.installed() != first || st.Current.Commit != c1 || st.Previous.Commit != c2 {
444 t.Errorf("after a rollback: profile %s, current %+v, previous %+v", f.nix.installed(), st.Current, st.Previous)
445 }
446 if !strings.Contains(f.out.String(), "rolled back to "+c1[:7]) || !strings.Contains(f.out.String(), "not pinned") {
447 t.Errorf("output:\n%s", f.out)
448 }
449
450 // A second rollback returns to where the first started.
451 if err := f.u.Rollback(context.Background()); err != nil {
452 t.Fatal(err)
453 }
454 if st := f.state(); f.nix.installed() != second || st.Current.Commit != c2 || st.Previous.Commit != c1 {
455 t.Errorf("after a second rollback: profile %s, current %+v, previous %+v", f.nix.installed(), st.Current, st.Previous)
456 }
457}
458
459func TestPin(t *testing.T) {
460 f := newFixture(t)
461 c1 := f.up.push("one")
462 f.mustUpdate(false)
463 if err := f.u.Pin(true); err != nil {
464 t.Fatal(err)
465 }
466 f.up.push("two")
467 out := f.mustUpdate(false)
468 if !strings.Contains(out, "pinned at "+c1[:7]) || len(f.nix.builds) != 1 {
469 t.Errorf("a pinned run built %v and printed:\n%s", f.nix.builds, out)
470 }
471
472 if err := f.u.Pin(false); err != nil {
473 t.Fatal(err)
474 }
475 f.mustUpdate(false)
476 if len(f.nix.builds) != 2 || f.state().Pinned {
477 t.Errorf("an unpinned run built %v; state %+v", f.nix.builds, f.state())
478 }
479}
480
481func TestReinstallsHandRemoved(t *testing.T) {
482 f := newFixture(t)
483 hand := f.handInstalled("0.1.0-1111111")
484 c1 := f.up.push("one")
485 f.mustUpdate(false)
486 installed := f.nix.installed()
487
488 delete(f.nix.profile, Element)
489 out := f.mustUpdate(false)
490 if !strings.Contains(out, "no longer "+c1[:7]+"; reinstalling it") {
491 t.Errorf("output:\n%s", out)
492 }
493 st := f.state()
494 if f.nix.installed() == "" || st.Current.Commit != c1 {
495 t.Errorf("after the reinstall: profile %q, current %+v", f.nix.installed(), st.Current)
496 }
497 // The rollback target is still the valley the first install replaced.
498 if st.Previous == nil || st.Previous.StorePath != hand {
499 t.Errorf("previous = %+v; want %s, not %s", st.Previous, hand, installed)
500 }
501}
502
503func TestVersionCommit(t *testing.T) {
504 for v, want := range map[string]string{
505 "0.1.0-e949dba": "e949dba",
506 "abcdefghijklmnopq-valley-0.1.0-e949dba": "e949dba",
507 "0.1.0-e949dba-dirty": "",
508 "0.1.0-unknown": "",
509 "": "",
510 "abcdefghijklmnopq-valley": "",
511 } {
512 if got := versionCommit(v); got != want {
513 t.Errorf("versionCommit(%q) = %q, want %q", v, got, want)
514 }
515 }
516}
517
518// TestErrorLine: a failure is reported by the line that says what went
519// wrong, not by the last line of a usage text printed after it.
520func TestErrorLine(t *testing.T) {
521 for out, want := range map[string]string{
522 "valley: unknown verb: --version\n\nvalley — S1 integrator verbs\n help show this help\n": "valley: unknown verb: --version",
523 "warning: Git tree is dirty\nerror: builder failed\nmore\n": "error: builder failed",
524 "one\ntwo\n\n": "two",
525 "": "",
526 } {
527 if got := ErrorLine(out); got != want {
528 t.Errorf("ErrorLine(%q) = %q, want %q", out, got, want)
529 }
530 }
531}