/
custom_root.go
109 lines (81 loc) · 2.42 KB
/
custom_root.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package testlib
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/9seconds/chore/internal/paths"
"github.com/adrg/xdg"
"github.com/stretchr/testify/require"
)
const (
defaultDirPermission = 0o700
defaultScriptPermission = 0o700
defaultConfigPermission = 0o600
)
type CustomRootTestSuite struct {
fsRoot string
t *testing.T
}
func (suite *CustomRootTestSuite) Setup(t *testing.T) {
t.Helper()
suite.t = t
suite.fsRoot = t.TempDir()
t.Setenv("TMPDIR", suite.fsRoot)
oldConfigHome := xdg.ConfigHome
oldDataHome := xdg.DataHome
oldCacheHome := xdg.CacheHome
oldStateHome := xdg.StateHome
oldRuntimeDir := xdg.RuntimeDir
t.Cleanup(func() {
xdg.ConfigHome = oldConfigHome
xdg.DataHome = oldDataHome
xdg.CacheHome = oldCacheHome
xdg.StateHome = oldStateHome
xdg.RuntimeDir = oldRuntimeDir
paths.TempDirCleanup()
})
xdg.ConfigHome = filepath.Join(suite.fsRoot, "config_home")
xdg.DataHome = filepath.Join(suite.fsRoot, "data_home")
xdg.CacheHome = filepath.Join(suite.fsRoot, "cache_home")
xdg.StateHome = filepath.Join(suite.fsRoot, "state_home")
xdg.RuntimeDir = filepath.Join(suite.fsRoot, "runtime_dir")
}
func (suite *CustomRootTestSuite) RootPath() string {
return suite.fsRoot
}
func (suite *CustomRootTestSuite) EnsureDir(path string) string {
suite.t.Helper()
require.NoError(suite.t, paths.EnsureDir(path))
return path
}
func (suite *CustomRootTestSuite) EnsureFile(path, content string, mode os.FileMode) string {
suite.t.Helper()
require.NoError(suite.t, paths.EnsureFile(path, content))
require.NoError(suite.t, os.Chmod(path, mode))
return path
}
func (suite *CustomRootTestSuite) EnsureScript(namespace, executable, content string) string {
suite.t.Helper()
content = "#!/usr/bin/env bash\nset -eu -o pipefail\n" + content
path := paths.ConfigNamespaceScript(namespace, executable)
suite.EnsureFile(path, content, defaultScriptPermission)
return path
}
func (suite *CustomRootTestSuite) EnsureScriptConfig(namespace, executable string, content interface{}) string {
suite.t.Helper()
strContent := ""
switch val := content.(type) {
case string:
strContent = val
case []byte:
strContent = string(val)
default:
data, err := json.Marshal(content)
strContent = string(data)
require.NoError(suite.t, err)
}
path := paths.ConfigNamespaceScriptConfig(namespace, executable)
suite.EnsureFile(path, strContent, defaultConfigPermission)
return path
}