cli/pkg/cmdutil/factory_test.go
Eng Zer Jun 471cbea4fa
test: use t.Setenv to set env vars in tests (#6333)
This commit replaces `os.Setenv` with `t.Setenv` in tests. The
environment variable is automatically restored to its original value
when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.Setenv
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2022-09-26 08:46:02 +00:00

56 lines
1.4 KiB
Go

package cmdutil
import (
"os"
"path/filepath"
"strings"
"testing"
)
func Test_executable(t *testing.T) {
testExe, err := os.Executable()
if err != nil {
t.Fatal(err)
}
testExeName := filepath.Base(testExe)
// Create 3 extra PATH entries that each contain an executable with the same name as the running test
// process. The first is a symlink, but to an unrelated executable, the second is a symlink to our test
// process and thus represents the result we want, and the third one is an unrelated executable.
dir := t.TempDir()
bin1 := filepath.Join(dir, "bin1")
bin1Exe := filepath.Join(bin1, testExeName)
bin2 := filepath.Join(dir, "bin2")
bin2Exe := filepath.Join(bin2, testExeName)
bin3 := filepath.Join(dir, "bin3")
bin3Exe := filepath.Join(bin3, testExeName)
if err := os.MkdirAll(bin1, 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(bin2, 0755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(bin3, 0755); err != nil {
t.Fatal(err)
}
if f, err := os.OpenFile(bin3Exe, os.O_CREATE, 0755); err == nil {
f.Close()
} else {
t.Fatal(err)
}
if err := os.Symlink(testExe, bin2Exe); err != nil {
t.Fatal(err)
}
if err := os.Symlink(bin3Exe, bin1Exe); err != nil {
t.Fatal(err)
}
oldPath := os.Getenv("PATH")
t.Setenv("PATH", strings.Join([]string{bin1, bin2, bin3, oldPath}, string(os.PathListSeparator)))
if got := executable(""); got != bin2Exe {
t.Errorf("executable() = %q, want %q", got, bin2Exe)
}
}