github.com/saucelabs/saucectl@v0.175.1/internal/report/json/json.go (about) 1 package json 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "io" 7 "net/http" 8 "os" 9 10 "github.com/rs/zerolog/log" 11 "github.com/saucelabs/saucectl/internal/report" 12 ) 13 14 // Reporter represents struct to report in json format 15 type Reporter struct { 16 WebhookURL string 17 Filename string 18 Results []report.TestResult 19 } 20 21 // Add adds a TestResult 22 func (r *Reporter) Add(t report.TestResult) { 23 r.Results = append(r.Results, t) 24 } 25 26 // Render sends the result to specified webhook WebhookURL and log the result to the specified json file 27 func (r *Reporter) Render() { 28 body, err := json.Marshal(r.Results) 29 if err != nil { 30 log.Err(err).Msg("failed to generate test result.") 31 return 32 } 33 34 if r.WebhookURL != "" { 35 resp, err := http.Post(r.WebhookURL, "application/json", bytes.NewBuffer(body)) 36 if err != nil { 37 log.Err(err).Str("webhook", r.WebhookURL).Msg("failed to send test result to webhook.") 38 } else { 39 webhookBody, _ := io.ReadAll(resp.Body) 40 if resp.StatusCode >= http.StatusBadRequest { 41 log.Error().Str("webhook", r.WebhookURL).Msgf("failed to send test result to webhook, status: %d, msg: %q.", resp.StatusCode, string(webhookBody)) 42 } 43 if resp.StatusCode%100 == 2 { 44 log.Info().Str("webhook", r.WebhookURL).Msgf("test result has been sent successfully to webhook, msg: %q.", string(webhookBody)) 45 } 46 } 47 } 48 49 if r.Filename != "" { 50 err = os.WriteFile(r.Filename, body, 0666) 51 if err != nil { 52 log.Err(err).Msgf("failed to write test result to %q.", r.Filename) 53 } 54 } 55 } 56 57 // Reset resets the reporter to its initial state. This action will delete all test results. 58 func (r *Reporter) Reset() { 59 r.Results = make([]report.TestResult, 0) 60 } 61 62 // ArtifactRequirements returns a list of artifact types this reporter requires to create a proper report. 63 func (r *Reporter) ArtifactRequirements() []report.ArtifactType { 64 return nil 65 }