github.com/SAP/jenkins-library@v1.362.0/cmd/gctsExecuteABAPUnitTests_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  	"time"
     9  
    10  	"github.com/SAP/jenkins-library/pkg/config"
    11  	"github.com/SAP/jenkins-library/pkg/log"
    12  	"github.com/SAP/jenkins-library/pkg/splunk"
    13  	"github.com/SAP/jenkins-library/pkg/telemetry"
    14  	"github.com/SAP/jenkins-library/pkg/validation"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  type gctsExecuteABAPUnitTestsOptions struct {
    19  	Username             string                 `json:"username,omitempty"`
    20  	Password             string                 `json:"password,omitempty"`
    21  	Host                 string                 `json:"host,omitempty"`
    22  	Repository           string                 `json:"repository,omitempty"`
    23  	Client               string                 `json:"client,omitempty"`
    24  	AUnitTest            bool                   `json:"aUnitTest,omitempty"`
    25  	AtcCheck             bool                   `json:"atcCheck,omitempty"`
    26  	AtcVariant           string                 `json:"atcVariant,omitempty"`
    27  	Scope                string                 `json:"scope,omitempty"`
    28  	Commit               string                 `json:"commit,omitempty"`
    29  	Workspace            string                 `json:"workspace,omitempty"`
    30  	AtcResultsFileName   string                 `json:"atcResultsFileName,omitempty"`
    31  	AUnitResultsFileName string                 `json:"aUnitResultsFileName,omitempty"`
    32  	QueryParameters      map[string]interface{} `json:"queryParameters,omitempty"`
    33  	SkipSSLVerification  bool                   `json:"skipSSLVerification,omitempty"`
    34  }
    35  
    36  // GctsExecuteABAPUnitTestsCommand Runs ABAP unit tests and ATC (ABAP Test Cockpit) checks for a specified object scope.
    37  func GctsExecuteABAPUnitTestsCommand() *cobra.Command {
    38  	const STEP_NAME = "gctsExecuteABAPUnitTests"
    39  
    40  	metadata := gctsExecuteABAPUnitTestsMetadata()
    41  	var stepConfig gctsExecuteABAPUnitTestsOptions
    42  	var startTime time.Time
    43  	var logCollector *log.CollectorHook
    44  	var splunkClient *splunk.Splunk
    45  	telemetryClient := &telemetry.Telemetry{}
    46  
    47  	var createGctsExecuteABAPUnitTestsCmd = &cobra.Command{
    48  		Use:   STEP_NAME,
    49  		Short: "Runs ABAP unit tests and ATC (ABAP Test Cockpit) checks for a specified object scope.",
    50  		Long:  `This step executes ABAP unit test and ATC checks for a specified scope of objects that exist in a local Git repository on an ABAP system.`,
    51  		PreRunE: func(cmd *cobra.Command, _ []string) error {
    52  			startTime = time.Now()
    53  			log.SetStepName(STEP_NAME)
    54  			log.SetVerbose(GeneralConfig.Verbose)
    55  
    56  			GeneralConfig.GitHubAccessTokens = ResolveAccessTokens(GeneralConfig.GitHubTokens)
    57  
    58  			path, _ := os.Getwd()
    59  			fatalHook := &log.FatalHook{CorrelationID: GeneralConfig.CorrelationID, Path: path}
    60  			log.RegisterHook(fatalHook)
    61  
    62  			err := PrepareConfig(cmd, &metadata, STEP_NAME, &stepConfig, config.OpenPiperFile)
    63  			if err != nil {
    64  				log.SetErrorCategory(log.ErrorConfiguration)
    65  				return err
    66  			}
    67  			log.RegisterSecret(stepConfig.Username)
    68  			log.RegisterSecret(stepConfig.Password)
    69  
    70  			if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 {
    71  				sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID)
    72  				log.RegisterHook(&sentryHook)
    73  			}
    74  
    75  			if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 || len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
    76  				splunkClient = &splunk.Splunk{}
    77  				logCollector = &log.CollectorHook{CorrelationID: GeneralConfig.CorrelationID}
    78  				log.RegisterHook(logCollector)
    79  			}
    80  
    81  			if err = log.RegisterANSHookIfConfigured(GeneralConfig.CorrelationID); err != nil {
    82  				log.Entry().WithError(err).Warn("failed to set up SAP Alert Notification Service log hook")
    83  			}
    84  
    85  			validation, err := validation.New(validation.WithJSONNamesForStructFields(), validation.WithPredefinedErrorMessages())
    86  			if err != nil {
    87  				return err
    88  			}
    89  			if err = validation.ValidateStruct(stepConfig); err != nil {
    90  				log.SetErrorCategory(log.ErrorConfiguration)
    91  				return err
    92  			}
    93  
    94  			return nil
    95  		},
    96  		Run: func(_ *cobra.Command, _ []string) {
    97  			stepTelemetryData := telemetry.CustomData{}
    98  			stepTelemetryData.ErrorCode = "1"
    99  			handler := func() {
   100  				config.RemoveVaultSecretFiles()
   101  				stepTelemetryData.Duration = fmt.Sprintf("%v", time.Since(startTime).Milliseconds())
   102  				stepTelemetryData.ErrorCategory = log.GetErrorCategory().String()
   103  				stepTelemetryData.PiperCommitHash = GitCommit
   104  				telemetryClient.SetData(&stepTelemetryData)
   105  				telemetryClient.Send()
   106  				if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 {
   107  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   108  						GeneralConfig.HookConfig.SplunkConfig.Dsn,
   109  						GeneralConfig.HookConfig.SplunkConfig.Token,
   110  						GeneralConfig.HookConfig.SplunkConfig.Index,
   111  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   112  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   113  				}
   114  				if len(GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint) > 0 {
   115  					splunkClient.Initialize(GeneralConfig.CorrelationID,
   116  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint,
   117  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken,
   118  						GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex,
   119  						GeneralConfig.HookConfig.SplunkConfig.SendLogs)
   120  					splunkClient.Send(telemetryClient.GetData(), logCollector)
   121  				}
   122  			}
   123  			log.DeferExitHandler(handler)
   124  			defer handler()
   125  			telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME, GeneralConfig.HookConfig.PendoConfig.Token)
   126  			gctsExecuteABAPUnitTests(stepConfig, &stepTelemetryData)
   127  			stepTelemetryData.ErrorCode = "0"
   128  			log.Entry().Info("SUCCESS")
   129  		},
   130  	}
   131  
   132  	addGctsExecuteABAPUnitTestsFlags(createGctsExecuteABAPUnitTestsCmd, &stepConfig)
   133  	return createGctsExecuteABAPUnitTestsCmd
   134  }
   135  
   136  func addGctsExecuteABAPUnitTestsFlags(cmd *cobra.Command, stepConfig *gctsExecuteABAPUnitTestsOptions) {
   137  	cmd.Flags().StringVar(&stepConfig.Username, "username", os.Getenv("PIPER_username"), "User that authenticates to the ABAP system. **Note** - Don´t provide this parameter directly. Either set it in the environment, or in the Jenkins credentials store, and provide the ID as value of the `abapCredentialsId` parameter.")
   138  	cmd.Flags().StringVar(&stepConfig.Password, "password", os.Getenv("PIPER_password"), "Password of the ABAP user that authenticates to the ABAP system. **Note** - Don´t provide this parameter directly. Either set it in the environment, or in the Jenkins credentials store, and provide the ID as value of the `abapCredentialsId` parameter.")
   139  	cmd.Flags().StringVar(&stepConfig.Host, "host", os.Getenv("PIPER_host"), "Protocol and host of the ABAP system, including the port. Please provide it in the format `<protocol>://<host>:<port>`. Supported protocols are `http` and `https`.")
   140  	cmd.Flags().StringVar(&stepConfig.Repository, "repository", os.Getenv("PIPER_repository"), "Name (ID) of the local repository on the ABAP system")
   141  	cmd.Flags().StringVar(&stepConfig.Client, "client", os.Getenv("PIPER_client"), "Client of the ABAP system in which you want to execute the checks")
   142  	cmd.Flags().BoolVar(&stepConfig.AUnitTest, "aUnitTest", true, "Indication whether you want to execute the ABAP Unit tests. If the ABAP Unit tests fail, the results are mapped as follows to the statuses available in the Jenkins plugin. (Successful ABAP unit test results are not displayed.)\n<br/>\n- Failed with severity `fatal` is displayed as an `Error`.\n<br/>\n- Failed with severity `critical` is displayed as an `Error`.\n<br/>\n- Failed with severity `warning` is displayed as a `Warning`.\n")
   143  	cmd.Flags().BoolVar(&stepConfig.AtcCheck, "atcCheck", true, "Indication whether you want to execute the ATC checks. If the ATC checks result in errors with priorities 1 and 2, they are considered as failed. The results are mapped as follows to the statuses available in the Jenkins plugin. (Successful ATC check results are not displayed.)\n<br/>\n- Priorities 1 and 2 are displayed as an `Error`.\n<br/>\n- Priority 3 is displayed as a `Warning`.\n")
   144  	cmd.Flags().StringVar(&stepConfig.AtcVariant, "atcVariant", `DEFAULT`, "Variant for ATC checks")
   145  	cmd.Flags().StringVar(&stepConfig.Scope, "scope", `repository`, "Scope of objects for which you want to execute the checks:\n<br/>\n- `localChangedObjects`: The object scope is derived from the last activity in the local repository. The checks are executed for the individual objects.\n<br/>\n- `remoteChangedObjects`: The object scope is the delta between the commit that triggered the pipeline and the current commit in the remote repository. The checks are executed for the individual objects.\n<br/>\n- `localChangedPackages`: The object scope is derived from the last activity in the local repository. All objects are resolved into packages. The checks are executed for the packages.\n<br/>\n- `remoteChangedPackages`: The object scope is the delta between the commit that triggered the pipeline and the current commit in the remote repository. All objects are resolved into packages. The checks are executed for the packages.\n<br/>\n- `repository`: The object scope comprises all objects that are part of the local repository. The checks are executed for the individual objects. Packages (DEVC) are excluded. This is the default scope.\n<br/>\n- `packages`: The object scope comprises all packages that are part of the local repository. The checks are executed for the packages.\n")
   146  	cmd.Flags().StringVar(&stepConfig.Commit, "commit", os.Getenv("PIPER_commit"), "ID of the commit that triggered the pipeline or any other commit used to calculate the object scope. Specifying a commit is mandatory for the `remoteChangedObjects` and `remoteChangedPackages` scopes.")
   147  	cmd.Flags().StringVar(&stepConfig.Workspace, "workspace", os.Getenv("PIPER_workspace"), "Absolute path to the directory that contains the source code that your CI/CD tool checks out. For example, in Jenkins, the workspace parameter is `/var/jenkins_home/workspace/<jobName>/`. As an alternative, you can use Jenkins's predefined environmental variable `WORKSPACE`.")
   148  	cmd.Flags().StringVar(&stepConfig.AtcResultsFileName, "atcResultsFileName", `ATCResults.xml`, "Specifies an output file name for the results of the ATC checks.")
   149  	cmd.Flags().StringVar(&stepConfig.AUnitResultsFileName, "aUnitResultsFileName", `AUnitResults.xml`, "Specifies an output file name for the results of the ABAP Unit tests.")
   150  
   151  	cmd.Flags().BoolVar(&stepConfig.SkipSSLVerification, "skipSSLVerification", false, "Skip the verification of SSL (Secure Socket Layer) certificates when using HTTPS. This parameter is **not recommended** for productive environments.")
   152  
   153  	cmd.MarkFlagRequired("username")
   154  	cmd.MarkFlagRequired("password")
   155  	cmd.MarkFlagRequired("host")
   156  	cmd.MarkFlagRequired("repository")
   157  	cmd.MarkFlagRequired("client")
   158  	cmd.MarkFlagRequired("workspace")
   159  }
   160  
   161  // retrieve step metadata
   162  func gctsExecuteABAPUnitTestsMetadata() config.StepData {
   163  	var theMetaData = config.StepData{
   164  		Metadata: config.StepMetadata{
   165  			Name:        "gctsExecuteABAPUnitTests",
   166  			Aliases:     []config.Alias{},
   167  			Description: "Runs ABAP unit tests and ATC (ABAP Test Cockpit) checks for a specified object scope.",
   168  		},
   169  		Spec: config.StepSpec{
   170  			Inputs: config.StepInputs{
   171  				Secrets: []config.StepSecrets{
   172  					{Name: "abapCredentialsId", Description: "ID taken from the Jenkins credentials store containing user name and password of the user that authenticates to the ABAP system on which you want to execute the checks.", Type: "jenkins"},
   173  				},
   174  				Parameters: []config.StepParameters{
   175  					{
   176  						Name: "username",
   177  						ResourceRef: []config.ResourceReference{
   178  							{
   179  								Name:  "abapCredentialsId",
   180  								Param: "username",
   181  								Type:  "secret",
   182  							},
   183  						},
   184  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   185  						Type:      "string",
   186  						Mandatory: true,
   187  						Aliases:   []config.Alias{},
   188  						Default:   os.Getenv("PIPER_username"),
   189  					},
   190  					{
   191  						Name: "password",
   192  						ResourceRef: []config.ResourceReference{
   193  							{
   194  								Name:  "abapCredentialsId",
   195  								Param: "password",
   196  								Type:  "secret",
   197  							},
   198  						},
   199  						Scope:     []string{"PARAMETERS", "STAGES", "STEPS"},
   200  						Type:      "string",
   201  						Mandatory: true,
   202  						Aliases:   []config.Alias{},
   203  						Default:   os.Getenv("PIPER_password"),
   204  					},
   205  					{
   206  						Name:        "host",
   207  						ResourceRef: []config.ResourceReference{},
   208  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   209  						Type:        "string",
   210  						Mandatory:   true,
   211  						Aliases:     []config.Alias{},
   212  						Default:     os.Getenv("PIPER_host"),
   213  					},
   214  					{
   215  						Name:        "repository",
   216  						ResourceRef: []config.ResourceReference{},
   217  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   218  						Type:        "string",
   219  						Mandatory:   true,
   220  						Aliases:     []config.Alias{},
   221  						Default:     os.Getenv("PIPER_repository"),
   222  					},
   223  					{
   224  						Name:        "client",
   225  						ResourceRef: []config.ResourceReference{},
   226  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   227  						Type:        "string",
   228  						Mandatory:   true,
   229  						Aliases:     []config.Alias{},
   230  						Default:     os.Getenv("PIPER_client"),
   231  					},
   232  					{
   233  						Name:        "aUnitTest",
   234  						ResourceRef: []config.ResourceReference{},
   235  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   236  						Type:        "bool",
   237  						Mandatory:   false,
   238  						Aliases:     []config.Alias{},
   239  						Default:     true,
   240  					},
   241  					{
   242  						Name:        "atcCheck",
   243  						ResourceRef: []config.ResourceReference{},
   244  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   245  						Type:        "bool",
   246  						Mandatory:   false,
   247  						Aliases:     []config.Alias{},
   248  						Default:     true,
   249  					},
   250  					{
   251  						Name:        "atcVariant",
   252  						ResourceRef: []config.ResourceReference{},
   253  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   254  						Type:        "string",
   255  						Mandatory:   false,
   256  						Aliases:     []config.Alias{},
   257  						Default:     `DEFAULT`,
   258  					},
   259  					{
   260  						Name:        "scope",
   261  						ResourceRef: []config.ResourceReference{},
   262  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   263  						Type:        "string",
   264  						Mandatory:   false,
   265  						Aliases:     []config.Alias{},
   266  						Default:     `repository`,
   267  					},
   268  					{
   269  						Name:        "commit",
   270  						ResourceRef: []config.ResourceReference{},
   271  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   272  						Type:        "string",
   273  						Mandatory:   false,
   274  						Aliases:     []config.Alias{},
   275  						Default:     os.Getenv("PIPER_commit"),
   276  					},
   277  					{
   278  						Name:        "workspace",
   279  						ResourceRef: []config.ResourceReference{},
   280  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   281  						Type:        "string",
   282  						Mandatory:   true,
   283  						Aliases:     []config.Alias{},
   284  						Default:     os.Getenv("PIPER_workspace"),
   285  					},
   286  					{
   287  						Name:        "atcResultsFileName",
   288  						ResourceRef: []config.ResourceReference{},
   289  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   290  						Type:        "string",
   291  						Mandatory:   false,
   292  						Aliases:     []config.Alias{},
   293  						Default:     `ATCResults.xml`,
   294  					},
   295  					{
   296  						Name:        "aUnitResultsFileName",
   297  						ResourceRef: []config.ResourceReference{},
   298  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   299  						Type:        "string",
   300  						Mandatory:   false,
   301  						Aliases:     []config.Alias{},
   302  						Default:     `AUnitResults.xml`,
   303  					},
   304  					{
   305  						Name:        "queryParameters",
   306  						ResourceRef: []config.ResourceReference{},
   307  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   308  						Type:        "map[string]interface{}",
   309  						Mandatory:   false,
   310  						Aliases:     []config.Alias{},
   311  					},
   312  					{
   313  						Name:        "skipSSLVerification",
   314  						ResourceRef: []config.ResourceReference{},
   315  						Scope:       []string{"PARAMETERS", "STAGES", "STEPS"},
   316  						Type:        "bool",
   317  						Mandatory:   false,
   318  						Aliases:     []config.Alias{},
   319  						Default:     false,
   320  					},
   321  				},
   322  			},
   323  		},
   324  	}
   325  	return theMetaData
   326  }