forked from hortonworks/cloudbreak-deployer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testutils.go
51 lines (47 loc) · 1.01 KB
/
testutils.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
package main
import (
"io/ioutil"
"os"
"testing"
)
func catchStdInStdOut(t *testing.T, input string, runnable func()) string {
realStdin := os.Stdin
realStdout := os.Stdout
defer func() {
os.Stdout = realStdout
os.Stdin = realStdin
}()
fakeStdin, w, err := os.Pipe()
dieOn(err, t)
r, fakeStdout, err := os.Pipe()
dieOn(err, t)
os.Stdin = fakeStdin
os.Stdout = fakeStdout
w.WriteString(input)
dieOn(w.Close(), t)
runnable()
dieOn(fakeStdout.Close(), t)
newOutBytes, err := ioutil.ReadAll(r)
dieOn(err, t)
dieOn(r.Close(), t)
dieOn(fakeStdin.Close(), t)
return string(newOutBytes)
}
func catchStdOut(t *testing.T, runnable func()) string {
realStdout := os.Stdout
defer func() { os.Stdout = realStdout }()
r, fakeStdout, err := os.Pipe()
dieOn(err, t)
os.Stdout = fakeStdout
runnable()
dieOn(fakeStdout.Close(), t)
newOutBytes, err := ioutil.ReadAll(r)
dieOn(err, t)
dieOn(r.Close(), t)
return string(newOutBytes)
}
func dieOn(err error, t *testing.T) {
if err != nil {
t.Fatal(err)
}
}