-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglobals_test.go
More file actions
113 lines (101 loc) · 2.46 KB
/
globals_test.go
File metadata and controls
113 lines (101 loc) · 2.46 KB
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
110
111
112
113
package pathlib_test
import (
"fmt"
"os"
"runtime"
"strings"
"testing"
"github.com/skalt/pathlib.go"
)
func ExampleUserHomeDir() {
homeDir := expect(pathlib.UserHomeDir())
fmt.Println(os.Getenv("HOME") == string(homeDir))
// Output:
// true
}
func ExampleUserCacheDir() {
stash := os.Getenv("XDG_CACHE_HOME")
defer func() {
_ = os.Setenv("XDG_CACHE_HOME", stash)
}()
fmt.Println("On Unix:")
{ // UserCacheDir() returns $XDG_CACHE_HOME if it's set
expected := "/example/.cache"
if err := os.Setenv("XDG_CACHE_HOME", expected); err != nil {
panic(err)
}
actual := expect(pathlib.UserCacheDir())
fmt.Printf("$XDG_CACHE_HOME: %q\n", expected)
fmt.Printf("UserCacheDir()): %q\n", actual)
}
{ // if $XDG_CACHE_HOME is unset, return the OS-specific default.
if err := os.Unsetenv("XDG_CACHE_HOME"); err != nil {
panic(err)
}
home := expect(pathlib.UserHomeDir())
actual := strings.Replace(
expect(pathlib.UserCacheDir()).String(),
home.String(),
"$HOME",
1,
)
fmt.Printf("$XDG_CACHE_HOME: %q\n", os.Getenv("XDG_CACHE_HOME"))
fmt.Printf("UserCacheDir()): %q\n", actual)
}
// Output:
// On Unix:
// $XDG_CACHE_HOME: "/example/.cache"
// UserCacheDir()): "/example/.cache"
// $XDG_CACHE_HOME: ""
// UserCacheDir()): "$HOME/.cache"
}
func ExampleUserConfigDir() {
stash := os.Getenv("XDG_CONFIG_HOME")
home := expect(pathlib.UserHomeDir())
defer func() {
_ = os.Setenv("XDG_CONFIG_HOME", stash)
}()
checkOutput := func(expected string) {
_ = os.Setenv("XDG_CONFIG_HOME", expected)
xdg_config_home := os.Getenv("XDG_CONFIG_HOME")
val, err := pathlib.UserConfigDir()
if err == nil {
fmt.Printf(
"%q => %q\n",
xdg_config_home,
strings.Replace(val.String(), home.String(), "$HOME", 1),
)
} else {
fmt.Printf("%q => Err(%q)\n", xdg_config_home, err.Error())
}
}
fmt.Println("On Unix")
checkOutput("/foo/bar")
checkOutput("")
checkOutput("./my_config")
// Output:
// On Unix
// "/foo/bar" => "/foo/bar"
// "" => "$HOME/.config"
// "./my_config" => Err("path in $XDG_CONFIG_HOME is relative")
}
func unsetHome(t *testing.T) {
t.Helper()
homeVar := "HOME"
switch runtime.GOOS {
case "windows":
homeVar = "USERPROFILE"
case "plan9":
homeVar = "home"
case "js", "wasip1":
t.Skip("Skipping on " + runtime.GOOS)
}
t.Setenv(homeVar, "")
}
func TestUserHomeDir(t *testing.T) {
unsetHome(t)
_, err := pathlib.UserHomeDir()
if err == nil {
t.Fatal("expected error when $HOME is unset")
}
}