2020-09-03 13:48:39 +08:00
|
|
|
package eval_test
|
2017-12-23 07:03:22 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
|
2021-01-27 09:28:38 +08:00
|
|
|
"src.elv.sh/pkg/env"
|
|
|
|
. "src.elv.sh/pkg/eval"
|
2022-06-21 03:29:14 +08:00
|
|
|
"src.elv.sh/pkg/must"
|
2021-01-27 09:28:38 +08:00
|
|
|
"src.elv.sh/pkg/testutil"
|
2017-12-23 07:03:22 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestChdir(t *testing.T) {
|
2021-08-07 05:18:09 +08:00
|
|
|
dst := testutil.TempDir(t)
|
2017-12-23 07:03:22 +08:00
|
|
|
|
2018-10-12 11:02:14 +08:00
|
|
|
ev := NewEvaler()
|
2017-12-23 07:03:22 +08:00
|
|
|
|
2018-10-12 11:02:14 +08:00
|
|
|
argDirInBefore, argDirInAfter := "", ""
|
2022-06-19 02:01:31 +08:00
|
|
|
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
|
|
|
|
2019-03-19 06:25:08 +08:00
|
|
|
back := saveWd()
|
|
|
|
defer back()
|
|
|
|
|
2018-10-12 11:02:14 +08:00
|
|
|
err := ev.Chdir(dst)
|
2017-12-23 07:03:22 +08:00
|
|
|
|
2018-10-12 11:02:14 +08:00
|
|
|
if err != nil {
|
|
|
|
t.Errorf("Chdir => error %v", err)
|
|
|
|
}
|
2020-08-16 21:12:48 +08:00
|
|
|
if envPwd := os.Getenv(env.PWD); envPwd != dst {
|
2018-10-12 11:02:14 +08:00
|
|
|
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 TestChdirError(t *testing.T) {
|
2021-08-07 05:18:09 +08:00
|
|
|
testutil.InTempDir(t)
|
2018-10-12 11:02:14 +08:00
|
|
|
|
|
|
|
ev := NewEvaler()
|
|
|
|
err := ev.Chdir("i/dont/exist")
|
|
|
|
if err == nil {
|
|
|
|
t.Errorf("Chdir => no error when dir does not exist")
|
|
|
|
}
|
2018-03-22 04:51:08 +08:00
|
|
|
}
|
|
|
|
|
2019-03-19 06:25:08 +08:00
|
|
|
// 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() {
|
2022-06-21 03:29:14 +08:00
|
|
|
must.Chdir(wd)
|
2018-10-12 11:02:14 +08:00
|
|
|
}
|
2017-12-23 07:23:52 +08:00
|
|
|
}
|