-
Notifications
You must be signed in to change notification settings - Fork 2
/
validate.go
390 lines (357 loc) · 8.61 KB
/
validate.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
package resource
import (
"bufio"
"encoding/json"
"fmt"
"github.com/onsi/gomega/format"
"io"
"reflect"
"regexp"
"strings"
"time"
"github.com/onsi/gomega/types"
)
const (
Value = iota
Values
Contains
Header
)
const (
SUCCESS = iota
FAIL
SKIP
)
const (
maxScanTokenSize = 1024 * 1024
)
type TestResult struct {
Successful bool `json:"successful" yaml:"successful"`
ResourceId string `json:"resource-id" yaml:"resource-id"`
ResourceType string `json:"resource-type" yaml:"resource-type"`
Title string `json:"title" yaml:"title"`
Meta meta `json:"meta" yaml:"meta"`
TestType int `json:"test-type" yaml:"test-type"`
Result int `json:"result" yaml:"result"`
Property string `json:"property" yaml:"property"`
Err error `json:"err" yaml:"err"`
Expected []string `json:"expected" yaml:"expected"`
Found []string `json:"found" yaml:"found"`
Human string `json:"human" yaml:"human"`
Duration time.Duration `json:"duration" yaml:"duration"`
}
func skipResult(typeS string, testType int, id string, title string, meta meta, property string, startTime time.Time) TestResult {
return TestResult{
Successful: true,
Result: SKIP,
ResourceType: typeS,
TestType: testType,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Duration: startTime.Sub(startTime),
}
}
func ValidateValue(res ResourceRead, property string, expectedValue interface{}, actual interface{}, skip bool) TestResult {
format.TruncatedDiff = false
id := res.ID()
title := res.GetTitle()
meta := res.GetMeta()
typ := reflect.TypeOf(res)
typeS := strings.Split(typ.String(), ".")[1]
startTime := time.Now()
if skip {
return skipResult(
typeS,
Values,
id,
title,
meta,
property,
startTime,
)
}
var foundValue interface{}
var err error
switch f := actual.(type) {
case func() (bool, error):
foundValue, err = f()
case func() (string, error):
foundValue, err = f()
case func() (int, error):
foundValue, err = f()
case func() ([]string, error):
foundValue, err = f()
case func() (interface{}, error):
foundValue, err = f()
default:
err = fmt.Errorf("Unknown method signature: %t", f)
}
expectedValue = sanitizeExpectedValue(expectedValue)
var gomegaMatcher types.GomegaMatcher
var success bool
if err == nil {
gomegaMatcher, err = matcherToGomegaMatcher(expectedValue)
}
if err == nil {
success, err = gomegaMatcher.Match(foundValue)
}
if err != nil {
return TestResult{
Successful: false,
Result: FAIL,
ResourceType: typeS,
TestType: Values,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Err: err,
Duration: time.Now().Sub(startTime),
}
}
var failMessage string
var result int
if !success {
failMessage = gomegaMatcher.FailureMessage(foundValue)
result = FAIL
}
expected, _ := json.Marshal(expectedValue)
found, _ := json.Marshal(foundValue)
return TestResult{
Successful: success,
Result: result,
ResourceType: typeS,
TestType: Value,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Expected: []string{string(expected)},
Found: []string{string(found)},
Human: failMessage,
Err: err,
Duration: time.Now().Sub(startTime),
}
}
type patternMatcher interface {
Match(string) bool
Pattern() string
Inverse() bool
}
type stringPattern struct {
pattern string
cleanPattern string
inverse bool
}
func newStringPattern(str string) *stringPattern {
var inverse bool
if strings.HasPrefix(str, "!") {
inverse = true
}
cleanPattern := strings.TrimLeft(str, "\\/!")
return &stringPattern{
pattern: str,
cleanPattern: cleanPattern,
inverse: inverse,
}
}
func (s *stringPattern) Match(str string) bool {
return strings.Contains(str, s.cleanPattern)
}
func (s *stringPattern) Pattern() string { return s.pattern }
func (s *stringPattern) Inverse() bool { return s.inverse }
type regexPattern struct {
pattern string
re *regexp.Regexp
inverse bool
}
func newRegexPattern(str string) (*regexPattern, error) {
var inverse bool
cleanStr := str
if strings.HasPrefix(str, "!") {
inverse = true
cleanStr = cleanStr[1:]
}
trimLeft := []rune{'\\', '/'}
for _, r := range trimLeft {
if rune(cleanStr[0]) == r {
cleanStr = cleanStr[1:]
break
}
}
trimRight := []rune{'/'}
for _, r := range trimRight {
if rune(cleanStr[len(cleanStr)-1]) == r {
cleanStr = cleanStr[:len(cleanStr)-1]
break
}
}
re, err := regexp.Compile(cleanStr)
return ®exPattern{
pattern: str,
re: re,
inverse: inverse,
}, err
}
func (re *regexPattern) Match(str string) bool {
return re.re.MatchString(str)
}
func (re *regexPattern) Pattern() string { return re.pattern }
func (re *regexPattern) Inverse() bool { return re.inverse }
func sliceToPatterns(slice []string) ([]patternMatcher, error) {
var patterns []patternMatcher
for _, s := range slice {
if (strings.HasPrefix(s, "/") || strings.HasPrefix(s, "!/")) && strings.HasSuffix(s, "/") {
pat, err := newRegexPattern(s)
if err != nil {
return nil, err
}
patterns = append(patterns, pat)
} else {
patterns = append(patterns, newStringPattern(s))
}
}
return patterns, nil
}
func patternsToSlice(patterns []patternMatcher) []string {
var slice []string
for _, p := range patterns {
slice = append(slice, p.Pattern())
}
return slice
}
func ValidateContains(res ResourceRead, property string, expectedValues []string, method func() (io.Reader, error), skip bool) TestResult {
format.TruncatedDiff = false
id := res.ID()
title := res.GetTitle()
meta := res.GetMeta()
typ := reflect.TypeOf(res)
typeS := strings.Split(typ.String(), ".")[1]
startTime := time.Now()
if skip {
return skipResult(
typeS,
Values,
id,
title,
meta,
property,
startTime,
)
}
var err error
var fh io.Reader
var notfound []patternMatcher
notfound, err = sliceToPatterns(expectedValues)
// short circuit
if len(notfound) == 0 && err == nil {
return TestResult{
Successful: true,
Result: SUCCESS,
ResourceType: typeS,
TestType: Contains,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Expected: expectedValues,
Duration: time.Now().Sub(startTime),
}
}
if err == nil {
fh, err = method()
}
if err != nil {
return TestResult{
Successful: false,
Result: FAIL,
ResourceType: typeS,
TestType: Contains,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Err: err,
Duration: time.Now().Sub(startTime),
}
}
defer func() {
//Do we need to close the stream?
if rc, ok := fh.(io.ReadCloser); ok {
rc.Close()
}
}()
scanner := bufio.NewScanner(fh)
scanner.Buffer(nil, maxScanTokenSize)
var found []patternMatcher
for scanner.Scan() {
line := scanner.Text()
i := 0
for _, pat := range notfound {
if pat.Match(line) {
// Found it, but wasn't supposed to, don't mark it as found, but remove it from search
if !pat.Inverse() {
found = append(found, pat)
}
continue
}
notfound[i] = pat
i++
}
notfound = notfound[:i]
if len(notfound) == 0 {
break
}
}
if err := scanner.Err(); err != nil {
return TestResult{
Successful: false,
Result: FAIL,
ResourceType: typeS,
TestType: Contains,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Err: err,
Duration: time.Now().Sub(startTime),
}
}
for _, pat := range notfound {
// Didn't find it, but we didn't want to.. so we mark it as found
// Empty pattern should match even if input to scanner is empty
if pat.Inverse() || pat.Pattern() == "" {
found = append(found, pat)
}
}
if len(expectedValues) != len(found) {
return TestResult{
Successful: false,
Result: FAIL,
ResourceType: typeS,
TestType: Contains,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Expected: expectedValues,
Found: patternsToSlice(found),
Duration: time.Now().Sub(startTime),
}
}
return TestResult{
Successful: true,
Result: SUCCESS,
ResourceType: typeS,
TestType: Contains,
ResourceId: id,
Title: title,
Meta: meta,
Property: property,
Expected: expectedValues,
Found: patternsToSlice(found),
Duration: time.Now().Sub(startTime),
}
}