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.
5 // go command is not available on android
23 "golang.org/x/tools/internal/testenv"
26 // This file contains a test that compiles and runs each program in testdata
27 // after generating the string method for its type. The rule is that for testdata/x.go
28 // we run stringer -type X and then compile and run the program. The resulting
29 // binary panics if the String method for X is not correct, including for error cases.
31 func TestEndToEnd(t *testing.T) {
32 dir, stringer := buildStringer(t)
33 defer os.RemoveAll(dir)
34 // Read the testdata directory.
35 fd, err := os.Open("testdata")
40 names, err := fd.Readdirnames(-1)
42 t.Fatalf("Readdirnames: %s", err)
44 // Generate, compile, and run the test programs.
45 for _, name := range names {
46 if !strings.HasSuffix(name, ".go") {
47 t.Errorf("%s is not a Go file", name)
50 if strings.HasPrefix(name, "tag_") || strings.HasPrefix(name, "vary_") {
51 // This file is used for tag processing in TestTags or TestConstValueChange, below.
54 if name == "cgo.go" && !build.Default.CgoEnabled {
55 t.Logf("cgo is not enabled for %s", name)
58 // Names are known to be ASCII and long enough.
59 typeName := fmt.Sprintf("%c%s", name[0]+'A'-'a', name[1:len(name)-len(".go")])
60 stringerCompileAndRun(t, dir, stringer, typeName, name)
64 // TestTags verifies that the -tags flag works as advertised.
65 func TestTags(t *testing.T) {
66 dir, stringer := buildStringer(t)
67 defer os.RemoveAll(dir)
69 protectedConst = []byte("TagProtected")
70 output = filepath.Join(dir, "const_string.go")
72 for _, file := range []string{"tag_main.go", "tag_tag.go"} {
73 err := copy(filepath.Join(dir, file), filepath.Join("testdata", file))
78 // Run stringer in the directory that contains the package files.
79 // We cannot run stringer in the current directory for the following reasons:
80 // - Versions of Go earlier than Go 1.11, do not support absolute directories as a pattern.
81 // - When the current directory is inside a go module, the path will not be considered
82 // a valid path to a package.
83 err := runInDir(dir, stringer, "-type", "Const", ".")
87 result, err := ioutil.ReadFile(output)
91 if bytes.Contains(result, protectedConst) {
92 t.Fatal("tagged variable appears in untagged run")
94 err = os.Remove(output)
98 err = runInDir(dir, stringer, "-type", "Const", "-tags", "tag", ".")
102 result, err = ioutil.ReadFile(output)
106 if !bytes.Contains(result, protectedConst) {
107 t.Fatal("tagged variable does not appear in tagged run")
111 // TestConstValueChange verifies that if a constant value changes and
112 // the stringer code is not regenerated, we'll get a compiler error.
113 func TestConstValueChange(t *testing.T) {
114 dir, stringer := buildStringer(t)
115 defer os.RemoveAll(dir)
116 source := filepath.Join(dir, "day.go")
117 err := copy(source, filepath.Join("testdata", "day.go"))
121 stringSource := filepath.Join(dir, "day_string.go")
122 // Run stringer in the directory that contains the package files.
123 err = runInDir(dir, stringer, "-type", "Day", "-output", stringSource)
127 // Run the binary in the temporary directory as a sanity check.
128 err = run("go", "run", stringSource, source)
132 // Overwrite the source file with a version that has changed constants.
133 err = copy(source, filepath.Join("testdata", "vary_day.go"))
137 // Unfortunately different compilers may give different error messages,
138 // so there's no easy way to verify that the build failed specifically
139 // because the constants changed rather than because the vary_day.go
142 // Instead we'll just rely on manual inspection of the polluted test
143 // output. An alternative might be to check that the error output
144 // matches a set of possible error strings emitted by known
146 fmt.Fprintf(os.Stderr, "Note: the following messages should indicate an out-of-bounds compiler error\n")
147 err = run("go", "build", stringSource, source)
149 t.Fatal("unexpected compiler success")
153 // buildStringer creates a temporary directory and installs stringer there.
154 func buildStringer(t *testing.T) (dir string, stringer string) {
156 testenv.NeedsTool(t, "go")
158 dir, err := ioutil.TempDir("", "stringer")
162 stringer = filepath.Join(dir, "stringer.exe")
163 err = run("go", "build", "-o", stringer)
165 t.Fatalf("building stringer: %s", err)
170 // stringerCompileAndRun runs stringer for the named file and compiles and
171 // runs the target binary in directory dir. That binary will panic if the String method is incorrect.
172 func stringerCompileAndRun(t *testing.T, dir, stringer, typeName, fileName string) {
174 t.Logf("run: %s %s\n", fileName, typeName)
175 source := filepath.Join(dir, fileName)
176 err := copy(source, filepath.Join("testdata", fileName))
178 t.Fatalf("copying file to temporary directory: %s", err)
180 stringSource := filepath.Join(dir, typeName+"_string.go")
181 // Run stringer in temporary directory.
182 err = run(stringer, "-type", typeName, "-output", stringSource, source)
186 // Run the binary in the temporary directory.
187 err = run("go", "run", stringSource, source)
193 // copy copies the from file to the to file.
194 func copy(to, from string) error {
195 toFd, err := os.Create(to)
200 fromFd, err := os.Open(from)
205 _, err = io.Copy(toFd, fromFd)
209 // run runs a single command and returns an error if it does not succeed.
210 // os/exec should have this function, to be honest.
211 func run(name string, arg ...string) error {
212 return runInDir(".", name, arg...)
215 // runInDir runs a single command in directory dir and returns an error if
216 // it does not succeed.
217 func runInDir(dir, name string, arg ...string) error {
218 cmd := exec.Command(name, arg...)
220 cmd.Stdout = os.Stdout
221 cmd.Stderr = os.Stderr
222 cmd.Env = append(os.Environ(), "GO111MODULE=auto")