osext_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2012 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. // +build darwin linux freebsd netbsd windows
  5. package osext
  6. import (
  7. "fmt"
  8. "os"
  9. oexec "os/exec"
  10. "path/filepath"
  11. "runtime"
  12. "testing"
  13. )
  14. const execPath_EnvVar = "OSTEST_OUTPUT_EXECPATH"
  15. func TestExecPath(t *testing.T) {
  16. ep, err := Executable()
  17. if err != nil {
  18. t.Fatalf("ExecPath failed: %v", err)
  19. }
  20. // we want fn to be of the form "dir/prog"
  21. dir := filepath.Dir(filepath.Dir(ep))
  22. fn, err := filepath.Rel(dir, ep)
  23. if err != nil {
  24. t.Fatalf("filepath.Rel: %v", err)
  25. }
  26. cmd := &oexec.Cmd{}
  27. // make child start with a relative program path
  28. cmd.Dir = dir
  29. cmd.Path = fn
  30. // forge argv[0] for child, so that we can verify we could correctly
  31. // get real path of the executable without influenced by argv[0].
  32. cmd.Args = []string{"-", "-test.run=XXXX"}
  33. cmd.Env = []string{fmt.Sprintf("%s=1", execPath_EnvVar)}
  34. out, err := cmd.CombinedOutput()
  35. if err != nil {
  36. t.Fatalf("exec(self) failed: %v", err)
  37. }
  38. outs := string(out)
  39. if !filepath.IsAbs(outs) {
  40. t.Fatalf("Child returned %q, want an absolute path", out)
  41. }
  42. if !sameFile(outs, ep) {
  43. t.Fatalf("Child returned %q, not the same file as %q", out, ep)
  44. }
  45. }
  46. func sameFile(fn1, fn2 string) bool {
  47. fi1, err := os.Stat(fn1)
  48. if err != nil {
  49. return false
  50. }
  51. fi2, err := os.Stat(fn2)
  52. if err != nil {
  53. return false
  54. }
  55. return os.SameFile(fi1, fi2)
  56. }
  57. func init() {
  58. if e := os.Getenv(execPath_EnvVar); e != "" {
  59. // first chdir to another path
  60. dir := "/"
  61. if runtime.GOOS == "windows" {
  62. dir = filepath.VolumeName(".")
  63. }
  64. os.Chdir(dir)
  65. if ep, err := Executable(); err != nil {
  66. fmt.Fprint(os.Stderr, "ERROR: ", err)
  67. } else {
  68. fmt.Fprint(os.Stderr, ep)
  69. }
  70. os.Exit(0)
  71. }
  72. }