github.com/coreos/mantle@v0.13.0/harness/reporters/json.go (about) 1 // Copyright 2017 CoreOS, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package reporters 16 17 import ( 18 "encoding/json" 19 "os" 20 "path/filepath" 21 "time" 22 23 "github.com/coreos/mantle/harness/testresult" 24 ) 25 26 type jsonReporter struct { 27 Tests []jsonTest `json:"tests"` 28 Result testresult.TestResult `json:"result"` 29 filename string 30 31 // Context variables 32 Platform string `json:"platform"` 33 Version string `json:"version"` 34 } 35 36 type jsonTest struct { 37 Name string `json:"name"` 38 Result testresult.TestResult `json:"result"` 39 Duration time.Duration `json:"duration"` 40 Output string `json:"output"` 41 } 42 43 func NewJSONReporter(filename, platform, version string) *jsonReporter { 44 return &jsonReporter{ 45 Platform: platform, 46 Version: version, 47 filename: filename, 48 } 49 } 50 51 func (r *jsonReporter) ReportTest(name string, result testresult.TestResult, duration time.Duration, b []byte) { 52 r.Tests = append(r.Tests, jsonTest{ 53 Name: name, 54 Result: result, 55 Duration: duration, 56 Output: string(b), 57 }) 58 } 59 60 func (r *jsonReporter) Output(path string) error { 61 f, err := os.Create(filepath.Join(path, r.filename)) 62 if err != nil { 63 return err 64 } 65 defer f.Close() 66 67 return json.NewEncoder(f).Encode(r) 68 } 69 70 func (r *jsonReporter) SetResult(result testresult.TestResult) { 71 r.Result = result 72 }