github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/eval/pwd_test.go (about)

     1  package eval_test
     2  
     3  import (
     4  	"errors"
     5  	"path/filepath"
     6  	"runtime"
     7  	"testing"
     8  
     9  	. "github.com/markusbkk/elvish/pkg/eval"
    10  	"github.com/markusbkk/elvish/pkg/testutil"
    11  
    12  	. "github.com/markusbkk/elvish/pkg/eval/evaltest"
    13  	"github.com/markusbkk/elvish/pkg/eval/vars"
    14  )
    15  
    16  func TestBuiltinPwd(t *testing.T) {
    17  	tmpHome := testutil.InTempHome(t)
    18  
    19  	testutil.MustMkdirAll("dir1")
    20  	testutil.MustMkdirAll("dir2")
    21  	dir1 := filepath.Join(tmpHome, "dir1")
    22  	dir2 := filepath.Join(tmpHome, "dir2")
    23  
    24  	Test(t,
    25  		That(`pwd=dir1 put $pwd; put $pwd`).Puts(dir1, tmpHome),
    26  		That(`pwd=(num 1) put $pwd`).Throws(vars.ErrPathMustBeString, "pwd"),
    27  	)
    28  
    29  	// We could separate these two test variants into separate unit test
    30  	// modules but that's overkill for this situation and makes the
    31  	// equivalence between the two environments harder to see.
    32  	if runtime.GOOS == "windows" {
    33  		Test(t,
    34  			That(`cd $E:HOME\dir2; pwd=$E:HOME put $pwd; put $pwd`).Puts(tmpHome, dir2),
    35  			That(`cd $E:HOME\dir2; pwd=..\dir1 put $pwd; put $pwd`).Puts(dir1, dir2),
    36  			That(`cd $E:HOME\dir1; pwd=..\dir2 put $pwd; put $pwd`).Puts(dir2, dir1),
    37  		)
    38  	} else {
    39  		Test(t,
    40  			That(`cd ~/dir2; pwd=~ put $pwd; put $pwd`).Puts(tmpHome, dir2),
    41  			That(`cd ~/dir2; pwd=~/dir1 put $pwd; put $pwd`).Puts(dir1, dir2),
    42  			That(`cd ~/dir1; pwd=../dir2 put $pwd; put $pwd`).Puts(dir2, dir1),
    43  		)
    44  	}
    45  }
    46  
    47  // Verify the behavior when the CWD cannot be determined.
    48  func TestBuiltinPwd_GetwdError(t *testing.T) {
    49  	origGetwd := Getwd
    50  	Getwd = mockGetwdWithError
    51  	defer func() { Getwd = origGetwd }()
    52  
    53  	Test(t,
    54  		That(`put $pwd`).Puts("/unknown/pwd"),
    55  	)
    56  }
    57  
    58  func mockGetwdWithError() (string, error) {
    59  	return "", errors.New("cwd unknown")
    60  }