github.com/kolbycrouch/elvish@v0.14.1-0.20210614162631-215b9ac1c423/pkg/shell/shell_test.go (about)

     1  package shell
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"src.elv.sh/pkg/env"
     8  	. "src.elv.sh/pkg/prog/progtest"
     9  )
    10  
    11  func TestShell_SHLVL_NormalCase(t *testing.T) {
    12  	restore := saveEnv(env.SHLVL)
    13  	defer restore()
    14  
    15  	os.Setenv(env.SHLVL, "10")
    16  	testSHLVL(t, "11")
    17  }
    18  
    19  func TestShell_SHLVL_Unset(t *testing.T) {
    20  	restore := saveEnv(env.SHLVL)
    21  	defer restore()
    22  
    23  	os.Unsetenv(env.SHLVL)
    24  	testSHLVL(t, "1")
    25  }
    26  
    27  func TestShell_SHLVL_Invalid(t *testing.T) {
    28  	restore := saveEnv(env.SHLVL)
    29  	defer restore()
    30  
    31  	os.Setenv(env.SHLVL, "invalid")
    32  	testSHLVL(t, "1")
    33  }
    34  
    35  func TestShell_NegativeSHLVL_Increments(t *testing.T) {
    36  	// Other shells don't agree what the behavior should be:
    37  	//
    38  	// ~> E:SHLVL=-100 bash -c 'echo $SHLVL'
    39  	// 0
    40  	// ~> E:SHLVL=-100 zsh -c 'echo $SHLVL'
    41  	// -99
    42  	// ~> E:SHLVL=-100 fish -c 'echo $SHLVL'
    43  	// 1
    44  	//
    45  	// Elvish follows Zsh here.
    46  	restore := saveEnv(env.SHLVL)
    47  	defer restore()
    48  
    49  	os.Setenv(env.SHLVL, "-100")
    50  	testSHLVL(t, "-99")
    51  }
    52  
    53  func testSHLVL(t *testing.T, wantSHLVL string) {
    54  	t.Helper()
    55  	f := Setup()
    56  	defer f.Cleanup()
    57  
    58  	oldValue, oldOK := os.LookupEnv(env.SHLVL)
    59  
    60  	Script(f.Fds(), []string{"print $E:SHLVL"}, &ScriptConfig{Cmd: true})
    61  	f.TestOut(t, 1, wantSHLVL)
    62  	f.TestOut(t, 2, "")
    63  
    64  	// Test that state of SHLVL is restored.
    65  	newValue, newOK := os.LookupEnv(env.SHLVL)
    66  	if newValue != oldValue {
    67  		t.Errorf("SHLVL not restored, %q -> %q", oldValue, newValue)
    68  	}
    69  	if oldOK != newOK {
    70  		t.Errorf("SHLVL existence not restored, %v -> %v", oldOK, newOK)
    71  	}
    72  }