pkg_test.go 1.9 KB

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