File: paths_unix_test.go

package info (click to toggle)
elvish 0.21.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,372 kB
  • sloc: javascript: 236; sh: 130; python: 104; makefile: 88; xml: 9
file content (67 lines) | stat: -rw-r--r-- 1,808 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//go:build unix

package shell

import (
	"fmt"
	"os"
	"path/filepath"
	"testing"

	"src.elv.sh/pkg/env"
	"src.elv.sh/pkg/testutil"
)

var elvishDashUID = fmt.Sprintf("elvish-%d", os.Getuid())

func TestSecureRunDir_PrefersXDGWhenNeitherExists(t *testing.T) {
	xdg, _ := setupForSecureRunDir(t)
	testSecureRunDir(t, filepath.Join(xdg, "elvish"), false)
}

func TestSecureRunDir_PrefersXDGWhenBothExist(t *testing.T) {
	xdg, tmp := setupForSecureRunDir(t)

	os.MkdirAll(filepath.Join(xdg, "elvish"), 0700)
	os.MkdirAll(filepath.Join(tmp, elvishDashUID), 0700)

	testSecureRunDir(t, filepath.Join(xdg, "elvish"), false)
}

func TestSecureRunDir_PrefersTmpWhenOnlyItExists(t *testing.T) {
	_, tmp := setupForSecureRunDir(t)

	os.MkdirAll(filepath.Join(tmp, elvishDashUID), 0700)

	testSecureRunDir(t, filepath.Join(tmp, elvishDashUID), false)
}

func TestSecureRunDir_PrefersTmpWhenXdgEnvIsEmpty(t *testing.T) {
	_, tmp := setupForSecureRunDir(t)
	os.Setenv(env.XDG_RUNTIME_DIR, "")
	testSecureRunDir(t, filepath.Join(tmp, elvishDashUID), false)
}

func TestSecureRunDir_ReturnsErrorWhenUnableToMkdir(t *testing.T) {
	xdg, _ := setupForSecureRunDir(t)
	os.WriteFile(filepath.Join(xdg, "elvish"), nil, 0600)
	testSecureRunDir(t, "", true)
}

func setupForSecureRunDir(c testutil.Cleanuper) (xdgRuntimeDir, tmpDir string) {
	xdg := testutil.Setenv(c, env.XDG_RUNTIME_DIR, testutil.TempDir(c))
	tmp := testutil.Setenv(c, "TMPDIR", testutil.TempDir(c))
	return xdg, tmp
}

func testSecureRunDir(t *testing.T, wantRunDir string, wantErr bool) {
	runDir, err := secureRunDir()
	if runDir != wantRunDir {
		t.Errorf("got rundir %q, want %q", runDir, wantRunDir)
	}
	if wantErr && err == nil {
		t.Errorf("got nil err, want non-nil")
	} else if !wantErr && err != nil {
		t.Errorf("got err %v, want nil err", err)
	}
}