github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/vmtest/internal/json2test/json2test.go (about) 1 // Copyright 2019 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package json2test 6 7 import ( 8 "encoding/json" 9 "io" 10 "time" 11 12 "github.com/u-root/u-root/pkg/uio" 13 ) 14 15 // Action is a TestEvent action. 16 type Action string 17 18 // These are the possible Actions generated by `go test -json` or `test2json`. 19 const ( 20 Run Action = "run" 21 Pause Action = "pause" 22 Continue Action = "cont" 23 Pass Action = "pass" 24 Fail Action = "fail" 25 Skip Action = "skip" 26 Output Action = "output" 27 Benchmark Action = "benchmark" 28 ) 29 30 // TestEvent is an event generated by `test2json`. 31 type TestEvent struct { 32 Time time.Time `json:",omitempty"` 33 Action Action 34 Package string `json:",omitempty"` 35 Test string `json:",omitempty"` 36 Elapsed float64 `json:",omitempty"` 37 Output string `json:",omitempty"` 38 } 39 40 // Handler is a callback for TestEvent events. 41 type Handler interface { 42 Handle(e TestEvent) 43 } 44 45 // EventParser returns a Writer that parses events and hands each event to all 46 // handlers h. 47 func EventParser(h ...Handler) io.WriteCloser { 48 return uio.FullLineWriter(&eventParser{h}) 49 } 50 51 type eventParser struct { 52 hs []Handler 53 } 54 55 func (ep *eventParser) OneLine(line []byte) { 56 // Poor man's JSON detector. 57 if len(line) == 0 || line[0] != '{' { 58 return 59 } 60 61 var e TestEvent 62 if err := json.Unmarshal(line, &e); err != nil { 63 return 64 } 65 for _, h := range ep.hs { 66 h.Handle(e) 67 } 68 }