dispatch/vendor/github.com/mitchellh/go-homedir/homedir_test.go

113 lines
1.6 KiB
Go
Raw Normal View History

2015-06-11 23:09:02 +00:00
package homedir
import (
"fmt"
"os"
"os/user"
"testing"
)
func patchEnv(key, value string) func() {
bck := os.Getenv(key)
deferFunc := func() {
os.Setenv(key, bck)
}
os.Setenv(key, value)
return deferFunc
}
2016-01-15 18:48:03 +00:00
func BenchmarkDir(b *testing.B) {
// We do this for any "warmups"
for i := 0; i < 10; i++ {
Dir()
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
Dir()
}
}
2015-06-11 23:09:02 +00:00
func TestDir(t *testing.T) {
u, err := user.Current()
if err != nil {
t.Fatalf("err: %s", err)
}
dir, err := Dir()
if err != nil {
t.Fatalf("err: %s", err)
}
if u.HomeDir != dir {
t.Fatalf("%#v != %#v", u.HomeDir, dir)
}
}
func TestExpand(t *testing.T) {
u, err := user.Current()
if err != nil {
t.Fatalf("err: %s", err)
}
cases := []struct {
Input string
Output string
Err bool
}{
{
"/foo",
"/foo",
false,
},
{
"~/foo",
fmt.Sprintf("%s/foo", u.HomeDir),
false,
},
{
"",
"",
false,
},
{
"~",
u.HomeDir,
false,
},
{
"~foo/foo",
"",
true,
},
}
for _, tc := range cases {
actual, err := Expand(tc.Input)
if (err != nil) != tc.Err {
t.Fatalf("Input: %#v\n\nErr: %s", tc.Input, err)
}
if actual != tc.Output {
t.Fatalf("Input: %#v\n\nOutput: %#v", tc.Input, actual)
}
}
2016-01-15 18:48:03 +00:00
DisableCache = true
defer func() { DisableCache = false }()
2015-06-11 23:09:02 +00:00
defer patchEnv("HOME", "/custom/path/")()
expected := "/custom/path/foo/bar"
actual, err := Expand("~/foo/bar")
if err != nil {
t.Errorf("No error is expected, got: %v", err)
} else if actual != "/custom/path/foo/bar" {
t.Errorf("Expected: %v; actual: %v", expected, actual)
}
}