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

     1  //go:build !windows && !plan9
     2  // +build !windows,!plan9
     3  
     4  package shell
     5  
     6  import (
     7  	"fmt"
     8  	"os"
     9  	"path/filepath"
    10  	"testing"
    11  
    12  	"github.com/markusbkk/elvish/pkg/env"
    13  	"github.com/markusbkk/elvish/pkg/testutil"
    14  )
    15  
    16  var elvishDashUID = fmt.Sprintf("elvish-%d", os.Getuid())
    17  
    18  func TestSecureRunDir_PrefersXDGWhenNeitherExists(t *testing.T) {
    19  	xdg, _ := setupForSecureRunDir(t)
    20  	testSecureRunDir(t, filepath.Join(xdg, "elvish"), false)
    21  }
    22  
    23  func TestSecureRunDir_PrefersXDGWhenBothExist(t *testing.T) {
    24  	xdg, tmp := setupForSecureRunDir(t)
    25  
    26  	os.MkdirAll(filepath.Join(xdg, "elvish"), 0700)
    27  	os.MkdirAll(filepath.Join(tmp, elvishDashUID), 0700)
    28  
    29  	testSecureRunDir(t, filepath.Join(xdg, "elvish"), false)
    30  }
    31  
    32  func TestSecureRunDir_PrefersTmpWhenOnlyItExists(t *testing.T) {
    33  	_, tmp := setupForSecureRunDir(t)
    34  
    35  	os.MkdirAll(filepath.Join(tmp, elvishDashUID), 0700)
    36  
    37  	testSecureRunDir(t, filepath.Join(tmp, elvishDashUID), false)
    38  }
    39  
    40  func TestSecureRunDir_PrefersTmpWhenXdgEnvIsEmpty(t *testing.T) {
    41  	_, tmp := setupForSecureRunDir(t)
    42  	os.Setenv(env.XDG_RUNTIME_DIR, "")
    43  	testSecureRunDir(t, filepath.Join(tmp, elvishDashUID), false)
    44  }
    45  
    46  func TestSecureRunDir_ReturnsErrorWhenUnableToMkdir(t *testing.T) {
    47  	xdg, _ := setupForSecureRunDir(t)
    48  	os.WriteFile(filepath.Join(xdg, "elvish"), nil, 0600)
    49  	testSecureRunDir(t, "", true)
    50  }
    51  
    52  func setupForSecureRunDir(c testutil.Cleanuper) (xdgRuntimeDir, tmpDir string) {
    53  	xdg := testutil.Setenv(c, env.XDG_RUNTIME_DIR, testutil.TempDir(c))
    54  	tmp := testutil.Setenv(c, "TMPDIR", testutil.TempDir(c))
    55  	return xdg, tmp
    56  }
    57  
    58  func testSecureRunDir(t *testing.T, wantRunDir string, wantErr bool) {
    59  	runDir, err := secureRunDir()
    60  	if runDir != wantRunDir {
    61  		t.Errorf("got rundir %q, want %q", runDir, wantRunDir)
    62  	}
    63  	if wantErr && err == nil {
    64  		t.Errorf("got nil err, want non-nil")
    65  	} else if !wantErr && err != nil {
    66  		t.Errorf("got err %v, want nil err", err)
    67  	}
    68  }