gunk-dev/the-valley

valley_test.go

sourceb8e46aa6aaccmain's published tip history
6.6 KiB
1package valley
2
3import (
4 "context"
5 "errors"
6 "os"
7 "path/filepath"
8 "strconv"
9 "strings"
10 "testing"
11 "time"
12)
13
14// TestTimeoutKillsValleysChildren runs a fake valley whose ready starts a
15// long-running child and waits for it, as a valley does while ssh carries
16// out the ready: when the timeout ends the ready, the child is gone too.
17func TestTimeoutKillsValleysChildren(t *testing.T) {
18 if _, err := os.Stat("/proc/self/stat"); err != nil {
19 t.Skip("needs /proc")
20 }
21 dir, bin := t.TempDir(), t.TempDir()
22 pidFile := filepath.Join(dir, "child.pid")
23 script := "#!/bin/sh\nsleep 300 &\necho $! > " + pidFile + "\nwait\n"
24 if err := os.WriteFile(filepath.Join(bin, "valley"), []byte(script), 0o755); err != nil {
25 t.Fatal(err)
26 }
27 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
28
29 ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
30 defer cancel()
31 start := time.Now()
32 _, err := Ready(ctx, dir, "nxvp-id", "0123456789abcdef0123456789abcdef01234567", "agent/x")
33 var verr *Error
34 if !errors.As(err, &verr) || !strings.HasPrefix(verr.Reason, "timed out") {
35 t.Fatalf("Ready = %v, want a timeout", err)
36 }
37 // The child held valley's stdout open: had it survived, Ready would have
38 // waited out WaitDelay.
39 if d := time.Since(start); d > 3*time.Second {
40 t.Errorf("Ready took %s after a 500ms timeout", d)
41 }
42
43 data, err := os.ReadFile(pidFile)
44 if err != nil {
45 t.Fatal(err)
46 }
47 pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
48 if err != nil {
49 t.Fatal(err)
50 }
51 for deadline := time.Now().Add(5 * time.Second); alive(pid); time.Sleep(50 * time.Millisecond) {
52 if time.Now().After(deadline) {
53 t.Fatalf("valley's child %d outlived the timeout", pid)
54 }
55 }
56}
57
58// TestUnreadyReadsValleysAnswer runs Unready against a fake valley: the
59// draft line means the change became a draft, a change that wasn't ready is
60// no error whether valley says so or refuses for it, and any other refusal
61// or output is one.
62func TestUnreadyReadsValleysAnswer(t *testing.T) {
63 dir, bin := t.TempDir(), t.TempDir()
64 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
65 fakeValley := func(stdout, stderr string, code int) {
66 t.Helper()
67 script := "#!/bin/sh\n[ \"$*\" = 'unready nxvp-id' ] || { echo \"bad args: $*\" >&2; exit 9; }\n" +
68 "printf '" + stdout + "'\nprintf '" + stderr + "' >&2\nexit " + strconv.Itoa(code) + "\n"
69 if err := os.WriteFile(filepath.Join(bin, "valley"), []byte(script), 0o755); err != nil {
70 t.Fatal(err)
71 }
72 }
73 for _, tc := range []struct {
74 name string
75 stdout, stderr string
76 code int
77 want Unreadied
78 wantErr string
79 }{
80 {name: "draft", stdout: "fetching...\\nsite nxvp draft\\n", want: Unreadied{Repo: "site", Handle: "nxvp", Draft: true}},
81 {name: "already a draft, said plainly", stdout: "nxvp is already a draft\\n", want: Unreadied{Note: "nxvp is already a draft"}},
82 {name: "draft already, refused (real valley wording)", stderr: "valley: tymm is a draft already; ready it to resume it\\n", code: 1,
83 want: Unreadied{Note: "valley: tymm is a draft already; ready it to resume it"}},
84 {name: "withdrawn, refused (real valley wording)", stderr: "valley: kkkk is withdrawn, and a withdrawn change is never made a draft; ready it to bring it back\\n", code: 1,
85 wantErr: "valley unready: valley: kkkk is withdrawn, and a withdrawn change is never made a draft; ready it to bring it back"},
86 {name: "not ready, refused", stderr: "valley: change nxvp is not ready\\n", code: 1,
87 want: Unreadied{Note: "valley: change nxvp is not ready"}},
88 {name: "no record, refused", stderr: "valley: no change record for nxvp-id\\n", code: 1,
89 want: Unreadied{Note: "valley: no change record for nxvp-id"}},
90 {name: "other refusal", stderr: "valley: refused: you do not own nxvp\\n", code: 1,
91 wantErr: "valley unready: valley: refused: you do not own nxvp"},
92 {name: "unexpected output", stdout: "site nxvp v2 ready\\n", wantErr: "valley unready: unexpected output: site nxvp v2 ready"},
93 {name: "no output", wantErr: "valley unready: unexpected output: "},
94 } {
95 t.Run(tc.name, func(t *testing.T) {
96 fakeValley(tc.stdout, tc.stderr, tc.code)
97 got, err := Unready(context.Background(), dir, "nxvp-id")
98 if tc.wantErr != "" {
99 if err == nil || err.Error() != tc.wantErr {
100 t.Fatalf("Unready = %+v, %v; want error %q", got, err, tc.wantErr)
101 }
102 return
103 }
104 if err != nil || got != tc.want {
105 t.Errorf("Unready = %+v, %v; want %+v", got, err, tc.want)
106 }
107 })
108 }
109}
110
111// alive reports whether process pid exists and isn't a zombie.
112func alive(pid int) bool {
113 stat, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
114 if err != nil {
115 return false
116 }
117 // The state follows the parenthesized command name.
118 i := strings.LastIndexByte(string(stat), ')')
119 return i < 0 || !strings.HasPrefix(string(stat[i+1:]), " Z")
120}
121
122// A CLI that refuses --checks is listed again without it, and not asked with
123// it again until the refusal is forgotten; a refusal of anything else, or
124// another failure, is an error, never a listing without checks.
125func TestListChecksFallsBackOnRefusal(t *testing.T) {
126 dir, bin := t.TempDir(), t.TempDir()
127 script := `#!/bin/sh
128echo "$@" >> ` + filepath.Join(dir, "argv") + `
129for a in "$@"; do
130 if [ "$a" = --checks ]; then
131 if [ -f ` + filepath.Join(dir, "other") + ` ]; then echo "valley: cannot reach host" >&2; else echo "valley: changes does not take --checks" >&2; fi
132 exit 1
133 fi
134done
135echo '{"schema":"valley-changes/v1","host":"h","repos":[]}'
136`
137 if err := os.WriteFile(filepath.Join(bin, "valley"), []byte(script), 0o755); err != nil {
138 t.Fatal(err)
139 }
140 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
141 checksRefused.Lock()
142 checksRefused.at, checksRefused.logged = time.Time{}, false
143 checksRefused.Unlock()
144 argv := func() string {
145 b, _ := os.ReadFile(filepath.Join(dir, "argv"))
146 return string(b)
147 }
148
149 for i := 0; i < 2; i++ {
150 if _, err := List(context.Background(), dir); err != nil {
151 t.Fatalf("List = %v, want the plain listing", err)
152 }
153 }
154 if got, want := argv(), "changes --all --json --checks\nchanges --all --json\nchanges --all --json\n"; got != want {
155 t.Errorf("valley ran:\n%s\nwant:\n%s", got, want)
156 }
157
158 // Once forgotten, the flag is tried again; another failure is an error.
159 old := ChecksRefusalMemory
160 ChecksRefusalMemory = 0
161 defer func() { ChecksRefusalMemory = old }()
162 if err := os.WriteFile(filepath.Join(dir, "other"), nil, 0o644); err != nil {
163 t.Fatal(err)
164 }
165 if _, err := List(context.Background(), dir); err == nil || !strings.Contains(err.Error(), "cannot reach host") {
166 t.Errorf("List = %v, want the valley's own failure", err)
167 }
168}