gunk-dev/the-valley

env_test.go

source6a6791929c36main's published tip history
8.2 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}