-
Notifications
You must be signed in to change notification settings - Fork 13
/
entry.go
412 lines (344 loc) · 11.9 KB
/
entry.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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// Copyright 2016-2021, Lenses.io Ltd
//
// 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 main
import (
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"strings"
"time"
shellwords "github.com/mattn/go-shellwords"
)
type (
// Entry contains the test case's entries' structure, see examples for more.
Entry struct {
Name string `yaml:"name"`
Description string `yaml:"description,omitempty"`
WorkDir string `yaml:"workdir"`
Command string `yaml:"command,omitempty"`
Stdin string `yaml:"stdin,omitempty"`
NoLog bool `yaml:"nolog,omitempty"`
EnvVars []string `yaml:"env,omitempty"`
Timeout time.Duration `yaml:"timeout,omitempty"`
// It differs from the `Timeout`,
// `SleepBefore` will wait for 'x' duration before the execution of this command.
SleepBefore time.Duration `yaml:"sleep_before,omitempty"`
// It differs from the `Timeout`,
// `SleepAfter` will wait for 'x' duration after the execution of this command.
SleepAfter time.Duration `yaml:"sleep_after,omitempty"`
// keep for backwards compatibility.
StdoutExpect []string `yaml:"stdout_has,omitempty"`
StdoutNotExpect []string `yaml:"stdout_not_has,omitempty"`
StderrExpect []string `yaml:"stderr_has,omitempty"`
StderrNotExpect []string `yaml:"stderr_not_has,omitempty"`
// NoRegex if true disables the regex matching which is the default behavior for "stdout_has", "stdout_not_has", "stderr_has", "stderr_not_has".
// Useful for matching [raw array results]).
NoRegex bool `yaml:"noregex,omitempty"`
Stdout OutFilters `yaml:"stdout,omitempty"`
Stderr OutFilters `yaml:"stderr,omitempty"`
IgnoreExitCode bool `yaml:"ignore_exit_code,omitempty"`
// Skip will Skip only if "true".
// It's type of string instead of bool because it is meant to help with manipulating tests from scripts.
//
// See `NoSkip` too.
Skip string `yaml:"skip,omitempty"`
// NoSkip will skip if it is set and not "true".
// It's type of string instead of bool because it is meant to help with manipulating tests from scripts.
//
// See `Skip` too.
NoSkip string `yaml:"noskip,omitempty"`
}
// OutFilter describes the stdout and stderr output's search expectation.
//
// See `Entry` for more.
OutFilter struct {
// Match should match (against regex expression if NoRegex is false, default behavior).
Match []string `yaml:"match,omitempty"`
// NotMatch should not match (against regex expression if NoRegex is false, default behavior).
NotMatch []string `yaml:"not_match,omitempty"`
/* More options below... */
// NoRegex if true disables the regex matching, which is the default behavior.
// Useful for matching [raw array results]).
NoRegex bool `yaml:"noregex,omitempty"`
// Partial if true then it passes the test if at least one of the Match/NotMatch entries and their content
// exist in the command's output.
// Essentialy is a small helper, it can be done with regex as well.
Partial bool `yaml:"partial,omitempty"`
}
// OutFilters is a set of `OutFilter`.
OutFilters []OutFilter
)
// GetMatches simply returns the text of all `Match` inside "filters".
func (filters OutFilters) GetMatches() (matches []string) {
for _, filter := range filters {
matches = append(matches, filter.Match...)
}
return
}
// GetNotMatches simply returns the text of all `NotMatch` inside "filters".
func (filters OutFilters) GetNotMatches() (notMatches []string) {
for _, filter := range filters {
notMatches = append(notMatches, filter.NotMatch...)
}
return
}
func removeNewLine(s string) string {
return strings.TrimRightFunc(s, func(c rune) bool {
return c == '\r' || c == '\n'
})
}
func canPassAgainstBackwards(against, output string, noregex bool) (bool, error) {
if noregex {
against, output = removeNewLine(against), removeNewLine(output)
return output == against, nil
}
return regexp.MatchString(against, output)
}
func canPassAgainst(against, output string, f OutFilter) (bool, error) {
if f.NoRegex {
against, output = removeNewLine(against), removeNewLine(output)
if f.Partial {
return strings.Contains(output, against), nil
}
return output == against, nil
}
if f.Partial {
return strings.Contains(output, against), nil
}
return regexp.MatchString(against, output)
}
// key -> the position of the test case for both stdout and stderr.
// value -> the error(s) produced by each of them.
type filterErrors map[int][]string
var newLineB = []byte("\n")
func (errs filterErrors) String() string {
b := new(strings.Builder)
if len(errs) == 0 {
return ""
}
for _, errors := range errs {
for _, errMsg := range errors {
if errMsg != "" {
b.WriteString(errMsg)
b.Write(newLineB)
}
}
}
return b.String()
}
func (f OutFilter) check(output string) (bool, error) {
matchErrors, notMatchErrors := make(filterErrors), make(filterErrors)
for i, v := range f.Match {
if v == "" {
continue
}
// check for match.
pass, errPass := canPassAgainst(v, output, f)
if errPass != nil {
matchErrors[i] = append(matchErrors[i], fmt.Sprintf("match: bad regexp: %v.", errPass))
}
if !pass {
errMsg := fmt.Sprintf("match: should expected '%s'.", v)
if output == "" {
errMsg += " Output is empty ''."
}
matchErrors[i] = append(matchErrors[i], errMsg)
} else if f.Partial { // we passed at least one case, break.
// and delete any previous errors for THIS `match` entry.
for j := 0; j < i; j++ {
delete(matchErrors, j)
}
break
}
}
for i, v := range f.NotMatch {
if v == "" {
continue
}
// check for not match (too).
pass, errPass := canPassAgainst(v, output, f)
if errPass != nil {
notMatchErrors[i] = append(notMatchErrors[i], fmt.Sprintf("not_match: bad regexp: %v.", errPass))
}
if pass {
notMatchErrors[i] = append(notMatchErrors[i], fmt.Sprintf("not_match: should not expected '%s'.", v))
} else if errPass == nil {
pass = true // we can ignore it because we only check for errMsg != "", it's here for readability.
if f.Partial { // we passed at least one case, break.
// and delete any previous errors for THIS `match` entry.
for j := 0; j < i; j++ {
delete(notMatchErrors, j)
}
break
}
}
}
if errMsg := matchErrors.String() + notMatchErrors.String(); errMsg != "" {
return false, errors.New(errMsg)
}
return true, nil
}
func (e *Entry) testBackwards(stdout, stderr string) (bool, error) {
var errMsg string
for _, v := range e.StdoutExpect {
if v == "" {
continue
}
toMatch := replaceUnique(v)
pass, errPass := canPassAgainstBackwards(toMatch, stdout, e.NoRegex)
if errPass != nil {
errMsg = fmt.Sprintf("%sStdout_has Bad Regexp: %v. \n", errMsg, errPass)
}
if !pass {
errMsg = fmt.Sprintf("%sStdout_has not matched expected '%s'.\n", errMsg, toMatch)
}
}
for _, v := range e.StdoutNotExpect {
if v == "" {
continue
}
toMatch := replaceUnique(v)
pass, errPass := canPassAgainstBackwards(toMatch, stdout, e.NoRegex)
if errPass != nil {
errMsg = fmt.Sprintf("%sStdout_not_has Bad Regexp: %v. \n", errMsg, errPass)
}
if pass {
errMsg = fmt.Sprintf("%sStdout_not_has matched not expected '%s'.\n", errMsg, toMatch)
} else if errPass == nil {
pass = true // pass the test.
}
}
// if errMsg != "" {
// errMsg += fmt.Sprintf("Output was: '%s'", stdout)
// }
for _, v := range e.StderrExpect {
if v == "" {
continue
}
toMatch := replaceUnique(v)
pass, errPass := canPassAgainstBackwards(toMatch, stderr, e.NoRegex)
if errPass != nil {
errMsg = fmt.Sprintf("%sStderr_has Bad Regexp: %v. \n", errMsg, errPass)
}
if !pass {
errMsg = fmt.Sprintf("%sStderr_has not matched expected '%s'.\n", errMsg, toMatch)
}
}
for _, v := range e.StderrNotExpect {
if v == "" {
continue
}
toMatch := replaceUnique(v)
pass, errPass := canPassAgainstBackwards(toMatch, stderr, e.NoRegex)
if errPass != nil {
errMsg = fmt.Sprintf("%sStderr_not_has Bad Regexp: %v. \n", errMsg, errPass)
}
if pass {
errMsg = fmt.Sprintf("%sStderr_not_has matched not expected '%s'.\n", errMsg, toMatch)
} else if errPass == nil {
pass = true // we can ignore it because we only check for errMsg != "", it's here for readability.
}
}
if errMsg != "" {
return false, errors.New(errMsg)
}
return true, nil
}
func mapVars(localVars, globalVars map[string]string, lists ...*[]string) {
for _, items := range lists {
tmp := *items
for i, item := range tmp {
result := replaceVars(replaceUnique(item), localVars, globalVars)
tmp[i] = result
}
*items = tmp
}
}
// MapVars maps the local and global vars to the name, command, stdin, env_vars and (not) expected stdout and stderr.
func (e *Entry) MapVars(localVars, globalVars map[string]string) { // note that local vars have priority over global vars.
// If unique strings are asked, replace the placeholders
// Also replace local and global vars.
e.Name = replaceVars(e.Name, localVars, globalVars)
e.Command = replaceVars(replaceUnique(e.Command), localVars, globalVars)
e.Stdin = replaceVars(replaceUnique(e.Stdin), localVars, globalVars)
mapVars(localVars, globalVars, &e.EnvVars)
shouldFirstCheckForOld := len(e.StderrExpect) > 0 || len(e.StderrNotExpect) > 0
if shouldFirstCheckForOld {
mapVars(localVars, globalVars, &e.StdoutExpect, &e.StdoutNotExpect, &e.StderrExpect, &e.StderrNotExpect)
}
for _, filter := range e.Stdout {
mapVars(localVars, globalVars, &filter.Match, &filter.NotMatch)
}
for _, filter := range e.Stderr {
mapVars(localVars, globalVars, &filter.Match, &filter.NotMatch)
}
}
// Test runs the tests based on the entry's fields and returns false if failed.
// The error is empty if test passed, otherwise it contains the necessary information text that
// the caller should know about the reason of failure of the particular test.
//
// Call of `MapVars` is required if local or/and global variables declared.
func (e *Entry) Test(stdout, stderr string) (bool, error) {
// here we can mix the old and new syntax,
// first check if with the old syntax passed, if passed and has new syntax is there, check that as well, otherwise fail.
shouldFirstCheckForOld := len(e.StdoutExpect)+len(e.StdoutNotExpect)+len(e.StderrExpect)+len(e.StderrNotExpect) > 0
if shouldFirstCheckForOld {
if _, err := e.testBackwards(stdout, stderr); err != nil {
return false, err
}
}
for i, filter := range e.Stdout {
if _, err := filter.check(stdout); err != nil {
err = fmt.Errorf("stdout[%d]: %s", i, err.Error())
return false, err
}
}
for i, filter := range e.Stderr {
if _, err := filter.check(stderr); err != nil {
err = fmt.Errorf("stderr[%d]: %s", i, err.Error())
return false, err
}
}
return true, nil
}
// TestCommand will test against the entry's command's output result.
func (e *Entry) TestCommand() (bool, error) {
args, err := shellwords.Parse(e.Command)
if err != nil {
return false, err
}
if len(args) == 0 { // Empty command?
return false, fmt.Errorf("test '%s' is missing the command field", e.Name)
}
cmd := exec.Command(args[0], args[1:]...)
if len(e.WorkDir) > 0 {
cmd.Dir = e.WorkDir
}
if len(e.Stdin) > 0 {
cmd.Stdin = strings.NewReader(e.Stdin)
}
cmd.Env = os.Environ()
if len(e.EnvVars) > 0 {
for _, v := range e.EnvVars {
cmd.Env = append(cmd.Env, v)
}
}
cmdOut, cmdErr := new(strings.Builder), new(strings.Builder)
cmd.Stdout, cmd.Stderr = cmdOut, cmdErr
if err = cmd.Run(); err != nil {
return false, err
}
return e.Test(cmdOut.String(), cmdErr.String())
}