-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
299 lines (267 loc) · 7.39 KB
/
utils.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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"time"
"github.com/crowdsecurity/crowdsec/pkg/types"
"github.com/google/go-cmp/cmp"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
type SingleItemTested struct {
count int
failCount int
}
type Overall struct {
overall map[string]map[string]SingleItemTested
}
func TestResults(expected []types.Event, results []types.Event, failFile string, testName string, write bool) error {
var (
err error
)
opt := getCmpOptions()
origResults := results // get a copy of the original results
Loop:
for i, expectedEvent := range expected {
for j, happenedEvent := range results {
if cmp.Equal(expectedEvent, happenedEvent, opt) {
expected = append(expected[:i], expected[i+1:]...)
results = append(results[:j], results[j+1:]...)
goto Loop
}
}
}
if len(expected) != 0 || len(results) != 0 {
if write {
log.Errorf("tests failed, writing results to %s", failFile)
err = marshalAndStore(origResults, failFile)
if err != nil {
return errors.Wrapf(err, "failed to marshal result in %s", failFile)
}
}
return errors.WithMessage(errors.New(cmp.Diff(expected, results, opt)), "mismatch diff (-want +got)")
}
log.Infof("%d/%d matched results", len(origResults)-len(results), len(origResults))
log.Infof("%s tests are finished", testName)
return nil
}
//generics, generics, generics, we lack youuuuuuuu
func TestProvisionalResults(expected []map[string]map[string]types.Event, results []map[string]map[string]types.Event, failFile string, testName string) error {
var (
err error
)
//from here we will deal with postoverflow
opt := getCmpOptions()
origResults := results // get a copy of the original results
Loop:
for i, expectedEvent := range expected {
for j, happenedEvent := range results {
if cmp.Equal(expectedEvent, happenedEvent, opt) {
expected = append(expected[:i], expected[i+1:]...)
results = append(results[:j], results[j+1:]...)
goto Loop
}
}
}
if len(expected) != 0 || len(results) != 0 {
log.Errorf("tests failed, writing results to %s", failFile)
err = marshalAndStore(origResults, failFile)
if err != nil {
return errors.Wrapf(err, "failed to marshal result in %s", failFile)
}
return errors.WithMessage(errors.New(cmp.Diff(expected, results, opt)), "provisional results mismatch diff (-want +got)")
}
log.Infof("%d/%d matched results", len(origResults)-len(results), len(origResults))
log.Infof("%s tests are finished", testName)
return nil
}
func getCmpOptions() cmp.Option {
/*
** we are using cmp's feature to match structures.
** because of the way marshal/unmarshal works we want to make nil == empty
*/
// This option handles slices and maps of any type.
alwaysEqual := cmp.Comparer(func(_, _ interface{}) bool { return true })
opt := cmp.FilterValues(func(x, y interface{}) bool {
vx, vy := reflect.ValueOf(x), reflect.ValueOf(y)
return (vx.IsValid() && vy.IsValid() && vx.Type() == vy.Type()) &&
(vx.Kind() == reflect.Slice || vx.Kind() == reflect.Map) &&
(vx.Len() == 0 && vy.Len() == 0)
}, alwaysEqual)
return opt
}
//cleanForMatch : cleanup results from items that might change every run. We strip as well strictly equal results
func cleanForMatch(in map[string]map[string]types.Event) map[string]map[string]types.Event {
for stage, val := range in {
for parser, evt := range val {
evt.Line.Time = time.Time{}
evt.Time = time.Time{}
in[stage][parser] = evt
}
}
return in
}
func cleanForMatchEvent(in types.Event) types.Event {
in.Line.Time = time.Time{}
in.Time = time.Time{}
return in
}
func marshalAndStore(in interface{}, filename string) error {
var (
out []byte
err error
)
if filename == "" {
return nil
}
if out, err = yaml.Marshal(in); err != nil {
return fmt.Errorf("Marshal %s error: %s, filename", filename, err)
}
if err = ioutil.WriteFile(filename, out, 0644); err != nil {
return fmt.Errorf("Write file %s error: %s", filename, err)
}
return nil
}
// be cautious to pass a pointer in the interface
func retrieveAndUnmarshal(filename string, b interface{}) error {
var (
buf []byte
err error
)
if buf, err = ioutil.ReadFile(filename); err != nil {
return fmt.Errorf("Read file %s error: %s", filename, err)
}
if err = yaml.Unmarshal(buf, b); err != nil {
return fmt.Errorf("Unmarshal file %s error: %s", filename, err)
}
return nil
}
func NewOverall() *Overall {
return &Overall{
overall: make(map[string]map[string]SingleItemTested),
}
}
func (o *Overall) AddSingleResult(tested map[string][]string, failure bool) {
for itemType, itemList := range tested {
if _, ok := o.overall[itemType]; !ok {
o.overall[itemType] = make(map[string]SingleItemTested)
}
for _, item := range itemList {
if _, ok := o.overall[itemType][item]; !ok {
if failure {
o.overall[itemType][item] = SingleItemTested{
count: 1,
failCount: 1,
}
} else {
o.overall[itemType][item] = SingleItemTested{
count: 1,
failCount: 0,
}
}
} else {
if failure {
tmp := o.overall[itemType][item]
tmp.count++
tmp.failCount++
o.overall[itemType][item] = tmp
} else {
tmp := o.overall[itemType][item]
tmp.count++
o.overall[itemType][item] = tmp
}
}
}
}
}
func buildOverallResult(dir string) (map[string]map[string]Configuration, error) {
ret := make(map[string]map[string]Configuration)
err := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {
if strings.Contains(path, ".tests") {
return nil
}
if f.Mode().IsDir() {
return nil
}
parts := strings.Split(path, "/")
if parts[0] != "parsers" && parts[0] != "scenarios" && parts[0] != "postoverflows" {
return nil
}
npath := ""
if parts[0] == "parsers" || parts[0] == "postoverflows" {
npath = strings.Join(parts[2:], "/")
}
if parts[0] == "scenarios" && len(parts) > 1 {
npath = strings.Join(parts[1:], "/")
}
if _, ok := ret[parts[0]]; !ok {
ret[parts[0]] = make(map[string]Configuration)
}
if filepath.Ext(npath) == ".md" {
var c Configuration
entry := strings.TrimSuffix(npath, ".md")
if _, ok := ret[parts[0]][entry]; ok {
c = ret[parts[0]][entry]
} else {
c = Configuration{}
}
c.markdown = true
if f.Size() == 0 {
c.markdownNotEmpty = false
ret[parts[0]][entry] = c
} else {
c.markdownNotEmpty = true
ret[parts[0]][entry] = c
}
}
if filepath.Ext(npath) == ".yaml" {
entry := strings.TrimSuffix(npath, ".yaml")
if _, ok := ret[parts[0]][entry]; !ok {
ret[parts[0]][entry] = Configuration{
markdown: false,
markdownNotEmpty: false,
count: 0,
failure: 0,
}
}
}
return nil
})
return ret, err
}
func getDataFromFile(filename string, dataFolder string) error {
var (
err error
buf []byte
)
if filename == "" {
log.Fatalf("provided with empty filename")
}
if buf, err = ioutil.ReadFile(filename); err != nil {
log.Fatalf("unable to open read %s", filename)
}
dec := yaml.NewDecoder(bytes.NewReader(buf))
for {
data := &types.DataSet{}
err = dec.Decode(data)
if err != nil {
if err == io.EOF {
break
} else {
return errors.Wrap(err, "while reading file")
}
}
err = types.GetData(data.Data, dataFolder)
if err != nil {
errors.Wrapf(err, "Unable to download data from %+v", data.Data)
}
}
return nil
}