Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / golang.org / x / tools@v0.0.0-20201105173854-bc9fc8d8c4bc / cmd / stringer / endtoend_test.go
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 // +build !android
8
9 package main
10
11 import (
12         "bytes"
13         "fmt"
14         "go/build"
15         "io"
16         "io/ioutil"
17         "os"
18         "os/exec"
19         "path/filepath"
20         "strings"
21         "testing"
22
23         "golang.org/x/tools/internal/testenv"
24 )
25
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.
30
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")
36         if err != nil {
37                 t.Fatal(err)
38         }
39         defer fd.Close()
40         names, err := fd.Readdirnames(-1)
41         if err != nil {
42                 t.Fatalf("Readdirnames: %s", err)
43         }
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)
48                         continue
49                 }
50                 if strings.HasPrefix(name, "tag_") || strings.HasPrefix(name, "vary_") {
51                         // This file is used for tag processing in TestTags or TestConstValueChange, below.
52                         continue
53                 }
54                 if name == "cgo.go" && !build.Default.CgoEnabled {
55                         t.Logf("cgo is not enabled for %s", name)
56                         continue
57                 }
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)
61         }
62 }
63
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)
68         var (
69                 protectedConst = []byte("TagProtected")
70                 output         = filepath.Join(dir, "const_string.go")
71         )
72         for _, file := range []string{"tag_main.go", "tag_tag.go"} {
73                 err := copy(filepath.Join(dir, file), filepath.Join("testdata", file))
74                 if err != nil {
75                         t.Fatal(err)
76                 }
77         }
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", ".")
84         if err != nil {
85                 t.Fatal(err)
86         }
87         result, err := ioutil.ReadFile(output)
88         if err != nil {
89                 t.Fatal(err)
90         }
91         if bytes.Contains(result, protectedConst) {
92                 t.Fatal("tagged variable appears in untagged run")
93         }
94         err = os.Remove(output)
95         if err != nil {
96                 t.Fatal(err)
97         }
98         err = runInDir(dir, stringer, "-type", "Const", "-tags", "tag", ".")
99         if err != nil {
100                 t.Fatal(err)
101         }
102         result, err = ioutil.ReadFile(output)
103         if err != nil {
104                 t.Fatal(err)
105         }
106         if !bytes.Contains(result, protectedConst) {
107                 t.Fatal("tagged variable does not appear in tagged run")
108         }
109 }
110
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"))
118         if err != nil {
119                 t.Fatal(err)
120         }
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)
124         if err != nil {
125                 t.Fatal(err)
126         }
127         // Run the binary in the temporary directory as a sanity check.
128         err = run("go", "run", stringSource, source)
129         if err != nil {
130                 t.Fatal(err)
131         }
132         // Overwrite the source file with a version that has changed constants.
133         err = copy(source, filepath.Join("testdata", "vary_day.go"))
134         if err != nil {
135                 t.Fatal(err)
136         }
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
140         // file is invalid.
141         //
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
145         // Go compilers.
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)
148         if err == nil {
149                 t.Fatal("unexpected compiler success")
150         }
151 }
152
153 // buildStringer creates a temporary directory and installs stringer there.
154 func buildStringer(t *testing.T) (dir string, stringer string) {
155         t.Helper()
156         testenv.NeedsTool(t, "go")
157
158         dir, err := ioutil.TempDir("", "stringer")
159         if err != nil {
160                 t.Fatal(err)
161         }
162         stringer = filepath.Join(dir, "stringer.exe")
163         err = run("go", "build", "-o", stringer)
164         if err != nil {
165                 t.Fatalf("building stringer: %s", err)
166         }
167         return dir, stringer
168 }
169
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) {
173         t.Helper()
174         t.Logf("run: %s %s\n", fileName, typeName)
175         source := filepath.Join(dir, fileName)
176         err := copy(source, filepath.Join("testdata", fileName))
177         if err != nil {
178                 t.Fatalf("copying file to temporary directory: %s", err)
179         }
180         stringSource := filepath.Join(dir, typeName+"_string.go")
181         // Run stringer in temporary directory.
182         err = run(stringer, "-type", typeName, "-output", stringSource, source)
183         if err != nil {
184                 t.Fatal(err)
185         }
186         // Run the binary in the temporary directory.
187         err = run("go", "run", stringSource, source)
188         if err != nil {
189                 t.Fatal(err)
190         }
191 }
192
193 // copy copies the from file to the to file.
194 func copy(to, from string) error {
195         toFd, err := os.Create(to)
196         if err != nil {
197                 return err
198         }
199         defer toFd.Close()
200         fromFd, err := os.Open(from)
201         if err != nil {
202                 return err
203         }
204         defer fromFd.Close()
205         _, err = io.Copy(toFd, fromFd)
206         return err
207 }
208
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...)
213 }
214
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...)
219         cmd.Dir = dir
220         cmd.Stdout = os.Stdout
221         cmd.Stderr = os.Stderr
222         cmd.Env = append(os.Environ(), "GO111MODULE=auto")
223         return cmd.Run()
224 }