-
Notifications
You must be signed in to change notification settings - Fork 1
/
exechelper_test.go
249 lines (222 loc) · 7.07 KB
/
exechelper_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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// +build !windows
package exechelper_test
import (
"bytes"
"context"
"errors"
"fmt"
"math/rand"
"os"
"os/exec"
"path"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/edwarnicke/exechelper"
)
const (
key1 = "key1"
)
func TestRunCmdDoesNotExist(t *testing.T) {
_, err := exechelper.CombinedOutput("fgipunergibergjefbg")
assert.Error(t, err)
}
func TestOutputCmdDoesExist(t *testing.T) {
_, err := exechelper.Output("ls")
assert.NoError(t, err)
}
func TestRunCmdNonZeroExitCode(t *testing.T) {
err := exechelper.Run("false")
assert.Error(t, err)
}
func TestCombinedOutputWithDir(t *testing.T) {
// Try with existing dir
dir := "/"
if _, err := os.Stat(dir); os.IsNotExist(err) {
defer func() { _ = os.Remove(dir) }()
}
b, err := exechelper.CombinedOutput("pwd", exechelper.WithDir(dir))
assert.NoError(t, err)
assert.Equal(t, dir, path.Base(strings.TrimSpace(string(b))))
// Try with *hopefully* non-existent dir
dir = fmt.Sprintf("testdir-%d", rand.Int()) // #nosec
if _, err = os.Stat(dir); os.IsNotExist(err) {
defer func() { _ = os.Remove(dir) }()
}
b, err = exechelper.CombinedOutput("pwd", exechelper.WithDir(dir))
assert.NoError(t, err)
assert.Equal(t, dir, path.Base(strings.TrimSpace(string(b))))
}
func TestStartWithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
errCh := exechelper.Start("sleep 600", exechelper.WithContext(ctx), exechelper.CmdOption(func(cmd *exec.Cmd) error {
return nil
}))
cancel()
select {
case err := <-errCh:
assert.IsType(t, &exec.ExitError{}, err) // Because we canceled we will get an exec.ExitError{}
exitErr := err.(*exec.ExitError)
status := exitErr.ProcessState.Sys().(syscall.WaitStatus)
assert.Equal(t, status.Signal(), syscall.SIGKILL)
assert.Empty(t, errCh)
case <-time.After(time.Second):
assert.Fail(t, "Failed to cancel context")
}
}
func TestCmdOptionErr(t *testing.T) {
_, err := exechelper.Output("ls")
assert.NoError(t, err)
_, err = exechelper.Output("ls", exechelper.CmdOption(func(cmd *exec.Cmd) error {
return errors.New("Test Error")
}))
assert.Error(t, err)
}
func TestWithArgs(t *testing.T) {
output, err := exechelper.Output("echo", exechelper.WithArgs("foo"))
assert.NoError(t, err)
assert.Equal(t, "foo", strings.TrimSpace(string(output)))
output, err = exechelper.Output("echo", exechelper.WithArgs("foo", "bar"))
assert.NoError(t, err)
assert.Equal(t, "foo bar", strings.TrimSpace(string(output)))
}
func TestWithStdin(t *testing.T) {
testStr := "hello world"
bufferIn := bytes.NewBuffer([]byte(testStr))
b, err := exechelper.Output("cat -", exechelper.WithStdin(bufferIn))
assert.NoError(t, err)
assert.Equal(t, testStr, strings.TrimSpace(string(b)))
}
func TestWithStdout(t *testing.T) {
buffer := bytes.NewBuffer([]byte{})
output, err := exechelper.Output("ls", exechelper.WithStdout(buffer))
assert.NoError(t, err)
assert.Equal(t, string(output), buffer.String())
}
func TestWithStderr(t *testing.T) {
buffer1 := bytes.NewBuffer([]byte{})
buffer2 := bytes.NewBuffer([]byte{})
err := exechelper.Run("ls fdhdhdhahdr",
exechelper.WithStderr(buffer1),
exechelper.WithStderr(buffer2),
)
assert.Error(t, err)
assert.True(t, buffer1.Len() > 0)
assert.Equal(t, buffer1.String(), buffer2.String())
}
func TestWithEnvMap(t *testing.T) {
// Try one
key1 := "key1"
value1 := "value1"
one := map[string]string{key1: value1}
b, err := exechelper.Output("printenv", exechelper.WithEnvMap(one))
assert.NoError(t, err)
assert.Equal(t, key1+"="+value1, strings.TrimSpace(string(b)))
// Try more than one
key2 := "key2"
value2 := "value2"
two := map[string]string{key1: value1, key2: value2}
b, err = exechelper.Output("printenv", exechelper.WithEnvMap(two))
assert.NoError(t, err)
assert.Contains(t, string(b), key1+"="+value1)
assert.Contains(t, string(b), key2+"="+value2)
// Try more than one sequentially
andThenTwo := map[string]string{key2: value2}
b, err = exechelper.Output("printenv", exechelper.WithEnvMap(one), exechelper.WithEnvMap(andThenTwo))
assert.NoError(t, err)
assert.Contains(t, string(b), key1+"="+value1)
assert.Contains(t, string(b), key2+"="+value2)
// Overwrite value
overwrite := map[string]string{key1: value2}
b, err = exechelper.Output("printenv", exechelper.WithEnvMap(one), exechelper.WithEnvMap(overwrite))
assert.NoError(t, err)
assert.Contains(t, string(b), key1+"="+value2)
assert.NotContains(t, string(b), key1+"="+value1)
}
func TestWithEnviron(t *testing.T) {
one := "key1=value1"
b, err := exechelper.Output("printenv", exechelper.WithEnvirons(one))
assert.NoError(t, err)
assert.Equal(t, one, strings.TrimSpace(string(b)))
invalid := key1
_, err = exechelper.Output("printenv", exechelper.WithEnvirons(invalid))
assert.Error(t, err)
}
func TestWithEnvKV(t *testing.T) {
_, err := exechelper.Output("printenv", exechelper.WithEnvKV(key1))
assert.Error(t, err)
}
func TestWithGracePeriodWithContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
graceperiod := 200 * time.Millisecond
err := exechelper.Run("go build ./testcmds/afterterm")
require.NoError(t, err)
errCh := exechelper.Start(
fmt.Sprintf("./afterterm %s", graceperiod-50*time.Millisecond),
exechelper.WithContext(ctx),
exechelper.WithGracePeriod(graceperiod),
exechelper.WithStdout(os.Stdout),
)
time.Sleep(100 * time.Millisecond)
cancelTime := time.Now()
cancel()
ok := true
for ok {
select {
case err, ok = <-errCh:
require.NoError(t, err)
case <-time.After(graceperiod + 50*time.Millisecond):
require.Failf(t, "", "failed to stop within graceperiod(%s): %s", graceperiod+50*time.Millisecond, time.Since(cancelTime))
ok = false
}
}
}
func TestWithGracePeriodExceeded(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
graceperiod := 200 * time.Millisecond
err := exechelper.Run("go build ./testcmds/afterterm")
require.NoError(t, err)
errCh := exechelper.Start(
fmt.Sprintf("./afterterm %s", 2*graceperiod),
exechelper.WithContext(ctx),
exechelper.WithGracePeriod(graceperiod),
exechelper.WithStdout(os.Stdout),
)
time.Sleep(100 * time.Millisecond)
cancelTime := time.Now()
cancel()
ok := true
errOnce := sync.Once{}
for ok {
select {
case err, ok = <-errCh:
errOnce.Do(func() {
assert.True(t, ok, "at least one real err should be returned on errCh")
})
if !ok {
break
}
require.IsType(t, &exec.ExitError{}, err) // Because graceperiod is exceeded, we get an ExitError for killed
exitErr := err.(*exec.ExitError)
status := exitErr.ProcessState.Sys().(syscall.WaitStatus)
assert.Equal(t, status.Signal(), syscall.SIGKILL)
assert.Empty(t, errCh)
case <-time.After(graceperiod + 100*time.Millisecond):
require.Failf(t, "", "failed to stop within graceperiod(%s): %s", graceperiod, time.Since(cancelTime))
ok = false
}
}
}
func TestWithGracePeriodWithoutContext(t *testing.T) {
graceperiod := 1 * time.Second
errCh := exechelper.Start(
"sleep 600",
exechelper.WithGracePeriod(graceperiod),
exechelper.WithStdout(os.Stdout),
)
require.Error(t, <-errCh)
}