github.com/xgoffin/jenkins-library@v1.154.0/cmd/batsExecuteTests_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  	"time"
    10  
    11  	"github.com/SAP/jenkins-library/pkg/config"
    12  	"github.com/SAP/jenkins-library/pkg/log"
    13  	"github.com/SAP/jenkins-library/pkg/piperenv"
    14  	"github.com/SAP/jenkins-library/pkg/splunk"
    15  	"github.com/SAP/jenkins-library/pkg/telemetry"
    16  	"github.com/SAP/jenkins-library/pkg/validation"
    17  	"github.com/spf13/cobra"
    18  )
    19  
    20  type batsExecuteTestsOptions struct {
    21  	OutputFormat string   `json:"outputFormat,omitempty" validate:"possible-values=tap junit"`
    22  	Repository   string   `json:"repository,omitempty"`
    23  	TestPackage  string   `json:"testPackage,omitempty"`
    24  	TestPath     string   `json:"testPath,omitempty"`
    25  	EnvVars      []string `json:"envVars,omitempty"`
    26  }
    27  
    28  type batsExecuteTestsInflux struct {
    29  	step_data struct {
    30  		fields struct {
    31  			bats bool
    32  		}
    33  		tags struct {
    34  		}
    35  	}
    36  }
    37  
    38  func (i *batsExecuteTestsInflux) persist(path, resourceName string) {
    39  	measurementContent := []struct {
    40  		measurement string
    41  		valType     string
    42  		name        string
    43  		value       interface{}
    44  	}{
    45  		{valType: config.InfluxField, measurement: "step_data", name: "bats", value: i.step_data.fields.bats},
    46  	}
    47  
    48  	errCount := 0
    49  	for _, metric := range measurementContent {
    50  		err := piperenv.SetResourceParameter(path, resourceName, filepath.Join(metric.measurement, fmt.Sprintf("%vs", metric.valType), metric.name), metric.value)
    51  		if err != nil {
    52  			log.Entry().WithError(err).Error("Error persisting influx environment.")
    53  			errCount++
    54  		}
    55  	}
    56  	if errCount > 0 {
    57  		log.Entry().Error("failed to persist Influx environment")
    58  	}
    59  }
    60  
    61  // BatsExecuteTestsCommand This step executes tests using the [Bash Automated Testing System - bats-core](https://github.com/bats-core/bats-core).
    62  func BatsExecuteTestsCommand() *cobra.Command {
    63  	const STEP_NAME = "batsExecuteTests"
    64  
    65  	metadata := batsExecuteTestsMetadata()
    66  	var stepConfig batsExecuteTestsOptions
    67  	var startTime time.Time
    68  	var influx batsExecuteTestsInflux
    69  	var logCollector *log.CollectorHook
    70  	var splunkClient *splunk.Splunk
    71  	telemetryClient := &telemetry.Telemetry{}
    72  
    73  	var createBatsExecuteTestsCmd = &cobra.Command{
    74  		Use:   STEP_NAME,
    75  		Short: "This step executes tests using the [Bash Automated Testing System - bats-core](https://github.com/bats-core/bats-core).",
    76  		Long:  `Bats is a TAP-compliant testing framework for Bash. It provides a simple way to verify that the UNIX programs you write behave as expected. A Bats test file is a Bash script with special syntax for defining test cases. Under the hood, each test case is just a function with a description.`,
    77  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    78  			startTime = time.Now()
    79  			log.SetStepName(STEP_NAME)
    80  			log.SetVerbose(GeneralConfig.Verbose)
    81  
    82  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    83  
    84  			path, _ := os.Getwd()
    85  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    86  			log.RegisterHook(fatalHook)
    87  
    88  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    89  			if err != nil {
    90  				log.SetErrorCategory(log.ErrorConfiguration)
    91  				return err
    92  			}
    93  
    94  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    95  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    96  				log.RegisterHook(&sentryHook)
    97  			}
    98  
    99  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   100  				splunkClient = &splunk.Splunk{}
   101  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
   102  				log.RegisterHook(logCollector)
   103  			}
   104  
   105  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
   106  			if err != nil {
   107  				return err
   108  			}
   109  			if err = validation.ValidateStruct(stepConfig); err != nil {
   110  				log.SetErrorCategory(log.ErrorConfiguration)
   111  				return err
   112  			}
   113  
   114  			return nil
   115  		},
   116  		Run: func(_ *cobra.Command, _ []string) {
   117  			stepTelemetryData := telemetry.CustomData{}
   118  			stepTelemetryData.ErrorCode = "1"
   119  			handler := func() {
   120  				influx.persist(GeneralConfig.EnvRootPath, "influx")
   121  				config.RemoveVaultSecretFiles()
   122  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   123  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   124  				stepTelemetryData.PiperCommitHash = GitCommit
   125  				telemetryClient.SetData(&stepTelemetryData)
   126  				telemetryClient.Send()
   127  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   128  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   129  				}
   130  			}
   131  			log.DeferExitHandler(handler)
   132  			defer handler()
   133  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME)
   134  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   135  				splunkClient.Initialize(GeneralConfig.CorrelationID,
   136  					GeneralConfig.HookConfig.SplunkConfig.Dsn,
   137  					GeneralConfig.HookConfig.SplunkConfig.Token,
   138  					GeneralConfig.HookConfig.SplunkConfig.Index,
   139  					GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   140  			}
   141  			batsExecuteTests(stepConfig, &stepTelemetryData, &influx)
   142  			stepTelemetryData.ErrorCode = "0"
   143  			log.Entry().Info("SUCCESS")
   144  		},
   145  	}
   146  
   147  	addBatsExecuteTestsFlags(createBatsExecuteTestsCmd, &stepConfig)
   148  	return createBatsExecuteTestsCmd
   149  }
   150  
   151  func addBatsExecuteTestsFlags(cmd *cobra.Command, stepConfig *batsExecuteTestsOptions) {
   152  	cmd.Flags().StringVar(&stepConfig.OutputFormat, "outputFormat", `junit`, "Defines the format of the test result output. junit would be the standard for automated build environments but you could use also the option tap.")
   153  	cmd.Flags().StringVar(&stepConfig.Repository, "repository", `https://github.com/bats-core/bats-core.git`, "Defines the version of bats-core to be used. By default we use the version from the master branch.")
   154  	cmd.Flags().StringVar(&stepConfig.TestPackage, "testPackage", `piper-bats`, "For the transformation of the test result to xUnit format the node module tap-xunit is used. This parameter defines the name of the test package used in the xUnit result file.")
   155  	cmd.Flags().StringVar(&stepConfig.TestPath, "testPath", `src/test`, "Defines either the directory which contains the test files (*.bats) or a single file. You can find further details in the Bats-core documentation.")
   156  	cmd.Flags().StringSliceVar(&stepConfig.EnvVars, "envVars", []string{}, "Injects environment variables to step execution. Format of value must be ['<KEY1>=<VALUE1>','<KEY2>=<VALUE2>']. Example: ['CONTAINER_NAME=piper-jenskins','IMAGE_NAME=my-image']")
   157  
   158  }
   159  
   160  // retrieve step metadata
   161  func batsExecuteTestsMetadata() config.StepData {
   162  	var theMetaData = config.StepData{
   163  		Metadata: config.StepMetadata{
   164  			Name:        "batsExecuteTests",
   165  			Aliases:     []config.Alias{},
   166  			Description: "This step executes tests using the [Bash Automated Testing System - bats-core](https://github.com/bats-core/bats-core).",
   167  		},
   168  		Spec: config.StepSpec{
   169  			Inputs: config.StepInputs{
   170  				Resources: []config.StepResources{
   171  					{Name: "tests", Type: "stash"},
   172  				},
   173  				Parameters: []config.StepParameters{
   174  					{
   175  						Name:        "outputFormat",
   176  						ResourceRef: []config.ResourceReference{},
   177  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   178  						Type:        "string",
   179  						Mandatory:   false,
   180  						Aliases:     []config.Alias{},
   181  						Default:     `junit`,
   182  					},
   183  					{
   184  						Name:        "repository",
   185  						ResourceRef: []config.ResourceReference{},
   186  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   187  						Type:        "string",
   188  						Mandatory:   false,
   189  						Aliases:     []config.Alias{},
   190  						Default:     `https://github.com/bats-core/bats-core.git`,
   191  					},
   192  					{
   193  						Name:        "testPackage",
   194  						ResourceRef: []config.ResourceReference{},
   195  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   196  						Type:        "string",
   197  						Mandatory:   false,
   198  						Aliases:     []config.Alias{},
   199  						Default:     `piper-bats`,
   200  					},
   201  					{
   202  						Name:        "testPath",
   203  						ResourceRef: []config.ResourceReference{},
   204  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   205  						Type:        "string",
   206  						Mandatory:   false,
   207  						Aliases:     []config.Alias{},
   208  						Default:     `src/test`,
   209  					},
   210  					{
   211  						Name:        "envVars",
   212  						ResourceRef: []config.ResourceReference{},
   213  						Scope:       []string{"STEPS", "STAGES", "PARAMETERS"},
   214  						Type:        "[]string",
   215  						Mandatory:   false,
   216  						Aliases:     []config.Alias{},
   217  						Default:     []string{},
   218  					},
   219  				},
   220  			},
   221  			Containers: []config.Container{
   222  				{Name: "bats", Image: "node:lts-stretch", WorkingDir: "/home/node", Conditions: []config.Condition{{ConditionRef: "strings-equal", Params: []config.Param{{Name: "outputFormat", Value: "junit"}}}}},
   223  			},
   224  			Outputs: config.StepOutputs{
   225  				Resources: []config.StepResources{
   226  					{
   227  						Name: "influx",
   228  						Type: "influx",
   229  						Parameters: []map[string]interface{}{
   230  							{"name": "step_data", "fields": []map[string]string{{"name": "bats"}}},
   231  						},
   232  					},
   233  				},
   234  			},
   235  		},
   236  	}
   237  	return theMetaData
   238  }