paths_unix_test.go 1.8 KB

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