github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/cmds/core/elvish/eval/chdir_test.go (about)

     1  package eval
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/u-root/u-root/cmds/core/elvish/parse"
     8  	"github.com/u-root/u-root/cmds/core/elvish/util"
     9  )
    10  
    11  type testAddDirer func(string, float64) error
    12  
    13  func (t testAddDirer) AddDir(dir string, weight float64) error {
    14  	return t(dir, weight)
    15  }
    16  
    17  func TestChdir(t *testing.T) {
    18  	inWithTempDir(func(pwd, dst string) {
    19  		ev := NewEvaler()
    20  
    21  		argDirInBefore, argDirInAfter := "", ""
    22  		ev.AddBeforeChdir(func(dir string) { argDirInBefore = dir })
    23  		ev.AddAfterChdir(func(dir string) { argDirInAfter = dir })
    24  
    25  		err := ev.Chdir(dst)
    26  
    27  		if err != nil {
    28  			t.Errorf("Chdir => error %v", err)
    29  		}
    30  		if envPwd := os.Getenv("PWD"); envPwd != dst {
    31  			t.Errorf("$PWD is %q after Chdir, want %q", envPwd, dst)
    32  		}
    33  
    34  		if argDirInBefore != dst {
    35  			t.Errorf("Chdir called before-hook with %q, want %q",
    36  				argDirInBefore, dst)
    37  		}
    38  		if argDirInAfter != dst {
    39  			t.Errorf("Chdir called before-hook with %q, want %q",
    40  				argDirInAfter, dst)
    41  		}
    42  	})
    43  }
    44  
    45  func TestChdirElvishHooks(t *testing.T) {
    46  	inWithTempDir(func(pwd, dst string) {
    47  		runTests(t, []Test{
    48  			That(`
    49  			dir-in-before dir-in-after = '' ''
    50  			@before-chdir = [dst]{ dir-in-before = $dst }
    51  			@after-chdir  = [dst]{ dir-in-after  = $dst }
    52  			cd `+parse.Quote(dst)+`
    53  			put $dir-in-before $dir-in-after
    54  			`).Puts(dst, dst),
    55  		})
    56  	})
    57  }
    58  
    59  func TestChdirError(t *testing.T) {
    60  	util.InTempDir(func(pwd string) {
    61  		ev := NewEvaler()
    62  		err := ev.Chdir("i/dont/exist")
    63  		if err == nil {
    64  			t.Errorf("Chdir => no error when dir does not exist")
    65  		}
    66  	})
    67  }
    68  
    69  func inWithTempDir(f func(pwd, other string)) {
    70  	util.InTempDir(func(pwd string) {
    71  		util.WithTempDir(func(other string) {
    72  			f(pwd, other)
    73  		})
    74  	})
    75  }