gunk-dev/the-valley

env_test.go

sourceb25f64483e27main's published tip history
9.8 KiB
1package main
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "io/fs"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "strings"
15 "syscall"
16 "testing"
17 "time"
18
19 "the-valley/change"
20 "the-valley/rebase"
21)
22
23// roleEnv, set to "main", makes the test binary valley-restacker itself,
24// so a test can run the program as a process of its own.
25const roleEnv = "RESTACK_TEST_ROLE"
26
27func TestMain(m *testing.M) {
28 if os.Getenv(roleEnv) == "main" {
29 main()
30 os.Exit(0)
31 }
32 os.Exit(m.Run())
33}
34
35// decoy is a repository, and files around it, that an inherited variable
36// would point git at instead of the scratch repository.
37type decoy struct {
38 dir, repo string
39}
40
41func newDecoy(t *testing.T, f *fixture) *decoy {
42 t.Helper()
43 d := &decoy{dir: t.TempDir()}
44 d.repo = filepath.Join(d.dir, "decoy.git")
45 f.run(d.dir, "init", "--quiet", "--bare", "--initial-branch=main", d.repo)
46 for _, sub := range []string{"wt", "objects/info", "objects/pack", "exec", "template/hooks"} {
47 if err := os.MkdirAll(filepath.Join(d.dir, sub), 0o755); err != nil {
48 t.Fatal(err)
49 }
50 }
51 files := map[string]string{
52 // Configuration that sends every fetch from origin to the decoy.
53 "gitconfig": "[url \"" + d.repo + "\"]\n\tinsteadOf = " + f.origin + "\n",
54 // A program git would run from its exec path to serve a fetch.
55 "exec/git-upload-pack": "#!/bin/sh\ntouch '" + filepath.Join(d.dir, "ran") + "'\nexit 1\n",
56 // A template git init would copy into a new repository.
57 "template/marker": "from the decoy\n",
58 "grafts": "",
59 }
60 for name, content := range files {
61 if err := os.WriteFile(filepath.Join(d.dir, name), []byte(content), 0o755); err != nil {
62 t.Fatal(err)
63 }
64 }
65 return d
66}
67
68// digest is every file under the decoy, by path and content.
69func (d *decoy) digest(t *testing.T) string {
70 t.Helper()
71 h := sha256.New()
72 err := filepath.WalkDir(d.dir, func(path string, e fs.DirEntry, err error) error {
73 if err != nil {
74 return err
75 }
76 h.Write([]byte(path + "\n"))
77 if !e.IsDir() {
78 data, err := os.ReadFile(path)
79 if err != nil {
80 return err
81 }
82 h.Write(data)
83 }
84 return nil
85 })
86 if err != nil {
87 t.Fatal(err)
88 }
89 return hex.EncodeToString(h.Sum(nil))
90}
91
92// shape is what a plan says, less what differs from pass to pass: the
93// operation and the commits built.
94func shape(t *testing.T, out []byte) string {
95 t.Helper()
96 var p Plan
97 if err := json.Unmarshal(out, &p); err != nil {
98 t.Fatalf("the plan does not read: %v\n%s", err, out)
99 }
100 p.Operation = ""
101 for i := range p.Families {
102 if w := p.Families[i].Writes; w != nil {
103 for j := range w.Branches {
104 w.Branches[j].New = ""
105 }
106 for j := range w.Versions {
107 w.Versions[j].Head, w.Versions[j].Record = "", ""
108 }
109 for j := range w.Reports {
110 w.Reports[j].Commit = ""
111 }
112 }
113 }
114 data, _ := json.Marshal(p)
115 return string(data)
116}
117
118// No variable that points git at another repository, other programs,
119// other attributes or another format, or that gives it configuration,
120// reaches what a pass runs. With each inherited, pointing at a decoy, the
121// pass plans and builds what it does without, the decoy is untouched, and
122// nothing the pass prints names it.
123func TestNoInheritedGitVariableReachesAPass(t *testing.T) {
124 f := newFixture(t, "")
125 f.readyAs(idA, "alice", "a", "main", "A's title")
126 f.readyAs(idB, "bob", "b", "a", "B's title")
127 f.moveMain()
128 d := newDecoy(t, f)
129 pass := func(t *testing.T) (string, string) {
130 t.Helper()
131 r := newRestacker(t, f)
132 r.c.state = t.TempDir()
133 var out, errOut bytes.Buffer
134 if err := once(context.Background(), reportOnly(t, r.c, "--json"), &out, &errOut); err != nil {
135 return "failed: " + err.Error(), errOut.String()
136 }
137 if _, err := os.Stat(filepath.Join(r.c.state, "scratch", ".git", "marker")); err == nil {
138 return "the decoy's template reached the scratch repository", errOut.String()
139 }
140 return shape(t, out.Bytes()), errOut.String()
141 }
142 want, _ := pass(t)
143 if strings.HasPrefix(want, "failed") {
144 t.Fatal(want)
145 }
146 before := d.digest(t)
147 head := f.at("refs/heads/a")
148 for _, tc := range []struct {
149 name string
150 vars map[string]string
151 }{
152 {"GIT_DIR", map[string]string{"GIT_DIR": d.repo}},
153 {"GIT_WORK_TREE", map[string]string{"GIT_WORK_TREE": filepath.Join(d.dir, "wt")}},
154 {"GIT_INDEX_FILE", map[string]string{"GIT_INDEX_FILE": filepath.Join(d.dir, "index")}},
155 {"GIT_OBJECT_DIRECTORY", map[string]string{"GIT_OBJECT_DIRECTORY": filepath.Join(d.dir, "objects")}},
156 {"GIT_ALTERNATE_OBJECT_DIRECTORIES", map[string]string{"GIT_ALTERNATE_OBJECT_DIRECTORIES": filepath.Join(d.dir, "no-such-objects")}},
157 {"GIT_COMMON_DIR", map[string]string{"GIT_COMMON_DIR": d.repo}},
158 {"GIT_NAMESPACE", map[string]string{"GIT_NAMESPACE": "decoy"}},
159 {"GIT_CONFIG_GLOBAL", map[string]string{"GIT_CONFIG_GLOBAL": filepath.Join(d.dir, "gitconfig")}},
160 {"GIT_CONFIG_SYSTEM", map[string]string{"GIT_CONFIG_SYSTEM": filepath.Join(d.dir, "gitconfig"), "GIT_CONFIG_NOSYSTEM": "0"}},
161 {"GIT_CONFIG", map[string]string{"GIT_CONFIG": filepath.Join(d.dir, "gitconfig")}},
162 {"GIT_CONFIG_COUNT", map[string]string{"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "url." + d.repo + ".insteadOf", "GIT_CONFIG_VALUE_0": f.origin}},
163 {"GIT_CONFIG_PARAMETERS", map[string]string{"GIT_CONFIG_PARAMETERS": "'url." + d.repo + ".insteadof'='" + f.origin + "'"}},
164 {"GIT_EXEC_PATH", map[string]string{"GIT_EXEC_PATH": filepath.Join(d.dir, "exec")}},
165 {"GIT_TEMPLATE_DIR", map[string]string{"GIT_TEMPLATE_DIR": filepath.Join(d.dir, "template")}},
166 {"GIT_DEFAULT_HASH", map[string]string{"GIT_DEFAULT_HASH": "sha256"}},
167 {"GIT_ATTR_SOURCE", map[string]string{"GIT_ATTR_SOURCE": "no-such-attribute-source"}},
168 {"GIT_GRAFT_FILE", map[string]string{"GIT_GRAFT_FILE": filepath.Join(d.dir, "grafts")}},
169 } {
170 t.Run(tc.name, func(t *testing.T) {
171 if tc.name == "GIT_GRAFT_FILE" {
172 // A graft that would cut a's commit from its history.
173 if err := os.WriteFile(filepath.Join(d.dir, "grafts"), []byte(head+"\n"), 0o644); err != nil {
174 t.Fatal(err)
175 }
176 defer os.WriteFile(filepath.Join(d.dir, "grafts"), nil, 0o755)
177 before = d.digest(t)
178 }
179 for name, value := range tc.vars {
180 t.Setenv(name, value)
181 }
182 got, stderr := pass(t)
183 if got != want {
184 t.Errorf("with %s inherited, the pass says\n%s\nand without\n%s", tc.name, got, want)
185 }
186 if after := d.digest(t); after != before {
187 t.Errorf("with %s inherited, the pass changed the decoy", tc.name)
188 }
189 if strings.Contains(stderr, d.dir) {
190 t.Errorf("with %s inherited, the pass printed\n%s", tc.name, stderr)
191 }
192 })
193 }
194}
195
196// The user's own attributes file, which git reads from XDG_CONFIG_HOME or
197// HOME whatever configuration it reads, does not change how a pass
198// rebases: a merge=union there would resolve a conflict silently.
199func TestTheUsersAttributesDoNotChangeARebase(t *testing.T) {
200 f := newFixture(t, "")
201 f.git("checkout", "--quiet", "-b", "a", "main")
202 head := f.commit("a's line", "shared.txt")
203 f.git("push", "--quiet", "origin", "a")
204 f.writeRecordAt(idA, "a", head)
205 f.git("checkout", "--quiet", "main")
206 if err := os.WriteFile(filepath.Join(f.work, "shared.txt"), []byte("main's line\n"), 0o644); err != nil {
207 t.Fatal(err)
208 }
209 f.git("add", "shared.txt")
210 f.git("commit", "--quiet", "-m", "main's line")
211 f.git("push", "--quiet", "origin", "main")
212
213 home := t.TempDir()
214 for _, dir := range []string{filepath.Join(home, ".config", "git"), filepath.Join(home, "xdg", "git")} {
215 if err := os.MkdirAll(dir, 0o755); err != nil {
216 t.Fatal(err)
217 }
218 if err := os.WriteFile(filepath.Join(dir, "attributes"), []byte("* merge=union\n"), 0o644); err != nil {
219 t.Fatal(err)
220 }
221 }
222 t.Setenv("HOME", home)
223 t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "xdg"))
224 r := newRestacker(t, f)
225 var out, errOut bytes.Buffer
226 if err := once(context.Background(), reportOnly(t, r.c, "--json"), &out, &errOut); err != nil {
227 t.Fatalf("once: %v\n%s", err, errOut.String())
228 }
229 var p Plan
230 if err := json.Unmarshal(out.Bytes(), &p); err != nil {
231 t.Fatal(err)
232 }
233 if len(p.Families) != 1 || p.Families[0].Writes == nil || p.Families[0].Writes.Result != "conflict" {
234 t.Errorf("with merge=union in the user's attributes, the pass says %s", out.String())
235 }
236}
237
238// writeRecordAt readies the change id at head on branch, owned by alice.
239func (f *fixture) writeRecordAt(id, branch, head string) {
240 f.t.Helper()
241 f.writeRecord(id, &change.Record{
242 Schema: change.Schema, ChangeID: id, Target: rebase.Target, Owner: "alice", State: change.Ready, Seq: 1, Active: 1,
243 Versions: []change.Version{{N: 1, Head: change.HeadPrefix + head, Title: "A title", Branch: branch, Uploader: "alice"}},
244 }, "", head)
245}
246
247// A process whose stderr nobody reads, and is full, still ends: the error
248// it ends with is given up on after a few seconds.
249func TestABlockedStderrDoesNotHoldTheProcess(t *testing.T) {
250 self, err := os.Executable()
251 if err != nil {
252 t.Fatal(err)
253 }
254 r, w, err := os.Pipe()
255 if err != nil {
256 t.Fatal(err)
257 }
258 defer r.Close()
259 defer w.Close()
260 fd := int(w.Fd())
261 if err := syscall.SetNonblock(fd, true); err != nil {
262 t.Fatal(err)
263 }
264 chunk := make([]byte, 4096)
265 for {
266 if _, err := syscall.Write(fd, chunk); err != nil {
267 if errors.Is(err, syscall.EAGAIN) {
268 break
269 }
270 t.Fatal(err)
271 }
272 }
273 if err := syscall.SetNonblock(fd, false); err != nil {
274 t.Fatal(err)
275 }
276 cmd := exec.Command(self, "once", "--report-only")
277 cmd.Env = append(os.Environ(), roleEnv+"=main")
278 cmd.Stderr = w
279 start := time.Now()
280 if err := cmd.Start(); err != nil {
281 t.Fatal(err)
282 }
283 done := make(chan error, 1)
284 go func() { done <- cmd.Wait() }()
285 select {
286 case err := <-done:
287 var exit *exec.ExitError
288 if !errors.As(err, &exit) || exit.ExitCode() != 1 {
289 t.Errorf("the process ended with %v, not the error it could not print", err)
290 }
291 if took := time.Since(start); took > sayBound+10*time.Second {
292 t.Errorf("the process took %v to end", took)
293 }
294 case <-time.After(sayBound + 30*time.Second):
295 cmd.Process.Kill()
296 t.Fatal("a process whose stderr nobody reads did not end")
297 }
298}