github.com/sdibtacm/sandbox@v0.0.0-20200320120712-60470cf803dc/lookpath_test.go (about)

     1  // +build linux
     2  
     3  // Copyright 2011 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import (
    10  	"io/ioutil"
    11  	"os"
    12  	"testing"
    13  )
    14  
    15  var nonExistentPaths = []string{
    16  	"some-non-existent-path",
    17  	"non-existent-path/slashed",
    18  }
    19  
    20  func TestLookPathNotFound(t *testing.T) {
    21  	for _, name := range nonExistentPaths {
    22  		path, err := LookPath(name)
    23  		if err == nil {
    24  			t.Fatalf("LookPath found %q in $PATH", name)
    25  		}
    26  		if path != "" {
    27  			t.Fatalf("LookPath path == %q when err != nil", path)
    28  		}
    29  		perr, ok := err.(*Error)
    30  		if !ok {
    31  			t.Fatal("LookPath error is not an exec.Error")
    32  		}
    33  		if perr.Name != name {
    34  			t.Fatalf("want Error name %q, got %q", name, perr.Name)
    35  		}
    36  	}
    37  }
    38  
    39  func TestLookPathUnixEmptyPath(t *testing.T) {
    40  	tmp, err := ioutil.TempDir("", "TestLookPathUnixEmptyPath")
    41  	if err != nil {
    42  		t.Fatal("TempDir failed: ", err)
    43  	}
    44  	defer os.RemoveAll(tmp)
    45  	wd, err := os.Getwd()
    46  	if err != nil {
    47  		t.Fatal("Getwd failed: ", err)
    48  	}
    49  	err = os.Chdir(tmp)
    50  	if err != nil {
    51  		t.Fatal("Chdir failed: ", err)
    52  	}
    53  	defer os.Chdir(wd)
    54  
    55  	f, err := os.OpenFile("exec_me", os.O_CREATE|os.O_EXCL, 0700)
    56  	if err != nil {
    57  		t.Fatal("OpenFile failed: ", err)
    58  	}
    59  	err = f.Close()
    60  	if err != nil {
    61  		t.Fatal("Close failed: ", err)
    62  	}
    63  
    64  	pathenv := os.Getenv("PATH")
    65  	defer os.Setenv("PATH", pathenv)
    66  
    67  	err = os.Setenv("PATH", "")
    68  	if err != nil {
    69  		t.Fatal("Setenv failed: ", err)
    70  	}
    71  
    72  	path, err := LookPath("exec_me")
    73  	if err == nil {
    74  		t.Fatal("LookPath found exec_me in empty $PATH")
    75  	}
    76  	if path != "" {
    77  		t.Fatalf("LookPath path == %q when err != nil", path)
    78  	}
    79  }