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