github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/cmd/gaugeExecuteTests_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 gaugeExecuteTestsOptions struct {
    25  	InstallCommand string `json:"installCommand,omitempty"`
    26  	LanguageRunner string `json:"languageRunner,omitempty"`
    27  	RunCommand     string `json:"runCommand,omitempty"`
    28  	TestOptions    string `json:"testOptions,omitempty"`
    29  }
    30  
    31  type gaugeExecuteTestsInflux struct {
    32  	step_data struct {
    33  		fields struct {
    34  			gauge bool
    35  		}
    36  		tags struct {
    37  		}
    38  	}
    39  }
    40  
    41  func (i *gaugeExecuteTestsInflux) persist(path, resourceName string) {
    42  	measurementContent := []struct {
    43  		measurement string
    44  		valType     string
    45  		name        string
    46  		value       interface{}
    47  	}{
    48  		{valType: config.InfluxField, measurement: "step_data", name: "gauge", value: i.step_data.fields.gauge},
    49  	}
    50  
    51  	errCount := 0
    52  	for _, metric := range measurementContent {
    53  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(metric.measurement, fmt.Sprintf("%vs", metric.valType), metric.name), metric.value)
    54  		if err != nil {
    55  			log.Entry().WithError(err).Error("Error persisting influx environment.")
    56  			errCount++
    57  		}
    58  	}
    59  	if errCount > 0 {
    60  		log.Entry().Error("failed to persist Influx environment")
    61  	}
    62  }
    63  
    64  type gaugeExecuteTestsReports struct {
    65  }
    66  
    67  func (p *gaugeExecuteTestsReports) persist(stepConfig gaugeExecuteTestsOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) {
    68  	if gcsBucketId == "" {
    69  		log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty")
    70  		return
    71  	}
    72  	log.Entry().Info("Uploading reports to Google Cloud Storage...")
    73  	content := []gcs.ReportOutputParam{
    74  		{FilePattern: "**/TEST-*.xml", ParamRef: "", StepResultType: "acceptance-test"},
    75  		{FilePattern: "**/requirement.mapping", ParamRef: "", StepResultType: "requirement-mapping"},
    76  		{FilePattern: "**/delivery.mapping", ParamRef: "", StepResultType: "delivery-mapping"},
    77  	}
    78  	envVars := []gcs.EnvVar{
    79  		{Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false},
    80  	}
    81  	gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars))
    82  	if err != nil {
    83  		log.Entry().Errorf("creation of GCS client failed: %v", err)
    84  		return
    85  	}
    86  	defer gcsClient.Close()
    87  	structVal := reflect.ValueOf(&stepConfig).Elem()
    88  	inputParameters := map[string]string{}
    89  	for i := 0; i < structVal.NumField(); i++ {
    90  		field := structVal.Type().Field(i)
    91  		if field.Type.String() == "string" {
    92  			paramName := strings.Split(field.Tag.Get("json"), ",")
    93  			paramValue, _ := structVal.Field(i).Interface().(string)
    94  			inputParameters[paramName[0]] = paramValue
    95  		}
    96  	}
    97  	if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil {
    98  		log.Entry().Errorf("failed to persist reports: %v", err)
    99  	}
   100  }
   101  
   102  // GaugeExecuteTestsCommand Installs gauge and executes specified gauge tests.
   103  func GaugeExecuteTestsCommand() *cobra.Command {
   104  	const STEP_NAME = "gaugeExecuteTests"
   105  
   106  	metadata := gaugeExecuteTestsMetadata()
   107  	var stepConfig gaugeExecuteTestsOptions
   108  	var startTime time.Time
   109  	var influx gaugeExecuteTestsInflux
   110  	var reports gaugeExecuteTestsReports
   111  	var logCollector *log.CollectorHook
   112  	var splunkClient *splunk.Splunk
   113  	telemetryClient := &telemetry.Telemetry{}
   114  
   115  	var createGaugeExecuteTestsCmd = &cobra.Command{
   116  		Use:   STEP_NAME,
   117  		Short: "Installs gauge and executes specified gauge tests.",
   118  		Long: `In this step Gauge ([getgauge.io](https://getgauge.io)) acceptance tests are executed. Using Gauge it will be possible to have a three-tier test layout:
   119  
   120  Acceptance Criteria
   121  Test implemenation layer
   122  Application driver layer
   123  
   124  This layout is propagated by Jez Humble and Dave Farley in their book "Continuous Delivery" as a way to create maintainable acceptance test suites (see "Continuous Delivery", p. 190ff).
   125  
   126  Using Gauge it is possible to write test specifications in [Markdown syntax](http://daringfireball.net/projects/markdown/syntax) and therefore allow e.g. product owners to write the relevant acceptance test specifications. At the same time it allows the developer to implement the steps described in the specification in her development environment.
   127  
   128  You can use the [sample projects](https://github.com/getgauge/gauge-mvn-archetypes) of Gauge.`,
   129  		PreRunE: func(cmd *cobra.Command, _ []string) error {
   130  			startTime = time.Now()
   131  			log.SetStepName(STEP_NAME)
   132  			log.SetVerbose(GeneralConfig.Verbose)
   133  
   134  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
   135  
   136  			path, _ := os.Getwd()
   137  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
   138  			log.RegisterHook(fatalHook)
   139  
   140  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
   141  			if err != nil {
   142  				log.SetErrorCategory(log.ErrorConfiguration)
   143  				return err
   144  			}
   145  
   146  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   147  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   148  				log.RegisterHook(&sentryHook)
   149  			}
   150  
   151  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   152  				splunkClient = &splunk.Splunk{}
   153  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   154  				log.RegisterHook(logCollector)
   155  			}
   156  
   157  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   158  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   159  			}
   160  
   161  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   162  			if err != nil {
   163  				return err
   164  			}
   165  			if err = validation.ValidateStruct(stepConfig); err != nil {
   166  				log.SetErrorCategory(log.ErrorConfiguration)
   167  				return err
   168  			}
   169  
   170  			return nil
   171  		},
   172  		Run: func(_ *cobra.Command, _ []string) {
   173  			stepTelemetryData := telemetry.CustomData{}
   174  			stepTelemetryData.ErrorCode = "1"
   175  			handler := func() {
   176  				influx.persist(GeneralConfig.EnvRootPath, "influx")
   177  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   178  				config.RemoveVaultSecretFiles()
   179  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   180  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   181  				stepTelemetryData.PiperCommitHash = GitCommit
   182  				telemetryClient.SetData(&stepTelemetryData)
   183  				telemetryClient.Send()
   184  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   185  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   186  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   187  						GeneralConfig.HookConfig.SplunkConfig.Token,
   188  						GeneralConfig.HookConfig.SplunkConfig.Index,
   189  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   190  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   191  				}
   192  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   193  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   194  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   195  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   196  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   197  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   198  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   199  				}
   200  			}
   201  			log.DeferExitHandler(handler)
   202  			defer handler()
   203  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   204  			gaugeExecuteTests(stepConfig, &stepTelemetryData, &influx)
   205  			stepTelemetryData.ErrorCode = "0"
   206  			log.Entry().Info("SUCCESS")
   207  		},
   208  	}
   209  
   210  	addGaugeExecuteTestsFlags(createGaugeExecuteTestsCmd, &stepConfig)
   211  	return createGaugeExecuteTestsCmd
   212  }
   213  
   214  func addGaugeExecuteTestsFlags(cmd *cobra.Command, stepConfig *gaugeExecuteTestsOptions) {
   215  	cmd.Flags().StringVar(&stepConfig.InstallCommand, "installCommand", os.Getenv("PIPER_installCommand"), "Defines the command for installing Gauge. Gauge should be installed using npm. Example: npm install -g @getgauge/cli@1.2.1")
   216  	cmd.Flags().StringVar(&stepConfig.LanguageRunner, "languageRunner", os.Getenv("PIPER_languageRunner"), "Defines the Gauge language runner to be used. Example: java")
   217  	cmd.Flags().StringVar(&stepConfig.RunCommand, "runCommand", os.Getenv("PIPER_runCommand"), "Defines the command which is used for executing Gauge. Example: run -s -p specs/")
   218  	cmd.Flags().StringVar(&stepConfig.TestOptions, "testOptions", os.Getenv("PIPER_testOptions"), "Allows to set specific options for the Gauge execution. Details can be found for example [in the Gauge Maven plugin documentation](https://github.com/getgauge-contrib/gauge-maven-plugin#executing-specs)")
   219  
   220  	cmd.MarkFlagRequired("runCommand")
   221  }
   222  
   223  // retrieve step metadata
   224  func gaugeExecuteTestsMetadata() config.StepData {
   225  	var theMetaData = config.StepData{
   226  		Metadata: config.StepMetadata{
   227  			Name:        "gaugeExecuteTests",
   228  			Aliases:     []config.Alias{},
   229  			Description: "Installs gauge and executes specified gauge tests.",
   230  		},
   231  		Spec: config.StepSpec{
   232  			Inputs: config.StepInputs{
   233  				Secrets: []config.StepSecrets{
   234  					{Name: "seleniumHubCredentialsId", Description: "Defines the id of the user/password credentials to be used to connect to a Selenium Hub. The credentials are provided in the environment variables `PIPER_SELENIUM_HUB_USER` and `PIPER_SELENIUM_HUB_PASSWORD`.", Type: "jenkins"},
   235  				},
   236  				Resources: []config.StepResources{
   237  					{Name: "buildDescriptor", Type: "stash"},
   238  					{Name: "tests", Type: "stash"},
   239  				},
   240  				Parameters: []config.StepParameters{
   241  					{
   242  						Name:        "installCommand",
   243  						ResourceRef: []config.ResourceReference{},
   244  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   245  						Type:        "string",
   246  						Mandatory:   false,
   247  						Aliases:     []config.Alias{},
   248  						Default:     os.Getenv("PIPER_installCommand"),
   249  					},
   250  					{
   251  						Name:        "languageRunner",
   252  						ResourceRef: []config.ResourceReference{},
   253  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   254  						Type:        "string",
   255  						Mandatory:   false,
   256  						Aliases:     []config.Alias{},
   257  						Default:     os.Getenv("PIPER_languageRunner"),
   258  					},
   259  					{
   260  						Name:        "runCommand",
   261  						ResourceRef: []config.ResourceReference{},
   262  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   263  						Type:        "string",
   264  						Mandatory:   true,
   265  						Aliases:     []config.Alias{},
   266  						Default:     os.Getenv("PIPER_runCommand"),
   267  					},
   268  					{
   269  						Name:        "testOptions",
   270  						ResourceRef: []config.ResourceReference{},
   271  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   272  						Type:        "string",
   273  						Mandatory:   false,
   274  						Aliases:     []config.Alias{},
   275  						Default:     os.Getenv("PIPER_testOptions"),
   276  					},
   277  				},
   278  			},
   279  			Containers: []config.Container{
   280  				{Name: "gauge", 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"},
   281  			},
   282  			Sidecars: []config.Container{
   283  				{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"}}},
   284  			},
   285  			Outputs: config.StepOutputs{
   286  				Resources: []config.StepResources{
   287  					{
   288  						Name: "influx",
   289  						Type: "influx",
   290  						Parameters: []map[string]interface{}{
   291  							{"name": "step_data", "fields": []map[string]string{{"name": "gauge"}}},
   292  						},
   293  					},
   294  					{
   295  						Name: "reports",
   296  						Type: "reports",
   297  						Parameters: []map[string]interface{}{
   298  							{"filePattern": "**/TEST-*.xml", "type": "acceptance-test"},
   299  							{"filePattern": "**/requirement.mapping", "type": "requirement-mapping"},
   300  							{"filePattern": "**/delivery.mapping", "type": "delivery-mapping"},
   301  						},
   302  					},
   303  				},
   304  			},
   305  		},
   306  	}
   307  	return theMetaData
   308  }