elvish/pkg/eval/chdir_test.go

84 lines
1.7 KiB
Go
Raw Normal View History

package eval_test
2017-12-23 07:03:22 +08:00
import (
"os"
"testing"
"src.elv.sh/pkg/env"
. "src.elv.sh/pkg/eval"
. "src.elv.sh/pkg/eval/evaltest"
"src.elv.sh/pkg/must"
"src.elv.sh/pkg/parse"
"src.elv.sh/pkg/testutil"
2017-12-23 07:03:22 +08:00
)
func TestChdir(t *testing.T) {
dst := testutil.TempDir(t)
2017-12-23 07:03:22 +08:00
ev := NewEvaler()
2017-12-23 07:03:22 +08:00
argDirInBefore, argDirInAfter := "", ""
ev.BeforeChdir = append(ev.BeforeChdir, func(dir string) { argDirInBefore = dir })
ev.AfterChdir = append(ev.AfterChdir, func(dir string) { argDirInAfter = dir })
2017-12-23 07:03:22 +08:00
back := saveWd()
defer back()
err := ev.Chdir(dst)
2017-12-23 07:03:22 +08:00
if err != nil {
t.Errorf("Chdir => error %v", err)
}
if envPwd := os.Getenv(env.PWD); envPwd != dst {
t.Errorf("$PWD is %q after Chdir, want %q", envPwd, dst)
}
if argDirInBefore != dst {
t.Errorf("Chdir called before-hook with %q, want %q",
argDirInBefore, dst)
}
if argDirInAfter != dst {
t.Errorf("Chdir called before-hook with %q, want %q",
argDirInAfter, dst)
}
2017-12-23 07:03:22 +08:00
}
2017-12-23 07:23:52 +08:00
func TestChdirElvishHooks(t *testing.T) {
dst := testutil.TempDir(t)
back := saveWd()
defer back()
Test(t,
That(`
var dir-in-before dir-in-after = '' ''
set @before-chdir = {|dst| set dir-in-before = $dst }
set @after-chdir = {|dst| set dir-in-after = $dst }
cd `+parse.Quote(dst)+`
put $dir-in-before $dir-in-after
`).Puts(dst, dst),
)
}
2017-12-23 07:23:52 +08:00
func TestChdirError(t *testing.T) {
testutil.InTempDir(t)
ev := NewEvaler()
err := ev.Chdir("i/dont/exist")
if err == nil {
t.Errorf("Chdir => no error when dir does not exist")
}
}
// Saves the current working directory, and returns a function for returning to
// it.
func saveWd() func() {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
return func() {
must.Chdir(wd)
}
2017-12-23 07:23:52 +08:00
}