github.com/SAP/jenkins-library@v1.362.0/cmd/uiVeri5ExecuteTests_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  	"reflect"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/SAP/jenkins-library/pkg/config"
    13  	"github.com/SAP/jenkins-library/pkg/gcs"
    14  	"github.com/SAP/jenkins-library/pkg/log"
    15  	"github.com/SAP/jenkins-library/pkg/splunk"
    16  	"github.com/SAP/jenkins-library/pkg/telemetry"
    17  	"github.com/SAP/jenkins-library/pkg/validation"
    18  	"github.com/bmatcuk/doublestar"
    19  	"github.com/spf13/cobra"
    20  )
    21  
    22  type uiVeri5ExecuteTestsOptions struct {
    23  	InstallCommand string   `json:"installCommand,omitempty"`
    24  	RunCommand     string   `json:"runCommand,omitempty"`
    25  	RunOptions     []string `json:"runOptions,omitempty"`
    26  	TestOptions    string   `json:"testOptions,omitempty"`
    27  	TestServerURL  string   `json:"testServerUrl,omitempty"`
    28  }
    29  
    30  type uiVeri5ExecuteTestsReports struct {
    31  }
    32  
    33  func (p *uiVeri5ExecuteTestsReports) persist(stepConfig uiVeri5ExecuteTestsOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) {
    34  	if gcsBucketId == "" {
    35  		log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty")
    36  		return
    37  	}
    38  	log.Entry().Info("Uploading reports to Google Cloud Storage...")
    39  	content := []gcs.ReportOutputParam{
    40  		{FilePattern: "**/TEST-*.xml", ParamRef: "", StepResultType: "acceptance-test"},
    41  		{FilePattern: "**/requirement.mapping", ParamRef: "", StepResultType: "requirement-mapping"},
    42  		{FilePattern: "**/delivery.mapping", ParamRef: "", StepResultType: "delivery-mapping"},
    43  	}
    44  	envVars := []gcs.EnvVar{
    45  		{Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false},
    46  	}
    47  	gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars))
    48  	if err != nil {
    49  		log.Entry().Errorf("creation of GCS client failed: %v", err)
    50  		return
    51  	}
    52  	defer gcsClient.Close()
    53  	structVal := reflect.ValueOf(&stepConfig).Elem()
    54  	inputParameters := map[string]string{}
    55  	for i := 0; i < structVal.NumField(); i++ {
    56  		field := structVal.Type().Field(i)
    57  		if field.Type.String() == "string" {
    58  			paramName := strings.Split(field.Tag.Get("json"), ",")
    59  			paramValue, _ := structVal.Field(i).Interface().(string)
    60  			inputParameters[paramName[0]] = paramValue
    61  		}
    62  	}
    63  	if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil {
    64  		log.Entry().Errorf("failed to persist reports: %v", err)
    65  	}
    66  }
    67  
    68  // UiVeri5ExecuteTestsCommand Executes UI5 e2e tests using uiVeri5
    69  func UiVeri5ExecuteTestsCommand() *cobra.Command {
    70  	const STEP_NAME = "uiVeri5ExecuteTests"
    71  
    72  	metadata := uiVeri5ExecuteTestsMetadata()
    73  	var stepConfig uiVeri5ExecuteTestsOptions
    74  	var startTime time.Time
    75  	var reports uiVeri5ExecuteTestsReports
    76  	var logCollector *log.CollectorHook
    77  	var splunkClient *splunk.Splunk
    78  	telemetryClient := &telemetry.Telemetry{}
    79  
    80  	var createUiVeri5ExecuteTestsCmd = &cobra.Command{
    81  		Use:   STEP_NAME,
    82  		Short: "Executes UI5 e2e tests using uiVeri5",
    83  		Long:  `In this step the ([UIVeri5 tests](https://github.com/SAP/ui5-uiveri5)) are executed.`,
    84  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    85  			startTime = time.Now()
    86  			log.SetStepName(STEP_NAME)
    87  			log.SetVerbose(GeneralConfig.Verbose)
    88  
    89  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    90  
    91  			path, _ := os.Getwd()
    92  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    93  			log.RegisterHook(fatalHook)
    94  
    95  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    96  			if err != nil {
    97  				log.SetErrorCategory(log.ErrorConfiguration)
    98  				return err
    99  			}
   100  
   101  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   102  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   103  				log.RegisterHook(&sentryHook)
   104  			}
   105  
   106  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   107  				splunkClient = &splunk.Splunk{}
   108  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   109  				log.RegisterHook(logCollector)
   110  			}
   111  
   112  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   113  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   114  			}
   115  
   116  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   117  			if err != nil {
   118  				return err
   119  			}
   120  			if err = validation.ValidateStruct(stepConfig); err != nil {
   121  				log.SetErrorCategory(log.ErrorConfiguration)
   122  				return err
   123  			}
   124  
   125  			return nil
   126  		},
   127  		Run: func(_ *cobra.Command, _ []string) {
   128  			stepTelemetryData := telemetry.CustomData{}
   129  			stepTelemetryData.ErrorCode = "1"
   130  			handler := func() {
   131  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   132  				config.RemoveVaultSecretFiles()
   133  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   134  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   135  				stepTelemetryData.PiperCommitHash = GitCommit
   136  				telemetryClient.SetData(&stepTelemetryData)
   137  				telemetryClient.Send()
   138  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   139  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   140  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   141  						GeneralConfig.HookConfig.SplunkConfig.Token,
   142  						GeneralConfig.HookConfig.SplunkConfig.Index,
   143  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   144  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   145  				}
   146  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   147  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   148  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   149  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   150  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   151  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   152  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   153  				}
   154  			}
   155  			log.DeferExitHandler(handler)
   156  			defer handler()
   157  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   158  			uiVeri5ExecuteTests(stepConfig, &stepTelemetryData)
   159  			stepTelemetryData.ErrorCode = "0"
   160  			log.Entry().Info("SUCCESS")
   161  		},
   162  	}
   163  
   164  	addUiVeri5ExecuteTestsFlags(createUiVeri5ExecuteTestsCmd, &stepConfig)
   165  	return createUiVeri5ExecuteTestsCmd
   166  }
   167  
   168  func addUiVeri5ExecuteTestsFlags(cmd *cobra.Command, stepConfig *uiVeri5ExecuteTestsOptions) {
   169  	cmd.Flags().StringVar(&stepConfig.InstallCommand, "installCommand", `npm install @ui5/uiveri5 --global --quiet`, "The command that is executed to install the uiveri5 test tool.")
   170  	cmd.Flags().StringVar(&stepConfig.RunCommand, "runCommand", `/home/node/.npm-global/bin/uiveri5`, "The command that is executed to start the tests.")
   171  	cmd.Flags().StringSliceVar(&stepConfig.RunOptions, "runOptions", []string{`--seleniumAddress=http://localhost:4444/wd/hub`}, "Options to append to the runCommand, last parameter has to be path to conf.js (default if missing: ./conf.js).")
   172  	cmd.Flags().StringVar(&stepConfig.TestOptions, "testOptions", os.Getenv("PIPER_testOptions"), "Deprecated and will result in an error if set. Please use runOptions instead. Split the testOptions string at the whitespaces when migrating it into a list of runOptions.")
   173  	cmd.Flags().StringVar(&stepConfig.TestServerURL, "testServerUrl", os.Getenv("PIPER_testServerUrl"), "URL pointing to the deployment.")
   174  
   175  	cmd.MarkFlagRequired("installCommand")
   176  	cmd.MarkFlagRequired("runCommand")
   177  	cmd.MarkFlagRequired("runOptions")
   178  }
   179  
   180  // retrieve step metadata
   181  func uiVeri5ExecuteTestsMetadata() config.StepData {
   182  	var theMetaData = config.StepData{
   183  		Metadata: config.StepMetadata{
   184  			Name:        "uiVeri5ExecuteTests",
   185  			Aliases:     []config.Alias{},
   186  			Description: "Executes UI5 e2e tests using uiVeri5",
   187  		},
   188  		Spec: config.StepSpec{
   189  			Inputs: config.StepInputs{
   190  				Resources: []config.StepResources{
   191  					{Name: "buildDescriptor", Type: "stash"},
   192  					{Name: "tests", Type: "stash"},
   193  				},
   194  				Parameters: []config.StepParameters{
   195  					{
   196  						Name:        "installCommand",
   197  						ResourceRef: []config.ResourceReference{},
   198  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   199  						Type:        "string",
   200  						Mandatory:   true,
   201  						Aliases:     []config.Alias{},
   202  						Default:     `npm install @ui5/uiveri5 --global --quiet`,
   203  					},
   204  					{
   205  						Name:        "runCommand",
   206  						ResourceRef: []config.ResourceReference{},
   207  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   208  						Type:        "string",
   209  						Mandatory:   true,
   210  						Aliases:     []config.Alias{},
   211  						Default:     `/home/node/.npm-global/bin/uiveri5`,
   212  					},
   213  					{
   214  						Name:        "runOptions",
   215  						ResourceRef: []config.ResourceReference{},
   216  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   217  						Type:        "[]string",
   218  						Mandatory:   true,
   219  						Aliases:     []config.Alias{},
   220  						Default:     []string{`--seleniumAddress=http://localhost:4444/wd/hub`},
   221  					},
   222  					{
   223  						Name:        "testOptions",
   224  						ResourceRef: []config.ResourceReference{},
   225  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   226  						Type:        "string",
   227  						Mandatory:   false,
   228  						Aliases:     []config.Alias{},
   229  						Default:     os.Getenv("PIPER_testOptions"),
   230  					},
   231  					{
   232  						Name:        "testServerUrl",
   233  						ResourceRef: []config.ResourceReference{},
   234  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   235  						Type:        "string",
   236  						Mandatory:   false,
   237  						Aliases:     []config.Alias{},
   238  						Default:     os.Getenv("PIPER_testServerUrl"),
   239  					},
   240  				},
   241  			},
   242  			Containers: []config.Container{
   243  				{Name: "uiVeri5", Image: "node:lts-buster", EnvVars: []config.EnvVar{{Name: "no_proxy", Value: "localhost,selenium,$no_proxy"}, {Name: "NO_PROXY", Value: "localhost,selenium,$NO_PROXY"}}, WorkingDir: "/home/node"},
   244  			},
   245  			Sidecars: []config.Container{
   246  				{Name: "selenium", Image: "selenium/standalone-chrome", EnvVars: []config.EnvVar{{Name: "NO_PROXY", Value: "localhost,selenium,$NO_PROXY"}, {Name: "no_proxy", Value: "localhost,selenium,$no_proxy"}}},
   247  			},
   248  			Outputs: config.StepOutputs{
   249  				Resources: []config.StepResources{
   250  					{
   251  						Name: "reports",
   252  						Type: "reports",
   253  						Parameters: []map[string]interface{}{
   254  							{"filePattern": "**/TEST-*.xml", "type": "acceptance-test"},
   255  							{"filePattern": "**/requirement.mapping", "type": "requirement-mapping"},
   256  							{"filePattern": "**/delivery.mapping", "type": "delivery-mapping"},
   257  						},
   258  					},
   259  				},
   260  			},
   261  		},
   262  	}
   263  	return theMetaData
   264  }