diff --git a/api/expressions.yaml b/api/expressions.yaml index 8319ddfc30..6df1b223e3 100644 --- a/api/expressions.yaml +++ b/api/expressions.yaml @@ -20,7 +20,7 @@ components: type: string selector: type: string - environmentId: + variableSetId: type: string ResolveResponseInfo: type: object diff --git a/api/openapi.yaml b/api/openapi.yaml index 1dca3ed1f6..4822b4ecf2 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1028,14 +1028,14 @@ paths: "204": description: OK - # Environments - /environments: + # VariableSets + /variableSets: get: tags: - resource-api - summary: "List environments" - description: "List environments available in Tracetest." - operationId: listEnvironments + summary: "List VariableSets" + description: "List VariableSets available in Tracetest." + operationId: listVariableSets parameters: - $ref: "./parameters.yaml#/components/parameters/take" - $ref: "./parameters.yaml#/components/parameters/skip" @@ -1047,7 +1047,7 @@ paths: content: application/json: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResourceList" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResourceList" text/yaml: schema: type: object @@ -1057,93 +1057,93 @@ paths: items: type: array items: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" 400: - description: "invalid query for environments, some data was sent in incorrect format." + description: "invalid query for VariableSets, some data was sent in incorrect format." 500: - description: "problem listing environments" + description: "problem listing VariableSets" post: tags: - resource-api - summary: "Create an environment" - description: "Create an environment that can be used by tests and transactions" - operationId: createEnvironment + summary: "Create a VariableSet" + description: "Create a VariableSet that can be used by tests and transactions" + operationId: createVariableSet requestBody: content: application/json: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" text/yaml: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" responses: 201: description: successful operation content: application/json: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" text/yaml: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" 500: - description: "problem creating an environment" + description: "problem creating an VariableSet" - /environments/{environmentId}: + /variableSets/{variableSetId}: get: tags: - resource-api parameters: - - $ref: "./parameters.yaml#/components/parameters/environmentId" - summary: "Get a specific environment" - description: "Get one environment by its id" - operationId: getEnvironment + - $ref: "./parameters.yaml#/components/parameters/variableSetId" + summary: "Get a specific VariableSet" + description: "Get one VariableSet by its id" + operationId: getVariableSet responses: 200: description: successful operation content: application/json: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" text/yaml: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" 404: - description: "environment not found" + description: "VariableSet not found" 500: - description: "problem getting an environment" + description: "problem getting an VariableSet" put: tags: - resource-api parameters: - - $ref: "./parameters.yaml#/components/parameters/environmentId" - summary: "Update an environment" - description: "Update an environment used on Tracetest" - operationId: updateEnvironment + - $ref: "./parameters.yaml#/components/parameters/variableSetId" + summary: "Update a VariableSet" + description: "Update a VariableSet used on Tracetest" + operationId: updateVariableSet requestBody: content: application/json: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" text/yaml: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" responses: 200: description: successful operation content: application/json: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" text/yaml: schema: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" + $ref: "./variableSets.yaml#/components/schemas/VariableSetResource" 400: - description: "invalid environment, some data was sent in incorrect format." + description: "invalid VariableSet, some data was sent in incorrect format." 404: - description: "environment not found" + description: "VariableSet not found" 500: - description: "problem updating an environment" + description: "problem updating an VariableSet" delete: tags: - resource-api @@ -1156,9 +1156,9 @@ paths: 204: description: successful operation 400: - description: "invalid environment, some data was sent in incorrect format." + description: "invalid VariableSet, some data was sent in incorrect format." 404: - description: "environment not found" + description: "VariableSet not found" 500: description: "problem deleting an environment" diff --git a/api/parameters.yaml b/api/parameters.yaml index 202ab6e374..9a7a1d08ce 100644 --- a/api/parameters.yaml +++ b/api/parameters.yaml @@ -126,11 +126,11 @@ components: schema: type: string - environmentId: + variableSetId: in: path - name: environmentId + name: variableSetId required: true - description: "ID of an environment used on Tracetest to inject values into tests and transactions" + description: "ID of a VariableSet used on Tracetest to inject values into tests and transactions" schema: type: string diff --git a/api/tests.yaml b/api/tests.yaml index 9c3bf134ab..149c600c57 100644 --- a/api/tests.yaml +++ b/api/tests.yaml @@ -195,8 +195,8 @@ components: completedAt: type: string format: date-time - environment: - $ref: "./environments.yaml#/components/schemas/Environment" + variableSet: + $ref: "./variableSets.yaml#/components/schemas/VariableSet" triggerResult: $ref: "./triggers.yaml#/components/schemas/TriggerResult" trace: @@ -238,12 +238,12 @@ components: nullable: true additionalProperties: type: string - environmentId: + variableSetId: type: string variables: type: array items: - $ref: "./environments.yaml#/components/schemas/EnvironmentValue" + $ref: "./variableSets.yaml#/components/schemas/VariableSetValue" requiredGates: type: array nullable: true diff --git a/api/transactions.yaml b/api/transactions.yaml index 177eaeae93..83f1268255 100644 --- a/api/transactions.yaml +++ b/api/transactions.yaml @@ -75,8 +75,8 @@ components: type: array items: $ref: "./tests.yaml#/components/schemas/TestRun" - environment: - $ref: "./environments.yaml#/components/schemas/Environment" + variableSet: + $ref: "./variableSets.yaml#/components/schemas/VariableSet" metadata: type: object additionalProperties: diff --git a/api/environments.yaml b/api/variableSets.yaml similarity index 59% rename from api/environments.yaml rename to api/variableSets.yaml index 6b9a8df72f..5cc5a12766 100644 --- a/api/environments.yaml +++ b/api/variableSets.yaml @@ -2,7 +2,7 @@ openapi: 3.0.0 components: schemas: - EnvironmentResourceList: + VariableSetResourceList: type: object properties: count: @@ -10,20 +10,19 @@ components: items: type: array items: - $ref: "./environments.yaml#/components/schemas/EnvironmentResource" - - EnvironmentResource: + $ref: "#/components/schemas/VariableSetResource" + VariableSetResource: type: object - description: "Represents an environment structured into the Resources format." + description: "Represents a VariableSet structured into the Resources format." properties: type: type: string - description: "Represents the type of this resource. It should always be set as 'Environment'." + description: "Represents the type of this resource. It should always be set as 'VariableSet'." enum: - - Environment + - VariableSet spec: - $ref: "#/components/schemas/Environment" - Environment: + $ref: "#/components/schemas/VariableSet" + VariableSet: type: object properties: id: @@ -35,8 +34,8 @@ components: values: type: array items: - $ref: "#/components/schemas/EnvironmentValue" - EnvironmentValue: + $ref: "#/components/schemas/VariableSetValue" + VariableSetValue: type: object properties: key: diff --git a/cli/cmd/legacy_test_cmd.go b/cli/cmd/legacy_test_cmd.go index fca472da6e..87bcba242d 100644 --- a/cli/cmd/legacy_test_cmd.go +++ b/cli/cmd/legacy_test_cmd.go @@ -61,7 +61,7 @@ var testRunCmd = &cobra.Command{ Run: func(_ *cobra.Command, _ []string) { // map old flags to new ones runParams.DefinitionFile = runTestFileDefinition - runParams.EnvID = runTestEnvID + runParams.VarsID = runTestEnvID runParams.SkipResultWait = !runTestWaitForResult runParams.JUnitOuptutFile = runTestJUnit diff --git a/cli/cmd/middleware.go b/cli/cmd/middleware.go index 6989445cf5..4e922ca3d6 100644 --- a/cli/cmd/middleware.go +++ b/cli/cmd/middleware.go @@ -1,11 +1,9 @@ package cmd import ( - "errors" "fmt" "os" - "github.com/kubeshop/tracetest/cli/pkg/resourcemanager" "github.com/spf13/cobra" ) @@ -84,8 +82,8 @@ func (p *resourceParameters) Validate(cmd *cobra.Command, args []string) []error p.ResourceName = args[0] - _, err := resources.Get(p.ResourceName) - if errors.Is(err, resourcemanager.ErrResourceNotFound) { + exists := resources.Exists(p.ResourceName) + if !exists { suggestion := resources.Suggest(p.ResourceName) if suggestion != "" { return []error{ diff --git a/cli/cmd/resource_run_cmd.go b/cli/cmd/resource_run_cmd.go index 3304028b33..57923d2764 100644 --- a/cli/cmd/resource_run_cmd.go +++ b/cli/cmd/resource_run_cmd.go @@ -35,13 +35,17 @@ func init() { orchestrator := runner.Orchestrator( cliLogger, utils.GetAPIClient(cliConfig), - environmentClient, + variableSetClient, ) + if runParams.EnvID != "" { + runParams.VarsID = runParams.EnvID + } + runParams := runner.RunOptions{ ID: runParams.ID, DefinitionFile: runParams.DefinitionFile, - EnvID: runParams.EnvID, + VarsID: runParams.VarsID, SkipResultWait: runParams.SkipResultWait, JUnitOuptutFile: runParams.JUnitOuptutFile, RequiredGates: runParams.RequriedGates, @@ -63,10 +67,16 @@ func init() { runCmd.Flags().StringVarP(&runParams.DefinitionFile, "file", "f", "", "path to the definition file") runCmd.Flags().StringVar(&runParams.ID, "id", "", "id of the resource to run") - runCmd.Flags().StringVarP(&runParams.EnvID, "environment", "e", "", "environment file or ID to be used") + runCmd.Flags().StringVarP(&runParams.VarsID, "vars", "", "", "variable set file or ID to be used") runCmd.Flags().BoolVarP(&runParams.SkipResultWait, "skip-result-wait", "W", false, "do not wait for results. exit immediately after test run started") runCmd.Flags().StringVarP(&runParams.JUnitOuptutFile, "junit", "j", "", "file path to save test results in junit format") runCmd.Flags().StringSliceVar(&runParams.RequriedGates, "required-gates", []string{}, "override default required gate. "+validRequiredGatesMsg()) + + //deprecated + runCmd.Flags().StringVarP(&runParams.EnvID, "env", "e", "", "environment file or ID to be used") + runCmd.Flags().MarkDeprecated("env", "use --vars instead") + runCmd.Flags().MarkShorthandDeprecated("e", "use --vars instead") + rootCmd.AddCommand(runCmd) } @@ -82,6 +92,7 @@ func validRequiredGatesMsg() string { type runParameters struct { ID string DefinitionFile string + VarsID string EnvID string SkipResultWait bool JUnitOuptutFile string diff --git a/cli/cmd/resources.go b/cli/cmd/resources.go index 6fc6464270..2682d2e28a 100644 --- a/cli/cmd/resources.go +++ b/cli/cmd/resources.go @@ -35,9 +35,10 @@ var ( var ( httpClient = &resourcemanager.HTTPClient{} - environmentClient = resourcemanager.NewClient( + variableSetPreprocessor = preprocessor.VariableSet(cliLogger) + variableSetClient = resourcemanager.NewClient( httpClient, cliLogger, - "environment", "environments", + "variableset", "variablesets", resourcemanager.WithTableConfig(resourcemanager.TableConfig{ Cells: []resourcemanager.TableCellConfig{ {Header: "ID", Path: "spec.id"}, @@ -45,6 +46,9 @@ var ( {Header: "DESCRIPTION", Path: "spec.description"}, }, }), + resourcemanager.WithResourceType("VariableSet"), + resourcemanager.WithApplyPreProcessor(variableSetPreprocessor.Preprocess), + resourcemanager.WithDeprecatedAlias("Environment"), ) testPreprocessor = preprocessor.Test(cliLogger) @@ -120,6 +124,13 @@ var ( resourcemanager.WithApplyPreProcessor(transactionPreprocessor.Preprocess), ) + // deprecated resources + deprecatedEnvironmentClient = resourcemanager.NewClient( + httpClient, cliLogger, + "environment", "environments", + resourcemanager.WithProxyResource("variableset"), + ) + resources = resourcemanager.NewRegistry(). Register( resourcemanager.NewClient( @@ -228,9 +239,12 @@ var ( resourcemanager.WithResourceType("TestRunner"), ), ). - Register(environmentClient). + Register(variableSetClient). Register(transactionClient). - Register(testClient) + Register(testClient). + + // deprecated resources + Register(deprecatedEnvironmentClient) ) func resourceList() string { diff --git a/cli/openapi/api_resource_api.go b/cli/openapi/api_resource_api.go index 41c0fce596..b5dc3d1cca 100644 --- a/cli/openapi/api_resource_api.go +++ b/cli/openapi/api_resource_api.go @@ -130,31 +130,31 @@ func (a *ResourceApiApiService) CreateDemoExecute(r ApiCreateDemoRequest) (*Demo return localVarReturnValue, localVarHTTPResponse, nil } -type ApiCreateEnvironmentRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - environmentResource *EnvironmentResource +type ApiCreateLinterRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + linterResource *LinterResource } -func (r ApiCreateEnvironmentRequest) EnvironmentResource(environmentResource EnvironmentResource) ApiCreateEnvironmentRequest { - r.environmentResource = &environmentResource +func (r ApiCreateLinterRequest) LinterResource(linterResource LinterResource) ApiCreateLinterRequest { + r.linterResource = &linterResource return r } -func (r ApiCreateEnvironmentRequest) Execute() (*EnvironmentResource, *http.Response, error) { - return r.ApiService.CreateEnvironmentExecute(r) +func (r ApiCreateLinterRequest) Execute() (*LinterResource, *http.Response, error) { + return r.ApiService.CreateLinterExecute(r) } /* -CreateEnvironment Create an environment +CreateLinter Create an Linter -Create an environment that can be used by tests and transactions +Create an Linter that can be used by tests and Linters @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateEnvironmentRequest + @return ApiCreateLinterRequest */ -func (a *ResourceApiApiService) CreateEnvironment(ctx context.Context) ApiCreateEnvironmentRequest { - return ApiCreateEnvironmentRequest{ +func (a *ResourceApiApiService) CreateLinter(ctx context.Context) ApiCreateLinterRequest { + return ApiCreateLinterRequest{ ApiService: a, ctx: ctx, } @@ -162,21 +162,21 @@ func (a *ResourceApiApiService) CreateEnvironment(ctx context.Context) ApiCreate // Execute executes the request // -// @return EnvironmentResource -func (a *ResourceApiApiService) CreateEnvironmentExecute(r ApiCreateEnvironmentRequest) (*EnvironmentResource, *http.Response, error) { +// @return LinterResource +func (a *ResourceApiApiService) CreateLinterExecute(r ApiCreateLinterRequest) (*LinterResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue *EnvironmentResource + localVarReturnValue *LinterResource ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateEnvironment") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateLinter") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/environments" + localVarPath := localBasePath + "/linters" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -200,7 +200,7 @@ func (a *ResourceApiApiService) CreateEnvironmentExecute(r ApiCreateEnvironmentR localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = r.environmentResource + localVarPostBody = r.linterResource req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -238,31 +238,31 @@ func (a *ResourceApiApiService) CreateEnvironmentExecute(r ApiCreateEnvironmentR return localVarReturnValue, localVarHTTPResponse, nil } -type ApiCreateLinterRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - linterResource *LinterResource +type ApiCreateTestRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + test *Test } -func (r ApiCreateLinterRequest) LinterResource(linterResource LinterResource) ApiCreateLinterRequest { - r.linterResource = &linterResource +func (r ApiCreateTestRequest) Test(test Test) ApiCreateTestRequest { + r.test = &test return r } -func (r ApiCreateLinterRequest) Execute() (*LinterResource, *http.Response, error) { - return r.ApiService.CreateLinterExecute(r) +func (r ApiCreateTestRequest) Execute() (*Test, *http.Response, error) { + return r.ApiService.CreateTestExecute(r) } /* -CreateLinter Create an Linter +CreateTest Create new test -Create an Linter that can be used by tests and Linters +Create new test action @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateLinterRequest + @return ApiCreateTestRequest */ -func (a *ResourceApiApiService) CreateLinter(ctx context.Context) ApiCreateLinterRequest { - return ApiCreateLinterRequest{ +func (a *ResourceApiApiService) CreateTest(ctx context.Context) ApiCreateTestRequest { + return ApiCreateTestRequest{ ApiService: a, ctx: ctx, } @@ -270,28 +270,28 @@ func (a *ResourceApiApiService) CreateLinter(ctx context.Context) ApiCreateLinte // Execute executes the request // -// @return LinterResource -func (a *ResourceApiApiService) CreateLinterExecute(r ApiCreateLinterRequest) (*LinterResource, *http.Response, error) { +// @return Test +func (a *ResourceApiApiService) CreateTestExecute(r ApiCreateTestRequest) (*Test, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue *LinterResource + localVarReturnValue *Test ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateLinter") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateTest") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/linters" + localVarPath := localBasePath + "/tests" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHTTPContentTypes := []string{"application/json", "text/yaml"} + localVarHTTPContentTypes := []string{"application/json"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) @@ -300,7 +300,7 @@ func (a *ResourceApiApiService) CreateLinterExecute(r ApiCreateLinterRequest) (* } // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} + localVarHTTPHeaderAccepts := []string{"application/json"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) @@ -308,7 +308,7 @@ func (a *ResourceApiApiService) CreateLinterExecute(r ApiCreateLinterRequest) (* localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = r.linterResource + localVarPostBody = r.test req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -346,31 +346,31 @@ func (a *ResourceApiApiService) CreateLinterExecute(r ApiCreateLinterRequest) (* return localVarReturnValue, localVarHTTPResponse, nil } -type ApiCreateTestRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - test *Test +type ApiCreateTransactionRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + transactionResource *TransactionResource } -func (r ApiCreateTestRequest) Test(test Test) ApiCreateTestRequest { - r.test = &test +func (r ApiCreateTransactionRequest) TransactionResource(transactionResource TransactionResource) ApiCreateTransactionRequest { + r.transactionResource = &transactionResource return r } -func (r ApiCreateTestRequest) Execute() (*Test, *http.Response, error) { - return r.ApiService.CreateTestExecute(r) +func (r ApiCreateTransactionRequest) Execute() (*TransactionResource, *http.Response, error) { + return r.ApiService.CreateTransactionExecute(r) } /* -CreateTest Create new test +CreateTransaction Create new transaction -Create new test action +Create new transaction @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateTestRequest + @return ApiCreateTransactionRequest */ -func (a *ResourceApiApiService) CreateTest(ctx context.Context) ApiCreateTestRequest { - return ApiCreateTestRequest{ +func (a *ResourceApiApiService) CreateTransaction(ctx context.Context) ApiCreateTransactionRequest { + return ApiCreateTransactionRequest{ ApiService: a, ctx: ctx, } @@ -378,28 +378,28 @@ func (a *ResourceApiApiService) CreateTest(ctx context.Context) ApiCreateTestReq // Execute executes the request // -// @return Test -func (a *ResourceApiApiService) CreateTestExecute(r ApiCreateTestRequest) (*Test, *http.Response, error) { +// @return TransactionResource +func (a *ResourceApiApiService) CreateTransactionExecute(r ApiCreateTransactionRequest) (*TransactionResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue *Test + localVarReturnValue *TransactionResource ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateTest") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateTransaction") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/tests" + localVarPath := localBasePath + "/transactions" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHTTPContentTypes := []string{"application/json"} + localVarHTTPContentTypes := []string{"application/json", "text/yaml"} // set Content-Type header localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) @@ -408,7 +408,7 @@ func (a *ResourceApiApiService) CreateTestExecute(r ApiCreateTestRequest) (*Test } // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json"} + localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} // set Accept header localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) @@ -416,7 +416,7 @@ func (a *ResourceApiApiService) CreateTestExecute(r ApiCreateTestRequest) (*Test localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = r.test + localVarPostBody = r.transactionResource req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -454,31 +454,31 @@ func (a *ResourceApiApiService) CreateTestExecute(r ApiCreateTestRequest) (*Test return localVarReturnValue, localVarHTTPResponse, nil } -type ApiCreateTransactionRequest struct { +type ApiCreateVariableSetRequest struct { ctx context.Context ApiService *ResourceApiApiService - transactionResource *TransactionResource + variableSetResource *VariableSetResource } -func (r ApiCreateTransactionRequest) TransactionResource(transactionResource TransactionResource) ApiCreateTransactionRequest { - r.transactionResource = &transactionResource +func (r ApiCreateVariableSetRequest) VariableSetResource(variableSetResource VariableSetResource) ApiCreateVariableSetRequest { + r.variableSetResource = &variableSetResource return r } -func (r ApiCreateTransactionRequest) Execute() (*TransactionResource, *http.Response, error) { - return r.ApiService.CreateTransactionExecute(r) +func (r ApiCreateVariableSetRequest) Execute() (*VariableSetResource, *http.Response, error) { + return r.ApiService.CreateVariableSetExecute(r) } /* -CreateTransaction Create new transaction +CreateVariableSet Create an VariableSet -Create new transaction +Create an VariableSet that can be used by tests and transactions @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateTransactionRequest + @return ApiCreateVariableSetRequest */ -func (a *ResourceApiApiService) CreateTransaction(ctx context.Context) ApiCreateTransactionRequest { - return ApiCreateTransactionRequest{ +func (a *ResourceApiApiService) CreateVariableSet(ctx context.Context) ApiCreateVariableSetRequest { + return ApiCreateVariableSetRequest{ ApiService: a, ctx: ctx, } @@ -486,21 +486,21 @@ func (a *ResourceApiApiService) CreateTransaction(ctx context.Context) ApiCreate // Execute executes the request // -// @return TransactionResource -func (a *ResourceApiApiService) CreateTransactionExecute(r ApiCreateTransactionRequest) (*TransactionResource, *http.Response, error) { +// @return VariableSetResource +func (a *ResourceApiApiService) CreateVariableSetExecute(r ApiCreateVariableSetRequest) (*VariableSetResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TransactionResource + localVarReturnValue *VariableSetResource ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateTransaction") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateVariableSet") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions" + localVarPath := localBasePath + "/variableSets" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -524,7 +524,7 @@ func (a *ResourceApiApiService) CreateTransactionExecute(r ApiCreateTransactionR localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = r.transactionResource + localVarPostBody = r.variableSetResource req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -746,48 +746,48 @@ func (a *ResourceApiApiService) DeleteDemoExecute(r ApiDeleteDemoRequest) (*http return localVarHTTPResponse, nil } -type ApiDeleteEnvironmentRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - environmentId string +type ApiDeleteLinterRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + linterId string } -func (r ApiDeleteEnvironmentRequest) Execute() (*http.Response, error) { - return r.ApiService.DeleteEnvironmentExecute(r) +func (r ApiDeleteLinterRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteLinterExecute(r) } /* -DeleteEnvironment Delete an environment +DeleteLinter Delete an Linter -Delete an environment from Tracetest +Delete an Linter from Tracetest @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param environmentId ID of an environment used on Tracetest to inject values into tests and transactions - @return ApiDeleteEnvironmentRequest + @param linterId ID of an Linter + @return ApiDeleteLinterRequest */ -func (a *ResourceApiApiService) DeleteEnvironment(ctx context.Context, environmentId string) ApiDeleteEnvironmentRequest { - return ApiDeleteEnvironmentRequest{ - ApiService: a, - ctx: ctx, - environmentId: environmentId, +func (a *ResourceApiApiService) DeleteLinter(ctx context.Context, linterId string) ApiDeleteLinterRequest { + return ApiDeleteLinterRequest{ + ApiService: a, + ctx: ctx, + linterId: linterId, } } // Execute executes the request -func (a *ResourceApiApiService) DeleteEnvironmentExecute(r ApiDeleteEnvironmentRequest) (*http.Response, error) { +func (a *ResourceApiApiService) DeleteLinterExecute(r ApiDeleteLinterRequest) (*http.Response, error) { var ( localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} formFiles []formFile ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteEnvironment") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteLinter") if err != nil { return nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/environments/{environmentId}" - localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) + localVarPath := localBasePath + "/linters/{LinterId}" + localVarPath = strings.Replace(localVarPath, "{"+"LinterId"+"}", url.PathEscape(parameterValueToString(r.linterId, "linterId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -838,48 +838,48 @@ func (a *ResourceApiApiService) DeleteEnvironmentExecute(r ApiDeleteEnvironmentR return localVarHTTPResponse, nil } -type ApiDeleteLinterRequest struct { +type ApiDeleteTestRequest struct { ctx context.Context ApiService *ResourceApiApiService - linterId string + testId string } -func (r ApiDeleteLinterRequest) Execute() (*http.Response, error) { - return r.ApiService.DeleteLinterExecute(r) +func (r ApiDeleteTestRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteTestExecute(r) } /* -DeleteLinter Delete an Linter +DeleteTest delete a test -Delete an Linter from Tracetest +delete a test @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param linterId ID of an Linter - @return ApiDeleteLinterRequest + @param testId id of the test + @return ApiDeleteTestRequest */ -func (a *ResourceApiApiService) DeleteLinter(ctx context.Context, linterId string) ApiDeleteLinterRequest { - return ApiDeleteLinterRequest{ +func (a *ResourceApiApiService) DeleteTest(ctx context.Context, testId string) ApiDeleteTestRequest { + return ApiDeleteTestRequest{ ApiService: a, ctx: ctx, - linterId: linterId, + testId: testId, } } // Execute executes the request -func (a *ResourceApiApiService) DeleteLinterExecute(r ApiDeleteLinterRequest) (*http.Response, error) { +func (a *ResourceApiApiService) DeleteTestExecute(r ApiDeleteTestRequest) (*http.Response, error) { var ( localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} formFiles []formFile ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteLinter") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteTest") if err != nil { return nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/linters/{LinterId}" - localVarPath = strings.Replace(localVarPath, "{"+"LinterId"+"}", url.PathEscape(parameterValueToString(r.linterId, "linterId")), -1) + localVarPath := localBasePath + "/tests/{testId}" + localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -930,48 +930,48 @@ func (a *ResourceApiApiService) DeleteLinterExecute(r ApiDeleteLinterRequest) (* return localVarHTTPResponse, nil } -type ApiDeleteTestRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - testId string +type ApiDeleteTransactionRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + transactionId string } -func (r ApiDeleteTestRequest) Execute() (*http.Response, error) { - return r.ApiService.DeleteTestExecute(r) +func (r ApiDeleteTransactionRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteTransactionExecute(r) } /* -DeleteTest delete a test +DeleteTransaction delete a transaction -delete a test +delete a transaction @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @return ApiDeleteTestRequest + @param transactionId id of the transaction + @return ApiDeleteTransactionRequest */ -func (a *ResourceApiApiService) DeleteTest(ctx context.Context, testId string) ApiDeleteTestRequest { - return ApiDeleteTestRequest{ - ApiService: a, - ctx: ctx, - testId: testId, +func (a *ResourceApiApiService) DeleteTransaction(ctx context.Context, transactionId string) ApiDeleteTransactionRequest { + return ApiDeleteTransactionRequest{ + ApiService: a, + ctx: ctx, + transactionId: transactionId, } } // Execute executes the request -func (a *ResourceApiApiService) DeleteTestExecute(r ApiDeleteTestRequest) (*http.Response, error) { +func (a *ResourceApiApiService) DeleteTransactionExecute(r ApiDeleteTransactionRequest) (*http.Response, error) { var ( localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} formFiles []formFile ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteTest") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteTransaction") if err != nil { return nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/tests/{testId}" - localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) + localVarPath := localBasePath + "/transactions/{transactionId}" + localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -1022,48 +1022,48 @@ func (a *ResourceApiApiService) DeleteTestExecute(r ApiDeleteTestRequest) (*http return localVarHTTPResponse, nil } -type ApiDeleteTransactionRequest struct { +type ApiDeleteVariableSetRequest struct { ctx context.Context ApiService *ResourceApiApiService - transactionId string + variableSetId string } -func (r ApiDeleteTransactionRequest) Execute() (*http.Response, error) { - return r.ApiService.DeleteTransactionExecute(r) +func (r ApiDeleteVariableSetRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteVariableSetExecute(r) } /* -DeleteTransaction delete a transaction +DeleteVariableSet Delete an VariableSet -delete a transaction +Delete an VariableSet from Tracetest @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @return ApiDeleteTransactionRequest + @param variableSetId ID of an VariableSet used on Tracetest to inject values into tests and transactions + @return ApiDeleteVariableSetRequest */ -func (a *ResourceApiApiService) DeleteTransaction(ctx context.Context, transactionId string) ApiDeleteTransactionRequest { - return ApiDeleteTransactionRequest{ +func (a *ResourceApiApiService) DeleteVariableSet(ctx context.Context, variableSetId string) ApiDeleteVariableSetRequest { + return ApiDeleteVariableSetRequest{ ApiService: a, ctx: ctx, - transactionId: transactionId, + variableSetId: variableSetId, } } // Execute executes the request -func (a *ResourceApiApiService) DeleteTransactionExecute(r ApiDeleteTransactionRequest) (*http.Response, error) { +func (a *ResourceApiApiService) DeleteVariableSetExecute(r ApiDeleteVariableSetRequest) (*http.Response, error) { var ( localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} formFiles []formFile ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteTransaction") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.DeleteVariableSet") if err != nil { return nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) + localVarPath := localBasePath + "/variableSets/{variableSetId}" + localVarPath = strings.Replace(localVarPath, "{"+"variableSetId"+"}", url.PathEscape(parameterValueToString(r.variableSetId, "variableSetId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -1426,110 +1426,6 @@ func (a *ResourceApiApiService) GetDemoExecute(r ApiGetDemoRequest) (*Demo, *htt return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetEnvironmentRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - environmentId string -} - -func (r ApiGetEnvironmentRequest) Execute() (*EnvironmentResource, *http.Response, error) { - return r.ApiService.GetEnvironmentExecute(r) -} - -/* -GetEnvironment Get a specific environment - -Get one environment by its id - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param environmentId ID of an environment used on Tracetest to inject values into tests and transactions - @return ApiGetEnvironmentRequest -*/ -func (a *ResourceApiApiService) GetEnvironment(ctx context.Context, environmentId string) ApiGetEnvironmentRequest { - return ApiGetEnvironmentRequest{ - ApiService: a, - ctx: ctx, - environmentId: environmentId, - } -} - -// Execute executes the request -// -// @return EnvironmentResource -func (a *ResourceApiApiService) GetEnvironmentExecute(r ApiGetEnvironmentRequest) (*EnvironmentResource, *http.Response, error) { - var ( - localVarHTTPMethod = http.MethodGet - localVarPostBody interface{} - formFiles []formFile - localVarReturnValue *EnvironmentResource - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetEnvironment") - if err != nil { - return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/environments/{environmentId}" - localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} - type ApiGetLinterRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -2142,6 +2038,110 @@ func (a *ResourceApiApiService) GetTransactionsExecute(r ApiGetTransactionsReque return localVarReturnValue, localVarHTTPResponse, nil } +type ApiGetVariableSetRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + variableSetId string +} + +func (r ApiGetVariableSetRequest) Execute() (*VariableSetResource, *http.Response, error) { + return r.ApiService.GetVariableSetExecute(r) +} + +/* +GetVariableSet Get a specific VariableSet + +Get one VariableSet by its id + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param variableSetId ID of an VariableSet used on Tracetest to inject values into tests and transactions + @return ApiGetVariableSetRequest +*/ +func (a *ResourceApiApiService) GetVariableSet(ctx context.Context, variableSetId string) ApiGetVariableSetRequest { + return ApiGetVariableSetRequest{ + ApiService: a, + ctx: ctx, + variableSetId: variableSetId, + } +} + +// Execute executes the request +// +// @return VariableSetResource +func (a *ResourceApiApiService) GetVariableSetExecute(r ApiGetVariableSetRequest) (*VariableSetResource, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *VariableSetResource + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetVariableSet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/variableSets/{variableSetId}" + localVarPath = strings.Replace(localVarPath, "{"+"variableSetId"+"}", url.PathEscape(parameterValueToString(r.variableSetId, "variableSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + type ApiListConfigurationRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -2562,7 +2562,7 @@ func (a *ResourceApiApiService) ListDemosExecute(r ApiListDemosRequest) (*DemoLi return localVarReturnValue, localVarHTTPResponse, nil } -type ApiListEnvironmentsRequest struct { +type ApiListLintersRequest struct { ctx context.Context ApiService *ResourceApiApiService take *int32 @@ -2572,43 +2572,43 @@ type ApiListEnvironmentsRequest struct { } // indicates how many resources can be returned by each page -func (r ApiListEnvironmentsRequest) Take(take int32) ApiListEnvironmentsRequest { +func (r ApiListLintersRequest) Take(take int32) ApiListLintersRequest { r.take = &take return r } // indicates how many resources will be skipped when paginating -func (r ApiListEnvironmentsRequest) Skip(skip int32) ApiListEnvironmentsRequest { +func (r ApiListLintersRequest) Skip(skip int32) ApiListLintersRequest { r.skip = &skip return r } // indicates the sort field for the resources -func (r ApiListEnvironmentsRequest) SortBy(sortBy string) ApiListEnvironmentsRequest { +func (r ApiListLintersRequest) SortBy(sortBy string) ApiListLintersRequest { r.sortBy = &sortBy return r } // indicates the sort direction for the resources -func (r ApiListEnvironmentsRequest) SortDirection(sortDirection string) ApiListEnvironmentsRequest { +func (r ApiListLintersRequest) SortDirection(sortDirection string) ApiListLintersRequest { r.sortDirection = &sortDirection return r } -func (r ApiListEnvironmentsRequest) Execute() (*EnvironmentResourceList, *http.Response, error) { - return r.ApiService.ListEnvironmentsExecute(r) +func (r ApiListLintersRequest) Execute() (*LinterResourceList, *http.Response, error) { + return r.ApiService.ListLintersExecute(r) } /* -ListEnvironments List environments +ListLinters List Linters -List environments available in Tracetest. +List Linters available in Tracetest. @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiListEnvironmentsRequest + @return ApiListLintersRequest */ -func (a *ResourceApiApiService) ListEnvironments(ctx context.Context) ApiListEnvironmentsRequest { - return ApiListEnvironmentsRequest{ +func (a *ResourceApiApiService) ListLinters(ctx context.Context) ApiListLintersRequest { + return ApiListLintersRequest{ ApiService: a, ctx: ctx, } @@ -2616,21 +2616,21 @@ func (a *ResourceApiApiService) ListEnvironments(ctx context.Context) ApiListEnv // Execute executes the request // -// @return EnvironmentResourceList -func (a *ResourceApiApiService) ListEnvironmentsExecute(r ApiListEnvironmentsRequest) (*EnvironmentResourceList, *http.Response, error) { +// @return LinterResourceList +func (a *ResourceApiApiService) ListLintersExecute(r ApiListLintersRequest) (*LinterResourceList, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *EnvironmentResourceList + localVarReturnValue *LinterResourceList ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.ListEnvironments") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.ListLinters") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/environments" + localVarPath := localBasePath + "/linters" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -2702,7 +2702,7 @@ func (a *ResourceApiApiService) ListEnvironmentsExecute(r ApiListEnvironmentsReq return localVarReturnValue, localVarHTTPResponse, nil } -type ApiListLintersRequest struct { +type ApiListPollingProfileRequest struct { ctx context.Context ApiService *ResourceApiApiService take *int32 @@ -2712,43 +2712,43 @@ type ApiListLintersRequest struct { } // indicates how many resources can be returned by each page -func (r ApiListLintersRequest) Take(take int32) ApiListLintersRequest { +func (r ApiListPollingProfileRequest) Take(take int32) ApiListPollingProfileRequest { r.take = &take return r } // indicates how many resources will be skipped when paginating -func (r ApiListLintersRequest) Skip(skip int32) ApiListLintersRequest { +func (r ApiListPollingProfileRequest) Skip(skip int32) ApiListPollingProfileRequest { r.skip = &skip return r } // indicates the sort field for the resources -func (r ApiListLintersRequest) SortBy(sortBy string) ApiListLintersRequest { +func (r ApiListPollingProfileRequest) SortBy(sortBy string) ApiListPollingProfileRequest { r.sortBy = &sortBy return r } // indicates the sort direction for the resources -func (r ApiListLintersRequest) SortDirection(sortDirection string) ApiListLintersRequest { +func (r ApiListPollingProfileRequest) SortDirection(sortDirection string) ApiListPollingProfileRequest { r.sortDirection = &sortDirection return r } -func (r ApiListLintersRequest) Execute() (*LinterResourceList, *http.Response, error) { - return r.ApiService.ListLintersExecute(r) +func (r ApiListPollingProfileRequest) Execute() (*PollingProfileList, *http.Response, error) { + return r.ApiService.ListPollingProfileExecute(r) } /* -ListLinters List Linters +ListPollingProfile List Polling Profile Configuration -List Linters available in Tracetest. +List Polling Profile configuration @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiListLintersRequest + @return ApiListPollingProfileRequest */ -func (a *ResourceApiApiService) ListLinters(ctx context.Context) ApiListLintersRequest { - return ApiListLintersRequest{ +func (a *ResourceApiApiService) ListPollingProfile(ctx context.Context) ApiListPollingProfileRequest { + return ApiListPollingProfileRequest{ ApiService: a, ctx: ctx, } @@ -2756,21 +2756,21 @@ func (a *ResourceApiApiService) ListLinters(ctx context.Context) ApiListLintersR // Execute executes the request // -// @return LinterResourceList -func (a *ResourceApiApiService) ListLintersExecute(r ApiListLintersRequest) (*LinterResourceList, *http.Response, error) { +// @return PollingProfileList +func (a *ResourceApiApiService) ListPollingProfileExecute(r ApiListPollingProfileRequest) (*PollingProfileList, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *LinterResourceList + localVarReturnValue *PollingProfileList ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.ListLinters") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.ListPollingProfile") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/linters" + localVarPath := localBasePath + "/pollingprofiles" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -2842,7 +2842,7 @@ func (a *ResourceApiApiService) ListLintersExecute(r ApiListLintersRequest) (*Li return localVarReturnValue, localVarHTTPResponse, nil } -type ApiListPollingProfileRequest struct { +type ApiListVariableSetsRequest struct { ctx context.Context ApiService *ResourceApiApiService take *int32 @@ -2852,43 +2852,43 @@ type ApiListPollingProfileRequest struct { } // indicates how many resources can be returned by each page -func (r ApiListPollingProfileRequest) Take(take int32) ApiListPollingProfileRequest { +func (r ApiListVariableSetsRequest) Take(take int32) ApiListVariableSetsRequest { r.take = &take return r } // indicates how many resources will be skipped when paginating -func (r ApiListPollingProfileRequest) Skip(skip int32) ApiListPollingProfileRequest { +func (r ApiListVariableSetsRequest) Skip(skip int32) ApiListVariableSetsRequest { r.skip = &skip return r } // indicates the sort field for the resources -func (r ApiListPollingProfileRequest) SortBy(sortBy string) ApiListPollingProfileRequest { +func (r ApiListVariableSetsRequest) SortBy(sortBy string) ApiListVariableSetsRequest { r.sortBy = &sortBy return r } // indicates the sort direction for the resources -func (r ApiListPollingProfileRequest) SortDirection(sortDirection string) ApiListPollingProfileRequest { +func (r ApiListVariableSetsRequest) SortDirection(sortDirection string) ApiListVariableSetsRequest { r.sortDirection = &sortDirection return r } -func (r ApiListPollingProfileRequest) Execute() (*PollingProfileList, *http.Response, error) { - return r.ApiService.ListPollingProfileExecute(r) +func (r ApiListVariableSetsRequest) Execute() (*VariableSetResourceList, *http.Response, error) { + return r.ApiService.ListVariableSetsExecute(r) } /* -ListPollingProfile List Polling Profile Configuration +ListVariableSets List variableSets -List Polling Profile configuration +List variableSets available in Tracetest. @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiListPollingProfileRequest + @return ApiListVariableSetsRequest */ -func (a *ResourceApiApiService) ListPollingProfile(ctx context.Context) ApiListPollingProfileRequest { - return ApiListPollingProfileRequest{ +func (a *ResourceApiApiService) ListVariableSets(ctx context.Context) ApiListVariableSetsRequest { + return ApiListVariableSetsRequest{ ApiService: a, ctx: ctx, } @@ -2896,21 +2896,21 @@ func (a *ResourceApiApiService) ListPollingProfile(ctx context.Context) ApiListP // Execute executes the request // -// @return PollingProfileList -func (a *ResourceApiApiService) ListPollingProfileExecute(r ApiListPollingProfileRequest) (*PollingProfileList, *http.Response, error) { +// @return VariableSetResourceList +func (a *ResourceApiApiService) ListVariableSetsExecute(r ApiListVariableSetsRequest) (*VariableSetResourceList, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *PollingProfileList + localVarReturnValue *VariableSetResourceList ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.ListPollingProfile") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.ListVariableSets") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/pollingprofiles" + localVarPath := localBasePath + "/variableSets" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -3410,118 +3410,6 @@ func (a *ResourceApiApiService) UpdateDemoExecute(r ApiUpdateDemoRequest) (*Demo return localVarReturnValue, localVarHTTPResponse, nil } -type ApiUpdateEnvironmentRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - environmentId string - environmentResource *EnvironmentResource -} - -func (r ApiUpdateEnvironmentRequest) EnvironmentResource(environmentResource EnvironmentResource) ApiUpdateEnvironmentRequest { - r.environmentResource = &environmentResource - return r -} - -func (r ApiUpdateEnvironmentRequest) Execute() (*EnvironmentResource, *http.Response, error) { - return r.ApiService.UpdateEnvironmentExecute(r) -} - -/* -UpdateEnvironment Update an environment - -Update an environment used on Tracetest - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param environmentId ID of an environment used on Tracetest to inject values into tests and transactions - @return ApiUpdateEnvironmentRequest -*/ -func (a *ResourceApiApiService) UpdateEnvironment(ctx context.Context, environmentId string) ApiUpdateEnvironmentRequest { - return ApiUpdateEnvironmentRequest{ - ApiService: a, - ctx: ctx, - environmentId: environmentId, - } -} - -// Execute executes the request -// -// @return EnvironmentResource -func (a *ResourceApiApiService) UpdateEnvironmentExecute(r ApiUpdateEnvironmentRequest) (*EnvironmentResource, *http.Response, error) { - var ( - localVarHTTPMethod = http.MethodPut - localVarPostBody interface{} - formFiles []formFile - localVarReturnValue *EnvironmentResource - ) - - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.UpdateEnvironment") - if err != nil { - return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} - } - - localVarPath := localBasePath + "/environments/{environmentId}" - localVarPath = strings.Replace(localVarPath, "{"+"environmentId"+"}", url.PathEscape(parameterValueToString(r.environmentId, "environmentId")), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHTTPContentTypes := []string{"application/json", "text/yaml"} - - // set Content-Type header - localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) - if localVarHTTPContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHTTPContentType - } - - // to determine the Accept header - localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} - - // set Accept header - localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) - if localVarHTTPHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept - } - // body params - localVarPostBody = r.environmentResource - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHTTPResponse, err := a.client.callAPI(req) - if err != nil || localVarHTTPResponse == nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) - localVarHTTPResponse.Body.Close() - localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) - if err != nil { - return localVarReturnValue, localVarHTTPResponse, err - } - - if localVarHTTPResponse.StatusCode >= 300 { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: localVarHTTPResponse.Status, - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) - if err != nil { - newErr := &GenericOpenAPIError{ - body: localVarBody, - error: err.Error(), - } - return localVarReturnValue, localVarHTTPResponse, newErr - } - - return localVarReturnValue, localVarHTTPResponse, nil -} - type ApiUpdateLinterRequest struct { ctx context.Context ApiService *ResourceApiApiService @@ -3957,3 +3845,115 @@ func (a *ResourceApiApiService) UpdateTransactionExecute(r ApiUpdateTransactionR return localVarReturnValue, localVarHTTPResponse, nil } + +type ApiUpdateVariableSetRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + variableSetId string + variableSetResource *VariableSetResource +} + +func (r ApiUpdateVariableSetRequest) VariableSetResource(variableSetResource VariableSetResource) ApiUpdateVariableSetRequest { + r.variableSetResource = &variableSetResource + return r +} + +func (r ApiUpdateVariableSetRequest) Execute() (*VariableSetResource, *http.Response, error) { + return r.ApiService.UpdateVariableSetExecute(r) +} + +/* +UpdateVariableSet Update an VariableSet + +Update an VariableSet used on Tracetest + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param variableSetId ID of an VariableSet used on Tracetest to inject values into tests and transactions + @return ApiUpdateVariableSetRequest +*/ +func (a *ResourceApiApiService) UpdateVariableSet(ctx context.Context, variableSetId string) ApiUpdateVariableSetRequest { + return ApiUpdateVariableSetRequest{ + ApiService: a, + ctx: ctx, + variableSetId: variableSetId, + } +} + +// Execute executes the request +// +// @return VariableSetResource +func (a *ResourceApiApiService) UpdateVariableSetExecute(r ApiUpdateVariableSetRequest) (*VariableSetResource, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *VariableSetResource + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.UpdateVariableSet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/variableSets/{variableSetId}" + localVarPath = strings.Replace(localVarPath, "{"+"variableSetId"+"}", url.PathEscape(parameterValueToString(r.variableSetId, "variableSetId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json", "text/yaml"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json", "text/yaml"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.variableSetResource + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/cli/openapi/model_list_environments_200_response.go b/cli/openapi/model_list_variable_sets_200_response.go similarity index 54% rename from cli/openapi/model_list_environments_200_response.go rename to cli/openapi/model_list_variable_sets_200_response.go index 149e59f2b3..a3708c0b7f 100644 --- a/cli/openapi/model_list_environments_200_response.go +++ b/cli/openapi/model_list_variable_sets_200_response.go @@ -14,34 +14,34 @@ import ( "encoding/json" ) -// checks if the ListEnvironments200Response type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &ListEnvironments200Response{} +// checks if the ListVariableSets200Response type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ListVariableSets200Response{} -// ListEnvironments200Response struct for ListEnvironments200Response -type ListEnvironments200Response struct { +// ListVariableSets200Response struct for ListVariableSets200Response +type ListVariableSets200Response struct { Count *int32 `json:"count,omitempty"` - Items []EnvironmentResource `json:"items,omitempty"` + Items []VariableSetResource `json:"items,omitempty"` } -// NewListEnvironments200Response instantiates a new ListEnvironments200Response object +// NewListVariableSets200Response instantiates a new ListVariableSets200Response object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewListEnvironments200Response() *ListEnvironments200Response { - this := ListEnvironments200Response{} +func NewListVariableSets200Response() *ListVariableSets200Response { + this := ListVariableSets200Response{} return &this } -// NewListEnvironments200ResponseWithDefaults instantiates a new ListEnvironments200Response object +// NewListVariableSets200ResponseWithDefaults instantiates a new ListVariableSets200Response object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set -func NewListEnvironments200ResponseWithDefaults() *ListEnvironments200Response { - this := ListEnvironments200Response{} +func NewListVariableSets200ResponseWithDefaults() *ListVariableSets200Response { + this := ListVariableSets200Response{} return &this } // GetCount returns the Count field value if set, zero value otherwise. -func (o *ListEnvironments200Response) GetCount() int32 { +func (o *ListVariableSets200Response) GetCount() int32 { if o == nil || isNil(o.Count) { var ret int32 return ret @@ -51,7 +51,7 @@ func (o *ListEnvironments200Response) GetCount() int32 { // GetCountOk returns a tuple with the Count field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *ListEnvironments200Response) GetCountOk() (*int32, bool) { +func (o *ListVariableSets200Response) GetCountOk() (*int32, bool) { if o == nil || isNil(o.Count) { return nil, false } @@ -59,7 +59,7 @@ func (o *ListEnvironments200Response) GetCountOk() (*int32, bool) { } // HasCount returns a boolean if a field has been set. -func (o *ListEnvironments200Response) HasCount() bool { +func (o *ListVariableSets200Response) HasCount() bool { if o != nil && !isNil(o.Count) { return true } @@ -68,14 +68,14 @@ func (o *ListEnvironments200Response) HasCount() bool { } // SetCount gets a reference to the given int32 and assigns it to the Count field. -func (o *ListEnvironments200Response) SetCount(v int32) { +func (o *ListVariableSets200Response) SetCount(v int32) { o.Count = &v } // GetItems returns the Items field value if set, zero value otherwise. -func (o *ListEnvironments200Response) GetItems() []EnvironmentResource { +func (o *ListVariableSets200Response) GetItems() []VariableSetResource { if o == nil || isNil(o.Items) { - var ret []EnvironmentResource + var ret []VariableSetResource return ret } return o.Items @@ -83,7 +83,7 @@ func (o *ListEnvironments200Response) GetItems() []EnvironmentResource { // GetItemsOk returns a tuple with the Items field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *ListEnvironments200Response) GetItemsOk() ([]EnvironmentResource, bool) { +func (o *ListVariableSets200Response) GetItemsOk() ([]VariableSetResource, bool) { if o == nil || isNil(o.Items) { return nil, false } @@ -91,7 +91,7 @@ func (o *ListEnvironments200Response) GetItemsOk() ([]EnvironmentResource, bool) } // HasItems returns a boolean if a field has been set. -func (o *ListEnvironments200Response) HasItems() bool { +func (o *ListVariableSets200Response) HasItems() bool { if o != nil && !isNil(o.Items) { return true } @@ -99,12 +99,12 @@ func (o *ListEnvironments200Response) HasItems() bool { return false } -// SetItems gets a reference to the given []EnvironmentResource and assigns it to the Items field. -func (o *ListEnvironments200Response) SetItems(v []EnvironmentResource) { +// SetItems gets a reference to the given []VariableSetResource and assigns it to the Items field. +func (o *ListVariableSets200Response) SetItems(v []VariableSetResource) { o.Items = v } -func (o ListEnvironments200Response) MarshalJSON() ([]byte, error) { +func (o ListVariableSets200Response) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -112,7 +112,7 @@ func (o ListEnvironments200Response) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o ListEnvironments200Response) ToMap() (map[string]interface{}, error) { +func (o ListVariableSets200Response) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Count) { toSerialize["count"] = o.Count @@ -123,38 +123,38 @@ func (o ListEnvironments200Response) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableListEnvironments200Response struct { - value *ListEnvironments200Response +type NullableListVariableSets200Response struct { + value *ListVariableSets200Response isSet bool } -func (v NullableListEnvironments200Response) Get() *ListEnvironments200Response { +func (v NullableListVariableSets200Response) Get() *ListVariableSets200Response { return v.value } -func (v *NullableListEnvironments200Response) Set(val *ListEnvironments200Response) { +func (v *NullableListVariableSets200Response) Set(val *ListVariableSets200Response) { v.value = val v.isSet = true } -func (v NullableListEnvironments200Response) IsSet() bool { +func (v NullableListVariableSets200Response) IsSet() bool { return v.isSet } -func (v *NullableListEnvironments200Response) Unset() { +func (v *NullableListVariableSets200Response) Unset() { v.value = nil v.isSet = false } -func NewNullableListEnvironments200Response(val *ListEnvironments200Response) *NullableListEnvironments200Response { - return &NullableListEnvironments200Response{value: val, isSet: true} +func NewNullableListVariableSets200Response(val *ListVariableSets200Response) *NullableListVariableSets200Response { + return &NullableListVariableSets200Response{value: val, isSet: true} } -func (v NullableListEnvironments200Response) MarshalJSON() ([]byte, error) { +func (v NullableListVariableSets200Response) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableListEnvironments200Response) UnmarshalJSON(src []byte) error { +func (v *NullableListVariableSets200Response) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_resolve_context.go b/cli/openapi/model_resolve_context.go index 80f381f0ce..2c34b78c8b 100644 --- a/cli/openapi/model_resolve_context.go +++ b/cli/openapi/model_resolve_context.go @@ -23,7 +23,7 @@ type ResolveContext struct { RunId *string `json:"runId,omitempty"` SpanId *string `json:"spanId,omitempty"` Selector *string `json:"selector,omitempty"` - EnvironmentId *string `json:"environmentId,omitempty"` + VariableSetId *string `json:"variableSetId,omitempty"` } // NewResolveContext instantiates a new ResolveContext object @@ -171,36 +171,36 @@ func (o *ResolveContext) SetSelector(v string) { o.Selector = &v } -// GetEnvironmentId returns the EnvironmentId field value if set, zero value otherwise. -func (o *ResolveContext) GetEnvironmentId() string { - if o == nil || isNil(o.EnvironmentId) { +// GetVariableSetId returns the VariableSetId field value if set, zero value otherwise. +func (o *ResolveContext) GetVariableSetId() string { + if o == nil || isNil(o.VariableSetId) { var ret string return ret } - return *o.EnvironmentId + return *o.VariableSetId } -// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value if set, nil otherwise +// GetVariableSetIdOk returns a tuple with the VariableSetId field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *ResolveContext) GetEnvironmentIdOk() (*string, bool) { - if o == nil || isNil(o.EnvironmentId) { +func (o *ResolveContext) GetVariableSetIdOk() (*string, bool) { + if o == nil || isNil(o.VariableSetId) { return nil, false } - return o.EnvironmentId, true + return o.VariableSetId, true } -// HasEnvironmentId returns a boolean if a field has been set. -func (o *ResolveContext) HasEnvironmentId() bool { - if o != nil && !isNil(o.EnvironmentId) { +// HasVariableSetId returns a boolean if a field has been set. +func (o *ResolveContext) HasVariableSetId() bool { + if o != nil && !isNil(o.VariableSetId) { return true } return false } -// SetEnvironmentId gets a reference to the given string and assigns it to the EnvironmentId field. -func (o *ResolveContext) SetEnvironmentId(v string) { - o.EnvironmentId = &v +// SetVariableSetId gets a reference to the given string and assigns it to the VariableSetId field. +func (o *ResolveContext) SetVariableSetId(v string) { + o.VariableSetId = &v } func (o ResolveContext) MarshalJSON() ([]byte, error) { @@ -225,8 +225,8 @@ func (o ResolveContext) ToMap() (map[string]interface{}, error) { if !isNil(o.Selector) { toSerialize["selector"] = o.Selector } - if !isNil(o.EnvironmentId) { - toSerialize["environmentId"] = o.EnvironmentId + if !isNil(o.VariableSetId) { + toSerialize["variableSetId"] = o.VariableSetId } return toSerialize, nil } diff --git a/cli/openapi/model_run_information.go b/cli/openapi/model_run_information.go index a9e37349a3..c086c9cb91 100644 --- a/cli/openapi/model_run_information.go +++ b/cli/openapi/model_run_information.go @@ -20,8 +20,8 @@ var _ MappedNullable = &RunInformation{} // RunInformation struct for RunInformation type RunInformation struct { Metadata map[string]string `json:"metadata,omitempty"` - EnvironmentId *string `json:"environmentId,omitempty"` - Variables []EnvironmentValue `json:"variables,omitempty"` + VariableSetId *string `json:"variableSetId,omitempty"` + Variables []VariableSetValue `json:"variables,omitempty"` RequiredGates []SupportedGates `json:"requiredGates,omitempty"` } @@ -75,42 +75,42 @@ func (o *RunInformation) SetMetadata(v map[string]string) { o.Metadata = v } -// GetEnvironmentId returns the EnvironmentId field value if set, zero value otherwise. -func (o *RunInformation) GetEnvironmentId() string { - if o == nil || isNil(o.EnvironmentId) { +// GetVariableSetId returns the VariableSetId field value if set, zero value otherwise. +func (o *RunInformation) GetVariableSetId() string { + if o == nil || isNil(o.VariableSetId) { var ret string return ret } - return *o.EnvironmentId + return *o.VariableSetId } -// GetEnvironmentIdOk returns a tuple with the EnvironmentId field value if set, nil otherwise +// GetVariableSetIdOk returns a tuple with the VariableSetId field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *RunInformation) GetEnvironmentIdOk() (*string, bool) { - if o == nil || isNil(o.EnvironmentId) { +func (o *RunInformation) GetVariableSetIdOk() (*string, bool) { + if o == nil || isNil(o.VariableSetId) { return nil, false } - return o.EnvironmentId, true + return o.VariableSetId, true } -// HasEnvironmentId returns a boolean if a field has been set. -func (o *RunInformation) HasEnvironmentId() bool { - if o != nil && !isNil(o.EnvironmentId) { +// HasVariableSetId returns a boolean if a field has been set. +func (o *RunInformation) HasVariableSetId() bool { + if o != nil && !isNil(o.VariableSetId) { return true } return false } -// SetEnvironmentId gets a reference to the given string and assigns it to the EnvironmentId field. -func (o *RunInformation) SetEnvironmentId(v string) { - o.EnvironmentId = &v +// SetVariableSetId gets a reference to the given string and assigns it to the VariableSetId field. +func (o *RunInformation) SetVariableSetId(v string) { + o.VariableSetId = &v } // GetVariables returns the Variables field value if set, zero value otherwise. -func (o *RunInformation) GetVariables() []EnvironmentValue { +func (o *RunInformation) GetVariables() []VariableSetValue { if o == nil || isNil(o.Variables) { - var ret []EnvironmentValue + var ret []VariableSetValue return ret } return o.Variables @@ -118,7 +118,7 @@ func (o *RunInformation) GetVariables() []EnvironmentValue { // GetVariablesOk returns a tuple with the Variables field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *RunInformation) GetVariablesOk() ([]EnvironmentValue, bool) { +func (o *RunInformation) GetVariablesOk() ([]VariableSetValue, bool) { if o == nil || isNil(o.Variables) { return nil, false } @@ -134,8 +134,8 @@ func (o *RunInformation) HasVariables() bool { return false } -// SetVariables gets a reference to the given []EnvironmentValue and assigns it to the Variables field. -func (o *RunInformation) SetVariables(v []EnvironmentValue) { +// SetVariables gets a reference to the given []VariableSetValue and assigns it to the Variables field. +func (o *RunInformation) SetVariables(v []VariableSetValue) { o.Variables = v } @@ -185,8 +185,8 @@ func (o RunInformation) ToMap() (map[string]interface{}, error) { if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } - if !isNil(o.EnvironmentId) { - toSerialize["environmentId"] = o.EnvironmentId + if !isNil(o.VariableSetId) { + toSerialize["variableSetId"] = o.VariableSetId } if !isNil(o.Variables) { toSerialize["variables"] = o.Variables diff --git a/cli/openapi/model_test_run.go b/cli/openapi/model_test_run.go index 55b2f4f518..3acf317507 100644 --- a/cli/openapi/model_test_run.go +++ b/cli/openapi/model_test_run.go @@ -38,7 +38,7 @@ type TestRun struct { ServiceTriggerCompletedAt *time.Time `json:"serviceTriggerCompletedAt,omitempty"` ObtainedTraceAt *time.Time `json:"obtainedTraceAt,omitempty"` CompletedAt *time.Time `json:"completedAt,omitempty"` - Environment *Environment `json:"environment,omitempty"` + VariableSet *VariableSet `json:"variableSet,omitempty"` TriggerResult *TriggerResult `json:"triggerResult,omitempty"` Trace *Trace `json:"trace,omitempty"` Result *AssertionResults `json:"result,omitempty"` @@ -483,36 +483,36 @@ func (o *TestRun) SetCompletedAt(v time.Time) { o.CompletedAt = &v } -// GetEnvironment returns the Environment field value if set, zero value otherwise. -func (o *TestRun) GetEnvironment() Environment { - if o == nil || isNil(o.Environment) { - var ret Environment +// GetVariableSet returns the VariableSet field value if set, zero value otherwise. +func (o *TestRun) GetVariableSet() VariableSet { + if o == nil || isNil(o.VariableSet) { + var ret VariableSet return ret } - return *o.Environment + return *o.VariableSet } -// GetEnvironmentOk returns a tuple with the Environment field value if set, nil otherwise +// GetVariableSetOk returns a tuple with the VariableSet field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TestRun) GetEnvironmentOk() (*Environment, bool) { - if o == nil || isNil(o.Environment) { +func (o *TestRun) GetVariableSetOk() (*VariableSet, bool) { + if o == nil || isNil(o.VariableSet) { return nil, false } - return o.Environment, true + return o.VariableSet, true } -// HasEnvironment returns a boolean if a field has been set. -func (o *TestRun) HasEnvironment() bool { - if o != nil && !isNil(o.Environment) { +// HasVariableSet returns a boolean if a field has been set. +func (o *TestRun) HasVariableSet() bool { + if o != nil && !isNil(o.VariableSet) { return true } return false } -// SetEnvironment gets a reference to the given Environment and assigns it to the Environment field. -func (o *TestRun) SetEnvironment(v Environment) { - o.Environment = &v +// SetVariableSet gets a reference to the given VariableSet and assigns it to the VariableSet field. +func (o *TestRun) SetVariableSet(v VariableSet) { + o.VariableSet = &v } // GetTriggerResult returns the TriggerResult field value if set, zero value otherwise. @@ -846,8 +846,8 @@ func (o TestRun) ToMap() (map[string]interface{}, error) { if !isNil(o.CompletedAt) { toSerialize["completedAt"] = o.CompletedAt } - if !isNil(o.Environment) { - toSerialize["environment"] = o.Environment + if !isNil(o.VariableSet) { + toSerialize["variableSet"] = o.VariableSet } if !isNil(o.TriggerResult) { toSerialize["triggerResult"] = o.TriggerResult diff --git a/cli/openapi/model_transaction_run.go b/cli/openapi/model_transaction_run.go index ef9fd0e91e..743e4ea437 100644 --- a/cli/openapi/model_transaction_run.go +++ b/cli/openapi/model_transaction_run.go @@ -26,7 +26,7 @@ type TransactionRun struct { CompletedAt *time.Time `json:"completedAt,omitempty"` State *string `json:"state,omitempty"` Steps []TestRun `json:"steps,omitempty"` - Environment *Environment `json:"environment,omitempty"` + VariableSet *VariableSet `json:"variableSet,omitempty"` Metadata *map[string]string `json:"metadata,omitempty"` Pass *int32 `json:"pass,omitempty"` Fail *int32 `json:"fail,omitempty"` @@ -242,36 +242,36 @@ func (o *TransactionRun) SetSteps(v []TestRun) { o.Steps = v } -// GetEnvironment returns the Environment field value if set, zero value otherwise. -func (o *TransactionRun) GetEnvironment() Environment { - if o == nil || isNil(o.Environment) { - var ret Environment +// GetVariableSet returns the VariableSet field value if set, zero value otherwise. +func (o *TransactionRun) GetVariableSet() VariableSet { + if o == nil || isNil(o.VariableSet) { + var ret VariableSet return ret } - return *o.Environment + return *o.VariableSet } -// GetEnvironmentOk returns a tuple with the Environment field value if set, nil otherwise +// GetVariableSetOk returns a tuple with the VariableSet field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetEnvironmentOk() (*Environment, bool) { - if o == nil || isNil(o.Environment) { +func (o *TransactionRun) GetVariableSetOk() (*VariableSet, bool) { + if o == nil || isNil(o.VariableSet) { return nil, false } - return o.Environment, true + return o.VariableSet, true } -// HasEnvironment returns a boolean if a field has been set. -func (o *TransactionRun) HasEnvironment() bool { - if o != nil && !isNil(o.Environment) { +// HasVariableSet returns a boolean if a field has been set. +func (o *TransactionRun) HasVariableSet() bool { + if o != nil && !isNil(o.VariableSet) { return true } return false } -// SetEnvironment gets a reference to the given Environment and assigns it to the Environment field. -func (o *TransactionRun) SetEnvironment(v Environment) { - o.Environment = &v +// SetVariableSet gets a reference to the given VariableSet and assigns it to the VariableSet field. +func (o *TransactionRun) SetVariableSet(v VariableSet) { + o.VariableSet = &v } // GetMetadata returns the Metadata field value if set, zero value otherwise. @@ -426,8 +426,8 @@ func (o TransactionRun) ToMap() (map[string]interface{}, error) { if !isNil(o.Steps) { toSerialize["steps"] = o.Steps } - if !isNil(o.Environment) { - toSerialize["environment"] = o.Environment + if !isNil(o.VariableSet) { + toSerialize["variableSet"] = o.VariableSet } if !isNil(o.Metadata) { toSerialize["metadata"] = o.Metadata diff --git a/cli/openapi/model_environment.go b/cli/openapi/model_variable_set.go similarity index 66% rename from cli/openapi/model_environment.go rename to cli/openapi/model_variable_set.go index c46f477e0b..9b59b29b89 100644 --- a/cli/openapi/model_environment.go +++ b/cli/openapi/model_variable_set.go @@ -14,36 +14,36 @@ import ( "encoding/json" ) -// checks if the Environment type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &Environment{} +// checks if the VariableSet type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &VariableSet{} -// Environment struct for Environment -type Environment struct { +// VariableSet struct for VariableSet +type VariableSet struct { Id *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` Description *string `json:"description,omitempty"` - Values []EnvironmentValue `json:"values,omitempty"` + Values []VariableSetValue `json:"values,omitempty"` } -// NewEnvironment instantiates a new Environment object +// NewVariableSet instantiates a new VariableSet object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewEnvironment() *Environment { - this := Environment{} +func NewVariableSet() *VariableSet { + this := VariableSet{} return &this } -// NewEnvironmentWithDefaults instantiates a new Environment object +// NewVariableSetWithDefaults instantiates a new VariableSet object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set -func NewEnvironmentWithDefaults() *Environment { - this := Environment{} +func NewVariableSetWithDefaults() *VariableSet { + this := VariableSet{} return &this } // GetId returns the Id field value if set, zero value otherwise. -func (o *Environment) GetId() string { +func (o *VariableSet) GetId() string { if o == nil || isNil(o.Id) { var ret string return ret @@ -53,7 +53,7 @@ func (o *Environment) GetId() string { // GetIdOk returns a tuple with the Id field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Environment) GetIdOk() (*string, bool) { +func (o *VariableSet) GetIdOk() (*string, bool) { if o == nil || isNil(o.Id) { return nil, false } @@ -61,7 +61,7 @@ func (o *Environment) GetIdOk() (*string, bool) { } // HasId returns a boolean if a field has been set. -func (o *Environment) HasId() bool { +func (o *VariableSet) HasId() bool { if o != nil && !isNil(o.Id) { return true } @@ -70,12 +70,12 @@ func (o *Environment) HasId() bool { } // SetId gets a reference to the given string and assigns it to the Id field. -func (o *Environment) SetId(v string) { +func (o *VariableSet) SetId(v string) { o.Id = &v } // GetName returns the Name field value if set, zero value otherwise. -func (o *Environment) GetName() string { +func (o *VariableSet) GetName() string { if o == nil || isNil(o.Name) { var ret string return ret @@ -85,7 +85,7 @@ func (o *Environment) GetName() string { // GetNameOk returns a tuple with the Name field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Environment) GetNameOk() (*string, bool) { +func (o *VariableSet) GetNameOk() (*string, bool) { if o == nil || isNil(o.Name) { return nil, false } @@ -93,7 +93,7 @@ func (o *Environment) GetNameOk() (*string, bool) { } // HasName returns a boolean if a field has been set. -func (o *Environment) HasName() bool { +func (o *VariableSet) HasName() bool { if o != nil && !isNil(o.Name) { return true } @@ -102,12 +102,12 @@ func (o *Environment) HasName() bool { } // SetName gets a reference to the given string and assigns it to the Name field. -func (o *Environment) SetName(v string) { +func (o *VariableSet) SetName(v string) { o.Name = &v } // GetDescription returns the Description field value if set, zero value otherwise. -func (o *Environment) GetDescription() string { +func (o *VariableSet) GetDescription() string { if o == nil || isNil(o.Description) { var ret string return ret @@ -117,7 +117,7 @@ func (o *Environment) GetDescription() string { // GetDescriptionOk returns a tuple with the Description field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Environment) GetDescriptionOk() (*string, bool) { +func (o *VariableSet) GetDescriptionOk() (*string, bool) { if o == nil || isNil(o.Description) { return nil, false } @@ -125,7 +125,7 @@ func (o *Environment) GetDescriptionOk() (*string, bool) { } // HasDescription returns a boolean if a field has been set. -func (o *Environment) HasDescription() bool { +func (o *VariableSet) HasDescription() bool { if o != nil && !isNil(o.Description) { return true } @@ -134,14 +134,14 @@ func (o *Environment) HasDescription() bool { } // SetDescription gets a reference to the given string and assigns it to the Description field. -func (o *Environment) SetDescription(v string) { +func (o *VariableSet) SetDescription(v string) { o.Description = &v } // GetValues returns the Values field value if set, zero value otherwise. -func (o *Environment) GetValues() []EnvironmentValue { +func (o *VariableSet) GetValues() []VariableSetValue { if o == nil || isNil(o.Values) { - var ret []EnvironmentValue + var ret []VariableSetValue return ret } return o.Values @@ -149,7 +149,7 @@ func (o *Environment) GetValues() []EnvironmentValue { // GetValuesOk returns a tuple with the Values field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Environment) GetValuesOk() ([]EnvironmentValue, bool) { +func (o *VariableSet) GetValuesOk() ([]VariableSetValue, bool) { if o == nil || isNil(o.Values) { return nil, false } @@ -157,7 +157,7 @@ func (o *Environment) GetValuesOk() ([]EnvironmentValue, bool) { } // HasValues returns a boolean if a field has been set. -func (o *Environment) HasValues() bool { +func (o *VariableSet) HasValues() bool { if o != nil && !isNil(o.Values) { return true } @@ -165,12 +165,12 @@ func (o *Environment) HasValues() bool { return false } -// SetValues gets a reference to the given []EnvironmentValue and assigns it to the Values field. -func (o *Environment) SetValues(v []EnvironmentValue) { +// SetValues gets a reference to the given []VariableSetValue and assigns it to the Values field. +func (o *VariableSet) SetValues(v []VariableSetValue) { o.Values = v } -func (o Environment) MarshalJSON() ([]byte, error) { +func (o VariableSet) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -178,7 +178,7 @@ func (o Environment) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o Environment) ToMap() (map[string]interface{}, error) { +func (o VariableSet) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Id) { toSerialize["id"] = o.Id @@ -195,38 +195,38 @@ func (o Environment) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableEnvironment struct { - value *Environment +type NullableVariableSet struct { + value *VariableSet isSet bool } -func (v NullableEnvironment) Get() *Environment { +func (v NullableVariableSet) Get() *VariableSet { return v.value } -func (v *NullableEnvironment) Set(val *Environment) { +func (v *NullableVariableSet) Set(val *VariableSet) { v.value = val v.isSet = true } -func (v NullableEnvironment) IsSet() bool { +func (v NullableVariableSet) IsSet() bool { return v.isSet } -func (v *NullableEnvironment) Unset() { +func (v *NullableVariableSet) Unset() { v.value = nil v.isSet = false } -func NewNullableEnvironment(val *Environment) *NullableEnvironment { - return &NullableEnvironment{value: val, isSet: true} +func NewNullableVariableSet(val *VariableSet) *NullableVariableSet { + return &NullableVariableSet{value: val, isSet: true} } -func (v NullableEnvironment) MarshalJSON() ([]byte, error) { +func (v NullableVariableSet) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableEnvironment) UnmarshalJSON(src []byte) error { +func (v *NullableVariableSet) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_environment_resource.go b/cli/openapi/model_variable_set_resource.go similarity index 57% rename from cli/openapi/model_environment_resource.go rename to cli/openapi/model_variable_set_resource.go index ec1b29a3e4..3c49e720e9 100644 --- a/cli/openapi/model_environment_resource.go +++ b/cli/openapi/model_variable_set_resource.go @@ -14,35 +14,35 @@ import ( "encoding/json" ) -// checks if the EnvironmentResource type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &EnvironmentResource{} +// checks if the VariableSetResource type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &VariableSetResource{} -// EnvironmentResource Represents an environment structured into the Resources format. -type EnvironmentResource struct { - // Represents the type of this resource. It should always be set as 'Environment'. +// VariableSetResource Represents an VariableSet structured into the Resources format. +type VariableSetResource struct { + // Represents the type of this resource. It should always be set as 'VariableSet'. Type *string `json:"type,omitempty"` - Spec *Environment `json:"spec,omitempty"` + Spec *VariableSet `json:"spec,omitempty"` } -// NewEnvironmentResource instantiates a new EnvironmentResource object +// NewVariableSetResource instantiates a new VariableSetResource object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewEnvironmentResource() *EnvironmentResource { - this := EnvironmentResource{} +func NewVariableSetResource() *VariableSetResource { + this := VariableSetResource{} return &this } -// NewEnvironmentResourceWithDefaults instantiates a new EnvironmentResource object +// NewVariableSetResourceWithDefaults instantiates a new VariableSetResource object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set -func NewEnvironmentResourceWithDefaults() *EnvironmentResource { - this := EnvironmentResource{} +func NewVariableSetResourceWithDefaults() *VariableSetResource { + this := VariableSetResource{} return &this } // GetType returns the Type field value if set, zero value otherwise. -func (o *EnvironmentResource) GetType() string { +func (o *VariableSetResource) GetType() string { if o == nil || isNil(o.Type) { var ret string return ret @@ -52,7 +52,7 @@ func (o *EnvironmentResource) GetType() string { // GetTypeOk returns a tuple with the Type field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *EnvironmentResource) GetTypeOk() (*string, bool) { +func (o *VariableSetResource) GetTypeOk() (*string, bool) { if o == nil || isNil(o.Type) { return nil, false } @@ -60,7 +60,7 @@ func (o *EnvironmentResource) GetTypeOk() (*string, bool) { } // HasType returns a boolean if a field has been set. -func (o *EnvironmentResource) HasType() bool { +func (o *VariableSetResource) HasType() bool { if o != nil && !isNil(o.Type) { return true } @@ -69,14 +69,14 @@ func (o *EnvironmentResource) HasType() bool { } // SetType gets a reference to the given string and assigns it to the Type field. -func (o *EnvironmentResource) SetType(v string) { +func (o *VariableSetResource) SetType(v string) { o.Type = &v } // GetSpec returns the Spec field value if set, zero value otherwise. -func (o *EnvironmentResource) GetSpec() Environment { +func (o *VariableSetResource) GetSpec() VariableSet { if o == nil || isNil(o.Spec) { - var ret Environment + var ret VariableSet return ret } return *o.Spec @@ -84,7 +84,7 @@ func (o *EnvironmentResource) GetSpec() Environment { // GetSpecOk returns a tuple with the Spec field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *EnvironmentResource) GetSpecOk() (*Environment, bool) { +func (o *VariableSetResource) GetSpecOk() (*VariableSet, bool) { if o == nil || isNil(o.Spec) { return nil, false } @@ -92,7 +92,7 @@ func (o *EnvironmentResource) GetSpecOk() (*Environment, bool) { } // HasSpec returns a boolean if a field has been set. -func (o *EnvironmentResource) HasSpec() bool { +func (o *VariableSetResource) HasSpec() bool { if o != nil && !isNil(o.Spec) { return true } @@ -100,12 +100,12 @@ func (o *EnvironmentResource) HasSpec() bool { return false } -// SetSpec gets a reference to the given Environment and assigns it to the Spec field. -func (o *EnvironmentResource) SetSpec(v Environment) { +// SetSpec gets a reference to the given VariableSet and assigns it to the Spec field. +func (o *VariableSetResource) SetSpec(v VariableSet) { o.Spec = &v } -func (o EnvironmentResource) MarshalJSON() ([]byte, error) { +func (o VariableSetResource) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -113,7 +113,7 @@ func (o EnvironmentResource) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o EnvironmentResource) ToMap() (map[string]interface{}, error) { +func (o VariableSetResource) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Type) { toSerialize["type"] = o.Type @@ -124,38 +124,38 @@ func (o EnvironmentResource) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableEnvironmentResource struct { - value *EnvironmentResource +type NullableVariableSetResource struct { + value *VariableSetResource isSet bool } -func (v NullableEnvironmentResource) Get() *EnvironmentResource { +func (v NullableVariableSetResource) Get() *VariableSetResource { return v.value } -func (v *NullableEnvironmentResource) Set(val *EnvironmentResource) { +func (v *NullableVariableSetResource) Set(val *VariableSetResource) { v.value = val v.isSet = true } -func (v NullableEnvironmentResource) IsSet() bool { +func (v NullableVariableSetResource) IsSet() bool { return v.isSet } -func (v *NullableEnvironmentResource) Unset() { +func (v *NullableVariableSetResource) Unset() { v.value = nil v.isSet = false } -func NewNullableEnvironmentResource(val *EnvironmentResource) *NullableEnvironmentResource { - return &NullableEnvironmentResource{value: val, isSet: true} +func NewNullableVariableSetResource(val *VariableSetResource) *NullableVariableSetResource { + return &NullableVariableSetResource{value: val, isSet: true} } -func (v NullableEnvironmentResource) MarshalJSON() ([]byte, error) { +func (v NullableVariableSetResource) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableEnvironmentResource) UnmarshalJSON(src []byte) error { +func (v *NullableVariableSetResource) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_environment_resource_list.go b/cli/openapi/model_variable_set_resource_list.go similarity index 56% rename from cli/openapi/model_environment_resource_list.go rename to cli/openapi/model_variable_set_resource_list.go index e9d39ed5a1..18eb9f8d6e 100644 --- a/cli/openapi/model_environment_resource_list.go +++ b/cli/openapi/model_variable_set_resource_list.go @@ -14,34 +14,34 @@ import ( "encoding/json" ) -// checks if the EnvironmentResourceList type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &EnvironmentResourceList{} +// checks if the VariableSetResourceList type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &VariableSetResourceList{} -// EnvironmentResourceList struct for EnvironmentResourceList -type EnvironmentResourceList struct { +// VariableSetResourceList struct for VariableSetResourceList +type VariableSetResourceList struct { Count *int32 `json:"count,omitempty"` - Items []EnvironmentResource `json:"items,omitempty"` + Items []VariableSetResource `json:"items,omitempty"` } -// NewEnvironmentResourceList instantiates a new EnvironmentResourceList object +// NewVariableSetResourceList instantiates a new VariableSetResourceList object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewEnvironmentResourceList() *EnvironmentResourceList { - this := EnvironmentResourceList{} +func NewVariableSetResourceList() *VariableSetResourceList { + this := VariableSetResourceList{} return &this } -// NewEnvironmentResourceListWithDefaults instantiates a new EnvironmentResourceList object +// NewVariableSetResourceListWithDefaults instantiates a new VariableSetResourceList object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set -func NewEnvironmentResourceListWithDefaults() *EnvironmentResourceList { - this := EnvironmentResourceList{} +func NewVariableSetResourceListWithDefaults() *VariableSetResourceList { + this := VariableSetResourceList{} return &this } // GetCount returns the Count field value if set, zero value otherwise. -func (o *EnvironmentResourceList) GetCount() int32 { +func (o *VariableSetResourceList) GetCount() int32 { if o == nil || isNil(o.Count) { var ret int32 return ret @@ -51,7 +51,7 @@ func (o *EnvironmentResourceList) GetCount() int32 { // GetCountOk returns a tuple with the Count field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *EnvironmentResourceList) GetCountOk() (*int32, bool) { +func (o *VariableSetResourceList) GetCountOk() (*int32, bool) { if o == nil || isNil(o.Count) { return nil, false } @@ -59,7 +59,7 @@ func (o *EnvironmentResourceList) GetCountOk() (*int32, bool) { } // HasCount returns a boolean if a field has been set. -func (o *EnvironmentResourceList) HasCount() bool { +func (o *VariableSetResourceList) HasCount() bool { if o != nil && !isNil(o.Count) { return true } @@ -68,14 +68,14 @@ func (o *EnvironmentResourceList) HasCount() bool { } // SetCount gets a reference to the given int32 and assigns it to the Count field. -func (o *EnvironmentResourceList) SetCount(v int32) { +func (o *VariableSetResourceList) SetCount(v int32) { o.Count = &v } // GetItems returns the Items field value if set, zero value otherwise. -func (o *EnvironmentResourceList) GetItems() []EnvironmentResource { +func (o *VariableSetResourceList) GetItems() []VariableSetResource { if o == nil || isNil(o.Items) { - var ret []EnvironmentResource + var ret []VariableSetResource return ret } return o.Items @@ -83,7 +83,7 @@ func (o *EnvironmentResourceList) GetItems() []EnvironmentResource { // GetItemsOk returns a tuple with the Items field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *EnvironmentResourceList) GetItemsOk() ([]EnvironmentResource, bool) { +func (o *VariableSetResourceList) GetItemsOk() ([]VariableSetResource, bool) { if o == nil || isNil(o.Items) { return nil, false } @@ -91,7 +91,7 @@ func (o *EnvironmentResourceList) GetItemsOk() ([]EnvironmentResource, bool) { } // HasItems returns a boolean if a field has been set. -func (o *EnvironmentResourceList) HasItems() bool { +func (o *VariableSetResourceList) HasItems() bool { if o != nil && !isNil(o.Items) { return true } @@ -99,12 +99,12 @@ func (o *EnvironmentResourceList) HasItems() bool { return false } -// SetItems gets a reference to the given []EnvironmentResource and assigns it to the Items field. -func (o *EnvironmentResourceList) SetItems(v []EnvironmentResource) { +// SetItems gets a reference to the given []VariableSetResource and assigns it to the Items field. +func (o *VariableSetResourceList) SetItems(v []VariableSetResource) { o.Items = v } -func (o EnvironmentResourceList) MarshalJSON() ([]byte, error) { +func (o VariableSetResourceList) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -112,7 +112,7 @@ func (o EnvironmentResourceList) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o EnvironmentResourceList) ToMap() (map[string]interface{}, error) { +func (o VariableSetResourceList) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Count) { toSerialize["count"] = o.Count @@ -123,38 +123,38 @@ func (o EnvironmentResourceList) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableEnvironmentResourceList struct { - value *EnvironmentResourceList +type NullableVariableSetResourceList struct { + value *VariableSetResourceList isSet bool } -func (v NullableEnvironmentResourceList) Get() *EnvironmentResourceList { +func (v NullableVariableSetResourceList) Get() *VariableSetResourceList { return v.value } -func (v *NullableEnvironmentResourceList) Set(val *EnvironmentResourceList) { +func (v *NullableVariableSetResourceList) Set(val *VariableSetResourceList) { v.value = val v.isSet = true } -func (v NullableEnvironmentResourceList) IsSet() bool { +func (v NullableVariableSetResourceList) IsSet() bool { return v.isSet } -func (v *NullableEnvironmentResourceList) Unset() { +func (v *NullableVariableSetResourceList) Unset() { v.value = nil v.isSet = false } -func NewNullableEnvironmentResourceList(val *EnvironmentResourceList) *NullableEnvironmentResourceList { - return &NullableEnvironmentResourceList{value: val, isSet: true} +func NewNullableVariableSetResourceList(val *VariableSetResourceList) *NullableVariableSetResourceList { + return &NullableVariableSetResourceList{value: val, isSet: true} } -func (v NullableEnvironmentResourceList) MarshalJSON() ([]byte, error) { +func (v NullableVariableSetResourceList) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableEnvironmentResourceList) UnmarshalJSON(src []byte) error { +func (v *NullableVariableSetResourceList) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_environment_value.go b/cli/openapi/model_variable_set_value.go similarity index 61% rename from cli/openapi/model_environment_value.go rename to cli/openapi/model_variable_set_value.go index 085cdebb7b..5d809f5a16 100644 --- a/cli/openapi/model_environment_value.go +++ b/cli/openapi/model_variable_set_value.go @@ -14,34 +14,34 @@ import ( "encoding/json" ) -// checks if the EnvironmentValue type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &EnvironmentValue{} +// checks if the VariableSetValue type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &VariableSetValue{} -// EnvironmentValue struct for EnvironmentValue -type EnvironmentValue struct { +// VariableSetValue struct for VariableSetValue +type VariableSetValue struct { Key *string `json:"key,omitempty"` Value *string `json:"value,omitempty"` } -// NewEnvironmentValue instantiates a new EnvironmentValue object +// NewVariableSetValue instantiates a new VariableSetValue object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed -func NewEnvironmentValue() *EnvironmentValue { - this := EnvironmentValue{} +func NewVariableSetValue() *VariableSetValue { + this := VariableSetValue{} return &this } -// NewEnvironmentValueWithDefaults instantiates a new EnvironmentValue object +// NewVariableSetValueWithDefaults instantiates a new VariableSetValue object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set -func NewEnvironmentValueWithDefaults() *EnvironmentValue { - this := EnvironmentValue{} +func NewVariableSetValueWithDefaults() *VariableSetValue { + this := VariableSetValue{} return &this } // GetKey returns the Key field value if set, zero value otherwise. -func (o *EnvironmentValue) GetKey() string { +func (o *VariableSetValue) GetKey() string { if o == nil || isNil(o.Key) { var ret string return ret @@ -51,7 +51,7 @@ func (o *EnvironmentValue) GetKey() string { // GetKeyOk returns a tuple with the Key field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *EnvironmentValue) GetKeyOk() (*string, bool) { +func (o *VariableSetValue) GetKeyOk() (*string, bool) { if o == nil || isNil(o.Key) { return nil, false } @@ -59,7 +59,7 @@ func (o *EnvironmentValue) GetKeyOk() (*string, bool) { } // HasKey returns a boolean if a field has been set. -func (o *EnvironmentValue) HasKey() bool { +func (o *VariableSetValue) HasKey() bool { if o != nil && !isNil(o.Key) { return true } @@ -68,12 +68,12 @@ func (o *EnvironmentValue) HasKey() bool { } // SetKey gets a reference to the given string and assigns it to the Key field. -func (o *EnvironmentValue) SetKey(v string) { +func (o *VariableSetValue) SetKey(v string) { o.Key = &v } // GetValue returns the Value field value if set, zero value otherwise. -func (o *EnvironmentValue) GetValue() string { +func (o *VariableSetValue) GetValue() string { if o == nil || isNil(o.Value) { var ret string return ret @@ -83,7 +83,7 @@ func (o *EnvironmentValue) GetValue() string { // GetValueOk returns a tuple with the Value field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *EnvironmentValue) GetValueOk() (*string, bool) { +func (o *VariableSetValue) GetValueOk() (*string, bool) { if o == nil || isNil(o.Value) { return nil, false } @@ -91,7 +91,7 @@ func (o *EnvironmentValue) GetValueOk() (*string, bool) { } // HasValue returns a boolean if a field has been set. -func (o *EnvironmentValue) HasValue() bool { +func (o *VariableSetValue) HasValue() bool { if o != nil && !isNil(o.Value) { return true } @@ -100,11 +100,11 @@ func (o *EnvironmentValue) HasValue() bool { } // SetValue gets a reference to the given string and assigns it to the Value field. -func (o *EnvironmentValue) SetValue(v string) { +func (o *VariableSetValue) SetValue(v string) { o.Value = &v } -func (o EnvironmentValue) MarshalJSON() ([]byte, error) { +func (o VariableSetValue) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -112,7 +112,7 @@ func (o EnvironmentValue) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o EnvironmentValue) ToMap() (map[string]interface{}, error) { +func (o VariableSetValue) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Key) { toSerialize["key"] = o.Key @@ -123,38 +123,38 @@ func (o EnvironmentValue) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableEnvironmentValue struct { - value *EnvironmentValue +type NullableVariableSetValue struct { + value *VariableSetValue isSet bool } -func (v NullableEnvironmentValue) Get() *EnvironmentValue { +func (v NullableVariableSetValue) Get() *VariableSetValue { return v.value } -func (v *NullableEnvironmentValue) Set(val *EnvironmentValue) { +func (v *NullableVariableSetValue) Set(val *VariableSetValue) { v.value = val v.isSet = true } -func (v NullableEnvironmentValue) IsSet() bool { +func (v NullableVariableSetValue) IsSet() bool { return v.isSet } -func (v *NullableEnvironmentValue) Unset() { +func (v *NullableVariableSetValue) Unset() { v.value = nil v.isSet = false } -func NewNullableEnvironmentValue(val *EnvironmentValue) *NullableEnvironmentValue { - return &NullableEnvironmentValue{value: val, isSet: true} +func NewNullableVariableSetValue(val *VariableSetValue) *NullableVariableSetValue { + return &NullableVariableSetValue{value: val, isSet: true} } -func (v NullableEnvironmentValue) MarshalJSON() ([]byte, error) { +func (v NullableVariableSetValue) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableEnvironmentValue) UnmarshalJSON(src []byte) error { +func (v *NullableVariableSetValue) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/pkg/resourcemanager/apply.go b/cli/pkg/resourcemanager/apply.go index 837d9dd8c5..f4aa027981 100644 --- a/cli/pkg/resourcemanager/apply.go +++ b/cli/pkg/resourcemanager/apply.go @@ -39,7 +39,7 @@ func (c Client) validType(inputFile fileutil.File) error { } c.logger.Debug("Parsed type", zap.String("type", t)) - if t != c.resourceType() { + if t != c.resourceType() && t != c.options.deprecatedAlias { return fmt.Errorf("cannot apply %s to %s resource", t, c.resourceType()) } diff --git a/cli/pkg/resourcemanager/client.go b/cli/pkg/resourcemanager/client.go index 31b60390f2..13fbeb7752 100644 --- a/cli/pkg/resourcemanager/client.go +++ b/cli/pkg/resourcemanager/client.go @@ -86,6 +86,7 @@ func (c Client) resourceType() string { if c.options.resourceType != "" { return c.options.resourceType } + // language.Und means Undefined caser := cases.Title(language.Und, cases.NoLower) return caser.String(c.resourceName) diff --git a/cli/pkg/resourcemanager/options.go b/cli/pkg/resourcemanager/options.go index 6984621992..2eb0b3daf2 100644 --- a/cli/pkg/resourcemanager/options.go +++ b/cli/pkg/resourcemanager/options.go @@ -5,6 +5,8 @@ type options struct { tableConfig TableConfig deleteSuccessMsg string resourceType string + deprecatedAlias string + proxyResource string } type option func(*options) @@ -32,3 +34,15 @@ func WithResourceType(resourceType string) option { o.resourceType = resourceType } } + +func WithDeprecatedAlias(resourceType string) option { + return func(o *options) { + o.deprecatedAlias = resourceType + } +} + +func WithProxyResource(proxyResource string) option { + return func(o *options) { + o.proxyResource = proxyResource + } +} diff --git a/cli/pkg/resourcemanager/registry.go b/cli/pkg/resourcemanager/registry.go index ad89cc02d8..5286b3385c 100644 --- a/cli/pkg/resourcemanager/registry.go +++ b/cli/pkg/resourcemanager/registry.go @@ -2,6 +2,7 @@ package resourcemanager import ( "errors" + "fmt" "sort" "github.com/agnivade/levenshtein" @@ -30,13 +31,33 @@ func (r *Registry) Get(resourceName string) (Client, error) { return Client{}, ErrResourceNotFound } + if c.options.proxyResource != "" { + c.logger.Warn(fmt.Sprintf("The resource `%s` is deprecated and will be removed in a future version. Please use `%s` instead.", c.resourceName, c.options.proxyResource)) + return r.Get(c.options.proxyResource) + } + return c, nil } +func (r *Registry) Exists(resourceName string) bool { + c, ok := r.resources[resourceName] + if !ok { + return false + } + + if c.options.proxyResource != "" { + return r.Exists(c.options.proxyResource) + } + + return true +} + func (r *Registry) List() []string { var resources []string - for k := range r.resources { - resources = append(resources, k) + for k, c := range r.resources { + if c.options.proxyResource == "" { + resources = append(resources, k) + } } sort.Strings(resources) diff --git a/cli/preprocessor/variableset.go b/cli/preprocessor/variableset.go new file mode 100644 index 0000000000..8d0a6959a6 --- /dev/null +++ b/cli/preprocessor/variableset.go @@ -0,0 +1,46 @@ +package preprocessor + +import ( + "context" + "fmt" + + "github.com/goccy/go-yaml" + "github.com/kubeshop/tracetest/cli/pkg/fileutil" + "go.uber.org/zap" +) + +type variableSet struct { + logger *zap.Logger +} + +type generic struct { + Type string `yaml:"type"` + Spec interface{} `yaml:"spec"` +} + +func VariableSet(logger *zap.Logger) variableSet { + return variableSet{ + logger: logger, + } +} + +func (vs variableSet) Preprocess(ctx context.Context, input fileutil.File) (fileutil.File, error) { + var resource generic + err := yaml.Unmarshal(input.Contents(), &resource) + if err != nil { + vs.logger.Error("error parsing test", zap.String("content", string(input.Contents())), zap.Error(err)) + return input, fmt.Errorf("could not unmarshal test yaml: %w", err) + } + + // TODO: This should be removed at some point as the Environment type is deprecated + if resource.Type == "Environment" { + resource.Type = "VariableSet" + } + + marshalled, err := yaml.Marshal(resource) + if err != nil { + return input, fmt.Errorf("could not marshal test yaml: %w", err) + } + + return fileutil.New(input.AbsPath(), marshalled), nil +} diff --git a/cli/runner/orchestrator.go b/cli/runner/orchestrator.go index 30915263c3..b3c0661a6a 100644 --- a/cli/runner/orchestrator.go +++ b/cli/runner/orchestrator.go @@ -30,8 +30,8 @@ type RunOptions struct { // the file will be applied before running DefinitionFile string - // environmentID or path to the file with environment definition - EnvID string + // varsID or path to the file with environment definition + VarsID string // By default the runner will wait for the result of the run // if this option is true, the wait will be skipped @@ -89,12 +89,12 @@ type Runner interface { func Orchestrator( logger *zap.Logger, openapiClient *openapi.APIClient, - environments resourcemanager.Client, + variableSets resourcemanager.Client, ) orchestrator { return orchestrator{ logger: logger, openapiClient: openapiClient, - environments: environments, + variableSets: variableSets, } } @@ -102,7 +102,7 @@ type orchestrator struct { logger *zap.Logger openapiClient *openapi.APIClient - environments resourcemanager.Client + variableSets resourcemanager.Client } var ( @@ -122,17 +122,17 @@ func (o orchestrator) Run(ctx context.Context, r Runner, opts RunOptions, output "Running test from definition", zap.String("definitionFile", opts.DefinitionFile), zap.String("ID", opts.ID), - zap.String("envID", opts.EnvID), + zap.String("varSetID", opts.VarsID), zap.Bool("skipResultsWait", opts.SkipResultWait), zap.String("junitOutputFile", opts.JUnitOuptutFile), zap.Strings("requiredGates", opts.RequiredGates), ) - envID, err := o.resolveEnvID(ctx, opts.EnvID) + varsID, err := o.resolveVarsID(ctx, opts.VarsID) if err != nil { - return ExitCodeGeneralError, fmt.Errorf("cannot resolve environment id: %w", err) + return ExitCodeGeneralError, fmt.Errorf("cannot resolve variable set id: %w", err) } - o.logger.Debug("env resolved", zap.String("ID", envID)) + o.logger.Debug("env resolved", zap.String("ID", varsID)) var resource any if opts.DefinitionFile != "" { @@ -163,13 +163,13 @@ func (o orchestrator) Run(ctx context.Context, r Runner, opts RunOptions, output } var result RunResult - var ev envVars + var ev varSets // iterate until we have all env vars, // or the server returns an actual error for { runInfo := openapi.RunInformation{ - EnvironmentId: &envID, + VariableSetId: &varsID, Variables: ev.toOpenapi(), Metadata: getMetadata(), RequiredGates: getRequiredGates(opts.RequiredGates), @@ -179,13 +179,13 @@ func (o orchestrator) Run(ctx context.Context, r Runner, opts RunOptions, output if err == nil { break } - if !errors.Is(err, missingEnvVarsError{}) { + if !errors.Is(err, missingVarsError{}) { // actual error, return return ExitCodeGeneralError, fmt.Errorf("cannot run test: %w", err) } // missing vars error - ev = askForMissingVars([]envVar(err.(missingEnvVarsError))) + ev = askForMissingVars([]varSet(err.(missingVarsError))) o.logger.Debug("filled variables", zap.Any("variables", ev)) } @@ -214,43 +214,43 @@ func (o orchestrator) Run(ctx context.Context, r Runner, opts RunOptions, output return exitCode, nil } -func (o orchestrator) resolveEnvID(ctx context.Context, envID string) (string, error) { - if !fileutil.IsFilePath(envID) { - o.logger.Debug("envID is not a file path", zap.String("envID", envID)) +func (o orchestrator) resolveVarsID(ctx context.Context, varsID string) (string, error) { + if !fileutil.IsFilePath(varsID) { + o.logger.Debug("varsID is not a file path", zap.String("vars", varsID)) // validate that env exists - _, err := o.environments.Get(ctx, envID, resourcemanager.Formats.Get(resourcemanager.FormatYAML)) + _, err := o.variableSets.Get(ctx, varsID, resourcemanager.Formats.Get(resourcemanager.FormatYAML)) if errors.Is(err, resourcemanager.ErrNotFound) { - return "", fmt.Errorf("environment '%s' not found", envID) + return "", fmt.Errorf("variable set '%s' not found", varsID) } if err != nil { - return "", fmt.Errorf("cannot get environment '%s': %w", envID, err) + return "", fmt.Errorf("cannot get variable set '%s': %w", varsID, err) } o.logger.Debug("envID is valid") - return envID, nil + return varsID, nil } - f, err := fileutil.Read(envID) + f, err := fileutil.Read(varsID) if err != nil { - return "", fmt.Errorf("cannot read environment file %s: %w", envID, err) + return "", fmt.Errorf("cannot read environment set file %s: %w", varsID, err) } - o.logger.Debug("envID is a file path", zap.String("filePath", envID), zap.Any("file", f)) - updatedEnv, err := o.environments.Apply(ctx, f, yamlFormat) + o.logger.Debug("envID is a file path", zap.String("filePath", varsID), zap.Any("file", f)) + updatedEnv, err := o.variableSets.Apply(ctx, f, yamlFormat) if err != nil { - return "", fmt.Errorf("could not read environment file: %w", err) + return "", fmt.Errorf("could not read environment set file: %w", err) } - var env openapi.EnvironmentResource - err = yaml.Unmarshal([]byte(updatedEnv), &env) + var vars openapi.VariableSetResource + err = yaml.Unmarshal([]byte(updatedEnv), &vars) if err != nil { o.logger.Error("error parsing json", zap.String("content", updatedEnv), zap.Error(err)) - return "", fmt.Errorf("could not unmarshal environment json: %w", err) + return "", fmt.Errorf("could not unmarshal variable set json: %w", err) } - return env.Spec.GetId(), nil + return vars.Spec.GetId(), nil } func (o orchestrator) injectLocalEnvVars(ctx context.Context, df fileutil.File) (fileutil.File, error) { @@ -260,7 +260,7 @@ func (o orchestrator) injectLocalEnvVars(ctx context.Context, df fileutil.File) injected, err := variableInjector.ReplaceInString(string(df.Contents())) if err != nil { - return df, fmt.Errorf("cannot inject local environment variables: %w", err) + return df, fmt.Errorf("cannot inject local variable set: %w", err) } df = fileutil.New(df.AbsPath(), []byte(injected)) @@ -382,7 +382,7 @@ func HandleRunError(resp *http.Response, reqErr error) error { } if resp.StatusCode == http.StatusUnprocessableEntity { - return buildMissingEnvVarsError(body) + return buildMissingVarsError(body) } if reqErr != nil { diff --git a/cli/runner/env_vars.go b/cli/runner/var_set.go similarity index 62% rename from cli/runner/env_vars.go rename to cli/runner/var_set.go index f75c15d789..ddd267df41 100644 --- a/cli/runner/env_vars.go +++ b/cli/runner/var_set.go @@ -7,11 +7,11 @@ import ( "github.com/kubeshop/tracetest/cli/ui" ) -func askForMissingVars(missingVars []envVar) []envVar { +func askForMissingVars(missingVars []varSet) []varSet { ui.DefaultUI.Warning("Some variables are required by one or more tests") ui.DefaultUI.Info("Fill the values for each variable:") - filledVariables := make([]envVar, 0, len(missingVars)) + filledVariables := make([]varSet, 0, len(missingVars)) for _, missingVar := range missingVars { answer := missingVar @@ -22,13 +22,13 @@ func askForMissingVars(missingVars []envVar) []envVar { return filledVariables } -type envVar struct { +type varSet struct { Name string DefaultValue string UserValue string } -func (ev envVar) value() string { +func (ev varSet) value() string { if ev.UserValue != "" { return ev.UserValue } @@ -36,12 +36,12 @@ func (ev envVar) value() string { return ev.DefaultValue } -type envVars []envVar +type varSets []varSet -func (evs envVars) toOpenapi() []openapi.EnvironmentValue { - vars := make([]openapi.EnvironmentValue, len(evs)) +func (evs varSets) toOpenapi() []openapi.VariableSetValue { + vars := make([]openapi.VariableSetValue, len(evs)) for i, ev := range evs { - vars[i] = openapi.EnvironmentValue{ + vars[i] = openapi.VariableSetValue{ Key: openapi.PtrString(ev.Name), Value: openapi.PtrString(ev.value()), } @@ -50,9 +50,9 @@ func (evs envVars) toOpenapi() []openapi.EnvironmentValue { return vars } -func (evs envVars) unique() envVars { +func (evs varSets) unique() varSets { seen := make(map[string]bool) - vars := make(envVars, 0, len(evs)) + vars := make(varSets, 0, len(evs)) for _, ev := range evs { if seen[ev.Name] { continue @@ -65,34 +65,34 @@ func (evs envVars) unique() envVars { return vars } -type missingEnvVarsError envVars +type missingVarsError varSets -func (e missingEnvVarsError) Error() string { - return fmt.Sprintf("missing env vars: %v", []envVar(e)) +func (e missingVarsError) Error() string { + return fmt.Sprintf("missing variables: %v", []varSet(e)) } -func (e missingEnvVarsError) Is(target error) bool { - _, ok := target.(missingEnvVarsError) +func (e missingVarsError) Is(target error) bool { + _, ok := target.(missingVarsError) return ok } -func buildMissingEnvVarsError(body []byte) error { +func buildMissingVarsError(body []byte) error { var missingVarsErrResp openapi.MissingVariablesError err := jsonFormat.Unmarshal(body, &missingVarsErrResp) if err != nil { return fmt.Errorf("could not unmarshal response body: %w", err) } - missingVars := envVars{} + missingVars := varSets{} for _, missingVarErr := range missingVarsErrResp.MissingVariables { for _, missingVar := range missingVarErr.Variables { - missingVars = append(missingVars, envVar{ + missingVars = append(missingVars, varSet{ Name: missingVar.GetKey(), DefaultValue: missingVar.GetDefaultValue(), }) } } - return missingEnvVarsError(missingVars.unique()) + return missingVarsError(missingVars.unique()) } diff --git a/examples/table-driven-test/table-test.bash b/examples/table-driven-test/table-test.bash index df99e645c7..b73d4cb5d7 100755 --- a/examples/table-driven-test/table-test.bash +++ b/examples/table-driven-test/table-test.bash @@ -27,7 +27,7 @@ while IFS=, read -ra fields; do # create the env file cat < "$envFile" -type: Environment +type: VariableSet spec: name: ${environmentID} values: @@ -43,8 +43,8 @@ EOF # run test echo "Running test" - $TRACETEST apply environment --file "${envFile}" > /dev/null - $TRACETEST run test --file "${TEST_DEFINITION}" --environment "${envFile}" + $TRACETEST apply variableset --file "${envFile}" > /dev/null + $TRACETEST run test --file "${TEST_DEFINITION}" --vars "${envFile}" ((line=line+1)) diff --git a/server/app/app.go b/server/app/app.go index b811cd6d9e..93fc542dc3 100644 --- a/server/app/app.go +++ b/server/app/app.go @@ -16,7 +16,6 @@ import ( "github.com/kubeshop/tracetest/server/config" "github.com/kubeshop/tracetest/server/config/demo" "github.com/kubeshop/tracetest/server/datastore" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor" "github.com/kubeshop/tracetest/server/executor/pollingprofile" "github.com/kubeshop/tracetest/server/executor/testrunner" @@ -38,6 +37,7 @@ import ( "github.com/kubeshop/tracetest/server/traces" "github.com/kubeshop/tracetest/server/tracing" "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -196,7 +196,7 @@ func (app *App) Start(opts ...appOption) error { demoRepo := demo.NewRepository(db) pollingProfileRepo := pollingprofile.NewRepository(db) dataStoreRepo := datastore.NewRepository(db) - environmentRepo := environment.NewRepository(db) + variableSetRepo := variableset.NewRepository(db) linterRepo := analyzer.NewRepository(db) testRepo := test.NewRepository(db) runRepo := test.NewRunRepository(db) @@ -255,7 +255,7 @@ func (app *App) Start(opts ...appOption) error { transactionRunRepository, testRepo, runRepo, - environmentRepo, + variableSetRepo, ) registerWSHandler(router, mappers, subscriptionManager) @@ -273,7 +273,7 @@ func (app *App) Start(opts ...appOption) error { registerTransactionResource(transactionsRepository, apiRouter, provisioner, tracer) registerConfigResource(configRepo, apiRouter, provisioner, tracer) registerPollingProfilesResource(pollingProfileRepo, apiRouter, provisioner, tracer) - registerEnvironmentResource(environmentRepo, apiRouter, provisioner, tracer) + registerVariableSetResource(variableSetRepo, apiRouter, provisioner, tracer) registerDemosResource(demoRepo, apiRouter, provisioner, tracer) registerDataStoreResource(dataStoreRepo, apiRouter, provisioner, tracer) registerAnalyzer(linterRepo, apiRouter, provisioner, tracer) @@ -426,10 +426,10 @@ func registerPollingProfilesResource(repository *pollingprofile.Repository, rout provisioner.AddResourceProvisioner(manager) } -func registerEnvironmentResource(repository *environment.Repository, router *mux.Router, provisioner *provisioning.Provisioner, tracer trace.Tracer) { - manager := resourcemanager.New[environment.Environment]( - environment.ResourceName, - environment.ResourceNamePlural, +func registerVariableSetResource(repository *variableset.Repository, router *mux.Router, provisioner *provisioning.Provisioner, tracer trace.Tracer) { + manager := resourcemanager.New[variableset.VariableSet]( + variableset.ResourceName, + variableset.ResourceNamePlural, repository, resourcemanager.WithTracer(tracer), ) @@ -509,7 +509,7 @@ func controller( transactionRunRepo *transaction.RunRepository, testRepo test.Repository, testRunRepo test.RunRepository, - environmentRepo *environment.Repository, + variablesetRepo *variableset.Repository, ) (*mux.Router, mappings.Mappings) { mappers := mappings.New(tracesConversionConfig(), comparator.DefaultRegistry()) @@ -526,7 +526,7 @@ func controller( transactionRunRepo, testRepo, testRunRepo, - environmentRepo, + variablesetRepo, mappers, )) @@ -547,7 +547,7 @@ func httpRouter( transactionRunRepo *transaction.RunRepository, testRepo test.Repository, testRunRepo test.RunRepository, - environmentRepo *environment.Repository, + variableSetRepo *variableset.Repository, mappers mappings.Mappings, ) openapi.Router { @@ -562,7 +562,7 @@ func httpRouter( transactionRunRepo, testRepo, testRunRepo, - environmentRepo, + variableSetRepo, tracedb.Factory(testRunRepo), mappers, diff --git a/server/environment/resource.go b/server/environment/resource.go deleted file mode 100644 index 3ece1b34b8..0000000000 --- a/server/environment/resource.go +++ /dev/null @@ -1,6 +0,0 @@ -package environment - -const ( - ResourceName = "Environment" - ResourceNamePlural = "Environments" -) diff --git a/server/executor/assertion_runner.go b/server/executor/assertion_runner.go index 59fb62aef1..257dd77691 100644 --- a/server/executor/assertion_runner.go +++ b/server/executor/assertion_runner.go @@ -7,12 +7,12 @@ import ( "log" "github.com/kubeshop/tracetest/server/analytics" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/expression" "github.com/kubeshop/tracetest/server/model/events" "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/test" + "github.com/kubeshop/tracetest/server/variableset" ) type defaultAssertionRunner struct { @@ -112,7 +112,7 @@ func (e *defaultAssertionRunner) executeAssertions(ctx context.Context, req Job) } ds := []expression.DataStore{expression.EnvironmentDataStore{ - Values: req.Run.Environment.Values, + Values: req.Run.VariableSet.Values, }} outputs, err := e.outputsProcessor(ctx, req.Test.Outputs, *run.Trace, ds) @@ -121,9 +121,9 @@ func (e *defaultAssertionRunner) executeAssertions(ctx context.Context, req Job) } e.validateOutputResolution(ctx, req, outputs) - newEnvironment := createEnvironment(req.Run.Environment, outputs) + newVariableSet := createVariableSet(req.Run.VariableSet, outputs) - ds = []expression.DataStore{expression.EnvironmentDataStore{Values: newEnvironment.Values}} + ds = []expression.DataStore{expression.EnvironmentDataStore{Values: newVariableSet.Values}} assertionResult, allPassed := e.assertionExecutor.Assert(ctx, req.Test.Specs, *run.Trace, ds) @@ -131,7 +131,7 @@ func (e *defaultAssertionRunner) executeAssertions(ctx context.Context, req Job) run = run.SuccessfullyAsserted( outputs, - newEnvironment, + newVariableSet, assertionResult, allPassed, ) @@ -174,10 +174,10 @@ func (e *defaultAssertionRunner) emitFailedAssertions(ctx context.Context, req J } } -func createEnvironment(env environment.Environment, outputs maps.Ordered[string, test.RunOutput]) environment.Environment { - outputVariables := make([]environment.EnvironmentValue, 0) +func createVariableSet(env variableset.VariableSet, outputs maps.Ordered[string, test.RunOutput]) variableset.VariableSet { + outputVariables := make([]variableset.VariableSetValue, 0) outputs.ForEach(func(key string, val test.RunOutput) error { - outputVariables = append(outputVariables, environment.EnvironmentValue{ + outputVariables = append(outputVariables, variableset.VariableSetValue{ Key: val.Name, Value: val.Value, }) @@ -185,7 +185,7 @@ func createEnvironment(env environment.Environment, outputs maps.Ordered[string, return nil }) - outputEnv := environment.Environment{Values: outputVariables} + outputEnv := variableset.VariableSet{Values: outputVariables} return env.Merge(outputEnv) } diff --git a/server/executor/runner.go b/server/executor/runner.go index 05e73e2199..528588ba42 100644 --- a/server/executor/runner.go +++ b/server/executor/runner.go @@ -121,7 +121,7 @@ func (r persistentRunner) ProcessItem(ctx context.Context, job Job) { r.handleDBError(run, r.updater.Update(ctx, run)) ds := []expression.DataStore{expression.EnvironmentDataStore{ - Values: run.Environment.Values, + Values: run.VariableSet.Values, }} executor := expression.NewExecutor(ds...) diff --git a/server/executor/runner_test.go b/server/executor/runner_test.go index e78014986e..08291a7331 100644 --- a/server/executor/runner_test.go +++ b/server/executor/runner_test.go @@ -8,7 +8,6 @@ import ( "github.com/kubeshop/tracetest/server/config" "github.com/kubeshop/tracetest/server/datastore" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor" "github.com/kubeshop/tracetest/server/executor/pollingprofile" "github.com/kubeshop/tracetest/server/executor/testrunner" @@ -20,6 +19,7 @@ import ( "github.com/kubeshop/tracetest/server/testdb" "github.com/kubeshop/tracetest/server/tracedb" "github.com/kubeshop/tracetest/server/tracing" + "github.com/kubeshop/tracetest/server/variableset" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -107,7 +107,7 @@ func (f runnerFixture) run(tests []test.Test, ttl time.Duration) { f.runner.Start() time.Sleep(10 * time.Millisecond) for _, testObj := range tests { - newRun := f.runner.Run(context.TODO(), testObj, test.RunMetadata{}, environment.Environment{}, nil) + newRun := f.runner.Run(context.TODO(), testObj, test.RunMetadata{}, variableset.VariableSet{}, nil) // readd this when using not-in-memory queues // f.runsMock. // On("GetRun", testObj.ID, newRun.ID). diff --git a/server/executor/test_pipeline.go b/server/executor/test_pipeline.go index 6e105af529..893b58b7b8 100644 --- a/server/executor/test_pipeline.go +++ b/server/executor/test_pipeline.go @@ -5,13 +5,13 @@ import ( "fmt" "log" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/pollingprofile" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/model/events" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/test" + "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -65,10 +65,10 @@ func NewTestPipeline( } } -func (p *TestPipeline) Run(ctx context.Context, testObj test.Test, metadata test.RunMetadata, environment environment.Environment, requiredGates *[]testrunner.RequiredGate) test.Run { +func (p *TestPipeline) Run(ctx context.Context, testObj test.Test, metadata test.RunMetadata, variableSet variableset.VariableSet, requiredGates *[]testrunner.RequiredGate) test.Run { run := test.NewRun() run.Metadata = metadata - run.Environment = environment + run.VariableSet = variableSet // configuring required gates if requiredGates == nil { diff --git a/server/executor/transaction_pipeline.go b/server/executor/transaction_pipeline.go index 323a39112b..4c0c342a0f 100644 --- a/server/executor/transaction_pipeline.go +++ b/server/executor/transaction_pipeline.go @@ -3,10 +3,10 @@ package executor import ( "context" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/variableset" ) type TransactionPipeline struct { @@ -28,10 +28,10 @@ func NewTransactionPipeline( } } -func (p *TransactionPipeline) Run(ctx context.Context, tran transaction.Transaction, metadata test.RunMetadata, environment environment.Environment, requiredGates *[]testrunner.RequiredGate) transaction.TransactionRun { +func (p *TransactionPipeline) Run(ctx context.Context, tran transaction.Transaction, metadata test.RunMetadata, variableSet variableset.VariableSet, requiredGates *[]testrunner.RequiredGate) transaction.TransactionRun { tranRun := tran.NewRun() tranRun.Metadata = metadata - tranRun.Environment = environment + tranRun.VariableSet = variableSet tranRun.RequiredGates = requiredGates tranRun, _ = p.runs.CreateRun(ctx, tranRun) diff --git a/server/executor/transaction_runner.go b/server/executor/transaction_runner.go index f595f66330..e9bea0cf09 100644 --- a/server/executor/transaction_runner.go +++ b/server/executor/transaction_runner.go @@ -5,12 +5,12 @@ import ( "fmt" "log" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/variableset" ) type transactionRunRepository interface { @@ -19,7 +19,7 @@ type transactionRunRepository interface { } type testRunner interface { - Run(context.Context, test.Test, test.RunMetadata, environment.Environment, *[]testrunner.RequiredGate) test.Run + Run(context.Context, test.Test, test.RunMetadata, variableset.VariableSet, *[]testrunner.RequiredGate) test.Run } func NewTransactionRunner( @@ -73,7 +73,7 @@ func (r persistentTransactionRunner) ProcessItem(ctx context.Context, job Job) { break } - run.Environment = mergeOutputsIntoEnv(run.Environment, run.Steps[step].Outputs) + run.VariableSet = mergeOutputsIntoEnv(run.VariableSet, run.Steps[step].Outputs) err = r.transactionRuns.UpdateRun(ctx, run) if err != nil { log.Printf("[TransactionRunner] could not update transaction step: %s", err.Error()) @@ -93,7 +93,7 @@ func (r persistentTransactionRunner) ProcessItem(ctx context.Context, job Job) { } func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr transaction.TransactionRun, step int, testObj test.Test) (transaction.TransactionRun, error) { - testRun := r.testRunner.Run(ctx, testObj, tr.Metadata, tr.Environment, tr.RequiredGates) + testRun := r.testRunner.Run(ctx, testObj, tr.Metadata, tr.VariableSet, tr.RequiredGates) tr, err := r.updateStepRun(ctx, tr, step, testRun) if err != nil { return transaction.TransactionRun{}, fmt.Errorf("could not update transaction run: %w", err) @@ -148,10 +148,10 @@ func (r persistentTransactionRunner) updateStepRun(ctx context.Context, tr trans return tr, nil } -func mergeOutputsIntoEnv(env environment.Environment, outputs maps.Ordered[string, test.RunOutput]) environment.Environment { - newEnv := make([]environment.EnvironmentValue, 0, outputs.Len()) +func mergeOutputsIntoEnv(variableSet variableset.VariableSet, outputs maps.Ordered[string, test.RunOutput]) variableset.VariableSet { + newEnv := make([]variableset.VariableSetValue, 0, outputs.Len()) outputs.ForEach(func(key string, val test.RunOutput) error { - newEnv = append(newEnv, environment.EnvironmentValue{ + newEnv = append(newEnv, variableset.VariableSetValue{ Key: key, Value: val.Value, }) @@ -159,7 +159,7 @@ func mergeOutputsIntoEnv(env environment.Environment, outputs maps.Ordered[strin return nil }) - return env.Merge(environment.Environment{ + return variableSet.Merge(variableset.VariableSet{ Values: newEnv, }) } diff --git a/server/executor/transaction_runner_test.go b/server/executor/transaction_runner_test.go index 516805cc2d..118b88389b 100644 --- a/server/executor/transaction_runner_test.go +++ b/server/executor/transaction_runner_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/model" @@ -18,6 +17,7 @@ import ( "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/testmock" "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/variableset" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -29,9 +29,9 @@ type fakeTestRunner struct { uid int } -func (r *fakeTestRunner) Run(ctx context.Context, testObj test.Test, metadata test.RunMetadata, env environment.Environment, requiredGates *[]testrunner.RequiredGate) test.Run { +func (r *fakeTestRunner) Run(ctx context.Context, testObj test.Test, metadata test.RunMetadata, variableSet variableset.VariableSet, requiredGates *[]testrunner.RequiredGate) test.Run { run := test.NewRun() - run.Environment = env + run.VariableSet = variableSet run.State = test.RunStateCreated newRun, err := r.db.CreateRun(ctx, testObj, run) if err != nil { @@ -74,7 +74,7 @@ func TestTransactionRunner(t *testing.T) { require.Len(t, actual.Steps, 2) assert.Equal(t, actual.Steps[0].State, test.RunStateFinished) assert.Equal(t, actual.Steps[1].State, test.RunStateFinished) - assert.Equal(t, "http://my-service.com", actual.Environment.Get("url")) + assert.Equal(t, "http://my-service.com", actual.VariableSet.Get("url")) assert.Equal(t, test.RunOutput{Name: "", Value: "1", SpanID: ""}, actual.Steps[0].Outputs.Get("USER_ID")) @@ -83,10 +83,10 @@ func TestTransactionRunner(t *testing.T) { // on the `fakeTestRunner` used here to actually save the environment // to the test run, like the real test runner would. // see line 27 - assert.Equal(t, "1", actual.Steps[1].Environment.Get("USER_ID")) + assert.Equal(t, "1", actual.Steps[1].VariableSet.Get("USER_ID")) assert.Equal(t, test.RunOutput{Name: "", Value: "2", SpanID: ""}, actual.Steps[1].Outputs.Get("USER_ID")) - assert.Equal(t, "2", actual.Environment.Get("USER_ID")) + assert.Equal(t, "2", actual.VariableSet.Get("USER_ID")) }) }) @@ -146,10 +146,10 @@ func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *test "service": "tracetest", } - envRepository := environment.NewRepository(rawDB) - env, err := envRepository.Create(ctx, environment.Environment{ + envRepository := variableset.NewRepository(rawDB) + env, err := envRepository.Create(ctx, variableset.VariableSet{ Name: "production", - Values: []environment.EnvironmentValue{ + Values: []variableset.VariableSetValue{ { Key: "url", Value: "http://my-service.com", diff --git a/server/expression/data_store.go b/server/expression/data_store.go index 517ac81ea7..89dc5e55bd 100644 --- a/server/expression/data_store.go +++ b/server/expression/data_store.go @@ -4,8 +4,8 @@ import ( "fmt" "strconv" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/model" + "github.com/kubeshop/tracetest/server/variableset" ) type DataStore interface { @@ -85,7 +85,7 @@ func (ds VariableDataStore) Get(name string) (string, error) { } type EnvironmentDataStore struct { - Values []environment.EnvironmentValue + Values []variableset.VariableSetValue } func (ds EnvironmentDataStore) Source() string { diff --git a/server/expression/executor_test.go b/server/expression/executor_test.go index 66c5ac27ad..d3c5535e06 100644 --- a/server/expression/executor_test.go +++ b/server/expression/executor_test.go @@ -6,9 +6,9 @@ import ( "strings" "testing" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/expression" "github.com/kubeshop/tracetest/server/model" + "github.com/kubeshop/tracetest/server/variableset" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -438,7 +438,7 @@ func TestFailureCases(t *testing.T) { ExpectedErrorMessage: `resolution error: environment variable "test" not found`, EnvironmentDataStore: expression.EnvironmentDataStore{ - Values: []environment.EnvironmentValue{}, + Values: []variableset.VariableSetValue{}, }, }, { @@ -469,7 +469,7 @@ func TestFailureCases(t *testing.T) { ExpectedErrorMessage: `resolution error: at index 1 of array: environment variable "test" not found`, EnvironmentDataStore: expression.EnvironmentDataStore{ - Values: []environment.EnvironmentValue{}, + Values: []variableset.VariableSetValue{}, }, }, } diff --git a/server/http/controller.go b/server/http/controller.go index 71a9d7b0e9..5fa1bc6f3f 100644 --- a/server/http/controller.go +++ b/server/http/controller.go @@ -11,7 +11,6 @@ import ( "github.com/kubeshop/tracetest/server/assertions/selectors" "github.com/kubeshop/tracetest/server/datastore" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/expression" @@ -24,6 +23,7 @@ import ( "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/tracedb" "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -39,7 +39,7 @@ type controller struct { transactionRepository transactionsRepository transactionRunRepository transactionRunRepository - environmentGetter environmentGetter + variableSetGetter variableSetGetter newTraceDBFn func(ds datastore.DataStore) (tracedb.TraceDB, error) mappers mappings.Mappings version string @@ -69,16 +69,16 @@ type transactionRunRepository interface { type testRunner interface { StopTest(_ context.Context, testID id.ID, runID int) - Run(context.Context, test.Test, test.RunMetadata, environment.Environment, *[]testrunner.RequiredGate) test.Run + Run(context.Context, test.Test, test.RunMetadata, variableset.VariableSet, *[]testrunner.RequiredGate) test.Run Rerun(_ context.Context, _ test.Test, runID int) test.Run } type transactionRunner interface { - Run(context.Context, transaction.Transaction, test.RunMetadata, environment.Environment, *[]testrunner.RequiredGate) transaction.TransactionRun + Run(context.Context, transaction.Transaction, test.RunMetadata, variableset.VariableSet, *[]testrunner.RequiredGate) transaction.TransactionRun } -type environmentGetter interface { - Get(context.Context, id.ID) (environment.Environment, error) +type variableSetGetter interface { + Get(context.Context, id.ID) (variableset.VariableSet, error) } func NewController( @@ -92,7 +92,7 @@ func NewController( transactionRunRepository transactionRunRepository, testRepository testsRepository, testRunRepository test.RunRepository, - environmentGetter environmentGetter, + variableSetGetter variableSetGetter, newTraceDBFn func(ds datastore.DataStore) (tracedb.TraceDB, error), mappers mappings.Mappings, @@ -104,7 +104,7 @@ func NewController( transactionRunRepository: transactionRunRepository, testRepository: testRepository, testRunRepository: testRunRepository, - environmentGetter: environmentGetter, + variableSetGetter: variableSetGetter, testRunner: testRunner, transactionRunner: transactionRunner, @@ -240,11 +240,11 @@ func (c *controller) RunTest(ctx context.Context, testID string, runInfo openapi return handleDBError(err), err } - variablesEnv := c.mappers.In.Environment(openapi.Environment{ + variablesEnv := c.mappers.In.VariableSet(openapi.VariableSet{ Values: runInfo.Variables, }) - environment, err := c.getEnvironment(ctx, runInfo.EnvironmentId, variablesEnv) + environment, err := c.getVariableSet(ctx, runInfo.VariableSetId, variablesEnv) if err != nil { return handleDBError(err), err } @@ -284,7 +284,7 @@ func (c *controller) DryRunAssertion(ctx context.Context, testID string, runID i definition := c.mappers.In.Definition(def.Specs) ds := []expression.DataStore{expression.EnvironmentDataStore{ - Values: run.Environment.Values, + Values: run.VariableSet.Values, }} assertionExecutor := executor.NewAssertionExecutor(c.tracer) @@ -389,12 +389,12 @@ func metadata(in *map[string]string) test.RunMetadata { return test.RunMetadata(*in) } -func (c *controller) getEnvironment(ctx context.Context, environmentID string, variablesEnv environment.Environment) (environment.Environment, error) { +func (c *controller) getVariableSet(ctx context.Context, environmentID string, variablesEnv variableset.VariableSet) (variableset.VariableSet, error) { if environmentID == "" { return variablesEnv, nil } - environment, err := c.environmentGetter.Get(ctx, id.ID(environmentID)) + environment, err := c.variableSetGetter.Get(ctx, id.ID(environmentID)) if err != nil { return variablesEnv, err @@ -431,8 +431,8 @@ func (c *controller) buildDataStores(ctx context.Context, info openapi.ResolveRe ds := []expression.DataStore{} - if context.EnvironmentId != "" { - environment, err := c.environmentGetter.Get(ctx, id.ID(context.EnvironmentId)) + if context.VariableSetId != "" { + environment, err := c.variableSetGetter.Get(ctx, id.ID(context.VariableSetId)) if err != nil { return [][]expression.DataStore{}, err @@ -513,11 +513,11 @@ func (c *controller) RunTransaction(ctx context.Context, transactionID string, r } metadata := metadata(runInfo.Metadata) - variablesEnv := c.mappers.In.Environment(openapi.Environment{ + variablesEnv := c.mappers.In.VariableSet(openapi.VariableSet{ Values: runInfo.Variables, }) - environment, err := c.getEnvironment(ctx, runInfo.EnvironmentId, variablesEnv) + environment, err := c.getVariableSet(ctx, runInfo.VariableSetId, variablesEnv) if err != nil { return handleDBError(err), err } diff --git a/server/http/mappings/tests.go b/server/http/mappings/tests.go index 5a36a0e6e8..dafbb9186d 100644 --- a/server/http/mappings/tests.go +++ b/server/http/mappings/tests.go @@ -7,7 +7,6 @@ import ( "github.com/kubeshop/tracetest/server/assertions/comparator" "github.com/kubeshop/tracetest/server/assertions/selectors" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/openapi" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/maps" @@ -15,6 +14,7 @@ import ( "github.com/kubeshop/tracetest/server/test/trigger" "github.com/kubeshop/tracetest/server/traces" "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -47,7 +47,7 @@ func (m OpenAPI) TransactionRun(in transaction.TransactionRun) openapi.Transacti State: string(in.State), Steps: steps, Metadata: in.Metadata, - Environment: m.Environment(in.Environment), + VariableSet: m.VariableSet(in.VariableSet), Pass: int32(in.Pass), Fail: int32(in.Fail), AllStepsRequiredGatesPassed: in.AllStepsRequiredGatesPassed, @@ -77,19 +77,19 @@ func (m OpenAPI) Test(in test.Test) openapi.Test { } // TODO: after migrating tests and transactions, we can remove this -func (m OpenAPI) Environment(in environment.Environment) openapi.Environment { - return openapi.Environment{ +func (m OpenAPI) VariableSet(in variableset.VariableSet) openapi.VariableSet { + return openapi.VariableSet{ Id: in.ID.String(), Name: in.Name, Description: in.Description, - Values: m.EnvironmentValues(in.Values), + Values: m.VariableSetValues(in.Values), } } -func (m OpenAPI) EnvironmentValues(in []environment.EnvironmentValue) []openapi.EnvironmentValue { - values := make([]openapi.EnvironmentValue, len(in)) +func (m OpenAPI) VariableSetValues(in []variableset.VariableSetValue) []openapi.VariableSetValue { + values := make([]openapi.VariableSetValue, len(in)) for i, v := range in { - values[i] = openapi.EnvironmentValue{Key: v.Key, Value: v.Value} + values[i] = openapi.VariableSetValue{Key: v.Key, Value: v.Value} } return values @@ -139,10 +139,10 @@ func (m OpenAPI) Tests(in []test.Test) []openapi.Test { return tests } -func (m OpenAPI) Environments(in []environment.Environment) []openapi.Environment { - environments := make([]openapi.Environment, len(in)) +func (m OpenAPI) VariableSets(in []variableset.VariableSet) []openapi.VariableSet { + environments := make([]openapi.VariableSet, len(in)) for i, t := range in { - environments[i] = m.Environment(t) + environments[i] = m.VariableSet(t) } return environments @@ -285,7 +285,7 @@ func (m OpenAPI) Run(in *test.Run) openapi.TestRun { Result: m.Result(in.Results), Outputs: m.RunOutputs(in.Outputs), Metadata: in.Metadata, - Environment: m.Environment(in.Environment), + VariableSet: m.VariableSet(in.VariableSet), TransactionId: in.TransactionID, TransactionRunId: in.TransactionRunID, Linter: m.LinterResult(in.Linter), @@ -412,7 +412,7 @@ func (m Model) Run(in openapi.TestRun) (*test.Run, error) { Results: result, Outputs: m.RunOutputs(in.Outputs), Metadata: in.Metadata, - Environment: m.Environment(in.Environment), + VariableSet: m.VariableSet(in.VariableSet), }, nil } @@ -500,19 +500,19 @@ func (m Model) Runs(in []openapi.TestRun) ([]test.Run, error) { return runs, nil } -func (m Model) Environment(in openapi.Environment) environment.Environment { - return environment.Environment{ +func (m Model) VariableSet(in openapi.VariableSet) variableset.VariableSet { + return variableset.VariableSet{ ID: id.ID(in.Id), Name: in.Name, Description: in.Description, - Values: m.EnvironmentValue(in.Values), + Values: m.VariableSetValue(in.Values), } } -func (m Model) EnvironmentValue(in []openapi.EnvironmentValue) []environment.EnvironmentValue { - values := make([]environment.EnvironmentValue, len(in)) +func (m Model) VariableSetValue(in []openapi.VariableSetValue) []variableset.VariableSetValue { + values := make([]variableset.VariableSetValue, len(in)) for i, h := range in { - values[i] = environment.EnvironmentValue{Key: h.Key, Value: h.Value} + values[i] = variableset.VariableSetValue{Key: h.Key, Value: h.Value} } return values diff --git a/server/http/validation/variable.go b/server/http/validation/variable.go index 2b76352878..ebe79048c8 100644 --- a/server/http/validation/variable.go +++ b/server/http/validation/variable.go @@ -5,12 +5,12 @@ import ( "database/sql" "errors" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/expression/linting" "github.com/kubeshop/tracetest/server/openapi" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/variableset" ) var ErrMissingVariables = errors.New("variables are missing") @@ -19,9 +19,9 @@ type augmentedTestGetter interface { GetAugmented(context.Context, id.ID) (test.Test, error) } -func ValidateMissingVariables(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, test test.Test, env environment.Environment) (openapi.MissingVariablesError, error) { +func ValidateMissingVariables(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, test test.Test, env variableset.VariableSet) (openapi.MissingVariablesError, error) { missingVariables := getMissingVariables(test, env) - previousValues := map[string]environment.EnvironmentValue{} + previousValues := map[string]variableset.VariableSetValue{} var err error if len(missingVariables) > 0 { previousValues, err = getPreviousEnvironmentValues(ctx, testRepo, runRepo, test) @@ -32,7 +32,7 @@ func ValidateMissingVariables(ctx context.Context, testRepo augmentedTestGetter, return buildErrorObject(test, missingVariables, previousValues) } -func getMissingVariables(test test.Test, environment environment.Environment) []string { +func getMissingVariables(test test.Test, environment variableset.VariableSet) []string { availableTestVariables := getAvailableVariables(test, environment) expectedVariables := linting.DetectMissingVariables(test, availableTestVariables) @@ -52,7 +52,7 @@ func getMissingVariables(test test.Test, environment environment.Environment) [] return missingVariables } -func getAvailableVariables(test test.Test, environment environment.Environment) []string { +func getAvailableVariables(test test.Test, environment variableset.VariableSet) []string { availableVariables := make([]string, 0) for _, env := range environment.Values { availableVariables = append(availableVariables, env.Key) @@ -65,10 +65,10 @@ func getAvailableVariables(test test.Test, environment environment.Environment) return availableVariables } -func getPreviousEnvironmentValues(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, test test.Test) (map[string]environment.EnvironmentValue, error) { +func getPreviousEnvironmentValues(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, test test.Test) (map[string]variableset.VariableSetValue, error) { latestTestVersion, err := testRepo.GetAugmented(ctx, test.ID) if err != nil { - return map[string]environment.EnvironmentValue{}, err + return map[string]variableset.VariableSetValue{}, err } previousTestRun, err := runRepo.GetLatestRunByTestVersion(ctx, test.ID, *latestTestVersion.Version) @@ -76,21 +76,21 @@ func getPreviousEnvironmentValues(ctx context.Context, testRepo augmentedTestGet // If error is not found, it means this is the first run. So just ignore this error // and provide empty values in the default values for the missing variables if err != sql.ErrNoRows { - return map[string]environment.EnvironmentValue{}, err + return map[string]variableset.VariableSetValue{}, err } } else { - envMap := make(map[string]environment.EnvironmentValue, len(previousTestRun.Environment.Values)) - for _, envVar := range previousTestRun.Environment.Values { + envMap := make(map[string]variableset.VariableSetValue, len(previousTestRun.VariableSet.Values)) + for _, envVar := range previousTestRun.VariableSet.Values { envMap[envVar.Key] = envVar } return envMap, nil } - return map[string]environment.EnvironmentValue{}, nil + return map[string]variableset.VariableSetValue{}, nil } -func ValidateMissingVariablesFromTransaction(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, transaction transaction.Transaction, env environment.Environment) (openapi.MissingVariablesError, error) { +func ValidateMissingVariablesFromTransaction(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, transaction transaction.Transaction, env variableset.VariableSet) (openapi.MissingVariablesError, error) { missingVariables := make([]openapi.MissingVariable, 0) for _, step := range transaction.Steps { stepValidationResult, err := ValidateMissingVariables(ctx, testRepo, runRepo, step, env) @@ -101,9 +101,9 @@ func ValidateMissingVariablesFromTransaction(ctx context.Context, testRepo augme missingVariables = append(missingVariables, stepValidationResult.MissingVariables...) // update env with this test outputs - outputs := make([]environment.EnvironmentValue, 0) + outputs := make([]variableset.VariableSetValue, 0) for _, output := range step.Outputs { - outputs = append(outputs, environment.EnvironmentValue{Key: output.Name}) + outputs = append(outputs, variableset.VariableSetValue{Key: output.Name}) } env.Values = append(env.Values, outputs...) @@ -116,7 +116,7 @@ func ValidateMissingVariablesFromTransaction(ctx context.Context, testRepo augme return openapi.MissingVariablesError{}, nil } -func buildErrorObject(test test.Test, missingVariables []string, previousValues map[string]environment.EnvironmentValue) (openapi.MissingVariablesError, error) { +func buildErrorObject(test test.Test, missingVariables []string, previousValues map[string]variableset.VariableSetValue) (openapi.MissingVariablesError, error) { if len(missingVariables) > 0 { missingVariableObjects := make([]openapi.Variable, 0, len(missingVariables)) for _, variable := range missingVariables { diff --git a/server/migrations/29_envs_to_variables.down.sql b/server/migrations/29_envs_to_variables.down.sql new file mode 100644 index 0000000000..e31e100df4 --- /dev/null +++ b/server/migrations/29_envs_to_variables.down.sql @@ -0,0 +1,12 @@ +BEGIN; + +ALTER TABLE + variable_sets RENAME TO environments; + +ALTER TABLE + test_runs RENAME COLUMN variable_set TO environment; + +ALTER TABLE + transaction_runs RENAME COLUMN variable_set TO environment; + +COMMIT; \ No newline at end of file diff --git a/server/migrations/29_envs_to_variables.up.sql b/server/migrations/29_envs_to_variables.up.sql new file mode 100644 index 0000000000..c22a4ab9d9 --- /dev/null +++ b/server/migrations/29_envs_to_variables.up.sql @@ -0,0 +1,12 @@ +BEGIN; + +ALTER TABLE + environments RENAME TO variable_sets; + +ALTER TABLE + test_runs RENAME COLUMN environment TO variable_set; + +ALTER TABLE + transaction_runs RENAME COLUMN environment TO variable_set; + +COMMIT; \ No newline at end of file diff --git a/server/model/yaml/encoding.go b/server/model/yaml/encoding.go index 30b04732a1..4a7286fcfe 100644 --- a/server/model/yaml/encoding.go +++ b/server/model/yaml/encoding.go @@ -4,8 +4,8 @@ import ( "fmt" "reflect" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/openapi" + "github.com/kubeshop/tracetest/server/variableset" "github.com/mitchellh/mapstructure" "gopkg.in/yaml.v2" ) @@ -38,12 +38,12 @@ func Decode(contents []byte) (File, error) { } f.Spec = transaction case FileTypeEnvironment: - var environment environment.Environment - err := mapstructure.Decode(f.Spec, &environment) + var variableSet variableset.VariableSet + err := mapstructure.Decode(f.Spec, &variableSet) if err != nil { return File{}, fmt.Errorf("cannot decode environment: %w", err) } - f.Spec = environment + f.Spec = variableSet case FileTypeDataStore: var dataStore openapi.DataStore err := mapstructure.Decode(f.Spec, &dataStore) diff --git a/server/openapi/api.go b/server/openapi/api.go index 945054c335..a13f97e59b 100644 --- a/server/openapi/api.go +++ b/server/openapi/api.go @@ -48,40 +48,40 @@ type ApiApiRouter interface { // pass the data to a ResourceApiApiServicer to perform the required actions, then write the service results to the http response. type ResourceApiApiRouter interface { CreateDemo(http.ResponseWriter, *http.Request) - CreateEnvironment(http.ResponseWriter, *http.Request) CreateLinter(http.ResponseWriter, *http.Request) CreateTest(http.ResponseWriter, *http.Request) CreateTransaction(http.ResponseWriter, *http.Request) + CreateVariableSet(http.ResponseWriter, *http.Request) DeleteDataStore(http.ResponseWriter, *http.Request) DeleteDemo(http.ResponseWriter, *http.Request) - DeleteEnvironment(http.ResponseWriter, *http.Request) DeleteLinter(http.ResponseWriter, *http.Request) DeleteTest(http.ResponseWriter, *http.Request) DeleteTransaction(http.ResponseWriter, *http.Request) + DeleteVariableSet(http.ResponseWriter, *http.Request) GetConfiguration(http.ResponseWriter, *http.Request) GetDataStore(http.ResponseWriter, *http.Request) GetDemo(http.ResponseWriter, *http.Request) - GetEnvironment(http.ResponseWriter, *http.Request) GetLinter(http.ResponseWriter, *http.Request) GetPollingProfile(http.ResponseWriter, *http.Request) GetTests(http.ResponseWriter, *http.Request) GetTransaction(http.ResponseWriter, *http.Request) GetTransactions(http.ResponseWriter, *http.Request) + GetVariableSet(http.ResponseWriter, *http.Request) ListConfiguration(http.ResponseWriter, *http.Request) ListDataStore(http.ResponseWriter, *http.Request) ListDemos(http.ResponseWriter, *http.Request) - ListEnvironments(http.ResponseWriter, *http.Request) ListLinters(http.ResponseWriter, *http.Request) ListPollingProfile(http.ResponseWriter, *http.Request) + ListVariableSets(http.ResponseWriter, *http.Request) TestsTestIdGet(http.ResponseWriter, *http.Request) UpdateConfiguration(http.ResponseWriter, *http.Request) UpdateDataStore(http.ResponseWriter, *http.Request) UpdateDemo(http.ResponseWriter, *http.Request) - UpdateEnvironment(http.ResponseWriter, *http.Request) UpdateLinter(http.ResponseWriter, *http.Request) UpdatePollingProfile(http.ResponseWriter, *http.Request) UpdateTest(http.ResponseWriter, *http.Request) UpdateTransaction(http.ResponseWriter, *http.Request) + UpdateVariableSet(http.ResponseWriter, *http.Request) } // ApiApiServicer defines the api actions for the ApiApi service @@ -120,38 +120,38 @@ type ApiApiServicer interface { // and updated with the logic required for the API. type ResourceApiApiServicer interface { CreateDemo(context.Context, Demo) (ImplResponse, error) - CreateEnvironment(context.Context, EnvironmentResource) (ImplResponse, error) CreateLinter(context.Context, LinterResource) (ImplResponse, error) CreateTest(context.Context, Test) (ImplResponse, error) CreateTransaction(context.Context, TransactionResource) (ImplResponse, error) + CreateVariableSet(context.Context, VariableSetResource) (ImplResponse, error) DeleteDataStore(context.Context, string) (ImplResponse, error) DeleteDemo(context.Context, string) (ImplResponse, error) - DeleteEnvironment(context.Context, string) (ImplResponse, error) DeleteLinter(context.Context, string) (ImplResponse, error) DeleteTest(context.Context, string) (ImplResponse, error) DeleteTransaction(context.Context, string) (ImplResponse, error) + DeleteVariableSet(context.Context, string) (ImplResponse, error) GetConfiguration(context.Context, string) (ImplResponse, error) GetDataStore(context.Context, string) (ImplResponse, error) GetDemo(context.Context, string) (ImplResponse, error) - GetEnvironment(context.Context, string) (ImplResponse, error) GetLinter(context.Context, string) (ImplResponse, error) GetPollingProfile(context.Context, string) (ImplResponse, error) GetTests(context.Context, int32, int32, string, string, string) (ImplResponse, error) GetTransaction(context.Context, string) (ImplResponse, error) GetTransactions(context.Context, int32, int32, string, string, string) (ImplResponse, error) + GetVariableSet(context.Context, string) (ImplResponse, error) ListConfiguration(context.Context, int32, int32, string, string) (ImplResponse, error) ListDataStore(context.Context, int32, int32, string, string) (ImplResponse, error) ListDemos(context.Context, int32, int32, string, string) (ImplResponse, error) - ListEnvironments(context.Context, int32, int32, string, string) (ImplResponse, error) ListLinters(context.Context, int32, int32, string, string) (ImplResponse, error) ListPollingProfile(context.Context, int32, int32, string, string) (ImplResponse, error) + ListVariableSets(context.Context, int32, int32, string, string) (ImplResponse, error) TestsTestIdGet(context.Context, string) (ImplResponse, error) UpdateConfiguration(context.Context, string, ConfigurationResource) (ImplResponse, error) UpdateDataStore(context.Context, string, DataStore) (ImplResponse, error) UpdateDemo(context.Context, string, Demo) (ImplResponse, error) - UpdateEnvironment(context.Context, string, EnvironmentResource) (ImplResponse, error) UpdateLinter(context.Context, string, LinterResource) (ImplResponse, error) UpdatePollingProfile(context.Context, string, PollingProfile) (ImplResponse, error) UpdateTest(context.Context, string, Test) (ImplResponse, error) UpdateTransaction(context.Context, string, TransactionResource) (ImplResponse, error) + UpdateVariableSet(context.Context, string, VariableSetResource) (ImplResponse, error) } diff --git a/server/openapi/api_resource_api.go b/server/openapi/api_resource_api.go index 6f02b4f86d..77d27e75a7 100644 --- a/server/openapi/api_resource_api.go +++ b/server/openapi/api_resource_api.go @@ -56,12 +56,6 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos", c.CreateDemo, }, - { - "CreateEnvironment", - strings.ToUpper("Post"), - "/api/environments", - c.CreateEnvironment, - }, { "CreateLinter", strings.ToUpper("Post"), @@ -80,6 +74,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/transactions", c.CreateTransaction, }, + { + "CreateVariableSet", + strings.ToUpper("Post"), + "/api/variableSets", + c.CreateVariableSet, + }, { "DeleteDataStore", strings.ToUpper("Delete"), @@ -92,12 +92,6 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos/{demoId}", c.DeleteDemo, }, - { - "DeleteEnvironment", - strings.ToUpper("Delete"), - "/api/environments/{environmentId}", - c.DeleteEnvironment, - }, { "DeleteLinter", strings.ToUpper("Delete"), @@ -116,6 +110,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/transactions/{transactionId}", c.DeleteTransaction, }, + { + "DeleteVariableSet", + strings.ToUpper("Delete"), + "/api/variableSets/{variableSetId}", + c.DeleteVariableSet, + }, { "GetConfiguration", strings.ToUpper("Get"), @@ -134,12 +134,6 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos/{demoId}", c.GetDemo, }, - { - "GetEnvironment", - strings.ToUpper("Get"), - "/api/environments/{environmentId}", - c.GetEnvironment, - }, { "GetLinter", strings.ToUpper("Get"), @@ -170,6 +164,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/transactions", c.GetTransactions, }, + { + "GetVariableSet", + strings.ToUpper("Get"), + "/api/variableSets/{variableSetId}", + c.GetVariableSet, + }, { "ListConfiguration", strings.ToUpper("Get"), @@ -188,12 +188,6 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos", c.ListDemos, }, - { - "ListEnvironments", - strings.ToUpper("Get"), - "/api/environments", - c.ListEnvironments, - }, { "ListLinters", strings.ToUpper("Get"), @@ -206,6 +200,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/pollingprofiles", c.ListPollingProfile, }, + { + "ListVariableSets", + strings.ToUpper("Get"), + "/api/variableSets", + c.ListVariableSets, + }, { "TestsTestIdGet", strings.ToUpper("Get"), @@ -230,12 +230,6 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/demos/{demoId}", c.UpdateDemo, }, - { - "UpdateEnvironment", - strings.ToUpper("Put"), - "/api/environments/{environmentId}", - c.UpdateEnvironment, - }, { "UpdateLinter", strings.ToUpper("Put"), @@ -260,6 +254,12 @@ func (c *ResourceApiApiController) Routes() Routes { "/api/transactions/{transactionId}", c.UpdateTransaction, }, + { + "UpdateVariableSet", + strings.ToUpper("Put"), + "/api/variableSets/{variableSetId}", + c.UpdateVariableSet, + }, } } @@ -287,30 +287,6 @@ func (c *ResourceApiApiController) CreateDemo(w http.ResponseWriter, r *http.Req } -// CreateEnvironment - Create an environment -func (c *ResourceApiApiController) CreateEnvironment(w http.ResponseWriter, r *http.Request) { - environmentResourceParam := EnvironmentResource{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&environmentResourceParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertEnvironmentResourceRequired(environmentResourceParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - result, err := c.service.CreateEnvironment(r.Context(), environmentResourceParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - // CreateLinter - Create an Linter func (c *ResourceApiApiController) CreateLinter(w http.ResponseWriter, r *http.Request) { linterResourceParam := LinterResource{} @@ -383,12 +359,20 @@ func (c *ResourceApiApiController) CreateTransaction(w http.ResponseWriter, r *h } -// DeleteDataStore - Delete a Data Store -func (c *ResourceApiApiController) DeleteDataStore(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - dataStoreIdParam := params["dataStoreId"] - - result, err := c.service.DeleteDataStore(r.Context(), dataStoreIdParam) +// CreateVariableSet - Create an VariableSet +func (c *ResourceApiApiController) CreateVariableSet(w http.ResponseWriter, r *http.Request) { + variableSetResourceParam := VariableSetResource{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&variableSetResourceParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + if err := AssertVariableSetResourceRequired(variableSetResourceParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.CreateVariableSet(r.Context(), variableSetResourceParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -399,12 +383,12 @@ func (c *ResourceApiApiController) DeleteDataStore(w http.ResponseWriter, r *htt } -// DeleteDemo - Delete a Demonstration setting -func (c *ResourceApiApiController) DeleteDemo(w http.ResponseWriter, r *http.Request) { +// DeleteDataStore - Delete a Data Store +func (c *ResourceApiApiController) DeleteDataStore(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - demoIdParam := params["demoId"] + dataStoreIdParam := params["dataStoreId"] - result, err := c.service.DeleteDemo(r.Context(), demoIdParam) + result, err := c.service.DeleteDataStore(r.Context(), dataStoreIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -415,12 +399,12 @@ func (c *ResourceApiApiController) DeleteDemo(w http.ResponseWriter, r *http.Req } -// DeleteEnvironment - Delete an environment -func (c *ResourceApiApiController) DeleteEnvironment(w http.ResponseWriter, r *http.Request) { +// DeleteDemo - Delete a Demonstration setting +func (c *ResourceApiApiController) DeleteDemo(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - environmentIdParam := params["environmentId"] + demoIdParam := params["demoId"] - result, err := c.service.DeleteEnvironment(r.Context(), environmentIdParam) + result, err := c.service.DeleteDemo(r.Context(), demoIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -479,12 +463,12 @@ func (c *ResourceApiApiController) DeleteTransaction(w http.ResponseWriter, r *h } -// GetConfiguration - Get Tracetest configuration -func (c *ResourceApiApiController) GetConfiguration(w http.ResponseWriter, r *http.Request) { +// DeleteVariableSet - Delete an VariableSet +func (c *ResourceApiApiController) DeleteVariableSet(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - configIdParam := params["configId"] + variableSetIdParam := params["variableSetId"] - result, err := c.service.GetConfiguration(r.Context(), configIdParam) + result, err := c.service.DeleteVariableSet(r.Context(), variableSetIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -495,12 +479,12 @@ func (c *ResourceApiApiController) GetConfiguration(w http.ResponseWriter, r *ht } -// GetDataStore - Get a Data Store -func (c *ResourceApiApiController) GetDataStore(w http.ResponseWriter, r *http.Request) { +// GetConfiguration - Get Tracetest configuration +func (c *ResourceApiApiController) GetConfiguration(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - dataStoreIdParam := params["dataStoreId"] + configIdParam := params["configId"] - result, err := c.service.GetDataStore(r.Context(), dataStoreIdParam) + result, err := c.service.GetConfiguration(r.Context(), configIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -511,12 +495,12 @@ func (c *ResourceApiApiController) GetDataStore(w http.ResponseWriter, r *http.R } -// GetDemo - Get Demonstration setting -func (c *ResourceApiApiController) GetDemo(w http.ResponseWriter, r *http.Request) { +// GetDataStore - Get a Data Store +func (c *ResourceApiApiController) GetDataStore(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - demoIdParam := params["demoId"] + dataStoreIdParam := params["dataStoreId"] - result, err := c.service.GetDemo(r.Context(), demoIdParam) + result, err := c.service.GetDataStore(r.Context(), dataStoreIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -527,12 +511,12 @@ func (c *ResourceApiApiController) GetDemo(w http.ResponseWriter, r *http.Reques } -// GetEnvironment - Get a specific environment -func (c *ResourceApiApiController) GetEnvironment(w http.ResponseWriter, r *http.Request) { +// GetDemo - Get Demonstration setting +func (c *ResourceApiApiController) GetDemo(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - environmentIdParam := params["environmentId"] + demoIdParam := params["demoId"] - result, err := c.service.GetEnvironment(r.Context(), environmentIdParam) + result, err := c.service.GetDemo(r.Context(), demoIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -645,6 +629,22 @@ func (c *ResourceApiApiController) GetTransactions(w http.ResponseWriter, r *htt } +// GetVariableSet - Get a specific VariableSet +func (c *ResourceApiApiController) GetVariableSet(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + variableSetIdParam := params["variableSetId"] + + result, err := c.service.GetVariableSet(r.Context(), variableSetIdParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, w) + +} + // ListConfiguration - List Tracetest configuration func (c *ResourceApiApiController) ListConfiguration(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() @@ -723,8 +723,8 @@ func (c *ResourceApiApiController) ListDemos(w http.ResponseWriter, r *http.Requ } -// ListEnvironments - List environments -func (c *ResourceApiApiController) ListEnvironments(w http.ResponseWriter, r *http.Request) { +// ListLinters - List Linters +func (c *ResourceApiApiController) ListLinters(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() takeParam, err := parseInt32Parameter(query.Get("take"), false) if err != nil { @@ -738,7 +738,7 @@ func (c *ResourceApiApiController) ListEnvironments(w http.ResponseWriter, r *ht } sortByParam := query.Get("sortBy") sortDirectionParam := query.Get("sortDirection") - result, err := c.service.ListEnvironments(r.Context(), takeParam, skipParam, sortByParam, sortDirectionParam) + result, err := c.service.ListLinters(r.Context(), takeParam, skipParam, sortByParam, sortDirectionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -749,8 +749,8 @@ func (c *ResourceApiApiController) ListEnvironments(w http.ResponseWriter, r *ht } -// ListLinters - List Linters -func (c *ResourceApiApiController) ListLinters(w http.ResponseWriter, r *http.Request) { +// ListPollingProfile - List Polling Profile Configuration +func (c *ResourceApiApiController) ListPollingProfile(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() takeParam, err := parseInt32Parameter(query.Get("take"), false) if err != nil { @@ -764,7 +764,7 @@ func (c *ResourceApiApiController) ListLinters(w http.ResponseWriter, r *http.Re } sortByParam := query.Get("sortBy") sortDirectionParam := query.Get("sortDirection") - result, err := c.service.ListLinters(r.Context(), takeParam, skipParam, sortByParam, sortDirectionParam) + result, err := c.service.ListPollingProfile(r.Context(), takeParam, skipParam, sortByParam, sortDirectionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -775,8 +775,8 @@ func (c *ResourceApiApiController) ListLinters(w http.ResponseWriter, r *http.Re } -// ListPollingProfile - List Polling Profile Configuration -func (c *ResourceApiApiController) ListPollingProfile(w http.ResponseWriter, r *http.Request) { +// ListVariableSets - List variableSets +func (c *ResourceApiApiController) ListVariableSets(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() takeParam, err := parseInt32Parameter(query.Get("take"), false) if err != nil { @@ -790,7 +790,7 @@ func (c *ResourceApiApiController) ListPollingProfile(w http.ResponseWriter, r * } sortByParam := query.Get("sortBy") sortDirectionParam := query.Get("sortDirection") - result, err := c.service.ListPollingProfile(r.Context(), takeParam, skipParam, sortByParam, sortDirectionParam) + result, err := c.service.ListVariableSets(r.Context(), takeParam, skipParam, sortByParam, sortDirectionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -898,33 +898,6 @@ func (c *ResourceApiApiController) UpdateDemo(w http.ResponseWriter, r *http.Req } -// UpdateEnvironment - Update an environment -func (c *ResourceApiApiController) UpdateEnvironment(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - environmentIdParam := params["environmentId"] - - environmentResourceParam := EnvironmentResource{} - d := json.NewDecoder(r.Body) - d.DisallowUnknownFields() - if err := d.Decode(&environmentResourceParam); err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - if err := AssertEnvironmentResourceRequired(environmentResourceParam); err != nil { - c.errorHandler(w, r, err, nil) - return - } - result, err := c.service.UpdateEnvironment(r.Context(), environmentIdParam, environmentResourceParam) - // If an error occurred, encode the error with the status code - if err != nil { - c.errorHandler(w, r, err, &result) - return - } - // If no error, encode the body and the result code - EncodeJSONResponse(result.Body, &result.Code, w) - -} - // UpdateLinter - Update a Linter func (c *ResourceApiApiController) UpdateLinter(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) @@ -1032,3 +1005,30 @@ func (c *ResourceApiApiController) UpdateTransaction(w http.ResponseWriter, r *h EncodeJSONResponse(result.Body, &result.Code, w) } + +// UpdateVariableSet - Update an VariableSet +func (c *ResourceApiApiController) UpdateVariableSet(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + variableSetIdParam := params["variableSetId"] + + variableSetResourceParam := VariableSetResource{} + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&variableSetResourceParam); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + if err := AssertVariableSetResourceRequired(variableSetResourceParam); err != nil { + c.errorHandler(w, r, err, nil) + return + } + result, err := c.service.UpdateVariableSet(r.Context(), variableSetIdParam, variableSetResourceParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, w) + +} diff --git a/server/openapi/api_resource_api_service.go b/server/openapi/api_resource_api_service.go index 8d98fa7c20..fcc259ce29 100644 --- a/server/openapi/api_resource_api_service.go +++ b/server/openapi/api_resource_api_service.go @@ -40,20 +40,6 @@ func (s *ResourceApiApiService) CreateDemo(ctx context.Context, demo Demo) (Impl return Response(http.StatusNotImplemented, nil), errors.New("CreateDemo method not implemented") } -// CreateEnvironment - Create an environment -func (s *ResourceApiApiService) CreateEnvironment(ctx context.Context, environmentResource EnvironmentResource) (ImplResponse, error) { - // TODO - update CreateEnvironment with the required logic for this service method. - // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - //TODO: Uncomment the next line to return response Response(201, EnvironmentResource{}) or use other options such as http.Ok ... - //return Response(201, EnvironmentResource{}), nil - - //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... - //return Response(500, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("CreateEnvironment method not implemented") -} - // CreateLinter - Create an Linter func (s *ResourceApiApiService) CreateLinter(ctx context.Context, linterResource LinterResource) (ImplResponse, error) { // TODO - update CreateLinter with the required logic for this service method. @@ -99,6 +85,20 @@ func (s *ResourceApiApiService) CreateTransaction(ctx context.Context, transacti return Response(http.StatusNotImplemented, nil), errors.New("CreateTransaction method not implemented") } +// CreateVariableSet - Create an VariableSet +func (s *ResourceApiApiService) CreateVariableSet(ctx context.Context, variableSetResource VariableSetResource) (ImplResponse, error) { + // TODO - update CreateVariableSet with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(201, VariableSetResource{}) or use other options such as http.Ok ... + //return Response(201, VariableSetResource{}), nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("CreateVariableSet method not implemented") +} + // DeleteDataStore - Delete a Data Store func (s *ResourceApiApiService) DeleteDataStore(ctx context.Context, dataStoreId string) (ImplResponse, error) { // TODO - update DeleteDataStore with the required logic for this service method. @@ -130,26 +130,6 @@ func (s *ResourceApiApiService) DeleteDemo(ctx context.Context, demoId string) ( return Response(http.StatusNotImplemented, nil), errors.New("DeleteDemo method not implemented") } -// DeleteEnvironment - Delete an environment -func (s *ResourceApiApiService) DeleteEnvironment(ctx context.Context, environmentId string) (ImplResponse, error) { - // TODO - update DeleteEnvironment with the required logic for this service method. - // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - //TODO: Uncomment the next line to return response Response(204, {}) or use other options such as http.Ok ... - //return Response(204, nil),nil - - //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - //return Response(400, nil),nil - - //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - //return Response(404, nil),nil - - //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... - //return Response(500, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("DeleteEnvironment method not implemented") -} - // DeleteLinter - Delete an Linter func (s *ResourceApiApiService) DeleteLinter(ctx context.Context, linterId string) (ImplResponse, error) { // TODO - update DeleteLinter with the required logic for this service method. @@ -198,6 +178,26 @@ func (s *ResourceApiApiService) DeleteTransaction(ctx context.Context, transacti return Response(http.StatusNotImplemented, nil), errors.New("DeleteTransaction method not implemented") } +// DeleteVariableSet - Delete an VariableSet +func (s *ResourceApiApiService) DeleteVariableSet(ctx context.Context, variableSetId string) (ImplResponse, error) { + // TODO - update DeleteVariableSet with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(204, {}) or use other options such as http.Ok ... + //return Response(204, nil),nil + + //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + //return Response(400, nil),nil + + //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + //return Response(404, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("DeleteVariableSet method not implemented") +} + // GetConfiguration - Get Tracetest configuration func (s *ResourceApiApiService) GetConfiguration(ctx context.Context, configId string) (ImplResponse, error) { // TODO - update GetConfiguration with the required logic for this service method. @@ -246,23 +246,6 @@ func (s *ResourceApiApiService) GetDemo(ctx context.Context, demoId string) (Imp return Response(http.StatusNotImplemented, nil), errors.New("GetDemo method not implemented") } -// GetEnvironment - Get a specific environment -func (s *ResourceApiApiService) GetEnvironment(ctx context.Context, environmentId string) (ImplResponse, error) { - // TODO - update GetEnvironment with the required logic for this service method. - // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - //TODO: Uncomment the next line to return response Response(200, EnvironmentResource{}) or use other options such as http.Ok ... - //return Response(200, EnvironmentResource{}), nil - - //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - //return Response(404, nil),nil - - //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... - //return Response(500, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("GetEnvironment method not implemented") -} - // GetLinter - Get a specific Linter func (s *ResourceApiApiService) GetLinter(ctx context.Context, linterId string) (ImplResponse, error) { // TODO - update GetLinter with the required logic for this service method. @@ -348,6 +331,23 @@ func (s *ResourceApiApiService) GetTransactions(ctx context.Context, take int32, return Response(http.StatusNotImplemented, nil), errors.New("GetTransactions method not implemented") } +// GetVariableSet - Get a specific VariableSet +func (s *ResourceApiApiService) GetVariableSet(ctx context.Context, variableSetId string) (ImplResponse, error) { + // TODO - update GetVariableSet with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(200, VariableSetResource{}) or use other options such as http.Ok ... + //return Response(200, VariableSetResource{}), nil + + //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + //return Response(404, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetVariableSet method not implemented") +} + // ListConfiguration - List Tracetest configuration func (s *ResourceApiApiService) ListConfiguration(ctx context.Context, take int32, skip int32, sortBy string, sortDirection string) (ImplResponse, error) { // TODO - update ListConfiguration with the required logic for this service method. @@ -393,23 +393,6 @@ func (s *ResourceApiApiService) ListDemos(ctx context.Context, take int32, skip return Response(http.StatusNotImplemented, nil), errors.New("ListDemos method not implemented") } -// ListEnvironments - List environments -func (s *ResourceApiApiService) ListEnvironments(ctx context.Context, take int32, skip int32, sortBy string, sortDirection string) (ImplResponse, error) { - // TODO - update ListEnvironments with the required logic for this service method. - // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - //TODO: Uncomment the next line to return response Response(200, EnvironmentResourceList{}) or use other options such as http.Ok ... - //return Response(200, EnvironmentResourceList{}), nil - - //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - //return Response(400, nil),nil - - //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... - //return Response(500, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("ListEnvironments method not implemented") -} - // ListLinters - List Linters func (s *ResourceApiApiService) ListLinters(ctx context.Context, take int32, skip int32, sortBy string, sortDirection string) (ImplResponse, error) { // TODO - update ListLinters with the required logic for this service method. @@ -441,6 +424,23 @@ func (s *ResourceApiApiService) ListPollingProfile(ctx context.Context, take int return Response(http.StatusNotImplemented, nil), errors.New("ListPollingProfile method not implemented") } +// ListVariableSets - List variableSets +func (s *ResourceApiApiService) ListVariableSets(ctx context.Context, take int32, skip int32, sortBy string, sortDirection string) (ImplResponse, error) { + // TODO - update ListVariableSets with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(200, VariableSetResourceList{}) or use other options such as http.Ok ... + //return Response(200, VariableSetResourceList{}), nil + + //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + //return Response(400, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("ListVariableSets method not implemented") +} + // TestsTestIdGet - get test func (s *ResourceApiApiService) TestsTestIdGet(ctx context.Context, testId string) (ImplResponse, error) { // TODO - update TestsTestIdGet with the required logic for this service method. @@ -506,26 +506,6 @@ func (s *ResourceApiApiService) UpdateDemo(ctx context.Context, demoId string, d return Response(http.StatusNotImplemented, nil), errors.New("UpdateDemo method not implemented") } -// UpdateEnvironment - Update an environment -func (s *ResourceApiApiService) UpdateEnvironment(ctx context.Context, environmentId string, environmentResource EnvironmentResource) (ImplResponse, error) { - // TODO - update UpdateEnvironment with the required logic for this service method. - // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. - - //TODO: Uncomment the next line to return response Response(200, EnvironmentResource{}) or use other options such as http.Ok ... - //return Response(200, EnvironmentResource{}), nil - - //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... - //return Response(400, nil),nil - - //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... - //return Response(404, nil),nil - - //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... - //return Response(500, nil),nil - - return Response(http.StatusNotImplemented, nil), errors.New("UpdateEnvironment method not implemented") -} - // UpdateLinter - Update a Linter func (s *ResourceApiApiService) UpdateLinter(ctx context.Context, linterId string, linterResource LinterResource) (ImplResponse, error) { // TODO - update UpdateLinter with the required logic for this service method. @@ -599,3 +579,23 @@ func (s *ResourceApiApiService) UpdateTransaction(ctx context.Context, transacti return Response(http.StatusNotImplemented, nil), errors.New("UpdateTransaction method not implemented") } + +// UpdateVariableSet - Update an VariableSet +func (s *ResourceApiApiService) UpdateVariableSet(ctx context.Context, variableSetId string, variableSetResource VariableSetResource) (ImplResponse, error) { + // TODO - update UpdateVariableSet with the required logic for this service method. + // Add api_resource_api_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + //TODO: Uncomment the next line to return response Response(200, VariableSetResource{}) or use other options such as http.Ok ... + //return Response(200, VariableSetResource{}), nil + + //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + //return Response(400, nil),nil + + //TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + //return Response(404, nil),nil + + //TODO: Uncomment the next line to return response Response(500, {}) or use other options such as http.Ok ... + //return Response(500, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("UpdateVariableSet method not implemented") +} diff --git a/server/openapi/model_environment_resource.go b/server/openapi/model_environment_resource.go deleted file mode 100644 index e2f9cf5a41..0000000000 --- a/server/openapi/model_environment_resource.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - * TraceTest - * - * OpenAPI definition for TraceTest endpoint and resources - * - * API version: 0.2.1 - * Generated by: OpenAPI Generator (https://openapi-generator.tech) - */ - -package openapi - -// EnvironmentResource - Represents an environment structured into the Resources format. -type EnvironmentResource struct { - - // Represents the type of this resource. It should always be set as 'Environment'. - Type string `json:"type,omitempty"` - - Spec Environment `json:"spec,omitempty"` -} - -// AssertEnvironmentResourceRequired checks if the required fields are not zero-ed -func AssertEnvironmentResourceRequired(obj EnvironmentResource) error { - if err := AssertEnvironmentRequired(obj.Spec); err != nil { - return err - } - return nil -} - -// AssertRecurseEnvironmentResourceRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of EnvironmentResource (e.g. [][]EnvironmentResource), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseEnvironmentResourceRequired(objSlice interface{}) error { - return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aEnvironmentResource, ok := obj.(EnvironmentResource) - if !ok { - return ErrTypeAssertionError - } - return AssertEnvironmentResourceRequired(aEnvironmentResource) - }) -} diff --git a/server/openapi/model_environment_resource_list.go b/server/openapi/model_environment_resource_list.go deleted file mode 100644 index 23b5d812a1..0000000000 --- a/server/openapi/model_environment_resource_list.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - * TraceTest - * - * OpenAPI definition for TraceTest endpoint and resources - * - * API version: 0.2.1 - * Generated by: OpenAPI Generator (https://openapi-generator.tech) - */ - -package openapi - -type EnvironmentResourceList struct { - Count int32 `json:"count,omitempty"` - - Items []EnvironmentResource `json:"items,omitempty"` -} - -// AssertEnvironmentResourceListRequired checks if the required fields are not zero-ed -func AssertEnvironmentResourceListRequired(obj EnvironmentResourceList) error { - for _, el := range obj.Items { - if err := AssertEnvironmentResourceRequired(el); err != nil { - return err - } - } - return nil -} - -// AssertRecurseEnvironmentResourceListRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of EnvironmentResourceList (e.g. [][]EnvironmentResourceList), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseEnvironmentResourceListRequired(objSlice interface{}) error { - return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aEnvironmentResourceList, ok := obj.(EnvironmentResourceList) - if !ok { - return ErrTypeAssertionError - } - return AssertEnvironmentResourceListRequired(aEnvironmentResourceList) - }) -} diff --git a/server/openapi/model_environment_value.go b/server/openapi/model_environment_value.go deleted file mode 100644 index ccb350c927..0000000000 --- a/server/openapi/model_environment_value.go +++ /dev/null @@ -1,33 +0,0 @@ -/* - * TraceTest - * - * OpenAPI definition for TraceTest endpoint and resources - * - * API version: 0.2.1 - * Generated by: OpenAPI Generator (https://openapi-generator.tech) - */ - -package openapi - -type EnvironmentValue struct { - Key string `json:"key,omitempty"` - - Value string `json:"value,omitempty"` -} - -// AssertEnvironmentValueRequired checks if the required fields are not zero-ed -func AssertEnvironmentValueRequired(obj EnvironmentValue) error { - return nil -} - -// AssertRecurseEnvironmentValueRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of EnvironmentValue (e.g. [][]EnvironmentValue), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseEnvironmentValueRequired(objSlice interface{}) error { - return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aEnvironmentValue, ok := obj.(EnvironmentValue) - if !ok { - return ErrTypeAssertionError - } - return AssertEnvironmentValueRequired(aEnvironmentValue) - }) -} diff --git a/server/openapi/model_list_environments_200_response.go b/server/openapi/model_list_environments_200_response.go deleted file mode 100644 index 25ca20377f..0000000000 --- a/server/openapi/model_list_environments_200_response.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - * TraceTest - * - * OpenAPI definition for TraceTest endpoint and resources - * - * API version: 0.2.1 - * Generated by: OpenAPI Generator (https://openapi-generator.tech) - */ - -package openapi - -type ListEnvironments200Response struct { - Count int32 `json:"count,omitempty"` - - Items []EnvironmentResource `json:"items,omitempty"` -} - -// AssertListEnvironments200ResponseRequired checks if the required fields are not zero-ed -func AssertListEnvironments200ResponseRequired(obj ListEnvironments200Response) error { - for _, el := range obj.Items { - if err := AssertEnvironmentResourceRequired(el); err != nil { - return err - } - } - return nil -} - -// AssertRecurseListEnvironments200ResponseRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of ListEnvironments200Response (e.g. [][]ListEnvironments200Response), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseListEnvironments200ResponseRequired(objSlice interface{}) error { - return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aListEnvironments200Response, ok := obj.(ListEnvironments200Response) - if !ok { - return ErrTypeAssertionError - } - return AssertListEnvironments200ResponseRequired(aListEnvironments200Response) - }) -} diff --git a/server/openapi/model_list_variable_sets_200_response.go b/server/openapi/model_list_variable_sets_200_response.go new file mode 100644 index 0000000000..075c2936c1 --- /dev/null +++ b/server/openapi/model_list_variable_sets_200_response.go @@ -0,0 +1,38 @@ +/* + * TraceTest + * + * OpenAPI definition for TraceTest endpoint and resources + * + * API version: 0.2.1 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package openapi + +type ListVariableSets200Response struct { + Count int32 `json:"count,omitempty"` + + Items []VariableSetResource `json:"items,omitempty"` +} + +// AssertListVariableSets200ResponseRequired checks if the required fields are not zero-ed +func AssertListVariableSets200ResponseRequired(obj ListVariableSets200Response) error { + for _, el := range obj.Items { + if err := AssertVariableSetResourceRequired(el); err != nil { + return err + } + } + return nil +} + +// AssertRecurseListVariableSets200ResponseRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of ListVariableSets200Response (e.g. [][]ListVariableSets200Response), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseListVariableSets200ResponseRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aListVariableSets200Response, ok := obj.(ListVariableSets200Response) + if !ok { + return ErrTypeAssertionError + } + return AssertListVariableSets200ResponseRequired(aListVariableSets200Response) + }) +} diff --git a/server/openapi/model_resolve_context.go b/server/openapi/model_resolve_context.go index 7b28415c1e..e22612b124 100644 --- a/server/openapi/model_resolve_context.go +++ b/server/openapi/model_resolve_context.go @@ -18,7 +18,7 @@ type ResolveContext struct { Selector string `json:"selector,omitempty"` - EnvironmentId string `json:"environmentId,omitempty"` + VariableSetId string `json:"variableSetId,omitempty"` } // AssertResolveContextRequired checks if the required fields are not zero-ed diff --git a/server/openapi/model_run_information.go b/server/openapi/model_run_information.go index 0bfb8fb204..27cf3468bb 100644 --- a/server/openapi/model_run_information.go +++ b/server/openapi/model_run_information.go @@ -12,9 +12,9 @@ package openapi type RunInformation struct { Metadata *map[string]string `json:"metadata,omitempty"` - EnvironmentId string `json:"environmentId,omitempty"` + VariableSetId string `json:"variableSetId,omitempty"` - Variables []EnvironmentValue `json:"variables,omitempty"` + Variables []VariableSetValue `json:"variables,omitempty"` RequiredGates *[]SupportedGates `json:"requiredGates,omitempty"` } @@ -22,7 +22,7 @@ type RunInformation struct { // AssertRunInformationRequired checks if the required fields are not zero-ed func AssertRunInformationRequired(obj RunInformation) error { for _, el := range obj.Variables { - if err := AssertEnvironmentValueRequired(el); err != nil { + if err := AssertVariableSetValueRequired(el); err != nil { return err } } diff --git a/server/openapi/model_test_run.go b/server/openapi/model_test_run.go index e2676beac9..ce6bef4dd6 100644 --- a/server/openapi/model_test_run.go +++ b/server/openapi/model_test_run.go @@ -45,7 +45,7 @@ type TestRun struct { CompletedAt time.Time `json:"completedAt,omitempty"` - Environment Environment `json:"environment,omitempty"` + VariableSet VariableSet `json:"variableSet,omitempty"` TriggerResult TriggerResult `json:"triggerResult,omitempty"` @@ -68,7 +68,7 @@ type TestRun struct { // AssertTestRunRequired checks if the required fields are not zero-ed func AssertTestRunRequired(obj TestRun) error { - if err := AssertEnvironmentRequired(obj.Environment); err != nil { + if err := AssertVariableSetRequired(obj.VariableSet); err != nil { return err } if err := AssertTriggerResultRequired(obj.TriggerResult); err != nil { diff --git a/server/openapi/model_transaction_run.go b/server/openapi/model_transaction_run.go index 1c69d63d23..91b818c0a8 100644 --- a/server/openapi/model_transaction_run.go +++ b/server/openapi/model_transaction_run.go @@ -26,7 +26,7 @@ type TransactionRun struct { Steps []TestRun `json:"steps,omitempty"` - Environment Environment `json:"environment,omitempty"` + VariableSet VariableSet `json:"variableSet,omitempty"` Metadata map[string]string `json:"metadata,omitempty"` @@ -44,7 +44,7 @@ func AssertTransactionRunRequired(obj TransactionRun) error { return err } } - if err := AssertEnvironmentRequired(obj.Environment); err != nil { + if err := AssertVariableSetRequired(obj.VariableSet); err != nil { return err } return nil diff --git a/server/openapi/model_environment.go b/server/openapi/model_variable_set.go similarity index 53% rename from server/openapi/model_environment.go rename to server/openapi/model_variable_set.go index d2d9cd8f04..dbd897b3df 100644 --- a/server/openapi/model_environment.go +++ b/server/openapi/model_variable_set.go @@ -9,34 +9,34 @@ package openapi -type Environment struct { +type VariableSet struct { Id string `json:"id,omitempty"` Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` - Values []EnvironmentValue `json:"values,omitempty"` + Values []VariableSetValue `json:"values,omitempty"` } -// AssertEnvironmentRequired checks if the required fields are not zero-ed -func AssertEnvironmentRequired(obj Environment) error { +// AssertVariableSetRequired checks if the required fields are not zero-ed +func AssertVariableSetRequired(obj VariableSet) error { for _, el := range obj.Values { - if err := AssertEnvironmentValueRequired(el); err != nil { + if err := AssertVariableSetValueRequired(el); err != nil { return err } } return nil } -// AssertRecurseEnvironmentRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of Environment (e.g. [][]Environment), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseEnvironmentRequired(objSlice interface{}) error { +// AssertRecurseVariableSetRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of VariableSet (e.g. [][]VariableSet), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseVariableSetRequired(objSlice interface{}) error { return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aEnvironment, ok := obj.(Environment) + aVariableSet, ok := obj.(VariableSet) if !ok { return ErrTypeAssertionError } - return AssertEnvironmentRequired(aEnvironment) + return AssertVariableSetRequired(aVariableSet) }) } diff --git a/server/openapi/model_variable_set_resource.go b/server/openapi/model_variable_set_resource.go new file mode 100644 index 0000000000..e6965788df --- /dev/null +++ b/server/openapi/model_variable_set_resource.go @@ -0,0 +1,39 @@ +/* + * TraceTest + * + * OpenAPI definition for TraceTest endpoint and resources + * + * API version: 0.2.1 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package openapi + +// VariableSetResource - Represents an VariableSet structured into the Resources format. +type VariableSetResource struct { + + // Represents the type of this resource. It should always be set as 'VariableSet'. + Type string `json:"type,omitempty"` + + Spec VariableSet `json:"spec,omitempty"` +} + +// AssertVariableSetResourceRequired checks if the required fields are not zero-ed +func AssertVariableSetResourceRequired(obj VariableSetResource) error { + if err := AssertVariableSetRequired(obj.Spec); err != nil { + return err + } + return nil +} + +// AssertRecurseVariableSetResourceRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of VariableSetResource (e.g. [][]VariableSetResource), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseVariableSetResourceRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aVariableSetResource, ok := obj.(VariableSetResource) + if !ok { + return ErrTypeAssertionError + } + return AssertVariableSetResourceRequired(aVariableSetResource) + }) +} diff --git a/server/openapi/model_variable_set_resource_list.go b/server/openapi/model_variable_set_resource_list.go new file mode 100644 index 0000000000..0c9c81365b --- /dev/null +++ b/server/openapi/model_variable_set_resource_list.go @@ -0,0 +1,38 @@ +/* + * TraceTest + * + * OpenAPI definition for TraceTest endpoint and resources + * + * API version: 0.2.1 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package openapi + +type VariableSetResourceList struct { + Count int32 `json:"count,omitempty"` + + Items []VariableSetResource `json:"items,omitempty"` +} + +// AssertVariableSetResourceListRequired checks if the required fields are not zero-ed +func AssertVariableSetResourceListRequired(obj VariableSetResourceList) error { + for _, el := range obj.Items { + if err := AssertVariableSetResourceRequired(el); err != nil { + return err + } + } + return nil +} + +// AssertRecurseVariableSetResourceListRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of VariableSetResourceList (e.g. [][]VariableSetResourceList), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseVariableSetResourceListRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aVariableSetResourceList, ok := obj.(VariableSetResourceList) + if !ok { + return ErrTypeAssertionError + } + return AssertVariableSetResourceListRequired(aVariableSetResourceList) + }) +} diff --git a/server/openapi/model_variable_set_value.go b/server/openapi/model_variable_set_value.go new file mode 100644 index 0000000000..68b20486dd --- /dev/null +++ b/server/openapi/model_variable_set_value.go @@ -0,0 +1,33 @@ +/* + * TraceTest + * + * OpenAPI definition for TraceTest endpoint and resources + * + * API version: 0.2.1 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package openapi + +type VariableSetValue struct { + Key string `json:"key,omitempty"` + + Value string `json:"value,omitempty"` +} + +// AssertVariableSetValueRequired checks if the required fields are not zero-ed +func AssertVariableSetValueRequired(obj VariableSetValue) error { + return nil +} + +// AssertRecurseVariableSetValueRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of VariableSetValue (e.g. [][]VariableSetValue), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseVariableSetValueRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aVariableSetValue, ok := obj.(VariableSetValue) + if !ok { + return ErrTypeAssertionError + } + return AssertVariableSetValueRequired(aVariableSetValue) + }) +} diff --git a/server/test/run.go b/server/test/run.go index 6d968f1172..b9317c98bd 100644 --- a/server/test/run.go +++ b/server/test/run.go @@ -5,13 +5,13 @@ import ( "math" "time" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/linter/analyzer" "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/test/trigger" + "github.com/kubeshop/tracetest/server/variableset" ) var ( @@ -108,12 +108,12 @@ func (r Run) SuccessfullyPolledTraces(t *model.Trace) Run { func (r Run) SuccessfullyAsserted( outputs maps.Ordered[string, RunOutput], - environment environment.Environment, + variableSet variableset.VariableSet, res maps.Ordered[SpanQuery, []AssertionResult], allPassed bool, ) Run { r.Outputs = outputs - r.Environment = environment + r.VariableSet = variableSet r.Results = &RunResults{ AllPassed: allPassed, Results: res, diff --git a/server/test/run_repository.go b/server/test/run_repository.go index 546b028e7b..28798d3a73 100644 --- a/server/test/run_repository.go +++ b/server/test/run_repository.go @@ -8,10 +8,10 @@ import ( "strconv" "time" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/sqlutil" + "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -69,8 +69,8 @@ INSERT INTO test_runs ( "metadata", - -- environment - "environment", + -- variable set + "variable_set", -- linter "linter", @@ -106,7 +106,7 @@ INSERT INTO test_runs ( 0, -- fail $12, -- metadata - $13, -- environment + $13, -- variable_set $14, -- linter $15, -- required_gates_result $16 -- tenant_id @@ -136,9 +136,9 @@ func (r *runRepository) CreateRun(ctx context.Context, test Test, run Run) (Run, return Run{}, fmt.Errorf("metadata encoding error: %w", err) } - jsonEnvironment, err := json.Marshal(run.Environment) + jsonVariableSet, err := json.Marshal(run.VariableSet) if err != nil { - return Run{}, fmt.Errorf("environment encoding error: %w", err) + return Run{}, fmt.Errorf("VariableSet encoding error: %w", err) } jsonlinter, err := json.Marshal(run.Linter) @@ -180,7 +180,7 @@ func (r *runRepository) CreateRun(ctx context.Context, test Test, run Run) (Run, jsonTriggerResults, jsonTrace, jsonMetadata, - jsonEnvironment, + jsonVariableSet, jsonlinter, jsonGatesResult, tenantID, @@ -219,7 +219,7 @@ UPDATE test_runs SET "fail" = $14, "metadata" = $15, - "environment" = $18, + "variable_set" = $18, --- linter "linter" = $19, @@ -256,7 +256,7 @@ func (r *runRepository) UpdateRun(ctx context.Context, run Run) error { return fmt.Errorf("encoding error: %w", err) } - jsonEnvironment, err := json.Marshal(run.Environment) + jsonVariableSet, err := json.Marshal(run.VariableSet) if err != nil { return fmt.Errorf("encoding error: %w", err) } @@ -299,7 +299,7 @@ func (r *runRepository) UpdateRun(ctx context.Context, run Run) error { jsonMetadata, run.ID, run.TestID, - jsonEnvironment, + jsonVariableSet, jsonLinter, jsonGatesResult, ) @@ -369,7 +369,7 @@ SELECT "outputs", "last_error", "metadata", - "environment", + "variable_set", -- transaction run transaction_run_steps.transaction_run_id, @@ -467,7 +467,7 @@ func readRunRow(row scanner) (Run, error) { jsonTestResults, jsonTrace, jsonOutputs, - jsonEnvironment, + jsonVariableSet, jsonLinter, jsonGatesResult, jsonMetadata []byte @@ -498,7 +498,7 @@ func readRunRow(row scanner) (Run, error) { &jsonOutputs, &lastError, &jsonMetadata, - &jsonEnvironment, + &jsonVariableSet, &transactionRunID, &transactionID, &jsonLinter, @@ -536,7 +536,7 @@ func readRunRow(row scanner) (Run, error) { err = json.Unmarshal(jsonOutputs, &r.Outputs) if err != nil { // try with raw outputs - var rawOutputs []environment.EnvironmentValue + var rawOutputs []variableset.VariableSetValue err = json.Unmarshal(jsonOutputs, &rawOutputs) for _, value := range rawOutputs { @@ -557,9 +557,9 @@ func readRunRow(row scanner) (Run, error) { return Run{}, fmt.Errorf("cannot parse Metadata: %w", err) } - err = json.Unmarshal(jsonEnvironment, &r.Environment) + err = json.Unmarshal(jsonVariableSet, &r.VariableSet) if err != nil { - return Run{}, fmt.Errorf("cannot parse Environment: %w", err) + return Run{}, fmt.Errorf("cannot parse VariableSet: %w", err) } if jsonGatesResult != nil { diff --git a/server/test/run_test.go b/server/test/run_test.go index fa8beaf52f..258b85e8ac 100644 --- a/server/test/run_test.go +++ b/server/test/run_test.go @@ -5,11 +5,11 @@ import ( "testing" "time" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/linter/analyzer" "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/test" + "github.com/kubeshop/tracetest/server/variableset" "github.com/stretchr/testify/assert" ) @@ -166,12 +166,12 @@ func TestRunRequiredGates(t *testing.T) { t.Run("TestSpecGate", func(t *testing.T) { gates := []testrunner.RequiredGate{testrunner.RequiredGateTestSpecs} outputs := maps.Ordered[string, test.RunOutput]{} - environment := environment.Environment{} + variableSet := variableset.VariableSet{} res := maps.Ordered[test.SpanQuery, []test.AssertionResult]{} allPassed := false run := test.Run{}.ConfigureRequiredGates(gates) - run = run.SuccessfullyAsserted(outputs, environment, res, allPassed) + run = run.SuccessfullyAsserted(outputs, variableSet, res, allPassed) assert.Len(t, run.RequiredGatesResult.Required, 1) assert.Equal(t, false, run.RequiredGatesResult.Passed) diff --git a/server/test/test_entities.go b/server/test/test_entities.go index 3d05354f7b..48d8f50351 100644 --- a/server/test/test_entities.go +++ b/server/test/test_entities.go @@ -4,13 +4,13 @@ import ( "fmt" "time" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/linter/analyzer" "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/test/trigger" + "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -123,8 +123,8 @@ type ( Metadata RunMetadata - // environment - Environment environment.Environment + // variable set + VariableSet variableset.VariableSet // transaction diff --git a/server/transaction/transaction_run_entities.go b/server/transaction/transaction_run_entities.go index c58bd68c1d..0e1cf83fef 100644 --- a/server/transaction/transaction_run_entities.go +++ b/server/transaction/transaction_run_entities.go @@ -4,10 +4,10 @@ import ( "fmt" "time" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/executor/testrunner" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/test" + "github.com/kubeshop/tracetest/server/variableset" ) type TransactionRun struct { @@ -35,8 +35,8 @@ type TransactionRun struct { Metadata test.RunMetadata - // environment - Environment environment.Environment + // variable set + VariableSet variableset.VariableSet RequiredGates *[]testrunner.RequiredGate } diff --git a/server/transaction/transaction_run_repository.go b/server/transaction/transaction_run_repository.go index 56b7e6caa3..79911243f7 100644 --- a/server/transaction/transaction_run_repository.go +++ b/server/transaction/transaction_run_repository.go @@ -53,8 +53,8 @@ INSERT INTO transaction_runs ( "metadata", - -- environment - "environment", + -- variable_set + "variable_set", "tenant_id" ) VALUES ( @@ -77,7 +77,7 @@ INSERT INTO transaction_runs ( TRUE, -- all_steps_required_gates_passed $6, -- metadata - $7, -- environment + $7, -- variable_set $8 -- tenant_id ) RETURNING "id"` @@ -108,9 +108,9 @@ func (td *RunRepository) CreateRun(ctx context.Context, tr TransactionRun) (Tran return TransactionRun{}, fmt.Errorf("failed to marshal transaction run metadata: %w", err) } - jsonEnvironment, err := json.Marshal(tr.Environment) + jsonVariableSet, err := json.Marshal(tr.VariableSet) if err != nil { - return TransactionRun{}, fmt.Errorf("failed to marshal transaction run environment: %w", err) + return TransactionRun{}, fmt.Errorf("failed to marshal transaction run variable set: %w", err) } tx, err := td.db.BeginTx(ctx, nil) @@ -136,7 +136,7 @@ func (td *RunRepository) CreateRun(ctx context.Context, tr TransactionRun) (Tran tr.State, tr.CurrentTest, jsonMetadata, - jsonEnvironment, + jsonVariableSet, tenantID, ).Scan(&runID) if err != nil { @@ -172,8 +172,8 @@ UPDATE transaction_runs SET "metadata" = $8, - -- environment - "environment" = $9 + -- variable_set + "variable_set" = $9 WHERE id = $10 AND transaction_id = $11 ` @@ -189,9 +189,9 @@ func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error return fmt.Errorf("failed to marshal transaction run metadata: %w", err) } - jsonEnvironment, err := json.Marshal(tr.Environment) + jsonVariableSet, err := json.Marshal(tr.VariableSet) if err != nil { - return fmt.Errorf("failed to marshal transaction run environment: %w", err) + return fmt.Errorf("failed to marshal transaction run variableSet: %w", err) } var lastError *string if tr.LastError != nil { @@ -213,7 +213,7 @@ func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error fail, allStepsRequiredGatesPassed, jsonMetadata, - jsonEnvironment, + jsonVariableSet, strconv.Itoa(tr.ID), tr.TransactionID, ) @@ -322,7 +322,7 @@ SELECT "metadata", - "environment" + "variable_set" FROM transaction_runs ` @@ -398,7 +398,7 @@ func (td *RunRepository) readRunRow(row scanner) (TransactionRun, error) { r := TransactionRun{} var ( - jsonEnvironment, + jsonVariableSet, jsonMetadata []byte lastError *string @@ -421,7 +421,7 @@ func (td *RunRepository) readRunRow(row scanner) (TransactionRun, error) { &fail, &allStepsRequiredGatesPassed, &jsonMetadata, - &jsonEnvironment, + &jsonVariableSet, ) if err != nil { return TransactionRun{}, fmt.Errorf("cannot read row: %w", err) @@ -432,9 +432,9 @@ func (td *RunRepository) readRunRow(row scanner) (TransactionRun, error) { return TransactionRun{}, fmt.Errorf("cannot parse Metadata: %w", err) } - err = json.Unmarshal(jsonEnvironment, &r.Environment) + err = json.Unmarshal(jsonVariableSet, &r.VariableSet) if err != nil { - return TransactionRun{}, fmt.Errorf("cannot parse Environment: %w", err) + return TransactionRun{}, fmt.Errorf("cannot parse VariableSet: %w", err) } if lastError != nil && *lastError != "" { diff --git a/server/environment/main_test.go b/server/variableset/main_test.go similarity index 89% rename from server/environment/main_test.go rename to server/variableset/main_test.go index 8ce556f336..2645451c87 100644 --- a/server/environment/main_test.go +++ b/server/variableset/main_test.go @@ -1,4 +1,4 @@ -package environment_test +package variableset_test import ( "os" diff --git a/server/variableset/resource.go b/server/variableset/resource.go new file mode 100644 index 0000000000..f6eb78343b --- /dev/null +++ b/server/variableset/resource.go @@ -0,0 +1,6 @@ +package variableset + +const ( + ResourceName = "VariableSet" + ResourceNamePlural = "VariableSets" +) diff --git a/server/environment/environment_entities.go b/server/variableset/variableset_entities.go similarity index 61% rename from server/environment/environment_entities.go rename to server/variableset/variableset_entities.go index dbe6e08b55..5bf7d2f7e8 100644 --- a/server/environment/environment_entities.go +++ b/server/variableset/variableset_entities.go @@ -1,4 +1,4 @@ -package environment +package variableset import ( "fmt" @@ -8,47 +8,47 @@ import ( ) type ( - Environment struct { + VariableSet struct { ID id.ID `json:"id"` Name string `json:"name"` Description string `json:"description"` CreatedAt string `json:"createdAt"` - Values []EnvironmentValue `json:"values"` + Values []VariableSetValue `json:"values"` } - EnvironmentValue struct { + VariableSetValue struct { Key string `json:"key"` Value string `json:"value"` } ) -func (e Environment) Validate() error { +func (e VariableSet) Validate() error { if e.Name == "" { - return fmt.Errorf("environment name cannot be empty") + return fmt.Errorf("variable set name cannot be empty") } for _, v := range e.Values { if v.Key == "" { - return fmt.Errorf("environment value name cannot be empty") + return fmt.Errorf("variable set value name cannot be empty") } } return nil } -func (e Environment) HasID() bool { +func (e VariableSet) HasID() bool { return e.ID != "" } -func (e Environment) GetID() id.ID { +func (e VariableSet) GetID() id.ID { return e.ID } -func (e Environment) Slug() id.ID { +func (e VariableSet) Slug() id.ID { return id.ID(strings.ToLower(strings.ReplaceAll(strings.TrimSpace(e.Name), " ", "-"))) } -func (e Environment) Get(key string) string { +func (e VariableSet) Get(key string) string { for _, v := range e.Values { if v.Key == key { return v.Value @@ -57,7 +57,7 @@ func (e Environment) Get(key string) string { return "" } -func (e Environment) Merge(env Environment) Environment { +func (e VariableSet) Merge(env VariableSet) VariableSet { values := make(map[string]string) for _, variable := range e.Values { values[variable.Key] = variable.Value @@ -67,9 +67,9 @@ func (e Environment) Merge(env Environment) Environment { values[variable.Key] = variable.Value } - newValues := make([]EnvironmentValue, 0, len(values)) + newValues := make([]VariableSetValue, 0, len(values)) for key, value := range values { - newValues = append(newValues, EnvironmentValue{ + newValues = append(newValues, VariableSetValue{ Key: key, Value: value, }) diff --git a/server/environment/environment_entities_test.go b/server/variableset/variableset_entities_test.go similarity index 56% rename from server/environment/environment_entities_test.go rename to server/variableset/variableset_entities_test.go index eaed9ebef7..f2684af41e 100644 --- a/server/environment/environment_entities_test.go +++ b/server/variableset/variableset_entities_test.go @@ -1,28 +1,28 @@ -package environment_test +package variableset_test import ( "testing" "time" - "github.com/kubeshop/tracetest/server/environment" + "github.com/kubeshop/tracetest/server/variableset" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestEnvironmentMerge(t *testing.T) { - env1 := environment.Environment{ +func TestVariableSetMerge(t *testing.T) { + env1 := variableset.VariableSet{ ID: "my-env", - Name: "my environment", + Name: "my var set", Description: "my description", CreatedAt: time.Now().String(), - Values: []environment.EnvironmentValue{ + Values: []variableset.VariableSetValue{ {Key: "URL", Value: "http://localhost"}, {Key: "PORT", Value: "8085"}, }, } - env2 := environment.Environment{ - Values: []environment.EnvironmentValue{ + env2 := variableset.VariableSet{ + Values: []variableset.VariableSetValue{ {Key: "apiKey", Value: "abcdef"}, {Key: "apiKeyLocation", Value: "header"}, {Key: "URL", Value: "http://my-api.com"}, @@ -37,26 +37,26 @@ func TestEnvironmentMerge(t *testing.T) { assert.Equal(t, env1.CreatedAt, newEnv.CreatedAt) require.Len(t, newEnv.Values, 4) - assert.Contains(t, newEnv.Values, environment.EnvironmentValue{Key: "URL", Value: "http://my-api.com"}) - assert.Contains(t, newEnv.Values, environment.EnvironmentValue{Key: "PORT", Value: "8085"}) - assert.Contains(t, newEnv.Values, environment.EnvironmentValue{Key: "apiKey", Value: "abcdef"}) - assert.Contains(t, newEnv.Values, environment.EnvironmentValue{Key: "apiKeyLocation", Value: "header"}) + assert.Contains(t, newEnv.Values, variableset.VariableSetValue{Key: "URL", Value: "http://my-api.com"}) + assert.Contains(t, newEnv.Values, variableset.VariableSetValue{Key: "PORT", Value: "8085"}) + assert.Contains(t, newEnv.Values, variableset.VariableSetValue{Key: "apiKey", Value: "abcdef"}) + assert.Contains(t, newEnv.Values, variableset.VariableSetValue{Key: "apiKeyLocation", Value: "header"}) } -func TestEnvironmentMergeWithEmptyEnvironment(t *testing.T) { - env1 := environment.Environment{ +func TestVariableSetMergeWithEmptyVariableSet(t *testing.T) { + env1 := variableset.VariableSet{ ID: "my-env", - Name: "my environment", + Name: "my var set", Description: "my description", CreatedAt: time.Now().String(), - Values: []environment.EnvironmentValue{ + Values: []variableset.VariableSetValue{ {Key: "URL", Value: "http://localhost"}, {Key: "PORT", Value: "8085"}, }, } - env2 := environment.Environment{ - Values: []environment.EnvironmentValue{}, + env2 := variableset.VariableSet{ + Values: []variableset.VariableSetValue{}, } newEnv := env1.Merge(env2) diff --git a/server/environment/environment_repository.go b/server/variableset/variableset_repository.go similarity index 60% rename from server/environment/environment_repository.go rename to server/variableset/variableset_repository.go index 23a715ae32..ddf79e6806 100644 --- a/server/environment/environment_repository.go +++ b/server/variableset/variableset_repository.go @@ -1,4 +1,4 @@ -package environment +package variableset import ( "context" @@ -25,7 +25,7 @@ type scanner interface { const ( insertQuery = ` - INSERT INTO environments ( + INSERT INTO variable_sets ( "id", "name", "description", @@ -35,7 +35,7 @@ const ( ) VALUES ($1, $2, $3, $4, $5, $6)` updateQuery = ` - UPDATE environments SET + UPDATE variable_sets SET "name" = $2, "description" = $3, "created_at" = $4, @@ -50,17 +50,17 @@ const ( e.description, e.created_at, e.values - FROM environments e + FROM variable_sets e ` - deleteQuery = "DELETE FROM environments WHERE id = $1" + deleteQuery = "DELETE FROM variable_sets WHERE id = $1" idExistsQuery = ` - SELECT COUNT(*) > 0 as exists FROM environments WHERE id = $1 + SELECT COUNT(*) > 0 as exists FROM variable_sets WHERE id = $1 ` countQuery = ` - SELECT COUNT(*) FROM environments e + SELECT COUNT(*) FROM variable_sets e ` ) @@ -68,31 +68,31 @@ func (*Repository) SortingFields() []string { return []string{"name", "createdAt"} } -func (r *Repository) SetID(environment Environment, id id.ID) Environment { - environment.ID = id - return environment +func (r *Repository) SetID(variableSet VariableSet, id id.ID) VariableSet { + variableSet.ID = id + return variableSet } -func (r *Repository) Create(ctx context.Context, environment Environment) (Environment, error) { - if !environment.HasID() { - environment.ID = environment.Slug() +func (r *Repository) Create(ctx context.Context, variableSet VariableSet) (VariableSet, error) { + if !variableSet.HasID() { + variableSet.ID = variableSet.Slug() } - environment.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano) - return r.insertIntoEnvironments(ctx, environment) + variableSet.CreatedAt = time.Now().UTC().Format(time.RFC3339Nano) + return r.insertIntoEnvironments(ctx, variableSet) } -func (r *Repository) Update(ctx context.Context, environment Environment) (Environment, error) { - oldEnvironment, err := r.Get(ctx, environment.ID) +func (r *Repository) Update(ctx context.Context, variableSet VariableSet) (VariableSet, error) { + oldEnvironment, err := r.Get(ctx, variableSet.ID) if err != nil { - return Environment{}, err + return VariableSet{}, err } // keep the same creation date to keep sort order - environment.CreatedAt = oldEnvironment.CreatedAt - environment.ID = oldEnvironment.ID + variableSet.CreatedAt = oldEnvironment.CreatedAt + variableSet.ID = oldEnvironment.ID - return r.updateIntoEnvironments(ctx, environment, oldEnvironment.ID) + return r.updateIntoEnvironments(ctx, variableSet, oldEnvironment.ID) } func (r *Repository) Delete(ctx context.Context, id id.ID) error { @@ -130,7 +130,7 @@ func listQuery(baseSQL, query string, params []any) (string, []any) { return sql, params } -func (r *Repository) List(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Environment, error) { +func (r *Repository) List(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]VariableSet, error) { if take == 0 { take = 20 } @@ -148,43 +148,43 @@ func (r *Repository) List(ctx context.Context, take, skip int, query, sortBy, so sql, params = sqlutil.Tenant(ctx, sql, params...) stmt, err := r.db.Prepare(sql) if err != nil { - return []Environment{}, err + return []VariableSet{}, err } defer stmt.Close() rows, err := stmt.QueryContext(ctx, params...) if err != nil { - return []Environment{}, err + return []VariableSet{}, err } - environments := []Environment{} + variableSets := []VariableSet{} for rows.Next() { - environment, err := r.readEnvironmentRow(ctx, rows) + variableSet, err := r.readEnvironmentRow(ctx, rows) if err != nil { - return []Environment{}, err + return []VariableSet{}, err } - environments = append(environments, environment) + variableSets = append(variableSets, variableSet) } - return environments, nil + return variableSets, nil } func (r *Repository) Count(ctx context.Context, query string) (int, error) { return r.countEnvironments(ctx, query) } -func (r *Repository) Get(ctx context.Context, id id.ID) (Environment, error) { +func (r *Repository) Get(ctx context.Context, id id.ID) (VariableSet, error) { query, params := sqlutil.Tenant(ctx, getQuery+" WHERE e.id = $1", id) row := r.db.QueryRowContext(ctx, query, params...) - environment, err := r.readEnvironmentRow(ctx, row) + variableSet, err := r.readEnvironmentRow(ctx, row) if err != nil { - return Environment{}, err + return VariableSet{}, err } - return environment, nil + return variableSet, nil } func (r *Repository) Exists(ctx context.Context, id id.ID) (bool, error) { @@ -198,32 +198,32 @@ func (r *Repository) Exists(ctx context.Context, id id.ID) (bool, error) { return exists, err } -func (r *Repository) readEnvironmentRow(ctx context.Context, row scanner) (Environment, error) { - environment := Environment{} +func (r *Repository) readEnvironmentRow(ctx context.Context, row scanner) (VariableSet, error) { + variableSet := VariableSet{} var ( jsonValues []byte ) err := row.Scan( - &environment.ID, - &environment.Name, - &environment.Description, - &environment.CreatedAt, + &variableSet.ID, + &variableSet.Name, + &variableSet.Description, + &variableSet.CreatedAt, &jsonValues, ) switch err { case sql.ErrNoRows: - return Environment{}, err + return VariableSet{}, err case nil: - err = json.Unmarshal(jsonValues, &environment.Values) + err = json.Unmarshal(jsonValues, &variableSet.Values) if err != nil { - return Environment{}, fmt.Errorf("cannot parse environment: %w", err) + return VariableSet{}, fmt.Errorf("cannot parse variableSet: %w", err) } - return environment, nil + return variableSet, nil default: - return Environment{}, err + return VariableSet{}, err } } @@ -247,52 +247,52 @@ func (r *Repository) countEnvironments(ctx context.Context, query string) (int, return count, nil } -func (r *Repository) insertIntoEnvironments(ctx context.Context, environment Environment) (Environment, error) { +func (r *Repository) insertIntoEnvironments(ctx context.Context, variableSet VariableSet) (VariableSet, error) { stmt, err := r.db.Prepare(insertQuery) if err != nil { - return Environment{}, fmt.Errorf("sql prepare: %w", err) + return VariableSet{}, fmt.Errorf("sql prepare: %w", err) } defer stmt.Close() - jsonValues, err := json.Marshal(environment.Values) + jsonValues, err := json.Marshal(variableSet.Values) if err != nil { - return Environment{}, fmt.Errorf("encoding error: %w", err) + return VariableSet{}, fmt.Errorf("encoding error: %w", err) } tenantID := sqlutil.TenantID(ctx) _, err = stmt.ExecContext( ctx, - environment.ID, - environment.Name, - environment.Description, - environment.CreatedAt, + variableSet.ID, + variableSet.Name, + variableSet.Description, + variableSet.CreatedAt, jsonValues, tenantID, ) if err != nil { - return Environment{}, fmt.Errorf("sql exec: %w", err) + return VariableSet{}, fmt.Errorf("sql exec: %w", err) } - return environment, nil + return variableSet, nil } -func (r *Repository) updateIntoEnvironments(ctx context.Context, environment Environment, oldId id.ID) (Environment, error) { - jsonValues, err := json.Marshal(environment.Values) +func (r *Repository) updateIntoEnvironments(ctx context.Context, variableSet VariableSet, oldId id.ID) (VariableSet, error) { + jsonValues, err := json.Marshal(variableSet.Values) if err != nil { - return Environment{}, fmt.Errorf("encoding error: %w", err) + return VariableSet{}, fmt.Errorf("encoding error: %w", err) } tx, err := r.db.BeginTx(ctx, nil) if err != nil { - return Environment{}, err + return VariableSet{}, err } defer tx.Rollback() query, params := sqlutil.Tenant(ctx, updateQuery, oldId, - environment.Name, - environment.Description, - environment.CreatedAt, + variableSet.Name, + variableSet.Description, + variableSet.CreatedAt, jsonValues, ) @@ -302,18 +302,18 @@ func (r *Repository) updateIntoEnvironments(ctx context.Context, environment Env params..., ) if err != nil { - return Environment{}, fmt.Errorf("sql exec: %w", err) + return VariableSet{}, fmt.Errorf("sql exec: %w", err) } err = tx.Commit() if err != nil { - return Environment{}, fmt.Errorf("commit: %w", err) + return VariableSet{}, fmt.Errorf("commit: %w", err) } - return environment, nil + return variableSet, nil } -func (r *Repository) Provision(ctx context.Context, environment Environment) error { - _, err := r.Create(ctx, environment) +func (r *Repository) Provision(ctx context.Context, variableSet VariableSet) error { + _, err := r.Create(ctx, variableSet) return err } diff --git a/server/environment/environment_repository_test.go b/server/variableset/variableset_repository_test.go similarity index 65% rename from server/environment/environment_repository_test.go rename to server/variableset/variableset_repository_test.go index e84fe7225a..98802aa570 100644 --- a/server/environment/environment_repository_test.go +++ b/server/variableset/variableset_repository_test.go @@ -1,4 +1,4 @@ -package environment_test +package variableset_test import ( "context" @@ -7,56 +7,56 @@ import ( "time" "github.com/gorilla/mux" - "github.com/kubeshop/tracetest/server/environment" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/resourcemanager" rmtests "github.com/kubeshop/tracetest/server/resourcemanager/testutil" + "github.com/kubeshop/tracetest/server/variableset" "github.com/stretchr/testify/require" ) -func TestEnvironmentRepository(t *testing.T) { - sampleEnvironment := environment.Environment{ +func TestVariableSetRepository(t *testing.T) { + sampleVariableSet := variableset.VariableSet{ ID: "dev", Name: "dev", Description: "dev variables", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), - Values: []environment.EnvironmentValue{ + Values: []variableset.VariableSetValue{ {Key: "URL", Value: "http://dev-app.com"}, }, } - secondEnvironment := environment.Environment{ + secondVariableSet := variableset.VariableSet{ ID: "new-dev", Name: "new dev", Description: "new dev variables", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), - Values: []environment.EnvironmentValue{ + Values: []variableset.VariableSetValue{ {Key: "URL", Value: "http://dev-app.com"}, {Key: "AUTH", Value: "user:pass"}, }, } - thirdEnvironment := environment.Environment{ + thirdVariableSet := variableset.VariableSet{ ID: "stg", Name: "staging", Description: "staging variables", CreatedAt: time.Now().UTC().Format(time.RFC3339Nano), - Values: []environment.EnvironmentValue{ + Values: []variableset.VariableSetValue{ {Key: "URL", Value: "http://stg-app.com"}, {Key: "AUTH", Value: "user:pass"}, }, } resourceTypeTest := rmtests.ResourceTypeTest{ - ResourceTypeSingular: environment.ResourceName, - ResourceTypePlural: environment.ResourceNamePlural, + ResourceTypeSingular: variableset.ResourceName, + ResourceTypePlural: variableset.ResourceNamePlural, RegisterManagerFn: func(router *mux.Router, db *sql.DB) resourcemanager.Manager { - environmentRepository := environment.NewRepository(db) + variableSetRepository := variableset.NewRepository(db) - manager := resourcemanager.New[environment.Environment]( - environment.ResourceName, - environment.ResourceNamePlural, - environmentRepository, + manager := resourcemanager.New[variableset.VariableSet]( + variableset.ResourceName, + variableset.ResourceNamePlural, + variableSetRepository, resourcemanager.WithIDGen(id.GenerateID), ) manager.RegisterRoutes(router) @@ -64,21 +64,21 @@ func TestEnvironmentRepository(t *testing.T) { return manager }, Prepare: func(t *testing.T, op rmtests.Operation, manager resourcemanager.Manager) { - environmentRepository := manager.Handler().(*environment.Repository) + variableSetRepository := manager.Handler().(*variableset.Repository) switch op { case rmtests.OperationGetSuccess, rmtests.OperationUpdateSuccess, rmtests.OperationDeleteSuccess, rmtests.OperationListSuccess: - environmentRepository.Create(context.TODO(), sampleEnvironment) + variableSetRepository.Create(context.TODO(), sampleVariableSet) case rmtests.OperationListSortSuccess: - environmentRepository.Create(context.TODO(), sampleEnvironment) - environmentRepository.Create(context.TODO(), secondEnvironment) - environmentRepository.Create(context.TODO(), thirdEnvironment) + variableSetRepository.Create(context.TODO(), sampleVariableSet) + variableSetRepository.Create(context.TODO(), secondVariableSet) + variableSetRepository.Create(context.TODO(), thirdVariableSet) } }, SampleJSON: `{ - "type": "Environment", + "type": "VariableSet", "spec": { "id": "dev", "name": "dev", @@ -89,7 +89,7 @@ func TestEnvironmentRepository(t *testing.T) { } }`, SampleJSONUpdated: `{ - "type": "Environment", + "type": "VariableSet", "spec": { "id": "dev", "name": "new-dev", @@ -102,10 +102,10 @@ func TestEnvironmentRepository(t *testing.T) { }`, } - rmtests.TestResourceType(t, resourceTypeTest, rmtests.JSONComparer(environmentJSONComparer)) + rmtests.TestResourceType(t, resourceTypeTest, rmtests.JSONComparer(VariableSetJSONComparer)) } -func environmentJSONComparer(t require.TestingT, operation rmtests.Operation, firstValue, secondValue string) { +func VariableSetJSONComparer(t require.TestingT, operation rmtests.Operation, firstValue, secondValue string) { expected := rmtests.RemoveFieldFromJSONResource("createdAt", firstValue) obtained := rmtests.RemoveFieldFromJSONResource("createdAt", secondValue) diff --git a/testing/cli-e2etest/Makefile b/testing/cli-e2etest/Makefile index 7e4d6a1717..d9e207f756 100644 --- a/testing/cli-e2etest/Makefile +++ b/testing/cli-e2etest/Makefile @@ -3,6 +3,7 @@ TRACETEST_CLI?="${PROJECT_ROOT}/../../dist/tracetest" TEST_ENVIRONMENT?="jaeger" TAG?="dev" ENABLE_CLI_DEBUG?="false" +TEST_SCENARIO?=test help: Makefile ## show list of commands @echo "Choose a command run:" @@ -17,6 +18,14 @@ test: # run tests for this application go clean -testcache; \ go test -v -timeout 300s -p 1 ./...; +test/scenario: # run tests for this application + export TRACETEST_CLI=$(TRACETEST_CLI); \ + export TEST_ENVIRONMENT=$(TEST_ENVIRONMENT); \ + export TAG=$(TAG); \ + export ENABLE_CLI_DEBUG=$(ENABLE_CLI_DEBUG); \ + go clean -testcache; \ + go test -v -timeout 300s -p 1 "$(PROJECT_ROOT)/testscenarios/$(TEST_SCENARIO)"; + test/debug: # run tests for this application with debug mode enabled export ENABLE_CLI_DEBUG="true"; \ make test; diff --git a/testing/cli-e2etest/README.md b/testing/cli-e2etest/README.md index facdbcf921..493bde96d0 100644 --- a/testing/cli-e2etest/README.md +++ b/testing/cli-e2etest/README.md @@ -31,11 +31,11 @@ The main idea is to test every CLI command against the Tracetest server with dif | CLI Command | Test scenarios | | ------------------------------------------------------------------ | -------------- | | `run test -f [test-definition]` | [RunTestWithGrpcTrigger](./testscenarios/test/run_test_with_grpc_trigger_test.go) | -| `run test -f [test-definition] -e [environment-id]` | [RunTestWithHttpTriggerAndEnvironmentFile](./testscenarios/test/run_test_with_http_trigger_and_environment_file_test.go) | -| `run test -f [test-definition] -e [environment-definition]` | [RunTestWithHttpTriggerAndEnvironmentFile](./testscenarios/test/run_test_with_http_trigger_and_environment_file_test.go) | +| `run test -f [test-definition] --vars [variableset-id]` | [RunTestWithHttpTriggerAndVariableSetFile](./testscenarios/test/run_test_with_http_trigger_and_variableset_file_test.go) | +| `run test -f [test-definition] --vars [variableset-definition]` | [RunTestWithHttpTriggerAndVariableSetFile](./testscenarios/test/run_test_with_http_trigger_and_variableset_file_test.go) | | `run transaction -f [transaction-definition]` | [RunTransaction](./testscenarios/transaction//run_transaction_test.go) | -| `run transaction -f [transaction-definition] -e [environment-id]` | | -| `run transaction -f [transaction-definition] -e [environment-definition]` | | +| `run transaction -f [transaction-definition] --vars [variableset-id]` | | +| `run transaction -f [transaction-definition] --vars [variableset-definition]` | | ### Resources: Config @@ -81,23 +81,23 @@ The main idea is to test every CLI command against the Tracetest server with dif | `list demo --skip 1 --take 1` | [ListDemo](./testscenarios/demo/list_demos_test.go) | | `list demo --sortBy name --sortDirection asc` | [ListDemo](./testscenarios/demo/list_demos_test.go) | -### Resources: Environment +### Resources: VariableSet | CLI Command | Test scenarios | | ----------------------------------------------------------- | -------------- | -| `apply environment -f [new-environment-file]` | [ApplyEnvironment](./testscenarios/environment/apply_environment_test.go) | -| `apply environment -f [existing-environment-file]` | [ApplyEnvironment](./testscenarios/environment/apply_environment_test.go) | -| `delete environment --id [existing-id]` | [DeleteEnvironment](./testscenarios/environment/delete_environment_test.go) | -| `delete environment --id [non-existing-id]` | [DeleteEnvironment](./testscenarios/environment/delete_environment_test.go) | -| `get environment --id [non-existing-id]` | [GetEnvironment](./testscenarios/environment/get_environment_test.go), [DeleteEnvironment](./testscenarios/environment/delete_environment_test.go) | -| `get environment --id [existing-id] --output pretty` | [GetEnvironment](./testscenarios/environment/get_environment_test.go) | -| `get environment --id [existing-id] --output json` | [GetEnvironment](./testscenarios/environment/get_environment_test.go) | -| `get environment --id [existing-id] --output yaml` | [GetEnvironment](./testscenarios/environment/get_environment_test.go) | -| `list environment --output pretty` | [ListEnvironment](./testscenarios/environment/list_environments_test.go) | -| `list environment --output json` | [ListEnvironment](./testscenarios/environment/list_environments_test.go) | -| `list environment --output yaml` | [ListEnvironment](./testscenarios/environment/list_environments_test.go) | -| `list environment --skip 1 --take 2` | [ListEnvironment](./testscenarios/environment/list_environments_test.go) | -| `list environment --sortBy name --sortDirection asc` | [ListEnvironment](./testscenarios/environment/list_environments_test.go) | +| `apply variableset -f [new-variableset-file]` | [ApplyVariableSet](./testscenarios/variableset/apply_variableset_test.go) | +| `apply variableset -f [existing-variableset-file]` | [ApplyVariableSet](./testscenarios/variableset/apply_variableset_test.go) | +| `delete variableset --id [existing-id]` | [DeleteVariableSet](./testscenarios/variableset/delete_variableset_test.go) | +| `delete variableset --id [non-existing-id]` | [DeleteVariableSet](./testscenarios/variableset/delete_variableset_test.go) | +| `get variableset --id [non-existing-id]` | [GetVariableSet](./testscenarios/variableset/get_variableset_test.go), [DeleteVariableSet](./testscenarios/variableset/delete_variableset_test.go) | +| `get variableset --id [existing-id] --output pretty` | [GetVariableSet](./testscenarios/variableset/get_variableset_test.go) | +| `get variableset --id [existing-id] --output json` | [GetVariableSet](./testscenarios/variableset/get_variableset_test.go) | +| `get variableset --id [existing-id] --output yaml` | [GetVariableSet](./testscenarios/variableset/get_variableset_test.go) | +| `list variableset --output pretty` | [ListVariableSet](./testscenarios/variableset/list_variableset_test.go) | +| `list variableset --output json` | [ListVariableSet](./testscenarios/variableset/list_variableset_test.go) | +| `list variableset --output yaml` | [ListVariableSet](./testscenarios/variableset/list_variableset_test.go) | +| `list variableset --skip 1 --take 2` | [ListVariableSet](./testscenarios/variableset/list_variableset_test.go) | +| `list variableset --sortBy name --sortDirection asc` | [ListVariableSet](./testscenarios/variableset/list_variableset_test.go) | ### Resources: PollingProfile diff --git a/testing/cli-e2etest/testscenarios/environment/apply_environment_test.go b/testing/cli-e2etest/testscenarios/environment/apply_environment_test.go deleted file mode 100644 index 006b082099..0000000000 --- a/testing/cli-e2etest/testscenarios/environment/apply_environment_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package environment - -import ( - "fmt" - "testing" - - "github.com/kubeshop/tracetest/cli-e2etest/environment" - "github.com/kubeshop/tracetest/cli-e2etest/helpers" - "github.com/kubeshop/tracetest/cli-e2etest/testscenarios/types" - "github.com/kubeshop/tracetest/cli-e2etest/tracetestcli" - "github.com/stretchr/testify/require" -) - -func TestApplyEnvironment(t *testing.T) { - // instantiate require with testing helper - require := require.New(t) - - // setup isolated e2e environment - env := environment.CreateAndStart(t) - defer env.Close(t) - - cliConfig := env.GetCLIConfigPath(t) - - // Given I am a Tracetest CLI user - // And I have my server recently created - - // When I try to set up a new environment - // Then it should be applied with success - newEnvironmentPath := env.GetTestResourcePath(t, "new-environment") - - result := tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - environmentVars := helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) - - require.Equal("Environment", environmentVars.Type) - require.Equal(".env", environmentVars.Spec.ID) - require.Equal(".env", environmentVars.Spec.Name) - require.Len(environmentVars.Spec.Values, 2) - require.Equal("FIRST_VAR", environmentVars.Spec.Values[0].Key) - require.Equal("some-value", environmentVars.Spec.Values[0].Value) - require.Equal("SECOND_VAR", environmentVars.Spec.Values[1].Key) - require.Equal("another_value", environmentVars.Spec.Values[1].Value) - - // When I try to get the environment applied on the last step - // Then it should return it - result = tracetestcli.Exec(t, "get environment --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - environmentVars = helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) - require.Equal("Environment", environmentVars.Type) - require.Equal(".env", environmentVars.Spec.ID) - require.Equal(".env", environmentVars.Spec.Name) - require.Len(environmentVars.Spec.Values, 2) - require.Equal("FIRST_VAR", environmentVars.Spec.Values[0].Key) - require.Equal("some-value", environmentVars.Spec.Values[0].Value) - require.Equal("SECOND_VAR", environmentVars.Spec.Values[1].Key) - require.Equal("another_value", environmentVars.Spec.Values[1].Value) - - // When I try to update the last environment - // Then it should be applied with success - updatedNewEnvironmentPath := env.GetTestResourcePath(t, "updated-new-environment") - - result = tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", updatedNewEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - updatedEnvironmentVars := helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) - require.Equal("Environment", updatedEnvironmentVars.Type) - require.Equal(".env", updatedEnvironmentVars.Spec.ID) - require.Equal(".env", updatedEnvironmentVars.Spec.Name) - require.Len(updatedEnvironmentVars.Spec.Values, 3) - require.Equal("FIRST_VAR", updatedEnvironmentVars.Spec.Values[0].Key) - require.Equal("some-value", updatedEnvironmentVars.Spec.Values[0].Value) - require.Equal("SECOND_VAR", updatedEnvironmentVars.Spec.Values[1].Key) - require.Equal("updated_value", updatedEnvironmentVars.Spec.Values[1].Value) // this value has been updated - require.Equal("THIRD_VAR", updatedEnvironmentVars.Spec.Values[2].Key) - require.Equal("hello", updatedEnvironmentVars.Spec.Values[2].Value) // this value was added - - // When I try to get the environment applied on the last step - // Then it should return it - result = tracetestcli.Exec(t, "get environment --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - updatedEnvironmentVars = helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) - require.Equal("Environment", updatedEnvironmentVars.Type) - require.Equal(".env", updatedEnvironmentVars.Spec.ID) - require.Equal(".env", updatedEnvironmentVars.Spec.Name) - require.Len(updatedEnvironmentVars.Spec.Values, 3) - require.Equal("FIRST_VAR", updatedEnvironmentVars.Spec.Values[0].Key) - require.Equal("some-value", updatedEnvironmentVars.Spec.Values[0].Value) - require.Equal("SECOND_VAR", updatedEnvironmentVars.Spec.Values[1].Key) - require.Equal("updated_value", updatedEnvironmentVars.Spec.Values[1].Value) // this value has been updated - require.Equal("THIRD_VAR", updatedEnvironmentVars.Spec.Values[2].Key) - require.Equal("hello", updatedEnvironmentVars.Spec.Values[2].Value) // this value was added -} diff --git a/testing/cli-e2etest/testscenarios/test/resources/deprecated-environment.yaml b/testing/cli-e2etest/testscenarios/test/resources/deprecated-environment.yaml new file mode 100644 index 0000000000..6cefb8812a --- /dev/null +++ b/testing/cli-e2etest/testscenarios/test/resources/deprecated-environment.yaml @@ -0,0 +1,9 @@ +type: Environment +spec: + id: deprecated-pokeapi-env + name: deprecated-pokeapi-env + values: + - key: POKEMON_NAME + value: snorlax + - key: POKEMON_URL + value: https://assets.pokemon.com/assets/cms2/img/pokedex/full/143.png diff --git a/testing/cli-e2etest/testscenarios/test/resources/environment-file.yaml b/testing/cli-e2etest/testscenarios/test/resources/environment-file.yaml deleted file mode 100644 index a8267a760a..0000000000 --- a/testing/cli-e2etest/testscenarios/test/resources/environment-file.yaml +++ /dev/null @@ -1,9 +0,0 @@ -type: Environment -spec: - id: pokeapi-env - name: pokeapi-env - values: - - key: POKEMON_NAME - value: snorlax - - key: POKEMON_URL - value: https://assets.pokemon.com/assets/cms2/img/pokedex/full/143.png diff --git a/testing/cli-e2etest/testscenarios/test/resources/variableSet-file.yaml b/testing/cli-e2etest/testscenarios/test/resources/variableSet-file.yaml new file mode 100644 index 0000000000..5c334f8810 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/test/resources/variableSet-file.yaml @@ -0,0 +1,9 @@ +type: VariableSet +spec: + id: pokeapi-env + name: pokeapi-env + values: + - key: POKEMON_NAME + value: snorlax + - key: POKEMON_URL + value: https://assets.pokemon.com/assets/cms2/img/pokedex/full/143.png diff --git a/testing/cli-e2etest/testscenarios/test/run_test_test.go b/testing/cli-e2etest/testscenarios/test/run_test_test.go index 7e59e0a04d..d614813b9b 100644 --- a/testing/cli-e2etest/testscenarios/test/run_test_test.go +++ b/testing/cli-e2etest/testscenarios/test/run_test_test.go @@ -37,7 +37,7 @@ func TestRunTransactionInsteadOfTest(t *testing.T) { }) } -func TestRunTestWithHttpTriggerAndEnvironmentFile(t *testing.T) { +func TestRunTestWithHttpTriggerAndVariableSetFile(t *testing.T) { // setup isolated e2e environment env := environment.CreateAndStart(t, environment.WithDataStoreEnabled(), environment.WithPokeshop()) defer env.Close(t) @@ -47,35 +47,35 @@ func TestRunTestWithHttpTriggerAndEnvironmentFile(t *testing.T) { // instantiate require with testing helper require := require.New(t) - t.Run("should pass when using environment definition file", func(t *testing.T) { + t.Run("should pass when using variable set definition file", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created // And the datasource is already set - // When I try to get an environment - // Then it should return a message saying that the environment was not found - result := tracetestcli.Exec(t, "get environment --id pokeapi-env", tracetestcli.WithCLIConfig(cliConfig)) + // When I try to get a variable set + // Then it should return a message saying that the variable set was not found + result := tracetestcli.Exec(t, "get variableset --id pokeapi-env", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - require.Contains(result.StdOut, "Resource environment with ID pokeapi-env not found") + require.Contains(result.StdOut, "Resource variableset with ID pokeapi-env not found") - // When I try to run a test with a http trigger and a environment file + // When I try to run a test with a http trigger and a variable set file // Then it should pass - environmentFile := env.GetTestResourcePath(t, "environment-file") + environmentFile := env.GetTestResourcePath(t, "variableSet-file") testFile := env.GetTestResourcePath(t, "http-trigger-with-environment-file") - command := fmt.Sprintf("run test -f %s --environment %s", testFile, environmentFile) + command := fmt.Sprintf("run test -f %s --vars %s", testFile, environmentFile) result = tracetestcli.Exec(t, command, tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) require.Contains(result.StdOut, "✔ It should add a Pokemon correctly") require.Contains(result.StdOut, "✔ It should save the correct data") - // When I try to get the environment created on the previous step + // When I try to get the variable set created on the previous step // Then it should retrieve it correctly - result = tracetestcli.Exec(t, "get environment --id pokeapi-env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + result = tracetestcli.Exec(t, "get variableset --id pokeapi-env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVars := helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) - require.Equal("Environment", environmentVars.Type) + environmentVars := helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) + require.Equal("VariableSet", environmentVars.Type) require.Equal("pokeapi-env", environmentVars.Spec.ID) require.Equal("pokeapi-env", environmentVars.Spec.Name) require.Len(environmentVars.Spec.Values, 2) @@ -85,20 +85,47 @@ func TestRunTestWithHttpTriggerAndEnvironmentFile(t *testing.T) { require.Equal("https://assets.pokemon.com/assets/cms2/img/pokedex/full/143.png", environmentVars.Spec.Values[1].Value) }) - t.Run("should pass when using environment id", func(t *testing.T) { + t.Run("should pass when using the deprecated environment definition file", func(t *testing.T) { + result := tracetestcli.Exec(t, "get environment --id deprecated-pokeapi-env", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + require.Contains(result.StdOut, "The resource `environment` is deprecated and will be removed in a future version. Please use `variableset` instead.") + require.Contains(result.StdOut, "Resource variableset with ID deprecated-pokeapi-env not found") + + // When I try to run a test with a http trigger and a variable set file + // Then it should pass + environmentFile := env.GetTestResourcePath(t, "deprecated-environment") + testFile := env.GetTestResourcePath(t, "http-trigger-with-environment-file") + + command := fmt.Sprintf("run test -f %s --env %s", testFile, environmentFile) + result = tracetestcli.Exec(t, command, tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + require.Contains(result.StdOut, "✔ It should add a Pokemon correctly") + require.Contains(result.StdOut, "✔ It should save the correct data") + + // When I try to get the variable set created on the previous step + // Then it should retrieve it correctly + result = tracetestcli.Exec(t, "get environment --id deprecated-pokeapi-env", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + require.Contains(result.StdOut, "The resource `environment` is deprecated and will be removed in a future version. Please use `variableset` instead.") + require.Contains(result.StdOut, "VariableSet") + require.Contains(result.StdOut, "https://assets.pokemon.com/assets/cms2/img/pokedex/full/143.png") + }) + + t.Run("should pass when using variable set id", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created // And the datasource is already set - // When I create an environment + // When I create an variable set // Then it should be created correctly - environmentFile := env.GetTestResourcePath(t, "environment-file") + environmentFile := env.GetTestResourcePath(t, "variableSet-file") - result := tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", environmentFile), tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", environmentFile), tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVars := helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) - require.Equal("Environment", environmentVars.Type) + environmentVars := helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) + require.Equal("VariableSet", environmentVars.Type) require.Equal("pokeapi-env", environmentVars.Spec.ID) require.Equal("pokeapi-env", environmentVars.Spec.Name) require.Len(environmentVars.Spec.Values, 2) @@ -107,12 +134,12 @@ func TestRunTestWithHttpTriggerAndEnvironmentFile(t *testing.T) { require.Equal("POKEMON_URL", environmentVars.Spec.Values[1].Key) require.Equal("https://assets.pokemon.com/assets/cms2/img/pokedex/full/143.png", environmentVars.Spec.Values[1].Value) - // When I try to run a test with a http trigger and a environment id + // When I try to run a test with a http trigger and a variable set id // Then it should pass testFile := env.GetTestResourcePath(t, "http-trigger-with-environment-file") - command := fmt.Sprintf("run test -f %s --environment pokeapi-env", testFile) + command := fmt.Sprintf("run test -f %s --vars pokeapi-env", testFile) result = tracetestcli.Exec(t, command, tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) require.Contains(result.StdOut, "✔ It should add a Pokemon correctly") diff --git a/testing/cli-e2etest/testscenarios/types/environment.go b/testing/cli-e2etest/testscenarios/types/environment.go index 2a9bc88a40..ec9859ba5b 100644 --- a/testing/cli-e2etest/testscenarios/types/environment.go +++ b/testing/cli-e2etest/testscenarios/types/environment.go @@ -3,18 +3,18 @@ package types // Note: these types are very similar to the types on the server folder // however they are defined here to avoid bias with the current implementation -type EnvironmentKeyValue struct { +type VariableSetKeyValue struct { Key string `json:"key"` Value string `json:"value"` } -type Environment struct { +type VariableSet struct { ID string `json:"id"` Name string `json:"name"` - Values []EnvironmentKeyValue `json:"values"` + Values []VariableSetKeyValue `json:"values"` } -type EnvironmentResource struct { +type VariableSetResource struct { Type string `json:"type"` - Spec Environment `json:"spec"` + Spec VariableSet `json:"spec"` } diff --git a/testing/cli-e2etest/testscenarios/variableset/apply_variableset_test.go b/testing/cli-e2etest/testscenarios/variableset/apply_variableset_test.go new file mode 100644 index 0000000000..8a5a2b92dd --- /dev/null +++ b/testing/cli-e2etest/testscenarios/variableset/apply_variableset_test.go @@ -0,0 +1,109 @@ +package variableset + +import ( + "fmt" + "testing" + + "github.com/kubeshop/tracetest/cli-e2etest/environment" + "github.com/kubeshop/tracetest/cli-e2etest/helpers" + "github.com/kubeshop/tracetest/cli-e2etest/testscenarios/types" + "github.com/kubeshop/tracetest/cli-e2etest/tracetestcli" + "github.com/stretchr/testify/require" +) + +func TestApplyVariableSet(t *testing.T) { + // instantiate require with testing helper + require := require.New(t) + + // setup isolated e2e environment + env := environment.CreateAndStart(t) + defer env.Close(t) + + cliConfig := env.GetCLIConfigPath(t) + + t.Run("When I try to set up a new variable set", func(t *testing.T) { + // Given I am a Tracetest CLI user + // And I have my server recently created + + // When I try to set up a new variable set + // Then it should be applied with success + newEnvironmentPath := env.GetTestResourcePath(t, "new-varSet") + + result := tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + environmentVars := helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) + + require.Equal("VariableSet", environmentVars.Type) + require.Equal(".env", environmentVars.Spec.ID) + require.Equal(".env", environmentVars.Spec.Name) + require.Len(environmentVars.Spec.Values, 2) + require.Equal("FIRST_VAR", environmentVars.Spec.Values[0].Key) + require.Equal("some-value", environmentVars.Spec.Values[0].Value) + require.Equal("SECOND_VAR", environmentVars.Spec.Values[1].Key) + require.Equal("another_value", environmentVars.Spec.Values[1].Value) + + // When I try to get the variable set applied on the last step + // Then it should return it + result = tracetestcli.Exec(t, "get variableset --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + environmentVars = helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) + require.Equal("VariableSet", environmentVars.Type) + require.Equal(".env", environmentVars.Spec.ID) + require.Equal(".env", environmentVars.Spec.Name) + require.Len(environmentVars.Spec.Values, 2) + require.Equal("FIRST_VAR", environmentVars.Spec.Values[0].Key) + require.Equal("some-value", environmentVars.Spec.Values[0].Value) + require.Equal("SECOND_VAR", environmentVars.Spec.Values[1].Key) + require.Equal("another_value", environmentVars.Spec.Values[1].Value) + }) + + t.Run("When I try to update the last environment", func(t *testing.T) { + // Then it should be applied with success + updatedNewEnvironmentPath := env.GetTestResourcePath(t, "updated-new-varSet") + + result := tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", updatedNewEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + updatedEnvironmentVars := helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) + require.Equal("VariableSet", updatedEnvironmentVars.Type) + require.Equal(".env", updatedEnvironmentVars.Spec.ID) + require.Equal(".env", updatedEnvironmentVars.Spec.Name) + require.Len(updatedEnvironmentVars.Spec.Values, 3) + require.Equal("FIRST_VAR", updatedEnvironmentVars.Spec.Values[0].Key) + require.Equal("some-value", updatedEnvironmentVars.Spec.Values[0].Value) + require.Equal("SECOND_VAR", updatedEnvironmentVars.Spec.Values[1].Key) + require.Equal("updated_value", updatedEnvironmentVars.Spec.Values[1].Value) // this value has been updated + require.Equal("THIRD_VAR", updatedEnvironmentVars.Spec.Values[2].Key) + require.Equal("hello", updatedEnvironmentVars.Spec.Values[2].Value) // this value was added + + // When I try to get the variable set applied on the last step + // Then it should return it + result = tracetestcli.Exec(t, "get variableset --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + updatedEnvironmentVars = helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) + require.Equal("VariableSet", updatedEnvironmentVars.Type) + require.Equal(".env", updatedEnvironmentVars.Spec.ID) + require.Equal(".env", updatedEnvironmentVars.Spec.Name) + require.Len(updatedEnvironmentVars.Spec.Values, 3) + require.Equal("FIRST_VAR", updatedEnvironmentVars.Spec.Values[0].Key) + require.Equal("some-value", updatedEnvironmentVars.Spec.Values[0].Value) + require.Equal("SECOND_VAR", updatedEnvironmentVars.Spec.Values[1].Key) + require.Equal("updated_value", updatedEnvironmentVars.Spec.Values[1].Value) // this value has been updated + require.Equal("THIRD_VAR", updatedEnvironmentVars.Spec.Values[2].Key) + require.Equal("hello", updatedEnvironmentVars.Spec.Values[2].Value) // this value was added + }) + + t.Run("using the deprecated environment command to apply a variable set", func(t *testing.T) { + newEnvironmentPath := env.GetTestResourcePath(t, "deprecated-environment") + + result := tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + require.Contains(result.StdOut, "The resource `environment` is deprecated and will be removed in a future version. Please use `variableset` instead.") + require.Contains(result.StdOut, "VariableSet") + require.Contains(result.StdOut, "deprecated-env") + }) +} diff --git a/testing/cli-e2etest/testscenarios/environment/delete_environment_test.go b/testing/cli-e2etest/testscenarios/variableset/delete_variableset_test.go similarity index 64% rename from testing/cli-e2etest/testscenarios/environment/delete_environment_test.go rename to testing/cli-e2etest/testscenarios/variableset/delete_variableset_test.go index 343d56353d..69883dfa1d 100644 --- a/testing/cli-e2etest/testscenarios/environment/delete_environment_test.go +++ b/testing/cli-e2etest/testscenarios/variableset/delete_variableset_test.go @@ -1,4 +1,4 @@ -package environment +package variableset import ( "fmt" @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestDeleteEnvironment(t *testing.T) { +func TestDeleteVariableSet(t *testing.T) { // instantiate require with testing helper require := require.New(t) @@ -24,32 +24,32 @@ func TestDeleteEnvironment(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created - // When I try to delete an environment that don't exist + // When I try to delete an variable set that don't exist // Then it should return an error and say that this resource does not exist - result := tracetestcli.Exec(t, "delete environment --id .env", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "delete variableset --id .env", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 1) - require.Contains(result.StdErr, "Resource environment with ID .env not found") + require.Contains(result.StdErr, "Resource variableset with ID .env not found") // When I try to set up a new environment // Then it should be applied with success - newEnvironmentPath := env.GetTestResourcePath(t, "new-environment") + newEnvironmentPath := env.GetTestResourcePath(t, "new-varSet") - result = tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + result = tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVars := helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) - require.Equal("Environment", environmentVars.Type) + environmentVars := helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) + require.Equal("VariableSet", environmentVars.Type) require.Equal(".env", environmentVars.Spec.ID) // When I try to delete the environment // Then it should delete with success - result = tracetestcli.Exec(t, "delete environment --id .env", tracetestcli.WithCLIConfig(cliConfig)) + result = tracetestcli.Exec(t, "delete variableset --id .env", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - require.Contains(result.StdOut, "✔ Environment successfully deleted") + require.Contains(result.StdOut, "✔ Variableset successfully deleted") // When I try to get an environment again // Then it should return a message saying that the environment was not found - result = tracetestcli.Exec(t, "get environment --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + result = tracetestcli.Exec(t, "get variableset --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - require.Contains(result.StdOut, "Resource environment with ID .env not found") + require.Contains(result.StdOut, "Resource variableset with ID .env not found") } diff --git a/testing/cli-e2etest/testscenarios/environment/get_environment_test.go b/testing/cli-e2etest/testscenarios/variableset/get_variableset_test.go similarity index 63% rename from testing/cli-e2etest/testscenarios/environment/get_environment_test.go rename to testing/cli-e2etest/testscenarios/variableset/get_variableset_test.go index c6bc7fa33d..6961712bde 100644 --- a/testing/cli-e2etest/testscenarios/environment/get_environment_test.go +++ b/testing/cli-e2etest/testscenarios/variableset/get_variableset_test.go @@ -1,4 +1,4 @@ -package environment +package variableset import ( "fmt" @@ -11,21 +11,21 @@ import ( "github.com/stretchr/testify/require" ) -func addGetEnvironmentPreReqs(t *testing.T, env environment.Manager) { +func addGetVariableSetPreReqs(t *testing.T, env environment.Manager) { cliConfig := env.GetCLIConfigPath(t) // Given I am a Tracetest CLI user // And I have my server recently created - // When I try to set up a new environment + // When I try to set up a new variable set // Then it should be applied with success - newEnvironmentPath := env.GetTestResourcePath(t, "new-environment") + newEnvironmentPath := env.GetTestResourcePath(t, "new-varSet") - result := tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) } -func TestGetEnvironment(t *testing.T) { +func TestGetVariableSet(t *testing.T) { // instantiate require with testing helper require := require.New(t) @@ -34,33 +34,33 @@ func TestGetEnvironment(t *testing.T) { cliConfig := env.GetCLIConfigPath(t) - t.Run("get with no environment initialized", func(t *testing.T) { + t.Run("get with no variable set initialized", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created // And no environment registered // When I try to get a environment on yaml mode // Then it should return a error message - result := tracetestcli.Exec(t, "get environment --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "get variableset --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - require.Contains(result.StdOut, "Resource environment with ID .env not found") + require.Contains(result.StdOut, "Resource variableset with ID .env not found") }) - addGetEnvironmentPreReqs(t, env) + addGetVariableSetPreReqs(t, env) t.Run("get with YAML format", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created - // And I have an environment already set + // And I have an variable set already set - // When I try to get an environment on yaml mode + // When I try to get an variable set on yaml mode // Then it should print a YAML - result := tracetestcli.Exec(t, "get environment --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "get variableset --id .env --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVars := helpers.UnmarshalYAML[types.EnvironmentResource](t, result.StdOut) + environmentVars := helpers.UnmarshalYAML[types.VariableSetResource](t, result.StdOut) - require.Equal("Environment", environmentVars.Type) + require.Equal("VariableSet", environmentVars.Type) require.Equal(".env", environmentVars.Spec.ID) require.Equal(".env", environmentVars.Spec.Name) require.Len(environmentVars.Spec.Values, 2) @@ -73,16 +73,16 @@ func TestGetEnvironment(t *testing.T) { t.Run("get with JSON format", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created - // And I have an environment already set + // And I have an variable set already set - // When I try to get an environment on json mode + // When I try to get an variable set on json mode // Then it should print a json - result := tracetestcli.Exec(t, "get environment --id .env --output json", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "get variableset --id .env --output json", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVars := helpers.UnmarshalJSON[types.EnvironmentResource](t, result.StdOut) + environmentVars := helpers.UnmarshalJSON[types.VariableSetResource](t, result.StdOut) - require.Equal("Environment", environmentVars.Type) + require.Equal("VariableSet", environmentVars.Type) require.Equal(".env", environmentVars.Spec.ID) require.Equal(".env", environmentVars.Spec.Name) require.Len(environmentVars.Spec.Values, 2) @@ -95,11 +95,11 @@ func TestGetEnvironment(t *testing.T) { t.Run("get with pretty format", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created - // And I have an environment already set + // And I have an variable set already set - // When I try to get an environment on pretty mode - // Then it should print a table with 4 lines printed: header, separator, environment item and empty line - result := tracetestcli.Exec(t, "get environment --id .env --output pretty", tracetestcli.WithCLIConfig(cliConfig)) + // When I try to get an variable set on pretty mode + // Then it should print a table with 4 lines printed: header, separator, variable set item and empty line + result := tracetestcli.Exec(t, "get variableset --id .env --output pretty", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) parsedTable := helpers.UnmarshalTable(t, result.StdOut) @@ -111,4 +111,13 @@ func TestGetEnvironment(t *testing.T) { require.Equal(".env", singleLine["NAME"]) require.Equal("", singleLine["DESCRIPTION"]) }) + + t.Run("getting a variable set using the deprecated environment command", func(t *testing.T) { + result := tracetestcli.Exec(t, "get environment --id .env", tracetestcli.WithCLIConfig(cliConfig)) + + helpers.RequireExitCodeEqual(t, result, 0) + require.Contains(result.StdOut, "The resource `environment` is deprecated and will be removed in a future version. Please use `variableset` instead.") + require.Contains(result.StdOut, "VariableSet") + require.Contains(result.StdOut, ".env") + }) } diff --git a/testing/cli-e2etest/testscenarios/environment/list_environments_test.go b/testing/cli-e2etest/testscenarios/variableset/list_variablesets_test.go similarity index 78% rename from testing/cli-e2etest/testscenarios/environment/list_environments_test.go rename to testing/cli-e2etest/testscenarios/variableset/list_variablesets_test.go index 4334addc8c..54afb2afa2 100644 --- a/testing/cli-e2etest/testscenarios/environment/list_environments_test.go +++ b/testing/cli-e2etest/testscenarios/variableset/list_variablesets_test.go @@ -1,4 +1,4 @@ -package environment +package variableset import ( "fmt" @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -func addListEnvironmentsPreReqs(t *testing.T, env environment.Manager) { +func addListVariableSetPreReqs(t *testing.T, env environment.Manager) { cliConfig := env.GetCLIConfigPath(t) // Given I am a Tracetest CLI user @@ -19,27 +19,27 @@ func addListEnvironmentsPreReqs(t *testing.T, env environment.Manager) { // When I try to set up a new environment // Then it should be applied with success - newEnvironmentPath := env.GetTestResourcePath(t, "new-environment") + newEnvironmentPath := env.GetTestResourcePath(t, "new-varSet") - result := tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", newEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) // When I try to set up a another environment // Then it should be applied with success - anotherEnvironmentPath := env.GetTestResourcePath(t, "another-environment") + anotherEnvironmentPath := env.GetTestResourcePath(t, "another-varSet") - result = tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", anotherEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + result = tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", anotherEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) // When I try to set up a third environment // Then it should be applied with success - oneMoreEnvironmentPath := env.GetTestResourcePath(t, "one-more-environment") + oneMoreEnvironmentPath := env.GetTestResourcePath(t, "one-more-varSet") - result = tracetestcli.Exec(t, fmt.Sprintf("apply environment --file %s", oneMoreEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) + result = tracetestcli.Exec(t, fmt.Sprintf("apply variableset --file %s", oneMoreEnvironmentPath), tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) } -func TestListEnvironments(t *testing.T) { +func TestListVariableSets(t *testing.T) { // instantiate require with testing helper require := require.New(t) @@ -49,26 +49,26 @@ func TestListEnvironments(t *testing.T) { cliConfig := env.GetCLIConfigPath(t) - t.Run("list no environments", func(t *testing.T) { + t.Run("list no variable sets", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created - // And there is no envs - result := tracetestcli.Exec(t, "list environment --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + // And there is no variable sets + result := tracetestcli.Exec(t, "list variableset --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVarsList := helpers.UnmarshalYAMLSequence[types.EnvironmentResource](t, result.StdOut) + environmentVarsList := helpers.UnmarshalYAMLSequence[types.VariableSetResource](t, result.StdOut) require.Len(environmentVarsList, 0) }) - addListEnvironmentsPreReqs(t, env) + addListVariableSetPreReqs(t, env) t.Run("list with invalid sortBy field", func(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created - // When I try to list these environments by an invalid field + // When I try to list these variable set by an invalid field // Then I should receive an error - result := tracetestcli.Exec(t, "list environment --sortBy id --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "list variableset --sortBy id --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 1) require.Contains(result.StdErr, "invalid sort field: id") // TODO: think on how to improve this error handling }) @@ -77,18 +77,18 @@ func TestListEnvironments(t *testing.T) { // Given I am a Tracetest CLI user // And I have my server recently created - // When I try to list these environments by a valid field and in YAML format - // Then I should receive three environments - result := tracetestcli.Exec(t, "list environment --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + // When I try to list these variable sets by a valid field and in YAML format + // Then I should receive three variable sets + result := tracetestcli.Exec(t, "list variableset --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVarsList := helpers.UnmarshalYAMLSequence[types.EnvironmentResource](t, result.StdOut) + environmentVarsList := helpers.UnmarshalYAMLSequence[types.VariableSetResource](t, result.StdOut) require.Len(environmentVarsList, 3) // due our database sorting algorithm, "another-env" comes in the front of ".env" // ref https://wiki.postgresql.org/wiki/FAQ#Why_do_my_strings_sort_incorrectly.3F anotherEnvironmentVars := environmentVarsList[0] - require.Equal("Environment", anotherEnvironmentVars.Type) + require.Equal("VariableSet", anotherEnvironmentVars.Type) require.Equal("another-env", anotherEnvironmentVars.Spec.ID) require.Equal("another-env", anotherEnvironmentVars.Spec.Name) require.Len(anotherEnvironmentVars.Spec.Values, 2) @@ -98,7 +98,7 @@ func TestListEnvironments(t *testing.T) { require.Equal("Again", anotherEnvironmentVars.Spec.Values[1].Value) environmentVars := environmentVarsList[1] - require.Equal("Environment", environmentVars.Type) + require.Equal("VariableSet", environmentVars.Type) require.Equal(".env", environmentVars.Spec.ID) require.Equal(".env", environmentVars.Spec.Name) require.Len(environmentVars.Spec.Values, 2) @@ -108,7 +108,7 @@ func TestListEnvironments(t *testing.T) { require.Equal("another_value", environmentVars.Spec.Values[1].Value) oneMoreEnvironmentVars := environmentVarsList[2] - require.Equal("Environment", oneMoreEnvironmentVars.Type) + require.Equal("VariableSet", oneMoreEnvironmentVars.Type) require.Equal("one-more-env", oneMoreEnvironmentVars.Spec.ID) require.Equal("one-more-env", oneMoreEnvironmentVars.Spec.Name) require.Len(oneMoreEnvironmentVars.Spec.Values, 2) @@ -124,17 +124,17 @@ func TestListEnvironments(t *testing.T) { // When I try to list these environments by a valid field and in JSON format // Then I should receive three environments - result := tracetestcli.Exec(t, "list environment --sortBy name --sortDirection asc --output json", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "list variableset --sortBy name --sortDirection asc --output json", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVarsList := helpers.UnmarshalJSON[types.ResourceList[types.EnvironmentResource]](t, result.StdOut) + environmentVarsList := helpers.UnmarshalJSON[types.ResourceList[types.VariableSetResource]](t, result.StdOut) require.Equal(3, environmentVarsList.Count) require.Len(environmentVarsList.Items, 3) // due our database sorting algorithm, "another-env" comes in the front of ".env" // ref https://wiki.postgresql.org/wiki/FAQ#Why_do_my_strings_sort_incorrectly.3F anotherEnvironmentVars := environmentVarsList.Items[0] - require.Equal("Environment", anotherEnvironmentVars.Type) + require.Equal("VariableSet", anotherEnvironmentVars.Type) require.Equal("another-env", anotherEnvironmentVars.Spec.ID) require.Equal("another-env", anotherEnvironmentVars.Spec.Name) require.Len(anotherEnvironmentVars.Spec.Values, 2) @@ -144,7 +144,7 @@ func TestListEnvironments(t *testing.T) { require.Equal("Again", anotherEnvironmentVars.Spec.Values[1].Value) environmentVars := environmentVarsList.Items[1] - require.Equal("Environment", environmentVars.Type) + require.Equal("VariableSet", environmentVars.Type) require.Equal(".env", environmentVars.Spec.ID) require.Equal(".env", environmentVars.Spec.Name) require.Len(environmentVars.Spec.Values, 2) @@ -154,7 +154,7 @@ func TestListEnvironments(t *testing.T) { require.Equal("another_value", environmentVars.Spec.Values[1].Value) oneMoreEnvironmentVars := environmentVarsList.Items[2] - require.Equal("Environment", oneMoreEnvironmentVars.Type) + require.Equal("VariableSet", oneMoreEnvironmentVars.Type) require.Equal("one-more-env", oneMoreEnvironmentVars.Spec.ID) require.Equal("one-more-env", oneMoreEnvironmentVars.Spec.Name) require.Len(oneMoreEnvironmentVars.Spec.Values, 2) @@ -170,7 +170,7 @@ func TestListEnvironments(t *testing.T) { // When I try to list these environments by a valid field and in pretty format // Then it should print a table with 6 lines printed: header, separator, three envs and empty line - result := tracetestcli.Exec(t, "list environment --sortBy name --sortDirection asc --output pretty", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "list variableset --sortBy name --sortDirection asc --output pretty", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) // due our database sorting algorithm, "another-env" comes in the front of ".env" @@ -203,16 +203,16 @@ func TestListEnvironments(t *testing.T) { // When I try to list these environments by a valid field, paging options and in YAML format // Then I should receive two environments - result := tracetestcli.Exec(t, "list environment --sortBy name --sortDirection asc --skip 1 --take 2 --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + result := tracetestcli.Exec(t, "list variableset --sortBy name --sortDirection asc --skip 1 --take 2 --output yaml", tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - environmentVarsList := helpers.UnmarshalYAMLSequence[types.EnvironmentResource](t, result.StdOut) + environmentVarsList := helpers.UnmarshalYAMLSequence[types.VariableSetResource](t, result.StdOut) require.Len(environmentVarsList, 2) // due our database sorting algorithm, "another-env" comes in the front of ".env" // ref https://wiki.postgresql.org/wiki/FAQ#Why_do_my_strings_sort_incorrectly.3F environmentVars := environmentVarsList[0] - require.Equal("Environment", environmentVars.Type) + require.Equal("VariableSet", environmentVars.Type) require.Equal(".env", environmentVars.Spec.ID) require.Equal(".env", environmentVars.Spec.Name) require.Len(environmentVars.Spec.Values, 2) @@ -222,7 +222,7 @@ func TestListEnvironments(t *testing.T) { require.Equal("another_value", environmentVars.Spec.Values[1].Value) oneMoreEnvironmentVars := environmentVarsList[1] - require.Equal("Environment", oneMoreEnvironmentVars.Type) + require.Equal("VariableSet", oneMoreEnvironmentVars.Type) require.Equal("one-more-env", oneMoreEnvironmentVars.Spec.ID) require.Equal("one-more-env", oneMoreEnvironmentVars.Spec.Name) require.Len(oneMoreEnvironmentVars.Spec.Values, 2) @@ -231,4 +231,12 @@ func TestListEnvironments(t *testing.T) { require.Equal("The", oneMoreEnvironmentVars.Spec.Values[1].Key) require.Equal("Third", oneMoreEnvironmentVars.Spec.Values[1].Value) }) + + t.Run("list using deprecated environment command", func(t *testing.T) { + result := tracetestcli.Exec(t, "list environment --sortBy name --sortDirection asc --skip 1 --take 2 --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + + helpers.RequireExitCodeEqual(t, result, 0) + require.Contains(result.StdOut, "The resource `environment` is deprecated and will be removed in a future version. Please use `variableset` instead.") + require.Contains(result.StdOut, "VariableSet") + }) } diff --git a/testing/cli-e2etest/testscenarios/environment/resources/another-environment.yaml b/testing/cli-e2etest/testscenarios/variableset/resources/another-varSet.yaml similarity index 86% rename from testing/cli-e2etest/testscenarios/environment/resources/another-environment.yaml rename to testing/cli-e2etest/testscenarios/variableset/resources/another-varSet.yaml index 06cb30c1ad..d72f8a0196 100644 --- a/testing/cli-e2etest/testscenarios/environment/resources/another-environment.yaml +++ b/testing/cli-e2etest/testscenarios/variableset/resources/another-varSet.yaml @@ -1,4 +1,4 @@ -type: Environment +type: VariableSet spec: id: another-env name: another-env diff --git a/testing/cli-e2etest/testscenarios/variableset/resources/deprecated-environment.yaml b/testing/cli-e2etest/testscenarios/variableset/resources/deprecated-environment.yaml new file mode 100644 index 0000000000..04e876af9e --- /dev/null +++ b/testing/cli-e2etest/testscenarios/variableset/resources/deprecated-environment.yaml @@ -0,0 +1,9 @@ +type: Environment +spec: + id: deprecated-env + name: deprecated-env + values: + - key: FIRST_VAR + value: some-value + - key: SECOND_VAR + value: another_value diff --git a/testing/cli-e2etest/testscenarios/environment/resources/new-environment.yaml b/testing/cli-e2etest/testscenarios/variableset/resources/new-varSet.yaml similarity index 87% rename from testing/cli-e2etest/testscenarios/environment/resources/new-environment.yaml rename to testing/cli-e2etest/testscenarios/variableset/resources/new-varSet.yaml index 9d7af611d3..376bc97b2c 100644 --- a/testing/cli-e2etest/testscenarios/environment/resources/new-environment.yaml +++ b/testing/cli-e2etest/testscenarios/variableset/resources/new-varSet.yaml @@ -1,4 +1,4 @@ -type: Environment +type: VariableSet spec: id: .env name: .env diff --git a/testing/cli-e2etest/testscenarios/environment/resources/one-more-environment.yaml b/testing/cli-e2etest/testscenarios/variableset/resources/one-more-varSet.yaml similarity index 86% rename from testing/cli-e2etest/testscenarios/environment/resources/one-more-environment.yaml rename to testing/cli-e2etest/testscenarios/variableset/resources/one-more-varSet.yaml index 122cca0822..f319095475 100644 --- a/testing/cli-e2etest/testscenarios/environment/resources/one-more-environment.yaml +++ b/testing/cli-e2etest/testscenarios/variableset/resources/one-more-varSet.yaml @@ -1,4 +1,4 @@ -type: Environment +type: VariableSet spec: id: one-more-env name: one-more-env diff --git a/testing/cli-e2etest/testscenarios/environment/resources/updated-new-environment.yaml b/testing/cli-e2etest/testscenarios/variableset/resources/updated-new-varSet.yaml similarity index 90% rename from testing/cli-e2etest/testscenarios/environment/resources/updated-new-environment.yaml rename to testing/cli-e2etest/testscenarios/variableset/resources/updated-new-varSet.yaml index 20a7a69c56..86fb622c5e 100644 --- a/testing/cli-e2etest/testscenarios/environment/resources/updated-new-environment.yaml +++ b/testing/cli-e2etest/testscenarios/variableset/resources/updated-new-varSet.yaml @@ -1,4 +1,4 @@ -type: Environment +type: VariableSet spec: id: .env name: .env diff --git a/testing/server-tracetesting/features/environment/_test_suite.yml b/testing/server-tracetesting/features/environment/_test_suite.yml deleted file mode 100644 index 9af254e327..0000000000 --- a/testing/server-tracetesting/features/environment/_test_suite.yml +++ /dev/null @@ -1,12 +0,0 @@ -type: Transaction -spec: - id: oCkH6vQ4gV - name: Environment Feature - description: Sequence of tests to validate if our Environment feature is working as expected - steps: - # create an environment - - ./01_create_environment.yml - # check if this environment is listed on API - - ./02_list_environment.yml - # delete environment - - ./03_delete_environment.yml diff --git a/testing/server-tracetesting/features/environment/01_create_environment.yml b/testing/server-tracetesting/features/variableset/01_create_variableset.yml similarity index 73% rename from testing/server-tracetesting/features/environment/01_create_environment.yml rename to testing/server-tracetesting/features/variableset/01_create_variableset.yml index 452d34f481..ebba7fe77c 100644 --- a/testing/server-tracetesting/features/environment/01_create_environment.yml +++ b/testing/server-tracetesting/features/variableset/01_create_variableset.yml @@ -1,22 +1,22 @@ type: Test spec: id: oCzNeDQVRI - name: Create Environment - description: Test step of 'Environment Feature - Test Suite' + name: Create Variable Set + description: Test step of 'Variable Set Feature - Test Suite' trigger: type: http httpRequest: - url: ${env:TARGET_URL}/api/environments + url: ${env:TARGET_URL}/api/variablesets method: POST headers: - key: Content-Type value: application/json body: | { - "type": "Environment", + "type": "VariableSet", "spec": { - "name": "test-environment", - "description": "test-environment", + "name": "test-variable-set", + "description": "test-variable-set", "values": [ { "key": "HOST", @@ -35,8 +35,8 @@ spec: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 201 # ensure we can reference outputs declared in the same test - - attr:tracetest.response.body | json_path '$.spec.id' = env:ENVIRONMENT_ID - - selector: span[name="POST /api/environments" tracetest.span.type="http"] + - attr:tracetest.response.body | json_path '$.spec.id' = env:VARIABLE_SET_ID + - selector: span[name="POST /api/variablesets" tracetest.span.type="http"] assertions: - attr:tracetest.selected_spans.count = 1 - selector: span[name = "exec INSERT"] @@ -44,8 +44,8 @@ spec: - attr:tracetest.selected_spans.count = 1 - selector: span[name = "exec INSERT"]:first assertions: - - attr:sql.query contains "INSERT INTO environments" + - attr:sql.query contains "INSERT INTO variable_sets" outputs: - - name: ENVIRONMENT_ID + - name: VARIABLE_SET_ID selector: span[name = "Tracetest trigger"] value: attr:tracetest.response.body | json_path '$.spec.id' diff --git a/testing/server-tracetesting/features/environment/02_list_environment.yml b/testing/server-tracetesting/features/variableset/02_list_variableset.yml similarity index 68% rename from testing/server-tracetesting/features/environment/02_list_environment.yml rename to testing/server-tracetesting/features/variableset/02_list_variableset.yml index 8a5f5ee7af..f6fc6a061f 100644 --- a/testing/server-tracetesting/features/environment/02_list_environment.yml +++ b/testing/server-tracetesting/features/variableset/02_list_variableset.yml @@ -1,12 +1,12 @@ type: Test spec: id: TCkN6vwVRN - name: List Environment - description: Test step of 'Environment Feature - Test Suite' + name: List Variable Set + description: Test step of 'Variable Set Feature - Test Suite' trigger: type: http httpRequest: - url: ${env:TARGET_URL}/api/environments + url: ${env:TARGET_URL}/api/variablesets method: GET headers: - key: Content-Type @@ -16,8 +16,8 @@ spec: assertions: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 200 - - attr:tracetest.response.body | json_path '$.items[*].spec.id' contains env:ENVIRONMENT_ID # check if the environment is listed - - selector: span[name="GET /api/environments" tracetest.span.type="http"] + - attr:tracetest.response.body | json_path '$.items[*].spec.id' contains env:VARIABLE_SET_ID # check if the variable set is listed + - selector: span[name="GET /api/variablesets" tracetest.span.type="http"] assertions: - attr:tracetest.selected_spans.count = 1 - selector: span[name = "query SELECT"] diff --git a/testing/server-tracetesting/features/environment/03_delete_environment.yml b/testing/server-tracetesting/features/variableset/03_delete_variableset.yml similarity index 78% rename from testing/server-tracetesting/features/environment/03_delete_environment.yml rename to testing/server-tracetesting/features/variableset/03_delete_variableset.yml index 5cbb76bf66..8964d01c69 100644 --- a/testing/server-tracetesting/features/environment/03_delete_environment.yml +++ b/testing/server-tracetesting/features/variableset/03_delete_variableset.yml @@ -2,12 +2,12 @@ type: Test spec: id: ojzN6vwVRv - name: Delete Environment - description: Test step of 'Environment Feature - Test Suite' + name: Delete Variable Set + description: Test step of 'Variable Set Feature - Test Suite' trigger: type: http httpRequest: - url: ${env:TARGET_URL}/api/environments/${env:ENVIRONMENT_ID} + url: ${env:TARGET_URL}/api/variablesets/${env:VARIABLE_SET_ID} method: DELETE headers: - key: Content-Type diff --git a/testing/server-tracetesting/features/variableset/_test_suite.yml b/testing/server-tracetesting/features/variableset/_test_suite.yml new file mode 100644 index 0000000000..8f4d886b16 --- /dev/null +++ b/testing/server-tracetesting/features/variableset/_test_suite.yml @@ -0,0 +1,12 @@ +type: Transaction +spec: + id: oCkH6vQ4gV + name: Variable Set Feature + description: Sequence of tests to validate if our Variable Set feature is working as expected + steps: + # create an variableset + - ./01_create_variableset.yml + # check if this variableset is listed on API + - ./02_list_variableset.yml + # delete variableset + - ./03_delete_variableset.yml diff --git a/testing/server-tracetesting/run.bash b/testing/server-tracetesting/run.bash index e8f87bff3d..7d41d14ca5 100755 --- a/testing/server-tracetesting/run.bash +++ b/testing/server-tracetesting/run.bash @@ -23,7 +23,7 @@ export EXAMPLE_TEST_ID="w2ON-RVVg" echo "Preparing to run tests on API..." echo "" -echo "Environment variables considered on this run:" +echo "Variable set considered on this run:" echo "TRACETEST_CLI: $TRACETEST_CLI" echo "TARGET_URL: $TARGET_URL" echo "TRACETEST_ENDPOINT: $TRACETEST_ENDPOINT" @@ -31,7 +31,7 @@ echo "DEMO_APP_URL: $DEMO_APP_URL" echo "DEMO_APP_GRPC_URL: $DEMO_APP_GRPC_URL" cat << EOF > tracetesting-env.yaml -type: Environment +type: VariableSet spec: id: tracetesting-env name: tracetesting-env @@ -46,7 +46,7 @@ spec: value: $EXAMPLE_TEST_ID EOF -echo "Environment variables set:" +echo "variables set created:" cat tracetesting-env.yaml echo "Setting up tracetest CLI configuration..." @@ -68,7 +68,7 @@ run_test_suite_for_feature() { # junit_output='results/'$feature'_test_suite.xml' definition='./features/'$feature'/_test_suite.yml' - testCMD="$TRACETEST_CLI --config ./config.yml run transaction --file $definition --environment ./tracetesting-env.yaml" + testCMD="$TRACETEST_CLI --config ./config.yml run transaction --file $definition --vars ./tracetesting-env.yaml" echo $testCMD $testCMD return $? @@ -84,7 +84,7 @@ EXIT_STATUS=0 # add more test suites here run_test_suite_for_feature 'http_test' || EXIT_STATUS=$? run_test_suite_for_feature 'grpc_test' || EXIT_STATUS=$? -run_test_suite_for_feature 'environment' || EXIT_STATUS=$? +run_test_suite_for_feature 'variableset' || EXIT_STATUS=$? run_test_suite_for_feature 'transaction' || EXIT_STATUS=$? echo "" diff --git a/web/cypress/e2e/Environments/Environments.spec.ts b/web/cypress/e2e/Environments/Environments.spec.ts deleted file mode 100644 index 670b5f2e0e..0000000000 --- a/web/cypress/e2e/Environments/Environments.spec.ts +++ /dev/null @@ -1,131 +0,0 @@ -import {POKEMON_HTTP_ENDPOINT} from '../constants/Test'; - -interface IEnvironment { - name: string; - description: string; - values: {key: string; value: string}[]; -} - -function createEnvironment(environment: IEnvironment) { - cy.visit('/environments'); - cy.contains('Create Environment').click(); - - cy.get('form#environment').within(() => { - cy.get('#environment_name').type(environment.name); - cy.get('#environment_description').type(environment.description); - cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(0).type(environment.values[0].key); - cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(1).type(environment.values[0].value); - }); - - cy.intercept({method: 'POST', url: '/api/environments'}).as('createEnvironment'); - cy.intercept({method: 'GET', url: '/api/environments?take=20&skip=0*'}).as('getEnvironments'); - - cy.get('.ant-modal-footer').contains('Create').click(); - cy.wait('@createEnvironment'); - cy.wait('@getEnvironments'); -} - -function deleteEnvironment() { - cy.visit('/environments'); - cy.get('[data-cy=environment-actions]').first().click(); - cy.get('[data-cy=environment-actions-delete]').click(); - - cy.intercept({method: 'DELETE', url: '/api/environments/*'}).as('deleteEnvironment'); - cy.intercept({method: 'GET', url: '/api/environments?take=20&skip=0*'}).as('getEnvironments'); - - cy.get('[data-cy=confirmation-modal] .ant-btn-primary').click(); - cy.wait('@deleteEnvironment'); - cy.wait('@getEnvironments'); -} - -describe('Environments', () => { - const environment1: IEnvironment = { - name: 'Environment One', - description: 'Description Environment One', - values: [{key: 'host', value: POKEMON_HTTP_ENDPOINT}], - }; - const environment2: IEnvironment = { - name: 'Environment Two', - description: 'Description Environment Two', - values: [{key: 'item2', value: 'value2'}], - }; - - it('should load the environments page', () => { - cy.visit('/environments'); - cy.contains('All Environments'); - cy.get('input[placeholder*="Search environment"]'); - cy.contains('Create Environment'); - }); - - it('should create a new environment', () => { - createEnvironment(environment1); - - cy.contains(environment1.name).click(); - cy.contains(environment1.description); - cy.contains(environment1.values[0].key); - cy.contains(environment1.values[0].value); - - deleteEnvironment(); - }); - - it('should update an environment', () => { - createEnvironment(environment1); - - cy.get('[data-cy=environment-actions]').first().click(); - cy.get('[data-cy=environment-actions-edit]').click(); - - cy.get('form#environment').within(() => { - cy.get('#environment_name').clear().type(environment2.name); - cy.get('#environment_description').clear().type(environment2.description); - cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(0).clear().type(environment2.values[0].key); - cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(1).clear().type(environment2.values[0].value); - }); - - cy.intercept({method: 'GET', url: '/api/environments?take=20&skip=0*'}).as('getEnvironments'); - - cy.get('.ant-modal-footer').contains('Update').click(); - cy.wait('@getEnvironments'); - - cy.contains(environment2.name).click(); - cy.contains(environment2.description); - cy.contains(environment2.values[0].key); - cy.contains(environment2.values[0].value); - - deleteEnvironment(); - }); - - it('should delete an environment', () => { - createEnvironment(environment1); - deleteEnvironment(); - - cy.contains(environment1.name).should('not.exist'); - }); - - it('should create a test using variables from environment', () => { - createEnvironment(environment1); - - cy.visit('/'); - cy.interceptHomeApiCall(); - - // Select created environment - cy.get('[data-cy=environment-selector]').click(); - cy.get('.environment-selector-items ul li').eq(1).click(); - - const name = `Test - Pokemon - #${String(Date.now()).slice(-4)}`; - cy.openTestCreationModal(); - cy.fillCreateFormBasicStep(name); - // eslint-disable-next-line no-template-curly-in-string - cy.setCreateFormUrl('GET', '${{}env:host}/pokemon'); - cy.submitCreateForm(); - cy.makeSureUserIsOnTracePage(); - - cy.reload().get('[data-cy=run-detail-trigger-response]').within(() => { - cy.contains('Environment').click(); - cy.contains(environment1.values[0].key); - cy.contains(environment1.values[0].value); - }); - - cy.deleteTest(true); - deleteEnvironment(); - }); -}); diff --git a/web/cypress/e2e/VariableSet/VariableSet.spec.ts b/web/cypress/e2e/VariableSet/VariableSet.spec.ts new file mode 100644 index 0000000000..423dc65cba --- /dev/null +++ b/web/cypress/e2e/VariableSet/VariableSet.spec.ts @@ -0,0 +1,131 @@ +import {POKEMON_HTTP_ENDPOINT} from '../constants/Test'; + +interface IVariableSet { + name: string; + description: string; + values: {key: string; value: string}[]; +} + +function createVariableSet(variableSet: IVariableSet) { + cy.visit('/variablesets'); + cy.contains('Create Variable Set').click(); + + cy.get('form#variableSet').within(() => { + cy.get('#variableSet_name').type(variableSet.name); + cy.get('#variableSet_description').type(variableSet.description); + cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(0).type(variableSet.values[0].key); + cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(1).type(variableSet.values[0].value); + }); + + cy.intercept({method: 'POST', url: '/api/variablesets'}).as('createVariableSet'); + cy.intercept({method: 'GET', url: '/api/variablesets?take=20&skip=0*'}).as('getVariableSet'); + + cy.get('.ant-modal-footer').contains('Create').click(); + cy.wait('@createVariableSet'); + cy.wait('@getVariableSet'); +} + +function deleteVariableSet() { + cy.visit('/variablesets'); + cy.get('[data-cy=variableSet-actions]').first().click(); + cy.get('[data-cy=variableSet-actions-delete]').click(); + + cy.intercept({method: 'DELETE', url: '/api/variablesets/*'}).as('deleteVariableSet'); + cy.intercept({method: 'GET', url: '/api/variablesets?take=20&skip=0*'}).as('getVariableSet'); + + cy.get('[data-cy=confirmation-modal] .ant-btn-primary').click(); + cy.wait('@deleteVariableSet'); + cy.wait('@getVariableSet'); +} + +describe('VariableSets', () => { + const variableSet1: IVariableSet = { + name: 'Vars One', + description: 'Description variableSet One', + values: [{key: 'host', value: POKEMON_HTTP_ENDPOINT}], + }; + const variableSet2: IVariableSet = { + name: 'Vars Two', + description: 'Description variableSet Two', + values: [{key: 'item2', value: 'value2'}], + }; + + it('should load the variableSets page', () => { + cy.visit('/variablesets'); + cy.contains('All Variable Sets'); + cy.get('input[placeholder*="Search variable set"]'); + cy.contains('Create Variable Set'); + }); + + it('should create a new variableSet', () => { + createVariableSet(variableSet1); + + cy.contains(variableSet1.name).click(); + cy.contains(variableSet1.description); + cy.contains(variableSet1.values[0].key); + cy.contains(variableSet1.values[0].value); + + deleteVariableSet(); + }); + + it('should update an variableSet', () => { + createVariableSet(variableSet1); + + cy.get('[data-cy=variableSet-actions]').first().click(); + cy.get('[data-cy=variableSet-actions-edit]').click(); + + cy.get('form#variableSet').within(() => { + cy.get('#variableSet_name').clear().type(variableSet2.name); + cy.get('#variableSet_description').clear().type(variableSet2.description); + cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(0).clear().type(variableSet2.values[0].key); + cy.get('[data-cy=interpolation-editor] [contenteditable]').eq(1).clear().type(variableSet2.values[0].value); + }); + + cy.intercept({method: 'GET', url: '/api/variablesets?take=20&skip=0*'}).as('getVariableSets'); + + cy.get('.ant-modal-footer').contains('Update').click(); + cy.wait('@getVariableSets'); + + cy.contains(variableSet2.name).click(); + cy.contains(variableSet2.description); + cy.contains(variableSet2.values[0].key); + cy.contains(variableSet2.values[0].value); + + deleteVariableSet(); + }); + + it('should delete an variableSet', () => { + createVariableSet(variableSet1); + deleteVariableSet(); + + cy.contains(variableSet1.name).should('not.exist'); + }); + + it.only('should create a test using variables from variableSet', () => { + createVariableSet(variableSet1); + + cy.visit('/'); + cy.interceptHomeApiCall(); + + // Select created variableSet + cy.get('[data-cy=variableSet-selector]').click(); + cy.get('.variableSet-selector-items ul li').eq(1).click(); + + const name = `Test - Pokemon - #${String(Date.now()).slice(-4)}`; + cy.openTestCreationModal(); + cy.fillCreateFormBasicStep(name); + // eslint-disable-next-line no-template-curly-in-string + cy.setCreateFormUrl('GET', '${{}env:host}/pokemon'); + cy.submitCreateForm(); + cy.makeSureUserIsOnTracePage(); + + cy.reload().get('[data-cy=run-detail-trigger-response]').within(() => { + cy.contains('Variable Set').click(); + cy.contains(variableSet1.values[0].key); + cy.contains(variableSet1.values[0].value); + }); + + cy.deleteTest(true); + deleteVariableSet(); + }); +}); diff --git a/web/cypress/fixtures/environment.json b/web/cypress/fixtures/environment.json index 0a6e0cc0c1..ad201dfc10 100644 --- a/web/cypress/fixtures/environment.json +++ b/web/cypress/fixtures/environment.json @@ -3,7 +3,7 @@ "name": "TracetestDEV", "values": [ { - "key": "CESCO", + "key": "HOST", "value": "From Environment", "type": "default", "enabled": true diff --git a/web/src/components/Editor/Expression/Expression.tsx b/web/src/components/Editor/Expression/Expression.tsx index 25fd122690..c0376b6975 100644 --- a/web/src/components/Editor/Expression/Expression.tsx +++ b/web/src/components/Editor/Expression/Expression.tsx @@ -5,7 +5,7 @@ import {Extension} from '@codemirror/state'; import {autocompletion} from '@codemirror/autocomplete'; import CodeMirror, {ReactCodeMirrorRef} from '@uiw/react-codemirror'; import {useCallback, useMemo, useRef, useState} from 'react'; -import {useEnvironment} from 'providers/Environment/Environment.provider'; +import {useVariableSet} from 'providers/VariableSet'; import EditorService from 'services/Editor.service'; import {SupportedEditors} from 'constants/Editor.constants'; @@ -32,10 +32,10 @@ const Expression = ({ }: IEditorProps) => { const {testId = '', runId = ''} = context; const [isHovering, setIsHovering] = useState(false); - const {selectedEnvironment} = useEnvironment(); + const {selectedVariableSet} = useVariableSet(); const editorTheme = useEditorTheme(); const completionFn = useAutoComplete({testId, runId, onSelect: onSelectAutocompleteOption, autocompleteCustomValues}); - const {onHover, resolvedValues, isLoading} = useTooltip({environmentId: selectedEnvironment?.id, ...context}); + const {onHover, resolvedValues, isLoading} = useTooltip({variableSetId: selectedVariableSet?.id, ...context}); const ref = useRef(null); const isValidQuery = useMemo(() => EditorService.getIsQueryValid(SupportedEditors.Expression, value), [value]); diff --git a/web/src/components/Editor/Expression/hooks/useAutoComplete.ts b/web/src/components/Editor/Expression/hooks/useAutoComplete.ts index 5771e7ead7..53bd197b22 100644 --- a/web/src/components/Editor/Expression/hooks/useAutoComplete.ts +++ b/web/src/components/Editor/Expression/hooks/useAutoComplete.ts @@ -3,7 +3,7 @@ import {noop, uniqBy} from 'lodash'; import {Completion, CompletionContext} from '@codemirror/autocomplete'; import {useAppStore} from 'redux/hooks'; import AssertionSelectors from 'selectors/Assertion.selectors'; -import EnvironmentSelectors from 'selectors/Environment.selectors'; +import VariableSetSelectors from 'selectors/VariableSet.selectors'; import SpanSelectors from 'selectors/Span.selectors'; import EditorService from 'services/Editor.service'; import {SupportedEditors} from 'constants/Editor.constants'; @@ -26,16 +26,16 @@ const useAutoComplete = ({testId, runId, onSelect = noop, autocompleteCustomValu return uniqBy(attributeList, 'key'); }, [getState, runId, testId]); - const getSelectedEnvironmentEntryList = useCallback(() => { + const getSelectedVariableSetEntryList = useCallback(() => { const state = getState(); - return EnvironmentSelectors.selectSelectedEnvironmentValues(state, true); + return VariableSetSelectors.selectSelectedVariableSetValues(state, true); }, [getState]); return useCallback( async (context: CompletionContext) => { const attributeList = getAttributeList(); - const envEntryList = getSelectedEnvironmentEntryList(); + const envEntryList = getSelectedVariableSetEntryList(); return EditorService.getAutocomplete({ type: SupportedEditors.Expression, @@ -46,7 +46,7 @@ const useAutoComplete = ({testId, runId, onSelect = noop, autocompleteCustomValu onSelect, }); }, - [autocompleteCustomValues, getAttributeList, getSelectedEnvironmentEntryList, onSelect] + [autocompleteCustomValues, getAttributeList, getSelectedVariableSetEntryList, onSelect] ); }; diff --git a/web/src/components/Editor/Interpolation/Interpolation.tsx b/web/src/components/Editor/Interpolation/Interpolation.tsx index 4cf64fbb66..e18dabe066 100644 --- a/web/src/components/Editor/Interpolation/Interpolation.tsx +++ b/web/src/components/Editor/Interpolation/Interpolation.tsx @@ -3,7 +3,7 @@ import {uniq} from 'lodash'; import {Tooltip} from 'antd'; import {autocompletion} from '@codemirror/autocomplete'; import {useCallback, useMemo} from 'react'; -import {useEnvironment} from 'providers/Environment/Environment.provider'; +import {useVariableSet} from 'providers/VariableSet'; import EditorService from 'services/Editor.service'; import {SupportedEditors} from 'constants/Editor.constants'; import {interpolationQL} from './grammar'; @@ -21,11 +21,11 @@ const Interpolation = ({ extensions = [], indentWithTab = false, }: IEditorProps) => { - const {selectedEnvironment} = useEnvironment(); + const {selectedVariableSet} = useVariableSet(); const editorTheme = useEditorTheme(); const completionFn = useAutoComplete(); const {onHover, resolvedValues} = useTooltip({ - environmentId: selectedEnvironment?.id, + variableSetId: selectedVariableSet?.id, }); const extensionList = useMemo( diff --git a/web/src/components/Editor/Interpolation/hooks/useAutoComplete.ts b/web/src/components/Editor/Interpolation/hooks/useAutoComplete.ts index 2925c105b6..780402a57b 100644 --- a/web/src/components/Editor/Interpolation/hooks/useAutoComplete.ts +++ b/web/src/components/Editor/Interpolation/hooks/useAutoComplete.ts @@ -3,24 +3,24 @@ import {CompletionContext} from '@codemirror/autocomplete'; import EditorService from 'services/Editor.service'; import {SupportedEditors} from 'constants/Editor.constants'; import {useAppStore} from 'redux/hooks'; -import EnvironmentSelectors from 'selectors/Environment.selectors'; +import VariableSetSelectors from 'selectors/VariableSet.selectors'; const useAutoComplete = () => { const {getState} = useAppStore(); - const getSelectedEnvironmentEntryList = useCallback(() => { + const getSelectedVariableSetEntryList = useCallback(() => { const state = getState(); - return EnvironmentSelectors.selectSelectedEnvironmentValues(state, false); + return VariableSetSelectors.selectSelectedVariableSetValues(state, false); }, [getState]); return useCallback( async (context: CompletionContext) => { - const envEntryList = getSelectedEnvironmentEntryList(); + const envEntryList = getSelectedVariableSetEntryList(); return EditorService.getAutocomplete({type: SupportedEditors.Interpolation, context, envEntryList}); }, - [getSelectedEnvironmentEntryList] + [getSelectedVariableSetEntryList] ); }; diff --git a/web/src/components/EnvironmentModal/EnvironmentModal.tsx b/web/src/components/EnvironmentModal/EnvironmentModal.tsx deleted file mode 100644 index 6add01e455..0000000000 --- a/web/src/components/EnvironmentModal/EnvironmentModal.tsx +++ /dev/null @@ -1,68 +0,0 @@ -import {Form} from 'antd'; -import {useEffect, useState} from 'react'; - -import EnvironmentForm from 'components/EnvironmentForm'; -import Environment from 'models/Environment.model'; -import * as S from './EnvironmentModal.styled'; -import EnvironmentModalFooter from './EnvironmentModalFooter'; -import EnvironmentService from '../../services/Environment.service'; - -interface IProps { - environment?: Environment; - isOpen: boolean; - isLoading: boolean; - onClose(): void; - onSubmit(environment: Environment): void; -} - -export const DEFAULT_VALUES = [{key: '', value: ''}]; - -const EnvironmentModal = ({environment, isOpen, onClose, onSubmit, isLoading}: IProps) => { - const [form] = Form.useForm(); - const [isFormValid, setIsFormValid] = useState(false); - const isEditing = Boolean(environment); - - useEffect(() => { - if (environment && isOpen) form.setFieldsValue(environment); - if (!isOpen || !environment) { - form.resetFields(); - form.setFieldsValue({values: [{key: '', value: ''}]}); - } - }, [environment, form, isOpen]); - - const handleOnValidate = (changedValues: any, draft: Environment) => { - setIsFormValid(EnvironmentService.validateDraft(draft)); - }; - - const handleOnSubmit = async (values: Environment) => { - onSubmit(values); - onClose(); - }; - - return ( - form.submit()} - /> - } - onCancel={onClose} - title={{isEditing ? 'Edit Environment' : 'Create Environment'}} - visible={isOpen} - > - - - ); -}; - -export default EnvironmentModal; diff --git a/web/src/components/EnvironmentSelector/AddEnvironment.tsx b/web/src/components/EnvironmentSelector/AddEnvironment.tsx deleted file mode 100644 index 52eef0fe70..0000000000 --- a/web/src/components/EnvironmentSelector/AddEnvironment.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import * as S from './EnvironmentSelector.styled'; - -const AddEnvironment = () => { - return ( - - - Create new env - - ); -}; - -export default AddEnvironment; diff --git a/web/src/components/EnvironmentSelector/EnvironmentSelector.tsx b/web/src/components/EnvironmentSelector/EnvironmentSelector.tsx deleted file mode 100644 index 680540f378..0000000000 --- a/web/src/components/EnvironmentSelector/EnvironmentSelector.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import {DownOutlined} from '@ant-design/icons'; -import {Dropdown, Menu, Space} from 'antd'; -import type {ItemType} from 'antd/lib/menu/hooks/useItems'; -import {useEnvironment} from 'providers/Environment/Environment.provider'; -import {useMemo, useState} from 'react'; -import AddEnvironment from './AddEnvironment'; -import EnvironmentSelectorEntry from './EnvironmentSelectorEntry'; - -const EnvironmentSelector = () => { - const {environmentList, selectedEnvironment, setSelectedEnvironment, isLoading} = useEnvironment(); - const [hoveredOption, setHoveredOption] = useState(); - const {onOpenModal} = useEnvironment(); - - const items = useMemo( - () => - ( - [ - { - key: 'no-env', - label: 'No environment', - onClick: () => setSelectedEnvironment(), - }, - ] as ItemType[] - ) - .concat( - environmentList.map(environment => ({ - key: environment.id, - label: ( - - ), - onClick: () => setSelectedEnvironment(environment), - onMouseEnter: () => setHoveredOption(environment.id), - })) - ) - .concat([ - { - type: 'divider', - }, - { - key: 'add-env', - label: , - onClick: () => onOpenModal(), - }, - ]), - [environmentList, hoveredOption, onOpenModal, setSelectedEnvironment] - ); - - return !isLoading ? ( - } overlayClassName="environment-selector-items"> - e.preventDefault()}> - - {selectedEnvironment?.name || 'No environment'} - - - - - ) : null; -}; - -export default EnvironmentSelector; diff --git a/web/src/components/EnvironmentSelector/EnvironmentSelectorEntry.tsx b/web/src/components/EnvironmentSelector/EnvironmentSelectorEntry.tsx deleted file mode 100644 index 65f4f5a11b..0000000000 --- a/web/src/components/EnvironmentSelector/EnvironmentSelectorEntry.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import {Tooltip} from 'antd'; -import Environment from 'models/Environment.model'; -import {useCallback} from 'react'; -import * as S from './EnvironmentSelector.styled'; - -interface IProps { - environment: Environment; - isHovering: boolean; - onEditClick(environment: Environment): void; -} - -const EnvironmentSelectorEntry = ({environment: {name}, environment, isHovering, onEditClick}: IProps) => { - const handleClick = useCallback( - event => { - event.stopPropagation(); - onEditClick(environment); - }, - [environment, onEditClick] - ); - - return ( - - {name} - {isHovering && ( - - - - )} - - ); -}; - -export default EnvironmentSelectorEntry; diff --git a/web/src/components/Header/Header.tsx b/web/src/components/Header/Header.tsx index 0b0daffa77..ded0ad305a 100644 --- a/web/src/components/Header/Header.tsx +++ b/web/src/components/Header/Header.tsx @@ -1,7 +1,7 @@ import {Space} from 'antd'; import Logo from 'assets/Logo.svg'; -import EnvironmentSelector from 'components/EnvironmentSelector'; +import VariableSetSelector from 'components/VariableSetSelector'; import Link from 'components/Link'; import NoTracingPopover from 'components/NoTracingPopover'; import * as S from './Header.styled'; @@ -24,7 +24,7 @@ const Header = ({hasLogo = false, isNoTracingMode}: IProps) => ( {isNoTracingMode && } - + diff --git a/web/src/components/Layout/Layout.tsx b/web/src/components/Layout/Layout.tsx index 05dbfed477..4e135ac8e6 100644 --- a/web/src/components/Layout/Layout.tsx +++ b/web/src/components/Layout/Layout.tsx @@ -9,7 +9,7 @@ import Header from 'components/Header'; import Link from 'components/Link'; import useRouterSync from 'hooks/useRouterSync'; import ConfirmationModalProvider from 'providers/ConfirmationModal'; -import EnvironmentProvider from 'providers/Environment'; +import VariableSetProvider from 'providers/VariableSet'; import {useSettingsValues} from 'providers/SettingsValues/SettingsValues.provider'; import MissingVariablesModalProvider from 'providers/MissingVariablesModal/MissingVariablesModal.provider'; import NotificationProvider from 'providers/Notification/Notification.provider'; @@ -31,8 +31,8 @@ const menuItems = [ { key: '1', icon: , - label: Environments, - path: '/environments', + label: Variable Sets, + path: '/variablesets', }, ]; @@ -56,7 +56,7 @@ const Layout = ({children, hasMenu = false}: IProps) => { - + {hasMenu && ( @@ -97,7 +97,7 @@ const Layout = ({children, hasMenu = false}: IProps) => { {children} - + diff --git a/web/src/components/MissingVariablesModal/MissingVariablesModal.tsx b/web/src/components/MissingVariablesModal/MissingVariablesModal.tsx index a42df168bb..126cd1fef4 100644 --- a/web/src/components/MissingVariablesModal/MissingVariablesModal.tsx +++ b/web/src/components/MissingVariablesModal/MissingVariablesModal.tsx @@ -2,7 +2,7 @@ import {useEffect} from 'react'; import {Form} from 'antd'; import VariablesService from 'services/Variables.service'; import {TDraftVariables, TTestVariablesMap} from 'types/Variables.types'; -import {TEnvironmentValue} from 'models/Environment.model'; +import {TVariableSetValue} from 'models/VariableSet.model'; import * as S from './MissingVariablesModal.styled'; import MissingVariablesModalFooter from './MissingVariablesModalFooter'; import MissingVariablesModalForm from './MissingVariablesModalForm'; @@ -12,7 +12,7 @@ interface IProps { isOpen: boolean; name: string; onClose(): void; - onSubmit(values: TEnvironmentValue[]): void; + onSubmit(values: TVariableSetValue[]): void; testVariables: TTestVariablesMap; } diff --git a/web/src/components/Router/Router.tsx b/web/src/components/Router/Router.tsx index c0698aca93..3aa7376e93 100644 --- a/web/src/components/Router/Router.tsx +++ b/web/src/components/Router/Router.tsx @@ -1,6 +1,6 @@ import {Navigate, Route, Routes} from 'react-router-dom'; -import Environments from 'pages/Environments'; +import VariableSet from 'pages/VariableSet'; import Home from 'pages/Home'; import RunDetail from 'pages/RunDetail'; import Settings from 'pages/Settings'; @@ -14,7 +14,7 @@ const Router = () => ( } /> - } /> + } /> } /> diff --git a/web/src/components/RunDetailAutomate/RunDetailAutomate.tsx b/web/src/components/RunDetailAutomate/RunDetailAutomate.tsx index f72ef864d9..b9d2d846b4 100644 --- a/web/src/components/RunDetailAutomate/RunDetailAutomate.tsx +++ b/web/src/components/RunDetailAutomate/RunDetailAutomate.tsx @@ -7,7 +7,7 @@ import DeepLink from 'components/RunDetailAutomateMethods/methods/DeepLink'; import {CLI_RUNNING_TESTS_URL} from 'constants/Common.constants'; import Test from 'models/Test.model'; import TestRun from 'models/TestRun.model'; -import {useEnvironment} from 'providers/Environment/Environment.provider'; +import {useVariableSet} from 'providers/VariableSet'; import {ResourceType} from 'types/Resource.type'; import * as S from './RunDetailAutomate.styled'; @@ -18,7 +18,7 @@ interface IProps { const RunDetailAutomate = ({test, run}: IProps) => { const [fileName, setFileName] = useState(`${snakeCase(test.name)}.yaml`); - const {selectedEnvironment: {id: environmentId} = {}} = useEnvironment(); + const {selectedVariableSet: {id: variableSetId} = {}} = useVariableSet(); return ( @@ -41,7 +41,7 @@ const RunDetailAutomate = ({test, run}: IProps) => { children: ( { { id: 'deeplink', label: 'Deep Link', - children: , + children: , }, ]} /> diff --git a/web/src/components/RunDetailAutomateMethods/methods/CLICommand/CliCommand.tsx b/web/src/components/RunDetailAutomateMethods/methods/CLICommand/CliCommand.tsx index d990bf60ab..41c3916cd6 100644 --- a/web/src/components/RunDetailAutomateMethods/methods/CLICommand/CliCommand.tsx +++ b/web/src/components/RunDetailAutomateMethods/methods/CLICommand/CliCommand.tsx @@ -7,13 +7,13 @@ import useCliCommand from './hooks/useCliCommand'; interface IProps { id: string; - environmentId?: string; + variableSetId?: string; fileName?: string; resourceType: ResourceType; docsUrl?: string; } -const CLiCommand = ({id, environmentId, fileName = '', resourceType, docsUrl}: IProps) => { +const CLiCommand = ({id, variableSetId, fileName = '', resourceType, docsUrl}: IProps) => { const {command, onGetCommand} = useCliCommand(); return ( @@ -35,7 +35,7 @@ const CLiCommand = ({id, environmentId, fileName = '', resourceType, docsUrl}: I onChange={onGetCommand} id={id} fileName={fileName} - environmentId={environmentId} + variableSetId={variableSetId} resourceType={resourceType} /> diff --git a/web/src/components/RunDetailAutomateMethods/methods/CLICommand/Controls.tsx b/web/src/components/RunDetailAutomateMethods/methods/CLICommand/Controls.tsx index 2e35d33891..ee89df3491 100644 --- a/web/src/components/RunDetailAutomateMethods/methods/CLICommand/Controls.tsx +++ b/web/src/components/RunDetailAutomateMethods/methods/CLICommand/Controls.tsx @@ -10,7 +10,7 @@ import SwitchControl from './SwitchControl'; import {defaultOptions} from './hooks/useCliCommand'; interface IOptionsMetadataParams { - isEnvironmentSelected: boolean; + isVariableSetSelected: boolean; resourceType: ResourceType; } interface IOptionsMetadata { @@ -20,17 +20,17 @@ interface IOptionsMetadata { } function getOptionsMetadata({ - isEnvironmentSelected, + isVariableSetSelected, resourceType, }: IOptionsMetadataParams): Record { return { [CliCommandOption.UseId]: {label: `Use ${resourceType} ID instead of file`}, [CliCommandOption.SkipResultWait]: {label: `Skip waiting for ${resourceType} to complete`}, [CliCommandOption.UseHostname]: {label: 'Specify Tracetest server hostname'}, - [CliCommandOption.UseCurrentEnvironment]: { - label: 'Use selected environment', - help: !isEnvironmentSelected ? 'This option is only available when an environment is selected' : undefined, - disabled: !isEnvironmentSelected, + [CliCommandOption.UseCurrentVariableSet]: { + label: 'Use selected variable set', + help: !isVariableSetSelected ? 'This option is only available when an variable set is selected' : undefined, + disabled: !isVariableSetSelected, }, [CliCommandOption.GeneratesJUnit]: {label: 'Generate JUnit report'}, [CliCommandOption.useDocker]: {label: 'Run CLI via Docker image'}, @@ -40,19 +40,19 @@ function getOptionsMetadata({ interface IProps { onChange(cmdConfig: TCliCommandConfig): void; id: string; - environmentId?: string; + variableSetId?: string; fileName: string; resourceType: ResourceType; } -const Controls = ({onChange, id, environmentId, fileName, resourceType}: IProps) => { +const Controls = ({onChange, id, variableSetId, fileName, resourceType}: IProps) => { const [form] = Form.useForm(); const options = Form.useWatch('options', form); const format = Form.useWatch('format', form); const requiredGates = Form.useWatch('required-gates', form); const optionsMetadata = useMemo( - () => getOptionsMetadata({isEnvironmentSelected: !!environmentId, resourceType}), - [environmentId, resourceType] + () => getOptionsMetadata({isVariableSetSelected: !!variableSetId, resourceType}), + [variableSetId, resourceType] ); useEffect(() => { @@ -61,11 +61,11 @@ const Controls = ({onChange, id, environmentId, fileName, resourceType}: IProps) format: format ?? CliCommandFormat.Pretty, requiredGates, id, - environmentId, + variableSetId, fileName, resourceType, }); - }, [environmentId, fileName, format, requiredGates, onChange, options, id, resourceType]); + }, [fileName, format, requiredGates, onChange, options, id, resourceType, variableSetId]); return ( diff --git a/web/src/components/RunDetailAutomateMethods/methods/CLICommand/hooks/useCliCommand.ts b/web/src/components/RunDetailAutomateMethods/methods/CLICommand/hooks/useCliCommand.ts index f987133271..4bc4d5e23a 100644 --- a/web/src/components/RunDetailAutomateMethods/methods/CLICommand/hooks/useCliCommand.ts +++ b/web/src/components/RunDetailAutomateMethods/methods/CLICommand/hooks/useCliCommand.ts @@ -9,7 +9,7 @@ export const defaultOptions: TCliCommandEnabledOptions = { [CliCommandOption.UseId]: false, [CliCommandOption.SkipResultWait]: false, [CliCommandOption.UseHostname]: false, - [CliCommandOption.UseCurrentEnvironment]: false, + [CliCommandOption.UseCurrentVariableSet]: false, [CliCommandOption.GeneratesJUnit]: false, [CliCommandOption.useDocker]: false, }; diff --git a/web/src/components/RunDetailAutomateMethods/methods/DeepLink/Controls.tsx b/web/src/components/RunDetailAutomateMethods/methods/DeepLink/Controls.tsx index 7942c7439b..69311aeb79 100644 --- a/web/src/components/RunDetailAutomateMethods/methods/DeepLink/Controls.tsx +++ b/web/src/components/RunDetailAutomateMethods/methods/DeepLink/Controls.tsx @@ -1,7 +1,7 @@ import {Form} from 'antd'; import {useEffect, useMemo} from 'react'; import {TDeepLinkConfig} from 'services/DeepLink.service'; -import Environment from 'models/Environment.model'; +import VariableSet from 'models/VariableSet.model'; import Test from 'models/Test.model'; import * as S from './DeepLink.styled'; import SwitchControl from '../CLICommand/SwitchControl'; @@ -9,20 +9,20 @@ import Variables from './Variables'; interface IProps { onChange(deepLinkConfig: TDeepLinkConfig): void; - environment?: Environment; + variableSet?: VariableSet; test: Test; - environmentId?: string; + variableSetId?: string; } -const Controls = ({onChange, environment: {values} = Environment({}), test, environmentId}: IProps) => { +const Controls = ({onChange, variableSet: {values} = VariableSet({}), test, variableSetId}: IProps) => { const [form] = Form.useForm(); const variables = Form.useWatch('variables', form); - const useEnvironmentId = Form.useWatch('useEnvironmentId', form); + const useVariableSetId = Form.useWatch('useVariableSetId', form); const defaultValues = useMemo( () => ({ variables: values, - useEnvironmentId: true, + useVariableSetId: true, }), [values] ); @@ -30,11 +30,11 @@ const Controls = ({onChange, environment: {values} = Environment({}), test, envi useEffect(() => { onChange({ variables: variables ?? [], - useEnvironmentId: useEnvironmentId ?? true, - environmentId, + useVariableSetId: useVariableSetId ?? true, + variableSetId, test, }); - }, [environmentId, test, onChange, variables, useEnvironmentId]); + }, [variableSetId, test, onChange, variables, useVariableSetId]); return ( @@ -47,8 +47,8 @@ const Controls = ({onChange, environment: {values} = Environment({}), test, envi Manage Execution - - + + diff --git a/web/src/components/RunDetailAutomateMethods/methods/DeepLink/DeepLink.tsx b/web/src/components/RunDetailAutomateMethods/methods/DeepLink/DeepLink.tsx index 17ffaf2a8d..98c2d7af9d 100644 --- a/web/src/components/RunDetailAutomateMethods/methods/DeepLink/DeepLink.tsx +++ b/web/src/components/RunDetailAutomateMethods/methods/DeepLink/DeepLink.tsx @@ -9,10 +9,10 @@ import useDeepLink from './hooks/useDeepLink'; interface IProps { test: Test; run: TestRun; - environmentId?: string; + variableSetId?: string; } -const DeepLink = ({test, environmentId, run: {environment}}: IProps) => { +const DeepLink = ({test, variableSetId, run: {variableSet}}: IProps) => { const {deepLink, onGetDeepLink} = useDeepLink(); return ( @@ -38,7 +38,7 @@ const DeepLink = ({test, environmentId, run: {environment}}: IProps) => { } /> - + ); }; diff --git a/web/src/components/RunDetailTriggerResponse/ResponseEnvironment.tsx b/web/src/components/RunDetailTriggerResponse/ResponseEnvironment.tsx deleted file mode 100644 index e0e8ff6455..0000000000 --- a/web/src/components/RunDetailTriggerResponse/ResponseEnvironment.tsx +++ /dev/null @@ -1,35 +0,0 @@ -import KeyValueRow from 'components/KeyValueRow'; -import {ENVIRONMENTS_DOCUMENTATION_URL} from 'constants/Common.constants'; -import {useTestRun} from 'providers/TestRun/TestRun.provider'; -import * as S from './RunDetailTriggerResponse.styled'; - -const ResponseEnvironment = () => { - const { - run: {environment}, - } = useTestRun(); - - if (!environment?.values?.length) { - return ( - - - There are no environment variables used in this test - - Learn more about environments{' '} - - here - - - - ); - } - - return ( - - {environment?.values?.map(value => ( - - ))} - - ); -}; - -export default ResponseEnvironment; diff --git a/web/src/components/RunDetailTriggerResponse/ResponseVariableSet.tsx b/web/src/components/RunDetailTriggerResponse/ResponseVariableSet.tsx new file mode 100644 index 0000000000..d0fcc7f4ac --- /dev/null +++ b/web/src/components/RunDetailTriggerResponse/ResponseVariableSet.tsx @@ -0,0 +1,35 @@ +import KeyValueRow from 'components/KeyValueRow'; +import {VARIABLE_SET_DOCUMENTATION_URL} from 'constants/Common.constants'; +import {useTestRun} from 'providers/TestRun/TestRun.provider'; +import * as S from './RunDetailTriggerResponse.styled'; + +const ResponseVariableSet = () => { + const { + run: {variableSet}, + } = useTestRun(); + + if (!variableSet?.values?.length) { + return ( + + + There are no variable sets used in this test + + Learn more about variable sets{' '} + + here + + + + ); + } + + return ( + + {variableSet?.values?.map(value => ( + + ))} + + ); +}; + +export default ResponseVariableSet; diff --git a/web/src/components/RunDetailTriggerResponse/RunDetailTriggerData.tsx b/web/src/components/RunDetailTriggerResponse/RunDetailTriggerData.tsx index 146a6b4456..8557419d62 100644 --- a/web/src/components/RunDetailTriggerResponse/RunDetailTriggerData.tsx +++ b/web/src/components/RunDetailTriggerResponse/RunDetailTriggerData.tsx @@ -3,12 +3,12 @@ import {useSearchParams} from 'react-router-dom'; import {StepsID} from 'components/GuidedTour/testRunSteps'; import {TestState} from 'constants/TestRun.constants'; import TestRunAnalyticsService from 'services/Analytics/TestRunAnalytics.service'; -import ResponseEnvironment from './ResponseEnvironment'; +import ResponseVariableSet from './ResponseVariableSet'; import * as S from './RunDetailTriggerResponse.styled'; import {IPropsComponent} from './RunDetailTriggerResponseFactory'; const TABS = { - Environment: 'environment', + VariableSet: 'variable-set', } as const; const RunDetailTriggerData = ({state, triggerTime = 0}: IPropsComponent) => { @@ -29,15 +29,15 @@ const RunDetailTriggerData = ({state, triggerTime = 0}: IPropsComponent) => { { TestRunAnalyticsService.onTriggerResponseTabChange(newTab); updateQuery([['tab', newTab]]); }} > - - + + diff --git a/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.styled.ts b/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.styled.ts index 269786ea66..07be1b459e 100644 --- a/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.styled.ts +++ b/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.styled.ts @@ -100,7 +100,7 @@ export const Actions = styled.div` gap: 10px; `; -export const ResponseEnvironmentContainer = styled.div` +export const ResponseVarsContainer = styled.div` padding: 16px 0; `; diff --git a/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.tsx b/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.tsx index 949058055e..3cf79f1161 100644 --- a/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.tsx +++ b/web/src/components/RunDetailTriggerResponse/RunDetailTriggerResponse.tsx @@ -14,7 +14,7 @@ import TestRunAnalyticsService from 'services/Analytics/TestRunAnalytics.service import AssertionService from 'services/Assertion.service'; import {TSpanFlatAttribute} from 'types/Span.types'; import ResponseBody from './ResponseBody'; -import ResponseEnvironment from './ResponseEnvironment'; +import ResponseVariableSet from './ResponseVariableSet'; import ResponseHeaders from './ResponseHeaders'; import * as S from './RunDetailTriggerResponse.styled'; import {IPropsComponent} from './RunDetailTriggerResponseFactory'; @@ -22,7 +22,7 @@ import {IPropsComponent} from './RunDetailTriggerResponseFactory'; const TabsKeys = { Body: 'body', Headers: 'headers', - Environment: 'environment', + VariableSet: 'variable-set', }; const tracetestTriggerSelector = 'span[tracetest.span.type="general" name="Tracetest trigger"]'; @@ -143,8 +143,8 @@ const RunDetailTriggerResponse = ({ onCreateTestSpec={handleCreateTestSpec} /> - - + + diff --git a/web/src/components/TransactionRunResult/TransactionRunResult.tsx b/web/src/components/TransactionRunResult/TransactionRunResult.tsx index f47149253f..22f214dc01 100644 --- a/web/src/components/TransactionRunResult/TransactionRunResult.tsx +++ b/web/src/components/TransactionRunResult/TransactionRunResult.tsx @@ -10,7 +10,7 @@ interface IProps { transactionRun: TransactionRun; } -const TransactionRunResult = ({transactionRun: {steps, environment, state}, transaction}: IProps) => { +const TransactionRunResult = ({transactionRun: {steps, variableSet, state}, transaction}: IProps) => { const hasRunFailed = state === TestState.FAILED; return ( @@ -28,7 +28,7 @@ const TransactionRunResult = ({transactionRun: {steps, environment, state}, tran
Variables - {environment?.values?.map(value => ( + {variableSet?.values?.map(value => ( ))}
diff --git a/web/src/components/EnvironmentForm/EnvironmentForm.styled.ts b/web/src/components/VariableSet/VariableSetForm.styled.ts similarity index 100% rename from web/src/components/EnvironmentForm/EnvironmentForm.styled.ts rename to web/src/components/VariableSet/VariableSetForm.styled.ts diff --git a/web/src/components/EnvironmentForm/EnvironmentForm.tsx b/web/src/components/VariableSet/VariableSetForm.tsx similarity index 69% rename from web/src/components/EnvironmentForm/EnvironmentForm.tsx rename to web/src/components/VariableSet/VariableSetForm.tsx index 794135b9e1..a208b9e0d5 100644 --- a/web/src/components/EnvironmentForm/EnvironmentForm.tsx +++ b/web/src/components/VariableSet/VariableSetForm.tsx @@ -1,23 +1,23 @@ import {Form, FormInstance, Input} from 'antd'; import RequestDetailsHeadersInput from 'components/CreateTestPlugins/Rest/steps/RequestDetails/RequestDetailsHeadersInput'; -import {DEFAULT_VALUES} from 'components/EnvironmentModal/EnvironmentModal'; -import Environment from 'models/Environment.model'; +import {DEFAULT_VALUES} from 'components/VariableSetModal/VariableSetModal'; +import VariableSet from 'models/VariableSet.model'; interface IProps { - form: FormInstance; - initialValues?: Environment; - onSubmit(values: Environment): void; - onValidate(changedValues: any, values: Environment): void; + form: FormInstance; + initialValues?: VariableSet; + onSubmit(values: VariableSet): void; + onValidate(changedValues: any, values: VariableSet): void; } -const EnvironmentForm = ({form, initialValues, onSubmit, onValidate}: IProps) => { +const VariableSetForm = ({form, initialValues, onSubmit, onValidate}: IProps) => { return ( - + initialValues={{...initialValues}} form={form} layout="vertical" - name="environment" + name="variableSet" onFinish={onSubmit} onValuesChange={onValidate} > @@ -46,4 +46,4 @@ const EnvironmentForm = ({form, initialValues, onSubmit, onValidate}: IProps) => ); }; -export default EnvironmentForm; +export default VariableSetForm; diff --git a/web/src/components/EnvironmentForm/index.ts b/web/src/components/VariableSet/index.ts similarity index 53% rename from web/src/components/EnvironmentForm/index.ts rename to web/src/components/VariableSet/index.ts index 5a61c88030..6caa08734d 100644 --- a/web/src/components/EnvironmentForm/index.ts +++ b/web/src/components/VariableSet/index.ts @@ -1,2 +1,2 @@ // eslint-disable-next-line no-restricted-exports -export {default} from './EnvironmentForm'; +export {default} from './VariableSetForm'; diff --git a/web/src/components/EnvironmentModal/EnvironmentModal.styled.ts b/web/src/components/VariableSetModal/VariableSetModal.styled.ts similarity index 100% rename from web/src/components/EnvironmentModal/EnvironmentModal.styled.ts rename to web/src/components/VariableSetModal/VariableSetModal.styled.ts diff --git a/web/src/components/VariableSetModal/VariableSetModal.tsx b/web/src/components/VariableSetModal/VariableSetModal.tsx new file mode 100644 index 0000000000..070ae7368d --- /dev/null +++ b/web/src/components/VariableSetModal/VariableSetModal.tsx @@ -0,0 +1,68 @@ +import {Form} from 'antd'; +import {useEffect, useState} from 'react'; + +import VariableSetForm from 'components/VariableSet'; +import VariableSet from 'models/VariableSet.model'; +import VariableSetService from 'services/VariableSet.service'; +import * as S from './VariableSetModal.styled'; +import VariableSetModalFooter from './VariableSetModalFooter'; + +interface IProps { + variableSet?: VariableSet; + isOpen: boolean; + isLoading: boolean; + onClose(): void; + onSubmit(variableSet: VariableSet): void; +} + +export const DEFAULT_VALUES = [{key: '', value: ''}]; + +const VariableSetModal = ({variableSet, isOpen, onClose, onSubmit, isLoading}: IProps) => { + const [form] = Form.useForm(); + const [isFormValid, setIsFormValid] = useState(false); + const isEditing = Boolean(variableSet); + + useEffect(() => { + if (variableSet && isOpen) form.setFieldsValue(variableSet); + if (!isOpen || !variableSet) { + form.resetFields(); + form.setFieldsValue({values: [{key: '', value: ''}]}); + } + }, [variableSet, form, isOpen]); + + const handleOnValidate = (changedValues: any, draft: VariableSet) => { + setIsFormValid(VariableSetService.validateDraft(draft)); + }; + + const handleOnSubmit = async (values: VariableSet) => { + onSubmit(values); + onClose(); + }; + + return ( + form.submit()} + /> + } + onCancel={onClose} + title={{isEditing ? 'Edit Variable Set' : 'Create Variable Set'}} + visible={isOpen} + > + + + ); +}; + +export default VariableSetModal; diff --git a/web/src/components/EnvironmentModal/EnvironmentModalFooter.tsx b/web/src/components/VariableSetModal/VariableSetModalFooter.tsx similarity index 77% rename from web/src/components/EnvironmentModal/EnvironmentModalFooter.tsx rename to web/src/components/VariableSetModal/VariableSetModalFooter.tsx index 18ebeee4fb..04af94755e 100644 --- a/web/src/components/EnvironmentModal/EnvironmentModalFooter.tsx +++ b/web/src/components/VariableSetModal/VariableSetModalFooter.tsx @@ -1,6 +1,6 @@ import {Button} from 'antd'; -import * as S from './EnvironmentModal.styled'; +import * as S from './VariableSetModal.styled'; interface IProps { isEditing: boolean; @@ -10,7 +10,7 @@ interface IProps { onSave(): void; } -const EnvironmentModalFooter = ({isEditing, isLoading, isValid, onCancel, onSave}: IProps) => ( +const VariableSetModalFooter = ({isEditing, isLoading, isValid, onCancel, onSave}: IProps) => (