github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/misc/cgo/testgodefs/testgodefs_test.go (about)

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