Debian Codegraph @

cmd/stringer/endtoend_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // go command is not available on android
6
•7 //go:build !android && ignore
8 // +build !android,ignore
9
10 package main
11
12 import (
13 "bytes"
14 "flag"
15 "fmt"
16 "io"
17 "os"
18 "path"
19 "path/filepath"
20 "reflect"
21 "slices"
22 "strings"
23 "sync"
24 "testing"
25
26 "golang.org/x/tools/internal/testenv"
27 )
28
29 // This file contains a test that compiles and runs each program in testdata
30 // after generating the string method for its type. The rule is that for testdata/x.go
31 // we run stringer -type X and then compile and run the program. The resulting
32 // binary panics if the String method for X is not correct, including for error cases.
33
34 func TestMain(m *testing.M) {
35 if os.Getenv("STRINGER_TEST_IS_STRINGER") != "" {
36 main()
37 os.Exit(0)
38 }
39
40 // Inform subprocesses that they should run the cmd/stringer main instead of
41 // running tests. It's a close approximation to building and running the real
42 // command, and much less complicated and expensive to build and clean up.
43 os.Setenv("STRINGER_TEST_IS_STRINGER", "1")
44
45 flag.Parse()
46 if testing.Verbose() {
47 os.Setenv("GOPACKAGESDEBUG", "true")
48 }
49
50 os.Exit(m.Run())
51 }
52
53 func TestEndToEnd(t *testing.T) {
54 testenv.NeedsTool(t, "go")
55
56 stringer := stringerPath(t)
57 // Read the testdata directory.
58 fd, err := os.Open("testdata")
59 if err != nil {
60 t.Fatal(err)
61 }
62 defer fd.Close()
63 names, err := fd.Readdirnames(-1)
64 if err != nil {
65 t.Fatalf("Readdirnames: %s", err)
66 }
67 // Generate, compile, and run the test programs.
68 for _, name := range names {
69 if name == "typeparams" {
70 // ignore the directory containing the tests with type params
71 continue
72 }
73 if !strings.HasSuffix(name, ".go") {
74 t.Errorf("%s is not a Go file", name)
75 continue
76 }
77 if strings.HasPrefix(name, "tag_") || strings.HasPrefix(name, "vary_") {
78 // This file is used for tag processing in TestTags or TestConstValueChange, below.
79 continue
80 }
81 t.Run(name, func(t *testing.T) {
82 if name == "cgo.go" {
83 testenv.NeedsTool(t, "cgo")
84 }
85 stringerCompileAndRun(t, t.TempDir(), stringer, typeName(name), name)
86 })
87 }
88 }
89
90 // a type name for stringer. use the last component of the file name with the .go
91 func typeName(fname string) string {
92 // file names are known to be ascii and end .go
93 base := path.Base(fname)
94 return fmt.Sprintf("%c%s", base[0]+'A'-'a', base[1:len(base)-len(".go")])
95 }
96
97 // TestTags verifies that the -tags flag works as advertised.
98 func TestTags(t *testing.T) {
99 stringer := stringerPath(t)
100 dir := t.TempDir()
101 var (
102 protectedConst = []byte("TagProtected")
103 output = filepath.Join(dir, "const_string.go")
104 )
105 for _, file := range []string{"tag_main.go", "tag_tag.go"} {
106 err := copy(filepath.Join(dir, file), filepath.Join("testdata", file))
107 if err != nil {
108 t.Fatal(err)
109 }
110 }
111 // Run stringer in the directory that contains the module that contains the package files.
112 if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module test\n"), 0o600); err != nil {
113 t.Fatal(err)
114 }
115 err := runInDir(t, dir, stringer, "-type", "Const", ".")
116 if err != nil {
117 t.Fatal(err)
118 }
119 result, err := os.ReadFile(output)
120 if err != nil {
121 t.Fatal(err)
122 }
123 if bytes.Contains(result, protectedConst) {
124 t.Fatal("tagged variable appears in untagged run")
125 }
126 err = os.Remove(output)
127 if err != nil {
128 t.Fatal(err)
129 }
130 err = runInDir(t, dir, stringer, "-type", "Const", "-tags", "tag", ".")
131 if err != nil {
132 t.Fatal(err)
133 }
134 result, err = os.ReadFile(output)
135 if err != nil {
136 t.Fatal(err)
137 }
138 if !bytes.Contains(result, protectedConst) {
139 t.Fatal("tagged variable does not appear in tagged run")
140 }
141 }
142
143 // TestConstValueChange verifies that if a constant value changes and
144 // the stringer code is not regenerated, we'll get a compiler error.
145 func TestConstValueChange(t *testing.T) {
146 testenv.NeedsTool(t, "go")
147
148 stringer := stringerPath(t)
149 dir := t.TempDir()
150 source := filepath.Join(dir, "day.go")
151 err := copy(source, filepath.Join("testdata", "day.go"))
152 if err != nil {
153 t.Fatal(err)
154 }
155 stringSource := filepath.Join(dir, "day_string.go")
156 // Run stringer in the directory that contains the module that contains the package files.
157 if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module test\n"), 0o600); err != nil {
158 t.Fatal(err)
159 }
160 err = runInDir(t, dir, stringer, "-type", "Day", "-output", stringSource)
161 if err != nil {
162 t.Fatal(err)
163 }
164 // Run the binary in the temporary directory as a sanity check.
165 err = run(t, "go", "run", stringSource, source)
166 if err != nil {
167 t.Fatal(err)
168 }
169 // Overwrite the source file with a version that has changed constants.
170 err = copy(source, filepath.Join("testdata", "vary_day.go"))
171 if err != nil {
172 t.Fatal(err)
173 }
174 // Unfortunately different compilers may give different error messages,
175 // so there's no easy way to verify that the build failed specifically
176 // because the constants changed rather than because the vary_day.go
177 // file is invalid.
178 //
179 // Instead we'll just rely on manual inspection of the polluted test
180 // output. An alternative might be to check that the error output
181 // matches a set of possible error strings emitted by known
182 // Go compilers.
183 t.Logf("Note: the following messages should indicate an out-of-bounds compiler error\n")
184 err = run(t, "go", "build", stringSource, source)
185 if err == nil {
186 t.Fatal("unexpected compiler success")
187 }
188 }
189
190 var testfileSrcs = map[string]string{
191 "go.mod": "module foo",
192
193 // Normal file in the package.
194 "main.go": `package foo
195
196 type Foo int
197
198 const (
199 fooX Foo = iota
200 fooY
201 fooZ
202 )
203 `,
204
205 // Test file in the package.
206 "main_test.go": `package foo
207
208 type Bar int
209
210 const (
211 barX Bar = iota
212 barY
213 barZ
214 )
215 `,
216
217 // Test file in the test package.
218 "main_pkg_test.go": `package foo_test
219
220 type Baz int
221
222 const (
223 bazX Baz = iota
224 bazY
225 bazZ
226 )
227 `,
228 }
229
230 // Test stringer on types defined in different kinds of tests.
231 // The generated code should not interfere between itself.
232 func TestTestFiles(t *testing.T) {
233 testenv.NeedsTool(t, "go")
234 stringer := stringerPath(t)
235
236 dir := t.TempDir()
237 t.Logf("TestTestFiles in: %s \n", dir)
238 for name, src := range testfileSrcs {
239 source := filepath.Join(dir, name)
240 err := os.WriteFile(source, []byte(src), 0666)
241 if err != nil {
242 t.Fatalf("write file: %s", err)
243 }
244 }
245
246 // Must run stringer in the temp directory, see TestTags.
247 err := runInDir(t, dir, stringer, "-type=Foo,Bar,Baz", dir)
248 if err != nil {
249 t.Fatalf("run stringer: %s", err)
250 }
251
252 // Check that stringer has created the expected files.
253 content, err := os.ReadDir(dir)
254 if err != nil {
255 t.Fatalf("read dir: %s", err)
256 }
257 gotFiles := []string{}
258 for _, f := range content {
259 if !f.IsDir() {
260 gotFiles = append(gotFiles, f.Name())
261 }
262 }
263 wantFiles := []string{
264 // Original.
265 "go.mod",
266 "main.go",
267 "main_test.go",
268 "main_pkg_test.go",
269 // Generated.
270 "foo_string.go",
271 "bar_string_test.go",
272 "baz_string_test.go",
273 }
274 slices.Sort(gotFiles)
275 slices.Sort(wantFiles)
276 if !reflect.DeepEqual(gotFiles, wantFiles) {
277 t.Errorf("stringer generated files:\n%s\n\nbut want:\n%s",
278 strings.Join(gotFiles, "\n"),
279 strings.Join(wantFiles, "\n"),
280 )
281 }
282
283 // Run go test as a smoke test.
284 err = runInDir(t, dir, "go", "test", "-count=1", ".")
285 if err != nil {
286 t.Fatalf("go test: %s", err)
287 }
288 }
289
290 // The -output flag cannot be used in combination with matching types across multiple packages.
291 func TestCollidingOutput(t *testing.T) {
292 testenv.NeedsTool(t, "go")
293 stringer := stringerPath(t)
294
295 dir := t.TempDir()
296 for name, src := range testfileSrcs {
297 source := filepath.Join(dir, name)
298 err := os.WriteFile(source, []byte(src), 0666)
299 if err != nil {
300 t.Fatalf("write file: %s", err)
301 }
302 }
303
304 // Must run stringer in the temp directory, see TestTags.
305 err := runInDir(t, dir, stringer, "-type=Foo,Bar,Baz", "-output=somefile.go", dir)
306 if err == nil {
307 t.Fatal("unexpected stringer success")
308 }
309 }
310
311 var exe struct {
312 path string
313 err error
314 once sync.Once
315 }
316
317 func stringerPath(t *testing.T) string {
318 testenv.NeedsExec(t)
319
320 exe.once.Do(func() {
321 exe.path, exe.err = os.Executable()
322 })
323 if exe.err != nil {
324 t.Fatal(exe.err)
325 }
326 return exe.path
327 }
328
329 // stringerCompileAndRun runs stringer for the named file and compiles and
330 // runs the target binary in directory dir. That binary will panic if the String method is incorrect.
331 func stringerCompileAndRun(t *testing.T, dir, stringer, typeName, fileName string) {
332 t.Logf("run: %s %s\n", fileName, typeName)
333 source := filepath.Join(dir, path.Base(fileName))
334 err := copy(source, filepath.Join("testdata", fileName))
335 if err != nil {
336 t.Fatalf("copying file to temporary directory: %s", err)
337 }
338 stringSource := filepath.Join(dir, typeName+"_string.go")
339 // Run stringer in temporary directory.
340 err = run(t, stringer, "-type", typeName, "-output", stringSource, source)
341 if err != nil {
342 t.Fatal(err)
343 }
344 // Run the binary in the temporary directory.
345 err = run(t, "go", "run", stringSource, source)
346 if err != nil {
347 t.Fatal(err)
348 }
349 }
350
351 // copy copies the from file to the to file.
352 func copy(to, from string) error {
353 toFd, err := os.Create(to)
354 if err != nil {
355 return err
356 }
357 defer toFd.Close()
358 fromFd, err := os.Open(from)
359 if err != nil {
360 return err
361 }
362 defer fromFd.Close()
363 _, err = io.Copy(toFd, fromFd)
364 return err
365 }
366
367 // run runs a single command and returns an error if it does not succeed.
368 // os/exec should have this function, to be honest.
369 func run(t testing.TB, name string, arg ...string) error {
370 t.Helper()
371 return runInDir(t, ".", name, arg...)
372 }
373
374 // runInDir runs a single command in directory dir and returns an error if
375 // it does not succeed.
376 func runInDir(t testing.TB, dir, name string, arg ...string) error {
377 t.Helper()
378 cmd := testenv.Command(t, name, arg...)
379 cmd.Dir = dir
380 out, err := cmd.CombinedOutput()
381 if len(out) > 0 {
382 t.Logf("%s", out)
383 }
384 if err != nil {
385 return fmt.Errorf("%v: %v", cmd, err)
386 }
387 return nil
388 }