gunk-dev/the-valley

env_test.go

source6a7605f70901main's published tip history
13.5 KiB
1package flowenv
2
3import (
4 "go/ast"
5 "go/parser"
6 "go/token"
7 "io/fs"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "reflect"
12 "regexp"
13 "strconv"
14 "strings"
15 "testing"
16)
17
18func TestVarPrecedence(t *testing.T) {
19 for _, v := range All {
20 t.Run(v.New, func(t *testing.T) {
21 unsetBoth := func(t *testing.T) {
22 t.Helper()
23 t.Setenv(v.New, "")
24 t.Setenv(v.Legacy, "")
25 _ = os.Unsetenv(v.New)
26 _ = os.Unsetenv(v.Legacy)
27 }
28
29 t.Run("neither set", func(t *testing.T) {
30 unsetBoth(t)
31 if got, ok := v.Lookup(); ok || got != "" {
32 t.Errorf("Lookup() = (%q, %v), want (\"\", false)", got, ok)
33 }
34 if got := v.Get(); got != "" {
35 t.Errorf("Get() = %q, want \"\"", got)
36 }
37 })
38
39 t.Run("legacy only", func(t *testing.T) {
40 unsetBoth(t)
41 t.Setenv(v.Legacy, "old-val")
42 if got, ok := v.Lookup(); !ok || got != "old-val" {
43 t.Errorf("Lookup() = (%q, %v), want (\"old-val\", true)", got, ok)
44 }
45 if got := v.Get(); got != "old-val" {
46 t.Errorf("Get() = %q, want \"old-val\"", got)
47 }
48 })
49
50 t.Run("new only", func(t *testing.T) {
51 unsetBoth(t)
52 t.Setenv(v.New, "new-val")
53 if got, ok := v.Lookup(); !ok || got != "new-val" {
54 t.Errorf("Lookup() = (%q, %v), want (\"new-val\", true)", got, ok)
55 }
56 if got := v.Get(); got != "new-val" {
57 t.Errorf("Get() = %q, want \"new-val\"", got)
58 }
59 })
60
61 t.Run("both set prefers new", func(t *testing.T) {
62 unsetBoth(t)
63 t.Setenv(v.Legacy, "old-val")
64 t.Setenv(v.New, "new-val")
65 if got, ok := v.Lookup(); !ok || got != "new-val" {
66 t.Errorf("Lookup() = (%q, %v), want (\"new-val\", true)", got, ok)
67 }
68 if got := v.Get(); got != "new-val" {
69 t.Errorf("Get() = %q, want \"new-val\"", got)
70 }
71 })
72
73 t.Run("new set to empty overrides legacy", func(t *testing.T) {
74 unsetBoth(t)
75 t.Setenv(v.Legacy, "old-val")
76 t.Setenv(v.New, "")
77 if got, ok := v.Lookup(); !ok || got != "" {
78 t.Errorf("Lookup() = (%q, %v), want (\"\", true)", got, ok)
79 }
80 if got := v.Get(); got != "" {
81 t.Errorf("Get() = %q, want \"\"", got)
82 }
83 })
84 })
85 }
86}
87
88// A child gets the value flow sets under the legacy name, whatever either
89// spelling it inherits, in each form flow builds a child's environment in.
90func TestSetForChild(t *testing.T) {
91 const value = "it's set"
92 for _, v := range All {
93 t.Run(v.New, func(t *testing.T) {
94 path := "PATH=" + os.Getenv("PATH")
95 inherited := []string{path, v.New + "=stale", v.Legacy + "=stale"}
96 got := v.Set(inherited, value)
97 if want := []string{path, v.Legacy + "=" + value}; !reflect.DeepEqual(got, want) {
98 t.Errorf("Set() = %q, want %q", got, want)
99 }
100
101 report := `printf '%s|%s' "${` + v.New + `-unset}" "${` + v.Legacy + `-unset}"`
102 for name, tc := range map[string]struct{ script, want string }{
103 "Export": {v.Export(value) + report, "unset|" + value},
104 "EnvPrefix": {v.EnvPrefix(value) + "sh -c " + shellQuote(report), "unset|" + value},
105 "UnsetPrefix": {v.UnsetPrefix() + "sh -c " + shellQuote(report), "unset|unset"},
106 } {
107 cmd := exec.Command("sh", "-c", tc.script)
108 cmd.Env = inherited
109 out, err := cmd.CombinedOutput()
110 if err != nil {
111 t.Fatalf("%s: %v: %s", name, err, out)
112 }
113 if string(out) != tc.want {
114 t.Errorf("%s: child saw %q, want %q", name, out, tc.want)
115 }
116 }
117 })
118 }
119}
120
121// TestOnlyFlowenvSpellsFlowVars fails if production Go code outside flowenv
122// spells a listed variable's name, so every read, set and clear of one goes
123// through flowenv. Prose that mentions a name is allowed.
124func TestOnlyFlowenvSpellsFlowVars(t *testing.T) {
125 flowRoot, err := filepath.Abs(filepath.Join("..", ".."))
126 if err != nil {
127 t.Fatal(err)
128 }
129 skip := map[string]bool{}
130 for _, dir := range []string{
131 "internal/flowenv",
132 // Test support no binary links: it clears both spellings from its own
133 // test process before any test runs.
134 "internal/tmux/tmuxtest",
135 } {
136 skip[filepath.Join(flowRoot, dir)] = true
137 }
138
139 spellings := newSpellingFinder()
140 fset := token.NewFileSet()
141 files := 0
142 err = filepath.WalkDir(flowRoot, func(path string, d fs.DirEntry, walkErr error) error {
143 if walkErr != nil {
144 return walkErr
145 }
146 if d.IsDir() {
147 if skip[path] || strings.HasPrefix(d.Name(), ".") {
148 return filepath.SkipDir
149 }
150 return nil
151 }
152 if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
153 return nil
154 }
155 f, err := parser.ParseFile(fset, path, nil, 0)
156 if err != nil {
157 return err
158 }
159 files++
160 for _, v := range spellings.find(fset, f) {
161 rel, _ := filepath.Rel(flowRoot, path)
162 t.Errorf("%s:%d: %s outside flowenv; read, set or clear it through flowenv", rel, v.line, v.what)
163 }
164 return nil
165 })
166 if err != nil {
167 t.Fatal(err)
168 }
169 if files == 0 {
170 t.Fatalf("found no production Go files under %s", flowRoot)
171 }
172}
173
174func TestSpellingFinder(t *testing.T) {
175 src := `package sample
176import (
177 "fmt"
178 "os"
179 fe "the-valley/flow/internal/flowenv"
180 "example.org/other"
181)
182const sessionIDEnv = "KLAUS_SESSION_ID"
183func bad(env []string, id string) {
184 _, _ = os.LookupEnv("VALLEY_FLOW_RUN_ID")
185 env = append(env, "KLAUS_BACKEND="+id)
186 _ = fmt.Sprintf("export KLAUS_RUN_ID=%s; ", id)
187 _ = "env -u TMUX -u VALLEY_FLOW_SCRATCH cmd"
188 _ = "unset TMUX KLAUS_TMUX_SOCKET; "
189 _ = fe.Scratch.New
190 _ = os.Getenv(fe.TmuxSocket.Legacy)
191}
192func good() {
193 _ = fmt.Errorf("KLAUS_SESSION_ID is not set")
194 _ = "go build -o \"$KLAUS_SCRATCH/<name>\""
195 _ = "KLAUS_SCRATCHPAD=1 MY_KLAUS_BACKEND=x"
196 _ = os.Getenv("TMUX")
197 _ = other.Scratch.New
198 _ = fe.SessionID.Get()
199}
200`
201 fset := token.NewFileSet()
202 f, err := parser.ParseFile(fset, "sample.go", src, 0)
203 if err != nil {
204 t.Fatal(err)
205 }
206 got := newSpellingFinder().find(fset, f)
207 var lines []int
208 for _, v := range got {
209 lines = append(lines, v.line)
210 }
211 if want := []int{8, 10, 11, 12, 13, 14, 15, 16}; !reflect.DeepEqual(lines, want) {
212 t.Errorf("found spellings on lines %v, want %v: %+v", lines, want, got)
213 }
214}
215
216type spelling struct {
217 line int
218 what string
219}
220
221// spellingFinder finds where a file spells a listed name: a string literal
222// that is one, that assigns one (NAME=), or that unsets one in shell text
223// (unset NAME, env -u NAME), or a Var's New or Legacy field.
224type spellingFinder struct {
225 names map[string]bool
226 assign, unsets *regexp.Regexp
227}
228
229func newSpellingFinder() spellingFinder {
230 names := map[string]bool{}
231 var alts []string
232 for _, v := range All {
233 for _, n := range []string{v.New, v.Legacy} {
234 names[n] = true
235 alts = append(alts, regexp.QuoteMeta(n))
236 }
237 }
238 any := "(?:" + strings.Join(alts, "|") + ")"
239 return spellingFinder{
240 names: names,
241 assign: regexp.MustCompile(`(?:^|[^A-Za-z0-9_])` + any + `=`),
242 unsets: regexp.MustCompile(`(?:\bunset(?:\s+[A-Za-z_][A-Za-z0-9_]*)*\s+|-u\s*)` + any + `(?:[^A-Za-z0-9_]|$)`),
243 }
244}
245
246func (s spellingFinder) find(fset *token.FileSet, f *ast.File) []spelling {
247 flowenvAliases := map[string]bool{}
248 for _, imp := range f.Imports {
249 if path, _ := strconv.Unquote(imp.Path.Value); path == "the-valley/flow/internal/flowenv" {
250 alias := filepath.Base(path)
251 if imp.Name != nil {
252 alias = imp.Name.Name
253 }
254 flowenvAliases[alias] = true
255 }
256 }
257 var found []spelling
258 ast.Inspect(f, func(n ast.Node) bool {
259 line := func() int { return fset.Position(n.Pos()).Line }
260 switch e := n.(type) {
261 case *ast.ImportSpec:
262 return false
263 case *ast.BasicLit:
264 lit, ok := stringLiteral(e)
265 switch {
266 case !ok:
267 case s.names[lit]:
268 found = append(found, spelling{line(), "names " + lit})
269 case s.assign.MatchString(lit):
270 found = append(found, spelling{line(), "assigns " + s.assign.FindString(lit)})
271 case s.unsets.MatchString(lit):
272 found = append(found, spelling{line(), "clears " + s.unsets.FindString(lit)})
273 }
274 case *ast.SelectorExpr:
275 if e.Sel.Name != "New" && e.Sel.Name != "Legacy" {
276 return true
277 }
278 if inner, ok := e.X.(*ast.SelectorExpr); ok {
279 if pkg, ok := inner.X.(*ast.Ident); ok && flowenvAliases[pkg.Name] {
280 found = append(found, spelling{line(), "names flowenv." + inner.Sel.Name + "." + e.Sel.Name})
281 }
282 }
283 }
284 return true
285 })
286 return found
287}
288
289func stringLiteral(e ast.Expr) (string, bool) {
290 lit, ok := e.(*ast.BasicLit)
291 if !ok || lit.Kind != token.STRING {
292 return "", false
293 }
294 s, err := strconv.Unquote(lit.Value)
295 if err != nil {
296 return "", false
297 }
298 return s, true
299}
300
301// useGeneration points HOME at a host config that sets naming_generation g.
302func useGeneration(t *testing.T, g string) {
303 t.Helper()
304 home := t.TempDir()
305 t.Setenv("HOME", home)
306 if err := os.MkdirAll(filepath.Join(home, ".klaus"), 0o755); err != nil {
307 t.Fatal(err)
308 }
309 if err := os.WriteFile(filepath.Join(home, ".klaus", "config.json"), []byte(`{"naming_generation": "`+g+`"}`), 0o644); err != nil {
310 t.Fatal(err)
311 }
312}
313
314// childSees runs report in sh with env and returns what it printed.
315func childSees(t *testing.T, env []string, script string) string {
316 t.Helper()
317 cmd := exec.Command("sh", "-c", script)
318 cmd.Env = env
319 out, err := cmd.CombinedOutput()
320 if err != nil {
321 t.Fatalf("%v: %s", err, out)
322 }
323 return string(out)
324}
325
326// Under bridge a child gets each variable flow sets under both names with
327// one value, an explicitly empty one included, whatever it inherited; one
328// flow removes, under neither.
329func TestBridgeSetsBothNames(t *testing.T) {
330 useGeneration(t, "bridge")
331 for _, v := range All {
332 t.Run(v.New, func(t *testing.T) {
333 path := "PATH=" + os.Getenv("PATH")
334 inherited := []string{path, v.New + "=new-stale", v.Legacy + "=legacy-stale"}
335 report := `printf '%s|%s' "${` + v.New + `-unset}" "${` + v.Legacy + `-unset}"`
336 for _, value := range []string{"it's set", ""} {
337 got := v.Set(inherited, value)
338 if want := []string{path, v.New + "=" + value, v.Legacy + "=" + value}; !reflect.DeepEqual(got, want) {
339 t.Errorf("Set(%q) = %q, want %q", value, got, want)
340 }
341 both := value + "|" + value
342 if got := childSees(t, inherited, v.Export(value)+report); got != both {
343 t.Errorf("Export(%q): child saw %q, want %q", value, got, both)
344 }
345 if got := childSees(t, inherited, v.EnvPrefix(value)+"sh -c "+shellQuote(report)); got != both {
346 t.Errorf("EnvPrefix(%q): child saw %q, want %q", value, got, both)
347 }
348 }
349 if got := childSees(t, inherited, v.UnsetPrefix()+"sh -c "+shellQuote(report)); got != "unset|unset" {
350 t.Errorf("UnsetPrefix: child saw %q", got)
351 }
352 if v.Name() != v.New {
353 t.Errorf("Name() = %q, want %q", v.Name(), v.New)
354 }
355 })
356 }
357}
358
359// Normalize resolves each variable as Lookup would, the new name first and
360// an empty value included, and gives the child it under both names, or
361// under neither; under legacy it leaves the environment as it is.
362func TestNormalize(t *testing.T) {
363 v := Scratch
364 cases := []struct {
365 name string
366 env []string
367 want []string
368 }{
369 {"names that disagree", []string{"A=1", v.Legacy + "=old", v.New + "=new"}, []string{"A=1", v.New + "=new", v.Legacy + "=new"}},
370 {"legacy alone", []string{v.Legacy + "=old", "A=1"}, []string{"A=1", v.New + "=old", v.Legacy + "=old"}},
371 {"an empty new name", []string{v.New + "=", v.Legacy + "=old"}, []string{v.New + "=", v.Legacy + "="}},
372 {"the last entry wins", []string{v.New + "=first", v.New + "=last"}, []string{v.New + "=last", v.Legacy + "=last"}},
373 {"neither", []string{"A=1"}, []string{"A=1"}},
374 }
375 useGeneration(t, "bridge")
376 for _, tc := range cases {
377 if got := Normalize(tc.env); !reflect.DeepEqual(got, tc.want) {
378 t.Errorf("bridge, %s: Normalize = %q, want %q", tc.name, got, tc.want)
379 }
380 }
381 useGeneration(t, "legacy")
382 for _, tc := range cases {
383 if got := Normalize(tc.env); !reflect.DeepEqual(got, tc.env) {
384 t.Errorf("legacy, %s: Normalize = %q, want it unchanged", tc.name, got)
385 }
386 }
387 if NormalizePrefix() != "" {
388 t.Errorf("legacy NormalizePrefix = %q, want none", NormalizePrefix())
389 }
390 if v.Name() != v.Legacy {
391 t.Errorf("legacy Name() = %q, want %q", v.Name(), v.Legacy)
392 }
393}
394
395// A pane's shell starts from the tmux server's environment: under bridge
396// NormalizePrefix gives it this process's values under both names, and
397// clears what this process has under neither.
398func TestNormalizePrefixAndProcess(t *testing.T) {
399 useGeneration(t, "bridge")
400 for _, v := range All {
401 t.Setenv(v.New, "")
402 t.Setenv(v.Legacy, "")
403 _ = os.Unsetenv(v.New)
404 _ = os.Unsetenv(v.Legacy)
405 }
406 t.Setenv(SessionID.Legacy, "session-a")
407 t.Setenv(RunID.New, "run-new")
408 t.Setenv(RunID.Legacy, "run-old")
409 t.Setenv(Backend.New, "")
410
411 // The server's environment holds stale values of its own.
412 server := []string{"PATH=" + os.Getenv("PATH"), Scratch.Legacy + "=stale", AgentBackend.New + "=stale"}
413 var report []string
414 for _, v := range All {
415 report = append(report, `printf '%s=%s|%s\n' `+v.New+` "${`+v.New+`-unset}" "${`+v.Legacy+`-unset}"`)
416 }
417 got := childSees(t, server, NormalizePrefix()+strings.Join(report, "; "))
418 want := map[string]string{
419 SessionID.New: "session-a|session-a",
420 RunID.New: "run-new|run-new",
421 Backend.New: "|",
422 RunEvents.New: "unset|unset",
423 AgentBackend.New: "unset|unset",
424 Scratch.New: "unset|unset",
425 TmuxSocket.New: "unset|unset",
426 }
427 for _, line := range strings.Split(strings.TrimSpace(got), "\n") {
428 name, seen, _ := strings.Cut(line, "=")
429 if seen != want[name] {
430 t.Errorf("pane saw %s as %q, want %q", name, seen, want[name])
431 }
432 }
433
434 NormalizeProcess()
435 for _, v := range []Var{SessionID, RunID, Backend} {
436 n, nok := os.LookupEnv(v.New)
437 l, lok := os.LookupEnv(v.Legacy)
438 if !nok || !lok || n != l {
439 t.Errorf("after NormalizeProcess %s = %q (%v), %s = %q (%v)", v.New, n, nok, v.Legacy, l, lok)
440 }
441 }
442 if _, ok := os.LookupEnv(Scratch.New); ok {
443 t.Errorf("NormalizeProcess set %s, which was under neither name", Scratch.New)
444 }
445}