github.com/jaylevin/jenkins-library@v1.230.4/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-stretch` + "`" + `)
    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 {
   119  				splunkClient = &splunk.Splunk{}
   120  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   121  				log.RegisterHook(logCollector)
   122  			}
   123  
   124  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   125  			if err != nil {
   126  				return err
   127  			}
   128  			if err = validation.ValidateStruct(stepConfig); err != nil {
   129  				log.SetErrorCategory(log.ErrorConfiguration)
   130  				return err
   131  			}
   132  
   133  			return nil
   134  		},
   135  		Run: func(_ *cobra.Command, _ []string) {
   136  			stepTelemetryData := telemetry.CustomData{}
   137  			stepTelemetryData.ErrorCode = "1"
   138  			handler := func() {
   139  				reports.persist(stepConfig, GeneralConfig.GCPJsonKeyFilePath, GeneralConfig.GCSBucketId, GeneralConfig.GCSFolderPath, GeneralConfig.GCSSubFolder)
   140  				config.RemoveVaultSecretFiles()
   141  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   142  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   143  				stepTelemetryData.PiperCommitHash = GitCommit
   144  				telemetryClient.SetData(&stepTelemetryData)
   145  				telemetryClient.Send()
   146  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   147  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   148  				}
   149  			}
   150  			log.DeferExitHandler(handler)
   151  			defer handler()
   152  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   153  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   154  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   155  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   156  					GeneralConfig.HookConfig.SplunkConfig.Token,
   157  					GeneralConfig.HookConfig.SplunkConfig.Index,
   158  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   159  			}
   160  			karmaExecuteTests(stepConfig, &stepTelemetryData)
   161  			stepTelemetryData.ErrorCode = "0"
   162  			log.Entry().Info("SUCCESS")
   163  		},
   164  	}
   165  
   166  	addKarmaExecuteTestsFlags(createKarmaExecuteTestsCmd, &stepConfig)
   167  	return createKarmaExecuteTestsCmd
   168  }
   169  
   170  func addKarmaExecuteTestsFlags(cmd *cobra.Command, stepConfig *karmaExecuteTestsOptions) {
   171  	cmd.Flags().StringVar(&stepConfig.InstallCommand, "installCommand", `npm install --quiet`, "The command that is executed to install the test tool.")
   172  	cmd.Flags().StringSliceVar(&stepConfig.Modules, "modules", []string{`.`}, "Define the paths of the modules to execute tests on.")
   173  	cmd.Flags().StringVar(&stepConfig.RunCommand, "runCommand", `npm run karma`, "The command that is executed to start the tests.")
   174  
   175  	cmd.MarkFlagRequired("installCommand")
   176  	cmd.MarkFlagRequired("modules")
   177  	cmd.MarkFlagRequired("runCommand")
   178  }
   179  
   180  // retrieve step metadata
   181  func karmaExecuteTestsMetadata() config.StepData {
   182  	var theMetaData = config.StepData{
   183  		Metadata: config.StepMetadata{
   184  			Name:        "karmaExecuteTests",
   185  			Aliases:     []config.Alias{},
   186  			Description: "Executes the Karma test runner",
   187  		},
   188  		Spec: config.StepSpec{
   189  			Inputs: config.StepInputs{
   190  				Secrets: []config.StepSecrets{
   191  					{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"},
   192  				},
   193  				Resources: []config.StepResources{
   194  					{Name: "buildDescriptor", Type: "stash"},
   195  					{Name: "tests", Type: "stash"},
   196  				},
   197  				Parameters: []config.StepParameters{
   198  					{
   199  						Name:        "installCommand",
   200  						ResourceRef: []config.ResourceReference{},
   201  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   202  						Type:        "string",
   203  						Mandatory:   true,
   204  						Aliases:     []config.Alias{},
   205  						Default:     `npm install --quiet`,
   206  					},
   207  					{
   208  						Name:        "modules",
   209  						ResourceRef: []config.ResourceReference{},
   210  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   211  						Type:        "[]string",
   212  						Mandatory:   true,
   213  						Aliases:     []config.Alias{},
   214  						Default:     []string{`.`},
   215  					},
   216  					{
   217  						Name:        "runCommand",
   218  						ResourceRef: []config.ResourceReference{},
   219  						Scope:       []string{"GENERAL", "PARAMETERS", "STAGES", "STEPS"},
   220  						Type:        "string",
   221  						Mandatory:   true,
   222  						Aliases:     []config.Alias{},
   223  						Default:     `npm run karma`,
   224  					},
   225  				},
   226  			},
   227  			Containers: []config.Container{
   228  				{Name: "karma", Image: "node:lts-stretch", 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"},
   229  			},
   230  			Sidecars: []config.Container{
   231  				{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"}}},
   232  			},
   233  			Outputs: config.StepOutputs{
   234  				Resources: []config.StepResources{
   235  					{
   236  						Name: "reports",
   237  						Type: "reports",
   238  						Parameters: []map[string]interface{}{
   239  							{"filePattern": "**/TEST-*.xml", "type": "karma"},
   240  							{"filePattern": "**/cobertura-coverage.xml", "type": "karma"},
   241  							{"filePattern": "**/TEST-*.xml", "type": "junit"},
   242  							{"filePattern": "**/jacoco.xml", "type": "jacoco-coverage"},
   243  							{"filePattern": "**/cobertura-coverage.xml", "type": "cobertura-coverage"},
   244  							{"filePattern": "**/xmake_stage.json", "type": "xmake"},
   245  							{"filePattern": "**/requirement.mapping", "type": "requirement-mapping"},
   246  						},
   247  					},
   248  				},
   249  			},
   250  		},
   251  	}
   252  	return theMetaData
   253  }