forked from beatgammit/stein
/
stein.go
435 lines (392 loc) · 9.35 KB
/
stein.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package stein
import (
"bufio"
"encoding/json"
"fmt"
"gopkg.in/v1/yaml"
"io"
"regexp"
"strconv"
"strings"
"time"
)
var (
docSep = regexp.MustCompile(`(?m)^---$|^\.\.\.$`)
tapTestLine = regexp.MustCompile(`(?m)^(ok|not ok)(?: (\d+))?( [^#]+)?(?:\s*#(.*))?$`)
tapPlan = regexp.MustCompile(`(?m)^\d..(\d+|N).*$`)
tapVersion = regexp.MustCompile(`(?m)^TAP version \d+$`)
tapBailOut = regexp.MustCompile(`(?m)^Bail out!\s*(.*)$`)
)
func Parse(r io.Reader) (*Suite, error) {
parser := Parser{&DefaultHandler{}}
return parser.Parse(r)
}
type Parser struct {
Handler Handler
}
func (p *Parser) Parse(r io.Reader) (*Suite, error) {
rd := bufio.NewReader(r)
b, err := rd.Peek(1)
if err != nil {
panic(err)
}
if p.Handler == nil {
p.Handler = &DefaultHandler{}
}
s := new(Suite)
switch b[0] {
case '{':
return s, s.parse(newDecoder("json", rd), p.Handler)
case '-':
return s, s.parse(newDecoder("yaml", rd), p.Handler)
default:
return ParseTap(rd, p.Handler)
}
}
type Time struct {
time.Time
}
func (t *Time) parse(val string) (err error) {
var ti time.Time
if ti, err = time.Parse("2006-01-02 15:04:05", val); err != nil {
if ti, err = time.Parse(time.RFC3339, val); err != nil {
return
}
}
(*t).Time = ti
return
}
func (t *Time) UnmarshalJSON(data []byte) (err error) {
// parse time, stripping the quotes
return t.parse(string(data[1 : len(data)-1]))
}
func (t *Time) GetYAML() (tag string, value interface{}) {
return "", t.String()
}
func (t *Time) SetYAML(tag string, value interface{}) bool {
if v, ok := value.(string); ok {
return t.parse(strings.Trim(v, `'"`)) == nil
}
return false
}
type Suite struct {
Type string
Start *Time
Count int
Seed int
Rev int
Extra interface{} `yaml:",omitempty" json:",omitempty"`
Tests []*Test
Cases []*Case
Notes []Note
Final Tally
}
func (s *Suite) parse(dec decoder, handler Handler) (err error) {
handler.HandleBeforeStream()
var lastCase *Case
for dec.Scan() {
doc := dec.Scanner.Text()
handler.HandleDoc(doc, dec.format)
if strings.TrimSpace(doc) == "" {
continue
}
if s.Start == nil {
if err = dec.Unmarshal([]byte(doc), &s); err != nil {
return
}
handler.HandleSuite(s)
continue
}
var typ string
if typ, err = dec.Type([]byte(doc)); err != nil {
return
}
switch typ {
case "case":
var c Case
if err = dec.Unmarshal([]byte(doc), &c); err != nil {
return
}
if c.Level == 0 {
s.Cases = append(s.Cases, &c)
lastCase = &c
} else if lastCase == nil {
// TODO: possibly just add this case to the suite
return fmt.Errorf("No parent found for test case: %v", c)
} else {
// find the parent
for c.Level <= lastCase.Level {
lastCase = lastCase.parent
}
// TODO: strict check to ensure c.Level == lastCase.Level + 1
c.parent = lastCase
lastCase.Subcases = append(lastCase.Subcases, &c)
}
handler.HandleCase(&c)
case "test":
var t Test
if err = dec.Unmarshal([]byte(doc), &t); err != nil {
return
}
if lastCase != nil {
lastCase.Tests = append(lastCase.Tests, &t)
} else {
s.Tests = append(s.Tests, &t)
}
handler.HandleTest(&t)
case "note":
var n Note
if err = dec.Unmarshal([]byte(doc), &n); err != nil {
return
}
s.Notes = append(s.Notes, n)
handler.HandleNote(&n)
case "tally":
var t Tally
if err = dec.Unmarshal([]byte(doc), &t); err != nil {
return
}
handler.HandleTally(&t)
case "final":
var t Tally
if err = dec.Unmarshal([]byte(doc), &t); err != nil {
return
}
s.Final = t
handler.HandleFinal(&t)
default:
err = fmt.Errorf("Invalid type: %s", typ)
return
}
}
handler.HandleAfterStream()
return
}
func (s Suite) Docs() (ret []interface{}) {
ret = append(ret, s)
for _, t := range s.Tests {
ret = append(ret, t)
}
for _, c := range s.Cases {
ret = append(ret, c.Docs()...)
}
for _, n := range s.Notes {
ret = append(ret, n)
}
ret = append(ret, s.Final)
return
}
func (s Suite) ToTapY() ([]byte, error) {
var ret []byte
for _, doc := range s.Docs() {
if b, err := yaml.Marshal(doc); err != nil {
return nil, err
} else {
ret = append(ret, []byte("---\n")...)
ret = append(ret, b...)
ret = append(ret, '\n')
}
}
return append(ret, []byte("...")...), nil
}
type Case struct {
Type string
Subtype string
Label string
Level int
Extra interface{} `yaml:",omitempty" json:",omitempty"`
Tests []*Test `yaml:"-" json:"-"`
Subcases []*Case `yaml:"-" json:"-"`
parent *Case
}
func (c Case) Docs() (ret []interface{}) {
ret = append(ret, c)
for _, t := range c.Tests {
ret = append(ret, t)
}
for _, c := range c.Subcases {
ret = append(ret, c.Docs()...)
}
return
}
// TODO: allow strings via UnmarshalJSON/YAML
type Snippet []map[string]string
type Test struct {
Type string
Subtype string `yaml:",omitempty" json:",omitempty"`
Status string
Setup string `yaml:",omitempty" json:",omitempty"`
Label string
Expected interface{} `yaml:",omitempty" json:",omitempty"`
Returned interface{} `yaml:",omitempty" json:",omitempty"`
File string `yaml:",omitempty" json:",omitempty"`
Line int `yaml:",omitempty" json:",omitempty"`
Source string `yaml:",omitempty" json:",omitempty"`
Snippet Snippet `yaml:",omitempty" json:",omitempty"`
Coverage struct {
File string
Line interface{}
Code string
} `yaml:",omitempty" json:",omitempty"`
Exception struct {
Message string
File string
Line int
Source string
Snippet Snippet
Backtrace interface{}
} `yaml:",omitempty" json:",omitempty"`
Stdout string `yaml:",omitempty" json:",omitempty"`
Stderr string `yaml:",omitempty" json:",omitempty"`
Time float64
Extra interface{} `yaml:",omitempty" json:",omitempty"`
}
type Note struct {
Type string
Text string
Extra interface{} `yaml:",omitempty" json:",omitempty"`
}
type Tally struct {
Type string
Time float64
Counts struct {
Total int
Pass int
Fail int
Error int
Omit int
Todo int
}
Extra interface{} `yaml:",omitempty" json:",omitempty"`
}
type decoder struct {
*bufio.Scanner
format string
Unmarshal func([]byte, interface{}) error
}
func scanYAMLDoc(data []byte, atEOF bool) (advance int, token []byte, err error) {
if loc := docSep.FindIndex(data); loc != nil {
if loc[0] == 0 {
// just a start document marker
return loc[1], nil, nil
}
// We found a complete document
return loc[1], data[0:loc[0]], nil
}
if atEOF {
// if we're at EOF without having matched docSep, there's nothing else to get
return len(data), nil, nil
}
// Request more data.
return 0, nil, nil
}
func newDecoder(typ string, r io.Reader) decoder {
dec := decoder{Scanner: bufio.NewScanner(r)}
// TODO: handle plain TAP with a decoder as well
switch typ {
case "json":
dec.format = "json"
dec.Unmarshal = json.Unmarshal
case "yaml":
dec.format = "yaml"
dec.Unmarshal = yaml.Unmarshal
dec.Scanner.Split(scanYAMLDoc)
default:
panic("Unsupported decoder")
}
return dec
}
func (dec decoder) Type(b []byte) (string, error) {
m := make(map[string]interface{})
if err := dec.Unmarshal(b, &m); err != nil {
return "", fmt.Errorf("Invalid document: %s", err)
}
if typ, ok := m["type"].(string); !ok {
return "", fmt.Errorf("Missing 'type' key in document")
} else {
return typ, nil
}
}
func ParseTap(r io.Reader, handler Handler) (*Suite, error) {
if handler == nil {
handler = &DefaultHandler{}
}
handler.HandleBeforeStream()
rd := bufio.NewReader(r)
var s Suite
s.Start = &Time{time.Now()}
first := true
var totalTests int
for {
line, err := rd.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
handler.HandleDoc(line, "tap")
if line[0] == '#' {
// TODO: do something with diagnostic lines
continue
}
if matches := tapBailOut.FindStringSubmatch(line); matches != nil {
// TODO: do something with the bail reason
break
}
if first {
if matches := tapVersion.FindStringSubmatch(line); matches != nil {
// TAP 13+
return nil, fmt.Errorf("TAP13 not supported yet")
}
first = false
if matches := tapPlan.FindStringSubmatch(line); matches != nil {
totalTests, _ = strconv.Atoi(matches[1])
s.Count = totalTests
// assuming plan line at beginning of output
handler.HandleSuite(&s)
continue
}
}
matches := tapTestLine.FindStringSubmatch(line)
if matches == nil {
// TODO: handle extra data
continue
}
t := Test{Type: "test"}
switch matches[1] {
case "ok":
t.Status = "pass"
case "not ok":
// TODO: error?
t.Status = "fail"
}
// ignore number
t.Label = strings.TrimSpace(matches[3])
directive := strings.TrimSpace(matches[4])
switch {
case strings.HasPrefix(strings.ToUpper(directive), "TODO"):
s.Final.Counts.Todo++
t.Label = directive
t.Status = "todo"
case strings.HasPrefix(strings.ToUpper(directive), "SKIP"):
s.Final.Counts.Omit++
t.Label = directive
t.Status = "omit"
case t.Status == "pass":
s.Final.Counts.Pass++
default:
s.Final.Counts.Fail++
}
handler.HandleTest(&t)
s.Final.Counts.Total++
s.Tests = append(s.Tests, &t)
}
// fixup missing tests
if totalTests > 0 && totalTests > s.Final.Counts.Total {
s.Final.Counts.Fail += (totalTests - s.Final.Counts.Total)
s.Final.Counts.Total = totalTests
}
handler.HandleFinal(&s.Final)
handler.HandleAfterStream()
return &s, nil
}