-
-
Notifications
You must be signed in to change notification settings - Fork 184
/
helpers_test.go
137 lines (112 loc) · 2.22 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
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package main
import (
"fmt"
"io"
"net/url"
"os"
"testing"
)
func mustParseURL(urlString string) *url.URL {
u, err := url.Parse(urlString)
if err != nil {
panic(err)
}
return u
}
func captureReader(block func()) (*os.File, *os.File, error) {
rOut, wOut, err := os.Pipe()
if err != nil {
return nil, nil, err
}
defer wOut.Close()
rErr, wErr, err := os.Pipe()
if err != nil {
return nil, nil, err
}
defer wErr.Close()
var stdout, stderr *os.File
os.Stdout, stdout = wOut, os.Stdout
os.Stderr, stderr = wErr, os.Stderr
defer func() {
os.Stdout = stdout
os.Stderr = stderr
}()
block()
wOut.Close()
wErr.Close()
return rOut, rErr, nil
}
func capture(block func()) (string, string, error) {
rOut, rErr, err := captureReader(block)
if err != nil {
return "", "", err
}
defer rOut.Close()
defer rErr.Close()
bufOut, err := io.ReadAll(rOut)
if err != nil {
return "", "", err
}
bufErr, err := io.ReadAll(rErr)
if err != nil {
return "", "", err
}
return string(bufOut), string(bufErr), nil
}
func captureWithInput(in []string, block func()) (string, string, error) {
rIn, wIn, err := os.Pipe()
if err != nil {
return "", "", err
}
defer rIn.Close()
var stdin *os.File
os.Stdin, stdin = rIn, os.Stdin
defer func() { os.Stdin = stdin }()
for _, line := range in {
fmt.Fprintln(wIn, line)
}
wIn.Close()
return capture(block)
}
func newTempDir(t *testing.T) string {
tmpdir, err := os.MkdirTemp("", "ghq-test")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(tmpdir) })
// Resolve /var/folders/.../T/... to /private/var/... in OSX
wd, err := os.Getwd()
if err != nil {
t.Fatalf("os.Getwd(): %s", err)
}
defer func() {
err := os.Chdir(wd)
if err != nil {
t.Fatalf("os.Chdir(): %s", err)
}
}()
err = os.Chdir(tmpdir)
if err != nil {
t.Fatalf("os.Chdir(): %s", err)
}
tmpdir, err = os.Getwd()
if err != nil {
t.Fatalf("os.Getwd(): %s", err)
}
s, err := toFullPath(tmpdir)
if err != nil {
t.Fatalf("toFullPath(%q): %s", tmpdir, err)
}
return s
}
func setEnv(t *testing.T, key, val string) {
orig, ok := os.LookupEnv(key)
os.Setenv(key, val)
t.Cleanup(func() {
if ok {
os.Setenv(key, orig)
} else {
os.Unsetenv(key)
}
})
}