1 // Copyright 2019 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.
17 // We are testing cgo -godefs, which translates Go files that use
18 // import "C" into Go files with Go definitions of types defined in the
19 // import "C" block. Add more tests here.
20 var filePrefixes = []string{
32 func TestGoDefs(t *testing.T) {
33 testdata, err := filepath.Abs("testdata")
38 gopath, err := os.MkdirTemp("", "testgodefs-gopath")
42 defer os.RemoveAll(gopath)
44 dir := filepath.Join(gopath, "src", "testgodefs")
45 if err := os.MkdirAll(dir, 0755); err != nil {
49 for _, fp := range filePrefixes {
50 cmd := exec.Command("go", "tool", "cgo",
55 cmd.Stderr = new(bytes.Buffer)
57 out, err := cmd.Output()
59 t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr)
63 if err := os.WriteFile(filepath.Join(dir, fn), out, 0644); err != nil {
67 // Verify that command line arguments are not rewritten in the generated comment,
68 // see go.dev/issue/52063
69 hasGeneratedByComment := false
70 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
72 if runtime.GOOS == "windows" {
75 if !strings.HasPrefix(line, "// "+cgoExe+" -godefs") {
78 if want := "// " + cgoExe + " " + strings.Join(cmd.Args[3:], " "); line != want {
79 t.Errorf("%s: got generated comment %q, want %q", fn, line, want)
81 hasGeneratedByComment = true
85 if !hasGeneratedByComment {
86 t.Errorf("%s: comment with generating cgo -godefs command not found", fn)
90 main, err := os.ReadFile(filepath.Join("testdata", "main.go"))
94 if err := os.WriteFile(filepath.Join(dir, "main.go"), main, 0644); err != nil {
98 if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module testgodefs\ngo 1.14\n"), 0644); err != nil {
102 // Use 'go run' to build and run the resulting binary in a single step,
103 // instead of invoking 'go build' and the resulting binary separately, so that
104 // this test can pass on mobile builders, which do not copy artifacts back
105 // from remote invocations.
106 cmd := exec.Command("go", "run", ".")
107 cmd.Env = append(os.Environ(), "GOPATH="+gopath)
109 if out, err := cmd.CombinedOutput(); err != nil {
110 t.Fatalf("%s [%s]: %v\n%s", strings.Join(cmd.Args, " "), dir, err, out)