github.com/jaylevin/jenkins-library@v1.230.4/cmd/newmanExecute_generated.go (about) 1 // Code generated by piper's step-generator. DO NOT EDIT. 2 3 package cmd 4 5 import ( 6 "fmt" 7 "os" 8 "path/filepath" 9 "reflect" 10 "strings" 11 "time" 12 13 "github.com/SAP/jenkins-library/pkg/config" 14 "github.com/SAP/jenkins-library/pkg/gcs" 15 "github.com/SAP/jenkins-library/pkg/log" 16 "github.com/SAP/jenkins-library/pkg/piperenv" 17 "github.com/SAP/jenkins-library/pkg/splunk" 18 "github.com/SAP/jenkins-library/pkg/telemetry" 19 "github.com/SAP/jenkins-library/pkg/validation" 20 "github.com/bmatcuk/doublestar" 21 "github.com/spf13/cobra" 22 ) 23 24 type newmanExecuteOptions struct { 25 NewmanCollection string `json:"newmanCollection,omitempty"` 26 NewmanRunCommand string `json:"newmanRunCommand,omitempty"` 27 RunOptions []string `json:"runOptions,omitempty"` 28 NewmanInstallCommand string `json:"newmanInstallCommand,omitempty"` 29 NewmanEnvironment string `json:"newmanEnvironment,omitempty"` 30 NewmanGlobals string `json:"newmanGlobals,omitempty"` 31 FailOnError bool `json:"failOnError,omitempty"` 32 CfAppsWithSecrets []string `json:"cfAppsWithSecrets,omitempty"` 33 } 34 35 type newmanExecuteInflux struct { 36 step_data struct { 37 fields struct { 38 newman bool 39 } 40 tags struct { 41 } 42 } 43 } 44 45 func (i *newmanExecuteInflux) persist(path, resourceName string) { 46 measurementContent := []struct { 47 measurement string 48 valType string 49 name string 50 value interface{} 51 }{ 52 {valType: config.InfluxField, measurement: "step_data", name: "newman", value: i.step_data.fields.newman}, 53 } 54 55 errCount := 0 56 for _, metric := range measurementContent { 57 err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(metric.measurement, fmt.Sprintf("%vs", metric.valType), metric.name), metric.value) 58 if err != nil { 59 log.Entry().WithError(err).Error("Error persisting influx environment.") 60 errCount++ 61 } 62 } 63 if errCount > 0 { 64 log.Entry().Error("failed to persist Influx environment") 65 } 66 } 67 68 type newmanExecuteReports struct { 69 } 70 71 func (p *newmanExecuteReports) persist(stepConfig newmanExecuteOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) { 72 if gcsBucketId == "" { 73 log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty") 74 return 75 } 76 log.Entry().Info("Uploading reports to Google Cloud Storage...") 77 content := []gcs.ReportOutputParam{ 78 {FilePattern: "**/TEST-*.xml", ParamRef: "", StepResultType: "acceptance-test"}, 79 {FilePattern: "**/requirement.mapping", ParamRef: "", StepResultType: "requirement-mapping"}, 80 {FilePattern: "**/delivery.mapping", ParamRef: "", StepResultType: "delivery-mapping"}, 81 } 82 envVars := []gcs.EnvVar{ 83 {Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false}, 84 } 85 gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars)) 86 if err != nil { 87 log.Entry().Errorf("creation of GCS client failed: %v", err) 88 return 89 } 90 defer gcsClient.Close() 91 structVal := reflect.ValueOf(&stepConfig).Elem() 92 inputParameters := map[string]string{} 93 for i := 0; i < structVal.NumField(); i++ { 94 field := structVal.Type().Field(i) 95 if field.Type.String() == "string" { 96 paramName := strings.Split(field.Tag.Get("json"), ",") 97 paramValue, _ := structVal.Field(i).Interface().(string) 98 inputParameters[paramName[0]] = paramValue 99 } 100 } 101 if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil { 102 log.Entry().Errorf("failed to persist reports: %v", err) 103 } 104 } 105 106 // NewmanExecuteCommand Installs newman and executes specified newman collections. 107 func NewmanExecuteCommand() *cobra.Command { 108 const STEP_NAME = "newmanExecute" 109 110 metadata := newmanExecuteMetadata() 111 var stepConfig newmanExecuteOptions 112 var startTime time.Time 113 var influx newmanExecuteInflux 114 var reports newmanExecuteReports 115 var logCollector *log.CollectorHook 116 var splunkClient *splunk.Splunk 117 telemetryClient := &telemetry.Telemetry{} 118 119 var createNewmanExecuteCmd = &cobra.Command{ 120 Use: STEP_NAME, 121 Short: "Installs newman and executes specified newman collections.", 122 Long: `This script executes [Postman](https://www.getpostman.com) tests from a collection via the [Newman](https://www.getpostman.com/docs/v6/postman/collection_runs/command_line_integration_with_newman) command line tool.`, 123 PreRunE: func(cmd *cobra.Command, _ []string) error { 124 startTime = time.Now() 125 log.SetStepName(STEP_NAME) 126 log.SetVerbose(GeneralConfig.Verbose) 127 128 GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens) 129 130 path, _ := os.Getwd() 131 fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path} 132 log.RegisterHook(fatalHook) 133 134 err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile) 135 if err != nil { 136 log.SetErrorCategory(log.ErrorConfiguration) 137 return err 138 } 139 140 if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 { 141 sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID) 142 log.RegisterHook(&sentryHook) 143 } 144 145 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 146 splunkClient = &splunk.Splunk{} 147 logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID} 148 log.RegisterHook(logCollector) 149 } 150 151 validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages()) 152 if err != nil { 153 return err 154 } 155 if err = validation.ValidateStruct(stepConfig); err != nil { 156 log.SetErrorCategory(log.ErrorConfiguration) 157 return err 158 } 159 160 return nil 161 }, 162 Run: func(_ *cobra.Command, _ []string) { 163 stepTelemetryData := telemetry.CustomData{} 164 stepTelemetryData.ErrorCode = "1" 165 handler := func() { 166 influx.persist(GeneralConfig.EnvRootPath, "influx") 167 reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder) 168 config.RemoveVaultSecretFiles() 169 stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds()) 170 stepTelemetryData.ErrorCategory = log.GetErrorCategory().String() 171 stepTelemetryData.PiperCommitHash = GitCommit 172 telemetryClient.SetData(&stepTelemetryData) 173 telemetryClient.Send() 174 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 175 splunkClient.Send(telemetryClient.GetData(), logCollector) 176 } 177 } 178 log.DeferExitHandler(handler) 179 defer handler() 180 telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME) 181 if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { 182 splunkClient.Initialize(GeneralConfig.CorrelationID, 183 GeneralConfig.HookConfig.SplunkConfig.Dsn, 184 GeneralConfig.HookConfig.SplunkConfig.Token, 185 GeneralConfig.HookConfig.SplunkConfig.Index, 186 GeneralConfig.HookConfig.SplunkConfig.SendLogs) 187 } 188 newmanExecute(stepConfig, &stepTelemetryData, &influx) 189 stepTelemetryData.ErrorCode = "0" 190 log.Entry().Info("SUCCESS") 191 }, 192 } 193 194 addNewmanExecuteFlags(createNewmanExecuteCmd, &stepConfig) 195 return createNewmanExecuteCmd 196 } 197 198 func addNewmanExecuteFlags(cmd *cobra.Command, stepConfig *newmanExecuteOptions) { 199 cmd.Flags().StringVar(&stepConfig.NewmanCollection, "newmanCollection", `**/*.postman_collection.json`, "The test collection that should be executed. This could also be a file pattern.") 200 cmd.Flags().StringVar(&stepConfig.NewmanRunCommand, "newmanRunCommand", os.Getenv("PIPER_newmanRunCommand"), "+++ Deprecated +++ Please use list parameter `runOptions` instead.") 201 cmd.Flags().StringSliceVar(&stepConfig.RunOptions, "runOptions", []string{`run`, `{{.NewmanCollection}}`, `--reporters`, `cli,junit,html`, `--reporter-junit-export`, `target/newman/TEST-{{.CollectionDisplayName}}.xml`, `--reporter-html-export`, `target/newman/TEST-{{.CollectionDisplayName}}.html`}, "The newman command that will be executed inside the docker container.") 202 cmd.Flags().StringVar(&stepConfig.NewmanInstallCommand, "newmanInstallCommand", `npm install newman newman-reporter-html --global --quiet`, "The shell command that will be executed inside the docker container to install Newman.") 203 cmd.Flags().StringVar(&stepConfig.NewmanEnvironment, "newmanEnvironment", os.Getenv("PIPER_newmanEnvironment"), "Specify an environment file path or URL. Environments provide a set of variables that one can use within collections.") 204 cmd.Flags().StringVar(&stepConfig.NewmanGlobals, "newmanGlobals", os.Getenv("PIPER_newmanGlobals"), "Specify the file path or URL for global variables. Global variables are similar to environment variables but have a lower precedence and can be overridden by environment variables having the same name.") 205 cmd.Flags().BoolVar(&stepConfig.FailOnError, "failOnError", true, "Defines the behavior, in case tests fail.") 206 cmd.Flags().StringSliceVar(&stepConfig.CfAppsWithSecrets, "cfAppsWithSecrets", []string{}, "List of CloudFoundry apps with secrets") 207 208 } 209 210 // retrieve step metadata 211 func newmanExecuteMetadata() config.StepData { 212 var theMetaData = config.StepData{ 213 Metadata: config.StepMetadata{ 214 Name: "newmanExecute", 215 Aliases: []config.Alias{}, 216 Description: "Installs newman and executes specified newman collections.", 217 }, 218 Spec: config.StepSpec{ 219 Inputs: config.StepInputs{ 220 Resources: []config.StepResources{ 221 {Name: "tests", Type: "stash"}, 222 }, 223 Parameters: []config.StepParameters{ 224 { 225 Name: "newmanCollection", 226 ResourceRef: []config.ResourceReference{}, 227 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 228 Type: "string", 229 Mandatory: false, 230 Aliases: []config.Alias{}, 231 Default: `**/*.postman_collection.json`, 232 }, 233 { 234 Name: "newmanRunCommand", 235 ResourceRef: []config.ResourceReference{}, 236 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 237 Type: "string", 238 Mandatory: false, 239 Aliases: []config.Alias{}, 240 Default: os.Getenv("PIPER_newmanRunCommand"), 241 }, 242 { 243 Name: "runOptions", 244 ResourceRef: []config.ResourceReference{}, 245 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 246 Type: "[]string", 247 Mandatory: false, 248 Aliases: []config.Alias{}, 249 Default: []string{`run`, `{{.NewmanCollection}}`, `--reporters`, `cli,junit,html`, `--reporter-junit-export`, `target/newman/TEST-{{.CollectionDisplayName}}.xml`, `--reporter-html-export`, `target/newman/TEST-{{.CollectionDisplayName}}.html`}, 250 }, 251 { 252 Name: "newmanInstallCommand", 253 ResourceRef: []config.ResourceReference{}, 254 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 255 Type: "string", 256 Mandatory: false, 257 Aliases: []config.Alias{}, 258 Default: `npm install newman newman-reporter-html --global --quiet`, 259 }, 260 { 261 Name: "newmanEnvironment", 262 ResourceRef: []config.ResourceReference{}, 263 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 264 Type: "string", 265 Mandatory: false, 266 Aliases: []config.Alias{}, 267 Default: os.Getenv("PIPER_newmanEnvironment"), 268 }, 269 { 270 Name: "newmanGlobals", 271 ResourceRef: []config.ResourceReference{}, 272 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 273 Type: "string", 274 Mandatory: false, 275 Aliases: []config.Alias{}, 276 Default: os.Getenv("PIPER_newmanGlobals"), 277 }, 278 { 279 Name: "failOnError", 280 ResourceRef: []config.ResourceReference{}, 281 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 282 Type: "bool", 283 Mandatory: false, 284 Aliases: []config.Alias{}, 285 Default: true, 286 }, 287 { 288 Name: "cfAppsWithSecrets", 289 ResourceRef: []config.ResourceReference{}, 290 Scope: []string{"PARAMETERS", "STAGES", "STEPS"}, 291 Type: "[]string", 292 Mandatory: false, 293 Aliases: []config.Alias{}, 294 Default: []string{}, 295 }, 296 }, 297 }, 298 Containers: []config.Container{ 299 {Name: "newman", Image: "node:lts-stretch", WorkingDir: "/home/node"}, 300 }, 301 Outputs: config.StepOutputs{ 302 Resources: []config.StepResources{ 303 { 304 Name: "influx", 305 Type: "influx", 306 Parameters: []map[string]interface{}{ 307 {"name": "step_data", "fields": []map[string]string{{"name": "newman"}}}, 308 }, 309 }, 310 { 311 Name: "reports", 312 Type: "reports", 313 Parameters: []map[string]interface{}{ 314 {"filePattern": "**/TEST-*.xml", "type": "acceptance-test"}, 315 {"filePattern": "**/requirement.mapping", "type": "requirement-mapping"}, 316 {"filePattern": "**/delivery.mapping", "type": "delivery-mapping"}, 317 }, 318 }, 319 }, 320 }, 321 }, 322 } 323 return theMetaData 324 }