-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
91 lines (84 loc) · 1.6 KB
/
main_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
package main
import (
"bytes"
"io"
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCMD(t *testing.T) {
tests := []struct {
name string
arguments []string
expect string
stdIn string
}{
{
"Test Simple Json",
[]string{"plist", "json", "-i", "testdata/TestArray.plist"},
"testdata/want/TestArray.json",
"",
},
{
"Test Simple Yaml",
[]string{"plist", "yaml", "-i", "testdata/TestArray.plist"},
"testdata/want/TestArray.yaml",
"",
},
{
"Test Simple Yaml via StdIn aka pipe",
[]string{"plist", "yaml"},
"testdata/want/TestArray.yaml",
"testdata/TestArray.plist",
},
}
oldArgs := os.Args
defer func() {
os.Args = oldArgs
}()
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := captureOut(func() {
os.Args = test.arguments
main()
}, test.stdIn)
be, err := ioutil.ReadFile(test.expect)
assert.NoError(t, err)
expected := string(be)
assert.Equal(t, expected, got)
})
}
}
func captureOut(test func(), stdInFile string) string {
oldIn := os.Stdin
oldOut := os.Stdout
defer func() {
os.Stdin = oldIn
os.Stdout = oldOut
}()
r, w, _ := os.Pipe()
os.Stdout = w
if stdInFile != "" {
in, err := os.Open(stdInFile)
defer func() {
_ = in.Close()
}()
if err != nil {
panic(err)
}
os.Stdin = in
}
test()
outC := make(chan string)
// copy the output in a separate goroutine so printing can't block indefinitely
go func() {
var buf bytes.Buffer
io.Copy(&buf, r)
outC <- buf.String()
}()
// back to normal state
w.Close()
out := <-outC
return out
}