gunk-dev/the-valley

main_test.go

sourcecfedff357a41main's published tip history
8.9 KiB
1package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "io/fs"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "regexp"
11 "slices"
12 "strings"
13 "testing"
14)
15
16// elsewhere has the test run in a directory of its own that is in no
17// repository, with a home of its own.
18func elsewhere(t *testing.T) {
19 t.Helper()
20 dir := t.TempDir()
21 t.Setenv("HOME", dir)
22 t.Setenv("GIT_CEILING_DIRECTORIES", filepath.Dir(dir))
23 t.Chdir(dir)
24}
25
26// command runs the valley command line args, elsewhere.
27func command(t *testing.T, args ...string) (status int, stdout, stderr string) {
28 t.Helper()
29 elsewhere(t)
30 return commandHere(t, args...)
31}
32
33// commandHere runs the valley command line args here.
34func commandHere(t *testing.T, args ...string) (status int, stdout, stderr string) {
35 t.Helper()
36 var out, errb bytes.Buffer
37 status = cli(args, &out, &errb, func(int) { t.Fatal("a verb ended the process") })
38 return status, out.String(), errb.String()
39}
40
41// No verb is help. An unknown verb prints the usage on stderr and exits 1.
42// Each public verb is its own: given an argument it refuses, it says so
43// itself.
44func TestDispatch(t *testing.T) {
45 if status, out, errs := command(t); status != 0 || out != helpText("") || errs != "" {
46 t.Errorf("no verb: %d %q %q", status, out, errs)
47 }
48 status, out, errs := command(t, "zx81q", "status")
49 if want := "valley: unknown verb: zx81q\n\n" + helpPart("usage"); status != 1 || out != "" || errs != want {
50 t.Errorf("an unknown verb: %d %q %q", status, out, errs)
51 }
52 refused := map[string][]string{"knot": {"zx81q"}, "telemetry": {"zx81q"}, "tail": {"a", "b"}, "replay": {"a", "b"}}
53 for verb := range helpTopics {
54 if verb == "flow" {
55 continue // its arguments are its helper's (flow_test.go)
56 }
57 args, ok := refused[verb]
58 if !ok {
59 args = []string{"--zx81q"}
60 }
61 status, out, errs := command(t, append([]string{verb}, args...)...)
62 if status == 0 || out != "" || errs == "" || strings.Contains(errs, "unknown verb: "+verb) {
63 t.Errorf("valley %s %s: %d %q %q", verb, strings.Join(args, " "), status, out, errs)
64 }
65 }
66}
67
68// -h or --help, alone after a public verb, is its help topic. With
69// another argument the verb reads them as its own.
70func TestVerbHelp(t *testing.T) {
71 for verb := range helpTopics {
72 if status, out, _ := command(t, "help", verb); status != 0 || out != helpText(verb) {
73 t.Errorf("valley help %s: %d", verb, status)
74 }
75 if verb == "flow" {
76 continue // its help flags are its helper's (flow_test.go)
77 }
78 for _, flag := range []string{"-h", "--help"} {
79 status, out, errs := command(t, verb, flag)
80 if status != 0 || out != helpText(verb) || errs != "" {
81 t.Errorf("valley %s %s: %d %q", verb, flag, status, errs)
82 }
83 }
84 }
85 for _, args := range [][]string{{"tail", "-h", "x"}, {"rebase", "--help", "x"}} {
86 status, out, errs := command(t, args...)
87 if status != 1 || out != "" || !strings.HasPrefix(errs, "valley: usage: valley "+args[0]+" ") {
88 t.Errorf("valley %s: %d %q %q", strings.Join(args, " "), status, out, errs)
89 }
90 }
91 for _, args := range [][]string{{"help", "a", "b"}, {"help", "zx81q"}, {"help", "resolve"}} {
92 if status, out, errs := command(t, args...); status != 1 || out != "" || errs == "" {
93 t.Errorf("valley %s: %d %q %q", strings.Join(args, " "), status, out, errs)
94 }
95 }
96}
97
98// --version prints the stamp, or says there is none.
99func TestVersion(t *testing.T) {
100 kept := versionStamp
101 t.Cleanup(func() { versionStamp = kept })
102 versionStamp = "0.1.0-97db597"
103 if _, out, _ := command(t, "--version"); out != "valley 0.1.0-97db597\n" {
104 t.Errorf("stamped: %q", out)
105 }
106 versionStamp = ""
107 if _, out, _ := command(t, "--version"); !strings.HasPrefix(out, "valley unstamped (") {
108 t.Errorf("unstamped: %q", out)
109 }
110}
111
112// Every verb the usage lists has a help topic, and every help file is a
113// public verb's topic or a part topics share.
114func TestHelpTopics(t *testing.T) {
115 listed := regexp.MustCompile(`(?m)^ ([a-z-]+) +[a-z]`).FindAllStringSubmatch(helpPart("usage"), -1)
116 if len(listed) != len(helpTopics) {
117 t.Errorf("the usage lists %d verbs, and %d have a topic", len(listed), len(helpTopics))
118 }
119 for _, m := range listed {
120 if !publicVerb(m[1]) {
121 t.Errorf("the usage lists %s, which has no topic", m[1])
122 }
123 }
124 shared := []string{"usage", "naming", "requests", "runtime"}
125 files, err := fs.Glob(helpFiles, "help/*")
126 if err != nil {
127 t.Fatal(err)
128 }
129 for _, f := range files {
130 name := strings.TrimSuffix(filepath.Base(f), ".txt")
131 if !publicVerb(name) && !slices.Contains(shared, name) || !strings.HasSuffix(f, ".txt") {
132 t.Errorf("%s is no verb's topic and no shared part", f)
133 }
134 }
135 for verb, parts := range helpTopics {
136 if parts[0] != verb || !strings.HasPrefix(helpText(verb), "usage: valley "+verb+" ") {
137 t.Errorf("%s's topic is not its own: %q", verb, parts)
138 }
139 }
140}
141
142// rebase takes one change and the signer flags, which it passes on in
143// front of the change, and it refuses anything else before it fetches.
144func TestRebaseArguments(t *testing.T) {
145 got, err := rebaseCommandArgs([]string{"--known-signers", "f", "topic", "--integrator-name=i"})
146 if want := []string{"--known-signers", "f", "--integrator-name=i", "topic"}; err != nil || !slices.Equal(got, want) {
147 t.Errorf("got %q %v, want %q", got, err, want)
148 }
149 for _, args := range [][]string{{}, {"a", "b"}, {"--head", "0123456", "a"}, {"a", "--known-signers"}, {"-", "a"}, {"--", "a"}, {""}} {
150 if _, err := rebaseCommandArgs(args); err == nil || err.Error() != rebaseUsage {
151 t.Errorf("rebase %q: %v", args, err)
152 }
153 // Outside a repository a fetch would fail with git's 128.
154 status, out, errs := command(t, append([]string{"rebase"}, args...)...)
155 if status != 1 || out != "" || errs != "valley: "+rebaseUsage+"\n" {
156 t.Errorf("valley rebase %q: %d %q %q", args, status, out, errs)
157 }
158 }
159}
160
161// pending and rebase fetch origin first, and a fetch that fails ends them
162// with git's own status.
163func TestFailedFetchExitsWithGitsStatus(t *testing.T) {
164 elsewhere(t)
165 gitIn := func(args ...string) error {
166 cmd := exec.Command("git", args...)
167 cmd.Env = gitEnvironment(os.Environ())
168 return cmd.Run()
169 }
170 if err := gitIn("init", "--quiet"); err != nil {
171 t.Fatal(err)
172 }
173 if err := gitIn("remote", "add", "origin", filepath.Join(t.TempDir(), "gone.git")); err != nil {
174 t.Fatal(err)
175 }
176 want := exitCode(gitIn("fetch", "--quiet", "origin"))
177 if want == 0 {
178 t.Fatal("a fetch of a missing origin succeeded")
179 }
180 for _, args := range [][]string{{"pending"}, {"rebase", "topic"}} {
181 if status, out, errs := commandHere(t, args...); status != want || out != "" {
182 t.Errorf("valley %s: %d, want git's %d: %s", strings.Join(args, " "), status, want, errs)
183 }
184 }
185}
186
187// replay publishes the payload the host's publisher hook does: a " in a
188// refname escaped as the hook escapes it, and < > & as they are.
189func TestReplayPayload(t *testing.T) {
190 oid := strings.Repeat("a1", 20)
191 got := refUpdated("app", `refs/heads/a"b<&>`, oid)
192 want := `{"event":"ref-updated","repo":"app","ref":"refs/heads/a\"b<&>","old":"` + strings.Repeat("0", 40) + `","new":"` + oid + `"}`
193 if got != want {
194 t.Fatalf("got %s\nwant %s", got, want)
195 }
196 var read struct{ Ref string }
197 if err := json.Unmarshal([]byte(got), &read); err != nil || read.Ref != `refs/heads/a"b<&>` {
198 t.Fatalf("the payload reads as %q: %v", read.Ref, err)
199 }
200}
201
202// The stamp is taken out of the environment, so a program valley starts
203// does not inherit it, and self-update and the command record still read
204// it. git there ignores replacement refs.
205func TestStampStaysOutOfStartedPrograms(t *testing.T) {
206 kept := versionStamp
207 t.Cleanup(func() { versionStamp = kept })
208 t.Setenv("VALLEY_VERSION", "0.1.0-97db597")
209 t.Setenv("GIT_NO_REPLACE_OBJECTS", "")
210 t.Setenv("GIT_GRAFT_FILE", "/elsewhere")
211 takeEnvironment()
212 out, err := exec.Command("sh", "-c", `printf '%s %s %s' "${VALLEY_VERSION-unset}" "$GIT_NO_REPLACE_OBJECTS" "${GIT_GRAFT_FILE-unset}"`).Output()
213 if err != nil || string(out) != "unset 1 unset" {
214 t.Fatalf("a started program's environment: %q %v", out, err)
215 }
216 if inv := commandOf([]string{"status", "topic"}); inv == nil || inv.version != "0.1.0-97db597" {
217 t.Errorf("the command record's version: %+v", inv)
218 }
219 u, err := newUpdater(selfUpdateArgs{repo: "/elsewhere.git", branch: "main"}, &bytes.Buffer{})
220 if err != nil || u.Version != "0.1.0-97db597" {
221 t.Errorf("self-update's version: %+v %v", u, err)
222 }
223}
224
225// A public verb run as the command records it, from the process's start;
226// help, a verb's help, --version, an unknown or internal verb and the
227// background flusher record nothing.
228func TestCommandOf(t *testing.T) {
229 if inv := commandOf([]string{"pending", "--json"}); inv == nil || !inv.since.Equal(phases.began) {
230 t.Errorf("pending: %+v", inv)
231 }
232 for _, args := range [][]string{{}, {"help", "pending"}, {"pending", "-h"}, {"review", "--help"}, {"--version"},
233 {"zx81q"}, {"resolve", "topic"}, {"checkline", "x"}, {"style"}, {"work"}, {"telemetry", "flush", "--watch", "1"}} {
234 if inv := commandOf(args); inv != nil {
235 t.Errorf("%q records %+v", args, inv)
236 }
237 }
238}