gunk-dev/the-valley

list_test.go

source83b8fc332220main's published tip history
14.1 KiB
1package main
2
3import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "os/exec"
8 "path/filepath"
9 "strings"
10 "testing"
11 "unicode/utf8"
12
13 "the-valley/change"
14)
15
16// A project's URL keeps the instance's transport, user and host, and
17// replaces the last path segment alone.
18func TestProjectURL(t *testing.T) {
19 for _, c := range []struct{ instance, want string }{
20 {"git@valley-host:valley.git", "git@valley-host:app.git"},
21 {"git@valley-host:valley", "git@valley-host:app"},
22 {"valley-host:srv/git/valley.git", "valley-host:srv/git/app.git"},
23 {"git@valley-host:/srv/git/valley.git/", "git@valley-host:/srv/git/app.git"},
24 {"ssh://git@valley-host/valley.git", "ssh://git@valley-host/app.git"},
25 {"ssh://git@valley-host:2222/srv/git/valley.git", "ssh://git@valley-host:2222/srv/git/app.git"},
26 {"ssh://git@[fe80::1]:22/valley.git", "ssh://git@[fe80::1]:22/app.git"},
27 {"https://git.example/valley/valley", "https://git.example/valley/app"},
28 {"file:///srv/git/valley.git", "file:///srv/git/app.git"},
29 {"/srv/git/valley.git", "/srv/git/app.git"},
30 {"./a:b/valley.git", "./a:b/app.git"},
31 } {
32 got, err := projectURL(c.instance, "app")
33 if err != nil || got != c.want {
34 t.Errorf("projectURL(%q) = %q, %v; want %q", c.instance, got, err, c.want)
35 }
36 }
37 for _, bad := range []string{"ssh://valley-host", "ssh://valley-host/", "git@valley-host:", "git@valley-host:.git"} {
38 if got, err := projectURL(bad, "app"); err == nil {
39 t.Errorf("projectURL(%q) = %q, where it has no path to replace", bad, got)
40 }
41 }
42}
43
44func TestHostOf(t *testing.T) {
45 for url, want := range map[string]string{
46 "git@valley-host:app.git": "valley-host",
47 "ssh://git@valley-host:2222/app.git": "valley-host:2222",
48 "https://user@git.example/valley/app.git": "git.example",
49 "/srv/git/app.git": "localhost",
50 "file:///srv/git/app.git": "localhost",
51 } {
52 if got := hostOf(url); got != want {
53 t.Errorf("hostOf(%q) = %q, want %q", url, got, want)
54 }
55 }
56}
57
58// pointerURL reads policy/valley as bin/valley's pointer_url does.
59func TestPointerURL(t *testing.T) {
60 got := pointerURL("# the owning valley\n\n git@valley-host:valley.git # floor\nother\n")
61 if got != "git@valley-host:valley.git" {
62 t.Errorf("pointerURL = %q", got)
63 }
64 if got := pointerURL("# nothing\n\n"); got != "" {
65 t.Errorf("pointerURL of comments alone = %q", got)
66 }
67}
68
69// Every handle among changes listed from several repositories is unique,
70// and minimal: one letter shorter, down to four, and another change
71// listed shares it.
72func TestHandlesUniqueAndMinimal(t *testing.T) {
73 app := []string{
74 "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz",
75 "nxvpwlzzqtsrzyoukklnpmqrstuvwxyz",
76 "xunxkkkkkkkkkkkkkkkkkkkkkkkkkkkk",
77 }
78 valley := []string{
79 "nxvpwlkmqtsrzyoukklnpmqrstuvwxyk", // shares 31 letters with app's first
80 "xunykkkkkkkkkkkkkkkkkkkkkkkkkkkk",
81 "qqqqkkkkkkkkkkkkkkkkkkkkkkkkkkkk",
82 }
83 repos := []listed{
84 {source: source{name: "app"}, snap: &snapshot{all: recordsOf(app)}},
85 {source: source{name: "valley"}, snap: &snapshot{all: recordsOf(valley)}},
86 {source: source{name: "ghost", err: errUnread}},
87 }
88 got := handles(repos)
89 h := map[string]string{}
90 for _, id := range app {
91 h[id] = got[handleKey{"app", "main", id}]
92 }
93 for _, id := range valley {
94 h[id] = got[handleKey{"valley", "main", id}]
95 }
96 all := append(append([]string(nil), app...), valley...)
97 seen := map[string]string{}
98 for _, id := range all {
99 handle := h[id]
100 if !strings.HasPrefix(id, handle) || len(handle) < 4 {
101 t.Fatalf("%s has the handle %q", id, handle)
102 }
103 if other, ok := seen[handle]; ok {
104 t.Fatalf("%s and %s share the handle %s", id, other, handle)
105 }
106 seen[handle] = id
107 for _, other := range all {
108 if other != id && strings.HasPrefix(other, handle) {
109 t.Fatalf("the handle %s of %s is a prefix of %s too", handle, id, other)
110 }
111 }
112 if shorter := handle[:len(handle)-1]; len(shorter) >= 4 {
113 shared := false
114 for _, other := range all {
115 shared = shared || other != id && strings.HasPrefix(other, shorter)
116 }
117 if !shared {
118 t.Errorf("the handle %s of %s is not minimal: %s names it alone", handle, id, shorter)
119 }
120 }
121 }
122 if h["xunxkkkkkkkkkkkkkkkkkkkkkkkkkkkk"] != "xunx" || h["qqqqkkkkkkkkkkkkkkkkkkkkkkkkkkkk"] != "qqqq" {
123 t.Errorf("four-letter handles grew: %v", h)
124 }
125 if got := h["nxvpwlkmqtsrzyoukklnpmqrstuvwxyz"]; len(got) != 32 {
126 t.Errorf("an ID sharing 31 letters with another listed elsewhere has the handle %s", got)
127 }
128}
129
130// One change ID recorded in two repositories has a handle qualified by
131// its repository in each, and the other changes keep theirs.
132func TestHandlesQualifiedAcrossRepos(t *testing.T) {
133 shared := "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz"
134 repos := []listed{
135 {source: source{name: "app"}, snap: &snapshot{all: recordsOf([]string{shared, "xunxkkkkkkkkkkkkkkkkkkkkkkkkkkkk"})}},
136 {source: source{name: "origin"}, snap: &snapshot{all: recordsOf([]string{shared})}},
137 }
138 h := handles(repos)
139 want := handleMap{
140 {"app", "main", shared}: "app:nxvp",
141 {"origin", "main", shared}: "origin:nxvp",
142 {"app", "main", "xunxkkkkkkkkkkkkkkkkkkkkkkkkkkkk"}: "xunx",
143 }
144 if len(h) != len(want) {
145 t.Fatalf("handles = %v, want %v", h, want)
146 }
147 for k, v := range want {
148 if h[k] != v {
149 t.Errorf("the handle of %v is %q, want %q", k, h[k], v)
150 }
151 }
152}
153
154// A URL from data that git would read as an option, or that names a
155// remote helper or another scheme, is refused. ssh, git, https, file,
156// scp-like and local URLs are read.
157func TestCheckURL(t *testing.T) {
158 for _, ok := range []string{
159 "git@valley-host:valley.git", "valley-host:valley", "ssh://git@valley-host:22/valley.git",
160 "ssh://git@[::1]/valley.git", "git://valley-host/valley.git", "https://git.example/valley",
161 "file:///srv/git/valley.git", "/srv/git/valley.git", "./valley.git",
162 } {
163 if err := checkURL(ok); err != nil {
164 t.Errorf("checkURL(%q) = %v", ok, err)
165 }
166 }
167 for _, bad := range []string{
168 "", "--upload-pack=touch /tmp/pwned; git-upload-pack", "-oProxyCommand=sh:x",
169 "ext::sh -c touch% /tmp/pwned", "fd::0", "remote-x::address", "http://git.example/valley",
170 "ftp://git.example/valley", "ssh://-oProxyCommand=sh/valley", "git@host:q\nvalley", "git@host:q\x1bvalley",
171 } {
172 if err := checkURL(bad); err == nil {
173 t.Errorf("checkURL(%q) let it through", bad)
174 }
175 }
176 if url, err := projectURL("ext::sh -c x/valley", "app"); err == nil {
177 t.Errorf("projectURL derived %q from a remote helper's URL", url)
178 }
179}
180
181var errUnread = failure("could not read")
182
183func recordsOf(ids []string) []recorded {
184 var all []recorded
185 for _, id := range ids {
186 all = append(all, recorded{id: id, record: &change.Record{Target: "main"}})
187 }
188 return all
189}
190
191// listingWith is a valley-changes/v1 document holding one change whose one
192// version has the title and branch given.
193func listingWith(title, branch string) jsonChanges {
194 tip := strings.Repeat("b", 40)
195 return jsonChanges{Schema: changesSchema, Host: "valley-host", Repos: []jsonRepo{{
196 Repo: "app", URL: "git@valley-host:app.git",
197 Changes: []jsonChange{{
198 ChangeID: "nxvpwlkmqtsrzyoukklnpmqrstuvwxyz", Handle: "nxvp", Target: "main",
199 Owner: "alice", State: "ready", Record: strings.Repeat("c", 40), Seq: 1, Active: 1,
200 Versions: []jsonVersion{{
201 N: 1, Head: strings.Repeat("a", 40), Title: title, Branch: branch, Uploader: "alice",
202 Landing: notLanded, Outcome: &versionOutcome{Decision: "failed", Head: strings.Repeat("a", 40), Tip: &tip},
203 }},
204 Includes: []string{},
205 }},
206 Drafts: &[]jsonChange{{ChangeID: "qqqqkkkkkkkkkkkkkkkkkkkkkkkkkkkk", Handle: "qqqq", Target: "main", Owner: "alice", State: "draft", Record: tip, Seq: 2, Active: 1, Versions: []jsonVersion{{N: 1, Head: tip, Title: title, Branch: branch, Uploader: "alice", Landing: notLanded}}, Includes: []string{}}},
207 Branches: []jsonBranch{{Branch: branch, Head: tip}},
208 }}}
209}
210
211// The writer puts out one line, with no control character in it, that
212// reads back as exactly the document written. A string that is not UTF-8
213// is refused rather than written as another one.
214func FuzzWriteDocument(f *testing.F) {
215 for _, seed := range [][2]string{
216 {"fix the frobnicator", "topic"},
217 {"tab\there, newline\nthere, nul\x00, del\x7f, esc\x1b[31m", "a/b"},
218 {"non-ASCII: café, 漢字, emoji 🎉, U+2028 
 and U+2029 
", "zweig/ä"},
219 {"quotes \" and backslash \\ and <html> & ampersand", "x"},
220 {"� replacement already there", "y"},
221 {"not UTF-8: \xff\xfe", "z"},
222 {"title", "branch\xc3"},
223 } {
224 f.Add(seed[0], seed[1])
225 }
226 f.Fuzz(func(t *testing.T, title, branch string) {
227 doc := listingWith(title, branch)
228 var buf bytes.Buffer
229 err := writeDocument(&buf, doc)
230 if !utf8.ValidString(title) || !utf8.ValidString(branch) {
231 if err == nil {
232 t.Fatalf("a string that is not UTF-8 was written: %q", buf.String())
233 }
234 return
235 }
236 if err != nil {
237 t.Fatalf("writeDocument: %v", err)
238 }
239 out := buf.Bytes()
240 if len(out) == 0 || out[len(out)-1] != '\n' || bytes.Count(out, []byte("\n")) != 1 {
241 t.Fatalf("not one line: %q", out)
242 }
243 for _, c := range out[:len(out)-1] {
244 if c < 0x20 {
245 t.Fatalf("a raw control character %q in %q", c, out)
246 }
247 }
248 var back jsonChanges
249 dec := json.NewDecoder(bytes.NewReader(out))
250 dec.DisallowUnknownFields()
251 if err := dec.Decode(&back); err != nil {
252 t.Fatalf("does not read back: %v: %q", err, out)
253 }
254 v := back.Repos[0].Changes[0].Versions[0]
255 d := (*back.Repos[0].Drafts)[0].Versions[0]
256 if v.Title != title || v.Branch != branch || back.Repos[0].Branches[0].Branch != branch || d.Title != title || d.Branch != branch {
257 t.Fatalf("read back as %q, %q, where %q, %q was written", v.Title, v.Branch, title, branch)
258 }
259 if back.Schema != changesSchema || v.LandedCommit != nil || v.Request != nil || *v.Outcome.Tip != strings.Repeat("b", 40) {
260 t.Fatalf("the fields around the strings moved: %q", out)
261 }
262 })
263}
264
265// Each change in valley changes and valley pending says which version it
266// landed as, and the commit on main it landed as, by the verdict valley
267// status gives and valley pending leaves landed changes out by: a change
268// landed at its active version; one whose first version landed while a
269// later version beside it was active, which landed as the first; and one
270// whose next round was made on the main that holds its landing, which has
271// not. Each lands by fast-forward, its head on main.
272func TestListingsSayWhichVersionAChangeLandedAs(t *testing.T) {
273 dir := t.TempDir()
274 t.Setenv("HOME", dir)
275 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
276 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
277 t.Setenv("VALLEY_KNOWN_SIGNERS", "")
278 origin, work := filepath.Join(dir, "origin.git"), filepath.Join(dir, "work")
279 git := func(args ...string) string {
280 t.Helper()
281 cmd := exec.Command("git", args...)
282 cmd.Dir = work
283 out, err := cmd.CombinedOutput()
284 if err != nil {
285 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
286 }
287 return strings.TrimSpace(string(out))
288 }
289 if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch=main", origin).CombinedOutput(); err != nil {
290 t.Fatalf("git init: %v\n%s", err, out)
291 }
292 if out, err := exec.Command("git", "clone", "--quiet", origin, work).CombinedOutput(); err != nil {
293 t.Fatalf("git clone: %v\n%s", err, out)
294 }
295 git("config", "user.name", "landed-test")
296 git("config", "user.email", "landed-test@localhost")
297 git("config", "valley.principal", "alice")
298 git("checkout", "--quiet", "-b", "main")
299 git("commit", "--quiet", "--allow-empty", "-m", "base")
300 git("push", "--quiet", "origin", "main")
301 commits := 0
302 branch := func(name, from string) string {
303 t.Helper()
304 commits++
305 git("checkout", "--quiet", "-B", name, from)
306 git("commit", "--quiet", "--allow-empty", "-m", fmt.Sprintf("%s, commit %d", name, commits))
307 git("push", "--quiet", "--force", "origin", name)
308 return git("rev-parse", "HEAD")
309 }
310
311 t.Chdir(work)
312 valley := func(args ...string) []byte {
313 t.Helper()
314 var stdout, stderr bytes.Buffer
315 if code := run(args, &stdout, &stderr); code != 0 {
316 t.Fatalf("valley-go %s: %s", strings.Join(args, " "), stderr.String())
317 }
318 return stdout.Bytes()
319 }
320 active, below, next := strings.Repeat("k", 32), strings.Repeat("m", 32), strings.Repeat("n", 32)
321 activeHead := branch("active", "main")
322 valley("ready", "--change", active, "active")
323 belowV1 := branch("below", "active")
324 valley("ready", "--change", below, "below")
325 nextV1 := branch("next", "below")
326 valley("ready", "--change", next, "next")
327 branch("below", "active")
328 valley("ready", "--change", below, "below")
329 git("push", "--quiet", "origin", nextV1+":refs/heads/main")
330 branch("next", nextV1)
331 valley("ready", "--change", next, "next")
332
333 verdict := func(v *int, commit *string) string {
334 if v == nil || commit == nil {
335 return fmt.Sprintf("%v %v", v, commit)
336 }
337 return fmt.Sprintf("v%d %s", *v, *commit)
338 }
339 listing := func(args ...string) map[string]string {
340 t.Helper()
341 var doc struct {
342 Repos []struct {
343 Changes []struct {
344 ID string `json:"change_id"`
345 Version *int `json:"landed_version"`
346 Commit *string `json:"landed_commit"`
347 } `json:"changes"`
348 } `json:"repos"`
349 }
350 if err := json.Unmarshal(valley(args...), &doc); err != nil || len(doc.Repos) != 1 {
351 t.Fatalf("valley-go %s: %v, %d repos", strings.Join(args, " "), err, len(doc.Repos))
352 }
353 got := map[string]string{}
354 for _, c := range doc.Repos[0].Changes {
355 got[c.ID] = verdict(c.Version, c.Commit)
356 }
357 return got
358 }
359 want := map[string]string{active: "v1 " + activeHead, below: "v1 " + belowV1, next: "<nil> <nil>"}
360 changes := listing("changes", "--json")
361 for id, w := range want {
362 if changes[id] != w {
363 t.Errorf("valley changes --json: %.4s landed as %q, want %q", id, changes[id], w)
364 }
365 var status struct {
366 Version *int `json:"landed_version"`
367 }
368 if err := json.Unmarshal(valley("status", "--json", id), &status); err != nil {
369 t.Fatalf("valley-go status --json %s: %v", id, err)
370 }
371 said := "<nil>"
372 if status.Version != nil {
373 said = fmt.Sprintf("v%d", *status.Version)
374 }
375 if said != strings.Fields(w)[0] {
376 t.Errorf("%.4s: valley status --json says landed_version %s, the listing %q", id, said, w)
377 }
378 }
379 if pending := listing("pending", "--json"); len(pending) != 1 || pending[next] != want[next] {
380 t.Errorf("valley pending --json lists %v, want only %.4s, unlanded", pending, next)
381 }
382}