-
Notifications
You must be signed in to change notification settings - Fork 22
/
helpers_test.go
72 lines (59 loc) · 1.16 KB
/
helpers_test.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
package gta
import (
"os"
"strings"
"testing"
)
// Setenv sets an environment variable, name, to value and returns a function
// to restore the environment variable to its former value.
func Setenv(t *testing.T, name, value string) func() {
t.Helper()
orig, ok := os.LookupEnv(name)
if err := os.Setenv(name, value); err != nil {
t.Fatal(err)
}
return func() {
if !ok {
if err := os.Unsetenv(name); err != nil {
t.Fatal(err)
}
return
}
if err := os.Setenv(name, orig); err != nil {
t.Fatal(err)
}
}
}
func AllSetenv(t *testing.T, env []string) func() {
t.Helper()
var fns []func()
for _, v := range env {
parts := strings.SplitN(v, "=", 2)
fn := Setenv(t, parts[0], parts[1])
fns = append(fns, fn)
}
return func() {
for _, f := range fns {
f()
}
}
}
// chdir changes to dir and returns a function that will restore the current
// working directory to its previous value.
func chdir(t *testing.T, dir string) func() {
t.Helper()
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
err = os.Chdir(dir)
if err != nil {
t.Fatal(err)
}
return func() {
err = os.Chdir(wd)
if err != nil {
t.Fatal(err)
}
}
}