Source file misc/cgo/testgodefs/testgodefs_test.go

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

View as plain text