-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonReportShipper.go
executable file
·217 lines (183 loc) · 6.63 KB
/
jsonReportShipper.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/getgauge/common"
"github.com/rodafr/json-report-shipper/gauge_messages"
"github.com/rodafr/json-report-shipper/logger"
)
const (
defaultReportsDir = "reports"
gaugeReportsDirEnvName = "gauge_reports_dir" // directory where reports are generated by plugins
overwriteReportsEnvProperty = "overwrite_reports"
jsonReportFile = "result.json"
jsonReport = "json-report-shipper"
setupAction = "setup"
executionAction = "execution"
gaugePortEnv = "plugin_connection_port"
pluginActionEnv = "json-report-shipper_action"
timeFormat = "2006-01-02 15.04.05"
reportApiUrlEnv = "grepo_url"
reportApiUserNameEnv = "grepo_api_user"
reportApiPasswordEnv = "grepo_api_pass"
)
var projectRoot string
type nameGenerator interface {
randomName() string
}
type timeStampedNameGenerator struct {
}
func (T timeStampedNameGenerator) randomName() string {
return time.Now().Format(timeFormat)
}
func findProjectRoot() {
projectRoot = os.Getenv(common.GaugeProjectRootEnv)
if projectRoot == "" {
logger.Fatalf("Environment variable '%s' is not set. \n", common.GaugeProjectRootEnv)
}
}
func addDefaultPropertiesToProject() {
defaultPropertiesFile := getDefaultPropertiesFile()
reportsDirProperty := &(common.Property{
Comment: "The path to the gauge reports directory. Should be either relative to the project directory or an absolute path",
Name: gaugeReportsDirEnvName,
DefaultValue: defaultReportsDir})
overwriteReportProperty := &(common.Property{
Comment: "Set as false if gauge reports should not be overwritten on each execution. A new time-stamped directory will be created on each execution.",
Name: overwriteReportsEnvProperty,
DefaultValue: "true"})
reportApiUrlProperty := &(common.Property{
Comment: "URL to API endpoint, /reports will be added",
Name: reportApiUrlEnv,
DefaultValue: "http://127.0.0.1:8080/",
})
if !common.FileExists(defaultPropertiesFile) {
logger.Infof("Failed to setup json report plugin shipper in project. Default properties file does not exist at %s. \n", defaultPropertiesFile)
return
}
if err := common.AppendProperties(defaultPropertiesFile, reportsDirProperty, overwriteReportProperty, reportApiUrlProperty); err != nil {
logger.Infof("Failed to setup json report shipper plugin in project: %s \n", err)
return
}
logger.Info("Successfully added configurations for json-report-shipper to env/default/default.properties")
}
func createReport(suiteResult *gauge_messages.SuiteExecutionResult) {
jsonContents := generateJSONFileContents(suiteResult)
reportDir, err := createJSONReport(createReportsDirectory(), jsonContents, getNameGen())
if err != nil {
logger.Fatalf("Report generation failed: %s \n", err)
} else {
logger.Infof("Successfully generated json-report to => %s\n", reportDir)
}
shipReport(jsonContents)
}
func shipReport(jsonContents []byte) int {
reportApiUrl := os.Getenv(reportApiUrlEnv)
reportApiUserName := os.Getenv(reportApiUserNameEnv)
reportApiPassword := os.Getenv(reportApiPasswordEnv)
data := bytes.NewReader(jsonContents)
if reportApiUserName == "" {
logger.Warnf("[WARNING] Report API username not set")
}
if reportApiPassword == "" {
logger.Warnf("[WARNING] Report API password not set")
}
u, err := url.Parse(reportApiUrl)
if err != nil {
logger.Fatalf("[FATAL] Invalid report API URL: %v", err)
}
u.Path = path.Join(u.Path, "api/reports")
logger.Infof("Received JSON content, shipping to %v\n", u.String())
client := &http.Client{}
request, err := http.NewRequest("POST", u.String(), data)
if err != nil {
logger.Debugf(err.Error())
}
request.SetBasicAuth(reportApiUserName, reportApiPassword)
response, err := client.Do(request)
if err != nil {
logger.Fatalf("[WARNING] Failed to connect to API: " + err.Error())
}
defer response.Body.Close()
if response.StatusCode != http.StatusCreated {
logger.Warnf("[WARNING] HTTP status code received was not 201: %v\n", response.Status)
} else {
logger.Infof("Success: HTTP status code received from API was: %v\n", response.Status)
}
return response.StatusCode
}
func generateJSONFileContents(protoSuiteExeResult *gauge_messages.SuiteExecutionResult) []byte {
var buffer bytes.Buffer
suiteRes := toSuiteResult(protoSuiteExeResult.GetSuiteResult())
buffer.WriteString(fmt.Sprintf("%s", marshal(suiteRes)))
return buffer.Bytes()
}
func marshal(item interface{}) []byte {
marshalledResult, err := json.MarshalIndent(item, "", "\t")
if err != nil {
logger.Fatalf("Failed to convert to json :%s\n", err)
}
return marshalledResult
}
func createJSONReport(reportsDir string, jsonContents []byte, nameGen nameGenerator) (string, error) {
var currentReportDir string
if nameGen != nil {
currentReportDir = filepath.Join(reportsDir, jsonReport, nameGen.randomName())
} else {
currentReportDir = filepath.Join(reportsDir, jsonReport)
}
createDirectory(currentReportDir)
return currentReportDir, writeResultJSONFile(currentReportDir, jsonContents)
}
func writeResultJSONFile(reportDir string, jsonContents []byte) error {
resultJsPath := filepath.Join(reportDir, jsonReportFile)
err := ioutil.WriteFile(resultJsPath, jsonContents, common.NewFilePermissions)
if err != nil {
return fmt.Errorf("failed to copy file: %s %s", jsonReportFile, err.Error())
}
return nil
}
func getNameGen() nameGenerator {
var nameGen nameGenerator
if shouldOverwriteReports() {
nameGen = nil
} else {
nameGen = timeStampedNameGenerator{}
}
return nameGen
}
func getDefaultPropertiesFile() string {
return filepath.Join(projectRoot, "env", "default", "default.properties")
}
func shouldOverwriteReports() bool {
envValue := os.Getenv(overwriteReportsEnvProperty)
if strings.ToLower(envValue) == "true" {
return true
}
return false
}
func createReportsDirectory() string {
reportsDir, err := filepath.Abs(os.Getenv(gaugeReportsDirEnvName))
if reportsDir == "" || err != nil {
reportsDir = defaultReportsDir
}
createDirectory(reportsDir)
return reportsDir
}
func createDirectory(dir string) {
if common.DirExists(dir) {
return
}
if err := os.MkdirAll(dir, common.NewDirectoryPermissions); err != nil {
logger.Fatalf("Failed to create directory %s: %s\n", defaultReportsDir, err)
}
}