-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloggedexec_test.go
125 lines (110 loc) · 1.99 KB
/
loggedexec_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
package lexec
import (
"bytes"
"fmt"
"io"
"os/exec"
"testing"
"github.com/stretchr/testify/assert"
)
func TestReturnsEmptyOutputWhenCommandReturnsNothing(t *testing.T) {
assertCommandOutput(
t,
[]string{`true`},
``,
``,
[]string{
`launch | true`,
`finish | true -> exit 0`,
},
nil,
)
}
func TestReturnsAndLogsLineOnStdout(t *testing.T) {
assertCommandOutput(
t,
[]string{`echo`, `1`},
"1\n",
``,
[]string{
`launch | echo 1`,
"stdout | 1",
`finish | echo 1 -> exit 0`,
},
nil,
)
}
func TestReturnsAndLogsLineOnStderr(t *testing.T) {
assertCommandOutput(
t,
[]string{`sh`, `-c`, `echo 1 >&2`},
``,
"1\n",
[]string{
`launch | sh -c "echo 1 >&2"`,
"stderr | 1",
`finish | sh -c "echo 1 >&2" -> exit 0`,
},
nil,
)
}
func TestReturnsAndLogsLineWithoutNewline(t *testing.T) {
assertCommandOutput(
t,
[]string{`echo`, `-n`, `1`},
"1",
``,
[]string{
`launch | echo -n 1`,
"stdout | 1",
`finish | echo -n 1 -> exit 0`,
},
nil,
)
}
func TestCanPassStdinToCommand(t *testing.T) {
assertCommandOutput(
t,
[]string{`sed`, `s/^/xxx /`},
"xxx test",
``,
[]string{
`launch | sed "s/^/xxx /"`,
"stdout | xxx test",
`finish | sed "s/^/xxx /" -> exit 0`,
},
bytes.NewBufferString(`test`),
)
}
func assertCommandOutput(
t *testing.T,
command []string,
stdout string,
stderr string,
logged []string,
stdin io.Reader,
) {
log := []string{}
logger := func(format string, data ...interface{}) {
log = append(log, fmt.Sprintf(format, data...))
}
execution := NewExec(
Loggerf(logger),
exec.Command(
command[0],
command[1:]...,
),
)
if stdin != nil {
execution.SetStdin(stdin)
}
actualStdout := &bytes.Buffer{}
actualStderr := &bytes.Buffer{}
execution.SetStdout(actualStdout)
execution.SetStderr(actualStderr)
err := execution.Run()
assert.NoError(t, err)
assert.Equal(t, stdout, actualStdout.String())
assert.Equal(t, stderr, actualStderr.String())
assert.Equal(t, logged, log)
}