| 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. |
| 4 |
|
| 5 |
package testgodefs |
| 6 |
|
| 7 |
import ( |
| 8 |
"bytes" |
| 9 |
"os" |
| 10 |
"os/exec" |
| 11 |
"path/filepath" |
| 12 |
"strings" |
| 13 |
"testing" |
| 14 |
) |
| 15 |
|
| 16 |
// We are testing cgo -godefs, which translates Go files that use |
| 17 |
// import "C" into Go files with Go definitions of types defined in the |
| 18 |
// import "C" block. Add more tests here. |
| 19 |
var filePrefixes = []string{ |
| 20 |
"anonunion", |
| 21 |
"bitfields", |
| 22 |
"issue8478", |
| 23 |
"fieldtypedef", |
| 24 |
"issue37479", |
| 25 |
"issue37621", |
| 26 |
"issue38649", |
| 27 |
"issue39534", |
| 28 |
"issue48396", |
| 29 |
} |
| 30 |
|
| 31 |
func TestGoDefs(t *testing.T) { |
| 32 |
testdata, err := filepath.Abs("testdata") |
| 33 |
if err != nil { |
| 34 |
t.Fatal(err) |
| 35 |
} |
| 36 |
|
| 37 |
gopath, err := os.MkdirTemp("", "testgodefs-gopath") |
| 38 |
if err != nil { |
| 39 |
t.Fatal(err) |
| 40 |
} |
| 41 |
defer os.RemoveAll(gopath) |
| 42 |
|
| 43 |
dir := filepath.Join(gopath, "src", "testgodefs") |
| 44 |
if err := os.MkdirAll(dir, 0755); err != nil { |
| 45 |
t.Fatal(err) |
| 46 |
} |
| 47 |
|
| 48 |
for _, fp := range filePrefixes { |
| 49 |
cmd := exec.Command("go", "tool", "cgo", |
| 50 |
"-godefs", |
| 51 |
"-srcdir", testdata, |
| 52 |
"-objdir", dir, |
| 53 |
fp+".go") |
| 54 |
cmd.Stderr = new(bytes.Buffer) |
| 55 |
|
| 56 |
out, err := cmd.Output() |
| 57 |
if err != nil { |
| 58 |
t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr) |
| 59 |
} |
| 60 |
|
| 61 |
if err := os.WriteFile(filepath.Join(dir, fp+"_defs.go"), out, 0644); err != nil { |
| 62 |
t.Fatal(err) |
| 63 |
} |
| 64 |
} |
| 65 |
|
| 66 |
main, err := os.ReadFile(filepath.Join("testdata", "main.go")) |
| 67 |
if err != nil { |
| 68 |
t.Fatal(err) |
| 69 |
} |
| 70 |
if err := os.WriteFile(filepath.Join(dir, "main.go"), main, 0644); err != nil { |
| 71 |
t.Fatal(err) |
| 72 |
} |
| 73 |
|
| 74 |
if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module testgodefs\ngo 1.14\n"), 0644); err != nil { |
| 75 |
t.Fatal(err) |
| 76 |
} |
| 77 |
|
| 78 |
// Use 'go run' to build and run the resulting binary in a single step, |
| 79 |
// instead of invoking 'go build' and the resulting binary separately, so that |
| 80 |
// this test can pass on mobile builders, which do not copy artifacts back |
| 81 |
// from remote invocations. |
| 82 |
cmd := exec.Command("go", "run", ".") |
| 83 |
cmd.Env = append(os.Environ(), "GOPATH="+gopath) |
| 84 |
cmd.Dir = dir |
| 85 |
if out, err := cmd.CombinedOutput(); err != nil { |
| 86 |
t.Fatalf("%s [%s]: %v\n%s", strings.Join(cmd.Args, " "), dir, err, out) |
| 87 |
} |
| 88 |
} |