github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/misc/cgo/test/pkg_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 cgotest
     6  
     7  import (
     8  	"io/ioutil"
     9  	"os"
    10  	"os/exec"
    11  	"path/filepath"
    12  	"runtime"
    13  	"strings"
    14  	"testing"
    15  )
    16  
    17  // TestCrossPackageTests compiles and runs tests that depend on imports of other
    18  // local packages, using source code stored in the testdata directory.
    19  //
    20  // The tests in the misc directory tree do not have a valid import path in
    21  // GOPATH mode, so they previously used relative imports. However, relative
    22  // imports do not work in module mode. In order to make the test work in both
    23  // modes, we synthesize a GOPATH in which the module paths are equivalent, and
    24  // run the tests as a subprocess.
    25  //
    26  // If and when we no longer support these tests in GOPATH mode, we can remove
    27  // this shim and move the tests currently located in testdata back into the
    28  // parent directory.
    29  func TestCrossPackageTests(t *testing.T) {
    30  	switch runtime.GOOS {
    31  	case "android":
    32  		t.Skip("Can't exec cmd/go subprocess on Android.")
    33  	case "darwin":
    34  		switch runtime.GOARCH {
    35  		case "arm", "arm64":
    36  			t.Skip("Can't exec cmd/go subprocess on iOS.")
    37  		}
    38  	}
    39  
    40  	GOPATH, err := ioutil.TempDir("", "cgotest")
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  	defer os.RemoveAll(GOPATH)
    45  
    46  	modRoot := filepath.Join(GOPATH, "src", "cgotest")
    47  	if err := overlayDir(modRoot, "testdata"); err != nil {
    48  		t.Fatal(err)
    49  	}
    50  	if err := ioutil.WriteFile(filepath.Join(modRoot, "go.mod"), []byte("module cgotest\n"), 0666); err != nil {
    51  		t.Fatal(err)
    52  	}
    53  
    54  	cmd := exec.Command("go", "test")
    55  	if testing.Verbose() {
    56  		cmd.Args = append(cmd.Args, "-v")
    57  	}
    58  	if testing.Short() {
    59  		cmd.Args = append(cmd.Args, "-short")
    60  	}
    61  	cmd.Dir = modRoot
    62  	cmd.Env = append(os.Environ(), "GOPATH="+GOPATH, "PWD="+cmd.Dir)
    63  	out, err := cmd.CombinedOutput()
    64  	if err == nil {
    65  		t.Logf("%s:\n%s", strings.Join(cmd.Args, " "), out)
    66  	} else {
    67  		t.Fatalf("%s: %s\n%s", strings.Join(cmd.Args, " "), err, out)
    68  	}
    69  }