github.com/SAP/jenkins-library@v1.362.0/cmd/karmaExecuteTests_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 karmaExecuteTestsOptions struct {
    23  	InstallCommand string   `json:"installCommand,omitempty"`
    24  	Modules        []string `json:"modules,omitempty"`
    25  	RunCommand     string   `json:"runCommand,omitempty"`
    26  }
    27  
    28  type karmaExecuteTestsReports struct {
    29  }
    30  
    31  func (p *karmaExecuteTestsReports) persist(stepConfig karmaExecuteTestsOptions, gcpJsonKeyFilePath string, gcsBucketId string, gcsFolderPath string, gcsSubFolder string) {
    32  	if gcsBucketId == "" {
    33  		log.Entry().Info("persisting reports to GCS is disabled, because gcsBucketId is empty")
    34  		return
    35  	}
    36  	log.Entry().Info("Uploading reports to Google Cloud Storage...")
    37  	content := []gcs.ReportOutputParam{
    38  		{FilePattern: "**/TEST-*.xml", ParamRef: "", StepResultType: "karma"},
    39  		{FilePattern: "**/cobertura-coverage.xml", ParamRef: "", StepResultType: "karma"},
    40  		{FilePattern: "**/TEST-*.xml", ParamRef: "", StepResultType: "junit"},
    41  		{FilePattern: "**/jacoco.xml", ParamRef: "", StepResultType: "jacoco-coverage"},
    42  		{FilePattern: "**/cobertura-coverage.xml", ParamRef: "", StepResultType: "cobertura-coverage"},
    43  		{FilePattern: "**/xmake_stage.json", ParamRef: "", StepResultType: "xmake"},
    44  		{FilePattern: "**/requirement.mapping", ParamRef: "", StepResultType: "requirement-mapping"},
    45  	}
    46  	envVars := []gcs.EnvVar{
    47  		{Name: "GOOGLE_APPLICATION_CREDENTIALS", Value: gcpJsonKeyFilePath, Modified: false},
    48  	}
    49  	gcsClient, err := gcs.NewClient(gcs.WithEnvVars(envVars))
    50  	if err != nil {
    51  		log.Entry().Errorf("creation of GCS client failed: %v", err)
    52  		return
    53  	}
    54  	defer gcsClient.Close()
    55  	structVal := reflect.ValueOf(&stepConfig).Elem()
    56  	inputParameters := map[string]string{}
    57  	for i := 0; i < structVal.NumField(); i++ {
    58  		field := structVal.Type().Field(i)
    59  		if field.Type.String() == "string" {
    60  			paramName := strings.Split(field.Tag.Get("json"), ",")
    61  			paramValue, _ := structVal.Field(i).Interface().(string)
    62  			inputParameters[paramName[0]] = paramValue
    63  		}
    64  	}
    65  	if err := gcs.PersistReportsToGCS(gcsClient, content, inputParameters, gcsFolderPath, gcsBucketId, gcsSubFolder, doublestar.Glob, os.Stat); err != nil {
    66  		log.Entry().Errorf("failed to persist reports: %v", err)
    67  	}
    68  }
    69  
    70  // KarmaExecuteTestsCommand Executes the Karma test runner
    71  func KarmaExecuteTestsCommand() *cobra.Command {
    72  	const STEP_NAME = "karmaExecuteTests"
    73  
    74  	metadata := karmaExecuteTestsMetadata()
    75  	var stepConfig karmaExecuteTestsOptions
    76  	var startTime time.Time
    77  	var reports karmaExecuteTestsReports
    78  	var logCollector *log.CollectorHook
    79  	var splunkClient *splunk.Splunk
    80  	telemetryClient := &telemetry.Telemetry{}
    81  
    82  	var createKarmaExecuteTestsCmd = &cobra.Command{
    83  		Use:   STEP_NAME,
    84  		Short: "Executes the Karma test runner",
    85  		Long: `In this step the ([Karma test runner](http://karma-runner.github.io)) is executed.
    86  
    87  The step is using the ` + "`" + `seleniumExecuteTest` + "`" + ` step to spin up two containers in a Docker network:
    88  
    89  * a Selenium/Chrome container (` + "`" + `selenium/standalone-chrome` + "`" + `)
    90  * a NodeJS container (` + "`" + `node:lts-buster` + "`" + `)
    91  
    92  In the Docker network, the containers can be referenced by the values provided in ` + "`" + `dockerName` + "`" + ` and ` + "`" + `sidecarName` + "`" + `, the default values are ` + "`" + `karma` + "`" + ` and ` + "`" + `selenium` + "`" + `. These values must be used in the ` + "`" + `hostname` + "`" + ` properties of the test configuration ([Karma](https://karma-runner.github.io/1.0/config/configuration-file.html) and [WebDriver](https://github.com/karma-runner/karma-webdriver-launcher#usage)).
    93  
    94  !!! note
    95      In a Kubernetes environment, the containers both need to be referenced with ` + "`" + `localhost` + "`" + `.`,
    96  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    97  			startTime = time.Now()
    98  			log.SetStepName(STEP_NAME)
    99  			log.SetVerbose(GeneralConfig.Verbose)
   100  
   101  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
   102  
   103  			path, _ := os.Getwd()
   104  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
   105  			log.RegisterHook(fatalHook)
   106  
   107  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
   108  			if err != nil {
   109  				log.SetErrorCategory(log.ErrorConfiguration)
   110  				return err
   111  			}
   112  
   113  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
   114  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
   115  				log.RegisterHook(&sentryHook)
   116  			}
   117  
   118  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   119  				splunkClient = &splunk.Splunk{}
   120  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   121  				log.RegisterHook(logCollector)
   122  			}
   123  
   124  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
   125  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
   126  			}
   127  
   128  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   129  			if err != nil {
   130  				return err
   131  			}
   132  			if err = validation.ValidateStruct(stepConfig); err != nil {
   133  				log.SetErrorCategory(log.ErrorConfiguration)
   134  				return err
   135  			}
   136  
   137  			return nil
   138  		},
   139  		Run: func(_ *cobra.Command, _ []string) {
   140  			stepTelemetryData := telemetry.CustomData{}
   141  			stepTelemetryData.ErrorCode = "1"
   142  			handler := func() {
   143  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   144  				config.RemoveVaultSecretFiles()
   145  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   146  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   147  				stepTelemetryData.PiperCommitHash = GitCommit
   148  				telemetryClient.SetData(&stepTelemetryData)
   149  				telemetryClient.Send()
   150  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   151  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   152  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   153  						GeneralConfig.HookConfig.SplunkConfig.Token,
   154  						GeneralConfig.HookConfig.SplunkConfig.Index,
   155  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   156  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   157  				}
   158  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   159  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   160  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   161  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   162  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   163  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   164  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   165  				}
   166  			}
   167  			log.DeferExitHandler(handler)
   168  			defer handler()
   169  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   170  			karmaExecuteTests(stepConfig, &stepTelemetryData)
   171  			stepTelemetryData.ErrorCode = "0"
   172  			log.Entry().Info("SUCCESS")
   173  		},
   174  	}
   175  
   176  	addKarmaExecuteTestsFlags(createKarmaExecuteTestsCmd, &stepConfig)
   177  	return createKarmaExecuteTestsCmd
   178  }
   179  
   180  func addKarmaExecuteTestsFlags(cmd *cobra.Command, stepConfig *karmaExecuteTestsOptions) {
   181  	cmd.Flags().StringVar(&stepConfig.InstallCommand, "installCommand", `npm install --quiet`, "The command that is executed to install the test tool.")
   182  	cmd.Flags().StringSliceVar(&stepConfig.Modules, "modules", []string{`.`}, "Define the paths of the modules to execute tests on.")
   183  	cmd.Flags().StringVar(&stepConfig.RunCommand, "runCommand", `npm run karma`, "The command that is executed to start the tests.")
   184  
   185  	cmd.MarkFlagRequired("installCommand")
   186  	cmd.MarkFlagRequired("modules")
   187  	cmd.MarkFlagRequired("runCommand")
   188  }
   189  
   190  // retrieve step metadata
   191  func karmaExecuteTestsMetadata() config.StepData {
   192  	var theMetaData = config.StepData{
   193  		Metadata: config.StepMetadata{
   194  			Name:        "karmaExecuteTests",
   195  			Aliases:     []config.Alias{},
   196  			Description: "Executes the Karma test runner",
   197  		},
   198  		Spec: config.StepSpec{
   199  			Inputs: config.StepInputs{
   200  				Secrets: []config.StepSecrets{
   201  					{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"},
   202  				},
   203  				Resources: []config.StepResources{
   204  					{Name: "buildDescriptor", Type: "stash"},
   205  					{Name: "tests", Type: "stash"},
   206  				},
   207  				Parameters: []config.StepParameters{
   208  					{
   209  						Name:        "installCommand",
   210  						ResourceRef: []config.ResourceReference{},
   211  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   212  						Type:        "string",
   213  						Mandatory:   true,
   214  						Aliases:     []config.Alias{},
   215  						Default:     `npm install --quiet`,
   216  					},
   217  					{
   218  						Name:        "modules",
   219  						ResourceRef: []config.ResourceReference{},
   220  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   221  						Type:        "[]string",
   222  						Mandatory:   true,
   223  						Aliases:     []config.Alias{},
   224  						Default:     []string{`.`},
   225  					},
   226  					{
   227  						Name:        "runCommand",
   228  						ResourceRef: []config.ResourceReference{},
   229  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   230  						Type:        "string",
   231  						Mandatory:   true,
   232  						Aliases:     []config.Alias{},
   233  						Default:     `npm run karma`,
   234  					},
   235  				},
   236  			},
   237  			Containers: []config.Container{
   238  				{Name: "karma", Image: "node:lts-buster", EnvVars: []config.EnvVar{{Name: "no_proxy", Value: "localhost,selenium,$no_proxy"}, {Name: "NO_PROXY", Value: "localhost,selenium,$NO_PROXY"}, {Name: "PIPER_SELENIUM_HOSTNAME", Value: "karma"}, {Name: "PIPER_SELENIUM_WEBDRIVER_HOSTNAME", Value: "selenium"}, {Name: "PIPER_SELENIUM_WEBDRIVER_PORT", Value: "4444"}}, WorkingDir: "/home/node"},
   239  			},
   240  			Sidecars: []config.Container{
   241  				{Name: "selenium", Image: "selenium/standalone-chrome", EnvVars: []config.EnvVar{{Name: "NO_PROXY", Value: "localhost,karma,$NO_PROXY"}, {Name: "no_proxy", Value: "localhost,selenium,$no_proxy"}}},
   242  			},
   243  			Outputs: config.StepOutputs{
   244  				Resources: []config.StepResources{
   245  					{
   246  						Name: "reports",
   247  						Type: "reports",
   248  						Parameters: []map[string]interface{}{
   249  							{"filePattern": "**/TEST-*.xml", "type": "karma"},
   250  							{"filePattern": "**/cobertura-coverage.xml", "type": "karma"},
   251  							{"filePattern": "**/TEST-*.xml", "type": "junit"},
   252  							{"filePattern": "**/jacoco.xml", "type": "jacoco-coverage"},
   253  							{"filePattern": "**/cobertura-coverage.xml", "type": "cobertura-coverage"},
   254  							{"filePattern": "**/xmake_stage.json", "type": "xmake"},
   255  							{"filePattern": "**/requirement.mapping", "type": "requirement-mapping"},
   256  						},
   257  					},
   258  				},
   259  			},
   260  		},
   261  	}
   262  	return theMetaData
   263  }