github.com/kvattikuti/drone@v0.2.1-0.20140603034306-d400229a327a/Godeps/_workspace/src/bitbucket.org/kardianos/osext/osext_test.go (about)

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