forked from cilium/cilium
/
cmd.go
371 lines (321 loc) · 12 KB
/
cmd.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// Copyright 2017 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helpers
import (
"bytes"
"encoding/json"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/cilium/cilium/test/config"
"github.com/onsi/gomega"
"github.com/onsi/gomega/types"
"k8s.io/client-go/util/jsonpath"
)
// CmdRes contains a variety of data which results from running a command.
type CmdRes struct {
cmd string // Command to run
params []string // Parameters to provide to command
stdout *Buffer // Stdout from running cmd
stderr *Buffer // Stderr from running cmd
success bool // Whether command successfully executed
exitcode int // The exit code of cmd
duration time.Duration // Is the representation of the the time that command took to execute.
wg *sync.WaitGroup // Used to wait until the command has finished running when used in conjunction with a Context
err error // If the command had any error being executed, the error will be written here.
}
// GetCmd returns res's cmd.
func (res *CmdRes) GetCmd() string {
return res.cmd
}
// GetExitCode returns res's exitcode.
func (res *CmdRes) GetExitCode() int {
return res.exitcode
}
// GetStdOut returns the contents of the stdout buffer of res as a string.
func (res *CmdRes) GetStdOut() string {
return res.stdout.String()
}
// GetStdErr returns the contents of the stderr buffer of res as a string.
func (res *CmdRes) GetStdErr() string {
return res.stderr.String()
}
// SendToLog writes to `TestLogWriter` the debug message for the running
// command, if the quietMode argument is true will print only the command and
// the exitcode.
func (res *CmdRes) SendToLog(quietMode bool) {
if quietMode {
logformat := "cmd: %q exitCode: %d duration: %s\n"
fmt.Fprintf(&config.TestLogWriter, logformat, res.cmd, res.GetExitCode(), res.duration)
return
}
logformat := "cmd: %q exitCode: %d duration: %s stdout:\n%s\n"
log := fmt.Sprintf(logformat, res.cmd, res.GetExitCode(), res.duration, res.stdout.String())
if res.stderr.Len() > 0 {
log = fmt.Sprintf("%sstderr:\n%s\n", log, res.stderr.String())
}
fmt.Fprint(&config.TestLogWriter, log)
}
// WasSuccessful returns true if cmd completed successfully.
func (res *CmdRes) WasSuccessful() bool {
return res.success
}
// ExpectFail asserts whether res failed to execute. It accepts an optional
// parameter that can be used to annotate failure messages.
func (res *CmdRes) ExpectFail(optionalDescription ...interface{}) bool {
return gomega.ExpectWithOffset(1, res).ShouldNot(
CMDSuccess(), optionalDescription...)
}
// ExpectSuccess asserts whether res executed successfully. It accepts an optional
// parameter that can be used to annotate failure messages.
func (res *CmdRes) ExpectSuccess(optionalDescription ...interface{}) bool {
return gomega.ExpectWithOffset(1, res).Should(
CMDSuccess(), optionalDescription...)
}
// ExpectContains asserts a string into the stdout of the response of executed
// command. It accepts an optional parameter that can be used to annotate
// failure messages.
func (res *CmdRes) ExpectContains(data string, optionalDescription ...interface{}) bool {
return gomega.ExpectWithOffset(1, res.Output().String()).To(
gomega.ContainSubstring(data), optionalDescription...)
}
// ExpectDoesNotContain asserts that a string is not contained in the stdout of
// the executed command. It accepts an optional parameter that can be used to
// annotate failure messages.
func (res *CmdRes) ExpectDoesNotContain(data string, optionalDescription ...interface{}) bool {
return gomega.ExpectWithOffset(1, res.Output().String()).ToNot(
gomega.ContainSubstring(data), optionalDescription...)
}
// ExpectDoesNotMatchRegexp asserts that the stdout of the executed command
// doesn't match the regexp. It accepts an optional parameter that can be used
// to annotate failure messages.
func (res *CmdRes) ExpectDoesNotMatchRegexp(regexp string, optionalDescription ...interface{}) bool {
return gomega.ExpectWithOffset(1, res.Output().String()).ToNot(
gomega.MatchRegexp(regexp), optionalDescription...)
}
// CountLines return the number of lines in the stdout of res.
func (res *CmdRes) CountLines() int {
return strings.Count(res.stdout.String(), "\n")
}
// CombineOutput returns the combined output of stdout and stderr for res.
func (res *CmdRes) CombineOutput() *bytes.Buffer {
result := new(bytes.Buffer)
result.WriteString(res.stdout.String())
result.WriteString(res.stderr.String())
return result
}
// IntOutput returns the stdout of res as an integer
func (res *CmdRes) IntOutput() (int, error) {
return strconv.Atoi(strings.Trim(res.stdout.String(), "\n\r"))
}
// FindResults filters res's stdout using the provided JSONPath filter. It
// returns an array of the values that match the filter, and an error if
// the unmarshalling of the stdout of res fails.
// TODO - what exactly is the need for this vs. Filter function below?
func (res *CmdRes) FindResults(filter string) ([]reflect.Value, error) {
var data interface{}
var result []reflect.Value
err := json.Unmarshal(res.stdout.Bytes(), &data)
if err != nil {
return nil, err
}
parser := jsonpath.New("").AllowMissingKeys(true)
parser.Parse(filter)
fullResults, _ := parser.FindResults(data)
for _, res := range fullResults {
for _, val := range res {
result = append(result, val)
}
}
return result, nil
}
// Filter returns the contents of res's stdout filtered using the provided
// JSONPath filter in a buffer. Returns an error if the unmarshalling of the
// contents of res's stdout fails.
func (res *CmdRes) Filter(filter string) (*FilterBuffer, error) {
var data interface{}
result := new(bytes.Buffer)
err := json.Unmarshal(res.stdout.Bytes(), &data)
if err != nil {
return nil, fmt.Errorf("could not parse JSON from command %q",
res.cmd)
}
parser := jsonpath.New("").AllowMissingKeys(true)
parser.Parse(filter)
err = parser.Execute(result, data)
if err != nil {
return nil, err
}
return &FilterBuffer{result}, nil
}
// ByLines returns res's stdout split by the newline character and, if the stdout
// contains `\r\n`, it will be split by carriage return and new line characters.
func (res *CmdRes) ByLines() []string {
stdoutStr := res.stdout.String()
sep := "\n"
if strings.Contains(stdoutStr, "\r\n") {
sep = "\r\n"
}
stdoutStr = strings.TrimRight(stdoutStr, sep)
return strings.Split(stdoutStr, sep)
}
// KVOutput returns a map of the stdout of res split based on
// the separator '='.
// For example, the following strings would be split as follows:
// a=1
// b=2
// c=3
func (res *CmdRes) KVOutput() map[string]string {
result := make(map[string]string)
for _, line := range res.ByLines() {
vals := strings.Split(line, "=")
if len(vals) == 2 {
result[vals[0]] = vals[1]
}
}
return result
}
// Output returns res's stdout.
func (res *CmdRes) Output() *Buffer {
return res.stdout
}
// OutputPrettyPrint returns a string with the ExitCode, stdout and stderr in a
// pretty format.
func (res *CmdRes) OutputPrettyPrint() string {
format := func(message string) string {
result := []string{}
for _, line := range strings.Split(message, "\n") {
result = append(result, fmt.Sprintf("\t %s", line))
}
return strings.Join(result, "\n")
}
return fmt.Sprintf(
"Exitcode: %d \nStdout:\n %s\nStderr:\n %s\n",
res.GetExitCode(),
format(res.GetStdOut()),
format(res.GetStdErr()))
}
// ExpectEqual asserts whether cmdRes.Output().String() and expected are equal.
// It accepts an optional parameter that can be used to annotate failure
// messages.
func (res *CmdRes) ExpectEqual(expected string, optionalDescription ...interface{}) bool {
return gomega.ExpectWithOffset(1, res.Output().String()).Should(
gomega.Equal(expected), optionalDescription...)
}
// Reset resets res's stdout buffer to be empty.
func (res *CmdRes) Reset() {
res.stdout.Reset()
return
}
// SingleOut returns res's stdout as a string without any newline characters
func (res *CmdRes) SingleOut() string {
strstdout := res.stdout.String()
strstdoutSingle := strings.Replace(strstdout, "\n", "", -1)
return strings.Replace(strstdoutSingle, "\r", "", -1)
}
// Unmarshal unmarshalls res's stdout into data. It assumes that the stdout of
// res is in JSON format. Returns an error if the unmarshalling fails.
func (res *CmdRes) Unmarshal(data interface{}) error {
err := json.Unmarshal(res.stdout.Bytes(), data)
return err
}
// GetDebugMessage returns executed command and its output
func (res *CmdRes) GetDebugMessage() string {
return fmt.Sprintf("cmd: %s\n%s", res.GetCmd(), res.OutputPrettyPrint())
}
// WaitUntilMatch waits until the given substring is present in the `CmdRes.stdout`
// If the timeout is reached it will return an error.
func (res *CmdRes) WaitUntilMatch(substr string) error {
body := func() bool {
return strings.Contains(res.Output().String(), substr)
}
return WithTimeout(
body,
fmt.Sprintf("%s is not in the output after timeout", substr),
&TimeoutConfig{Timeout: HelperTimeout})
}
// WaitUntilMatchRegexp waits until the `CmdRes.stdout` matches the given regexp.
// If the timeout is reached it will return an error.
func (res *CmdRes) WaitUntilMatchRegexp(expr string) error {
r := regexp.MustCompile(expr)
body := func() bool {
return r.Match(res.Output().Bytes())
}
return WithTimeout(
body,
fmt.Sprintf("The output doesn't match regexp %q after timeout", expr),
&TimeoutConfig{Timeout: HelperTimeout})
}
// WaitUntilFinish waits until the command context completes correctly
func (res *CmdRes) WaitUntilFinish() {
if res.wg == nil {
return
}
res.wg.Wait()
}
// GetErr returns error created from program output if command is not successful
func (res *CmdRes) GetErr(context string) error {
if res.WasSuccessful() {
return nil
}
return &cmdError{fmt.Sprintf("%s (%s) output: %s", context, res.err, res.GetDebugMessage())}
}
// GetError returns the error for this CmdRes.
func (res *CmdRes) GetError() error {
return res.err
}
// BeSuccesfulMatcher a new Ginkgo matcher for CmdRes struct
type BeSuccesfulMatcher struct{}
// Match validates that the given interface will be a `*CmdRes` struct and it
// was successful. In case of not a valid CmdRes will return an error. If the
// command was not successful it returns false.
func (matcher *BeSuccesfulMatcher) Match(actual interface{}) (success bool, err error) {
res, ok := actual.(*CmdRes)
if !ok {
return false, fmt.Errorf("%q is not a valid *CmdRes type", actual)
}
return res.WasSuccessful(), nil
}
// FailureMessage it returns a pretty printed error message in the case of the
// command was not successful.
func (matcher *BeSuccesfulMatcher) FailureMessage(actual interface{}) (message string) {
res, _ := actual.(*CmdRes)
return fmt.Sprintf("Expected command: %s \nTo succeed, but it failed:\n%s",
res.GetCmd(), res.OutputPrettyPrint())
}
// NegatedFailureMessage returns a pretty printed error message in case of the
// command is tested with a negative
func (matcher *BeSuccesfulMatcher) NegatedFailureMessage(actual interface{}) (message string) {
res, _ := actual.(*CmdRes)
return fmt.Sprintf("Expected command: %s\nTo have failed, but it was successful:\n%s",
res.GetCmd(), res.OutputPrettyPrint())
}
// CMDSuccess return a new Matcher that expects a CmdRes is a successful run command.
func CMDSuccess() types.GomegaMatcher {
return &BeSuccesfulMatcher{}
}
// cmdError is a implementation of error with String method to improve the debugging.
type cmdError struct {
s string
}
func (e *cmdError) Error() string {
return e.s
}
func (e *cmdError) String() string {
return e.s
}