diff --git a/api/openapi.yaml b/api/openapi.yaml index 4822b4ecf2..2565603fa3 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -6,14 +6,14 @@ info: servers: - url: /api paths: - # Transactions - /transactions: + # TestSuites + /testsuites: get: tags: - resource-api - summary: "Get transactions" - description: "get transactions" - operationId: getTransactions + summary: "Get testsuites" + description: "get testsuites" + operationId: getTestSuites parameters: - $ref: "./parameters.yaml#/components/parameters/take" - $ref: "./parameters.yaml#/components/parameters/skip" @@ -26,7 +26,7 @@ paths: content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResourceList" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResourceList" text/yaml: schema: type: object @@ -36,138 +36,138 @@ paths: items: type: array items: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" 400: - description: "invalid query for transactions, some data was sent in incorrect format." + description: "invalid query for testsuites, some data was sent in incorrect format." 500: - description: "problem with getting transactions" + description: "problem with getting testsuites" post: tags: - resource-api - summary: "Create new transaction" - description: "Create new transaction" - operationId: createTransaction + summary: "Create new TestSuite" + description: "Create new TestSuite" + operationId: createTestSuite requestBody: content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" text/yaml: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" responses: 201: description: successful operation content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" text/yaml: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" 400: - description: "trying to create a transaction with an already existing ID" + description: "trying to create a TestSuite with an already existing ID" 500: - description: "problem creating a transaction" - /transactions/{transactionId}: + description: "problem creating a TestSuite" + /testsuites/{testSuiteId}: get: tags: - resource-api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" - summary: "get transaction" - description: "get transaction" - operationId: getTransaction + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" + summary: "get TestSuite" + description: "get TestSuite" + operationId: getTestSuite responses: 200: description: successful operation content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" text/yaml: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" 404: - description: "transaction not found" + description: "TestSuite not found" 500: - description: "problem getting an transaction" + description: "problem getting an TestSuite" put: tags: - resource-api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" - summary: "update transaction" - description: "update transaction action" - operationId: updateTransaction + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" + summary: "update TestSuite" + description: "update TestSuite action" + operationId: updateTestSuite requestBody: content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" text/yaml: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" responses: 200: description: successful operation content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" text/yaml: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionResource" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteResource" 400: - description: "invalid transaction, some data was sent in incorrect format." + description: "invalid TestSuite, some data was sent in incorrect format." 404: - description: "transaction not found" + description: "TestSuite not found" 500: - description: "problem updating a transaction" + description: "problem updating a TestSuite" delete: tags: - resource-api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" - summary: "delete a transaction" - description: "delete a transaction" - operationId: deleteTransaction + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" + summary: "delete a TestSuite" + description: "delete a TestSuite" + operationId: deleteTestSuite responses: 204: description: successful operation 404: - description: "transaction not found" + description: "TestSuite not found" 500: - description: "problem deleting a transaction" - /transactions/{transactionId}/version/{version}: + description: "problem deleting a TestSuite" + /testsuites/{testSuiteId}/version/{version}: get: tags: - api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" - $ref: "./parameters.yaml#/components/parameters/version" - summary: "get a transaction specific version" - description: "get a transaction specific version" - operationId: getTransactionVersion + summary: "get a TestSuite specific version" + description: "get a TestSuite specific version" + operationId: getTestSuiteVersion responses: 200: description: successful operation content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/Transaction" + $ref: "./testsuites.yaml#/components/schemas/TestSuite" 500: description: "problem with getting a test" - /transactions/{transactionId}/run: + /testsuites/{testSuiteId}/run: post: tags: - api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" - summary: "run transaction" - description: "run a particular transaction" - operationId: runTransaction + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" + summary: "run TestSuite" + description: "run a particular TestSuite" + operationId: runTestSuite requestBody: content: application/json: @@ -179,17 +179,17 @@ paths: content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionRun" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteRun" get: tags: - api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" - $ref: "./parameters.yaml#/components/parameters/take" - $ref: "./parameters.yaml#/components/parameters/skip" - summary: "Get all runs from a particular transaction" - description: "Get all runs from a particular transaction" - operationId: getTransactionRuns + summary: "Get all runs from a particular TestSuite" + description: "Get all runs from a particular TestSuite" + operationId: getTestSuiteRuns responses: 200: description: OK @@ -198,41 +198,41 @@ paths: schema: type: array items: - $ref: "./transactions.yaml#/components/schemas/TransactionRun" - /transactions/{transactionId}/run/{runId}: + $ref: "./testsuites.yaml#/components/schemas/TestSuiteRun" + /testsuites/{testSuiteId}/run/{runId}: get: tags: - api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" - $ref: "./parameters.yaml#/components/parameters/runId" - summary: "Get a specific run from a particular transaction" - description: "Get a specific run from a particular transaction" - operationId: getTransactionRun + summary: "Get a specific run from a particular TestSuite" + description: "Get a specific run from a particular TestSuite" + operationId: getTestSuiteRun responses: 200: description: OK content: application/json: schema: - $ref: "./transactions.yaml#/components/schemas/TransactionRun" + $ref: "./testsuites.yaml#/components/schemas/TestSuiteRun" 404: - description: transaction run not found + description: TestSuite run not found delete: tags: - api parameters: - - $ref: "./parameters.yaml#/components/parameters/transactionId" + - $ref: "./parameters.yaml#/components/parameters/testSuiteId" - $ref: "./parameters.yaml#/components/parameters/runId" - summary: "Delete a specific run from a particular transaction" - description: "Delete a specific run from a particular transaction" - operationId: deleteTransactionRun + summary: "Delete a specific run from a particular TestSuite" + description: "Delete a specific run from a particular TestSuite" + operationId: deleteTestSuiteRun responses: 204: description: OK 404: - description: transaction run not found + description: TestSuite run not found # Tests /tests: @@ -613,7 +613,7 @@ paths: schema: $ref: "./expressions.yaml#/components/schemas/ResolveResponseInfo" - # Resources (Tests, Transactions) + # Resources (Tests, TestSuites) /resources: get: tags: @@ -1066,7 +1066,7 @@ paths: tags: - resource-api summary: "Create a VariableSet" - description: "Create a VariableSet that can be used by tests and transactions" + description: "Create a VariableSet that can be used by tests and test suites" operationId: createVariableSet requestBody: content: @@ -1148,10 +1148,10 @@ paths: tags: - resource-api parameters: - - $ref: "./parameters.yaml#/components/parameters/environmentId" - summary: "Delete an environment" - description: "Delete an environment from Tracetest" - operationId: deleteEnvironment + - $ref: "./parameters.yaml#/components/parameters/variableSetId" + summary: "Delete an variable set" + description: "Delete an variable set from Tracetest" + operationId: deleteVariableSet responses: 204: description: successful operation @@ -1160,7 +1160,7 @@ paths: 404: description: "VariableSet not found" 500: - description: "problem deleting an environment" + description: "problem deleting an variable set" /version: get: diff --git a/api/parameters.yaml b/api/parameters.yaml index 9a7a1d08ce..3f332924c3 100644 --- a/api/parameters.yaml +++ b/api/parameters.yaml @@ -28,12 +28,12 @@ components: schema: type: integer - # transaction - transactionId: + # TestSuite + testSuiteId: in: path - name: transactionId + name: testSuiteId required: true - description: id of the transaction + description: id of the TestSuite schema: type: string @@ -130,7 +130,7 @@ components: in: path name: variableSetId required: true - description: "ID of a VariableSet used on Tracetest to inject values into tests and transactions" + description: "ID of a VariableSet used on Tracetest to inject values into tests and TestSuites" schema: type: string diff --git a/api/tests.yaml b/api/tests.yaml index 149c600c57..70a0c4d75c 100644 --- a/api/tests.yaml +++ b/api/tests.yaml @@ -179,7 +179,7 @@ components: description: time in seconds it took for the test to complete, either success or fail. If the test is still running, it will show the time up to the time of the request triggerTime: type: integer - description: time in milliseconds it took for the triggering transaction to complete, either success or fail. If the test is still running, it will show the time up to the time of the request + description: time in milliseconds it took for the triggering testSuite to complete, either success or fail. If the test is still running, it will show the time up to the time of the request createdAt: type: string format: date-time @@ -225,9 +225,9 @@ components: type: object additionalProperties: type: string - transactionId: + testSuiteId: type: string - transactionRunId: + testSuiteRunId: type: string RunInformation: diff --git a/api/transactions.yaml b/api/testsuites.yaml similarity index 75% rename from api/transactions.yaml rename to api/testsuites.yaml index 83f1268255..de0fdc2b86 100644 --- a/api/transactions.yaml +++ b/api/testsuites.yaml @@ -1,7 +1,7 @@ openapi: 3.0.0 components: schemas: - TransactionResourceList: + TestSuiteResourceList: type: object properties: count: @@ -9,21 +9,21 @@ components: items: type: array items: - $ref: "#/components/schemas/TransactionResource" + $ref: "#/components/schemas/TestSuiteResource" - TransactionResource: + TestSuiteResource: type: object - description: "Represents a transaction structured into the Resources format." + description: "Represents a TestSuite structured into the Resources format." properties: type: type: string - description: "Represents the type of this resource. It should always be set as 'Transaction'." + description: "Represents the type of this resource. It should always be set as 'TestSuite'." enum: - - Transaction + - TestSuite spec: - $ref: "#/components/schemas/Transaction" + $ref: "#/components/schemas/TestSuite" - Transaction: + TestSuite: type: object properties: id: @@ -37,12 +37,12 @@ components: description: version number of the test steps: type: array - description: list of steps of the transaction containing just each test id + description: list of steps of the TestSuite containing just each test id items: type: string fullSteps: type: array - description: list of steps of the transaction containing the whole test object + description: list of steps of the TestSuite containing the whole test object items: $ref: "./tests.yaml#/components/schemas/Test" createdAt: @@ -50,10 +50,10 @@ components: format: date-time summary: $ref: "./tests.yaml#/components/schemas/TestSummary" - description: summary of transaction + description: summary of TestSuite readOnly: true - TransactionRun: + TestSuiteRun: type: object properties: id: diff --git a/cli/cmd/resources.go b/cli/cmd/resources.go index 2682d2e28a..9e49f4182b 100644 --- a/cli/cmd/resources.go +++ b/cli/cmd/resources.go @@ -19,17 +19,20 @@ import ( var resourceParams = &resourceParameters{} var ( + testSuiteRunner = runner.TestSuiteRunner( + testSuiteClient, + openapiClient, + formatters.TestSuiteRun(func() string { return cliConfig.URL() }, true), + ) + runnerRegistry = runner.NewRegistry(). - Register(runner.TestRunner( + Register(runner.TestRunner( testClient, openapiClient, formatters.TestRun(func() string { return cliConfig.URL() }, true), )). - Register(runner.TransactionRunner( - transactionClient, - openapiClient, - formatters.TransactionRun(func() string { return cliConfig.URL() }, true), - )) + Register(testSuiteRunner). + RegisterProxy("transaction", testSuiteRunner.Name()) ) var ( @@ -68,7 +71,7 @@ var ( {Header: "URL", Path: "spec.url"}, }, ItemModifier: func(item *gabs.Container) error { - // set spec.summary.steps to the number of steps in the transaction + // set spec.summary.steps to the number of steps in the test suite id, ok := item.Path("spec.id").Data().(string) if !ok { return fmt.Errorf("test id '%s' is not a string", id) @@ -87,7 +90,7 @@ var ( resourcemanager.WithApplyPreProcessor(testPreprocessor.Preprocess), ) - transactionPreprocessor = preprocessor.Transaction(cliLogger, func(ctx context.Context, input fileutil.File) (fileutil.File, error) { + testSuitePreprocessor = preprocessor.TestSuite(cliLogger, func(ctx context.Context, input fileutil.File) (fileutil.File, error) { updated, err := testClient.Apply(ctx, input, resourcemanager.Formats.Get(resourcemanager.FormatYAML)) if err != nil { return input, fmt.Errorf("cannot apply test: %w", err) @@ -96,9 +99,9 @@ var ( return fileutil.New(input.AbsPath(), []byte(updated)), nil }) - transactionClient = resourcemanager.NewClient( + testSuiteClient = resourcemanager.NewClient( httpClient, cliLogger, - "transaction", "transactions", + "testsuite", "testsuites", resourcemanager.WithTableConfig(resourcemanager.TableConfig{ Cells: []resourcemanager.TableCellConfig{ {Header: "ID", Path: "spec.id"}, @@ -111,7 +114,7 @@ var ( {Header: "LAST RUN FAILURES", Path: "spec.summary.lastRun.fails"}, }, ItemModifier: func(item *gabs.Container) error { - // set spec.summary.steps to the number of steps in the transaction + // set spec.summary.steps to the number of steps in the test suite item.SetP(len(item.Path("spec.steps").Children()), "spec.summary.steps") if err := formatItemDate(item, "spec.summary.lastRun.time"); err != nil { @@ -121,7 +124,9 @@ var ( return nil }, }), - resourcemanager.WithApplyPreProcessor(transactionPreprocessor.Preprocess), + resourcemanager.WithResourceType("TestSuite"), + resourcemanager.WithApplyPreProcessor(testSuitePreprocessor.Preprocess), + resourcemanager.WithDeprecatedAlias("Transaction"), ) // deprecated resources @@ -131,6 +136,12 @@ var ( resourcemanager.WithProxyResource("variableset"), ) + deprecatedTransactionsClient = resourcemanager.NewClient( + httpClient, cliLogger, + "transaction", "transactions", + resourcemanager.WithProxyResource("testsuite"), + ) + resources = resourcemanager.NewRegistry(). Register( resourcemanager.NewClient( @@ -240,11 +251,12 @@ var ( ), ). Register(variableSetClient). - Register(transactionClient). + Register(testSuiteClient). Register(testClient). // deprecated resources - Register(deprecatedEnvironmentClient) + Register(deprecatedEnvironmentClient). + Register(deprecatedTransactionsClient) ) func resourceList() string { diff --git a/cli/formatters/transaction_run.go b/cli/formatters/testsuite.go similarity index 61% rename from cli/formatters/transaction_run.go rename to cli/formatters/testsuite.go index 2752e8d254..725d5f5dc3 100644 --- a/cli/formatters/transaction_run.go +++ b/cli/formatters/testsuite.go @@ -9,29 +9,29 @@ import ( "github.com/pterm/pterm" ) -type transactionRun struct { +type testSuiteRun struct { baseURLFn func() string colorsEnabled bool testRunFormatter testRun } -func TransactionRun(baseURLFn func() string, colorsEnabled bool) transactionRun { - return transactionRun{ +func TestSuiteRun(baseURLFn func() string, colorsEnabled bool) testSuiteRun { + return testSuiteRun{ baseURLFn: baseURLFn, colorsEnabled: colorsEnabled, testRunFormatter: TestRun(baseURLFn, colorsEnabled, WithPadding(1)), } } -type TransactionRunOutput struct { - HasResults bool `json:"-"` - Transaction openapi.Transaction `json:"transaction"` - Run openapi.TransactionRun `json:"transactionRun"` - RunWebURL string `json:"transactionRunWebUrl"` +type TestSuiteRunOutput struct { + HasResults bool `json:"-"` + TestSuite openapi.TestSuite `json:"testSuite"` + Run openapi.TestSuiteRun `json:"testSuiteRun"` + RunWebURL string `json:"testSuiteRunWebUrl"` } -func (f transactionRun) Format(output TransactionRunOutput, format Output) string { - output.RunWebURL = f.getRunLink(output.Transaction.GetId(), output.Run.GetId()) +func (f testSuiteRun) Format(output TestSuiteRunOutput, format Output) string { + output.RunWebURL = f.getRunLink(output.TestSuite.GetId(), output.Run.GetId()) switch format { case JSON: @@ -43,13 +43,13 @@ func (f transactionRun) Format(output TransactionRunOutput, format Output) strin return "" } -func (f transactionRun) json(output TransactionRunOutput) string { +func (f testSuiteRun) json(output TestSuiteRunOutput) string { type stepResult struct { Name string `json:"name"` Results openapi.AssertionResults `json:"results"` } - type transactionResult struct { + type testSuiteResult struct { RunWebURL string `json:"testRunWebUrl"` Steps []stepResult `json:"steps"` } @@ -57,14 +57,14 @@ func (f transactionRun) json(output TransactionRunOutput) string { stepsResults := make([]stepResult, 0, len(output.Run.Steps)) for i, step := range output.Run.Steps { - test := output.Transaction.FullSteps[i] + test := output.TestSuite.FullSteps[i] stepsResults = append(stepsResults, stepResult{ Name: *test.Name, Results: *step.Result, }) } - result := transactionResult{ + result := testSuiteResult{ RunWebURL: output.RunWebURL, Steps: stepsResults, } @@ -77,23 +77,23 @@ func (f transactionRun) json(output TransactionRunOutput) string { return string(bytes) + "\n" } -func (f transactionRun) pretty(output TransactionRunOutput) string { - message := fmt.Sprintf("%s %s (%s)\n", PASSED_TEST_ICON, output.Transaction.GetName(), output.RunWebURL) +func (f testSuiteRun) pretty(output TestSuiteRunOutput) string { + message := fmt.Sprintf("%s %s (%s)\n", PASSED_TEST_ICON, output.TestSuite.GetName(), output.RunWebURL) if !output.HasResults { return f.getColoredText(true, message) } - allStepsPassed := f.allTransactionStepsPassed(output) + allStepsPassed := f.allTestSuiteStepsPassed(output) if !allStepsPassed { - message = fmt.Sprintf("%s %s (%s)\n", FAILED_TEST_ICON, output.Transaction.GetName(), output.RunWebURL) + message = fmt.Sprintf("%s %s (%s)\n", FAILED_TEST_ICON, output.TestSuite.GetName(), output.RunWebURL) } - // the transaction name + all steps + // the test suite name + all steps formattedMessages := make([]string, 0, len(output.Run.Steps)+1) formattedMessages = append(formattedMessages, f.getColoredText(allStepsPassed, message)) for i, testRun := range output.Run.Steps { - test := output.Transaction.FullSteps[i] + test := output.TestSuite.FullSteps[i] message := f.testRunFormatter.pretty(TestRunOutput{ HasResults: true, Test: test, @@ -107,7 +107,7 @@ func (f transactionRun) pretty(output TransactionRunOutput) string { return strings.Join(formattedMessages, "") } -func (f transactionRun) allTransactionStepsPassed(output TransactionRunOutput) bool { +func (f testSuiteRun) allTestSuiteStepsPassed(output TestSuiteRunOutput) bool { for _, step := range output.Run.Steps { if !step.Result.GetAllPassed() { return false @@ -116,7 +116,7 @@ func (f transactionRun) allTransactionStepsPassed(output TransactionRunOutput) b return true } -func (f transactionRun) getColoredText(passed bool, text string) string { +func (f testSuiteRun) getColoredText(passed bool, text string) string { if !f.colorsEnabled { return text } @@ -128,6 +128,6 @@ func (f transactionRun) getColoredText(passed bool, text string) string { return pterm.FgRed.Sprintf(text) } -func (f transactionRun) getRunLink(transactionID, runID string) string { - return fmt.Sprintf("%s/transaction/%s/run/%s", f.baseURLFn(), transactionID, runID) +func (f testSuiteRun) getRunLink(tsID, runID string) string { + return fmt.Sprintf("%s/testsuite/%s/run/%s", f.baseURLFn(), tsID, runID) } diff --git a/cli/openapi/api_api.go b/cli/openapi/api_api.go index 0dd9020c7d..21ed613205 100644 --- a/cli/openapi/api_api.go +++ b/cli/openapi/api_api.go @@ -118,51 +118,51 @@ func (a *ApiApiService) DeleteTestRunExecute(r ApiDeleteTestRunRequest) (*http.R return localVarHTTPResponse, nil } -type ApiDeleteTransactionRunRequest struct { - ctx context.Context - ApiService *ApiApiService - transactionId string - runId int32 +type ApiDeleteTestSuiteRunRequest struct { + ctx context.Context + ApiService *ApiApiService + testSuiteId string + runId int32 } -func (r ApiDeleteTransactionRunRequest) Execute() (*http.Response, error) { - return r.ApiService.DeleteTransactionRunExecute(r) +func (r ApiDeleteTestSuiteRunRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteTestSuiteRunExecute(r) } /* -DeleteTransactionRun Delete a specific run from a particular transaction +DeleteTestSuiteRun Delete a specific run from a particular TestSuite -Delete a specific run from a particular transaction +Delete a specific run from a particular TestSuite @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction + @param testSuiteId id of the TestSuite @param runId id of the run - @return ApiDeleteTransactionRunRequest + @return ApiDeleteTestSuiteRunRequest */ -func (a *ApiApiService) DeleteTransactionRun(ctx context.Context, transactionId string, runId int32) ApiDeleteTransactionRunRequest { - return ApiDeleteTransactionRunRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, - runId: runId, +func (a *ApiApiService) DeleteTestSuiteRun(ctx context.Context, testSuiteId string, runId int32) ApiDeleteTestSuiteRunRequest { + return ApiDeleteTestSuiteRunRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, + runId: runId, } } // Execute executes the request -func (a *ApiApiService) DeleteTransactionRunExecute(r ApiDeleteTransactionRunRequest) (*http.Response, error) { +func (a *ApiApiService) DeleteTestSuiteRunExecute(r ApiDeleteTestSuiteRunRequest) (*http.Response, error) { var ( localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} formFiles []formFile ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.DeleteTransactionRun") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.DeleteTestSuiteRun") if err != nil { return nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}/run/{runId}" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) + localVarPath := localBasePath + "/testsuites/{testSuiteId}/run/{runId}" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) localVarPath = strings.Replace(localVarPath, "{"+"runId"+"}", url.PathEscape(parameterValueToString(r.runId, "runId")), -1) localVarHeaderParams := make(map[string]string) @@ -1366,55 +1366,55 @@ func (a *ApiApiService) GetTestSpecsExecute(r ApiGetTestSpecsRequest) ([]TestSpe return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetTestVersionRequest struct { - ctx context.Context - ApiService *ApiApiService - testId string - version int32 +type ApiGetTestSuiteRunRequest struct { + ctx context.Context + ApiService *ApiApiService + testSuiteId string + runId int32 } -func (r ApiGetTestVersionRequest) Execute() (*Test, *http.Response, error) { - return r.ApiService.GetTestVersionExecute(r) +func (r ApiGetTestSuiteRunRequest) Execute() (*TestSuiteRun, *http.Response, error) { + return r.ApiService.GetTestSuiteRunExecute(r) } /* -GetTestVersion get a test specific version +GetTestSuiteRun Get a specific run from a particular TestSuite -get a test specific version +Get a specific run from a particular TestSuite @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param testId id of the test - @param version version of the test - @return ApiGetTestVersionRequest + @param testSuiteId id of the TestSuite + @param runId id of the run + @return ApiGetTestSuiteRunRequest */ -func (a *ApiApiService) GetTestVersion(ctx context.Context, testId string, version int32) ApiGetTestVersionRequest { - return ApiGetTestVersionRequest{ - ApiService: a, - ctx: ctx, - testId: testId, - version: version, +func (a *ApiApiService) GetTestSuiteRun(ctx context.Context, testSuiteId string, runId int32) ApiGetTestSuiteRunRequest { + return ApiGetTestSuiteRunRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, + runId: runId, } } // Execute executes the request // -// @return Test -func (a *ApiApiService) GetTestVersionExecute(r ApiGetTestVersionRequest) (*Test, *http.Response, error) { +// @return TestSuiteRun +func (a *ApiApiService) GetTestSuiteRunExecute(r ApiGetTestSuiteRunRequest) (*TestSuiteRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *Test + localVarReturnValue *TestSuiteRun ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTestVersion") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTestSuiteRun") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/tests/{testId}/version/{version}" - localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version"+"}", url.PathEscape(parameterValueToString(r.version, "version")), -1) + localVarPath := localBasePath + "/testsuites/{testSuiteId}/run/{runId}" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"runId"+"}", url.PathEscape(parameterValueToString(r.runId, "runId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -1474,60 +1474,76 @@ func (a *ApiApiService) GetTestVersionExecute(r ApiGetTestVersionRequest) (*Test return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetTransactionRunRequest struct { - ctx context.Context - ApiService *ApiApiService - transactionId string - runId int32 +type ApiGetTestSuiteRunsRequest struct { + ctx context.Context + ApiService *ApiApiService + testSuiteId string + take *int32 + skip *int32 +} + +// indicates how many resources can be returned by each page +func (r ApiGetTestSuiteRunsRequest) Take(take int32) ApiGetTestSuiteRunsRequest { + r.take = &take + return r } -func (r ApiGetTransactionRunRequest) Execute() (*TransactionRun, *http.Response, error) { - return r.ApiService.GetTransactionRunExecute(r) +// indicates how many resources will be skipped when paginating +func (r ApiGetTestSuiteRunsRequest) Skip(skip int32) ApiGetTestSuiteRunsRequest { + r.skip = &skip + return r +} + +func (r ApiGetTestSuiteRunsRequest) Execute() ([]TestSuiteRun, *http.Response, error) { + return r.ApiService.GetTestSuiteRunsExecute(r) } /* -GetTransactionRun Get a specific run from a particular transaction +GetTestSuiteRuns Get all runs from a particular TestSuite -Get a specific run from a particular transaction +Get all runs from a particular TestSuite @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction - @param runId id of the run - @return ApiGetTransactionRunRequest + @param testSuiteId id of the TestSuite + @return ApiGetTestSuiteRunsRequest */ -func (a *ApiApiService) GetTransactionRun(ctx context.Context, transactionId string, runId int32) ApiGetTransactionRunRequest { - return ApiGetTransactionRunRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, - runId: runId, +func (a *ApiApiService) GetTestSuiteRuns(ctx context.Context, testSuiteId string) ApiGetTestSuiteRunsRequest { + return ApiGetTestSuiteRunsRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, } } // Execute executes the request // -// @return TransactionRun -func (a *ApiApiService) GetTransactionRunExecute(r ApiGetTransactionRunRequest) (*TransactionRun, *http.Response, error) { +// @return []TestSuiteRun +func (a *ApiApiService) GetTestSuiteRunsExecute(r ApiGetTestSuiteRunsRequest) ([]TestSuiteRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TransactionRun + localVarReturnValue []TestSuiteRun ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTransactionRun") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTestSuiteRuns") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}/run/{runId}" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) - localVarPath = strings.Replace(localVarPath, "{"+"runId"+"}", url.PathEscape(parameterValueToString(r.runId, "runId")), -1) + localVarPath := localBasePath + "/testsuites/{testSuiteId}/run" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} + if r.take != nil { + parameterAddToQuery(localVarQueryParams, "take", r.take, "") + } + if r.skip != nil { + parameterAddToQuery(localVarQueryParams, "skip", r.skip, "") + } // to determine the Content-Type header localVarHTTPContentTypes := []string{} @@ -1582,76 +1598,60 @@ func (a *ApiApiService) GetTransactionRunExecute(r ApiGetTransactionRunRequest) return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetTransactionRunsRequest struct { - ctx context.Context - ApiService *ApiApiService - transactionId string - take *int32 - skip *int32 -} - -// indicates how many resources can be returned by each page -func (r ApiGetTransactionRunsRequest) Take(take int32) ApiGetTransactionRunsRequest { - r.take = &take - return r -} - -// indicates how many resources will be skipped when paginating -func (r ApiGetTransactionRunsRequest) Skip(skip int32) ApiGetTransactionRunsRequest { - r.skip = &skip - return r +type ApiGetTestSuiteVersionRequest struct { + ctx context.Context + ApiService *ApiApiService + testSuiteId string + version int32 } -func (r ApiGetTransactionRunsRequest) Execute() ([]TransactionRun, *http.Response, error) { - return r.ApiService.GetTransactionRunsExecute(r) +func (r ApiGetTestSuiteVersionRequest) Execute() (*TestSuite, *http.Response, error) { + return r.ApiService.GetTestSuiteVersionExecute(r) } /* -GetTransactionRuns Get all runs from a particular transaction +GetTestSuiteVersion get a TestSuite specific version -Get all runs from a particular transaction +get a TestSuite specific version @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 ApiGetTransactionRunsRequest + @param testSuiteId id of the TestSuite + @param version version of the test + @return ApiGetTestSuiteVersionRequest */ -func (a *ApiApiService) GetTransactionRuns(ctx context.Context, transactionId string) ApiGetTransactionRunsRequest { - return ApiGetTransactionRunsRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, +func (a *ApiApiService) GetTestSuiteVersion(ctx context.Context, testSuiteId string, version int32) ApiGetTestSuiteVersionRequest { + return ApiGetTestSuiteVersionRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, + version: version, } } // Execute executes the request // -// @return []TransactionRun -func (a *ApiApiService) GetTransactionRunsExecute(r ApiGetTransactionRunsRequest) ([]TransactionRun, *http.Response, error) { +// @return TestSuite +func (a *ApiApiService) GetTestSuiteVersionExecute(r ApiGetTestSuiteVersionRequest) (*TestSuite, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue []TransactionRun + localVarReturnValue *TestSuite ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTransactionRuns") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTestSuiteVersion") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}/run" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) + localVarPath := localBasePath + "/testsuites/{testSuiteId}/version/{version}" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version"+"}", url.PathEscape(parameterValueToString(r.version, "version")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if r.take != nil { - parameterAddToQuery(localVarQueryParams, "take", r.take, "") - } - if r.skip != nil { - parameterAddToQuery(localVarQueryParams, "skip", r.skip, "") - } // to determine the Content-Type header localVarHTTPContentTypes := []string{} @@ -1706,54 +1706,54 @@ func (a *ApiApiService) GetTransactionRunsExecute(r ApiGetTransactionRunsRequest return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetTransactionVersionRequest struct { - ctx context.Context - ApiService *ApiApiService - transactionId string - version int32 +type ApiGetTestVersionRequest struct { + ctx context.Context + ApiService *ApiApiService + testId string + version int32 } -func (r ApiGetTransactionVersionRequest) Execute() (*Transaction, *http.Response, error) { - return r.ApiService.GetTransactionVersionExecute(r) +func (r ApiGetTestVersionRequest) Execute() (*Test, *http.Response, error) { + return r.ApiService.GetTestVersionExecute(r) } /* -GetTransactionVersion get a transaction specific version +GetTestVersion get a test specific version -get a transaction specific version +get a test specific version @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @param transactionId id of the transaction + @param testId id of the test @param version version of the test - @return ApiGetTransactionVersionRequest + @return ApiGetTestVersionRequest */ -func (a *ApiApiService) GetTransactionVersion(ctx context.Context, transactionId string, version int32) ApiGetTransactionVersionRequest { - return ApiGetTransactionVersionRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, - version: version, +func (a *ApiApiService) GetTestVersion(ctx context.Context, testId string, version int32) ApiGetTestVersionRequest { + return ApiGetTestVersionRequest{ + ApiService: a, + ctx: ctx, + testId: testId, + version: version, } } // Execute executes the request // -// @return Transaction -func (a *ApiApiService) GetTransactionVersionExecute(r ApiGetTransactionVersionRequest) (*Transaction, *http.Response, error) { +// @return Test +func (a *ApiApiService) GetTestVersionExecute(r ApiGetTestVersionRequest) (*Test, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *Transaction + localVarReturnValue *Test ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTransactionVersion") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.GetTestVersion") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}/version/{version}" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) + localVarPath := localBasePath + "/tests/{testId}/version/{version}" + localVarPath = strings.Replace(localVarPath, "{"+"testId"+"}", url.PathEscape(parameterValueToString(r.testId, "testId")), -1) localVarPath = strings.Replace(localVarPath, "{"+"version"+"}", url.PathEscape(parameterValueToString(r.version, "version")), -1) localVarHeaderParams := make(map[string]string) @@ -2252,57 +2252,57 @@ func (a *ApiApiService) RunTestExecute(r ApiRunTestRequest) (*TestRun, *http.Res return localVarReturnValue, localVarHTTPResponse, nil } -type ApiRunTransactionRequest struct { +type ApiRunTestSuiteRequest struct { ctx context.Context ApiService *ApiApiService - transactionId string + testSuiteId string runInformation *RunInformation } -func (r ApiRunTransactionRequest) RunInformation(runInformation RunInformation) ApiRunTransactionRequest { +func (r ApiRunTestSuiteRequest) RunInformation(runInformation RunInformation) ApiRunTestSuiteRequest { r.runInformation = &runInformation return r } -func (r ApiRunTransactionRequest) Execute() (*TransactionRun, *http.Response, error) { - return r.ApiService.RunTransactionExecute(r) +func (r ApiRunTestSuiteRequest) Execute() (*TestSuiteRun, *http.Response, error) { + return r.ApiService.RunTestSuiteExecute(r) } /* -RunTransaction run transaction +RunTestSuite run TestSuite -run a particular transaction +run a particular TestSuite @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 ApiRunTransactionRequest + @param testSuiteId id of the TestSuite + @return ApiRunTestSuiteRequest */ -func (a *ApiApiService) RunTransaction(ctx context.Context, transactionId string) ApiRunTransactionRequest { - return ApiRunTransactionRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, +func (a *ApiApiService) RunTestSuite(ctx context.Context, testSuiteId string) ApiRunTestSuiteRequest { + return ApiRunTestSuiteRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, } } // Execute executes the request // -// @return TransactionRun -func (a *ApiApiService) RunTransactionExecute(r ApiRunTransactionRequest) (*TransactionRun, *http.Response, error) { +// @return TestSuiteRun +func (a *ApiApiService) RunTestSuiteExecute(r ApiRunTestSuiteRequest) (*TestSuiteRun, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TransactionRun + localVarReturnValue *TestSuiteRun ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.RunTransaction") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ApiApiService.RunTestSuite") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}/run" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) + localVarPath := localBasePath + "/testsuites/{testSuiteId}/run" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} diff --git a/cli/openapi/api_resource_api.go b/cli/openapi/api_resource_api.go index b5dc3d1cca..c701ab410e 100644 --- a/cli/openapi/api_resource_api.go +++ b/cli/openapi/api_resource_api.go @@ -346,31 +346,31 @@ func (a *ResourceApiApiService) CreateTestExecute(r ApiCreateTestRequest) (*Test return localVarReturnValue, localVarHTTPResponse, nil } -type ApiCreateTransactionRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - transactionResource *TransactionResource +type ApiCreateTestSuiteRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + testSuiteResource *TestSuiteResource } -func (r ApiCreateTransactionRequest) TransactionResource(transactionResource TransactionResource) ApiCreateTransactionRequest { - r.transactionResource = &transactionResource +func (r ApiCreateTestSuiteRequest) TestSuiteResource(testSuiteResource TestSuiteResource) ApiCreateTestSuiteRequest { + r.testSuiteResource = &testSuiteResource return r } -func (r ApiCreateTransactionRequest) Execute() (*TransactionResource, *http.Response, error) { - return r.ApiService.CreateTransactionExecute(r) +func (r ApiCreateTestSuiteRequest) Execute() (*TestSuiteResource, *http.Response, error) { + return r.ApiService.CreateTestSuiteExecute(r) } /* -CreateTransaction Create new transaction +CreateTestSuite Create new TestSuite -Create new transaction +Create new TestSuite @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiCreateTransactionRequest + @return ApiCreateTestSuiteRequest */ -func (a *ResourceApiApiService) CreateTransaction(ctx context.Context) ApiCreateTransactionRequest { - return ApiCreateTransactionRequest{ +func (a *ResourceApiApiService) CreateTestSuite(ctx context.Context) ApiCreateTestSuiteRequest { + return ApiCreateTestSuiteRequest{ ApiService: a, ctx: ctx, } @@ -378,21 +378,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 TestSuiteResource +func (a *ResourceApiApiService) CreateTestSuiteExecute(r ApiCreateTestSuiteRequest) (*TestSuiteResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPost localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TransactionResource + localVarReturnValue *TestSuiteResource ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateTransaction") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.CreateTestSuite") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions" + localVarPath := localBasePath + "/testsuites" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -416,7 +416,7 @@ func (a *ResourceApiApiService) CreateTransactionExecute(r ApiCreateTransactionR localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = r.transactionResource + localVarPostBody = r.testSuiteResource req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -470,9 +470,9 @@ func (r ApiCreateVariableSetRequest) Execute() (*VariableSetResource, *http.Resp } /* -CreateVariableSet Create an VariableSet +CreateVariableSet Create a VariableSet -Create an VariableSet that can be used by tests and transactions +Create a VariableSet that can be used by tests and test suites @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). @return ApiCreateVariableSetRequest @@ -930,48 +930,48 @@ func (a *ResourceApiApiService) DeleteTestExecute(r ApiDeleteTestRequest) (*http return localVarHTTPResponse, nil } -type ApiDeleteTransactionRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - transactionId string +type ApiDeleteTestSuiteRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + testSuiteId string } -func (r ApiDeleteTransactionRequest) Execute() (*http.Response, error) { - return r.ApiService.DeleteTransactionExecute(r) +func (r ApiDeleteTestSuiteRequest) Execute() (*http.Response, error) { + return r.ApiService.DeleteTestSuiteExecute(r) } /* -DeleteTransaction delete a transaction +DeleteTestSuite delete a TestSuite -delete a transaction +delete a TestSuite @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 testSuiteId id of the TestSuite + @return ApiDeleteTestSuiteRequest */ -func (a *ResourceApiApiService) DeleteTransaction(ctx context.Context, transactionId string) ApiDeleteTransactionRequest { - return ApiDeleteTransactionRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, +func (a *ResourceApiApiService) DeleteTestSuite(ctx context.Context, testSuiteId string) ApiDeleteTestSuiteRequest { + return ApiDeleteTestSuiteRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, } } // Execute executes the request -func (a *ResourceApiApiService) DeleteTransactionExecute(r ApiDeleteTransactionRequest) (*http.Response, error) { +func (a *ResourceApiApiService) DeleteTestSuiteExecute(r ApiDeleteTestSuiteRequest) (*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.DeleteTestSuite") 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 + "/testsuites/{testSuiteId}" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -1033,12 +1033,12 @@ func (r ApiDeleteVariableSetRequest) Execute() (*http.Response, error) { } /* -DeleteVariableSet Delete an VariableSet +DeleteVariableSet Delete an variable set -Delete an VariableSet from Tracetest +Delete an variable set from 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 + @param variableSetId ID of a VariableSet used on Tracetest to inject values into tests and TestSuites @return ApiDeleteVariableSetRequest */ func (a *ResourceApiApiService) DeleteVariableSet(ctx context.Context, variableSetId string) ApiDeleteVariableSetRequest { @@ -1634,102 +1634,56 @@ func (a *ResourceApiApiService) GetPollingProfileExecute(r ApiGetPollingProfileR return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetTestsRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - take *int32 - skip *int32 - query *string - sortBy *string - sortDirection *string -} - -// indicates how many resources can be returned by each page -func (r ApiGetTestsRequest) Take(take int32) ApiGetTestsRequest { - r.take = &take - return r -} - -// indicates how many resources will be skipped when paginating -func (r ApiGetTestsRequest) Skip(skip int32) ApiGetTestsRequest { - r.skip = &skip - return r -} - -// query to search resources -func (r ApiGetTestsRequest) Query(query string) ApiGetTestsRequest { - r.query = &query - return r -} - -// indicates the sort field for the resources -func (r ApiGetTestsRequest) SortBy(sortBy string) ApiGetTestsRequest { - r.sortBy = &sortBy - return r -} - -// indicates the sort direction for the resources -func (r ApiGetTestsRequest) SortDirection(sortDirection string) ApiGetTestsRequest { - r.sortDirection = &sortDirection - return r +type ApiGetTestSuiteRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + testSuiteId string } -func (r ApiGetTestsRequest) Execute() (*TestResourceList, *http.Response, error) { - return r.ApiService.GetTestsExecute(r) +func (r ApiGetTestSuiteRequest) Execute() (*TestSuiteResource, *http.Response, error) { + return r.ApiService.GetTestSuiteExecute(r) } /* -GetTests Get tests +GetTestSuite get TestSuite -get tests +get TestSuite @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiGetTestsRequest + @param testSuiteId id of the TestSuite + @return ApiGetTestSuiteRequest */ -func (a *ResourceApiApiService) GetTests(ctx context.Context) ApiGetTestsRequest { - return ApiGetTestsRequest{ - ApiService: a, - ctx: ctx, +func (a *ResourceApiApiService) GetTestSuite(ctx context.Context, testSuiteId string) ApiGetTestSuiteRequest { + return ApiGetTestSuiteRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, } } // Execute executes the request // -// @return TestResourceList -func (a *ResourceApiApiService) GetTestsExecute(r ApiGetTestsRequest) (*TestResourceList, *http.Response, error) { +// @return TestSuiteResource +func (a *ResourceApiApiService) GetTestSuiteExecute(r ApiGetTestSuiteRequest) (*TestSuiteResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TestResourceList + localVarReturnValue *TestSuiteResource ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetTests") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetTestSuite") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/tests" + localVarPath := localBasePath + "/testsuites/{testSuiteId}" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if r.take != nil { - parameterAddToQuery(localVarQueryParams, "take", r.take, "") - } - if r.skip != nil { - parameterAddToQuery(localVarQueryParams, "skip", r.skip, "") - } - if r.query != nil { - parameterAddToQuery(localVarQueryParams, "query", r.query, "") - } - if r.sortBy != nil { - parameterAddToQuery(localVarQueryParams, "sortBy", r.sortBy, "") - } - if r.sortDirection != nil { - parameterAddToQuery(localVarQueryParams, "sortDirection", r.sortDirection, "") - } // to determine the Content-Type header localVarHTTPContentTypes := []string{} @@ -1784,56 +1738,102 @@ func (a *ResourceApiApiService) GetTestsExecute(r ApiGetTestsRequest) (*TestReso return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetTransactionRequest struct { +type ApiGetTestSuitesRequest struct { ctx context.Context ApiService *ResourceApiApiService - transactionId string + take *int32 + skip *int32 + query *string + sortBy *string + sortDirection *string +} + +// indicates how many resources can be returned by each page +func (r ApiGetTestSuitesRequest) Take(take int32) ApiGetTestSuitesRequest { + r.take = &take + return r } -func (r ApiGetTransactionRequest) Execute() (*TransactionResource, *http.Response, error) { - return r.ApiService.GetTransactionExecute(r) +// indicates how many resources will be skipped when paginating +func (r ApiGetTestSuitesRequest) Skip(skip int32) ApiGetTestSuitesRequest { + r.skip = &skip + return r +} + +// query to search resources +func (r ApiGetTestSuitesRequest) Query(query string) ApiGetTestSuitesRequest { + r.query = &query + return r +} + +// indicates the sort field for the resources +func (r ApiGetTestSuitesRequest) SortBy(sortBy string) ApiGetTestSuitesRequest { + r.sortBy = &sortBy + return r +} + +// indicates the sort direction for the resources +func (r ApiGetTestSuitesRequest) SortDirection(sortDirection string) ApiGetTestSuitesRequest { + r.sortDirection = &sortDirection + return r +} + +func (r ApiGetTestSuitesRequest) Execute() (*TestSuiteResourceList, *http.Response, error) { + return r.ApiService.GetTestSuitesExecute(r) } /* -GetTransaction get transaction +GetTestSuites Get testsuites -get transaction +get testsuites @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 ApiGetTransactionRequest + @return ApiGetTestSuitesRequest */ -func (a *ResourceApiApiService) GetTransaction(ctx context.Context, transactionId string) ApiGetTransactionRequest { - return ApiGetTransactionRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, +func (a *ResourceApiApiService) GetTestSuites(ctx context.Context) ApiGetTestSuitesRequest { + return ApiGetTestSuitesRequest{ + ApiService: a, + ctx: ctx, } } // Execute executes the request // -// @return TransactionResource -func (a *ResourceApiApiService) GetTransactionExecute(r ApiGetTransactionRequest) (*TransactionResource, *http.Response, error) { +// @return TestSuiteResourceList +func (a *ResourceApiApiService) GetTestSuitesExecute(r ApiGetTestSuitesRequest) (*TestSuiteResourceList, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TransactionResource + localVarReturnValue *TestSuiteResourceList ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetTransaction") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetTestSuites") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) + localVarPath := localBasePath + "/testsuites" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} + if r.take != nil { + parameterAddToQuery(localVarQueryParams, "take", r.take, "") + } + if r.skip != nil { + parameterAddToQuery(localVarQueryParams, "skip", r.skip, "") + } + if r.query != nil { + parameterAddToQuery(localVarQueryParams, "query", r.query, "") + } + if r.sortBy != nil { + parameterAddToQuery(localVarQueryParams, "sortBy", r.sortBy, "") + } + if r.sortDirection != nil { + parameterAddToQuery(localVarQueryParams, "sortDirection", r.sortDirection, "") + } // to determine the Content-Type header localVarHTTPContentTypes := []string{} @@ -1888,7 +1888,7 @@ func (a *ResourceApiApiService) GetTransactionExecute(r ApiGetTransactionRequest return localVarReturnValue, localVarHTTPResponse, nil } -type ApiGetTransactionsRequest struct { +type ApiGetTestsRequest struct { ctx context.Context ApiService *ResourceApiApiService take *int32 @@ -1899,49 +1899,49 @@ type ApiGetTransactionsRequest struct { } // indicates how many resources can be returned by each page -func (r ApiGetTransactionsRequest) Take(take int32) ApiGetTransactionsRequest { +func (r ApiGetTestsRequest) Take(take int32) ApiGetTestsRequest { r.take = &take return r } // indicates how many resources will be skipped when paginating -func (r ApiGetTransactionsRequest) Skip(skip int32) ApiGetTransactionsRequest { +func (r ApiGetTestsRequest) Skip(skip int32) ApiGetTestsRequest { r.skip = &skip return r } // query to search resources -func (r ApiGetTransactionsRequest) Query(query string) ApiGetTransactionsRequest { +func (r ApiGetTestsRequest) Query(query string) ApiGetTestsRequest { r.query = &query return r } // indicates the sort field for the resources -func (r ApiGetTransactionsRequest) SortBy(sortBy string) ApiGetTransactionsRequest { +func (r ApiGetTestsRequest) SortBy(sortBy string) ApiGetTestsRequest { r.sortBy = &sortBy return r } // indicates the sort direction for the resources -func (r ApiGetTransactionsRequest) SortDirection(sortDirection string) ApiGetTransactionsRequest { +func (r ApiGetTestsRequest) SortDirection(sortDirection string) ApiGetTestsRequest { r.sortDirection = &sortDirection return r } -func (r ApiGetTransactionsRequest) Execute() (*TransactionResourceList, *http.Response, error) { - return r.ApiService.GetTransactionsExecute(r) +func (r ApiGetTestsRequest) Execute() (*TestResourceList, *http.Response, error) { + return r.ApiService.GetTestsExecute(r) } /* -GetTransactions Get transactions +GetTests Get tests -get transactions +get tests @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - @return ApiGetTransactionsRequest + @return ApiGetTestsRequest */ -func (a *ResourceApiApiService) GetTransactions(ctx context.Context) ApiGetTransactionsRequest { - return ApiGetTransactionsRequest{ +func (a *ResourceApiApiService) GetTests(ctx context.Context) ApiGetTestsRequest { + return ApiGetTestsRequest{ ApiService: a, ctx: ctx, } @@ -1949,21 +1949,21 @@ func (a *ResourceApiApiService) GetTransactions(ctx context.Context) ApiGetTrans // Execute executes the request // -// @return TransactionResourceList -func (a *ResourceApiApiService) GetTransactionsExecute(r ApiGetTransactionsRequest) (*TransactionResourceList, *http.Response, error) { +// @return TestResourceList +func (a *ResourceApiApiService) GetTestsExecute(r ApiGetTestsRequest) (*TestResourceList, *http.Response, error) { var ( localVarHTTPMethod = http.MethodGet localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TransactionResourceList + localVarReturnValue *TestResourceList ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetTransactions") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.GetTests") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions" + localVarPath := localBasePath + "/tests" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -2054,7 +2054,7 @@ 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 + @param variableSetId ID of a VariableSet used on Tracetest to inject values into tests and TestSuites @return ApiGetVariableSetRequest */ func (a *ResourceApiApiService) GetVariableSet(ctx context.Context, variableSetId string) ApiGetVariableSetRequest { @@ -2880,9 +2880,9 @@ func (r ApiListVariableSetsRequest) Execute() (*VariableSetResourceList, *http.R } /* -ListVariableSets List variableSets +ListVariableSets List VariableSets -List variableSets available in Tracetest. +List VariableSets available in Tracetest. @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). @return ApiListVariableSetsRequest @@ -3734,57 +3734,57 @@ func (a *ResourceApiApiService) UpdateTestExecute(r ApiUpdateTestRequest) (*http return localVarHTTPResponse, nil } -type ApiUpdateTransactionRequest struct { - ctx context.Context - ApiService *ResourceApiApiService - transactionId string - transactionResource *TransactionResource +type ApiUpdateTestSuiteRequest struct { + ctx context.Context + ApiService *ResourceApiApiService + testSuiteId string + testSuiteResource *TestSuiteResource } -func (r ApiUpdateTransactionRequest) TransactionResource(transactionResource TransactionResource) ApiUpdateTransactionRequest { - r.transactionResource = &transactionResource +func (r ApiUpdateTestSuiteRequest) TestSuiteResource(testSuiteResource TestSuiteResource) ApiUpdateTestSuiteRequest { + r.testSuiteResource = &testSuiteResource return r } -func (r ApiUpdateTransactionRequest) Execute() (*TransactionResource, *http.Response, error) { - return r.ApiService.UpdateTransactionExecute(r) +func (r ApiUpdateTestSuiteRequest) Execute() (*TestSuiteResource, *http.Response, error) { + return r.ApiService.UpdateTestSuiteExecute(r) } /* -UpdateTransaction update transaction +UpdateTestSuite update TestSuite -update transaction action +update TestSuite action @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 ApiUpdateTransactionRequest + @param testSuiteId id of the TestSuite + @return ApiUpdateTestSuiteRequest */ -func (a *ResourceApiApiService) UpdateTransaction(ctx context.Context, transactionId string) ApiUpdateTransactionRequest { - return ApiUpdateTransactionRequest{ - ApiService: a, - ctx: ctx, - transactionId: transactionId, +func (a *ResourceApiApiService) UpdateTestSuite(ctx context.Context, testSuiteId string) ApiUpdateTestSuiteRequest { + return ApiUpdateTestSuiteRequest{ + ApiService: a, + ctx: ctx, + testSuiteId: testSuiteId, } } // Execute executes the request // -// @return TransactionResource -func (a *ResourceApiApiService) UpdateTransactionExecute(r ApiUpdateTransactionRequest) (*TransactionResource, *http.Response, error) { +// @return TestSuiteResource +func (a *ResourceApiApiService) UpdateTestSuiteExecute(r ApiUpdateTestSuiteRequest) (*TestSuiteResource, *http.Response, error) { var ( localVarHTTPMethod = http.MethodPut localVarPostBody interface{} formFiles []formFile - localVarReturnValue *TransactionResource + localVarReturnValue *TestSuiteResource ) - localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.UpdateTransaction") + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ResourceApiApiService.UpdateTestSuite") if err != nil { return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} } - localVarPath := localBasePath + "/transactions/{transactionId}" - localVarPath = strings.Replace(localVarPath, "{"+"transactionId"+"}", url.PathEscape(parameterValueToString(r.transactionId, "transactionId")), -1) + localVarPath := localBasePath + "/testsuites/{testSuiteId}" + localVarPath = strings.Replace(localVarPath, "{"+"testSuiteId"+"}", url.PathEscape(parameterValueToString(r.testSuiteId, "testSuiteId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -3808,7 +3808,7 @@ func (a *ResourceApiApiService) UpdateTransactionExecute(r ApiUpdateTransactionR localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = r.transactionResource + localVarPostBody = r.testSuiteResource req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err @@ -3863,12 +3863,12 @@ func (r ApiUpdateVariableSetRequest) Execute() (*VariableSetResource, *http.Resp } /* -UpdateVariableSet Update an VariableSet +UpdateVariableSet Update a VariableSet -Update an VariableSet used on Tracetest +Update a 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 + @param variableSetId ID of a VariableSet used on Tracetest to inject values into tests and TestSuites @return ApiUpdateVariableSetRequest */ func (a *ResourceApiApiService) UpdateVariableSet(ctx context.Context, variableSetId string) ApiUpdateVariableSetRequest { diff --git a/cli/openapi/model_get_test_suites_200_response.go b/cli/openapi/model_get_test_suites_200_response.go new file mode 100644 index 0000000000..f8296f0d73 --- /dev/null +++ b/cli/openapi/model_get_test_suites_200_response.go @@ -0,0 +1,160 @@ +/* +TraceTest + +OpenAPI definition for TraceTest endpoint and resources + +API version: 0.2.1 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// checks if the GetTestSuites200Response type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &GetTestSuites200Response{} + +// GetTestSuites200Response struct for GetTestSuites200Response +type GetTestSuites200Response struct { + Count *int32 `json:"count,omitempty"` + Items []TestSuiteResource `json:"items,omitempty"` +} + +// NewGetTestSuites200Response instantiates a new GetTestSuites200Response 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 NewGetTestSuites200Response() *GetTestSuites200Response { + this := GetTestSuites200Response{} + return &this +} + +// NewGetTestSuites200ResponseWithDefaults instantiates a new GetTestSuites200Response 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 NewGetTestSuites200ResponseWithDefaults() *GetTestSuites200Response { + this := GetTestSuites200Response{} + return &this +} + +// GetCount returns the Count field value if set, zero value otherwise. +func (o *GetTestSuites200Response) GetCount() int32 { + if o == nil || isNil(o.Count) { + var ret int32 + return ret + } + return *o.Count +} + +// 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 *GetTestSuites200Response) GetCountOk() (*int32, bool) { + if o == nil || isNil(o.Count) { + return nil, false + } + return o.Count, true +} + +// HasCount returns a boolean if a field has been set. +func (o *GetTestSuites200Response) HasCount() bool { + if o != nil && !isNil(o.Count) { + return true + } + + return false +} + +// SetCount gets a reference to the given int32 and assigns it to the Count field. +func (o *GetTestSuites200Response) SetCount(v int32) { + o.Count = &v +} + +// GetItems returns the Items field value if set, zero value otherwise. +func (o *GetTestSuites200Response) GetItems() []TestSuiteResource { + if o == nil || isNil(o.Items) { + var ret []TestSuiteResource + return ret + } + return o.Items +} + +// 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 *GetTestSuites200Response) GetItemsOk() ([]TestSuiteResource, bool) { + if o == nil || isNil(o.Items) { + return nil, false + } + return o.Items, true +} + +// HasItems returns a boolean if a field has been set. +func (o *GetTestSuites200Response) HasItems() bool { + if o != nil && !isNil(o.Items) { + return true + } + + return false +} + +// SetItems gets a reference to the given []TestSuiteResource and assigns it to the Items field. +func (o *GetTestSuites200Response) SetItems(v []TestSuiteResource) { + o.Items = v +} + +func (o GetTestSuites200Response) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o GetTestSuites200Response) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !isNil(o.Count) { + toSerialize["count"] = o.Count + } + if !isNil(o.Items) { + toSerialize["items"] = o.Items + } + return toSerialize, nil +} + +type NullableGetTestSuites200Response struct { + value *GetTestSuites200Response + isSet bool +} + +func (v NullableGetTestSuites200Response) Get() *GetTestSuites200Response { + return v.value +} + +func (v *NullableGetTestSuites200Response) Set(val *GetTestSuites200Response) { + v.value = val + v.isSet = true +} + +func (v NullableGetTestSuites200Response) IsSet() bool { + return v.isSet +} + +func (v *NullableGetTestSuites200Response) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableGetTestSuites200Response(val *GetTestSuites200Response) *NullableGetTestSuites200Response { + return &NullableGetTestSuites200Response{value: val, isSet: true} +} + +func (v NullableGetTestSuites200Response) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableGetTestSuites200Response) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/cli/openapi/model_get_transactions_200_response.go b/cli/openapi/model_get_transactions_200_response.go deleted file mode 100644 index 7db02ef53f..0000000000 --- a/cli/openapi/model_get_transactions_200_response.go +++ /dev/null @@ -1,160 +0,0 @@ -/* -TraceTest - -OpenAPI definition for TraceTest endpoint and resources - -API version: 0.2.1 -*/ - -// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. - -package openapi - -import ( - "encoding/json" -) - -// checks if the GetTransactions200Response type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &GetTransactions200Response{} - -// GetTransactions200Response struct for GetTransactions200Response -type GetTransactions200Response struct { - Count *int32 `json:"count,omitempty"` - Items []TransactionResource `json:"items,omitempty"` -} - -// NewGetTransactions200Response instantiates a new GetTransactions200Response 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 NewGetTransactions200Response() *GetTransactions200Response { - this := GetTransactions200Response{} - return &this -} - -// NewGetTransactions200ResponseWithDefaults instantiates a new GetTransactions200Response 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 NewGetTransactions200ResponseWithDefaults() *GetTransactions200Response { - this := GetTransactions200Response{} - return &this -} - -// GetCount returns the Count field value if set, zero value otherwise. -func (o *GetTransactions200Response) GetCount() int32 { - if o == nil || isNil(o.Count) { - var ret int32 - return ret - } - return *o.Count -} - -// 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 *GetTransactions200Response) GetCountOk() (*int32, bool) { - if o == nil || isNil(o.Count) { - return nil, false - } - return o.Count, true -} - -// HasCount returns a boolean if a field has been set. -func (o *GetTransactions200Response) HasCount() bool { - if o != nil && !isNil(o.Count) { - return true - } - - return false -} - -// SetCount gets a reference to the given int32 and assigns it to the Count field. -func (o *GetTransactions200Response) SetCount(v int32) { - o.Count = &v -} - -// GetItems returns the Items field value if set, zero value otherwise. -func (o *GetTransactions200Response) GetItems() []TransactionResource { - if o == nil || isNil(o.Items) { - var ret []TransactionResource - return ret - } - return o.Items -} - -// 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 *GetTransactions200Response) GetItemsOk() ([]TransactionResource, bool) { - if o == nil || isNil(o.Items) { - return nil, false - } - return o.Items, true -} - -// HasItems returns a boolean if a field has been set. -func (o *GetTransactions200Response) HasItems() bool { - if o != nil && !isNil(o.Items) { - return true - } - - return false -} - -// SetItems gets a reference to the given []TransactionResource and assigns it to the Items field. -func (o *GetTransactions200Response) SetItems(v []TransactionResource) { - o.Items = v -} - -func (o GetTransactions200Response) MarshalJSON() ([]byte, error) { - toSerialize, err := o.ToMap() - if err != nil { - return []byte{}, err - } - return json.Marshal(toSerialize) -} - -func (o GetTransactions200Response) ToMap() (map[string]interface{}, error) { - toSerialize := map[string]interface{}{} - if !isNil(o.Count) { - toSerialize["count"] = o.Count - } - if !isNil(o.Items) { - toSerialize["items"] = o.Items - } - return toSerialize, nil -} - -type NullableGetTransactions200Response struct { - value *GetTransactions200Response - isSet bool -} - -func (v NullableGetTransactions200Response) Get() *GetTransactions200Response { - return v.value -} - -func (v *NullableGetTransactions200Response) Set(val *GetTransactions200Response) { - v.value = val - v.isSet = true -} - -func (v NullableGetTransactions200Response) IsSet() bool { - return v.isSet -} - -func (v *NullableGetTransactions200Response) Unset() { - v.value = nil - v.isSet = false -} - -func NewNullableGetTransactions200Response(val *GetTransactions200Response) *NullableGetTransactions200Response { - return &NullableGetTransactions200Response{value: val, isSet: true} -} - -func (v NullableGetTransactions200Response) MarshalJSON() ([]byte, error) { - return json.Marshal(v.value) -} - -func (v *NullableGetTransactions200Response) UnmarshalJSON(src []byte) error { - v.isSet = true - return json.Unmarshal(src, &v.value) -} diff --git a/cli/openapi/model_test_run.go b/cli/openapi/model_test_run.go index 3acf317507..b993280aff 100644 --- a/cli/openapi/model_test_run.go +++ b/cli/openapi/model_test_run.go @@ -31,7 +31,7 @@ type TestRun struct { LastErrorState *string `json:"lastErrorState,omitempty"` // time in seconds it took for the test to complete, either success or fail. If the test is still running, it will show the time up to the time of the request ExecutionTime *int32 `json:"executionTime,omitempty"` - // time in milliseconds it took for the triggering transaction to complete, either success or fail. If the test is still running, it will show the time up to the time of the request + // time in milliseconds it took for the triggering testSuite to complete, either success or fail. If the test is still running, it will show the time up to the time of the request TriggerTime *int32 `json:"triggerTime,omitempty"` CreatedAt *time.Time `json:"createdAt,omitempty"` ServiceTriggeredAt *time.Time `json:"serviceTriggeredAt,omitempty"` @@ -46,8 +46,8 @@ type TestRun struct { Outputs []TestRunOutputsInner `json:"outputs,omitempty"` RequiredGatesResult *RequiredGatesResult `json:"requiredGatesResult,omitempty"` Metadata *map[string]string `json:"metadata,omitempty"` - TransactionId *string `json:"transactionId,omitempty"` - TransactionRunId *string `json:"transactionRunId,omitempty"` + TestSuiteId *string `json:"testSuiteId,omitempty"` + TestSuiteRunId *string `json:"testSuiteRunId,omitempty"` } // NewTestRun instantiates a new TestRun object @@ -739,68 +739,68 @@ func (o *TestRun) SetMetadata(v map[string]string) { o.Metadata = &v } -// GetTransactionId returns the TransactionId field value if set, zero value otherwise. -func (o *TestRun) GetTransactionId() string { - if o == nil || isNil(o.TransactionId) { +// GetTestSuiteId returns the TestSuiteId field value if set, zero value otherwise. +func (o *TestRun) GetTestSuiteId() string { + if o == nil || isNil(o.TestSuiteId) { var ret string return ret } - return *o.TransactionId + return *o.TestSuiteId } -// GetTransactionIdOk returns a tuple with the TransactionId field value if set, nil otherwise +// GetTestSuiteIdOk returns a tuple with the TestSuiteId field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TestRun) GetTransactionIdOk() (*string, bool) { - if o == nil || isNil(o.TransactionId) { +func (o *TestRun) GetTestSuiteIdOk() (*string, bool) { + if o == nil || isNil(o.TestSuiteId) { return nil, false } - return o.TransactionId, true + return o.TestSuiteId, true } -// HasTransactionId returns a boolean if a field has been set. -func (o *TestRun) HasTransactionId() bool { - if o != nil && !isNil(o.TransactionId) { +// HasTestSuiteId returns a boolean if a field has been set. +func (o *TestRun) HasTestSuiteId() bool { + if o != nil && !isNil(o.TestSuiteId) { return true } return false } -// SetTransactionId gets a reference to the given string and assigns it to the TransactionId field. -func (o *TestRun) SetTransactionId(v string) { - o.TransactionId = &v +// SetTestSuiteId gets a reference to the given string and assigns it to the TestSuiteId field. +func (o *TestRun) SetTestSuiteId(v string) { + o.TestSuiteId = &v } -// GetTransactionRunId returns the TransactionRunId field value if set, zero value otherwise. -func (o *TestRun) GetTransactionRunId() string { - if o == nil || isNil(o.TransactionRunId) { +// GetTestSuiteRunId returns the TestSuiteRunId field value if set, zero value otherwise. +func (o *TestRun) GetTestSuiteRunId() string { + if o == nil || isNil(o.TestSuiteRunId) { var ret string return ret } - return *o.TransactionRunId + return *o.TestSuiteRunId } -// GetTransactionRunIdOk returns a tuple with the TransactionRunId field value if set, nil otherwise +// GetTestSuiteRunIdOk returns a tuple with the TestSuiteRunId field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TestRun) GetTransactionRunIdOk() (*string, bool) { - if o == nil || isNil(o.TransactionRunId) { +func (o *TestRun) GetTestSuiteRunIdOk() (*string, bool) { + if o == nil || isNil(o.TestSuiteRunId) { return nil, false } - return o.TransactionRunId, true + return o.TestSuiteRunId, true } -// HasTransactionRunId returns a boolean if a field has been set. -func (o *TestRun) HasTransactionRunId() bool { - if o != nil && !isNil(o.TransactionRunId) { +// HasTestSuiteRunId returns a boolean if a field has been set. +func (o *TestRun) HasTestSuiteRunId() bool { + if o != nil && !isNil(o.TestSuiteRunId) { return true } return false } -// SetTransactionRunId gets a reference to the given string and assigns it to the TransactionRunId field. -func (o *TestRun) SetTransactionRunId(v string) { - o.TransactionRunId = &v +// SetTestSuiteRunId gets a reference to the given string and assigns it to the TestSuiteRunId field. +func (o *TestRun) SetTestSuiteRunId(v string) { + o.TestSuiteRunId = &v } func (o TestRun) MarshalJSON() ([]byte, error) { @@ -870,11 +870,11 @@ func (o TestRun) ToMap() (map[string]interface{}, error) { if !isNil(o.Metadata) { toSerialize["metadata"] = o.Metadata } - if !isNil(o.TransactionId) { - toSerialize["transactionId"] = o.TransactionId + if !isNil(o.TestSuiteId) { + toSerialize["testSuiteId"] = o.TestSuiteId } - if !isNil(o.TransactionRunId) { - toSerialize["transactionRunId"] = o.TransactionRunId + if !isNil(o.TestSuiteRunId) { + toSerialize["testSuiteRunId"] = o.TestSuiteRunId } return toSerialize, nil } diff --git a/cli/openapi/model_transaction.go b/cli/openapi/model_test_suite.go similarity index 72% rename from cli/openapi/model_transaction.go rename to cli/openapi/model_test_suite.go index cafb423e75..b04e9efd7d 100644 --- a/cli/openapi/model_transaction.go +++ b/cli/openapi/model_test_suite.go @@ -15,43 +15,43 @@ import ( "time" ) -// checks if the Transaction type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &Transaction{} +// checks if the TestSuite type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &TestSuite{} -// Transaction struct for Transaction -type Transaction struct { +// TestSuite struct for TestSuite +type TestSuite struct { Id *string `json:"id,omitempty"` Name *string `json:"name,omitempty"` Description *string `json:"description,omitempty"` // version number of the test Version *int32 `json:"version,omitempty"` - // list of steps of the transaction containing just each test id + // list of steps of the TestSuite containing just each test id Steps []string `json:"steps,omitempty"` - // list of steps of the transaction containing the whole test object + // list of steps of the TestSuite containing the whole test object FullSteps []Test `json:"fullSteps,omitempty"` CreatedAt *time.Time `json:"createdAt,omitempty"` Summary *TestSummary `json:"summary,omitempty"` } -// NewTransaction instantiates a new Transaction object +// NewTestSuite instantiates a new TestSuite 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 NewTransaction() *Transaction { - this := Transaction{} +func NewTestSuite() *TestSuite { + this := TestSuite{} return &this } -// NewTransactionWithDefaults instantiates a new Transaction object +// NewTestSuiteWithDefaults instantiates a new TestSuite 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 NewTransactionWithDefaults() *Transaction { - this := Transaction{} +func NewTestSuiteWithDefaults() *TestSuite { + this := TestSuite{} return &this } // GetId returns the Id field value if set, zero value otherwise. -func (o *Transaction) GetId() string { +func (o *TestSuite) GetId() string { if o == nil || isNil(o.Id) { var ret string return ret @@ -61,7 +61,7 @@ func (o *Transaction) 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 *Transaction) GetIdOk() (*string, bool) { +func (o *TestSuite) GetIdOk() (*string, bool) { if o == nil || isNil(o.Id) { return nil, false } @@ -69,7 +69,7 @@ func (o *Transaction) GetIdOk() (*string, bool) { } // HasId returns a boolean if a field has been set. -func (o *Transaction) HasId() bool { +func (o *TestSuite) HasId() bool { if o != nil && !isNil(o.Id) { return true } @@ -78,12 +78,12 @@ func (o *Transaction) HasId() bool { } // SetId gets a reference to the given string and assigns it to the Id field. -func (o *Transaction) SetId(v string) { +func (o *TestSuite) SetId(v string) { o.Id = &v } // GetName returns the Name field value if set, zero value otherwise. -func (o *Transaction) GetName() string { +func (o *TestSuite) GetName() string { if o == nil || isNil(o.Name) { var ret string return ret @@ -93,7 +93,7 @@ func (o *Transaction) 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 *Transaction) GetNameOk() (*string, bool) { +func (o *TestSuite) GetNameOk() (*string, bool) { if o == nil || isNil(o.Name) { return nil, false } @@ -101,7 +101,7 @@ func (o *Transaction) GetNameOk() (*string, bool) { } // HasName returns a boolean if a field has been set. -func (o *Transaction) HasName() bool { +func (o *TestSuite) HasName() bool { if o != nil && !isNil(o.Name) { return true } @@ -110,12 +110,12 @@ func (o *Transaction) HasName() bool { } // SetName gets a reference to the given string and assigns it to the Name field. -func (o *Transaction) SetName(v string) { +func (o *TestSuite) SetName(v string) { o.Name = &v } // GetDescription returns the Description field value if set, zero value otherwise. -func (o *Transaction) GetDescription() string { +func (o *TestSuite) GetDescription() string { if o == nil || isNil(o.Description) { var ret string return ret @@ -125,7 +125,7 @@ func (o *Transaction) 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 *Transaction) GetDescriptionOk() (*string, bool) { +func (o *TestSuite) GetDescriptionOk() (*string, bool) { if o == nil || isNil(o.Description) { return nil, false } @@ -133,7 +133,7 @@ func (o *Transaction) GetDescriptionOk() (*string, bool) { } // HasDescription returns a boolean if a field has been set. -func (o *Transaction) HasDescription() bool { +func (o *TestSuite) HasDescription() bool { if o != nil && !isNil(o.Description) { return true } @@ -142,12 +142,12 @@ func (o *Transaction) HasDescription() bool { } // SetDescription gets a reference to the given string and assigns it to the Description field. -func (o *Transaction) SetDescription(v string) { +func (o *TestSuite) SetDescription(v string) { o.Description = &v } // GetVersion returns the Version field value if set, zero value otherwise. -func (o *Transaction) GetVersion() int32 { +func (o *TestSuite) GetVersion() int32 { if o == nil || isNil(o.Version) { var ret int32 return ret @@ -157,7 +157,7 @@ func (o *Transaction) GetVersion() int32 { // GetVersionOk returns a tuple with the Version field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Transaction) GetVersionOk() (*int32, bool) { +func (o *TestSuite) GetVersionOk() (*int32, bool) { if o == nil || isNil(o.Version) { return nil, false } @@ -165,7 +165,7 @@ func (o *Transaction) GetVersionOk() (*int32, bool) { } // HasVersion returns a boolean if a field has been set. -func (o *Transaction) HasVersion() bool { +func (o *TestSuite) HasVersion() bool { if o != nil && !isNil(o.Version) { return true } @@ -174,12 +174,12 @@ func (o *Transaction) HasVersion() bool { } // SetVersion gets a reference to the given int32 and assigns it to the Version field. -func (o *Transaction) SetVersion(v int32) { +func (o *TestSuite) SetVersion(v int32) { o.Version = &v } // GetSteps returns the Steps field value if set, zero value otherwise. -func (o *Transaction) GetSteps() []string { +func (o *TestSuite) GetSteps() []string { if o == nil || isNil(o.Steps) { var ret []string return ret @@ -189,7 +189,7 @@ func (o *Transaction) GetSteps() []string { // GetStepsOk returns a tuple with the Steps field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Transaction) GetStepsOk() ([]string, bool) { +func (o *TestSuite) GetStepsOk() ([]string, bool) { if o == nil || isNil(o.Steps) { return nil, false } @@ -197,7 +197,7 @@ func (o *Transaction) GetStepsOk() ([]string, bool) { } // HasSteps returns a boolean if a field has been set. -func (o *Transaction) HasSteps() bool { +func (o *TestSuite) HasSteps() bool { if o != nil && !isNil(o.Steps) { return true } @@ -206,12 +206,12 @@ func (o *Transaction) HasSteps() bool { } // SetSteps gets a reference to the given []string and assigns it to the Steps field. -func (o *Transaction) SetSteps(v []string) { +func (o *TestSuite) SetSteps(v []string) { o.Steps = v } // GetFullSteps returns the FullSteps field value if set, zero value otherwise. -func (o *Transaction) GetFullSteps() []Test { +func (o *TestSuite) GetFullSteps() []Test { if o == nil || isNil(o.FullSteps) { var ret []Test return ret @@ -221,7 +221,7 @@ func (o *Transaction) GetFullSteps() []Test { // GetFullStepsOk returns a tuple with the FullSteps field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Transaction) GetFullStepsOk() ([]Test, bool) { +func (o *TestSuite) GetFullStepsOk() ([]Test, bool) { if o == nil || isNil(o.FullSteps) { return nil, false } @@ -229,7 +229,7 @@ func (o *Transaction) GetFullStepsOk() ([]Test, bool) { } // HasFullSteps returns a boolean if a field has been set. -func (o *Transaction) HasFullSteps() bool { +func (o *TestSuite) HasFullSteps() bool { if o != nil && !isNil(o.FullSteps) { return true } @@ -238,12 +238,12 @@ func (o *Transaction) HasFullSteps() bool { } // SetFullSteps gets a reference to the given []Test and assigns it to the FullSteps field. -func (o *Transaction) SetFullSteps(v []Test) { +func (o *TestSuite) SetFullSteps(v []Test) { o.FullSteps = v } // GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. -func (o *Transaction) GetCreatedAt() time.Time { +func (o *TestSuite) GetCreatedAt() time.Time { if o == nil || isNil(o.CreatedAt) { var ret time.Time return ret @@ -253,7 +253,7 @@ func (o *Transaction) GetCreatedAt() time.Time { // GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Transaction) GetCreatedAtOk() (*time.Time, bool) { +func (o *TestSuite) GetCreatedAtOk() (*time.Time, bool) { if o == nil || isNil(o.CreatedAt) { return nil, false } @@ -261,7 +261,7 @@ func (o *Transaction) GetCreatedAtOk() (*time.Time, bool) { } // HasCreatedAt returns a boolean if a field has been set. -func (o *Transaction) HasCreatedAt() bool { +func (o *TestSuite) HasCreatedAt() bool { if o != nil && !isNil(o.CreatedAt) { return true } @@ -270,12 +270,12 @@ func (o *Transaction) HasCreatedAt() bool { } // SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. -func (o *Transaction) SetCreatedAt(v time.Time) { +func (o *TestSuite) SetCreatedAt(v time.Time) { o.CreatedAt = &v } // GetSummary returns the Summary field value if set, zero value otherwise. -func (o *Transaction) GetSummary() TestSummary { +func (o *TestSuite) GetSummary() TestSummary { if o == nil || isNil(o.Summary) { var ret TestSummary return ret @@ -285,7 +285,7 @@ func (o *Transaction) GetSummary() TestSummary { // GetSummaryOk returns a tuple with the Summary field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *Transaction) GetSummaryOk() (*TestSummary, bool) { +func (o *TestSuite) GetSummaryOk() (*TestSummary, bool) { if o == nil || isNil(o.Summary) { return nil, false } @@ -293,7 +293,7 @@ func (o *Transaction) GetSummaryOk() (*TestSummary, bool) { } // HasSummary returns a boolean if a field has been set. -func (o *Transaction) HasSummary() bool { +func (o *TestSuite) HasSummary() bool { if o != nil && !isNil(o.Summary) { return true } @@ -302,11 +302,11 @@ func (o *Transaction) HasSummary() bool { } // SetSummary gets a reference to the given TestSummary and assigns it to the Summary field. -func (o *Transaction) SetSummary(v TestSummary) { +func (o *TestSuite) SetSummary(v TestSummary) { o.Summary = &v } -func (o Transaction) MarshalJSON() ([]byte, error) { +func (o TestSuite) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -314,7 +314,7 @@ func (o Transaction) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o Transaction) ToMap() (map[string]interface{}, error) { +func (o TestSuite) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Id) { toSerialize["id"] = o.Id @@ -343,38 +343,38 @@ func (o Transaction) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableTransaction struct { - value *Transaction +type NullableTestSuite struct { + value *TestSuite isSet bool } -func (v NullableTransaction) Get() *Transaction { +func (v NullableTestSuite) Get() *TestSuite { return v.value } -func (v *NullableTransaction) Set(val *Transaction) { +func (v *NullableTestSuite) Set(val *TestSuite) { v.value = val v.isSet = true } -func (v NullableTransaction) IsSet() bool { +func (v NullableTestSuite) IsSet() bool { return v.isSet } -func (v *NullableTransaction) Unset() { +func (v *NullableTestSuite) Unset() { v.value = nil v.isSet = false } -func NewNullableTransaction(val *Transaction) *NullableTransaction { - return &NullableTransaction{value: val, isSet: true} +func NewNullableTestSuite(val *TestSuite) *NullableTestSuite { + return &NullableTestSuite{value: val, isSet: true} } -func (v NullableTransaction) MarshalJSON() ([]byte, error) { +func (v NullableTestSuite) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableTransaction) UnmarshalJSON(src []byte) error { +func (v *NullableTestSuite) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_transaction_resource.go b/cli/openapi/model_test_suite_resource.go similarity index 53% rename from cli/openapi/model_transaction_resource.go rename to cli/openapi/model_test_suite_resource.go index 552e8c20e5..231515850b 100644 --- a/cli/openapi/model_transaction_resource.go +++ b/cli/openapi/model_test_suite_resource.go @@ -14,35 +14,35 @@ import ( "encoding/json" ) -// checks if the TransactionResource type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &TransactionResource{} +// checks if the TestSuiteResource type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &TestSuiteResource{} -// TransactionResource Represents a transaction structured into the Resources format. -type TransactionResource struct { - // Represents the type of this resource. It should always be set as 'Transaction'. - Type *string `json:"type,omitempty"` - Spec *Transaction `json:"spec,omitempty"` +// TestSuiteResource Represents a TestSuite structured into the Resources format. +type TestSuiteResource struct { + // Represents the type of this resource. It should always be set as 'TestSuite'. + Type *string `json:"type,omitempty"` + Spec *TestSuite `json:"spec,omitempty"` } -// NewTransactionResource instantiates a new TransactionResource object +// NewTestSuiteResource instantiates a new TestSuiteResource 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 NewTransactionResource() *TransactionResource { - this := TransactionResource{} +func NewTestSuiteResource() *TestSuiteResource { + this := TestSuiteResource{} return &this } -// NewTransactionResourceWithDefaults instantiates a new TransactionResource object +// NewTestSuiteResourceWithDefaults instantiates a new TestSuiteResource 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 NewTransactionResourceWithDefaults() *TransactionResource { - this := TransactionResource{} +func NewTestSuiteResourceWithDefaults() *TestSuiteResource { + this := TestSuiteResource{} return &this } // GetType returns the Type field value if set, zero value otherwise. -func (o *TransactionResource) GetType() string { +func (o *TestSuiteResource) GetType() string { if o == nil || isNil(o.Type) { var ret string return ret @@ -52,7 +52,7 @@ func (o *TransactionResource) 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 *TransactionResource) GetTypeOk() (*string, bool) { +func (o *TestSuiteResource) GetTypeOk() (*string, bool) { if o == nil || isNil(o.Type) { return nil, false } @@ -60,7 +60,7 @@ func (o *TransactionResource) GetTypeOk() (*string, bool) { } // HasType returns a boolean if a field has been set. -func (o *TransactionResource) HasType() bool { +func (o *TestSuiteResource) HasType() bool { if o != nil && !isNil(o.Type) { return true } @@ -69,14 +69,14 @@ func (o *TransactionResource) HasType() bool { } // SetType gets a reference to the given string and assigns it to the Type field. -func (o *TransactionResource) SetType(v string) { +func (o *TestSuiteResource) SetType(v string) { o.Type = &v } // GetSpec returns the Spec field value if set, zero value otherwise. -func (o *TransactionResource) GetSpec() Transaction { +func (o *TestSuiteResource) GetSpec() TestSuite { if o == nil || isNil(o.Spec) { - var ret Transaction + var ret TestSuite return ret } return *o.Spec @@ -84,7 +84,7 @@ func (o *TransactionResource) GetSpec() Transaction { // 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 *TransactionResource) GetSpecOk() (*Transaction, bool) { +func (o *TestSuiteResource) GetSpecOk() (*TestSuite, bool) { if o == nil || isNil(o.Spec) { return nil, false } @@ -92,7 +92,7 @@ func (o *TransactionResource) GetSpecOk() (*Transaction, bool) { } // HasSpec returns a boolean if a field has been set. -func (o *TransactionResource) HasSpec() bool { +func (o *TestSuiteResource) HasSpec() bool { if o != nil && !isNil(o.Spec) { return true } @@ -100,12 +100,12 @@ func (o *TransactionResource) HasSpec() bool { return false } -// SetSpec gets a reference to the given Transaction and assigns it to the Spec field. -func (o *TransactionResource) SetSpec(v Transaction) { +// SetSpec gets a reference to the given TestSuite and assigns it to the Spec field. +func (o *TestSuiteResource) SetSpec(v TestSuite) { o.Spec = &v } -func (o TransactionResource) MarshalJSON() ([]byte, error) { +func (o TestSuiteResource) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -113,7 +113,7 @@ func (o TransactionResource) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o TransactionResource) ToMap() (map[string]interface{}, error) { +func (o TestSuiteResource) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Type) { toSerialize["type"] = o.Type @@ -124,38 +124,38 @@ func (o TransactionResource) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableTransactionResource struct { - value *TransactionResource +type NullableTestSuiteResource struct { + value *TestSuiteResource isSet bool } -func (v NullableTransactionResource) Get() *TransactionResource { +func (v NullableTestSuiteResource) Get() *TestSuiteResource { return v.value } -func (v *NullableTransactionResource) Set(val *TransactionResource) { +func (v *NullableTestSuiteResource) Set(val *TestSuiteResource) { v.value = val v.isSet = true } -func (v NullableTransactionResource) IsSet() bool { +func (v NullableTestSuiteResource) IsSet() bool { return v.isSet } -func (v *NullableTransactionResource) Unset() { +func (v *NullableTestSuiteResource) Unset() { v.value = nil v.isSet = false } -func NewNullableTransactionResource(val *TransactionResource) *NullableTransactionResource { - return &NullableTransactionResource{value: val, isSet: true} +func NewNullableTestSuiteResource(val *TestSuiteResource) *NullableTestSuiteResource { + return &NullableTestSuiteResource{value: val, isSet: true} } -func (v NullableTransactionResource) MarshalJSON() ([]byte, error) { +func (v NullableTestSuiteResource) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableTransactionResource) UnmarshalJSON(src []byte) error { +func (v *NullableTestSuiteResource) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_transaction_resource_list.go b/cli/openapi/model_test_suite_resource_list.go similarity index 51% rename from cli/openapi/model_transaction_resource_list.go rename to cli/openapi/model_test_suite_resource_list.go index fae48a477e..ea2490987b 100644 --- a/cli/openapi/model_transaction_resource_list.go +++ b/cli/openapi/model_test_suite_resource_list.go @@ -14,34 +14,34 @@ import ( "encoding/json" ) -// checks if the TransactionResourceList type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &TransactionResourceList{} +// checks if the TestSuiteResourceList type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &TestSuiteResourceList{} -// TransactionResourceList struct for TransactionResourceList -type TransactionResourceList struct { - Count *int32 `json:"count,omitempty"` - Items []TransactionResource `json:"items,omitempty"` +// TestSuiteResourceList struct for TestSuiteResourceList +type TestSuiteResourceList struct { + Count *int32 `json:"count,omitempty"` + Items []TestSuiteResource `json:"items,omitempty"` } -// NewTransactionResourceList instantiates a new TransactionResourceList object +// NewTestSuiteResourceList instantiates a new TestSuiteResourceList 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 NewTransactionResourceList() *TransactionResourceList { - this := TransactionResourceList{} +func NewTestSuiteResourceList() *TestSuiteResourceList { + this := TestSuiteResourceList{} return &this } -// NewTransactionResourceListWithDefaults instantiates a new TransactionResourceList object +// NewTestSuiteResourceListWithDefaults instantiates a new TestSuiteResourceList 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 NewTransactionResourceListWithDefaults() *TransactionResourceList { - this := TransactionResourceList{} +func NewTestSuiteResourceListWithDefaults() *TestSuiteResourceList { + this := TestSuiteResourceList{} return &this } // GetCount returns the Count field value if set, zero value otherwise. -func (o *TransactionResourceList) GetCount() int32 { +func (o *TestSuiteResourceList) GetCount() int32 { if o == nil || isNil(o.Count) { var ret int32 return ret @@ -51,7 +51,7 @@ func (o *TransactionResourceList) 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 *TransactionResourceList) GetCountOk() (*int32, bool) { +func (o *TestSuiteResourceList) GetCountOk() (*int32, bool) { if o == nil || isNil(o.Count) { return nil, false } @@ -59,7 +59,7 @@ func (o *TransactionResourceList) GetCountOk() (*int32, bool) { } // HasCount returns a boolean if a field has been set. -func (o *TransactionResourceList) HasCount() bool { +func (o *TestSuiteResourceList) HasCount() bool { if o != nil && !isNil(o.Count) { return true } @@ -68,14 +68,14 @@ func (o *TransactionResourceList) HasCount() bool { } // SetCount gets a reference to the given int32 and assigns it to the Count field. -func (o *TransactionResourceList) SetCount(v int32) { +func (o *TestSuiteResourceList) SetCount(v int32) { o.Count = &v } // GetItems returns the Items field value if set, zero value otherwise. -func (o *TransactionResourceList) GetItems() []TransactionResource { +func (o *TestSuiteResourceList) GetItems() []TestSuiteResource { if o == nil || isNil(o.Items) { - var ret []TransactionResource + var ret []TestSuiteResource return ret } return o.Items @@ -83,7 +83,7 @@ func (o *TransactionResourceList) GetItems() []TransactionResource { // 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 *TransactionResourceList) GetItemsOk() ([]TransactionResource, bool) { +func (o *TestSuiteResourceList) GetItemsOk() ([]TestSuiteResource, bool) { if o == nil || isNil(o.Items) { return nil, false } @@ -91,7 +91,7 @@ func (o *TransactionResourceList) GetItemsOk() ([]TransactionResource, bool) { } // HasItems returns a boolean if a field has been set. -func (o *TransactionResourceList) HasItems() bool { +func (o *TestSuiteResourceList) HasItems() bool { if o != nil && !isNil(o.Items) { return true } @@ -99,12 +99,12 @@ func (o *TransactionResourceList) HasItems() bool { return false } -// SetItems gets a reference to the given []TransactionResource and assigns it to the Items field. -func (o *TransactionResourceList) SetItems(v []TransactionResource) { +// SetItems gets a reference to the given []TestSuiteResource and assigns it to the Items field. +func (o *TestSuiteResourceList) SetItems(v []TestSuiteResource) { o.Items = v } -func (o TransactionResourceList) MarshalJSON() ([]byte, error) { +func (o TestSuiteResourceList) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -112,7 +112,7 @@ func (o TransactionResourceList) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o TransactionResourceList) ToMap() (map[string]interface{}, error) { +func (o TestSuiteResourceList) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} if !isNil(o.Count) { toSerialize["count"] = o.Count @@ -123,38 +123,38 @@ func (o TransactionResourceList) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableTransactionResourceList struct { - value *TransactionResourceList +type NullableTestSuiteResourceList struct { + value *TestSuiteResourceList isSet bool } -func (v NullableTransactionResourceList) Get() *TransactionResourceList { +func (v NullableTestSuiteResourceList) Get() *TestSuiteResourceList { return v.value } -func (v *NullableTransactionResourceList) Set(val *TransactionResourceList) { +func (v *NullableTestSuiteResourceList) Set(val *TestSuiteResourceList) { v.value = val v.isSet = true } -func (v NullableTransactionResourceList) IsSet() bool { +func (v NullableTestSuiteResourceList) IsSet() bool { return v.isSet } -func (v *NullableTransactionResourceList) Unset() { +func (v *NullableTestSuiteResourceList) Unset() { v.value = nil v.isSet = false } -func NewNullableTransactionResourceList(val *TransactionResourceList) *NullableTransactionResourceList { - return &NullableTransactionResourceList{value: val, isSet: true} +func NewNullableTestSuiteResourceList(val *TestSuiteResourceList) *NullableTestSuiteResourceList { + return &NullableTestSuiteResourceList{value: val, isSet: true} } -func (v NullableTransactionResourceList) MarshalJSON() ([]byte, error) { +func (v NullableTestSuiteResourceList) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableTransactionResourceList) UnmarshalJSON(src []byte) error { +func (v *NullableTestSuiteResourceList) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_transaction_run.go b/cli/openapi/model_test_suite_run.go similarity index 73% rename from cli/openapi/model_transaction_run.go rename to cli/openapi/model_test_suite_run.go index 743e4ea437..74e591b8ee 100644 --- a/cli/openapi/model_transaction_run.go +++ b/cli/openapi/model_test_suite_run.go @@ -15,11 +15,11 @@ import ( "time" ) -// checks if the TransactionRun type satisfies the MappedNullable interface at compile time -var _ MappedNullable = &TransactionRun{} +// checks if the TestSuiteRun type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &TestSuiteRun{} -// TransactionRun struct for TransactionRun -type TransactionRun struct { +// TestSuiteRun struct for TestSuiteRun +type TestSuiteRun struct { Id *string `json:"id,omitempty"` Version *int32 `json:"version,omitempty"` CreatedAt *time.Time `json:"createdAt,omitempty"` @@ -33,25 +33,25 @@ type TransactionRun struct { AllStepsRequiredGatesPassed *bool `json:"allStepsRequiredGatesPassed,omitempty"` } -// NewTransactionRun instantiates a new TransactionRun object +// NewTestSuiteRun instantiates a new TestSuiteRun 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 NewTransactionRun() *TransactionRun { - this := TransactionRun{} +func NewTestSuiteRun() *TestSuiteRun { + this := TestSuiteRun{} return &this } -// NewTransactionRunWithDefaults instantiates a new TransactionRun object +// NewTestSuiteRunWithDefaults instantiates a new TestSuiteRun 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 NewTransactionRunWithDefaults() *TransactionRun { - this := TransactionRun{} +func NewTestSuiteRunWithDefaults() *TestSuiteRun { + this := TestSuiteRun{} return &this } // GetId returns the Id field value if set, zero value otherwise. -func (o *TransactionRun) GetId() string { +func (o *TestSuiteRun) GetId() string { if o == nil || isNil(o.Id) { var ret string return ret @@ -61,7 +61,7 @@ func (o *TransactionRun) 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 *TransactionRun) GetIdOk() (*string, bool) { +func (o *TestSuiteRun) GetIdOk() (*string, bool) { if o == nil || isNil(o.Id) { return nil, false } @@ -69,7 +69,7 @@ func (o *TransactionRun) GetIdOk() (*string, bool) { } // HasId returns a boolean if a field has been set. -func (o *TransactionRun) HasId() bool { +func (o *TestSuiteRun) HasId() bool { if o != nil && !isNil(o.Id) { return true } @@ -78,12 +78,12 @@ func (o *TransactionRun) HasId() bool { } // SetId gets a reference to the given string and assigns it to the Id field. -func (o *TransactionRun) SetId(v string) { +func (o *TestSuiteRun) SetId(v string) { o.Id = &v } // GetVersion returns the Version field value if set, zero value otherwise. -func (o *TransactionRun) GetVersion() int32 { +func (o *TestSuiteRun) GetVersion() int32 { if o == nil || isNil(o.Version) { var ret int32 return ret @@ -93,7 +93,7 @@ func (o *TransactionRun) GetVersion() int32 { // GetVersionOk returns a tuple with the Version field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetVersionOk() (*int32, bool) { +func (o *TestSuiteRun) GetVersionOk() (*int32, bool) { if o == nil || isNil(o.Version) { return nil, false } @@ -101,7 +101,7 @@ func (o *TransactionRun) GetVersionOk() (*int32, bool) { } // HasVersion returns a boolean if a field has been set. -func (o *TransactionRun) HasVersion() bool { +func (o *TestSuiteRun) HasVersion() bool { if o != nil && !isNil(o.Version) { return true } @@ -110,12 +110,12 @@ func (o *TransactionRun) HasVersion() bool { } // SetVersion gets a reference to the given int32 and assigns it to the Version field. -func (o *TransactionRun) SetVersion(v int32) { +func (o *TestSuiteRun) SetVersion(v int32) { o.Version = &v } // GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. -func (o *TransactionRun) GetCreatedAt() time.Time { +func (o *TestSuiteRun) GetCreatedAt() time.Time { if o == nil || isNil(o.CreatedAt) { var ret time.Time return ret @@ -125,7 +125,7 @@ func (o *TransactionRun) GetCreatedAt() time.Time { // GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetCreatedAtOk() (*time.Time, bool) { +func (o *TestSuiteRun) GetCreatedAtOk() (*time.Time, bool) { if o == nil || isNil(o.CreatedAt) { return nil, false } @@ -133,7 +133,7 @@ func (o *TransactionRun) GetCreatedAtOk() (*time.Time, bool) { } // HasCreatedAt returns a boolean if a field has been set. -func (o *TransactionRun) HasCreatedAt() bool { +func (o *TestSuiteRun) HasCreatedAt() bool { if o != nil && !isNil(o.CreatedAt) { return true } @@ -142,12 +142,12 @@ func (o *TransactionRun) HasCreatedAt() bool { } // SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. -func (o *TransactionRun) SetCreatedAt(v time.Time) { +func (o *TestSuiteRun) SetCreatedAt(v time.Time) { o.CreatedAt = &v } // GetCompletedAt returns the CompletedAt field value if set, zero value otherwise. -func (o *TransactionRun) GetCompletedAt() time.Time { +func (o *TestSuiteRun) GetCompletedAt() time.Time { if o == nil || isNil(o.CompletedAt) { var ret time.Time return ret @@ -157,7 +157,7 @@ func (o *TransactionRun) GetCompletedAt() time.Time { // GetCompletedAtOk returns a tuple with the CompletedAt field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetCompletedAtOk() (*time.Time, bool) { +func (o *TestSuiteRun) GetCompletedAtOk() (*time.Time, bool) { if o == nil || isNil(o.CompletedAt) { return nil, false } @@ -165,7 +165,7 @@ func (o *TransactionRun) GetCompletedAtOk() (*time.Time, bool) { } // HasCompletedAt returns a boolean if a field has been set. -func (o *TransactionRun) HasCompletedAt() bool { +func (o *TestSuiteRun) HasCompletedAt() bool { if o != nil && !isNil(o.CompletedAt) { return true } @@ -174,12 +174,12 @@ func (o *TransactionRun) HasCompletedAt() bool { } // SetCompletedAt gets a reference to the given time.Time and assigns it to the CompletedAt field. -func (o *TransactionRun) SetCompletedAt(v time.Time) { +func (o *TestSuiteRun) SetCompletedAt(v time.Time) { o.CompletedAt = &v } // GetState returns the State field value if set, zero value otherwise. -func (o *TransactionRun) GetState() string { +func (o *TestSuiteRun) GetState() string { if o == nil || isNil(o.State) { var ret string return ret @@ -189,7 +189,7 @@ func (o *TransactionRun) GetState() string { // GetStateOk returns a tuple with the State field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetStateOk() (*string, bool) { +func (o *TestSuiteRun) GetStateOk() (*string, bool) { if o == nil || isNil(o.State) { return nil, false } @@ -197,7 +197,7 @@ func (o *TransactionRun) GetStateOk() (*string, bool) { } // HasState returns a boolean if a field has been set. -func (o *TransactionRun) HasState() bool { +func (o *TestSuiteRun) HasState() bool { if o != nil && !isNil(o.State) { return true } @@ -206,12 +206,12 @@ func (o *TransactionRun) HasState() bool { } // SetState gets a reference to the given string and assigns it to the State field. -func (o *TransactionRun) SetState(v string) { +func (o *TestSuiteRun) SetState(v string) { o.State = &v } // GetSteps returns the Steps field value if set, zero value otherwise. -func (o *TransactionRun) GetSteps() []TestRun { +func (o *TestSuiteRun) GetSteps() []TestRun { if o == nil || isNil(o.Steps) { var ret []TestRun return ret @@ -221,7 +221,7 @@ func (o *TransactionRun) GetSteps() []TestRun { // GetStepsOk returns a tuple with the Steps field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetStepsOk() ([]TestRun, bool) { +func (o *TestSuiteRun) GetStepsOk() ([]TestRun, bool) { if o == nil || isNil(o.Steps) { return nil, false } @@ -229,7 +229,7 @@ func (o *TransactionRun) GetStepsOk() ([]TestRun, bool) { } // HasSteps returns a boolean if a field has been set. -func (o *TransactionRun) HasSteps() bool { +func (o *TestSuiteRun) HasSteps() bool { if o != nil && !isNil(o.Steps) { return true } @@ -238,12 +238,12 @@ func (o *TransactionRun) HasSteps() bool { } // SetSteps gets a reference to the given []TestRun and assigns it to the Steps field. -func (o *TransactionRun) SetSteps(v []TestRun) { +func (o *TestSuiteRun) SetSteps(v []TestRun) { o.Steps = v } // GetVariableSet returns the VariableSet field value if set, zero value otherwise. -func (o *TransactionRun) GetVariableSet() VariableSet { +func (o *TestSuiteRun) GetVariableSet() VariableSet { if o == nil || isNil(o.VariableSet) { var ret VariableSet return ret @@ -253,7 +253,7 @@ func (o *TransactionRun) GetVariableSet() VariableSet { // 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) GetVariableSetOk() (*VariableSet, bool) { +func (o *TestSuiteRun) GetVariableSetOk() (*VariableSet, bool) { if o == nil || isNil(o.VariableSet) { return nil, false } @@ -261,7 +261,7 @@ func (o *TransactionRun) GetVariableSetOk() (*VariableSet, bool) { } // HasVariableSet returns a boolean if a field has been set. -func (o *TransactionRun) HasVariableSet() bool { +func (o *TestSuiteRun) HasVariableSet() bool { if o != nil && !isNil(o.VariableSet) { return true } @@ -270,12 +270,12 @@ func (o *TransactionRun) HasVariableSet() bool { } // SetVariableSet gets a reference to the given VariableSet and assigns it to the VariableSet field. -func (o *TransactionRun) SetVariableSet(v VariableSet) { +func (o *TestSuiteRun) SetVariableSet(v VariableSet) { o.VariableSet = &v } // GetMetadata returns the Metadata field value if set, zero value otherwise. -func (o *TransactionRun) GetMetadata() map[string]string { +func (o *TestSuiteRun) GetMetadata() map[string]string { if o == nil || isNil(o.Metadata) { var ret map[string]string return ret @@ -285,7 +285,7 @@ func (o *TransactionRun) GetMetadata() map[string]string { // GetMetadataOk returns a tuple with the Metadata field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetMetadataOk() (*map[string]string, bool) { +func (o *TestSuiteRun) GetMetadataOk() (*map[string]string, bool) { if o == nil || isNil(o.Metadata) { return nil, false } @@ -293,7 +293,7 @@ func (o *TransactionRun) GetMetadataOk() (*map[string]string, bool) { } // HasMetadata returns a boolean if a field has been set. -func (o *TransactionRun) HasMetadata() bool { +func (o *TestSuiteRun) HasMetadata() bool { if o != nil && !isNil(o.Metadata) { return true } @@ -302,12 +302,12 @@ func (o *TransactionRun) HasMetadata() bool { } // SetMetadata gets a reference to the given map[string]string and assigns it to the Metadata field. -func (o *TransactionRun) SetMetadata(v map[string]string) { +func (o *TestSuiteRun) SetMetadata(v map[string]string) { o.Metadata = &v } // GetPass returns the Pass field value if set, zero value otherwise. -func (o *TransactionRun) GetPass() int32 { +func (o *TestSuiteRun) GetPass() int32 { if o == nil || isNil(o.Pass) { var ret int32 return ret @@ -317,7 +317,7 @@ func (o *TransactionRun) GetPass() int32 { // GetPassOk returns a tuple with the Pass field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetPassOk() (*int32, bool) { +func (o *TestSuiteRun) GetPassOk() (*int32, bool) { if o == nil || isNil(o.Pass) { return nil, false } @@ -325,7 +325,7 @@ func (o *TransactionRun) GetPassOk() (*int32, bool) { } // HasPass returns a boolean if a field has been set. -func (o *TransactionRun) HasPass() bool { +func (o *TestSuiteRun) HasPass() bool { if o != nil && !isNil(o.Pass) { return true } @@ -334,12 +334,12 @@ func (o *TransactionRun) HasPass() bool { } // SetPass gets a reference to the given int32 and assigns it to the Pass field. -func (o *TransactionRun) SetPass(v int32) { +func (o *TestSuiteRun) SetPass(v int32) { o.Pass = &v } // GetFail returns the Fail field value if set, zero value otherwise. -func (o *TransactionRun) GetFail() int32 { +func (o *TestSuiteRun) GetFail() int32 { if o == nil || isNil(o.Fail) { var ret int32 return ret @@ -349,7 +349,7 @@ func (o *TransactionRun) GetFail() int32 { // GetFailOk returns a tuple with the Fail field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetFailOk() (*int32, bool) { +func (o *TestSuiteRun) GetFailOk() (*int32, bool) { if o == nil || isNil(o.Fail) { return nil, false } @@ -357,7 +357,7 @@ func (o *TransactionRun) GetFailOk() (*int32, bool) { } // HasFail returns a boolean if a field has been set. -func (o *TransactionRun) HasFail() bool { +func (o *TestSuiteRun) HasFail() bool { if o != nil && !isNil(o.Fail) { return true } @@ -366,12 +366,12 @@ func (o *TransactionRun) HasFail() bool { } // SetFail gets a reference to the given int32 and assigns it to the Fail field. -func (o *TransactionRun) SetFail(v int32) { +func (o *TestSuiteRun) SetFail(v int32) { o.Fail = &v } // GetAllStepsRequiredGatesPassed returns the AllStepsRequiredGatesPassed field value if set, zero value otherwise. -func (o *TransactionRun) GetAllStepsRequiredGatesPassed() bool { +func (o *TestSuiteRun) GetAllStepsRequiredGatesPassed() bool { if o == nil || isNil(o.AllStepsRequiredGatesPassed) { var ret bool return ret @@ -381,7 +381,7 @@ func (o *TransactionRun) GetAllStepsRequiredGatesPassed() bool { // GetAllStepsRequiredGatesPassedOk returns a tuple with the AllStepsRequiredGatesPassed field value if set, nil otherwise // and a boolean to check if the value has been set. -func (o *TransactionRun) GetAllStepsRequiredGatesPassedOk() (*bool, bool) { +func (o *TestSuiteRun) GetAllStepsRequiredGatesPassedOk() (*bool, bool) { if o == nil || isNil(o.AllStepsRequiredGatesPassed) { return nil, false } @@ -389,7 +389,7 @@ func (o *TransactionRun) GetAllStepsRequiredGatesPassedOk() (*bool, bool) { } // HasAllStepsRequiredGatesPassed returns a boolean if a field has been set. -func (o *TransactionRun) HasAllStepsRequiredGatesPassed() bool { +func (o *TestSuiteRun) HasAllStepsRequiredGatesPassed() bool { if o != nil && !isNil(o.AllStepsRequiredGatesPassed) { return true } @@ -398,11 +398,11 @@ func (o *TransactionRun) HasAllStepsRequiredGatesPassed() bool { } // SetAllStepsRequiredGatesPassed gets a reference to the given bool and assigns it to the AllStepsRequiredGatesPassed field. -func (o *TransactionRun) SetAllStepsRequiredGatesPassed(v bool) { +func (o *TestSuiteRun) SetAllStepsRequiredGatesPassed(v bool) { o.AllStepsRequiredGatesPassed = &v } -func (o TransactionRun) MarshalJSON() ([]byte, error) { +func (o TestSuiteRun) MarshalJSON() ([]byte, error) { toSerialize, err := o.ToMap() if err != nil { return []byte{}, err @@ -410,7 +410,7 @@ func (o TransactionRun) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } -func (o TransactionRun) ToMap() (map[string]interface{}, error) { +func (o TestSuiteRun) ToMap() (map[string]interface{}, error) { toSerialize := map[string]interface{}{} // skip: id is readOnly // skip: version is readOnly @@ -444,38 +444,38 @@ func (o TransactionRun) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -type NullableTransactionRun struct { - value *TransactionRun +type NullableTestSuiteRun struct { + value *TestSuiteRun isSet bool } -func (v NullableTransactionRun) Get() *TransactionRun { +func (v NullableTestSuiteRun) Get() *TestSuiteRun { return v.value } -func (v *NullableTransactionRun) Set(val *TransactionRun) { +func (v *NullableTestSuiteRun) Set(val *TestSuiteRun) { v.value = val v.isSet = true } -func (v NullableTransactionRun) IsSet() bool { +func (v NullableTestSuiteRun) IsSet() bool { return v.isSet } -func (v *NullableTransactionRun) Unset() { +func (v *NullableTestSuiteRun) Unset() { v.value = nil v.isSet = false } -func NewNullableTransactionRun(val *TransactionRun) *NullableTransactionRun { - return &NullableTransactionRun{value: val, isSet: true} +func NewNullableTestSuiteRun(val *TestSuiteRun) *NullableTestSuiteRun { + return &NullableTestSuiteRun{value: val, isSet: true} } -func (v NullableTransactionRun) MarshalJSON() ([]byte, error) { +func (v NullableTestSuiteRun) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } -func (v *NullableTransactionRun) UnmarshalJSON(src []byte) error { +func (v *NullableTestSuiteRun) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) } diff --git a/cli/openapi/model_variable_set_resource.go b/cli/openapi/model_variable_set_resource.go index 3c49e720e9..d8e0bb936e 100644 --- a/cli/openapi/model_variable_set_resource.go +++ b/cli/openapi/model_variable_set_resource.go @@ -17,7 +17,7 @@ import ( // checks if the VariableSetResource type satisfies the MappedNullable interface at compile time var _ MappedNullable = &VariableSetResource{} -// VariableSetResource Represents an VariableSet structured into the Resources format. +// VariableSetResource Represents a 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"` diff --git a/cli/preprocessor/testsuite.go b/cli/preprocessor/testsuite.go new file mode 100644 index 0000000000..55437c4627 --- /dev/null +++ b/cli/preprocessor/testsuite.go @@ -0,0 +1,93 @@ +package preprocessor + +import ( + "context" + "fmt" + + "github.com/goccy/go-yaml" + "github.com/kubeshop/tracetest/cli/openapi" + "github.com/kubeshop/tracetest/cli/pkg/fileutil" + "go.uber.org/zap" +) + +type applyTestFunc func(context.Context, fileutil.File) (fileutil.File, error) + +type testSuite struct { + logger *zap.Logger + applyTestFn applyTestFunc +} + +func TestSuite(logger *zap.Logger, applyTestFn applyTestFunc) testSuite { + return testSuite{ + logger: logger, + applyTestFn: applyTestFn, + } +} + +func (t testSuite) Preprocess(ctx context.Context, input fileutil.File) (fileutil.File, error) { + var suite openapi.TestSuiteResource + err := yaml.Unmarshal(input.Contents(), &suite) + if err != nil { + t.logger.Error("error parsing test suite", zap.String("content", string(input.Contents())), zap.Error(err)) + return input, fmt.Errorf("could not unmarshal test suite yaml: %w", err) + } + + // TODO: This should be removed at some point as the Environment type is deprecated + if *suite.Type == "Transaction" { + textType := "TestSuite" + suite.Type = &textType + } + + suite, err = t.mapTestSuiteSteps(ctx, input, suite) + if err != nil { + return input, fmt.Errorf("could not map test suite steps: %w", err) + } + + marshalled, err := yaml.Marshal(suite) + if err != nil { + return input, fmt.Errorf("could not marshal test yaml: %w", err) + } + return fileutil.New(input.AbsPath(), marshalled), nil +} + +func (t testSuite) mapTestSuiteSteps(ctx context.Context, input fileutil.File, suite openapi.TestSuiteResource) (openapi.TestSuiteResource, error) { + for i, step := range suite.Spec.GetSteps() { + t.logger.Debug("mapping test suite step", + zap.Int("index", i), + zap.String("step", step), + ) + if !fileutil.LooksLikeFilePath(step) { + t.logger.Debug("does not look like a file path", + zap.Int("index", i), + zap.String("step", step), + ) + continue + } + + f, err := fileutil.Read(input.RelativeFile(step)) + if err != nil { + return openapi.TestSuiteResource{}, fmt.Errorf("cannot read test file: %w", err) + } + + testFile, err := t.applyTestFn(ctx, f) + if err != nil { + return openapi.TestSuiteResource{}, fmt.Errorf("cannot apply test '%s': %w", step, err) + } + + var test openapi.TestResource + err = yaml.Unmarshal(testFile.Contents(), &test) + if err != nil { + return openapi.TestSuiteResource{}, fmt.Errorf("cannot unmarshal updated test '%s': %w", step, err) + } + + t.logger.Debug("mapped test suite step", + zap.Int("index", i), + zap.String("step", step), + zap.String("mapped step", test.Spec.GetId()), + ) + + suite.Spec.Steps[i] = test.Spec.GetId() + } + + return suite, nil +} diff --git a/cli/preprocessor/transaction.go b/cli/preprocessor/transaction.go deleted file mode 100644 index 7c3015ae64..0000000000 --- a/cli/preprocessor/transaction.go +++ /dev/null @@ -1,87 +0,0 @@ -package preprocessor - -import ( - "context" - "fmt" - - "github.com/goccy/go-yaml" - "github.com/kubeshop/tracetest/cli/openapi" - "github.com/kubeshop/tracetest/cli/pkg/fileutil" - "go.uber.org/zap" -) - -type applyTestFunc func(context.Context, fileutil.File) (fileutil.File, error) - -type transaction struct { - logger *zap.Logger - applyTestFn applyTestFunc -} - -func Transaction(logger *zap.Logger, applyTestFn applyTestFunc) transaction { - return transaction{ - logger: logger, - applyTestFn: applyTestFn, - } -} - -func (t transaction) Preprocess(ctx context.Context, input fileutil.File) (fileutil.File, error) { - var tran openapi.TransactionResource - err := yaml.Unmarshal(input.Contents(), &tran) - if err != nil { - t.logger.Error("error parsing transaction", zap.String("content", string(input.Contents())), zap.Error(err)) - return input, fmt.Errorf("could not unmarshal transaction yaml: %w", err) - } - - tran, err = t.mapTransactionSteps(ctx, input, tran) - if err != nil { - return input, fmt.Errorf("could not map transaction steps: %w", err) - } - - marshalled, err := yaml.Marshal(tran) - if err != nil { - return input, fmt.Errorf("could not marshal test yaml: %w", err) - } - return fileutil.New(input.AbsPath(), marshalled), nil -} - -func (t transaction) mapTransactionSteps(ctx context.Context, input fileutil.File, tran openapi.TransactionResource) (openapi.TransactionResource, error) { - for i, step := range tran.Spec.GetSteps() { - t.logger.Debug("mapping transaction step", - zap.Int("index", i), - zap.String("step", step), - ) - if !fileutil.LooksLikeFilePath(step) { - t.logger.Debug("does not look like a file path", - zap.Int("index", i), - zap.String("step", step), - ) - continue - } - - f, err := fileutil.Read(input.RelativeFile(step)) - if err != nil { - return openapi.TransactionResource{}, fmt.Errorf("cannot read test file: %w", err) - } - - testFile, err := t.applyTestFn(ctx, f) - if err != nil { - return openapi.TransactionResource{}, fmt.Errorf("cannot apply test '%s': %w", step, err) - } - - var test openapi.TestResource - err = yaml.Unmarshal(testFile.Contents(), &test) - if err != nil { - return openapi.TransactionResource{}, fmt.Errorf("cannot unmarshal updated test '%s': %w", step, err) - } - - t.logger.Debug("mapped transaction step", - zap.Int("index", i), - zap.String("step", step), - zap.String("mapped step", test.Spec.GetId()), - ) - - tran.Spec.Steps[i] = test.Spec.GetId() - } - - return tran, nil -} diff --git a/cli/runner/orchestrator.go b/cli/runner/orchestrator.go index 97fd4a3248..11f2f95f4c 100644 --- a/cli/runner/orchestrator.go +++ b/cli/runner/orchestrator.go @@ -386,7 +386,7 @@ func HandleRunError(resp *http.Response, reqErr error) error { } if reqErr != nil { - return fmt.Errorf("could not run transaction: %w", reqErr) + return fmt.Errorf("could not run test suite: %w", reqErr) } return nil diff --git a/cli/runner/registry.go b/cli/runner/registry.go index ab80a0a76e..2f865791a9 100644 --- a/cli/runner/registry.go +++ b/cli/runner/registry.go @@ -4,30 +4,48 @@ import ( "fmt" ) -type Registry map[string]Runner +type Registry struct { + runners map[string]Runner + proxies map[string]string +} func NewRegistry() Registry { - return Registry{} + return Registry{ + runners: map[string]Runner{}, + proxies: map[string]string{}, + } } func (r Registry) Register(runner Runner) Registry { - r[runner.Name()] = runner + r.runners[runner.Name()] = runner + return r +} + +func (r Registry) RegisterProxy(proxyName, runnerName string) Registry { + r.proxies[proxyName] = runnerName return r } var ErrNotFound = fmt.Errorf("runner not found") func (r Registry) Get(name string) (Runner, error) { - if runner, ok := r[name]; ok { - return runner, nil + runner, ok := r.runners[name] + if !ok { + if runnerName, ok := r.proxies[name]; ok { + if !ok { + return nil, ErrNotFound + } + + return r.Get(runnerName) + } } - return nil, ErrNotFound + return runner, nil } func (r Registry) List() []string { var list []string - for name := range r { + for name := range r.runners { list = append(list, name) } diff --git a/cli/runner/testsuite_runner.go b/cli/runner/testsuite_runner.go new file mode 100644 index 0000000000..53a60d4860 --- /dev/null +++ b/cli/runner/testsuite_runner.go @@ -0,0 +1,146 @@ +package runner + +import ( + "context" + "fmt" + "strconv" + + "github.com/kubeshop/tracetest/cli/formatters" + "github.com/kubeshop/tracetest/cli/openapi" + "github.com/kubeshop/tracetest/cli/pkg/fileutil" + "github.com/kubeshop/tracetest/cli/pkg/resourcemanager" +) + +type testSuiteFormatter interface { + Format(output formatters.TestSuiteRunOutput, format formatters.Output) string +} + +type testSuiteRunner struct { + client resourcemanager.Client + openapiClient *openapi.APIClient + formatter testSuiteFormatter +} + +func TestSuiteRunner( + client resourcemanager.Client, + openapiClient *openapi.APIClient, + formatter testSuiteFormatter, +) Runner { + return testSuiteRunner{ + client: client, + openapiClient: openapiClient, + formatter: formatter, + } +} + +func (r testSuiteRunner) Name() string { + return "testsuite" +} + +func (r testSuiteRunner) GetByID(_ context.Context, id string) (resource any, _ error) { + jsonTestSuite, err := r.client.Get(context.Background(), id, jsonFormat) + if err != nil { + return nil, fmt.Errorf("cannot get test suite '%s': %w", id, err) + } + + var testSuite openapi.TestSuiteResource + err = jsonFormat.Unmarshal([]byte(jsonTestSuite), &testSuite) + if err != nil { + return nil, fmt.Errorf("cannot unmarshal test suite definition file: %w", err) + } + + return testSuite, nil +} + +func (r testSuiteRunner) Apply(ctx context.Context, df fileutil.File) (resource any, _ error) { + updated, err := r.client.Apply(ctx, df, yamlFormat) + if err != nil { + return nil, fmt.Errorf("could not read test suite file: %w", err) + } + + var parsed openapi.TestSuiteResource + err = yamlFormat.Unmarshal([]byte(updated), &parsed) + if err != nil { + return nil, fmt.Errorf("cannot unmarshal test suite definition file: %w", err) + } + + return parsed, nil +} + +func (r testSuiteRunner) StartRun(ctx context.Context, resource any, runInfo openapi.RunInformation) (RunResult, error) { + tran := resource.(openapi.TestSuiteResource) + run, resp, err := r.openapiClient.ApiApi. + RunTestSuite(ctx, tran.Spec.GetId()). + RunInformation(runInfo). + Execute() + + err = HandleRunError(resp, err) + if err != nil { + return RunResult{}, err + } + + full, err := r.client.Get(ctx, tran.Spec.GetId(), jsonFormat) + if err != nil { + return RunResult{}, fmt.Errorf("cannot get full test suite '%s': %w", tran.Spec.GetId(), err) + } + err = jsonFormat.Unmarshal([]byte(full), &tran) + if err != nil { + return RunResult{}, fmt.Errorf("cannot get full test suite '%s': %w", tran.Spec.GetId(), err) + } + + return RunResult{ + Resource: tran, + Run: *run, + }, nil +} + +func (r testSuiteRunner) UpdateResult(ctx context.Context, result RunResult) (RunResult, error) { + testSuite := result.Resource.(openapi.TestSuiteResource) + run := result.Run.(openapi.TestSuiteRun) + runID, err := strconv.Atoi(run.GetId()) + if err != nil { + return RunResult{}, fmt.Errorf("invalid test suite run id format: %w", err) + } + + updated, _, err := r.openapiClient.ApiApi. + GetTestSuiteRun(ctx, testSuite.Spec.GetId(), int32(runID)). + Execute() + + if err != nil { + return RunResult{}, err + } + + allPassed := true + for _, s := range updated.GetSteps() { + if !s.Result.GetAllPassed() { + allPassed = false + break + } + } + + passed := !isStateFailed(updated.GetState()) && allPassed && updated.GetAllStepsRequiredGatesPassed() + + return RunResult{ + Resource: testSuite, + Run: *updated, + Finished: isStateFinished(updated.GetState()), + Passed: passed, + }, nil +} + +func (r testSuiteRunner) JUnitResult(ctx context.Context, result RunResult) (string, error) { + return "", ErrJUnitNotSupported +} + +func (r testSuiteRunner) FormatResult(result RunResult, format string) string { + testSuite := result.Resource.(openapi.TestSuiteResource) + run := result.Run.(openapi.TestSuiteRun) + + tro := formatters.TestSuiteRunOutput{ + HasResults: result.Finished, + TestSuite: testSuite.GetSpec(), + Run: run, + } + + return r.formatter.Format(tro, formatters.Output(format)) +} diff --git a/cli/runner/transaction_runner.go b/cli/runner/transaction_runner.go deleted file mode 100644 index d29fcae731..0000000000 --- a/cli/runner/transaction_runner.go +++ /dev/null @@ -1,146 +0,0 @@ -package runner - -import ( - "context" - "fmt" - "strconv" - - "github.com/kubeshop/tracetest/cli/formatters" - "github.com/kubeshop/tracetest/cli/openapi" - "github.com/kubeshop/tracetest/cli/pkg/fileutil" - "github.com/kubeshop/tracetest/cli/pkg/resourcemanager" -) - -type transactionFormatter interface { - Format(output formatters.TransactionRunOutput, format formatters.Output) string -} - -type transactionRunner struct { - client resourcemanager.Client - openapiClient *openapi.APIClient - formatter transactionFormatter -} - -func TransactionRunner( - client resourcemanager.Client, - openapiClient *openapi.APIClient, - formatter transactionFormatter, -) Runner { - return transactionRunner{ - client: client, - openapiClient: openapiClient, - formatter: formatter, - } -} - -func (r transactionRunner) Name() string { - return "transaction" -} - -func (r transactionRunner) GetByID(_ context.Context, id string) (resource any, _ error) { - jsonTransaction, err := r.client.Get(context.Background(), id, jsonFormat) - if err != nil { - return nil, fmt.Errorf("cannot get transaction '%s': %w", id, err) - } - - var transaction openapi.TransactionResource - err = jsonFormat.Unmarshal([]byte(jsonTransaction), &transaction) - if err != nil { - return nil, fmt.Errorf("cannot unmarshal transaction definition file: %w", err) - } - - return transaction, nil -} - -func (r transactionRunner) Apply(ctx context.Context, df fileutil.File) (resource any, _ error) { - updated, err := r.client.Apply(ctx, df, yamlFormat) - if err != nil { - return nil, fmt.Errorf("could not read transaction file: %w", err) - } - - var parsed openapi.TransactionResource - err = yamlFormat.Unmarshal([]byte(updated), &parsed) - if err != nil { - return nil, fmt.Errorf("cannot unmarshal transaction definition file: %w", err) - } - - return parsed, nil -} - -func (r transactionRunner) StartRun(ctx context.Context, resource any, runInfo openapi.RunInformation) (RunResult, error) { - tran := resource.(openapi.TransactionResource) - run, resp, err := r.openapiClient.ApiApi. - RunTransaction(ctx, tran.Spec.GetId()). - RunInformation(runInfo). - Execute() - - err = HandleRunError(resp, err) - if err != nil { - return RunResult{}, err - } - - full, err := r.client.Get(ctx, tran.Spec.GetId(), jsonFormat) - if err != nil { - return RunResult{}, fmt.Errorf("cannot get full transaction '%s': %w", tran.Spec.GetId(), err) - } - err = jsonFormat.Unmarshal([]byte(full), &tran) - if err != nil { - return RunResult{}, fmt.Errorf("cannot get full transaction '%s': %w", tran.Spec.GetId(), err) - } - - return RunResult{ - Resource: tran, - Run: *run, - }, nil -} - -func (r transactionRunner) UpdateResult(ctx context.Context, result RunResult) (RunResult, error) { - transaction := result.Resource.(openapi.TransactionResource) - run := result.Run.(openapi.TransactionRun) - runID, err := strconv.Atoi(run.GetId()) - if err != nil { - return RunResult{}, fmt.Errorf("invalid transaction run id format: %w", err) - } - - updated, _, err := r.openapiClient.ApiApi. - GetTransactionRun(ctx, transaction.Spec.GetId(), int32(runID)). - Execute() - - if err != nil { - return RunResult{}, err - } - - allPassed := true - for _, s := range updated.GetSteps() { - if !s.Result.GetAllPassed() { - allPassed = false - break - } - } - - passed := !isStateFailed(updated.GetState()) && allPassed && updated.GetAllStepsRequiredGatesPassed() - - return RunResult{ - Resource: transaction, - Run: *updated, - Finished: isStateFinished(updated.GetState()), - Passed: passed, - }, nil -} - -func (r transactionRunner) JUnitResult(ctx context.Context, result RunResult) (string, error) { - return "", ErrJUnitNotSupported -} - -func (r transactionRunner) FormatResult(result RunResult, format string) string { - transaction := result.Resource.(openapi.TransactionResource) - run := result.Run.(openapi.TransactionRun) - - tro := formatters.TransactionRunOutput{ - HasResults: result.Finished, - Transaction: transaction.GetSpec(), - Run: run, - } - - return r.formatter.Format(tro, formatters.Output(format)) -} diff --git a/server/README.md b/server/README.md index 14ba20888f..1f190dfc95 100644 --- a/server/README.md +++ b/server/README.md @@ -25,3 +25,4 @@ test/ test_run_repository.go test_run_entities.go ``` + diff --git a/server/app/app.go b/server/app/app.go index dc55bd9f13..f88962e9fd 100644 --- a/server/app/app.go +++ b/server/app/app.go @@ -34,10 +34,10 @@ import ( "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/testdb" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/kubeshop/tracetest/server/tracedb" "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" ) @@ -214,8 +214,8 @@ func (app *App) Start(opts ...appOption) error { testRunnerRepo := testrunner.NewRepository(db) tracesRepo := traces.NewTraceRepository(db) - transactionsRepository := transaction.NewRepository(db, testRepo) - transactionRunRepository := transaction.NewRunRepository(db, runRepo) + testSuiteRepository := testsuite.NewRepository(db, testRepo) + testSuiteRunRepository := testsuite.NewRunRepository(db, runRepo) tracedbFactory := tracedb.Factory(tracesRepo) @@ -241,16 +241,16 @@ func (app *App) Start(opts ...appOption) error { testPipeline.Stop() }) - transactionPipeline := buildTransactionPipeline( - transactionsRepository, - transactionRunRepository, + testSuitePipeline := buildTestSuitePipeline( + testSuiteRepository, + testSuiteRunRepository, testPipeline, subscriptionManager, ) - transactionPipeline.Start() + testSuitePipeline.Start() app.registerStopFn(func() { - transactionPipeline.Stop() + testSuitePipeline.Stop() }) err = analytics.SendEvent("Server Started", "beacon", "", nil) @@ -264,11 +264,11 @@ func (app *App) Start(opts ...appOption) error { tracer, testPipeline, - transactionPipeline, + testSuitePipeline, testDB, - transactionsRepository, - transactionRunRepository, + testSuiteRepository, + testSuiteRunRepository, testRepo, runRepo, variableSetRepo, @@ -287,7 +287,7 @@ func (app *App) Start(opts ...appOption) error { PathPrefix("/api"). Subrouter() - registerTransactionResource(transactionsRepository, apiRouter, provisioner, tracer) + registerTestSuiteResource(testSuiteRepository, apiRouter, provisioner, tracer) registerConfigResource(configRepo, apiRouter, provisioner, tracer) registerPollingProfilesResource(pollingProfileRepo, apiRouter, provisioner, tracer) registerVariableSetResource(variableSetRepo, apiRouter, provisioner, tracer) @@ -407,10 +407,10 @@ func registerTestRunner(testRunnerRepo *testrunner.Repository, router *mux.Route provisioner.AddResourceProvisioner(manager) } -func registerTransactionResource(repo *transaction.Repository, router *mux.Router, provisioner *provisioning.Provisioner, tracer trace.Tracer) { - manager := resourcemanager.New[transaction.Transaction]( - transaction.TransactionResourceName, - transaction.TransactionResourceNamePlural, +func registerTestSuiteResource(repo *testsuite.Repository, router *mux.Router, provisioner *provisioning.Provisioner, tracer trace.Tracer) { + manager := resourcemanager.New[testsuite.TestSuite]( + testsuite.TestSuiteResourceName, + testsuite.TestSuiteResourceNamePlural, repo, resourcemanager.CanBeAugmented(), resourcemanager.WithTracer(tracer), @@ -519,11 +519,11 @@ func controller( tracer trace.Tracer, testRunner *executor.TestPipeline, - transactionRunner *executor.TransactionPipeline, + testSuitesRunner *executor.TestSuitesPipeline, testRunEvents model.TestRunEventRepository, - transactionRepo *transaction.Repository, - transactionRunRepo *transaction.RunRepository, + transactionRepo *testsuite.Repository, + transactionRunRepo *testsuite.RunRepository, testRepo test.Repository, testRunRepo test.RunRepository, variablesetRepo *variableset.Repository, @@ -537,7 +537,7 @@ func controller( tracer, testRunner, - transactionRunner, + testSuitesRunner, testRunEvents, transactionRepo, @@ -559,11 +559,11 @@ func httpRouter( tracer trace.Tracer, testRunner *executor.TestPipeline, - transactionRunner *executor.TransactionPipeline, + testSuitesRunner *executor.TestSuitesPipeline, testRunEvents model.TestRunEventRepository, - transactionRepo *transaction.Repository, - transactionRunRepo *transaction.RunRepository, + testSuiteRepo *testsuite.Repository, + testSuiteRunRepo *testsuite.RunRepository, testRepo test.Repository, testRunRepo test.RunRepository, variableSetRepo *variableset.Repository, @@ -575,11 +575,11 @@ func httpRouter( tracer, testRunner, - transactionRunner, + testSuitesRunner, testRunEvents, - transactionRepo, - transactionRunRepo, + testSuiteRepo, + testSuiteRunRepo, testRepo, testRunRepo, variableSetRepo, diff --git a/server/app/test_suite_pipeline.go b/server/app/test_suite_pipeline.go new file mode 100644 index 0000000000..560b0b7822 --- /dev/null +++ b/server/app/test_suite_pipeline.go @@ -0,0 +1,28 @@ +package app + +import ( + "github.com/kubeshop/tracetest/server/executor" + "github.com/kubeshop/tracetest/server/subscription" + "github.com/kubeshop/tracetest/server/testsuite" +) + +func buildTestSuitePipeline( + tranRepo *testsuite.Repository, + runRepo *testsuite.RunRepository, + testRunner *executor.TestPipeline, + subscriptionManager *subscription.Manager, +) *executor.TestSuitesPipeline { + tranRunner := executor.NewTestSuiteRunner(testRunner, runRepo, subscriptionManager) + queueBuilder := executor.NewQueueBuilder(). + WithTestSuiteGetter(tranRepo). + WithTestSuiteRunGetter(runRepo) + + pipeline := executor.NewPipeline(queueBuilder, + executor.PipelineStep{Processor: tranRunner, Driver: executor.NewInMemoryQueueDriver("testSuiteRunner")}, + ) + + return executor.NewTestSuitePipeline( + pipeline, + runRepo, + ) +} diff --git a/server/app/transaction_pipeline.go b/server/app/transaction_pipeline.go deleted file mode 100644 index 5783dcc6f2..0000000000 --- a/server/app/transaction_pipeline.go +++ /dev/null @@ -1,28 +0,0 @@ -package app - -import ( - "github.com/kubeshop/tracetest/server/executor" - "github.com/kubeshop/tracetest/server/subscription" - "github.com/kubeshop/tracetest/server/transaction" -) - -func buildTransactionPipeline( - tranRepo *transaction.Repository, - runRepo *transaction.RunRepository, - testRunner *executor.TestPipeline, - subscriptionManager *subscription.Manager, -) *executor.TransactionPipeline { - tranRunner := executor.NewTransactionRunner(testRunner, runRepo, subscriptionManager) - queueBuilder := executor.NewQueueBuilder(). - WithTransactionGetter(tranRepo). - WithTransactionRunGetter(runRepo) - - pipeline := executor.NewPipeline(queueBuilder, - executor.PipelineStep{Processor: tranRunner, Driver: executor.NewInMemoryQueueDriver("transactionRunner")}, - ) - - return executor.NewTransactionPipeline( - pipeline, - runRepo, - ) -} diff --git a/server/executor/queue.go b/server/executor/queue.go index c1a8498978..36eb565bcf 100644 --- a/server/executor/queue.go +++ b/server/executor/queue.go @@ -13,7 +13,7 @@ import ( "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/test" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" "go.opentelemetry.io/otel/propagation" ) @@ -69,8 +69,8 @@ func (h headers) SetBool(key string, value bool) { type Job struct { Headers *headers - Transaction transaction.Transaction - TransactionRun transaction.TransactionRun + TestSuite testsuite.TestSuite + TestSuiteRun testsuite.TestSuiteRun Test test.Test Run test.Run @@ -81,8 +81,8 @@ type Job struct { type jsonJob struct { Headers *headers `json:"headers"` - TransactionID string `json:"transaction_id"` - TransactionRunID int `json:"transaction_run_id"` + TestSuiteID string `json:"test_suite_id"` + TestSuiteRunID int `json:"test_suite_run_id"` TestID string `json:"test_id"` RunID int `json:"run_id"` PollingProfileID string `json:"polling_profile_id"` @@ -92,8 +92,8 @@ type jsonJob struct { func (job Job) MarshalJSON() ([]byte, error) { return json.Marshal(jsonJob{ Headers: job.Headers, - TransactionID: job.Transaction.ID.String(), - TransactionRunID: job.TransactionRun.ID, + TestSuiteID: job.TestSuite.ID.String(), + TestSuiteRunID: job.TestSuiteRun.ID, TestID: job.Test.ID.String(), RunID: job.Run.ID, PollingProfileID: job.PollingProfile.ID.String(), @@ -109,8 +109,8 @@ func (job *Job) UnmarshalJSON(data []byte) error { } job.Headers = jj.Headers - job.Transaction.ID = id.ID(jj.TransactionID) - job.TransactionRun.ID = jj.TransactionRunID + job.TestSuite.ID = id.ID(jj.TestSuiteID) + job.TestSuiteRun.ID = jj.TestSuiteRunID job.Test.ID = id.ID(jj.TestID) job.Run.ID = jj.RunID job.PollingProfile.ID = id.ID(jj.PollingProfileID) @@ -157,12 +157,12 @@ type testRunGetter interface { GetRun(_ context.Context, testID id.ID, runID int) (test.Run, error) } -type transactionGetter interface { - GetAugmented(context.Context, id.ID) (transaction.Transaction, error) +type testSuiteGetter interface { + GetAugmented(context.Context, id.ID) (testsuite.TestSuite, error) } -type transactionRunGetter interface { - GetTransactionRun(_ context.Context, transactionID id.ID, runID int) (transaction.TransactionRun, error) +type testSuiteRunGetter interface { + GetTestSuiteRun(_ context.Context, transactionID id.ID, runID int) (testsuite.TestSuiteRun, error) } type subscriptor interface { @@ -181,8 +181,8 @@ type QueueBuilder struct { runs testRunGetter tests testGetter - transactionRuns transactionRunGetter - transactions transactionGetter + testSuiteRuns testSuiteRunGetter + testSuites testSuiteGetter pollingProfiles pollingProfileGetter dataStores dataStoreGetter @@ -222,13 +222,13 @@ func (qb *QueueBuilder) WithDataStoreGetter(dataStore dataStoreGetter) *QueueBui return qb } -func (qb *QueueBuilder) WithTransactionGetter(transactions transactionGetter) *QueueBuilder { - qb.transactions = transactions +func (qb *QueueBuilder) WithTestSuiteGetter(suites testSuiteGetter) *QueueBuilder { + qb.testSuites = suites return qb } -func (qb *QueueBuilder) WithTransactionRunGetter(transactionRuns transactionRunGetter) *QueueBuilder { - qb.transactionRuns = transactionRuns +func (qb *QueueBuilder) WithTestSuiteRunGetter(suiteRuns testSuiteRunGetter) *QueueBuilder { + qb.testSuiteRuns = suiteRuns return qb } @@ -240,8 +240,8 @@ func (qb *QueueBuilder) Build(driver QueueDriver, itemProcessor QueueItemProcess runs: qb.runs, tests: qb.tests, - transactionRuns: qb.transactionRuns, - transactions: qb.transactions, + testSuiteRuns: qb.testSuiteRuns, + testSuites: qb.testSuites, pollingProfiles: qb.pollingProfiles, dataStores: qb.dataStores, @@ -262,8 +262,8 @@ type Queue struct { runs testRunGetter tests testGetter - transactionRuns transactionRunGetter - transactions transactionGetter + testSuiteRuns testSuiteRunGetter + testSuites testSuiteGetter pollingProfiles pollingProfileGetter dataStores dataStoreGetter @@ -296,8 +296,8 @@ func (q Queue) Enqueue(ctx context.Context, job Job) { Test: test.Test{ID: job.Test.ID}, Run: test.Run{ID: job.Run.ID}, - Transaction: transaction.Transaction{ID: job.Transaction.ID}, - TransactionRun: transaction.TransactionRun{ID: job.TransactionRun.ID}, + TestSuite: testsuite.TestSuite{ID: job.TestSuite.ID}, + TestSuiteRun: testsuite.TestSuiteRun{ID: job.TestSuiteRun.ID}, PollingProfile: pollingprofile.PollingProfile{ID: job.PollingProfile.ID}, DataStore: datastore.DataStore{ID: job.DataStore.ID}, @@ -323,8 +323,8 @@ func (q Queue) Listen(job Job) { // todo: change the otlp server to have its own table // newJob.Run = job.Run - newJob.Transaction = q.resolveTransaction(ctx, job) - newJob.TransactionRun = q.resolveTransactionRun(ctx, job) + newJob.TestSuite = q.resolveTestSuite(ctx, job) + newJob.TestSuiteRun = q.resolveTestSuiteRun(ctx, job) newJob.PollingProfile = q.resolvePollingProfile(ctx, job) newJob.DataStore = q.resolveDataStore(ctx, job) @@ -376,14 +376,14 @@ func (q Queue) listenForStopRequests(ctx context.Context, cancelCtx context.Canc q.subscriptor.Subscribe((StopRequest{job.Test.ID, job.Run.ID}).ResourceID(), sfn) } -func (q Queue) resolveTransaction(ctx context.Context, job Job) transaction.Transaction { - if q.transactions == nil { - return transaction.Transaction{} +func (q Queue) resolveTestSuite(ctx context.Context, job Job) testsuite.TestSuite { + if q.testSuites == nil { + return testsuite.TestSuite{} } - tran, err := q.transactions.GetAugmented(ctx, job.Transaction.ID) + tran, err := q.testSuites.GetAugmented(ctx, job.TestSuite.ID) if errors.Is(err, sql.ErrNoRows) { - return transaction.Transaction{} + return testsuite.TestSuite{} } if err != nil { panic(err) @@ -391,14 +391,14 @@ func (q Queue) resolveTransaction(ctx context.Context, job Job) transaction.Tran return tran } -func (q Queue) resolveTransactionRun(ctx context.Context, job Job) transaction.TransactionRun { - if q.transactionRuns == nil { - return transaction.TransactionRun{} +func (q Queue) resolveTestSuiteRun(ctx context.Context, job Job) testsuite.TestSuiteRun { + if q.testSuiteRuns == nil { + return testsuite.TestSuiteRun{} } - tranRun, err := q.transactionRuns.GetTransactionRun(ctx, job.Transaction.ID, job.TransactionRun.ID) + tranRun, err := q.testSuiteRuns.GetTestSuiteRun(ctx, job.TestSuite.ID, job.TestSuiteRun.ID) if errors.Is(err, sql.ErrNoRows) { - return transaction.TransactionRun{} + return testsuite.TestSuiteRun{} } if err != nil { panic(err) diff --git a/server/executor/transaction_run_updater.go b/server/executor/test_suite_run_updater.go similarity index 59% rename from server/executor/transaction_run_updater.go rename to server/executor/test_suite_run_updater.go index 765da7e31f..5df49e0a8a 100644 --- a/server/executor/transaction_run_updater.go +++ b/server/executor/test_suite_run_updater.go @@ -5,25 +5,25 @@ import ( "fmt" "github.com/kubeshop/tracetest/server/subscription" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" ) -type TransactionRunUpdater interface { - Update(context.Context, transaction.TransactionRun) error +type TestSuiteRunUpdater interface { + Update(context.Context, testsuite.TestSuiteRun) error } type CompositeTransactionUpdater struct { - listeners []TransactionRunUpdater + listeners []TestSuiteRunUpdater } -func (u CompositeTransactionUpdater) Add(l TransactionRunUpdater) CompositeTransactionUpdater { +func (u CompositeTransactionUpdater) Add(l TestSuiteRunUpdater) CompositeTransactionUpdater { u.listeners = append(u.listeners, l) return u } -var _ TransactionRunUpdater = CompositeTransactionUpdater{} +var _ TestSuiteRunUpdater = CompositeTransactionUpdater{} -func (u CompositeTransactionUpdater) Update(ctx context.Context, run transaction.TransactionRun) error { +func (u CompositeTransactionUpdater) Update(ctx context.Context, run testsuite.TestSuiteRun) error { for _, l := range u.listeners { if err := l.Update(ctx, run); err != nil { return fmt.Errorf("composite updating error: %w", err) @@ -38,14 +38,14 @@ type dbTransactionUpdater struct { } type transactionUpdater interface { - UpdateRun(context.Context, transaction.TransactionRun) error + UpdateRun(context.Context, testsuite.TestSuiteRun) error } -func NewDBTranasctionUpdater(repo transactionUpdater) TransactionRunUpdater { +func NewDBTranasctionUpdater(repo transactionUpdater) TestSuiteRunUpdater { return dbTransactionUpdater{repo} } -func (u dbTransactionUpdater) Update(ctx context.Context, run transaction.TransactionRun) error { +func (u dbTransactionUpdater) Update(ctx context.Context, run testsuite.TestSuiteRun) error { return u.repo.UpdateRun(ctx, run) } @@ -53,11 +53,11 @@ type subscriptionTransactionUpdater struct { manager *subscription.Manager } -func NewSubscriptionTransactionUpdater(manager *subscription.Manager) TransactionRunUpdater { +func NewSubscriptionTransactionUpdater(manager *subscription.Manager) TestSuiteRunUpdater { return subscriptionTransactionUpdater{manager} } -func (u subscriptionTransactionUpdater) Update(ctx context.Context, run transaction.TransactionRun) error { +func (u subscriptionTransactionUpdater) Update(ctx context.Context, run testsuite.TestSuiteRun) error { u.manager.PublishUpdate(subscription.Message{ ResourceID: run.ResourceID(), Type: "result_update", diff --git a/server/executor/transaction_runner.go b/server/executor/test_suite_runner.go similarity index 76% rename from server/executor/transaction_runner.go rename to server/executor/test_suite_runner.go index e9bea0cf09..f9b001a8f9 100644 --- a/server/executor/transaction_runner.go +++ b/server/executor/test_suite_runner.go @@ -9,22 +9,22 @@ import ( "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/testsuite" "github.com/kubeshop/tracetest/server/variableset" ) -type transactionRunRepository interface { +type testSuiteRunRepository interface { transactionUpdater - CreateRun(context.Context, transaction.TransactionRun) (transaction.TransactionRun, error) + CreateRun(context.Context, testsuite.TestSuiteRun) (testsuite.TestSuiteRun, error) } type testRunner interface { Run(context.Context, test.Test, test.RunMetadata, variableset.VariableSet, *[]testrunner.RequiredGate) test.Run } -func NewTransactionRunner( +func NewTestSuiteRunner( testRunner testRunner, - transactionRuns transactionRunRepository, + transactionRuns testSuiteRunRepository, subscriptionManager *subscription.Manager, ) *persistentTransactionRunner { updater := (CompositeTransactionUpdater{}). @@ -41,8 +41,8 @@ func NewTransactionRunner( type persistentTransactionRunner struct { testRunner testRunner - transactionRuns transactionRunRepository - updater TransactionRunUpdater + transactionRuns testSuiteRunRepository + updater TestSuiteRunUpdater subscriptionManager *subscription.Manager } @@ -51,25 +51,25 @@ func (r *persistentTransactionRunner) SetOutputQueue(_ Enqueuer) { } func (r persistentTransactionRunner) ProcessItem(ctx context.Context, job Job) { - tran := job.Transaction - run := job.TransactionRun + tran := job.TestSuite + run := job.TestSuiteRun - run.State = transaction.TransactionRunStateExecuting + run.State = testsuite.TestSuiteStateExecuting err := r.updater.Update(ctx, run) if err != nil { log.Printf("[TransactionRunner] could not update transaction run: %s", err.Error()) return } - log.Printf("[TransactionRunner] running transaction %s with %d steps", run.TransactionID, len(tran.Steps)) + log.Printf("[TransactionRunner] running transaction %s with %d steps", run.TestSuiteID, len(tran.Steps)) for step, test := range tran.Steps { run, err = r.runTransactionStep(ctx, run, step, test) if err != nil { - log.Printf("[TransactionRunner] could not execute step %d of transaction %s: %s", step, run.TransactionID, err.Error()) + log.Printf("[TransactionRunner] could not execute step %d of transaction %s: %s", step, run.TestSuiteID, err.Error()) return } - if run.State == transaction.TransactionRunStateFailed { + if run.State == testsuite.TestSuiteStateFailed { break } @@ -81,8 +81,8 @@ func (r persistentTransactionRunner) ProcessItem(ctx context.Context, job Job) { } } - if run.State != transaction.TransactionRunStateFailed { - run.State = transaction.TransactionRunStateFinished + if run.State != testsuite.TestSuiteStateFailed { + run.State = testsuite.TestSuiteStateFinished } err = r.updater.Update(ctx, run) @@ -92,11 +92,11 @@ 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) { +func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr testsuite.TestSuiteRun, step int, testObj test.Test) (testsuite.TestSuiteRun, error) { 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) + return testsuite.TestSuiteRun{}, fmt.Errorf("could not update transaction run: %w", err) } done := make(chan bool) @@ -105,7 +105,7 @@ func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr func(m subscription.Message) error { testRun := m.Content.(test.Run) if testRun.LastError != nil { - tr.State = transaction.TransactionRunStateFailed + tr.State = testsuite.TestSuiteStateFailed tr.LastError = testRun.LastError } @@ -134,7 +134,7 @@ func (r persistentTransactionRunner) runTransactionStep(ctx context.Context, tr return tr, err } -func (r persistentTransactionRunner) updateStepRun(ctx context.Context, tr transaction.TransactionRun, step int, run test.Run) (transaction.TransactionRun, error) { +func (r persistentTransactionRunner) updateStepRun(ctx context.Context, tr testsuite.TestSuiteRun, step int, run test.Run) (testsuite.TestSuiteRun, error) { if len(tr.Steps) <= step { tr.Steps = append(tr.Steps, test.Run{}) } @@ -142,7 +142,7 @@ func (r persistentTransactionRunner) updateStepRun(ctx context.Context, tr trans tr.Steps[step] = run err := r.updater.Update(ctx, tr) if err != nil { - return transaction.TransactionRun{}, fmt.Errorf("could not update transaction run: %w", err) + return testsuite.TestSuiteRun{}, fmt.Errorf("could not update transaction run: %w", err) } return tr, nil diff --git a/server/executor/transaction_runner_test.go b/server/executor/test_suite_runner_test.go similarity index 81% rename from server/executor/transaction_runner_test.go rename to server/executor/test_suite_runner_test.go index 118b88389b..5682c81d50 100644 --- a/server/executor/transaction_runner_test.go +++ b/server/executor/test_suite_runner_test.go @@ -16,7 +16,7 @@ import ( "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/testmock" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/kubeshop/tracetest/server/variableset" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -66,11 +66,11 @@ func (r *fakeTestRunner) Run(ctx context.Context, testObj test.Test, metadata te return newRun } -func TestTransactionRunner(t *testing.T) { +func TestTestSuiteRunner(t *testing.T) { t.Run("NoErrors", func(t *testing.T) { - runTransactionRunnerTest(t, false, func(t *testing.T, actual transaction.TransactionRun) { - assert.Equal(t, transaction.TransactionRunStateFinished, actual.State) + runTestSuiteRunnerTest(t, false, func(t *testing.T, actual testsuite.TestSuiteRun) { + assert.Equal(t, testsuite.TestSuiteStateFinished, actual.State) require.Len(t, actual.Steps, 2) assert.Equal(t, actual.Steps[0].State, test.RunStateFinished) assert.Equal(t, actual.Steps[1].State, test.RunStateFinished) @@ -92,8 +92,8 @@ func TestTransactionRunner(t *testing.T) { }) t.Run("WithErrors", func(t *testing.T) { - runTransactionRunnerTest(t, true, func(t *testing.T, actual transaction.TransactionRun) { - assert.Equal(t, transaction.TransactionRunStateFailed, actual.State) + runTestSuiteRunnerTest(t, true, func(t *testing.T, actual testsuite.TestSuiteRun) { + assert.Equal(t, testsuite.TestSuiteStateFailed, actual.State) require.Len(t, actual.Steps, 1) assert.Equal(t, test.RunStateTriggerFailed, actual.Steps[0].State) }) @@ -108,7 +108,7 @@ func getDB() (model.Repository, *sql.DB) { return db, rawDB } -func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *testing.T, actual transaction.TransactionRun)) { +func runTestSuiteRunnerTest(t *testing.T, withErrors bool, assert func(t *testing.T, actual testsuite.TestSuiteRun)) { ctx := context.Background() _, rawDB := getDB() @@ -129,11 +129,11 @@ func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *test test2, err := testRepo.Create(ctx, test.Test{Name: "Test 2"}) require.NoError(t, err) - transactionsRepo := transaction.NewRepository(rawDB, testRepo) - transactionRunRepo := transaction.NewRunRepository(rawDB, runRepo) - tran, err := transactionsRepo.Create(ctx, transaction.Transaction{ + transactionsRepo := testsuite.NewRepository(rawDB, testRepo) + transactionRunRepo := testsuite.NewRunRepository(rawDB, runRepo) + tran, err := transactionsRepo.Create(ctx, testsuite.TestSuite{ ID: id.ID("tran1"), - Name: "transaction", + Name: "test_suite", StepIDs: []id.ID{test1.ID, test2.ID}, }) require.NoError(t, err) @@ -158,17 +158,17 @@ func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *test }) require.NoError(t, err) - runner := executor.NewTransactionRunner(testRunner, transactionRunRepo, subscriptionManager) + runner := executor.NewTestSuiteRunner(testRunner, transactionRunRepo, subscriptionManager) queueBuilder := executor.NewQueueBuilder(). - WithTransactionGetter(transactionsRepo). - WithTransactionRunGetter(transactionRunRepo) + WithTestSuiteGetter(transactionsRepo). + WithTestSuiteRunGetter(transactionRunRepo) pipeline := executor.NewPipeline(queueBuilder, executor.PipelineStep{Processor: runner, Driver: executor.NewInMemoryQueueDriver("runner")}, ) - transactionPipeline := executor.NewTransactionPipeline(pipeline, transactionRunRepo) + transactionPipeline := executor.NewTestSuitePipeline(pipeline, transactionRunRepo) transactionPipeline.Start() ctxWithTimeout, cancel := context.WithTimeout(ctx, 1*time.Second) @@ -176,9 +176,9 @@ func runTransactionRunnerTest(t *testing.T, withErrors bool, assert func(t *test transactionRun := transactionPipeline.Run(ctxWithTimeout, tran, metadata, env, nil) - done := make(chan transaction.TransactionRun, 1) + done := make(chan testsuite.TestSuiteRun, 1) sf := subscription.NewSubscriberFunction(func(m subscription.Message) error { - tr := m.Content.(transaction.TransactionRun) + tr := m.Content.(testsuite.TestSuiteRun) if tr.State.IsFinal() { done <- tr } diff --git a/server/executor/test_suites_pipeline.go b/server/executor/test_suites_pipeline.go new file mode 100644 index 0000000000..b54c66f2dd --- /dev/null +++ b/server/executor/test_suites_pipeline.go @@ -0,0 +1,46 @@ +package executor + +import ( + "context" + + "github.com/kubeshop/tracetest/server/executor/testrunner" + "github.com/kubeshop/tracetest/server/test" + "github.com/kubeshop/tracetest/server/testsuite" + "github.com/kubeshop/tracetest/server/variableset" +) + +type TestSuitesPipeline struct { + *Pipeline + runs testSuiteRunRepo +} + +type testSuiteRunRepo interface { + CreateRun(context.Context, testsuite.TestSuiteRun) (testsuite.TestSuiteRun, error) +} + +func NewTestSuitePipeline( + pipeline *Pipeline, + runs testSuiteRunRepo, +) *TestSuitesPipeline { + return &TestSuitesPipeline{ + Pipeline: pipeline, + runs: runs, + } +} + +func (p *TestSuitesPipeline) Run(ctx context.Context, tran testsuite.TestSuite, metadata test.RunMetadata, variableSet variableset.VariableSet, requiredGates *[]testrunner.RequiredGate) testsuite.TestSuiteRun { + tranRun := tran.NewRun() + tranRun.Metadata = metadata + tranRun.VariableSet = variableSet + tranRun.RequiredGates = requiredGates + + tranRun, _ = p.runs.CreateRun(ctx, tranRun) + + job := NewJob() + job.TestSuite = tran + job.TestSuiteRun = tranRun + + p.Pipeline.Begin(ctx, job) + + return tranRun +} diff --git a/server/executor/transaction_pipeline.go b/server/executor/transaction_pipeline.go deleted file mode 100644 index 4c0c342a0f..0000000000 --- a/server/executor/transaction_pipeline.go +++ /dev/null @@ -1,46 +0,0 @@ -package executor - -import ( - "context" - - "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 { - *Pipeline - runs transactionsRunRepo -} - -type transactionsRunRepo interface { - CreateRun(context.Context, transaction.TransactionRun) (transaction.TransactionRun, error) -} - -func NewTransactionPipeline( - pipeline *Pipeline, - runs transactionsRunRepo, -) *TransactionPipeline { - return &TransactionPipeline{ - Pipeline: pipeline, - runs: runs, - } -} - -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.VariableSet = variableSet - tranRun.RequiredGates = requiredGates - - tranRun, _ = p.runs.CreateRun(ctx, tranRun) - - job := NewJob() - job.Transaction = tran - job.TransactionRun = tranRun - - p.Pipeline.Begin(ctx, job) - - return tranRun -} diff --git a/server/http/controller.go b/server/http/controller.go index 5fa1bc6f3f..52d263c926 100644 --- a/server/http/controller.go +++ b/server/http/controller.go @@ -21,8 +21,8 @@ import ( "github.com/kubeshop/tracetest/server/openapi" "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/test" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/kubeshop/tracetest/server/tracedb" - "github.com/kubeshop/tracetest/server/transaction" "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -33,11 +33,11 @@ type controller struct { testRunner testRunner transactionRunner transactionRunner - testRunEvents model.TestRunEventRepository - testRunRepository test.RunRepository - testRepository testsRepository - transactionRepository transactionsRepository - transactionRunRepository transactionRunRepository + testRunEvents model.TestRunEventRepository + testRunRepository test.RunRepository + testRepository testsRepository + testSuiteRepository testSuiteRepository + testSuiteRunRepository testSuiteRunRepository variableSetGetter variableSetGetter newTraceDBFn func(ds datastore.DataStore) (tracedb.TraceDB, error) @@ -45,11 +45,11 @@ type controller struct { version string } -type transactionsRepository interface { - GetAugmented(context.Context, id.ID) (transaction.Transaction, error) - ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]transaction.Transaction, error) +type testSuiteRepository interface { + GetAugmented(context.Context, id.ID) (testsuite.TestSuite, error) + ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]testsuite.TestSuite, error) Count(ctx context.Context, query string) (int, error) - GetVersion(context.Context, id.ID, int) (transaction.Transaction, error) + GetVersion(context.Context, id.ID, int) (testsuite.TestSuite, error) } type testsRepository interface { @@ -61,10 +61,10 @@ type testsRepository interface { Create(context.Context, test.Test) (test.Test, error) } -type transactionRunRepository interface { - GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (transaction.TransactionRun, error) - GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]transaction.TransactionRun, error) - DeleteTransactionRun(ctx context.Context, tr transaction.TransactionRun) error +type testSuiteRunRepository interface { + GetTestSuiteRun(ctx context.Context, transactionID id.ID, runID int) (testsuite.TestSuiteRun, error) + GetTestSuiteRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]testsuite.TestSuiteRun, error) + DeleteTestSuiteRun(ctx context.Context, tr testsuite.TestSuiteRun) error } type testRunner interface { @@ -74,7 +74,7 @@ type testRunner interface { } type transactionRunner interface { - Run(context.Context, transaction.Transaction, test.RunMetadata, variableset.VariableSet, *[]testrunner.RequiredGate) transaction.TransactionRun + Run(context.Context, testsuite.TestSuite, test.RunMetadata, variableset.VariableSet, *[]testrunner.RequiredGate) testsuite.TestSuiteRun } type variableSetGetter interface { @@ -88,8 +88,8 @@ func NewController( transactionRunner transactionRunner, testRunEvents model.TestRunEventRepository, - transactionRepository transactionsRepository, - transactionRunRepository transactionRunRepository, + transactionRepository testSuiteRepository, + transactionRunRepository testSuiteRunRepository, testRepository testsRepository, testRunRepository test.RunRepository, variableSetGetter variableSetGetter, @@ -99,12 +99,12 @@ func NewController( version string, ) openapi.ApiApiServicer { return &controller{ - testRunEvents: testRunEvents, - transactionRepository: transactionRepository, - transactionRunRepository: transactionRunRepository, - testRepository: testRepository, - testRunRepository: testRunRepository, - variableSetGetter: variableSetGetter, + testRunEvents: testRunEvents, + testSuiteRepository: transactionRepository, + testSuiteRunRepository: transactionRunRepository, + testRepository: testRepository, + testRunRepository: testRunRepository, + variableSetGetter: variableSetGetter, testRunner: testRunner, transactionRunner: transactionRunner, @@ -495,8 +495,8 @@ func (c *controller) buildDataStores(ctx context.Context, info openapi.ResolveRe return [][]expression.DataStore{ds}, nil } -func (c *controller) GetTransactionVersion(ctx context.Context, tID string, version int32) (openapi.ImplResponse, error) { - transaction, err := c.transactionRepository.GetVersion(ctx, id.ID(tID), int(version)) +func (c *controller) GetTestSuiteVersion(ctx context.Context, tID string, version int32) (openapi.ImplResponse, error) { + transaction, err := c.testSuiteRepository.GetVersion(ctx, id.ID(tID), int(version)) if err != nil { return handleDBError(err), err @@ -506,8 +506,8 @@ func (c *controller) GetTransactionVersion(ctx context.Context, tID string, vers } // RunTransaction implements openapi.ApiApiServicer -func (c *controller) RunTransaction(ctx context.Context, transactionID string, runInfo openapi.RunInformation) (openapi.ImplResponse, error) { - transaction, err := c.transactionRepository.GetAugmented(ctx, id.ID(transactionID)) +func (c *controller) RunTestSuite(ctx context.Context, transactionID string, runInfo openapi.RunInformation) (openapi.ImplResponse, error) { + transaction, err := c.testSuiteRepository.GetAugmented(ctx, id.ID(transactionID)) if err != nil { return handleDBError(err), err } @@ -535,40 +535,40 @@ func (c *controller) RunTransaction(ctx context.Context, transactionID string, r run := c.transactionRunner.Run(ctx, transaction, metadata, environment, requiredGates) - return openapi.Response(http.StatusOK, c.mappers.Out.TransactionRun(run)), nil + return openapi.Response(http.StatusOK, c.mappers.Out.TestSuiteRun(run)), nil } -func (c *controller) GetTransactionRun(ctx context.Context, transactionId string, runId int32) (openapi.ImplResponse, error) { - run, err := c.transactionRunRepository.GetTransactionRun(ctx, id.ID(transactionId), int(runId)) +func (c *controller) GetTestSuiteRun(ctx context.Context, transactionId string, runId int32) (openapi.ImplResponse, error) { + run, err := c.testSuiteRunRepository.GetTestSuiteRun(ctx, id.ID(transactionId), int(runId)) if err != nil { return handleDBError(err), err } - openapiRun := c.mappers.Out.TransactionRun(run) + openapiRun := c.mappers.Out.TestSuiteRun(run) return openapi.Response(http.StatusOK, openapiRun), nil } -func (c *controller) GetTransactionRuns(ctx context.Context, transactionId string, take, skip int32) (openapi.ImplResponse, error) { - runs, err := c.transactionRunRepository.GetTransactionsRuns(ctx, id.ID(transactionId), take, skip) +func (c *controller) GetTestSuiteRuns(ctx context.Context, transactionId string, take, skip int32) (openapi.ImplResponse, error) { + runs, err := c.testSuiteRunRepository.GetTestSuiteRuns(ctx, id.ID(transactionId), take, skip) if err != nil { return handleDBError(err), err } - openapiRuns := make([]openapi.TransactionRun, 0, len(runs)) + openapiRuns := make([]openapi.TestSuiteRun, 0, len(runs)) for _, run := range runs { - openapiRuns = append(openapiRuns, c.mappers.Out.TransactionRun(run)) + openapiRuns = append(openapiRuns, c.mappers.Out.TestSuiteRun(run)) } return openapi.Response(http.StatusOK, openapiRuns), nil } -func (c *controller) DeleteTransactionRun(ctx context.Context, transactionId string, runId int32) (openapi.ImplResponse, error) { - run, err := c.transactionRunRepository.GetTransactionRun(ctx, id.ID(transactionId), int(runId)) +func (c *controller) DeleteTestSuiteRun(ctx context.Context, transactionId string, runId int32) (openapi.ImplResponse, error) { + run, err := c.testSuiteRunRepository.GetTestSuiteRun(ctx, id.ID(transactionId), int(runId)) if err != nil { return handleDBError(err), err } - err = c.transactionRunRepository.DeleteTransactionRun(ctx, run) + err = c.testSuiteRunRepository.DeleteTestSuiteRun(ctx, run) if err != nil { return handleDBError(err), err } @@ -579,7 +579,7 @@ func (c *controller) DeleteTransactionRun(ctx context.Context, transactionId str func (c *controller) GetResources(ctx context.Context, take, skip int32, query, sortBy, sortDirection string) (openapi.ImplResponse, error) { // TODO: this is endpoint is a hack to unblock the team quickly. // This is not production ready because it might take too long to respond if there are numerous - // transactions and transaction. + // tests and testsuite. if take == 0 { take = 20 @@ -587,12 +587,12 @@ func (c *controller) GetResources(ctx context.Context, take, skip int32, query, newTake := take + skip - transactions, err := c.transactionRepository.ListAugmented(ctx, int(newTake), 0, query, sortBy, sortDirection) + transactions, err := c.testSuiteRepository.ListAugmented(ctx, int(newTake), 0, query, sortBy, sortDirection) if err != nil { return handleDBError(err), err } - transactionCount, err := c.transactionRepository.Count(ctx, query) + transactionCount, err := c.testSuiteRepository.Count(ctx, query) if err != nil { return handleDBError(err), err } @@ -619,7 +619,7 @@ func (c *controller) GetResources(ctx context.Context, take, skip int32, query, return openapi.Response(http.StatusOK, paginatedResponse), nil } -func takeResources(transactions []transaction.Transaction, tests []test.Test, take, skip int32) []openapi.Resource { +func takeResources(transactions []testsuite.TestSuite, tests []test.Test, take, skip int32) []openapi.Resource { numItems := len(transactions) + len(tests) items := make([]openapi.Resource, numItems) maxNumItems := len(transactions) + len(tests) @@ -639,7 +639,7 @@ func takeResources(transactions []transaction.Transaction, tests []test.Test, ta if j >= len(tests) { transaction := transactions[i] transactionInterface := any(transaction) - items[currentNumberItens] = openapi.Resource{Type: "transaction", Item: &transactionInterface} + items[currentNumberItens] = openapi.Resource{Type: "testsuite", Item: &transactionInterface} i++ currentNumberItens++ continue @@ -651,7 +651,7 @@ func takeResources(transactions []transaction.Transaction, tests []test.Test, ta testInterface := any(test) if transaction.CreatedAt.After(*test.CreatedAt) { - items[currentNumberItens] = openapi.Resource{Type: "transaction", Item: &transactionInterface} + items[currentNumberItens] = openapi.Resource{Type: "testsuite", Item: &transactionInterface} i++ } else { items[currentNumberItens] = openapi.Resource{Type: "test", Item: &testInterface} diff --git a/server/http/custom_routes.go b/server/http/custom_routes.go index 859ccaab46..59894986b2 100644 --- a/server/http/custom_routes.go +++ b/server/http/custom_routes.go @@ -33,7 +33,7 @@ func (c *customController) Routes() openapi.Routes { routes := c.router.Routes() - routes[c.getRouteIndex("GetTransactionVersion")].HandlerFunc = c.GetTransactionVersion + routes[c.getRouteIndex("GetTestSuiteVersion")].HandlerFunc = c.GetTestSuiteVersion routes[c.getRouteIndex("GetRunResultJUnit")].HandlerFunc = c.GetRunResultJUnit @@ -56,9 +56,9 @@ func (c *customController) Routes() openapi.Routes { } // GetTransactionVersion - get a transaction specific version -func (c *customController) GetTransactionVersion(w http.ResponseWriter, r *http.Request) { +func (c *customController) GetTestSuiteVersion(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - transactionIdParam := params["transactionId"] + transactionIdParam := params["testSuiteId"] versionParam, err := parseInt32Parameter(params["version"], true) if err != nil { @@ -66,7 +66,7 @@ func (c *customController) GetTransactionVersion(w http.ResponseWriter, r *http. return } - result, err := c.service.GetTransactionVersion(r.Context(), transactionIdParam, versionParam) + result, err := c.service.GetTestSuiteVersion(r.Context(), transactionIdParam, versionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/server/http/mappings/tests.go b/server/http/mappings/tests.go index dafbb9186d..e94a70dd8e 100644 --- a/server/http/mappings/tests.go +++ b/server/http/mappings/tests.go @@ -12,8 +12,8 @@ import ( "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/test/trigger" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/kubeshop/tracetest/server/traces" - "github.com/kubeshop/tracetest/server/transaction" "github.com/kubeshop/tracetest/server/variableset" "go.opentelemetry.io/otel/trace" ) @@ -32,16 +32,16 @@ func optionalTime(in time.Time) *time.Time { return &in } -func (m OpenAPI) TransactionRun(in transaction.TransactionRun) openapi.TransactionRun { +func (m OpenAPI) TestSuiteRun(in testsuite.TestSuiteRun) openapi.TestSuiteRun { steps := make([]openapi.TestRun, 0, len(in.Steps)) for _, step := range in.Steps { steps = append(steps, m.Run(&step)) } - return openapi.TransactionRun{ + return openapi.TestSuiteRun{ Id: strconv.Itoa(in.ID), - Version: int32(in.TransactionVersion), + Version: int32(in.TestSuiteVersion), CreatedAt: in.CreatedAt, CompletedAt: in.CompletedAt, State: string(in.State), @@ -286,8 +286,8 @@ func (m OpenAPI) Run(in *test.Run) openapi.TestRun { Outputs: m.RunOutputs(in.Outputs), Metadata: in.Metadata, VariableSet: m.VariableSet(in.VariableSet), - TransactionId: in.TransactionID, - TransactionRunId: in.TransactionRunID, + TestSuiteId: in.TestSuiteID, + TestSuiteRunId: in.TestSuiteRunID, Linter: m.LinterResult(in.Linter), RequiredGatesResult: m.RequiredGatesResult(in.RequiredGatesResult), } diff --git a/server/http/validation/variable.go b/server/http/validation/variable.go index ebe79048c8..be5f8269f9 100644 --- a/server/http/validation/variable.go +++ b/server/http/validation/variable.go @@ -9,7 +9,7 @@ import ( "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/testsuite" "github.com/kubeshop/tracetest/server/variableset" ) @@ -90,9 +90,9 @@ func getPreviousEnvironmentValues(ctx context.Context, testRepo augmentedTestGet return map[string]variableset.VariableSetValue{}, nil } -func ValidateMissingVariablesFromTransaction(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, transaction transaction.Transaction, env variableset.VariableSet) (openapi.MissingVariablesError, error) { +func ValidateMissingVariablesFromTransaction(ctx context.Context, testRepo augmentedTestGetter, runRepo test.RunRepository, suite testsuite.TestSuite, env variableset.VariableSet) (openapi.MissingVariablesError, error) { missingVariables := make([]openapi.MissingVariable, 0) - for _, step := range transaction.Steps { + for _, step := range suite.Steps { stepValidationResult, err := ValidateMissingVariables(ctx, testRepo, runRepo, step, env) if err != ErrMissingVariables { return openapi.MissingVariablesError{}, err diff --git a/server/http/websocket/subscribe.go b/server/http/websocket/subscribe.go index 2856fe1cd9..c1a8490268 100644 --- a/server/http/websocket/subscribe.go +++ b/server/http/websocket/subscribe.go @@ -9,7 +9,7 @@ import ( "github.com/kubeshop/tracetest/server/model" "github.com/kubeshop/tracetest/server/subscription" "github.com/kubeshop/tracetest/server/test" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" ) type subscriptionMessage struct { @@ -64,10 +64,10 @@ func (e subscribeCommandExecutor) ResourceUpdatedEvent(resource interface{}) Eve mapped = e.mappers.Out.Run(&v) case *test.Run: mapped = e.mappers.Out.Run(v) - case transaction.TransactionRun: - mapped = e.mappers.Out.TransactionRun(v) - case *transaction.TransactionRun: - mapped = e.mappers.Out.TransactionRun(*v) + case testsuite.TestSuiteRun: + mapped = e.mappers.Out.TestSuiteRun(v) + case *testsuite.TestSuiteRun: + mapped = e.mappers.Out.TestSuiteRun(*v) case model.TestRunEvent: mapped = e.mappers.Out.TestRunEvent(v) default: diff --git a/server/migrations/31_transactions_to_testsuites.down.sql b/server/migrations/31_transactions_to_testsuites.down.sql new file mode 100644 index 0000000000..44de50a961 --- /dev/null +++ b/server/migrations/31_transactions_to_testsuites.down.sql @@ -0,0 +1,33 @@ +BEGIN; + +ALTER TABLE + test_suites RENAME TO transactions; + +ALTER TABLE + test_suite_steps RENAME TO transaction_steps; + +ALTER TABLE + transaction_steps RENAME COlUMN test_suite_id TO transaction_id; + +ALTER TABLE + transaction_steps RENAME COlUMN test_suite_version TO transaction_version; + +ALTER TABLE + test_suite_runs RENAME TO transaction_runs; + +ALTER TABLE + transaction_runs RENAME COlUMN test_suite_id TO transaction_id; + +ALTER TABLE + transaction_runs RENAME COlUMN test_suite_version TO transaction_version; + +ALTER TABLE + test_suite_run_steps RENAME TO transaction_run_steps; + +ALTER TABLE + transaction_run_steps RENAME COLUMN test_suite_run_id TO transaction_run_id; + +ALTER TABLE + transaction_run_steps RENAME COLUMN test_suite_run_test_suite_id TO transaction_run_transaction_id; + +COMMIT; \ No newline at end of file diff --git a/server/migrations/31_transactions_to_testsuites.up.sql b/server/migrations/31_transactions_to_testsuites.up.sql new file mode 100644 index 0000000000..d8831a6082 --- /dev/null +++ b/server/migrations/31_transactions_to_testsuites.up.sql @@ -0,0 +1,33 @@ +BEGIN; + +ALTER TABLE + transactions RENAME TO test_suites; + +ALTER TABLE + transaction_steps RENAME TO test_suite_steps; + +ALTER TABLE + test_suite_steps RENAME COlUMN transaction_id TO test_suite_id; + +ALTER TABLE + test_suite_steps RENAME COlUMN transaction_version TO test_suite_version; + +ALTER TABLE + transaction_runs RENAME TO test_suite_runs; + +ALTER TABLE + test_suite_runs RENAME COlUMN transaction_id TO test_suite_id; + +ALTER TABLE + test_suite_runs RENAME COlUMN transaction_version TO test_suite_version; + +ALTER TABLE + transaction_run_steps RENAME TO test_suite_run_steps; + +ALTER TABLE + test_suite_run_steps RENAME COLUMN transaction_run_id TO test_suite_run_id; + +ALTER TABLE + test_suite_run_steps RENAME COLUMN transaction_run_transaction_id TO test_suite_run_test_suite_id; + +COMMIT; \ No newline at end of file diff --git a/server/model/yaml/encoding.go b/server/model/yaml/encoding.go index 4a7286fcfe..8f4a9ebb56 100644 --- a/server/model/yaml/encoding.go +++ b/server/model/yaml/encoding.go @@ -30,8 +30,8 @@ func Decode(contents []byte) (File, error) { return File{}, fmt.Errorf("cannot decode test: %w", err) } f.Spec = test - case FileTypeTransaction: - var transaction Transaction + case FileTypeTestSuite: + var transaction TestSuite err := mapstructure.Decode(f.Spec, &transaction) if err != nil { return File{}, fmt.Errorf("cannot decode transaction: %w", err) diff --git a/server/model/yaml/encoding_test.go b/server/model/yaml/encoding_test.go index 94dd881faf..796c9e380e 100644 --- a/server/model/yaml/encoding_test.go +++ b/server/model/yaml/encoding_test.go @@ -58,11 +58,11 @@ func TestDecode(t *testing.T) { }, { - name: "Transaction", - yaml: readFile("./testdata/transaction.yaml"), + name: "TestSuite", + yaml: readFile("./testdata/test-suite.yaml"), file: yaml.File{ - Type: yaml.FileTypeTransaction, - Spec: yaml.Transaction{ + Type: yaml.FileTypeTestSuite, + Spec: yaml.TestSuite{ ID: "ZsoMdf44R", Name: "Get example", Steps: []string{ @@ -72,9 +72,9 @@ func TestDecode(t *testing.T) { }, }, testSpecFn: func(t *testing.T, expected, actual yaml.File) { - test, err := actual.Transaction() + test, err := actual.TestSuite() require.NoError(t, err) - assert.Equal(t, expected.Spec.(yaml.Transaction), test) + assert.Equal(t, expected.Spec.(yaml.TestSuite), test) }, }, } diff --git a/server/model/yaml/file.go b/server/model/yaml/file.go index fac856bb59..e75946b5e5 100644 --- a/server/model/yaml/file.go +++ b/server/model/yaml/file.go @@ -14,7 +14,7 @@ func (ft FileType) String() string { const ( FileTypeTest FileType = "Test" - FileTypeTransaction FileType = "Transaction" + FileTypeTestSuite FileType = "TestSuite" FileTypeEnvironment FileType = "Environment" FileTypeDataStore FileType = "DataStore" FileTypeConfig FileType = "Config" @@ -40,8 +40,8 @@ func (f File) Validate() error { return err } return test.Validate() - case FileTypeTransaction: - transaction, err := f.Transaction() + case FileTypeTestSuite: + transaction, err := f.TestSuite() if err != nil { return err } @@ -63,14 +63,14 @@ func (f File) Test() (Test, error) { return test, nil } -func (f File) Transaction() (Transaction, error) { - if f.Type != FileTypeTransaction { - return Transaction{}, fmt.Errorf("file is not a transaction") +func (f File) TestSuite() (TestSuite, error) { + if f.Type != FileTypeTestSuite { + return TestSuite{}, fmt.Errorf("file is not a testsuite") } - transaction, ok := f.Spec.(Transaction) + transaction, ok := f.Spec.(TestSuite) if !ok { - return Transaction{}, fmt.Errorf("file spec cannot be casted to a transaction") + return TestSuite{}, fmt.Errorf("file spec cannot be casted to a testsuite") } return transaction, nil diff --git a/server/model/yaml/testdata/transaction.yaml b/server/model/yaml/testdata/test-suite.yaml similarity index 80% rename from server/model/yaml/testdata/transaction.yaml rename to server/model/yaml/testdata/test-suite.yaml index f2d2f393d4..7d7683d4a6 100644 --- a/server/model/yaml/testdata/transaction.yaml +++ b/server/model/yaml/testdata/test-suite.yaml @@ -1,4 +1,4 @@ -type: Transaction +type: TestSuite spec: id: ZsoMdf44R name: Get example diff --git a/server/model/yaml/transaction.go b/server/model/yaml/transaction.go index ec005cc8c3..a53387d24d 100644 --- a/server/model/yaml/transaction.go +++ b/server/model/yaml/transaction.go @@ -5,10 +5,10 @@ import ( dc "github.com/fluidtruck/deepcopy" "github.com/kubeshop/tracetest/server/pkg/id" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" ) -type Transaction struct { +type TestSuite struct { ID string `mapstructure:"id"` Name string `mapstructure:"name"` Description string `mapstructure:"description" yaml:",omitempty"` @@ -16,8 +16,8 @@ type Transaction struct { Steps []string `mapstructure:"steps"` } -func (t Transaction) Model() transaction.Transaction { - mt := transaction.Transaction{} +func (t TestSuite) Model() testsuite.TestSuite { + mt := testsuite.TestSuite{} dc.DeepCopy(t, &mt) mt.StepIDs = make([]id.ID, 0, len(t.Steps)) for _, stepID := range t.Steps { @@ -27,9 +27,9 @@ func (t Transaction) Model() transaction.Transaction { return mt } -func (t Transaction) Validate() error { +func (t TestSuite) Validate() error { if t.Name == "" { - return fmt.Errorf("transaction name cannot be empty") + return fmt.Errorf("suite name cannot be empty") } return nil diff --git a/server/openapi/api.go b/server/openapi/api.go index a13f97e59b..56a9fb4f02 100644 --- a/server/openapi/api.go +++ b/server/openapi/api.go @@ -19,7 +19,7 @@ import ( // pass the data to a ApiApiServicer to perform the required actions, then write the service results to the http response. type ApiApiRouter interface { DeleteTestRun(http.ResponseWriter, *http.Request) - DeleteTransactionRun(http.ResponseWriter, *http.Request) + DeleteTestSuiteRun(http.ResponseWriter, *http.Request) DryRunAssertion(http.ResponseWriter, *http.Request) ExportTestRun(http.ResponseWriter, *http.Request) ExpressionResolve(http.ResponseWriter, *http.Request) @@ -30,15 +30,15 @@ type ApiApiRouter interface { GetTestRunEvents(http.ResponseWriter, *http.Request) GetTestRuns(http.ResponseWriter, *http.Request) GetTestSpecs(http.ResponseWriter, *http.Request) + GetTestSuiteRun(http.ResponseWriter, *http.Request) + GetTestSuiteRuns(http.ResponseWriter, *http.Request) + GetTestSuiteVersion(http.ResponseWriter, *http.Request) GetTestVersion(http.ResponseWriter, *http.Request) - GetTransactionRun(http.ResponseWriter, *http.Request) - GetTransactionRuns(http.ResponseWriter, *http.Request) - GetTransactionVersion(http.ResponseWriter, *http.Request) GetVersion(http.ResponseWriter, *http.Request) ImportTestRun(http.ResponseWriter, *http.Request) RerunTestRun(http.ResponseWriter, *http.Request) RunTest(http.ResponseWriter, *http.Request) - RunTransaction(http.ResponseWriter, *http.Request) + RunTestSuite(http.ResponseWriter, *http.Request) StopTestRun(http.ResponseWriter, *http.Request) TestConnection(http.ResponseWriter, *http.Request) } @@ -50,22 +50,22 @@ type ResourceApiApiRouter interface { CreateDemo(http.ResponseWriter, *http.Request) CreateLinter(http.ResponseWriter, *http.Request) CreateTest(http.ResponseWriter, *http.Request) - CreateTransaction(http.ResponseWriter, *http.Request) + CreateTestSuite(http.ResponseWriter, *http.Request) CreateVariableSet(http.ResponseWriter, *http.Request) DeleteDataStore(http.ResponseWriter, *http.Request) DeleteDemo(http.ResponseWriter, *http.Request) DeleteLinter(http.ResponseWriter, *http.Request) DeleteTest(http.ResponseWriter, *http.Request) - DeleteTransaction(http.ResponseWriter, *http.Request) + DeleteTestSuite(http.ResponseWriter, *http.Request) DeleteVariableSet(http.ResponseWriter, *http.Request) GetConfiguration(http.ResponseWriter, *http.Request) GetDataStore(http.ResponseWriter, *http.Request) GetDemo(http.ResponseWriter, *http.Request) GetLinter(http.ResponseWriter, *http.Request) GetPollingProfile(http.ResponseWriter, *http.Request) + GetTestSuite(http.ResponseWriter, *http.Request) + GetTestSuites(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) @@ -80,7 +80,7 @@ type ResourceApiApiRouter interface { UpdateLinter(http.ResponseWriter, *http.Request) UpdatePollingProfile(http.ResponseWriter, *http.Request) UpdateTest(http.ResponseWriter, *http.Request) - UpdateTransaction(http.ResponseWriter, *http.Request) + UpdateTestSuite(http.ResponseWriter, *http.Request) UpdateVariableSet(http.ResponseWriter, *http.Request) } @@ -90,7 +90,7 @@ type ResourceApiApiRouter interface { // and updated with the logic required for the API. type ApiApiServicer interface { DeleteTestRun(context.Context, string, int32) (ImplResponse, error) - DeleteTransactionRun(context.Context, string, int32) (ImplResponse, error) + DeleteTestSuiteRun(context.Context, string, int32) (ImplResponse, error) DryRunAssertion(context.Context, string, int32, TestSpecs) (ImplResponse, error) ExportTestRun(context.Context, string, int32) (ImplResponse, error) ExpressionResolve(context.Context, ResolveRequestInfo) (ImplResponse, error) @@ -101,15 +101,15 @@ type ApiApiServicer interface { GetTestRunEvents(context.Context, string, int32) (ImplResponse, error) GetTestRuns(context.Context, string, int32, int32) (ImplResponse, error) GetTestSpecs(context.Context, string) (ImplResponse, error) + GetTestSuiteRun(context.Context, string, int32) (ImplResponse, error) + GetTestSuiteRuns(context.Context, string, int32, int32) (ImplResponse, error) + GetTestSuiteVersion(context.Context, string, int32) (ImplResponse, error) GetTestVersion(context.Context, string, int32) (ImplResponse, error) - GetTransactionRun(context.Context, string, int32) (ImplResponse, error) - GetTransactionRuns(context.Context, string, int32, int32) (ImplResponse, error) - GetTransactionVersion(context.Context, string, int32) (ImplResponse, error) GetVersion(context.Context) (ImplResponse, error) ImportTestRun(context.Context, ExportedTestInformation) (ImplResponse, error) RerunTestRun(context.Context, string, int32) (ImplResponse, error) RunTest(context.Context, string, RunInformation) (ImplResponse, error) - RunTransaction(context.Context, string, RunInformation) (ImplResponse, error) + RunTestSuite(context.Context, string, RunInformation) (ImplResponse, error) StopTestRun(context.Context, string, int32) (ImplResponse, error) TestConnection(context.Context, DataStore) (ImplResponse, error) } @@ -122,22 +122,22 @@ type ResourceApiApiServicer interface { CreateDemo(context.Context, Demo) (ImplResponse, error) CreateLinter(context.Context, LinterResource) (ImplResponse, error) CreateTest(context.Context, Test) (ImplResponse, error) - CreateTransaction(context.Context, TransactionResource) (ImplResponse, error) + CreateTestSuite(context.Context, TestSuiteResource) (ImplResponse, error) CreateVariableSet(context.Context, VariableSetResource) (ImplResponse, error) DeleteDataStore(context.Context, string) (ImplResponse, error) DeleteDemo(context.Context, string) (ImplResponse, error) DeleteLinter(context.Context, string) (ImplResponse, error) DeleteTest(context.Context, string) (ImplResponse, error) - DeleteTransaction(context.Context, string) (ImplResponse, error) + DeleteTestSuite(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) GetLinter(context.Context, string) (ImplResponse, error) GetPollingProfile(context.Context, string) (ImplResponse, error) + GetTestSuite(context.Context, string) (ImplResponse, error) + GetTestSuites(context.Context, int32, int32, string, string, 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) @@ -152,6 +152,6 @@ type ResourceApiApiServicer interface { 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) + UpdateTestSuite(context.Context, string, TestSuiteResource) (ImplResponse, error) UpdateVariableSet(context.Context, string, VariableSetResource) (ImplResponse, error) } diff --git a/server/openapi/api_api.go b/server/openapi/api_api.go index abce5fc084..2cf6227871 100644 --- a/server/openapi/api_api.go +++ b/server/openapi/api_api.go @@ -57,10 +57,10 @@ func (c *ApiApiController) Routes() Routes { c.DeleteTestRun, }, { - "DeleteTransactionRun", + "DeleteTestSuiteRun", strings.ToUpper("Delete"), - "/api/transactions/{transactionId}/run/{runId}", - c.DeleteTransactionRun, + "/api/testsuites/{testSuiteId}/run/{runId}", + c.DeleteTestSuiteRun, }, { "DryRunAssertion", @@ -123,28 +123,28 @@ func (c *ApiApiController) Routes() Routes { c.GetTestSpecs, }, { - "GetTestVersion", + "GetTestSuiteRun", strings.ToUpper("Get"), - "/api/tests/{testId}/version/{version}", - c.GetTestVersion, + "/api/testsuites/{testSuiteId}/run/{runId}", + c.GetTestSuiteRun, }, { - "GetTransactionRun", + "GetTestSuiteRuns", strings.ToUpper("Get"), - "/api/transactions/{transactionId}/run/{runId}", - c.GetTransactionRun, + "/api/testsuites/{testSuiteId}/run", + c.GetTestSuiteRuns, }, { - "GetTransactionRuns", + "GetTestSuiteVersion", strings.ToUpper("Get"), - "/api/transactions/{transactionId}/run", - c.GetTransactionRuns, + "/api/testsuites/{testSuiteId}/version/{version}", + c.GetTestSuiteVersion, }, { - "GetTransactionVersion", + "GetTestVersion", strings.ToUpper("Get"), - "/api/transactions/{transactionId}/version/{version}", - c.GetTransactionVersion, + "/api/tests/{testId}/version/{version}", + c.GetTestVersion, }, { "GetVersion", @@ -171,10 +171,10 @@ func (c *ApiApiController) Routes() Routes { c.RunTest, }, { - "RunTransaction", + "RunTestSuite", strings.ToUpper("Post"), - "/api/transactions/{transactionId}/run", - c.RunTransaction, + "/api/testsuites/{testSuiteId}/run", + c.RunTestSuite, }, { "StopTestRun", @@ -213,10 +213,10 @@ func (c *ApiApiController) DeleteTestRun(w http.ResponseWriter, r *http.Request) } -// DeleteTransactionRun - Delete a specific run from a particular transaction -func (c *ApiApiController) DeleteTransactionRun(w http.ResponseWriter, r *http.Request) { +// DeleteTestSuiteRun - Delete a specific run from a particular TestSuite +func (c *ApiApiController) DeleteTestSuiteRun(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - transactionIdParam := params["transactionId"] + testSuiteIdParam := params["testSuiteId"] runIdParam, err := parseInt32Parameter(params["runId"], true) if err != nil { @@ -224,7 +224,7 @@ func (c *ApiApiController) DeleteTransactionRun(w http.ResponseWriter, r *http.R return } - result, err := c.service.DeleteTransactionRun(r.Context(), transactionIdParam, runIdParam) + result, err := c.service.DeleteTestSuiteRun(r.Context(), testSuiteIdParam, runIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -474,18 +474,18 @@ func (c *ApiApiController) GetTestSpecs(w http.ResponseWriter, r *http.Request) } -// GetTestVersion - get a test specific version -func (c *ApiApiController) GetTestVersion(w http.ResponseWriter, r *http.Request) { +// GetTestSuiteRun - Get a specific run from a particular TestSuite +func (c *ApiApiController) GetTestSuiteRun(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - testIdParam := params["testId"] + testSuiteIdParam := params["testSuiteId"] - versionParam, err := parseInt32Parameter(params["version"], true) + runIdParam, err := parseInt32Parameter(params["runId"], true) if err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - result, err := c.service.GetTestVersion(r.Context(), testIdParam, versionParam) + result, err := c.service.GetTestSuiteRun(r.Context(), testSuiteIdParam, runIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -496,18 +496,23 @@ func (c *ApiApiController) GetTestVersion(w http.ResponseWriter, r *http.Request } -// GetTransactionRun - Get a specific run from a particular transaction -func (c *ApiApiController) GetTransactionRun(w http.ResponseWriter, r *http.Request) { +// GetTestSuiteRuns - Get all runs from a particular TestSuite +func (c *ApiApiController) GetTestSuiteRuns(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - transactionIdParam := params["transactionId"] + query := r.URL.Query() + testSuiteIdParam := params["testSuiteId"] - runIdParam, err := parseInt32Parameter(params["runId"], true) + takeParam, err := parseInt32Parameter(query.Get("take"), false) if err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - - result, err := c.service.GetTransactionRun(r.Context(), transactionIdParam, runIdParam) + skipParam, err := parseInt32Parameter(query.Get("skip"), false) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + result, err := c.service.GetTestSuiteRuns(r.Context(), testSuiteIdParam, takeParam, skipParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -518,23 +523,18 @@ func (c *ApiApiController) GetTransactionRun(w http.ResponseWriter, r *http.Requ } -// GetTransactionRuns - Get all runs from a particular transaction -func (c *ApiApiController) GetTransactionRuns(w http.ResponseWriter, r *http.Request) { +// GetTestSuiteVersion - get a TestSuite specific version +func (c *ApiApiController) GetTestSuiteVersion(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - query := r.URL.Query() - transactionIdParam := params["transactionId"] + testSuiteIdParam := params["testSuiteId"] - takeParam, err := parseInt32Parameter(query.Get("take"), false) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return - } - skipParam, err := parseInt32Parameter(query.Get("skip"), false) + versionParam, err := parseInt32Parameter(params["version"], true) if err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - result, err := c.service.GetTransactionRuns(r.Context(), transactionIdParam, takeParam, skipParam) + + result, err := c.service.GetTestSuiteVersion(r.Context(), testSuiteIdParam, versionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -545,10 +545,10 @@ func (c *ApiApiController) GetTransactionRuns(w http.ResponseWriter, r *http.Req } -// GetTransactionVersion - get a transaction specific version -func (c *ApiApiController) GetTransactionVersion(w http.ResponseWriter, r *http.Request) { +// GetTestVersion - get a test specific version +func (c *ApiApiController) GetTestVersion(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - transactionIdParam := params["transactionId"] + testIdParam := params["testId"] versionParam, err := parseInt32Parameter(params["version"], true) if err != nil { @@ -556,7 +556,7 @@ func (c *ApiApiController) GetTransactionVersion(w http.ResponseWriter, r *http. return } - result, err := c.service.GetTransactionVersion(r.Context(), transactionIdParam, versionParam) + result, err := c.service.GetTestVersion(r.Context(), testIdParam, versionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -653,10 +653,10 @@ func (c *ApiApiController) RunTest(w http.ResponseWriter, r *http.Request) { } -// RunTransaction - run transaction -func (c *ApiApiController) RunTransaction(w http.ResponseWriter, r *http.Request) { +// RunTestSuite - run TestSuite +func (c *ApiApiController) RunTestSuite(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - transactionIdParam := params["transactionId"] + testSuiteIdParam := params["testSuiteId"] runInformationParam := RunInformation{} d := json.NewDecoder(r.Body) @@ -669,7 +669,7 @@ func (c *ApiApiController) RunTransaction(w http.ResponseWriter, r *http.Request c.errorHandler(w, r, err, nil) return } - result, err := c.service.RunTransaction(r.Context(), transactionIdParam, runInformationParam) + result, err := c.service.RunTestSuite(r.Context(), testSuiteIdParam, runInformationParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/server/openapi/api_resource_api.go b/server/openapi/api_resource_api.go index 77d27e75a7..181f2e7641 100644 --- a/server/openapi/api_resource_api.go +++ b/server/openapi/api_resource_api.go @@ -69,10 +69,10 @@ func (c *ResourceApiApiController) Routes() Routes { c.CreateTest, }, { - "CreateTransaction", + "CreateTestSuite", strings.ToUpper("Post"), - "/api/transactions", - c.CreateTransaction, + "/api/testsuites", + c.CreateTestSuite, }, { "CreateVariableSet", @@ -105,10 +105,10 @@ func (c *ResourceApiApiController) Routes() Routes { c.DeleteTest, }, { - "DeleteTransaction", + "DeleteTestSuite", strings.ToUpper("Delete"), - "/api/transactions/{transactionId}", - c.DeleteTransaction, + "/api/testsuites/{testSuiteId}", + c.DeleteTestSuite, }, { "DeleteVariableSet", @@ -147,22 +147,22 @@ func (c *ResourceApiApiController) Routes() Routes { c.GetPollingProfile, }, { - "GetTests", + "GetTestSuite", strings.ToUpper("Get"), - "/api/tests", - c.GetTests, + "/api/testsuites/{testSuiteId}", + c.GetTestSuite, }, { - "GetTransaction", + "GetTestSuites", strings.ToUpper("Get"), - "/api/transactions/{transactionId}", - c.GetTransaction, + "/api/testsuites", + c.GetTestSuites, }, { - "GetTransactions", + "GetTests", strings.ToUpper("Get"), - "/api/transactions", - c.GetTransactions, + "/api/tests", + c.GetTests, }, { "GetVariableSet", @@ -249,10 +249,10 @@ func (c *ResourceApiApiController) Routes() Routes { c.UpdateTest, }, { - "UpdateTransaction", + "UpdateTestSuite", strings.ToUpper("Put"), - "/api/transactions/{transactionId}", - c.UpdateTransaction, + "/api/testsuites/{testSuiteId}", + c.UpdateTestSuite, }, { "UpdateVariableSet", @@ -335,20 +335,20 @@ func (c *ResourceApiApiController) CreateTest(w http.ResponseWriter, r *http.Req } -// CreateTransaction - Create new transaction -func (c *ResourceApiApiController) CreateTransaction(w http.ResponseWriter, r *http.Request) { - transactionResourceParam := TransactionResource{} +// CreateTestSuite - Create new TestSuite +func (c *ResourceApiApiController) CreateTestSuite(w http.ResponseWriter, r *http.Request) { + testSuiteResourceParam := TestSuiteResource{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() - if err := d.Decode(&transactionResourceParam); err != nil { + if err := d.Decode(&testSuiteResourceParam); err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - if err := AssertTransactionResourceRequired(transactionResourceParam); err != nil { + if err := AssertTestSuiteResourceRequired(testSuiteResourceParam); err != nil { c.errorHandler(w, r, err, nil) return } - result, err := c.service.CreateTransaction(r.Context(), transactionResourceParam) + result, err := c.service.CreateTestSuite(r.Context(), testSuiteResourceParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -359,7 +359,7 @@ func (c *ResourceApiApiController) CreateTransaction(w http.ResponseWriter, r *h } -// CreateVariableSet - Create an VariableSet +// CreateVariableSet - Create a VariableSet func (c *ResourceApiApiController) CreateVariableSet(w http.ResponseWriter, r *http.Request) { variableSetResourceParam := VariableSetResource{} d := json.NewDecoder(r.Body) @@ -447,12 +447,12 @@ func (c *ResourceApiApiController) DeleteTest(w http.ResponseWriter, r *http.Req } -// DeleteTransaction - delete a transaction -func (c *ResourceApiApiController) DeleteTransaction(w http.ResponseWriter, r *http.Request) { +// DeleteTestSuite - delete a TestSuite +func (c *ResourceApiApiController) DeleteTestSuite(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - transactionIdParam := params["transactionId"] + testSuiteIdParam := params["testSuiteId"] - result, err := c.service.DeleteTransaction(r.Context(), transactionIdParam) + result, err := c.service.DeleteTestSuite(r.Context(), testSuiteIdParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -463,7 +463,7 @@ func (c *ResourceApiApiController) DeleteTransaction(w http.ResponseWriter, r *h } -// DeleteVariableSet - Delete an VariableSet +// DeleteVariableSet - Delete an variable set func (c *ResourceApiApiController) DeleteVariableSet(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) variableSetIdParam := params["variableSetId"] @@ -559,8 +559,24 @@ func (c *ResourceApiApiController) GetPollingProfile(w http.ResponseWriter, r *h } -// GetTests - Get tests -func (c *ResourceApiApiController) GetTests(w http.ResponseWriter, r *http.Request) { +// GetTestSuite - get TestSuite +func (c *ResourceApiApiController) GetTestSuite(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + testSuiteIdParam := params["testSuiteId"] + + result, err := c.service.GetTestSuite(r.Context(), testSuiteIdParam) + // 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) + +} + +// GetTestSuites - Get testsuites +func (c *ResourceApiApiController) GetTestSuites(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() takeParam, err := parseInt32Parameter(query.Get("take"), false) if err != nil { @@ -575,23 +591,7 @@ func (c *ResourceApiApiController) GetTests(w http.ResponseWriter, r *http.Reque queryParam := query.Get("query") sortByParam := query.Get("sortBy") sortDirectionParam := query.Get("sortDirection") - result, err := c.service.GetTests(r.Context(), takeParam, skipParam, queryParam, sortByParam, sortDirectionParam) - // 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) - -} - -// GetTransaction - get transaction -func (c *ResourceApiApiController) GetTransaction(w http.ResponseWriter, r *http.Request) { - params := mux.Vars(r) - transactionIdParam := params["transactionId"] - - result, err := c.service.GetTransaction(r.Context(), transactionIdParam) + result, err := c.service.GetTestSuites(r.Context(), takeParam, skipParam, queryParam, sortByParam, sortDirectionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -602,8 +602,8 @@ func (c *ResourceApiApiController) GetTransaction(w http.ResponseWriter, r *http } -// GetTransactions - Get transactions -func (c *ResourceApiApiController) GetTransactions(w http.ResponseWriter, r *http.Request) { +// GetTests - Get tests +func (c *ResourceApiApiController) GetTests(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() takeParam, err := parseInt32Parameter(query.Get("take"), false) if err != nil { @@ -618,7 +618,7 @@ func (c *ResourceApiApiController) GetTransactions(w http.ResponseWriter, r *htt queryParam := query.Get("query") sortByParam := query.Get("sortBy") sortDirectionParam := query.Get("sortDirection") - result, err := c.service.GetTransactions(r.Context(), takeParam, skipParam, queryParam, sortByParam, sortDirectionParam) + result, err := c.service.GetTests(r.Context(), takeParam, skipParam, queryParam, sortByParam, sortDirectionParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -775,7 +775,7 @@ func (c *ResourceApiApiController) ListPollingProfile(w http.ResponseWriter, r * } -// ListVariableSets - List variableSets +// ListVariableSets - List VariableSets func (c *ResourceApiApiController) ListVariableSets(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() takeParam, err := parseInt32Parameter(query.Get("take"), false) @@ -979,23 +979,23 @@ func (c *ResourceApiApiController) UpdateTest(w http.ResponseWriter, r *http.Req } -// UpdateTransaction - update transaction -func (c *ResourceApiApiController) UpdateTransaction(w http.ResponseWriter, r *http.Request) { +// UpdateTestSuite - update TestSuite +func (c *ResourceApiApiController) UpdateTestSuite(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) - transactionIdParam := params["transactionId"] + testSuiteIdParam := params["testSuiteId"] - transactionResourceParam := TransactionResource{} + testSuiteResourceParam := TestSuiteResource{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() - if err := d.Decode(&transactionResourceParam); err != nil { + if err := d.Decode(&testSuiteResourceParam); err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - if err := AssertTransactionResourceRequired(transactionResourceParam); err != nil { + if err := AssertTestSuiteResourceRequired(testSuiteResourceParam); err != nil { c.errorHandler(w, r, err, nil) return } - result, err := c.service.UpdateTransaction(r.Context(), transactionIdParam, transactionResourceParam) + result, err := c.service.UpdateTestSuite(r.Context(), testSuiteIdParam, testSuiteResourceParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -1006,7 +1006,7 @@ func (c *ResourceApiApiController) UpdateTransaction(w http.ResponseWriter, r *h } -// UpdateVariableSet - Update an VariableSet +// UpdateVariableSet - Update a VariableSet func (c *ResourceApiApiController) UpdateVariableSet(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) variableSetIdParam := params["variableSetId"] diff --git a/server/openapi/api_resource_api_service.go b/server/openapi/api_resource_api_service.go index fcc259ce29..b0764d8152 100644 --- a/server/openapi/api_resource_api_service.go +++ b/server/openapi/api_resource_api_service.go @@ -68,13 +68,13 @@ func (s *ResourceApiApiService) CreateTest(ctx context.Context, test Test) (Impl return Response(http.StatusNotImplemented, nil), errors.New("CreateTest method not implemented") } -// CreateTransaction - Create new transaction -func (s *ResourceApiApiService) CreateTransaction(ctx context.Context, transactionResource TransactionResource) (ImplResponse, error) { - // TODO - update CreateTransaction with the required logic for this service method. +// CreateTestSuite - Create new TestSuite +func (s *ResourceApiApiService) CreateTestSuite(ctx context.Context, testSuiteResource TestSuiteResource) (ImplResponse, error) { + // TODO - update CreateTestSuite 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, TransactionResource{}) or use other options such as http.Ok ... - //return Response(201, TransactionResource{}), nil + //TODO: Uncomment the next line to return response Response(201, TestSuiteResource{}) or use other options such as http.Ok ... + //return Response(201, TestSuiteResource{}), nil //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... //return Response(400, nil),nil @@ -82,10 +82,10 @@ func (s *ResourceApiApiService) CreateTransaction(ctx context.Context, transacti //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("CreateTransaction method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("CreateTestSuite method not implemented") } -// CreateVariableSet - Create an VariableSet +// CreateVariableSet - Create a 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. @@ -161,9 +161,9 @@ func (s *ResourceApiApiService) DeleteTest(ctx context.Context, testId string) ( return Response(http.StatusNotImplemented, nil), errors.New("DeleteTest method not implemented") } -// DeleteTransaction - delete a transaction -func (s *ResourceApiApiService) DeleteTransaction(ctx context.Context, transactionId string) (ImplResponse, error) { - // TODO - update DeleteTransaction with the required logic for this service method. +// DeleteTestSuite - delete a TestSuite +func (s *ResourceApiApiService) DeleteTestSuite(ctx context.Context, testSuiteId string) (ImplResponse, error) { + // TODO - update DeleteTestSuite 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 ... @@ -175,10 +175,10 @@ func (s *ResourceApiApiService) DeleteTransaction(ctx context.Context, transacti //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("DeleteTransaction method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("DeleteTestSuite method not implemented") } -// DeleteVariableSet - Delete an VariableSet +// DeleteVariableSet - Delete an variable set 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. @@ -280,47 +280,47 @@ func (s *ResourceApiApiService) GetPollingProfile(ctx context.Context, pollingPr return Response(http.StatusNotImplemented, nil), errors.New("GetPollingProfile method not implemented") } -// GetTests - Get tests -func (s *ResourceApiApiService) GetTests(ctx context.Context, take int32, skip int32, query string, sortBy string, sortDirection string) (ImplResponse, error) { - // TODO - update GetTests with the required logic for this service method. +// GetTestSuite - get TestSuite +func (s *ResourceApiApiService) GetTestSuite(ctx context.Context, testSuiteId string) (ImplResponse, error) { + // TODO - update GetTestSuite 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, TestResourceList{}) or use other options such as http.Ok ... - //return Response(200, TestResourceList{}), nil + //TODO: Uncomment the next line to return response Response(200, TestSuiteResource{}) or use other options such as http.Ok ... + //return Response(200, TestSuiteResource{}), 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("GetTests method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("GetTestSuite method not implemented") } -// GetTransaction - get transaction -func (s *ResourceApiApiService) GetTransaction(ctx context.Context, transactionId string) (ImplResponse, error) { - // TODO - update GetTransaction with the required logic for this service method. +// GetTestSuites - Get testsuites +func (s *ResourceApiApiService) GetTestSuites(ctx context.Context, take int32, skip int32, query string, sortBy string, sortDirection string) (ImplResponse, error) { + // TODO - update GetTestSuites 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, TransactionResource{}) or use other options such as http.Ok ... - //return Response(200, TransactionResource{}), nil + //TODO: Uncomment the next line to return response Response(200, TestSuiteResourceList{}) or use other options such as http.Ok ... + //return Response(200, TestSuiteResourceList{}), 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(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("GetTransaction method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("GetTestSuites method not implemented") } -// GetTransactions - Get transactions -func (s *ResourceApiApiService) GetTransactions(ctx context.Context, take int32, skip int32, query string, sortBy string, sortDirection string) (ImplResponse, error) { - // TODO - update GetTransactions with the required logic for this service method. +// GetTests - Get tests +func (s *ResourceApiApiService) GetTests(ctx context.Context, take int32, skip int32, query string, sortBy string, sortDirection string) (ImplResponse, error) { + // TODO - update GetTests 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, TransactionResourceList{}) or use other options such as http.Ok ... - //return Response(200, TransactionResourceList{}), nil + //TODO: Uncomment the next line to return response Response(200, TestResourceList{}) or use other options such as http.Ok ... + //return Response(200, TestResourceList{}), nil //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... //return Response(400, nil),nil @@ -328,7 +328,7 @@ func (s *ResourceApiApiService) GetTransactions(ctx context.Context, take int32, //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("GetTransactions method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("GetTests method not implemented") } // GetVariableSet - Get a specific VariableSet @@ -424,7 +424,7 @@ func (s *ResourceApiApiService) ListPollingProfile(ctx context.Context, take int return Response(http.StatusNotImplemented, nil), errors.New("ListPollingProfile method not implemented") } -// ListVariableSets - List variableSets +// 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. @@ -560,13 +560,13 @@ func (s *ResourceApiApiService) UpdateTest(ctx context.Context, testId string, t return Response(http.StatusNotImplemented, nil), errors.New("UpdateTest method not implemented") } -// UpdateTransaction - update transaction -func (s *ResourceApiApiService) UpdateTransaction(ctx context.Context, transactionId string, transactionResource TransactionResource) (ImplResponse, error) { - // TODO - update UpdateTransaction with the required logic for this service method. +// UpdateTestSuite - update TestSuite +func (s *ResourceApiApiService) UpdateTestSuite(ctx context.Context, testSuiteId string, testSuiteResource TestSuiteResource) (ImplResponse, error) { + // TODO - update UpdateTestSuite 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, TransactionResource{}) or use other options such as http.Ok ... - //return Response(200, TransactionResource{}), nil + //TODO: Uncomment the next line to return response Response(200, TestSuiteResource{}) or use other options such as http.Ok ... + //return Response(200, TestSuiteResource{}), nil //TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... //return Response(400, nil),nil @@ -577,10 +577,10 @@ func (s *ResourceApiApiService) UpdateTransaction(ctx context.Context, transacti //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("UpdateTransaction method not implemented") + return Response(http.StatusNotImplemented, nil), errors.New("UpdateTestSuite method not implemented") } -// UpdateVariableSet - Update an VariableSet +// UpdateVariableSet - Update a 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. diff --git a/server/openapi/model_get_test_suites_200_response.go b/server/openapi/model_get_test_suites_200_response.go new file mode 100644 index 0000000000..450c6a3341 --- /dev/null +++ b/server/openapi/model_get_test_suites_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 GetTestSuites200Response struct { + Count int32 `json:"count,omitempty"` + + Items []TestSuiteResource `json:"items,omitempty"` +} + +// AssertGetTestSuites200ResponseRequired checks if the required fields are not zero-ed +func AssertGetTestSuites200ResponseRequired(obj GetTestSuites200Response) error { + for _, el := range obj.Items { + if err := AssertTestSuiteResourceRequired(el); err != nil { + return err + } + } + return nil +} + +// AssertRecurseGetTestSuites200ResponseRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of GetTestSuites200Response (e.g. [][]GetTestSuites200Response), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseGetTestSuites200ResponseRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aGetTestSuites200Response, ok := obj.(GetTestSuites200Response) + if !ok { + return ErrTypeAssertionError + } + return AssertGetTestSuites200ResponseRequired(aGetTestSuites200Response) + }) +} diff --git a/server/openapi/model_get_transactions_200_response.go b/server/openapi/model_get_transactions_200_response.go deleted file mode 100644 index 3967df9b4d..0000000000 --- a/server/openapi/model_get_transactions_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 GetTransactions200Response struct { - Count int32 `json:"count,omitempty"` - - Items []TransactionResource `json:"items,omitempty"` -} - -// AssertGetTransactions200ResponseRequired checks if the required fields are not zero-ed -func AssertGetTransactions200ResponseRequired(obj GetTransactions200Response) error { - for _, el := range obj.Items { - if err := AssertTransactionResourceRequired(el); err != nil { - return err - } - } - return nil -} - -// AssertRecurseGetTransactions200ResponseRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of GetTransactions200Response (e.g. [][]GetTransactions200Response), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseGetTransactions200ResponseRequired(objSlice interface{}) error { - return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aGetTransactions200Response, ok := obj.(GetTransactions200Response) - if !ok { - return ErrTypeAssertionError - } - return AssertGetTransactions200ResponseRequired(aGetTransactions200Response) - }) -} diff --git a/server/openapi/model_test_run.go b/server/openapi/model_test_run.go index ce6bef4dd6..9dd6b81ebc 100644 --- a/server/openapi/model_test_run.go +++ b/server/openapi/model_test_run.go @@ -32,7 +32,7 @@ type TestRun struct { // time in seconds it took for the test to complete, either success or fail. If the test is still running, it will show the time up to the time of the request ExecutionTime int32 `json:"executionTime,omitempty"` - // time in milliseconds it took for the triggering transaction to complete, either success or fail. If the test is still running, it will show the time up to the time of the request + // time in milliseconds it took for the triggering testSuite to complete, either success or fail. If the test is still running, it will show the time up to the time of the request TriggerTime int32 `json:"triggerTime,omitempty"` CreatedAt time.Time `json:"createdAt,omitempty"` @@ -61,9 +61,9 @@ type TestRun struct { Metadata map[string]string `json:"metadata,omitempty"` - TransactionId string `json:"transactionId,omitempty"` + TestSuiteId string `json:"testSuiteId,omitempty"` - TransactionRunId string `json:"transactionRunId,omitempty"` + TestSuiteRunId string `json:"testSuiteRunId,omitempty"` } // AssertTestRunRequired checks if the required fields are not zero-ed diff --git a/server/openapi/model_transaction.go b/server/openapi/model_test_suite.go similarity index 58% rename from server/openapi/model_transaction.go rename to server/openapi/model_test_suite.go index c8ab5eb12e..85a9eda7a6 100644 --- a/server/openapi/model_transaction.go +++ b/server/openapi/model_test_suite.go @@ -13,7 +13,7 @@ import ( "time" ) -type Transaction struct { +type TestSuite struct { Id string `json:"id,omitempty"` Name string `json:"name,omitempty"` @@ -23,10 +23,10 @@ type Transaction struct { // version number of the test Version int32 `json:"version,omitempty"` - // list of steps of the transaction containing just each test id + // list of steps of the TestSuite containing just each test id Steps []string `json:"steps,omitempty"` - // list of steps of the transaction containing the whole test object + // list of steps of the TestSuite containing the whole test object FullSteps []Test `json:"fullSteps,omitempty"` CreatedAt time.Time `json:"createdAt,omitempty"` @@ -34,8 +34,8 @@ type Transaction struct { Summary TestSummary `json:"summary,omitempty"` } -// AssertTransactionRequired checks if the required fields are not zero-ed -func AssertTransactionRequired(obj Transaction) error { +// AssertTestSuiteRequired checks if the required fields are not zero-ed +func AssertTestSuiteRequired(obj TestSuite) error { for _, el := range obj.FullSteps { if err := AssertTestRequired(el); err != nil { return err @@ -47,14 +47,14 @@ func AssertTransactionRequired(obj Transaction) error { return nil } -// AssertRecurseTransactionRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of Transaction (e.g. [][]Transaction), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseTransactionRequired(objSlice interface{}) error { +// AssertRecurseTestSuiteRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of TestSuite (e.g. [][]TestSuite), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseTestSuiteRequired(objSlice interface{}) error { return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aTransaction, ok := obj.(Transaction) + aTestSuite, ok := obj.(TestSuite) if !ok { return ErrTypeAssertionError } - return AssertTransactionRequired(aTransaction) + return AssertTestSuiteRequired(aTestSuite) }) } diff --git a/server/openapi/model_test_suite_resource.go b/server/openapi/model_test_suite_resource.go new file mode 100644 index 0000000000..92512089d6 --- /dev/null +++ b/server/openapi/model_test_suite_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 + +// TestSuiteResource - Represents a TestSuite structured into the Resources format. +type TestSuiteResource struct { + + // Represents the type of this resource. It should always be set as 'TestSuite'. + Type string `json:"type,omitempty"` + + Spec TestSuite `json:"spec,omitempty"` +} + +// AssertTestSuiteResourceRequired checks if the required fields are not zero-ed +func AssertTestSuiteResourceRequired(obj TestSuiteResource) error { + if err := AssertTestSuiteRequired(obj.Spec); err != nil { + return err + } + return nil +} + +// AssertRecurseTestSuiteResourceRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of TestSuiteResource (e.g. [][]TestSuiteResource), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseTestSuiteResourceRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aTestSuiteResource, ok := obj.(TestSuiteResource) + if !ok { + return ErrTypeAssertionError + } + return AssertTestSuiteResourceRequired(aTestSuiteResource) + }) +} diff --git a/server/openapi/model_test_suite_resource_list.go b/server/openapi/model_test_suite_resource_list.go new file mode 100644 index 0000000000..70daf077d7 --- /dev/null +++ b/server/openapi/model_test_suite_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 TestSuiteResourceList struct { + Count int32 `json:"count,omitempty"` + + Items []TestSuiteResource `json:"items,omitempty"` +} + +// AssertTestSuiteResourceListRequired checks if the required fields are not zero-ed +func AssertTestSuiteResourceListRequired(obj TestSuiteResourceList) error { + for _, el := range obj.Items { + if err := AssertTestSuiteResourceRequired(el); err != nil { + return err + } + } + return nil +} + +// AssertRecurseTestSuiteResourceListRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of TestSuiteResourceList (e.g. [][]TestSuiteResourceList), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseTestSuiteResourceListRequired(objSlice interface{}) error { + return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { + aTestSuiteResourceList, ok := obj.(TestSuiteResourceList) + if !ok { + return ErrTypeAssertionError + } + return AssertTestSuiteResourceListRequired(aTestSuiteResourceList) + }) +} diff --git a/server/openapi/model_transaction_run.go b/server/openapi/model_test_suite_run.go similarity index 65% rename from server/openapi/model_transaction_run.go rename to server/openapi/model_test_suite_run.go index 91b818c0a8..f015a48fbc 100644 --- a/server/openapi/model_transaction_run.go +++ b/server/openapi/model_test_suite_run.go @@ -13,7 +13,7 @@ import ( "time" ) -type TransactionRun struct { +type TestSuiteRun struct { Id string `json:"id,omitempty"` Version int32 `json:"version,omitempty"` @@ -37,8 +37,8 @@ type TransactionRun struct { AllStepsRequiredGatesPassed bool `json:"allStepsRequiredGatesPassed,omitempty"` } -// AssertTransactionRunRequired checks if the required fields are not zero-ed -func AssertTransactionRunRequired(obj TransactionRun) error { +// AssertTestSuiteRunRequired checks if the required fields are not zero-ed +func AssertTestSuiteRunRequired(obj TestSuiteRun) error { for _, el := range obj.Steps { if err := AssertTestRunRequired(el); err != nil { return err @@ -50,14 +50,14 @@ func AssertTransactionRunRequired(obj TransactionRun) error { return nil } -// AssertRecurseTransactionRunRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of TransactionRun (e.g. [][]TransactionRun), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseTransactionRunRequired(objSlice interface{}) error { +// AssertRecurseTestSuiteRunRequired recursively checks if required fields are not zero-ed in a nested slice. +// Accepts only nested slice of TestSuiteRun (e.g. [][]TestSuiteRun), otherwise ErrTypeAssertionError is thrown. +func AssertRecurseTestSuiteRunRequired(objSlice interface{}) error { return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aTransactionRun, ok := obj.(TransactionRun) + aTestSuiteRun, ok := obj.(TestSuiteRun) if !ok { return ErrTypeAssertionError } - return AssertTransactionRunRequired(aTransactionRun) + return AssertTestSuiteRunRequired(aTestSuiteRun) }) } diff --git a/server/openapi/model_transaction_resource.go b/server/openapi/model_transaction_resource.go deleted file mode 100644 index a2558e6a8e..0000000000 --- a/server/openapi/model_transaction_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 - -// TransactionResource - Represents a transaction structured into the Resources format. -type TransactionResource struct { - - // Represents the type of this resource. It should always be set as 'Transaction'. - Type string `json:"type,omitempty"` - - Spec Transaction `json:"spec,omitempty"` -} - -// AssertTransactionResourceRequired checks if the required fields are not zero-ed -func AssertTransactionResourceRequired(obj TransactionResource) error { - if err := AssertTransactionRequired(obj.Spec); err != nil { - return err - } - return nil -} - -// AssertRecurseTransactionResourceRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of TransactionResource (e.g. [][]TransactionResource), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseTransactionResourceRequired(objSlice interface{}) error { - return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aTransactionResource, ok := obj.(TransactionResource) - if !ok { - return ErrTypeAssertionError - } - return AssertTransactionResourceRequired(aTransactionResource) - }) -} diff --git a/server/openapi/model_transaction_resource_list.go b/server/openapi/model_transaction_resource_list.go deleted file mode 100644 index 79d9e7452b..0000000000 --- a/server/openapi/model_transaction_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 TransactionResourceList struct { - Count int32 `json:"count,omitempty"` - - Items []TransactionResource `json:"items,omitempty"` -} - -// AssertTransactionResourceListRequired checks if the required fields are not zero-ed -func AssertTransactionResourceListRequired(obj TransactionResourceList) error { - for _, el := range obj.Items { - if err := AssertTransactionResourceRequired(el); err != nil { - return err - } - } - return nil -} - -// AssertRecurseTransactionResourceListRequired recursively checks if required fields are not zero-ed in a nested slice. -// Accepts only nested slice of TransactionResourceList (e.g. [][]TransactionResourceList), otherwise ErrTypeAssertionError is thrown. -func AssertRecurseTransactionResourceListRequired(objSlice interface{}) error { - return AssertRecurseInterfaceRequired(objSlice, func(obj interface{}) error { - aTransactionResourceList, ok := obj.(TransactionResourceList) - if !ok { - return ErrTypeAssertionError - } - return AssertTransactionResourceListRequired(aTransactionResourceList) - }) -} diff --git a/server/openapi/model_variable_set_resource.go b/server/openapi/model_variable_set_resource.go index e6965788df..83985b15d9 100644 --- a/server/openapi/model_variable_set_resource.go +++ b/server/openapi/model_variable_set_resource.go @@ -9,7 +9,7 @@ package openapi -// VariableSetResource - Represents an VariableSet structured into the Resources format. +// VariableSetResource - Represents a VariableSet structured into the Resources format. type VariableSetResource struct { // Represents the type of this resource. It should always be set as 'VariableSet'. diff --git a/server/test/mocks/run_repository_mock.go b/server/test/mocks/run_repository_mock.go index a2bed74e83..c8e453135b 100644 --- a/server/test/mocks/run_repository_mock.go +++ b/server/test/mocks/run_repository_mock.go @@ -49,7 +49,7 @@ func (m *RunRepository) GetLatestRunByTestVersion(ctx context.Context, id id.ID, return args.Get(0).(test.Run), args.Error(1) } -func (m *RunRepository) GetTransactionRunSteps(ctx context.Context, id id.ID, runID int) ([]test.Run, error) { +func (m *RunRepository) GetTestSuiteRunSteps(ctx context.Context, id id.ID, runID int) ([]test.Run, error) { args := m.Called(ctx, id, runID) return args.Get(0).([]test.Run), args.Error(1) } diff --git a/server/test/run_repository.go b/server/test/run_repository.go index 28798d3a73..41adab7e05 100644 --- a/server/test/run_repository.go +++ b/server/test/run_repository.go @@ -24,7 +24,7 @@ type RunRepository interface { GetRunByTraceID(context.Context, trace.TraceID) (Run, error) GetLatestRunByTestVersion(context.Context, id.ID, int) (Run, error) - GetTransactionRunSteps(_ context.Context, _ id.ID, runID int) ([]Run, error) + GetTestSuiteRunSteps(_ context.Context, _ id.ID, runID int) ([]Run, error) } type runRepository struct { @@ -318,7 +318,7 @@ func (r *runRepository) UpdateRun(ctx context.Context, run Run) error { func (r *runRepository) DeleteRun(ctx context.Context, run Run) error { queries := []string{ - "DELETE FROM transaction_run_steps WHERE test_run_id = $1 AND test_run_test_id = $2", + "DELETE FROM test_suite_run_steps WHERE test_run_id = $1 AND test_run_test_id = $2", "DELETE FROM test_runs WHERE id = $1 AND test_id = $2", } @@ -371,16 +371,16 @@ SELECT "metadata", "variable_set", - -- transaction run - transaction_run_steps.transaction_run_id, - transaction_run_steps.transaction_run_transaction_id, + -- test_suite run + test_suite_run_steps.test_suite_run_id, + test_suite_run_steps.test_suite_run_test_suite_id, "linter", "required_gates_result" FROM test_runs - LEFT OUTER JOIN transaction_run_steps - ON transaction_run_steps.test_run_id = test_runs.id AND transaction_run_steps.test_run_test_id = test_runs.test_id + LEFT OUTER JOIN test_suite_run_steps + ON test_suite_run_steps.test_run_id = test_runs.id AND test_suite_run_steps.test_run_test_id = test_runs.test_id ` func (r *runRepository) GetRun(ctx context.Context, testID id.ID, runID int) (Run, error) { @@ -476,8 +476,8 @@ func readRunRow(row scanner) (Run, error) { traceID, spanID string - transactionID, - transactionRunID sql.NullString + testSuiteID, + testSuiteRunID sql.NullString ) err := row.Scan( @@ -499,8 +499,8 @@ func readRunRow(row scanner) (Run, error) { &lastError, &jsonMetadata, &jsonVariableSet, - &transactionRunID, - &transactionID, + &testSuiteRunID, + &testSuiteID, &jsonLinter, &jsonGatesResult, ) @@ -590,17 +590,17 @@ func readRunRow(row scanner) (Run, error) { r.LastError = fmt.Errorf(*lastError) } - if transactionID.Valid && transactionRunID.Valid { - r.TransactionID = transactionID.String - r.TransactionRunID = transactionRunID.String + if testSuiteID.Valid && testSuiteRunID.Valid { + r.TestSuiteID = testSuiteID.String + r.TestSuiteRunID = testSuiteRunID.String } return r, nil } -func (r *runRepository) GetTransactionRunSteps(ctx context.Context, id id.ID, runID int) ([]Run, error) { +func (r *runRepository) GetTestSuiteRunSteps(ctx context.Context, id id.ID, runID int) ([]Run, error) { query := selectRunQuery + ` -WHERE transaction_run_steps.transaction_run_id = $1 AND transaction_run_steps.transaction_run_transaction_id = $2 +WHERE test_suite_run_steps.test_suite_run_id = $1 AND test_suite_run_steps.test_suite_run_test_suite_id = $2 ORDER BY test_runs.completed_at ASC ` query, params := sqlutil.Tenant(ctx, query, strconv.Itoa(runID), id) diff --git a/server/test/test_entities.go b/server/test/test_entities.go index c998054bee..c52af2a94f 100644 --- a/server/test/test_entities.go +++ b/server/test/test_entities.go @@ -128,8 +128,8 @@ type ( // transaction - TransactionID string - TransactionRunID string + TestSuiteID string + TestSuiteRunID string Linter analyzer.LinterResult RequiredGatesResult testrunner.RequiredGatesResult } diff --git a/server/test/test_repository.go b/server/test/test_repository.go index 6cfb838439..c8aae497aa 100644 --- a/server/test/test_repository.go +++ b/server/test/test_repository.go @@ -33,7 +33,7 @@ type Repository interface { Update(context.Context, Test) (Test, error) Delete(context.Context, id.ID) error - GetTransactionSteps(_ context.Context, _ id.ID, version int) ([]Test, error) + GetTestSuiteSteps(_ context.Context, _ id.ID, version int) ([]Test, error) DB() *sql.DB } @@ -203,10 +203,10 @@ func (r *repository) get(ctx context.Context, id id.ID) (Test, error) { return test, nil } -func (r *repository) GetTransactionSteps(ctx context.Context, id id.ID, version int) ([]Test, error) { +func (r *repository) GetTestSuiteSteps(ctx context.Context, id id.ID, version int) ([]Test, error) { sortQuery := `ORDER BY ts.step_number ASC` - query, params := sqlutil.Tenant(ctx, getTestSQL+testMaxVersionQuery+` INNER JOIN transaction_steps ts ON t.id = ts.test_id - WHERE ts.transaction_id = $1 AND ts.transaction_version = $2`, id, version) + query, params := sqlutil.Tenant(ctx, getTestSQL+testMaxVersionQuery+` INNER JOIN test_suite_steps ts ON t.id = ts.test_id + WHERE ts.test_suite_id = $1 AND ts.test_suite_version = $2`, id, version) stmt, err := r.db.Prepare(query + sortQuery) if err != nil { return []Test{}, fmt.Errorf("prepare 2: %w", err) @@ -493,8 +493,8 @@ func (r *repository) Delete(ctx context.Context, id id.ID) error { } queries := []string{ - "DELETE FROM transaction_run_steps WHERE test_run_test_id = $1", - "DELETE FROM transaction_steps WHERE test_id = $1", + "DELETE FROM test_suite_run_steps WHERE test_run_test_id = $1", + "DELETE FROM test_suite_steps WHERE test_id = $1", "DELETE FROM test_runs WHERE test_id = $1", "DELETE FROM tests WHERE id = $1", } diff --git a/server/test/test_repository_test.go b/server/test/test_repository_test.go index 2e67339a95..f5f1730e5d 100644 --- a/server/test/test_repository_test.go +++ b/server/test/test_repository_test.go @@ -14,7 +14,7 @@ import ( "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/test/trigger" "github.com/kubeshop/tracetest/server/testmock" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -166,7 +166,7 @@ func TestIfDeleteTestsCascadeDeletes(t *testing.T) { Outputs: test.Outputs{}, } - var transactionSample = transaction.Transaction{ + var transactionSample = testsuite.TestSuite{ ID: "a98s76de", Name: "Verify Import", Description: "check the working of the import flow", @@ -181,8 +181,8 @@ func TestIfDeleteTestsCascadeDeletes(t *testing.T) { testRepository := test.NewRepository(db) runRepository := test.NewRunRepository(db) - transactionRepository := transaction.NewRepository(db, testRepository) - transactionRunRepository := transaction.NewRunRepository(db, runRepository) + transactionRepository := testsuite.NewRepository(db, testRepository) + transactionRunRepository := testsuite.NewRunRepository(db, runRepository) _, err := testRepository.Create(context.TODO(), testSample) require.NoError(t, err) @@ -213,7 +213,7 @@ func TestIfDeleteTestsCascadeDeletes(t *testing.T) { err = testRepository.Delete(context.TODO(), testSample.ID) require.NoError(t, err) - recentTransactionRun, err := transactionRunRepository.GetTransactionRun(context.TODO(), transactionSample.ID, transactionRun.ID) + recentTransactionRun, err := transactionRunRepository.GetTestSuiteRun(context.TODO(), transactionSample.ID, transactionRun.ID) require.NoError(t, err) assert.Len(t, recentTransactionRun.Steps, 1) diff --git a/server/testdb/mock.go b/server/testdb/mock.go index 26b3d81f70..639372ad29 100644 --- a/server/testdb/mock.go +++ b/server/testdb/mock.go @@ -7,7 +7,7 @@ import ( "github.com/kubeshop/tracetest/server/pkg/id" "github.com/kubeshop/tracetest/server/pkg/maps" "github.com/kubeshop/tracetest/server/test" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/stretchr/testify/mock" "go.opentelemetry.io/otel/trace" ) @@ -126,24 +126,24 @@ func (m *MockRepository) Drop() error { return args.Error(0) } -func (m *MockRepository) CreateTransaction(_ context.Context, t transaction.Transaction) (transaction.Transaction, error) { +func (m *MockRepository) CreateTransaction(_ context.Context, t testsuite.TestSuite) (testsuite.TestSuite, error) { args := m.Called(t) - return args.Get(0).(transaction.Transaction), args.Error(1) + return args.Get(0).(testsuite.TestSuite), args.Error(1) } -func (m *MockRepository) UpdateTransaction(_ context.Context, t transaction.Transaction) (transaction.Transaction, error) { +func (m *MockRepository) UpdateTransaction(_ context.Context, t testsuite.TestSuite) (testsuite.TestSuite, error) { args := m.Called(t) - return args.Get(0).(transaction.Transaction), args.Error(1) + return args.Get(0).(testsuite.TestSuite), args.Error(1) } -func (m *MockRepository) DeleteTransaction(_ context.Context, transaction transaction.Transaction) error { +func (m *MockRepository) DeleteTransaction(_ context.Context, transaction testsuite.TestSuite) error { args := m.Called(transaction) return args.Error(1) } -func (m *MockRepository) GetLatestTransactionVersion(_ context.Context, id id.ID) (transaction.Transaction, error) { +func (m *MockRepository) GetLatestTransactionVersion(_ context.Context, id id.ID) (testsuite.TestSuite, error) { args := m.Called(id) - return args.Get(0).(transaction.Transaction), args.Error(1) + return args.Get(0).(testsuite.TestSuite), args.Error(1) } func (m *MockRepository) TransactionIDExists(_ context.Context, id id.ID) (bool, error) { @@ -151,15 +151,15 @@ func (m *MockRepository) TransactionIDExists(_ context.Context, id id.ID) (bool, return args.Bool(0), args.Error(1) } -func (m *MockRepository) GetTransactionVersion(_ context.Context, id id.ID, version int) (transaction.Transaction, error) { +func (m *MockRepository) GetTransactionVersion(_ context.Context, id id.ID, version int) (testsuite.TestSuite, error) { args := m.Called(id, version) - return args.Get(0).(transaction.Transaction), args.Error(1) + return args.Get(0).(testsuite.TestSuite), args.Error(1) } -func (m *MockRepository) GetTransactions(_ context.Context, take, skip int32, query, sortBy, sortDirection string) (model.List[transaction.Transaction], error) { +func (m *MockRepository) GetTransactions(_ context.Context, take, skip int32, query, sortBy, sortDirection string) (model.List[testsuite.TestSuite], error) { args := m.Called(take, skip, query, sortBy, sortDirection) - transactions := args.Get(0).([]transaction.Transaction) - list := model.List[transaction.Transaction]{ + transactions := args.Get(0).([]testsuite.TestSuite) + list := model.List[testsuite.TestSuite]{ Items: transactions, TotalCount: len(transactions), } @@ -167,35 +167,35 @@ func (m *MockRepository) GetTransactions(_ context.Context, take, skip int32, qu } // DeleteTransactionRun implements model.Repository -func (m *MockRepository) DeleteTransactionRun(ctx context.Context, run transaction.TransactionRun) error { +func (m *MockRepository) DeleteTransactionRun(ctx context.Context, run testsuite.TestSuite) error { args := m.Called(ctx, run) return args.Error(0) } // GetTransactionRun implements model.Repository -func (m *MockRepository) GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (transaction.TransactionRun, error) { +func (m *MockRepository) GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (testsuite.TestSuite, error) { args := m.Called(ctx, transactionID, runID) - return args.Get(0).(transaction.TransactionRun), args.Error(1) + return args.Get(0).(testsuite.TestSuite), args.Error(1) } -func (m *MockRepository) GetLatestRunByTransactionVersion(_ context.Context, transactionID id.ID, version int) (transaction.TransactionRun, error) { +func (m *MockRepository) GetLatestRunByTransactionVersion(_ context.Context, transactionID id.ID, version int) (testsuite.TestSuite, error) { args := m.Called(transactionID, version) - return args.Get(0).(transaction.TransactionRun), args.Error(1) + return args.Get(0).(testsuite.TestSuite), args.Error(1) } // GetTransactionsRuns implements model.Repository -func (m *MockRepository) GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]transaction.TransactionRun, error) { +func (m *MockRepository) GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]testsuite.TestSuite, error) { args := m.Called(ctx, transactionID, take, skip) - return args.Get(0).([]transaction.TransactionRun), args.Error(1) + return args.Get(0).([]testsuite.TestSuite), args.Error(1) } // UpdateTransactionRun implements model.Repository -func (m *MockRepository) UpdateTransactionRun(ctx context.Context, run transaction.TransactionRun) error { +func (m *MockRepository) UpdateTransactionRun(ctx context.Context, run testsuite.TestSuite) error { args := m.Called(ctx, run) return args.Error(0) } -func (m *MockRepository) CreateTransactionRun(ctx context.Context, run transaction.TransactionRun) error { +func (m *MockRepository) CreateTransactionRun(ctx context.Context, run testsuite.TestSuite) error { args := m.Called(ctx, run) return args.Error(0) } diff --git a/server/testdb/postgres.go b/server/testdb/postgres.go index 8b33f2f31b..70c128a847 100644 --- a/server/testdb/postgres.go +++ b/server/testdb/postgres.go @@ -58,10 +58,10 @@ func (p *postgresDB) ensureLatestMigration() error { func (td *postgresDB) Drop() error { return dropTables( td, - "transaction_run_steps", - "transaction_runs", - "transaction_steps", - "transactions", + "test_suite_run_steps", + "test_suite_runs", + "test_suite_steps", + "test_suites", "test_runs", "tests", "environments", diff --git a/server/testmock/database.go b/server/testmock/database.go index 33d69a593f..6c3d629920 100644 --- a/server/testmock/database.go +++ b/server/testmock/database.go @@ -175,13 +175,13 @@ func randomInt() int { func DropDatabase(db *sql.DB) error { return dropTables( db, - "transaction_run_steps", - "transaction_runs", - "transaction_steps", - "transactions", + "test_suite_run_steps", + "test_suite_runs", + "test_suite_steps", + "test_suites", "test_runs", "tests", - "environments", + "variable_sets", "data_stores", "server", "schema_migrations", diff --git a/server/transaction/main_test.go b/server/testsuite/main_test.go similarity index 89% rename from server/transaction/main_test.go rename to server/testsuite/main_test.go index 28c597549a..d602732c48 100644 --- a/server/transaction/main_test.go +++ b/server/testsuite/main_test.go @@ -1,4 +1,4 @@ -package transaction_test +package testsuite_test import ( "os" diff --git a/server/testsuite/testsuite_entities.go b/server/testsuite/testsuite_entities.go new file mode 100644 index 0000000000..3176dd9a5f --- /dev/null +++ b/server/testsuite/testsuite_entities.go @@ -0,0 +1,83 @@ +package testsuite + +import ( + "time" + + "github.com/kubeshop/tracetest/server/pkg/id" + "github.com/kubeshop/tracetest/server/test" +) + +const ( + TestSuiteResourceName = "TestSuite" + TestSuiteResourceNamePlural = "TestSuites" +) + +type TestSuite struct { + ID id.ID `json:"id"` + CreatedAt *time.Time `json:"createdAt,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + Version *int `json:"version,omitempty"` + StepIDs []id.ID `json:"steps"` + Steps []test.Test `json:"fullSteps,omitempty"` + Summary *test.Summary `json:"summary,omitempty"` +} + +func setVersion(t *TestSuite, v int) { + t.Version = &v +} + +func (t TestSuite) GetVersion() int { + if t.Version == nil { + return 0 + } + return *t.Version +} + +func setCreatedAt(t *TestSuite, d time.Time) { + t.CreatedAt = &d +} + +func (t TestSuite) GetCreatedAt() time.Time { + if t.CreatedAt == nil { + return time.Time{} + } + return *t.CreatedAt +} + +func (t TestSuite) HasID() bool { + return t.ID != "" +} + +func (t TestSuite) GetID() id.ID { + return t.ID +} + +func (t TestSuite) Validate() error { + return nil +} + +func (t TestSuite) NewRun() TestSuiteRun { + + return TestSuiteRun{ + TestSuiteID: t.ID, + TestSuiteVersion: t.GetVersion(), + CreatedAt: time.Now().UTC(), + State: TestSuiteStateCreated, + Steps: make([]test.Run, 0, len(t.StepIDs)), + CurrentTest: 0, + } +} + +type TestSuiteRunState string + +const ( + TestSuiteStateCreated TestSuiteRunState = "CREATED" + TestSuiteStateExecuting TestSuiteRunState = "EXECUTING" + TestSuiteStateFailed TestSuiteRunState = "FAILED" + TestSuiteStateFinished TestSuiteRunState = "FINISHED" +) + +func (rs TestSuiteRunState) IsFinal() bool { + return rs == TestSuiteStateFailed || rs == TestSuiteStateFinished +} diff --git a/server/transaction/transaction_repository.go b/server/testsuite/testsuite_repository.go similarity index 51% rename from server/transaction/transaction_repository.go rename to server/testsuite/testsuite_repository.go index 0f94abf4b0..1336454ec5 100644 --- a/server/transaction/transaction_repository.go +++ b/server/testsuite/testsuite_repository.go @@ -1,4 +1,4 @@ -package transaction +package testsuite import ( "context" @@ -14,7 +14,7 @@ import ( "github.com/kubeshop/tracetest/server/test" ) -func NewRepository(db *sql.DB, stepRepository transactionStepRepository) *Repository { +func NewRepository(db *sql.DB, stepRepository testSuiteStepRepository) *Repository { repo := &Repository{ db: db, stepRepository: stepRepository, @@ -23,13 +23,13 @@ func NewRepository(db *sql.DB, stepRepository transactionStepRepository) *Reposi return repo } -type transactionStepRepository interface { - GetTransactionSteps(_ context.Context, _ id.ID, version int) ([]test.Test, error) +type testSuiteStepRepository interface { + GetTestSuiteSteps(_ context.Context, _ id.ID, version int) ([]test.Test, error) } type Repository struct { db *sql.DB - stepRepository transactionStepRepository + stepRepository testSuiteStepRepository } // needed for test @@ -37,54 +37,54 @@ func (r *Repository) DB() *sql.DB { return r.db } -func (r *Repository) SetID(t Transaction, id id.ID) Transaction { +func (r *Repository) SetID(t TestSuite, id id.ID) TestSuite { t.ID = id return t } -func (r *Repository) Provision(ctx context.Context, transaction Transaction) error { - _, err := r.Create(ctx, transaction) +func (r *Repository) Provision(ctx context.Context, testSuite TestSuite) error { + _, err := r.Create(ctx, testSuite) return err } -func (r *Repository) Create(ctx context.Context, transaction Transaction) (Transaction, error) { - setVersion(&transaction, 1) - if transaction.CreatedAt == nil { - setCreatedAt(&transaction, time.Now()) +func (r *Repository) Create(ctx context.Context, testSuite TestSuite) (TestSuite, error) { + setVersion(&testSuite, 1) + if testSuite.CreatedAt == nil { + setCreatedAt(&testSuite, time.Now()) } - t, err := r.insertIntoTransactions(ctx, transaction) + t, err := r.insertIntoTestSuites(ctx, testSuite) if err != nil { - return Transaction{}, err + return TestSuite{}, err } removeNonAugmentedFields(&t) return t, nil } -func (r *Repository) Update(ctx context.Context, transaction Transaction) (Transaction, error) { - oldTransaction, err := r.GetLatestVersion(ctx, transaction.ID) +func (r *Repository) Update(ctx context.Context, testSuite TestSuite) (TestSuite, error) { + oldTestSuite, err := r.GetLatestVersion(ctx, testSuite.ID) if err != nil { - return Transaction{}, fmt.Errorf("could not get latest test version while updating test: %w", err) + return TestSuite{}, fmt.Errorf("could not get latest test version while updating test: %w", err) } - if transaction.GetVersion() == 0 { - setVersion(&transaction, oldTransaction.GetVersion()) + if testSuite.GetVersion() == 0 { + setVersion(&testSuite, oldTestSuite.GetVersion()) } // keep the same creation date to keep sort order - transaction.CreatedAt = oldTransaction.CreatedAt - transactionToUpdate := BumpTransactionVersionIfNeeded(oldTransaction, transaction) + testSuite.CreatedAt = oldTestSuite.CreatedAt + transactionToUpdate := BumpTestSuiteVersionIfNeeded(oldTestSuite, testSuite) - if oldTransaction.GetVersion() == transactionToUpdate.GetVersion() { + if oldTestSuite.GetVersion() == transactionToUpdate.GetVersion() { // No change in the version, so nothing changes and it doesn't need to persist it return transactionToUpdate, nil } - t, err := r.insertIntoTransactions(ctx, transactionToUpdate) + t, err := r.insertIntoTestSuites(ctx, transactionToUpdate) if err != nil { - return Transaction{}, err + return TestSuite{}, err } removeNonAugmentedFields(&t) @@ -113,28 +113,28 @@ func (r *Repository) Delete(ctx context.Context, id id.ID) error { return err } - query, params := sqlutil.Tenant(ctx, "DELETE FROM transaction_steps WHERE transaction_id = $1", id) + query, params := sqlutil.Tenant(ctx, "DELETE FROM test_suite_steps WHERE test_suite_id = $1", id) _, err = tx.ExecContext(ctx, query, params...) if err != nil { tx.Rollback() return err } - q, params := sqlutil.Tenant(ctx, "DELETE FROM transaction_run_steps WHERE transaction_run_id IN (SELECT id FROM transaction_runs WHERE transaction_id = $1)", id) + q, params := sqlutil.Tenant(ctx, "DELETE FROM test_suite_run_steps WHERE test_suite_run_id IN (SELECT id FROM test_suite_runs WHERE test_suite_id = $1)", id) _, err = tx.ExecContext(ctx, q, params...) if err != nil { tx.Rollback() return err } - q, params = sqlutil.Tenant(ctx, "DELETE FROM transaction_runs WHERE transaction_id = $1", id) + q, params = sqlutil.Tenant(ctx, "DELETE FROM test_suite_runs WHERE test_suite_id = $1", id) _, err = tx.ExecContext(ctx, q, params...) if err != nil { tx.Rollback() return err } - q, params = sqlutil.Tenant(ctx, "DELETE FROM transactions WHERE id = $1", id) + q, params = sqlutil.Tenant(ctx, "DELETE FROM test_suites WHERE id = $1", id) _, err = tx.ExecContext(ctx, q, params...) if err != nil { tx.Rollback() @@ -146,7 +146,7 @@ func (r *Repository) Delete(ctx context.Context, id id.ID) error { func (r *Repository) IDExists(ctx context.Context, id id.ID) (bool, error) { exists := false - query, params := sqlutil.Tenant(ctx, "SELECT COUNT(*) > 0 as exists FROM transactions WHERE id = $1", id) + query, params := sqlutil.Tenant(ctx, "SELECT COUNT(*) > 0 as exists FROM test_suites WHERE id = $1", id) row := r.db.QueryRowContext(ctx, query, params...) err := row.Scan(&exists) @@ -157,24 +157,24 @@ func (r *Repository) IDExists(ctx context.Context, id id.ID) (bool, error) { return exists, nil } -const getTransactionSQL = ` +const getTestSuiteSQL = ` SELECT %s - FROM transactions t + FROM test_suites t LEFT OUTER JOIN ( - SELECT MAX(id) as id, transaction_id FROM transaction_runs GROUP BY transaction_id - ) as ltr ON ltr.transaction_id = t.id + SELECT MAX(id) as id, test_suite_id FROM test_suite_runs GROUP BY test_suite_id + ) as ltr ON ltr.test_suite_id = t.id LEFT OUTER JOIN - transaction_runs last_transaction_run - ON last_transaction_run.transaction_id = ltr.transaction_id AND last_transaction_run.id = ltr.id + test_suite_runs last_test_suite_run + ON last_test_suite_run.test_suite_id = ltr.test_suite_id AND last_test_suite_run.id = ltr.id ` -const transactionMaxVersionQuery = ` +const testSuiteMaxVersionQuery = ` INNER JOIN ( - SELECT id as idx, max(version) as latest_version FROM transactions GROUP BY idx - ) as latest_transactions ON latest_transactions.idx = t.id + SELECT id as idx, max(version) as latest_version FROM test_suites GROUP BY idx + ) as latest_test_suites ON latest_test_suites.idx = t.id - WHERE t.version = latest_transactions.latest_version ` + WHERE t.version = latest_test_suites.latest_version ` func (r *Repository) SortingFields() []string { return []string{ @@ -184,21 +184,21 @@ func (r *Repository) SortingFields() []string { } } -func (r *Repository) ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Transaction, error) { +func (r *Repository) ListAugmented(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]TestSuite, error) { return r.list(ctx, take, skip, query, sortBy, sortDirection, true) } -func (r *Repository) List(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]Transaction, error) { +func (r *Repository) List(ctx context.Context, take, skip int, query, sortBy, sortDirection string) ([]TestSuite, error) { return r.list(ctx, take, skip, query, sortBy, sortDirection, false) } -func (r *Repository) list(ctx context.Context, take, skip int, query, sortBy, sortDirection string, augmented bool) ([]Transaction, error) { +func (r *Repository) list(ctx context.Context, take, skip int, query, sortBy, sortDirection string, augmented bool) ([]TestSuite, error) { q, params := listQuery(ctx, querySelect(), query, []any{take, skip}) sortingFields := map[string]string{ "created": "t.created_at", "name": "t.name", - "last_run": "last_transaction_run_time", + "last_run": "last_test_suite_run_time", } q = sqlutil.Sort(q, sortBy, sortDirection, "created", sortingFields) @@ -215,20 +215,20 @@ func (r *Repository) list(ctx context.Context, take, skip int, query, sortBy, so return nil, err } - transactions, err := r.readRows(ctx, rows, augmented) + suites, err := r.readRows(ctx, rows, augmented) if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err } - return transactions, nil + return suites, nil } func queryCount() string { - return fmt.Sprintf(getTransactionSQL, "COUNT(*)") + return fmt.Sprintf(getTestSuiteSQL, "COUNT(*)") } func querySelect() string { - return fmt.Sprintf(getTransactionSQL, ` + return fmt.Sprintf(getTestSuiteSQL, ` t.id, t.version, t.name, @@ -236,15 +236,15 @@ func querySelect() string { t.created_at, ( SELECT step_ids_query.ids FROM ( - SELECT ts.transaction_id, ts.transaction_version, string_agg(ts.test_id, ',') as ids FROM transaction_steps ts - GROUP BY transaction_id, transaction_version - HAVING ts.transaction_id = t.id AND ts.transaction_version = t.version + SELECT ts.test_suite_id, ts.test_suite_version, string_agg(ts.test_id, ',') as ids FROM test_suite_steps ts + GROUP BY test_suite_id, test_suite_version + HAVING ts.test_suite_id = t.id AND ts.test_suite_version = t.version ) as step_ids_query ) as step_ids, - (SELECT COUNT(*) FROM transaction_runs tr WHERE tr.transaction_id = t.id) as total_runs, - last_transaction_run.created_at as last_transaction_run_time, - last_transaction_run.pass as last_test_run_pass, - last_transaction_run.fail as last_test_run_fail + (SELECT COUNT(*) FROM test_suite_runs tr WHERE tr.test_suite_id = t.id) as total_runs, + last_test_suite_run.created_at as last_test_suite_run_time, + last_test_suite_run.pass as last_test_run_pass, + last_test_suite_run.fail as last_test_run_fail `) } @@ -263,75 +263,75 @@ func (r *Repository) Count(ctx context.Context, query string) (int, error) { return count, nil } -func (r *Repository) GetAugmented(ctx context.Context, id id.ID) (Transaction, error) { +func (r *Repository) GetAugmented(ctx context.Context, id id.ID) (TestSuite, error) { return r.get(ctx, id, true) } -func (r *Repository) Get(ctx context.Context, id id.ID) (Transaction, error) { +func (r *Repository) Get(ctx context.Context, id id.ID) (TestSuite, error) { return r.get(ctx, id, false) } -func (r *Repository) get(ctx context.Context, id id.ID, augmented bool) (Transaction, error) { +func (r *Repository) get(ctx context.Context, id id.ID, augmented bool) (TestSuite, error) { query, params := sqlutil.Tenant(ctx, querySelect()+" WHERE t.id = $1", id) stmt, err := r.db.Prepare(query + "ORDER BY t.version DESC LIMIT 1") if err != nil { - return Transaction{}, fmt.Errorf("prepare: %w", err) + return TestSuite{}, fmt.Errorf("prepare: %w", err) } defer stmt.Close() - transaction, err := r.readRow(ctx, stmt.QueryRowContext(ctx, params...), augmented) + testSuite, err := r.readRow(ctx, stmt.QueryRowContext(ctx, params...), augmented) if err != nil { - return Transaction{}, err + return TestSuite{}, err } - return transaction, nil + return testSuite, nil } -func (r *Repository) GetVersion(ctx context.Context, id id.ID, version int) (Transaction, error) { +func (r *Repository) GetVersion(ctx context.Context, id id.ID, version int) (TestSuite, error) { query, params := sqlutil.Tenant(ctx, querySelect()+" WHERE t.id = $1 AND t.version = $2", id, version) stmt, err := r.db.Prepare(query) if err != nil { - return Transaction{}, fmt.Errorf("prepare 1: %w", err) + return TestSuite{}, fmt.Errorf("prepare 1: %w", err) } defer stmt.Close() - transaction, err := r.readRow(ctx, stmt.QueryRowContext(ctx, params...), true) + testSuite, err := r.readRow(ctx, stmt.QueryRowContext(ctx, params...), true) if err != nil { - return Transaction{}, err + return TestSuite{}, err } - return transaction, nil + return testSuite, nil } func listQuery(ctx context.Context, baseSQL, query string, params []any) (string, []any) { paramNumber := len(params) + 1 condition := fmt.Sprintf(" AND (t.name ilike $%d OR t.description ilike $%d)", paramNumber, paramNumber) - sql := baseSQL + transactionMaxVersionQuery + sql := baseSQL + testSuiteMaxVersionQuery sql, params = sqlutil.Search(sql, condition, query, params) sql, params = sqlutil.Tenant(ctx, sql, params...) return sql, params } -func (r *Repository) GetLatestVersion(ctx context.Context, id id.ID) (Transaction, error) { +func (r *Repository) GetLatestVersion(ctx context.Context, id id.ID) (TestSuite, error) { query, params := sqlutil.Tenant(ctx, querySelect()+" WHERE t.id = $1", id) stmt, err := r.db.Prepare(query + " ORDER BY t.version DESC LIMIT 1") if err != nil { - return Transaction{}, fmt.Errorf("prepare: %w", err) + return TestSuite{}, fmt.Errorf("prepare: %w", err) } defer stmt.Close() - transaction, err := r.readRow(ctx, stmt.QueryRowContext(ctx, params...), true) + testSuite, err := r.readRow(ctx, stmt.QueryRowContext(ctx, params...), true) if err != nil { - return Transaction{}, err + return TestSuite{}, err } - return transaction, nil + return testSuite, nil } -const insertIntoTransactionsQuery = ` -INSERT INTO transactions ( +const insertIntoTestSuiteQuery = ` +INSERT INTO test_suites ( "id", "version", "name", @@ -340,16 +340,16 @@ INSERT INTO transactions ( "tenant_id" ) VALUES ($1, $2, $3, $4, $5, $6)` -func (r *Repository) insertIntoTransactions(ctx context.Context, transaction Transaction) (Transaction, error) { +func (r *Repository) insertIntoTestSuites(ctx context.Context, suite TestSuite) (TestSuite, error) { tx, err := r.db.BeginTx(ctx, &sql.TxOptions{}) defer tx.Rollback() if err != nil { - return Transaction{}, fmt.Errorf("sql begin: %w", err) + return TestSuite{}, fmt.Errorf("sql begin: %w", err) } - stmt, err := tx.Prepare(insertIntoTransactionsQuery) + stmt, err := tx.Prepare(insertIntoTestSuiteQuery) if err != nil { - return Transaction{}, fmt.Errorf("sql prepare: %w", err) + return TestSuite{}, fmt.Errorf("sql prepare: %w", err) } defer stmt.Close() @@ -357,71 +357,71 @@ func (r *Repository) insertIntoTransactions(ctx context.Context, transaction Tra _, err = stmt.ExecContext( ctx, - transaction.ID, - transaction.GetVersion(), - transaction.Name, - transaction.Description, - transaction.GetCreatedAt(), + suite.ID, + suite.GetVersion(), + suite.Name, + suite.Description, + suite.GetCreatedAt(), tenantID, ) if err != nil { - return Transaction{}, fmt.Errorf("sql exec: %w", err) + return TestSuite{}, fmt.Errorf("sql exec: %w", err) } - return r.setTransactionSteps(ctx, tx, transaction) + return r.setTestSuiteSteps(ctx, tx, suite) } -func (r *Repository) setTransactionSteps(ctx context.Context, tx *sql.Tx, transaction Transaction) (Transaction, error) { +func (r *Repository) setTestSuiteSteps(ctx context.Context, tx *sql.Tx, suite TestSuite) (TestSuite, error) { // delete existing steps - query, params := sqlutil.Tenant(ctx, "DELETE FROM transaction_steps WHERE transaction_id = $1 AND transaction_version = $2", transaction.ID, transaction.GetVersion()) + query, params := sqlutil.Tenant(ctx, "DELETE FROM test_suite_steps WHERE test_suite_id = $1 AND test_suite_version = $2", suite.ID, suite.GetVersion()) stmt, err := tx.Prepare(query) if err != nil { - return Transaction{}, err + return TestSuite{}, err } _, err = stmt.ExecContext(ctx, params...) if err != nil { - return Transaction{}, err + return TestSuite{}, err } - if len(transaction.StepIDs) == 0 { - return transaction, tx.Commit() + if len(suite.StepIDs) == 0 { + return suite, tx.Commit() } tenantID := sqlutil.TenantID(ctx) values := []string{} - for i, testID := range transaction.StepIDs { + for i, testID := range suite.StepIDs { stepNumber := i + 1 if tenantID == nil { values = append( values, - fmt.Sprintf("('%s', %d, '%s', %d, NULL)", transaction.ID, transaction.GetVersion(), testID, stepNumber), + fmt.Sprintf("('%s', %d, '%s', %d, NULL)", suite.ID, suite.GetVersion(), testID, stepNumber), ) } else { values = append( values, - fmt.Sprintf("('%s', %d, '%s', %d, '%s')", transaction.ID, transaction.GetVersion(), testID, stepNumber, *tenantID), + fmt.Sprintf("('%s', %d, '%s', %d, '%s')", suite.ID, suite.GetVersion(), testID, stepNumber, *tenantID), ) } } - sql := "INSERT INTO transaction_steps VALUES " + strings.Join(values, ", ") + sql := "INSERT INTO test_suite_steps VALUES " + strings.Join(values, ", ") _, err = tx.ExecContext(ctx, sql) if err != nil { - return Transaction{}, fmt.Errorf("cannot save transaction steps: %w", err) + return TestSuite{}, fmt.Errorf("cannot save test suite steps: %w", err) } - return transaction, tx.Commit() + return suite, tx.Commit() } -func (r *Repository) readRows(ctx context.Context, rows *sql.Rows, augmented bool) ([]Transaction, error) { - transactions := []Transaction{} +func (r *Repository) readRows(ctx context.Context, rows *sql.Rows, augmented bool) ([]TestSuite, error) { + transactions := []TestSuite{} for rows.Next() { transaction, err := r.readRow(ctx, rows, augmented) if err != nil { - return []Transaction{}, fmt.Errorf("cannot read rows: %w", err) + return []TestSuite{}, fmt.Errorf("cannot read rows: %w", err) } transactions = append(transactions, transaction) @@ -434,8 +434,8 @@ type scanner interface { Scan(dest ...interface{}) error } -func (r *Repository) readRow(ctx context.Context, row scanner, augmented bool) (Transaction, error) { - transaction := Transaction{ +func (r *Repository) readRow(ctx context.Context, row scanner, augmented bool) (TestSuite, error) { + suite := TestSuite{ Summary: &test.Summary{}, } @@ -448,13 +448,13 @@ func (r *Repository) readRow(ctx context.Context, row scanner, augmented bool) ( ) err := row.Scan( - &transaction.ID, + &suite.ID, &version, - &transaction.Name, - &transaction.Description, - &transaction.CreatedAt, + &suite.Name, + &suite.Description, + &suite.CreatedAt, &stepIDs, - &transaction.Summary.Runs, + &suite.Summary.Runs, &lastRunTime, &pass, &fail, @@ -462,56 +462,56 @@ func (r *Repository) readRow(ctx context.Context, row scanner, augmented bool) ( if err != nil { if err == sql.ErrNoRows { - return transaction, err + return suite, err } - return Transaction{}, fmt.Errorf("cannot read row: %w", err) + return TestSuite{}, fmt.Errorf("cannot read row: %w", err) } if stepIDs != nil && *stepIDs != "" { ids := strings.Split(*stepIDs, ",") - transaction.StepIDs = make([]id.ID, len(ids)) + suite.StepIDs = make([]id.ID, len(ids)) for i, sid := range ids { - transaction.StepIDs[i] = id.ID(sid) + suite.StepIDs[i] = id.ID(sid) } } if version != 0 { - transaction.Version = &version + suite.Version = &version } if lastRunTime != nil { - transaction.Summary.LastRun.Time = *lastRunTime + suite.Summary.LastRun.Time = *lastRunTime } if pass != nil { - transaction.Summary.LastRun.Passes = *pass + suite.Summary.LastRun.Passes = *pass } if fail != nil { - transaction.Summary.LastRun.Fails = *fail + suite.Summary.LastRun.Fails = *fail } if !augmented { - removeNonAugmentedFields(&transaction) + removeNonAugmentedFields(&suite) } else { - steps, err := r.stepRepository.GetTransactionSteps(ctx, transaction.ID, *transaction.Version) + steps, err := r.stepRepository.GetTestSuiteSteps(ctx, suite.ID, *suite.Version) if err != nil { - return Transaction{}, fmt.Errorf("cannot read row: %w", err) + return TestSuite{}, fmt.Errorf("cannot read row: %w", err) } - transaction.Steps = steps + suite.Steps = steps } - return transaction, nil + return suite, nil } -func removeNonAugmentedFields(t *Transaction) { +func removeNonAugmentedFields(t *TestSuite) { t.CreatedAt = nil t.Version = nil t.Summary = nil } -func BumpTransactionVersionIfNeeded(original, updated Transaction) Transaction { - transactionHasChanged := transactionHasChanged(original, updated) +func BumpTestSuiteVersionIfNeeded(original, updated TestSuite) TestSuite { + transactionHasChanged := testSuiteHasChanged(original, updated) if transactionHasChanged { setVersion(&updated, original.GetVersion()+1) } @@ -519,7 +519,7 @@ func BumpTransactionVersionIfNeeded(original, updated Transaction) Transaction { return updated } -func transactionHasChanged(in, updated Transaction) bool { +func testSuiteHasChanged(in, updated TestSuite) bool { jsons := []struct { Name string Description string @@ -543,7 +543,7 @@ func transactionHasChanged(in, updated Transaction) bool { return string(inJson) != string(updatedJson) } -func stepIDsToStringSlice(in Transaction) []string { +func stepIDsToStringSlice(in TestSuite) []string { steps := make([]string, len(in.StepIDs)) for i, stepID := range in.StepIDs { steps[i] = stepID.String() diff --git a/server/transaction/transaction_repository_test.go b/server/testsuite/testsuite_repository_test.go similarity index 81% rename from server/transaction/transaction_repository_test.go rename to server/testsuite/testsuite_repository_test.go index 7a8406f4c3..13cf13846a 100644 --- a/server/transaction/transaction_repository_test.go +++ b/server/testsuite/testsuite_repository_test.go @@ -1,4 +1,4 @@ -package transaction_test +package testsuite_test import ( "context" @@ -14,12 +14,12 @@ import ( "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/test/trigger" "github.com/kubeshop/tracetest/server/testmock" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -type transactionFixture struct { +type testSuiteFixture struct { t1 test.Test t2 test.Test testRun test.Run @@ -61,11 +61,11 @@ func createRun(runRepository test.RunRepository, t test.Test) test.Run { return run } -func setupTransactionFixture(t *testing.T, db *sql.DB) transactionFixture { +func setupTestSuiteFixture(t *testing.T, db *sql.DB) testSuiteFixture { testsDB := test.NewRepository(db) runDB := test.NewRunRepository(db) - fixture := transactionFixture{} + fixture := testSuiteFixture{} createdTest := test.Test{ ID: "ezMn7bE4g", @@ -132,35 +132,35 @@ func setupTransactionFixture(t *testing.T, db *sql.DB) transactionFixture { } func setupTests(t *testing.T, db *sql.DB) test.Run { - f := setupTransactionFixture(t, db) + f := setupTestSuiteFixture(t, db) return f.testRun } -func TestDeleteTestsRelatedToTransactions(t *testing.T) { +func TestDeleteTestsRelatedToTestSuite(t *testing.T) { db := testmock.CreateMigratedDatabase() defer db.Close() testRepository := test.NewRepository(db) runRepository := test.NewRunRepository(db) - transactionRepo := transaction.NewRepository(db, testRepository) - transactionRunRepo := transaction.NewRunRepository(db, runRepository) + testSuiteRepo := testsuite.NewRepository(db, testRepository) + testSuiteRunRepo := testsuite.NewRunRepository(db, runRepository) - transactionRepo.Create(context.TODO(), transactionSample) + testSuiteRepo.Create(context.TODO(), testSuiteSample) - f := setupTransactionFixture(t, db) - createTransactionRun(transactionRepo, transactionRunRepo, transactionSample, f.testRun) + f := setupTestSuiteFixture(t, db) + createTransactionRun(testSuiteRepo, testSuiteRunRepo, testSuiteSample, f.testRun) testRepository.Delete(context.TODO(), f.t1.ID) testRepository.Delete(context.TODO(), f.t2.ID) - actual, err := transactionRepo.Get(context.TODO(), transactionSample.ID) + actual, err := testSuiteRepo.Get(context.TODO(), testSuiteSample.ID) assert.NoError(t, err) assert.Len(t, actual.StepIDs, 0) } -var transactionSample = transaction.Transaction{ +var testSuiteSample = testsuite.TestSuite{ ID: "NiWVnxP4R", Name: "Verify Import", Description: "check the working of the import flow", @@ -170,19 +170,19 @@ var transactionSample = transaction.Transaction{ }, } -func TestTransactions(t *testing.T) { - // sample2 := transaction.Transaction{ +func TestTestSuites(t *testing.T) { + // sample2 := testsuite.TestSuite{ // ID: "sample2", - // Name: "Some Transaction", + // Name: "Some testsuite", // Description: "Do important stuff", // StepIDs: []id.ID{ // "ezMn7bE4g", // }, // } - // sample3 := transaction.Transaction{ + // sample3 := testsuite.TestSuite{ // ID: "sample3", - // Name: "Some Transaction", + // Name: "Some testsuite", // Description: "Do important stuff", // StepIDs: []id.ID{ // "ezMn7bE4g", @@ -190,15 +190,15 @@ func TestTransactions(t *testing.T) { // } rmtests.TestResourceType(t, rmtests.ResourceTypeTest{ - ResourceTypeSingular: transaction.TransactionResourceName, - ResourceTypePlural: transaction.TransactionResourceNamePlural, + ResourceTypeSingular: testsuite.TestSuiteResourceName, + ResourceTypePlural: testsuite.TestSuiteResourceNamePlural, RegisterManagerFn: func(router *mux.Router, db *sql.DB) resourcemanager.Manager { testsDB := test.NewRepository(db) - transactionsRepo := transaction.NewRepository(db, testsDB) + transactionsRepo := testsuite.NewRepository(db, testsDB) - manager := resourcemanager.New[transaction.Transaction]( - transaction.TransactionResourceName, - transaction.TransactionResourceNamePlural, + manager := resourcemanager.New[testsuite.TestSuite]( + testsuite.TestSuiteResourceName, + testsuite.TestSuiteResourceNamePlural, transactionsRepo, resourcemanager.CanBeAugmented(), ) @@ -207,32 +207,32 @@ func TestTransactions(t *testing.T) { return manager }, Prepare: func(t *testing.T, op rmtests.Operation, manager resourcemanager.Manager) { - transactionRepo := manager.Handler().(*transaction.Repository) + transactionRepo := manager.Handler().(*testsuite.Repository) runRepository := test.NewRunRepository(transactionRepo.DB()) - runRepo := transaction.NewRunRepository(transactionRepo.DB(), runRepository) + runRepo := testsuite.NewRunRepository(transactionRepo.DB(), runRepository) switch op { case rmtests.OperationGetSuccess, rmtests.OperationUpdateSuccess, rmtests.OperationListSuccess: - transactionRepo.Create(context.TODO(), transactionSample) + transactionRepo.Create(context.TODO(), testSuiteSample) case rmtests.OperationDeleteSuccess: - transactionRepo.Create(context.TODO(), transactionSample) + transactionRepo.Create(context.TODO(), testSuiteSample) // test delete with more than 1 run run := setupTests(t, transactionRepo.DB()) - createTransactionRun(transactionRepo, runRepo, transactionSample, run) + createTransactionRun(transactionRepo, runRepo, testSuiteSample, run) run = copyRun(runRepository, run) - createTransactionRun(transactionRepo, runRepo, transactionSample, run) + createTransactionRun(transactionRepo, runRepo, testSuiteSample, run) case rmtests.OperationListAugmentedSuccess, rmtests.OperationGetAugmentedSuccess: - transactionRepo.Create(context.TODO(), transactionSample) + transactionRepo.Create(context.TODO(), testSuiteSample) run := setupTests(t, transactionRepo.DB()) - createTransactionRun(transactionRepo, runRepo, transactionSample, run) + createTransactionRun(transactionRepo, runRepo, testSuiteSample, run) // TODO: reenable this tests when we figure out how to test it // problems: @@ -245,7 +245,7 @@ func TestTransactions(t *testing.T) { } }, SampleJSON: `{ - "type": "Transaction", + "type": "TestSuite", "spec": { "id": "NiWVnxP4R", "name": "Verify Import", @@ -257,7 +257,7 @@ func TestTransactions(t *testing.T) { } }`, SampleJSONAugmented: `{ - "type": "Transaction", + "type": "TestSuite", "spec": { "id": "NiWVnxP4R", "createdAt": "REMOVEME", @@ -358,7 +358,7 @@ func TestTransactions(t *testing.T) { } }`, SampleJSONUpdated: `{ - "type": "Transaction", + "type": "TestSuite", "spec": { "id": "NiWVnxP4R", "name": "Verify Import Updated", @@ -394,7 +394,7 @@ func compareJSON(t require.TestingT, operation rmtests.Operation, firstValue, se require.JSONEq(t, expected, actual) } -func createTransactionRun(transactionRepo *transaction.Repository, runRepo *transaction.RunRepository, tran transaction.Transaction, run test.Run) { +func createTransactionRun(transactionRepo *testsuite.Repository, runRepo *testsuite.RunRepository, tran testsuite.TestSuite, run test.Run) { updated, err := transactionRepo.GetAugmented(context.TODO(), tran.ID) if err != nil { panic(err) diff --git a/server/transaction/transaction_run_entities.go b/server/testsuite/testsuite_run_entities.go similarity index 70% rename from server/transaction/transaction_run_entities.go rename to server/testsuite/testsuite_run_entities.go index 0e1cf83fef..57599e6506 100644 --- a/server/transaction/transaction_run_entities.go +++ b/server/testsuite/testsuite_run_entities.go @@ -1,4 +1,4 @@ -package transaction +package testsuite import ( "fmt" @@ -10,10 +10,10 @@ import ( "github.com/kubeshop/tracetest/server/variableset" ) -type TransactionRun struct { - ID int - TransactionID id.ID - TransactionVersion int +type TestSuiteRun struct { + ID int + TestSuiteID id.ID + TestSuiteVersion int // Timestamps CreatedAt time.Time @@ -24,7 +24,7 @@ type TransactionRun struct { Steps []test.Run // trigger params - State TransactionRunState + State TestSuiteRunState CurrentTest int // result info @@ -40,11 +40,11 @@ type TransactionRun struct { RequiredGates *[]testrunner.RequiredGate } -func (tr TransactionRun) ResourceID() string { - return fmt.Sprintf("transaction/%s/run/%d", tr.TransactionID, tr.ID) +func (tr TestSuiteRun) ResourceID() string { + return fmt.Sprintf("testsuites/%s/run/%d", tr.TestSuiteID, tr.ID) } -func (tr TransactionRun) ResultsCount() (pass, fail int) { +func (tr TestSuiteRun) ResultsCount() (pass, fail int) { if tr.Steps == nil { return } @@ -59,7 +59,7 @@ func (tr TransactionRun) ResultsCount() (pass, fail int) { return } -func (tr TransactionRun) StepsGatesValidation() bool { +func (tr TestSuiteRun) StepsGatesValidation() bool { for _, step := range tr.Steps { if !step.RequiredGatesResult.Passed { return false diff --git a/server/transaction/transaction_run_repository.go b/server/testsuite/testsuite_run_repository.go similarity index 54% rename from server/transaction/transaction_run_repository.go rename to server/testsuite/testsuite_run_repository.go index 79911243f7..26d92fd9a0 100644 --- a/server/transaction/transaction_run_repository.go +++ b/server/testsuite/testsuite_run_repository.go @@ -1,4 +1,4 @@ -package transaction +package testsuite import ( "context" @@ -15,11 +15,11 @@ import ( "github.com/kubeshop/tracetest/server/test" ) -type transactionStepRunRepository interface { - GetTransactionRunSteps(_ context.Context, _ id.ID, runID int) ([]test.Run, error) +type testSuiteStepRunRepository interface { + GetTestSuiteRunSteps(_ context.Context, _ id.ID, runID int) ([]test.Run, error) } -func NewRunRepository(db *sql.DB, stepsRepository transactionStepRunRepository) *RunRepository { +func NewRunRepository(db *sql.DB, stepsRepository testSuiteStepRunRepository) *RunRepository { return &RunRepository{ db: db, stepsRepository: stepsRepository, @@ -28,14 +28,14 @@ func NewRunRepository(db *sql.DB, stepsRepository transactionStepRunRepository) type RunRepository struct { db *sql.DB - stepsRepository transactionStepRunRepository + stepsRepository testSuiteStepRunRepository } -const createTransactionRunQuery = ` -INSERT INTO transaction_runs ( +const createTestSuiteRunQuery = ` +INSERT INTO test_suite_runs ( "id", - "transaction_id", - "transaction_version", + "test_suite_id", + "test_suite_version", -- timestamps "created_at", @@ -59,8 +59,8 @@ INSERT INTO transaction_runs ( "tenant_id" ) VALUES ( nextval('` + runSequenceName + `'), -- id - $1, -- transaction_id - $2, -- transaction_version + $1, -- test_suite_id + $2, -- test_suite_version -- timestamps $3, -- created_at @@ -93,35 +93,35 @@ func md5Hash(text string) string { return hex.EncodeToString(hash[:]) } -func replaceTransactionRunSequenceName(sql string, transactionID id.ID) string { +func replaceTestSuiteRunSequenceName(sql string, ID id.ID) string { // postgres doesn't like uppercase chars in sequence names. // transactionID might contain uppercase chars, and we cannot lowercase them // because they might lose their uniqueness. // md5 creates a unique, lowercase hash. - seqName := "runs_transaction_" + md5Hash(transactionID.String()) + "_seq" + seqName := "runs_test_suite_" + md5Hash(ID.String()) + "_seq" return strings.ReplaceAll(sql, runSequenceName, seqName) } -func (td *RunRepository) CreateRun(ctx context.Context, tr TransactionRun) (TransactionRun, error) { +func (td *RunRepository) CreateRun(ctx context.Context, tr TestSuiteRun) (TestSuiteRun, error) { jsonMetadata, err := json.Marshal(tr.Metadata) if err != nil { - return TransactionRun{}, fmt.Errorf("failed to marshal transaction run metadata: %w", err) + return TestSuiteRun{}, fmt.Errorf("failed to marshal test_suite run metadata: %w", err) } jsonVariableSet, err := json.Marshal(tr.VariableSet) if err != nil { - return TransactionRun{}, fmt.Errorf("failed to marshal transaction run variable set: %w", err) + return TestSuiteRun{}, fmt.Errorf("failed to marshal test_suite run variable set: %w", err) } tx, err := td.db.BeginTx(ctx, nil) if err != nil { - return TransactionRun{}, fmt.Errorf("sql beginTx: %w", err) + return TestSuiteRun{}, fmt.Errorf("sql beginTx: %w", err) } - _, err = tx.ExecContext(ctx, replaceTransactionRunSequenceName(createSequenceQuery, tr.TransactionID)) + _, err = tx.ExecContext(ctx, replaceTestSuiteRunSequenceName(createSequenceQuery, tr.TestSuiteID)) if err != nil { tx.Rollback() - return TransactionRun{}, fmt.Errorf("sql exec: %w", err) + return TestSuiteRun{}, fmt.Errorf("sql exec: %w", err) } tenantID := sqlutil.TenantID(ctx) @@ -129,9 +129,9 @@ func (td *RunRepository) CreateRun(ctx context.Context, tr TransactionRun) (Tran var runID int err = tx.QueryRowContext( ctx, - replaceTransactionRunSequenceName(createTransactionRunQuery, tr.TransactionID), - tr.TransactionID, - tr.TransactionVersion, + replaceTestSuiteRunSequenceName(createTestSuiteRunQuery, tr.TestSuiteID), + tr.TestSuiteID, + tr.TestSuiteVersion, tr.CreatedAt, tr.State, tr.CurrentTest, @@ -141,12 +141,12 @@ func (td *RunRepository) CreateRun(ctx context.Context, tr TransactionRun) (Tran ).Scan(&runID) if err != nil { tx.Rollback() - return TransactionRun{}, fmt.Errorf("sql exec: %w", err) + return TestSuiteRun{}, fmt.Errorf("sql exec: %w", err) } err = tx.Commit() if err != nil { - return TransactionRun{}, fmt.Errorf("commit: %w", err) + return TestSuiteRun{}, fmt.Errorf("commit: %w", err) } tr.ID = runID @@ -154,8 +154,8 @@ func (td *RunRepository) CreateRun(ctx context.Context, tr TransactionRun) (Tran return tr, nil } -const updateTransactionRunQuery = ` -UPDATE transaction_runs SET +const updateTestSuiteRunQuery = ` +UPDATE test_suite_runs SET -- timestamps "completed_at" = $1, @@ -175,10 +175,10 @@ UPDATE transaction_runs SET -- variable_set "variable_set" = $9 -WHERE id = $10 AND transaction_id = $11 +WHERE id = $10 AND test_suite_id = $11 ` -func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error { +func (td *RunRepository) UpdateRun(ctx context.Context, tr TestSuiteRun) error { tx, err := td.db.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("sql beginTx: %w", err) @@ -186,12 +186,12 @@ func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error jsonMetadata, err := json.Marshal(tr.Metadata) if err != nil { - return fmt.Errorf("failed to marshal transaction run metadata: %w", err) + return fmt.Errorf("failed to marshal test_suite run metadata: %w", err) } jsonVariableSet, err := json.Marshal(tr.VariableSet) if err != nil { - return fmt.Errorf("failed to marshal transaction run variableSet: %w", err) + return fmt.Errorf("failed to marshal test_suite run variableSet: %w", err) } var lastError *string if tr.LastError != nil { @@ -204,7 +204,7 @@ func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error query, params := sqlutil.Tenant( ctx, - updateTransactionRunQuery, + updateTestSuiteRunQuery, tr.CompletedAt, tr.State, tr.CurrentTest, @@ -215,7 +215,7 @@ func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error jsonMetadata, jsonVariableSet, strconv.Itoa(tr.ID), - tr.TransactionID, + tr.TestSuiteID, ) stmt, err := tx.Prepare(query) if err != nil { @@ -230,12 +230,12 @@ func (td *RunRepository) UpdateRun(ctx context.Context, tr TransactionRun) error return fmt.Errorf("sql exec: %w", err) } - return td.setTransactionRunSteps(ctx, tx, tr) + return td.setTestSuiteRunSteps(ctx, tx, tr) } -func (td *RunRepository) setTransactionRunSteps(ctx context.Context, tx *sql.Tx, tr TransactionRun) error { +func (td *RunRepository) setTestSuiteRunSteps(ctx context.Context, tx *sql.Tx, tr TestSuiteRun) error { // delete existing steps - query, params := sqlutil.Tenant(ctx, "DELETE FROM transaction_run_steps WHERE transaction_run_id = $1 AND transaction_run_transaction_id = $2", strconv.Itoa(tr.ID), tr.TransactionID) + query, params := sqlutil.Tenant(ctx, "DELETE FROM test_suite_run_steps WHERE test_suite_run_id = $1 AND test_suite_run_test_suite_id = $2", strconv.Itoa(tr.ID), tr.TestSuiteID) stmt, err := tx.Prepare(query) if err != nil { return err @@ -243,7 +243,7 @@ func (td *RunRepository) setTransactionRunSteps(ctx context.Context, tx *sql.Tx, _, err = stmt.ExecContext(ctx, params...) if err != nil { - return fmt.Errorf("cannot reset transaction run steps: %w", err) + return fmt.Errorf("cannot reset test_suite run steps: %w", err) } if len(tr.Steps) == 0 { @@ -262,52 +262,52 @@ func (td *RunRepository) setTransactionRunSteps(ctx context.Context, tx *sql.Tx, if tenantID == nil { values = append( values, - fmt.Sprintf("('%d', '%s', %d, '%s', NULL)", tr.ID, tr.TransactionID, run.ID, run.TestID), + fmt.Sprintf("('%d', '%s', %d, '%s', NULL)", tr.ID, tr.TestSuiteID, run.ID, run.TestID), ) } else { values = append( values, - fmt.Sprintf("('%d', '%s', %d, '%s', '%s')", tr.ID, tr.TransactionID, run.ID, run.TestID, *tenantID), + fmt.Sprintf("('%d', '%s', %d, '%s', '%s')", tr.ID, tr.TestSuiteID, run.ID, run.TestID, *tenantID), ) } } - sql := "INSERT INTO transaction_run_steps VALUES " + strings.Join(values, ", ") + sql := "INSERT INTO test_suite_run_steps VALUES " + strings.Join(values, ", ") _, err = tx.ExecContext(ctx, sql) if err != nil { - return fmt.Errorf("cannot save transaction run steps: %w", err) + return fmt.Errorf("cannot save test_suite run steps: %w", err) } return tx.Commit() } -func (td *RunRepository) DeleteTransactionRun(ctx context.Context, tr TransactionRun) error { +func (td *RunRepository) DeleteTestSuiteRun(ctx context.Context, tr TestSuiteRun) error { tx, err := td.db.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("sql beginTx: %w", err) } - query, params := sqlutil.Tenant(ctx, "DELETE FROM transaction_run_steps WHERE transaction_run_id = $1 AND transaction_run_transaction_id = $2", tr.ID, tr.TransactionID) + query, params := sqlutil.Tenant(ctx, "DELETE FROM test_suite_run_steps WHERE test_suite_run_id = $1 AND test_suite_run_test_suite_id = $2", tr.ID, tr.TestSuiteID) _, err = tx.ExecContext(ctx, query, params...) if err != nil { tx.Rollback() - return fmt.Errorf("delete transaction run steps: %w", err) + return fmt.Errorf("delete test_suite run steps: %w", err) } - query, params = sqlutil.Tenant(ctx, "DELETE FROM transaction_runs WHERE id = $1 AND transaction_id = $2", tr.ID, tr.TransactionID) + query, params = sqlutil.Tenant(ctx, "DELETE FROM test_suite_runs WHERE id = $1 AND test_suite_id = $2", tr.ID, tr.TestSuiteID) _, err = tx.ExecContext(ctx, query, params...) if err != nil { tx.Rollback() - return fmt.Errorf("delete transaction runs: %w", err) + return fmt.Errorf("delete test_suite runs: %w", err) } return tx.Commit() } -const selectTransactionRunQuery = ` +const selectTestSuiteRunQuery = ` SELECT "id", - "transaction_id", - "transaction_version", + "test_suite_id", + "test_suite_version", "created_at", "completed_at", @@ -323,69 +323,69 @@ SELECT "metadata", "variable_set" -FROM transaction_runs +FROM test_suite_runs ` -func (td *RunRepository) GetTransactionRun(ctx context.Context, transactionID id.ID, runID int) (TransactionRun, error) { - query, params := sqlutil.Tenant(ctx, selectTransactionRunQuery+" WHERE id = $1 AND transaction_id = $2", strconv.Itoa(runID), transactionID) +func (td *RunRepository) GetTestSuiteRun(ctx context.Context, ID id.ID, runID int) (TestSuiteRun, error) { + query, params := sqlutil.Tenant(ctx, selectTestSuiteRunQuery+" WHERE id = $1 AND test_suite_id = $2", strconv.Itoa(runID), ID) stmt, err := td.db.Prepare(query) if err != nil { - return TransactionRun{}, fmt.Errorf("prepare: %w", err) + return TestSuiteRun{}, fmt.Errorf("prepare: %w", err) } run, err := td.readRunRow(stmt.QueryRowContext(ctx, params...)) if err != nil { - return TransactionRun{}, err + return TestSuiteRun{}, err } - run.Steps, err = td.stepsRepository.GetTransactionRunSteps(ctx, run.TransactionID, run.ID) + run.Steps, err = td.stepsRepository.GetTestSuiteRunSteps(ctx, run.TestSuiteID, run.ID) if err != nil { - return TransactionRun{}, err + return TestSuiteRun{}, err } return run, nil } -func (td *RunRepository) GetLatestRunByTransactionVersion(ctx context.Context, transactionID id.ID, version int) (TransactionRun, error) { +func (td *RunRepository) GetLatestRunByTestSuiteVersion(ctx context.Context, ID id.ID, version int) (TestSuiteRun, error) { sortQuery := "ORDER BY created_at DESC LIMIT 1" - query, params := sqlutil.Tenant(ctx, selectTransactionRunQuery+" WHERE transaction_id = $1 AND transaction_version = $2", transactionID, version) + query, params := sqlutil.Tenant(ctx, selectTestSuiteRunQuery+" WHERE test_suite_id = $1 AND test_suite_version = $2", ID, version) stmt, err := td.db.Prepare(query + sortQuery) if err != nil { - return TransactionRun{}, fmt.Errorf("prepare: %w", err) + return TestSuiteRun{}, fmt.Errorf("prepare: %w", err) } run, err := td.readRunRow(stmt.QueryRowContext(ctx, params...)) if err != nil { - return TransactionRun{}, err + return TestSuiteRun{}, err } - run.Steps, err = td.stepsRepository.GetTransactionRunSteps(ctx, run.TransactionID, run.ID) + run.Steps, err = td.stepsRepository.GetTestSuiteRunSteps(ctx, run.TestSuiteID, run.ID) if err != nil { - return TransactionRun{}, err + return TestSuiteRun{}, err } return run, nil } -func (td *RunRepository) GetTransactionsRuns(ctx context.Context, transactionID id.ID, take, skip int32) ([]TransactionRun, error) { +func (td *RunRepository) GetTestSuiteRuns(ctx context.Context, ID id.ID, take, skip int32) ([]TestSuiteRun, error) { sortQuery := "ORDER BY created_at DESC LIMIT $2 OFFSET $3" - query, params := sqlutil.Tenant(ctx, selectTransactionRunQuery+" WHERE transaction_id = $1", transactionID.String(), take, skip) + query, params := sqlutil.Tenant(ctx, selectTestSuiteRunQuery+" WHERE test_suite_id = $1", ID.String(), take, skip) stmt, err := td.db.Prepare(query + sortQuery) if err != nil { - return []TransactionRun{}, fmt.Errorf("prepare: %w", err) + return []TestSuiteRun{}, fmt.Errorf("prepare: %w", err) } rows, err := stmt.QueryContext(ctx, params...) if err != nil { - return []TransactionRun{}, fmt.Errorf("query: %w", err) + return []TestSuiteRun{}, fmt.Errorf("query: %w", err) } - var runs []TransactionRun + var runs []TestSuiteRun for rows.Next() { run, err := td.readRunRow(rows) if err != nil { - return []TransactionRun{}, err + return []TestSuiteRun{}, err } - run.Steps, err = td.stepsRepository.GetTransactionRunSteps(ctx, run.TransactionID, run.ID) + run.Steps, err = td.stepsRepository.GetTestSuiteRunSteps(ctx, run.TestSuiteID, run.ID) if err != nil { - return []TransactionRun{}, err + return []TestSuiteRun{}, err } runs = append(runs, run) @@ -394,8 +394,8 @@ func (td *RunRepository) GetTransactionsRuns(ctx context.Context, transactionID return runs, nil } -func (td *RunRepository) readRunRow(row scanner) (TransactionRun, error) { - r := TransactionRun{} +func (td *RunRepository) readRunRow(row scanner) (TestSuiteRun, error) { + r := TestSuiteRun{} var ( jsonVariableSet, @@ -410,8 +410,8 @@ func (td *RunRepository) readRunRow(row scanner) (TransactionRun, error) { err := row.Scan( &r.ID, - &r.TransactionID, - &r.TransactionVersion, + &r.TestSuiteID, + &r.TestSuiteVersion, &r.CreatedAt, &r.CompletedAt, &r.State, @@ -424,17 +424,17 @@ func (td *RunRepository) readRunRow(row scanner) (TransactionRun, error) { &jsonVariableSet, ) if err != nil { - return TransactionRun{}, fmt.Errorf("cannot read row: %w", err) + return TestSuiteRun{}, fmt.Errorf("cannot read row: %w", err) } err = json.Unmarshal(jsonMetadata, &r.Metadata) if err != nil { - return TransactionRun{}, fmt.Errorf("cannot parse Metadata: %w", err) + return TestSuiteRun{}, fmt.Errorf("cannot parse Metadata: %w", err) } err = json.Unmarshal(jsonVariableSet, &r.VariableSet) if err != nil { - return TransactionRun{}, fmt.Errorf("cannot parse VariableSet: %w", err) + return TestSuiteRun{}, fmt.Errorf("cannot parse VariableSet: %w", err) } if lastError != nil && *lastError != "" { diff --git a/server/transaction/transaction_run_repository_test.go b/server/testsuite/testsuite_run_repository_test.go similarity index 59% rename from server/transaction/transaction_run_repository_test.go rename to server/testsuite/testsuite_run_repository_test.go index c2fe148ce0..d0628a9af5 100644 --- a/server/transaction/transaction_run_repository_test.go +++ b/server/testsuite/testsuite_run_repository_test.go @@ -1,4 +1,4 @@ -package transaction_test +package testsuite_test import ( "context" @@ -8,7 +8,7 @@ import ( "github.com/kubeshop/tracetest/server/test" "github.com/kubeshop/tracetest/server/test/trigger" "github.com/kubeshop/tracetest/server/testmock" - "github.com/kubeshop/tracetest/server/transaction" + "github.com/kubeshop/tracetest/server/testsuite" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -33,22 +33,22 @@ func createTestWithName(t *testing.T, db test.Repository, name string) test.Test return updated } -func getRepos() (*transaction.Repository, *transaction.RunRepository, test.Repository) { +func getRepos() (*testsuite.Repository, *testsuite.RunRepository, test.Repository) { db := testmock.CreateMigratedDatabase() testRepo := test.NewRepository(db) testRunRepo := test.NewRunRepository(db) - transactionRepo := transaction.NewRepository(db, testRepo) - runRepo := transaction.NewRunRepository(db, testRunRepo) + transactionRepo := testsuite.NewRepository(db, testRepo) + runRepo := testsuite.NewRunRepository(db, testRunRepo) return transactionRepo, runRepo, testRepo } -func getTransaction(t *testing.T, transactionRepo *transaction.Repository, testsRepo test.Repository) (transaction.Transaction, transactionFixture) { - f := setupTransactionFixture(t, transactionRepo.DB()) +func getTransaction(t *testing.T, transactionRepo *testsuite.Repository, testsRepo test.Repository) (testsuite.TestSuite, testSuiteFixture) { + f := setupTestSuiteFixture(t, transactionRepo.DB()) - transaction := transaction.Transaction{ + suite := testsuite.TestSuite{ ID: id.NewRandGenerator().ID(), Name: "first test", Description: "description", @@ -58,13 +58,13 @@ func getTransaction(t *testing.T, transactionRepo *transaction.Repository, tests }, } - _, err := transactionRepo.Create(context.TODO(), transaction) + _, err := transactionRepo.Create(context.TODO(), suite) require.NoError(t, err) - transaction, err = transactionRepo.GetAugmented(context.TODO(), transaction.ID) + suite, err = transactionRepo.GetAugmented(context.TODO(), suite.ID) require.NoError(t, err) - return transaction, f + return suite, f } func TestCreateTransactionRun(t *testing.T) { @@ -74,8 +74,8 @@ func TestCreateTransactionRun(t *testing.T) { tr, err := transactionRunRepo.CreateRun(context.TODO(), transactionObject.NewRun()) require.NoError(t, err) - assert.Equal(t, tr.TransactionID, transactionObject.ID) - assert.Equal(t, tr.State, transaction.TransactionRunStateCreated) + assert.Equal(t, tr.TestSuiteID, transactionObject.ID) + assert.Equal(t, tr.State, testsuite.TestSuiteStateCreated) assert.Len(t, tr.Steps, 0) } @@ -86,53 +86,53 @@ func TestUpdateTransactionRun(t *testing.T) { tr, err := transactionRunRepo.CreateRun(context.TODO(), transactionObject.NewRun()) require.NoError(t, err) - tr.State = transaction.TransactionRunStateExecuting + tr.State = testsuite.TestSuiteStateExecuting tr.Steps = []test.Run{fixture.testRun} err = transactionRunRepo.UpdateRun(context.TODO(), tr) require.NoError(t, err) - updatedRun, err := transactionRunRepo.GetTransactionRun(context.TODO(), transactionObject.ID, tr.ID) + updatedRun, err := transactionRunRepo.GetTestSuiteRun(context.TODO(), transactionObject.ID, tr.ID) require.NoError(t, err) - assert.Equal(t, tr.TransactionID, transactionObject.ID) - assert.Equal(t, transaction.TransactionRunStateExecuting, updatedRun.State) + assert.Equal(t, tr.TestSuiteID, transactionObject.ID) + assert.Equal(t, testsuite.TestSuiteStateExecuting, updatedRun.State) assert.Len(t, tr.Steps, 1) } func TestDeleteTransactionRun(t *testing.T) { transactionRepo, transactionRunRepo, testsRepo := getRepos() - transaction, _ := getTransaction(t, transactionRepo, testsRepo) + suite, _ := getTransaction(t, transactionRepo, testsRepo) - tr, err := transactionRunRepo.CreateRun(context.TODO(), transaction.NewRun()) + tr, err := transactionRunRepo.CreateRun(context.TODO(), suite.NewRun()) require.NoError(t, err) - err = transactionRunRepo.DeleteTransactionRun(context.TODO(), tr) + err = transactionRunRepo.DeleteTestSuiteRun(context.TODO(), tr) require.NoError(t, err) - _, err = transactionRunRepo.GetTransactionRun(context.TODO(), transaction.ID, tr.ID) + _, err = transactionRunRepo.GetTestSuiteRun(context.TODO(), suite.ID, tr.ID) require.ErrorContains(t, err, "no rows in result set") } -func createTransaction(t *testing.T, repo *transaction.Repository, tran transaction.Transaction) transaction.Transaction { +func createTransaction(t *testing.T, repo *testsuite.Repository, suite testsuite.TestSuite) testsuite.TestSuite { one := 1 - tran.ID = id.GenerateID() - tran.Version = &one - for _, step := range tran.Steps { - tran.StepIDs = append(tran.StepIDs, step.ID) + suite.ID = id.GenerateID() + suite.Version = &one + for _, step := range suite.Steps { + suite.StepIDs = append(suite.StepIDs, step.ID) } - _, err := repo.Create(context.TODO(), tran) + _, err := repo.Create(context.TODO(), suite) require.NoError(t, err) - tran, err = repo.GetAugmented(context.TODO(), tran.ID) + suite, err = repo.GetAugmented(context.TODO(), suite.ID) require.NoError(t, err) - return tran + return suite } func TestListTransactionRun(t *testing.T) { transactionRepo, transactionRunRepo, testsRepo := getRepos() - t1 := createTransaction(t, transactionRepo, transaction.Transaction{ + t1 := createTransaction(t, transactionRepo, testsuite.TestSuite{ Name: "first test", Description: "description", Steps: []test.Test{ @@ -141,8 +141,8 @@ func TestListTransactionRun(t *testing.T) { }, }) - t2 := createTransaction(t, transactionRepo, transaction.Transaction{ - Name: "second transaction", + t2 := createTransaction(t, transactionRepo, testsuite.TestSuite{ + Name: "second testsuite", Description: "description", Steps: []test.Test{ createTestWithName(t, testsRepo, "first step"), @@ -159,7 +159,7 @@ func TestListTransactionRun(t *testing.T) { _, err = transactionRunRepo.CreateRun(context.TODO(), t2.NewRun()) require.NoError(t, err) - runs, err := transactionRunRepo.GetTransactionsRuns(context.TODO(), t1.ID, 20, 0) + runs, err := transactionRunRepo.GetTestSuiteRuns(context.TODO(), t1.ID, 20, 0) require.NoError(t, err) assert.Len(t, runs, 2) @@ -172,7 +172,7 @@ func TestBug(t *testing.T) { ctx := context.TODO() - transaction := createTransaction(t, transactionRepo, transaction.Transaction{ + suite := createTransaction(t, transactionRepo, testsuite.TestSuite{ Name: "first test", Description: "description", Steps: []test.Test{ @@ -181,28 +181,28 @@ func TestBug(t *testing.T) { }, }) - run1, err := transactionRunRepo.CreateRun(ctx, transaction.NewRun()) + run1, err := transactionRunRepo.CreateRun(ctx, suite.NewRun()) require.NoError(t, err) - run2, err := transactionRunRepo.CreateRun(ctx, transaction.NewRun()) + run2, err := transactionRunRepo.CreateRun(ctx, suite.NewRun()) require.NoError(t, err) - runs, err := transactionRunRepo.GetTransactionsRuns(ctx, transaction.ID, 20, 0) + runs, err := transactionRunRepo.GetTestSuiteRuns(ctx, suite.ID, 20, 0) require.NoError(t, err) assert.Equal(t, runs[0].ID, run2.ID) assert.Equal(t, runs[1].ID, run1.ID) - transaction.Name = "another thing" - _, err = transactionRepo.Update(ctx, transaction) + suite.Name = "another thing" + _, err = transactionRepo.Update(ctx, suite) require.NoError(t, err) - newTransaction, err := transactionRepo.GetAugmented(context.TODO(), transaction.ID) + newTransaction, err := transactionRepo.GetAugmented(context.TODO(), suite.ID) require.NoError(t, err) - run3, err := transactionRunRepo.CreateRun(ctx, newTransaction.NewRun()) + run3, err := transactionRunRepo.CreateRun(ctx, suite.NewRun()) require.NoError(t, err) - runs, err = transactionRunRepo.GetTransactionsRuns(ctx, newTransaction.ID, 20, 0) + runs, err = transactionRunRepo.GetTestSuiteRuns(ctx, newTransaction.ID, 20, 0) require.NoError(t, err) assert.Len(t, runs, 3) diff --git a/server/transaction/transaction_entities.go b/server/transaction/transaction_entities.go deleted file mode 100644 index 629edb1af7..0000000000 --- a/server/transaction/transaction_entities.go +++ /dev/null @@ -1,83 +0,0 @@ -package transaction - -import ( - "time" - - "github.com/kubeshop/tracetest/server/pkg/id" - "github.com/kubeshop/tracetest/server/test" -) - -const ( - TransactionResourceName = "Transaction" - TransactionResourceNamePlural = "Transactions" -) - -type Transaction struct { - ID id.ID `json:"id"` - CreatedAt *time.Time `json:"createdAt,omitempty"` - Name string `json:"name"` - Description string `json:"description"` - Version *int `json:"version,omitempty"` - StepIDs []id.ID `json:"steps"` - Steps []test.Test `json:"fullSteps,omitempty"` - Summary *test.Summary `json:"summary,omitempty"` -} - -func setVersion(t *Transaction, v int) { - t.Version = &v -} - -func (t Transaction) GetVersion() int { - if t.Version == nil { - return 0 - } - return *t.Version -} - -func setCreatedAt(t *Transaction, d time.Time) { - t.CreatedAt = &d -} - -func (t Transaction) GetCreatedAt() time.Time { - if t.CreatedAt == nil { - return time.Time{} - } - return *t.CreatedAt -} - -func (t Transaction) HasID() bool { - return t.ID != "" -} - -func (t Transaction) GetID() id.ID { - return t.ID -} - -func (t Transaction) Validate() error { - return nil -} - -func (t Transaction) NewRun() TransactionRun { - - return TransactionRun{ - TransactionID: t.ID, - TransactionVersion: t.GetVersion(), - CreatedAt: time.Now().UTC(), - State: TransactionRunStateCreated, - Steps: make([]test.Run, 0, len(t.StepIDs)), - CurrentTest: 0, - } -} - -type TransactionRunState string - -const ( - TransactionRunStateCreated TransactionRunState = "CREATED" - TransactionRunStateExecuting TransactionRunState = "EXECUTING" - TransactionRunStateFailed TransactionRunState = "FAILED" - TransactionRunStateFinished TransactionRunState = "FINISHED" -) - -func (rs TransactionRunState) IsFinal() bool { - return rs == TransactionRunStateFailed || rs == TransactionRunStateFinished -} diff --git a/testing/cli-e2etest/README.md b/testing/cli-e2etest/README.md index 493bde96d0..6576e1d2f4 100644 --- a/testing/cli-e2etest/README.md +++ b/testing/cli-e2etest/README.md @@ -26,16 +26,16 @@ The main idea is to test every CLI command against the Tracetest server with dif | `--help`, `-h` | [HelpCommand](./testscenarios/help_test.go) | | `--config` | All scenarios | -### Run Tests and Transactions +### Run Tests and TestSuites | CLI Command | Test scenarios | | ------------------------------------------------------------------ | -------------- | | `run test -f [test-definition]` | [RunTestWithGrpcTrigger](./testscenarios/test/run_test_with_grpc_trigger_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] --vars [variableset-id]` | | -| `run transaction -f [transaction-definition] --vars [variableset-definition]` | | +| `run testsuite -f [testsuite-definition]` | [RunTestSuite](./testscenarios/testsuite//run_testsuite_test.go) | +| `run testsuite -f [testsuite-definition] --vars [variableset-id]` | | +| `run testsuite -f [testsuite-definition] --vars [variableset-definition]` | | ### Resources: Config @@ -138,23 +138,23 @@ The main idea is to test every CLI command against the Tracetest server with dif | `list analyzer --output json` | [ListAnalyzer](./testscenarios/analyzer/list_analyzer_test.go) | | `list analyzer --output yaml` | [ListAnalyzer](./testscenarios/analyzer/list_analyzer_test.go) | -### Resources: Transactions +### Resources: TestSuites | CLI Command | Test scenarios | | ----------------------------------------------------------- | -------------- | -| `apply transaction -f [new-transaction-file]` | [ApplyTransaction](./testscenarios/transaction/apply_transaction_test.go) | -| `apply transaction -f [existing-transaction-file]` | [ApplyTransaction](./testscenarios/transaction/apply_transaction_test.go) | -| `delete transaction --id [existing-id]` | [DeleteTransaction](./testscenarios/transaction/delete_transaction_test.go) | -| `delete transaction --id [non-existing-id]` | [DeleteTransaction](./testscenarios/transaction/delete_transaction_test.go) | -| `get transaction --id [non-existing-id]` | [GetTransaction](./testscenarios/transaction/get_transaction_test.go), [DeleteTransaction](./testscenarios/transaction/delete_transaction_test.go) | -| `get transaction --id [existing-id] --output pretty` | [GetTransaction](./testscenarios/transaction/get_transaction_test.go) | -| `get transaction --id [existing-id] --output json` | [GetTransaction](./testscenarios/transaction/get_transaction_test.go) | -| `get transaction --id [existing-id] --output yaml` | [GetTransaction](./testscenarios/transaction/get_transaction_test.go) | -| `list transaction --output pretty` | [ListTransaction](./testscenarios/transaction/list_transactions_test.go) | -| `list transaction --output json` | [ListTransaction](./testscenarios/transaction/list_transactions_test.go) | -| `list transaction --output yaml` | [ListTransaction](./testscenarios/transaction/list_transactions_test.go) | -| `list transaction --skip 1 --take 2` | [ListTransaction](./testscenarios/transaction/list_transactions_test.go) | -| `list transaction --sortBy name --sortDirection asc` | [ListTransaction](./testscenarios/transaction/list_transactions_test.go) | +| `apply testsuite -f [new-testsuite-file]` | [ApplyTestSuite](./testscenarios/testsuite/apply_testsuite_test.go) | +| `apply testsuite -f [existing-testsuite-file]` | [ApplyTestSuite](./testscenarios/testsuite/apply_testsuite_test.go) | +| `delete testsuite --id [existing-id]` | [DeleteTestSuite](./testscenarios/testsuite/delete_testsuite_test.go) | +| `delete testsuite --id [non-existing-id]` | [DeleteTestSuite](./testscenarios/testsuite/delete_testsuite_test.go) | +| `get testsuite --id [non-existing-id]` | [GetTestSuite](./testscenarios/testsuite/get_testsuite_test.go), [DeleteTestSuite](./testscenarios/testsuite/delete_testsuite_test.go) | +| `get testsuite --id [existing-id] --output pretty` | [GetTestSuite](./testscenarios/testsuite/get_testsuite_test.go) | +| `get testsuite --id [existing-id] --output json` | [GetTestSuite](./testscenarios/testsuite/get_testsuite_test.go) | +| `get testsuite --id [existing-id] --output yaml` | [GetTestSuite](./testscenarios/testsuite/get_testsuite_test.go) | +| `list testsuite --output pretty` | [ListTestSuite](./testscenarios/testsuite/list_testsuites_test.go) | +| `list testsuite --output json` | [ListTestSuite](./testscenarios/testsuite/list_testsuites_test.go) | +| `list testsuite --output yaml` | [ListTestSuite](./testscenarios/testsuite/list_testsuites_test.go) | +| `list testsuite --skip 1 --take 2` | [ListTestSuite](./testscenarios/testsuite/list_testsuites_test.go) | +| `list testsuite --sortBy name --sortDirection asc` | [ListTestSuite](./testscenarios/testsuite/list_testsuites_test.go) | ### Resources: Tests diff --git a/testing/cli-e2etest/helpers/common.go b/testing/cli-e2etest/helpers/common.go index 4e363fffaf..2f69283aa5 100644 --- a/testing/cli-e2etest/helpers/common.go +++ b/testing/cli-e2etest/helpers/common.go @@ -98,14 +98,14 @@ func Copy(source, dst string) { } } -func RemoveIDFromTransactionFile(t *testing.T, filePath string) { +func RemoveIDFromTestSuiteFile(t *testing.T, filePath string) { fileContent, err := os.ReadFile(filePath) require.NoError(t, err) - transaction := UnmarshalYAML[types.TransactionResource](t, string(fileContent)) - transaction.Spec.ID = "" + suite := UnmarshalYAML[types.TestSuiteResource](t, string(fileContent)) + suite.Spec.ID = "" - newFileContent, err := yaml.Marshal(transaction) + newFileContent, err := yaml.Marshal(suite) require.NoError(t, err) err = os.WriteFile(filePath, newFileContent, os.ModeAppend) diff --git a/testing/cli-e2etest/testscenarios/test/run_test_test.go b/testing/cli-e2etest/testscenarios/test/run_test_test.go index 6ee037c0c5..d724ba280b 100644 --- a/testing/cli-e2etest/testscenarios/test/run_test_test.go +++ b/testing/cli-e2etest/testscenarios/test/run_test_test.go @@ -11,8 +11,8 @@ import ( "github.com/stretchr/testify/require" ) -func TestRunTransactionInsteadOfTest(t *testing.T) { - t.Run("should fail if transaction resource is selected", func(t *testing.T) { +func TestRunTestSuiteInsteadOfTest(t *testing.T) { + t.Run("should fail if test suite resource is selected", func(t *testing.T) { // setup isolated e2e environment env := environment.CreateAndStart(t) defer env.Close(t) @@ -26,14 +26,14 @@ func TestRunTransactionInsteadOfTest(t *testing.T) { // And I have my server recently created // And the datasource is already set - // When I try to run a transaction + // When I try to run a test suite // Then it should pass testFil := env.GetTestResourcePath(t, "import") - command := fmt.Sprintf("run transaction -f %s", testFil) + command := fmt.Sprintf("run testsuite -f %s", testFil) result := tracetestcli.Exec(t, command, tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 1) - require.Contains(result.StdErr, "cannot apply Test to Transaction resource") + require.Contains(result.StdErr, "cannot apply Test to TestSuite resource") }) } diff --git a/testing/cli-e2etest/testscenarios/testsuite/apply_testsuite_test.go b/testing/cli-e2etest/testscenarios/testsuite/apply_testsuite_test.go new file mode 100644 index 0000000000..a11083fc47 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/apply_testsuite_test.go @@ -0,0 +1,147 @@ +package testsuite + +import ( + "fmt" + "os" + "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 TestApplyTestSuite(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("should apply a test suite", 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 testsuite + // Then it should be applied with success + newTestSuitePath := env.GetTestResourcePath(t, "new-testsuite") + + result := tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", newTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + testsuite := helpers.UnmarshalYAML[types.TestSuiteResource](t, result.StdOut) + + require.Equal("TestSuite", testsuite.Type) + require.Equal("Qti5R3_VR", testsuite.Spec.ID) + require.Equal("New TestSuite", testsuite.Spec.Name) + require.Equal("a TestSuite", testsuite.Spec.Description) + require.Len(testsuite.Spec.Steps, 2) + require.Equal("9wtAH2_Vg", testsuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", testsuite.Spec.Steps[1]) + + // When I try to get the testsuite applied on the last step + // Then it should return it + result = tracetestcli.Exec(t, "get testsuite --id Qti5R3_VR --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + require.Equal("TestSuite", testsuite.Type) + require.Equal("Qti5R3_VR", testsuite.Spec.ID) + require.Equal("New TestSuite", testsuite.Spec.Name) + require.Equal("a TestSuite", testsuite.Spec.Description) + require.Len(testsuite.Spec.Steps, 2) + require.Equal("9wtAH2_Vg", testsuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", testsuite.Spec.Steps[1]) + + // When I try to update the last testsuite + // Then it should be applied with success + updatedNewTestSuitePath := env.GetTestResourcePath(t, "updated-new-testsuite") + + result = tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", updatedNewTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + updatedTestSuite := helpers.UnmarshalYAML[types.TestSuiteResource](t, result.StdOut) + require.Equal("TestSuite", updatedTestSuite.Type) + require.Equal("Qti5R3_VR", updatedTestSuite.Spec.ID) + require.Equal("Updated TestSuite", updatedTestSuite.Spec.Name) + require.Equal("an updated TestSuite", updatedTestSuite.Spec.Description) + require.Len(updatedTestSuite.Spec.Steps, 3) + require.Equal("9wtAH2_Vg", updatedTestSuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", updatedTestSuite.Spec.Steps[1]) + require.Equal("ajksdkasjbd", updatedTestSuite.Spec.Steps[2]) + + // When I try to get the testsuite applied on the last step + // Then it should return it + result = tracetestcli.Exec(t, "get testsuite --id Qti5R3_VR --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + updatedTestSuite = helpers.UnmarshalYAML[types.TestSuiteResource](t, result.StdOut) + require.Equal("TestSuite", updatedTestSuite.Type) + require.Equal("Qti5R3_VR", updatedTestSuite.Spec.ID) + require.Equal("Updated TestSuite", updatedTestSuite.Spec.Name) + require.Equal("an updated TestSuite", updatedTestSuite.Spec.Description) + require.Len(updatedTestSuite.Spec.Steps, 3) + require.Equal("9wtAH2_Vg", updatedTestSuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", updatedTestSuite.Spec.Steps[1]) + require.Equal("ajksdkasjbd", updatedTestSuite.Spec.Steps[2]) + + // When I try to set up a new testsuite without any id + // Then it should be applied with success and it should not update + // the steps with its ids. + testsuiteWithoutIDPath := env.GetTestResourcePath(t, "new-testsuite-without-id") + helpers.Copy(testsuiteWithoutIDPath+".tpl", testsuiteWithoutIDPath) + + helpers.RemoveIDFromTestSuiteFile(t, testsuiteWithoutIDPath) + + testsuiteWithoutIDResult := tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", testsuiteWithoutIDPath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, testsuiteWithoutIDResult, 0) + + content, err := os.ReadFile(testsuiteWithoutIDPath) + require.NoError(err) + + testsuiteWithoutID := helpers.UnmarshalYAML[types.TestSuiteResource](t, string(content)) + + require.Equal("TestSuite", testsuiteWithoutID.Type) + require.NotEmpty(testsuiteWithoutID.Spec.ID) + require.Equal("New TestSuite", testsuiteWithoutID.Spec.Name) + require.Equal("a TestSuite", testsuiteWithoutID.Spec.Description) + require.Len(testsuiteWithoutID.Spec.Steps, 2) + require.Equal("./testsuite-step-1.yaml", testsuiteWithoutID.Spec.Steps[0]) + require.Equal("./testsuite-step-2.yaml", testsuiteWithoutID.Spec.Steps[1]) + }) + + t.Run("should apply a legacy transaction", 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 legacy transaction + // Then it should be applied with success + newTestSuitePath := env.GetTestResourcePath(t, "legacy-transaction") + + result := tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", newTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + require.Contains(result.StdOut, "TestSuite") + require.Contains(result.StdOut, "Qti5R3_VR") + require.Contains(result.StdOut, "New Transaction") + require.Contains(result.StdOut, "a Transaction") + require.Contains(result.StdOut, "9wtAH2_Vg") + require.Contains(result.StdOut, "ajksdkasjbd") + + // When I try to get the testsuite applied on the last step + // Then it should return it + result = tracetestcli.Exec(t, "get transaction --id Qti5R3_VR --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + require.Contains(result.StdOut, "TestSuite") + require.Contains(result.StdOut, "Qti5R3_VR") + require.Contains(result.StdOut, "New Transaction") + require.Contains(result.StdOut, "a Transaction") + require.Contains(result.StdOut, "9wtAH2_Vg") + require.Contains(result.StdOut, "ajksdkasjbd") + }) +} diff --git a/testing/cli-e2etest/testscenarios/testsuite/delete_testsuite_test.go b/testing/cli-e2etest/testscenarios/testsuite/delete_testsuite_test.go new file mode 100644 index 0000000000..b0da478fc4 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/delete_testsuite_test.go @@ -0,0 +1,50 @@ +package testsuite + +import ( + "fmt" + "testing" + + "github.com/kubeshop/tracetest/cli-e2etest/environment" + "github.com/kubeshop/tracetest/cli-e2etest/helpers" + "github.com/kubeshop/tracetest/cli-e2etest/tracetestcli" + "github.com/stretchr/testify/require" +) + +func TestDeleteTestSuite(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 delete a TestSuite that don't exist + // Then it should return an error and say that this resource does not exist + result := tracetestcli.Exec(t, "delete testsuite --id dont-exist", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 1) + require.Contains(result.StdErr, "Resource testsuite with ID dont-exist not found") + + // When I try to set up a new testsuite + // Then it should be applied with success + newTestSuitePath := env.GetTestResourcePath(t, "new-testsuite") + + result = tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", newTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + // When I try to delete the testsuite + // Then it should delete with success + result = tracetestcli.Exec(t, "delete testsuite --id Qti5R3_VR", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + require.Contains(result.StdOut, "✔ Testsuite successfully deleted") + + // When I try to get a TestSuite again + // Then it should return a message saying that the testsuite was not found + result = tracetestcli.Exec(t, "delete testsuite --id Qti5R3_VR", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 1) + require.Contains(result.StdErr, "Resource testsuite with ID Qti5R3_VR not found") +} diff --git a/testing/cli-e2etest/testscenarios/testsuite/get_testsuite_test.go b/testing/cli-e2etest/testscenarios/testsuite/get_testsuite_test.go new file mode 100644 index 0000000000..218b065173 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/get_testsuite_test.go @@ -0,0 +1,121 @@ +package testsuite + +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 addGetTestSuitePreReqs(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 testsuite + // Then it should be applied with success + newTestSuitePath := env.GetTestResourcePath(t, "new-testsuite") + + result := tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", newTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) +} + +func TestGetTestSuite(t *testing.T) { + // instantiate require with testing helper + require := require.New(t) + + env := environment.CreateAndStart(t) + defer env.Close(t) + + cliConfig := env.GetCLIConfigPath(t) + + t.Run("get with no testsuite initialized", func(t *testing.T) { + // Given I am a Tracetest CLI user + // And I have my server recently created + // And no testsuite registered + + // When I try to get a TestSuite on yaml mode + // Then it should return a error message + result := tracetestcli.Exec(t, "get testsuite --id no-id --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + require.Contains(result.StdOut, "Resource testsuite with ID no-id not found") + }) + + addGetTestSuitePreReqs(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 a TestSuite already set + + // When I try to get a TestSuite on yaml mode + // Then it should print a YAML + result := tracetestcli.Exec(t, "get testsuite --id Qti5R3_VR --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + testsuite := helpers.UnmarshalYAML[types.TestSuiteResource](t, result.StdOut) + + require.Equal("TestSuite", testsuite.Type) + require.Equal("Qti5R3_VR", testsuite.Spec.ID) + require.Equal("New TestSuite", testsuite.Spec.Name) + require.Equal("a TestSuite", testsuite.Spec.Description) + require.Len(testsuite.Spec.Steps, 2) + require.Equal("9wtAH2_Vg", testsuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", testsuite.Spec.Steps[1]) + }) + + 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 a TestSuite already set + + // When I try to get a TestSuite on json mode + // Then it should print a json + result := tracetestcli.Exec(t, "get testsuite --id Qti5R3_VR --output json", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + // it should return an augmented resource on get + testsuite := helpers.UnmarshalJSON[types.AugmentedTestSuiteResource](t, result.StdOut) + + require.Equal("TestSuite", testsuite.Type) + require.Equal("Qti5R3_VR", testsuite.Spec.ID) + require.Equal("New TestSuite", testsuite.Spec.Name) + require.Equal("a TestSuite", testsuite.Spec.Description) + require.Len(testsuite.Spec.Steps, 2) + require.Equal("9wtAH2_Vg", testsuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", testsuite.Spec.Steps[1]) + require.Equal(0, testsuite.Spec.Summary.Runs) + require.Equal(0, testsuite.Spec.Summary.LastRun.Fails) + require.Equal(0, testsuite.Spec.Summary.LastRun.Passes) + }) + + 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 a TestSuite already set + + // When I try to get a TestSuite on pretty mode + // Then it should print a table with 4 lines printed: header, separator, testsuite item and empty line + result := tracetestcli.Exec(t, "get testsuite --id Qti5R3_VR --output pretty", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + parsedTable := helpers.UnmarshalTable(t, result.StdOut) + require.Len(parsedTable, 1) + + singleLine := parsedTable[0] + + require.Equal("Qti5R3_VR", singleLine["ID"]) + require.Equal("New TestSuite", singleLine["NAME"]) + require.Equal("1", singleLine["VERSION"]) + require.Equal("2", singleLine["STEPS"]) + require.Equal("0", singleLine["RUNS"]) + require.Equal("", singleLine["LAST RUN TIME"]) + require.Equal("0", singleLine["LAST RUN SUCCESSES"]) + require.Equal("0", singleLine["LAST RUN FAILURES"]) + }) +} diff --git a/testing/cli-e2etest/testscenarios/testsuite/list_testsuite_test.go b/testing/cli-e2etest/testscenarios/testsuite/list_testsuite_test.go new file mode 100644 index 0000000000..5d31f9ed12 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/list_testsuite_test.go @@ -0,0 +1,261 @@ +package testsuite + +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 addListTestSuitePreReqs(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 + // Then it should be applied with success + newTestSuitePath := env.GetTestResourcePath(t, "new-testsuite") + + result := tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", newTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + // When I try to set up a another environment + // Then it should be applied with success + anotherTestSuitePath := env.GetTestResourcePath(t, "another-testsuite") + + result = tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", anotherTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + // When I try to set up a third environment + // Then it should be applied with success + oneMoreTestSuitePath := env.GetTestResourcePath(t, "one-more-testsuite") + + result = tracetestcli.Exec(t, fmt.Sprintf("apply testsuite --file %s", oneMoreTestSuitePath), tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) +} + +func TestListTestSuites(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("list no testsuites", 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 testsuite --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + testsuites := helpers.UnmarshalYAMLSequence[types.AugmentedTestSuiteResource](t, result.StdOut) + require.Len(testsuites, 0) + }) + + addListTestSuitePreReqs(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 testsuites by an invalid field + // Then I should receive an error + result := tracetestcli.Exec(t, "list testsuite --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 + }) + + t.Run("list with YAML format", func(t *testing.T) { + // Given I am a Tracetest CLI user + // And I have my server recently created + + // When I try to list these testsuites by a valid field and in YAML format + // Then I should receive three testsuites + result := tracetestcli.Exec(t, "list testsuite --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + testsuites := helpers.UnmarshalYAMLSequence[types.AugmentedTestSuiteResource](t, result.StdOut) + require.Len(testsuites, 3) + + anotherTestSuite := testsuites[0] + require.Equal("TestSuite", anotherTestSuite.Type) + require.Equal("asuhfdkj", anotherTestSuite.Spec.ID) + require.Equal("Another TestSuite", anotherTestSuite.Spec.Name) + require.Equal("another TestSuite", anotherTestSuite.Spec.Description) + require.Equal(0, anotherTestSuite.Spec.Summary.Runs) + require.Equal(0, anotherTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, anotherTestSuite.Spec.Summary.LastRun.Passes) + require.Len(anotherTestSuite.Spec.Steps, 4) + require.Equal("9wtAH2_Vg", anotherTestSuite.Spec.Steps[0]) + require.Equal("9wtAH2_Vg", anotherTestSuite.Spec.Steps[1]) + require.Equal("ajksdkasjbd", anotherTestSuite.Spec.Steps[2]) + require.Equal("ajksdkasjbd", anotherTestSuite.Spec.Steps[3]) + + newTestSuite := testsuites[1] + require.Equal("TestSuite", newTestSuite.Type) + require.Equal("Qti5R3_VR", newTestSuite.Spec.ID) + require.Equal("New TestSuite", newTestSuite.Spec.Name) + require.Equal("a TestSuite", newTestSuite.Spec.Description) + require.Equal(0, newTestSuite.Spec.Summary.Runs) + require.Equal(0, newTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, newTestSuite.Spec.Summary.LastRun.Passes) + require.Len(newTestSuite.Spec.Steps, 2) + require.Equal("9wtAH2_Vg", newTestSuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", newTestSuite.Spec.Steps[1]) + + oneMoreTestSuite := testsuites[2] + require.Equal("TestSuite", oneMoreTestSuite.Type) + require.Equal("i2ug34j", oneMoreTestSuite.Spec.ID) + require.Equal("One More TestSuite", oneMoreTestSuite.Spec.Name) + require.Equal("one more TestSuite", oneMoreTestSuite.Spec.Description) + require.Equal(0, oneMoreTestSuite.Spec.Summary.Runs) + require.Equal(0, oneMoreTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, oneMoreTestSuite.Spec.Summary.LastRun.Passes) + require.Len(oneMoreTestSuite.Spec.Steps, 3) + require.Equal("9wtAH2_Vg", oneMoreTestSuite.Spec.Steps[0]) + require.Equal("9wtAH2_Vg", oneMoreTestSuite.Spec.Steps[1]) + require.Equal("ajksdkasjbd", oneMoreTestSuite.Spec.Steps[2]) + }) + + t.Run("list with JSON format", func(t *testing.T) { + // Given I am a Tracetest CLI user + // And I have my server recently created + + // When I try to list these testsuites by a valid field and in JSON format + // Then I should receive three testsuites + result := tracetestcli.Exec(t, "list testsuite --sortBy name --sortDirection asc --output json", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + testsuites := helpers.UnmarshalJSON[types.ResourceList[types.AugmentedTestSuiteResource]](t, result.StdOut) + require.Len(testsuites.Items, 3) + require.Equal(len(testsuites.Items), testsuites.Count) + + anotherTestSuite := testsuites.Items[0] + require.Equal("TestSuite", anotherTestSuite.Type) + require.Equal("asuhfdkj", anotherTestSuite.Spec.ID) + require.Equal("Another TestSuite", anotherTestSuite.Spec.Name) + require.Equal("another TestSuite", anotherTestSuite.Spec.Description) + require.Equal(0, anotherTestSuite.Spec.Summary.Runs) + require.Equal(0, anotherTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, anotherTestSuite.Spec.Summary.LastRun.Passes) + require.Len(anotherTestSuite.Spec.Steps, 4) + require.Equal("9wtAH2_Vg", anotherTestSuite.Spec.Steps[0]) + require.Equal("9wtAH2_Vg", anotherTestSuite.Spec.Steps[1]) + require.Equal("ajksdkasjbd", anotherTestSuite.Spec.Steps[2]) + require.Equal("ajksdkasjbd", anotherTestSuite.Spec.Steps[3]) + + newTestSuite := testsuites.Items[1] + require.Equal("TestSuite", newTestSuite.Type) + require.Equal("Qti5R3_VR", newTestSuite.Spec.ID) + require.Equal("New TestSuite", newTestSuite.Spec.Name) + require.Equal("a TestSuite", newTestSuite.Spec.Description) + require.Equal(0, newTestSuite.Spec.Summary.Runs) + require.Equal(0, newTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, newTestSuite.Spec.Summary.LastRun.Passes) + require.Len(newTestSuite.Spec.Steps, 2) + require.Equal("9wtAH2_Vg", newTestSuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", newTestSuite.Spec.Steps[1]) + + oneMoreTestSuite := testsuites.Items[2] + require.Equal("TestSuite", oneMoreTestSuite.Type) + require.Equal("i2ug34j", oneMoreTestSuite.Spec.ID) + require.Equal("One More TestSuite", oneMoreTestSuite.Spec.Name) + require.Equal("one more TestSuite", oneMoreTestSuite.Spec.Description) + require.Equal(0, oneMoreTestSuite.Spec.Summary.Runs) + require.Equal(0, oneMoreTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, oneMoreTestSuite.Spec.Summary.LastRun.Passes) + require.Len(oneMoreTestSuite.Spec.Steps, 3) + require.Equal("9wtAH2_Vg", oneMoreTestSuite.Spec.Steps[0]) + require.Equal("9wtAH2_Vg", oneMoreTestSuite.Spec.Steps[1]) + require.Equal("ajksdkasjbd", oneMoreTestSuite.Spec.Steps[2]) + }) + + t.Run("list with pretty format", func(t *testing.T) { + // Given I am a Tracetest CLI user + // And I have my server recently created + + // When I try to list these testsuites by a valid field and in pretty format + // Then it should print a table with 6 lines printed: header, separator, three testsuites and empty line + result := tracetestcli.Exec(t, "list testsuite --sortBy name --sortDirection asc --output pretty", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + parsedTable := helpers.UnmarshalTable(t, result.StdOut) + require.Len(parsedTable, 3) + + firstLine := parsedTable[0] + require.Equal("asuhfdkj", firstLine["ID"]) + require.Equal("Another TestSuite", firstLine["NAME"]) + require.Equal("1", firstLine["VERSION"]) + require.Equal("4", firstLine["STEPS"]) + require.Equal("0", firstLine["RUNS"]) + require.Equal("", firstLine["LAST RUN TIME"]) + require.Equal("0", firstLine["LAST RUN SUCCESSES"]) + require.Equal("0", firstLine["LAST RUN FAILURES"]) + + secondLine := parsedTable[1] + require.Equal("Qti5R3_VR", secondLine["ID"]) + require.Equal("New TestSuite", secondLine["NAME"]) + require.Equal("1", secondLine["VERSION"]) + require.Equal("2", secondLine["STEPS"]) + require.Equal("0", secondLine["RUNS"]) + require.Equal("", secondLine["LAST RUN TIME"]) + require.Equal("0", secondLine["LAST RUN SUCCESSES"]) + require.Equal("0", secondLine["LAST RUN FAILURES"]) + + thirdLine := parsedTable[2] + require.Equal("i2ug34j", thirdLine["ID"]) + require.Equal("One More TestSuite", thirdLine["NAME"]) + require.Equal("1", thirdLine["VERSION"]) + require.Equal("3", thirdLine["STEPS"]) + require.Equal("0", thirdLine["RUNS"]) + require.Equal("", thirdLine["LAST RUN TIME"]) + require.Equal("0", thirdLine["LAST RUN SUCCESSES"]) + require.Equal("0", thirdLine["LAST RUN FAILURES"]) + }) + + t.Run("list with YAML format skipping the first and taking two items", func(t *testing.T) { + // Given I am a Tracetest CLI user + // And I have my server recently created + + // When I try to list these testsuites by a valid field, paging options and in YAML format + // Then I should receive two testsuites + result := tracetestcli.Exec(t, "list testsuite --sortBy name --sortDirection asc --skip 1 --take 2 --output yaml", tracetestcli.WithCLIConfig(cliConfig)) + helpers.RequireExitCodeEqual(t, result, 0) + + testsuites := helpers.UnmarshalYAMLSequence[types.AugmentedTestSuiteResource](t, result.StdOut) + require.Len(testsuites, 2) + + newTestSuite := testsuites[0] + require.Equal("TestSuite", newTestSuite.Type) + require.Equal("Qti5R3_VR", newTestSuite.Spec.ID) + require.Equal("New TestSuite", newTestSuite.Spec.Name) + require.Equal("a TestSuite", newTestSuite.Spec.Description) + require.Equal(0, newTestSuite.Spec.Summary.Runs) + require.Equal(0, newTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, newTestSuite.Spec.Summary.LastRun.Passes) + require.Len(newTestSuite.Spec.Steps, 2) + require.Equal("9wtAH2_Vg", newTestSuite.Spec.Steps[0]) + require.Equal("ajksdkasjbd", newTestSuite.Spec.Steps[1]) + + oneMoreTestSuite := testsuites[1] + require.Equal("TestSuite", oneMoreTestSuite.Type) + require.Equal("i2ug34j", oneMoreTestSuite.Spec.ID) + require.Equal("One More TestSuite", oneMoreTestSuite.Spec.Name) + require.Equal("one more TestSuite", oneMoreTestSuite.Spec.Description) + require.Equal(0, oneMoreTestSuite.Spec.Summary.Runs) + require.Equal(0, oneMoreTestSuite.Spec.Summary.LastRun.Fails) + require.Equal(0, oneMoreTestSuite.Spec.Summary.LastRun.Passes) + require.Len(oneMoreTestSuite.Spec.Steps, 3) + require.Equal("9wtAH2_Vg", oneMoreTestSuite.Spec.Steps[0]) + require.Equal("9wtAH2_Vg", oneMoreTestSuite.Spec.Steps[1]) + require.Equal("ajksdkasjbd", oneMoreTestSuite.Spec.Steps[2]) + }) +} diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/.gitignore b/testing/cli-e2etest/testscenarios/testsuite/resources/.gitignore new file mode 100644 index 0000000000..0348c5c7ea --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/.gitignore @@ -0,0 +1 @@ +new-testsuite-without-id.yaml diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/another-testsuite.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/another-testsuite.yaml new file mode 100644 index 0000000000..8cbc9e9bd8 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/another-testsuite.yaml @@ -0,0 +1,10 @@ +type: TestSuite +spec: + id: asuhfdkj + name: Another TestSuite + description: another TestSuite + steps: + - ./testsuite-step-1.yaml + - ./testsuite-step-1.yaml + - ./testsuite-step-2.yaml + - ./testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/legacy-transaction.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/legacy-transaction.yaml new file mode 100644 index 0000000000..e4ecab65dd --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/legacy-transaction.yaml @@ -0,0 +1,8 @@ +type: Transaction +spec: + id: Qti5R3_VR + name: New Transaction + description: a Transaction + steps: + - ./testsuite-step-1.yaml + - ./testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/new-testsuite-without-id.yaml.tpl b/testing/cli-e2etest/testscenarios/testsuite/resources/new-testsuite-without-id.yaml.tpl new file mode 100644 index 0000000000..ea97b8c8e7 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/new-testsuite-without-id.yaml.tpl @@ -0,0 +1,7 @@ +type: TestSuite +spec: + name: New TestSuite + description: a TestSuite + steps: + - ./testsuite-step-1.yaml + - ./testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/new-testsuite.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/new-testsuite.yaml new file mode 100644 index 0000000000..86f83d6c78 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/new-testsuite.yaml @@ -0,0 +1,8 @@ +type: TestSuite +spec: + id: Qti5R3_VR + name: New TestSuite + description: a TestSuite + steps: + - ./testsuite-step-1.yaml + - ./testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/one-more-testsuite.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/one-more-testsuite.yaml new file mode 100644 index 0000000000..67772ed0d3 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/one-more-testsuite.yaml @@ -0,0 +1,9 @@ +type: TestSuite +spec: + id: i2ug34j + name: One More TestSuite + description: one more TestSuite + steps: + - ./testsuite-step-1.yaml + - ./testsuite-step-1.yaml + - ./testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/transaction-step-1.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/testsuite-step-1.yaml similarity index 100% rename from testing/cli-e2etest/testscenarios/transaction/resources/transaction-step-1.yaml rename to testing/cli-e2etest/testscenarios/testsuite/resources/testsuite-step-1.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/transaction-step-2.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/testsuite-step-2.yaml similarity index 100% rename from testing/cli-e2etest/testscenarios/transaction/resources/transaction-step-2.yaml rename to testing/cli-e2etest/testscenarios/testsuite/resources/testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/testsuite-to-run.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/testsuite-to-run.yaml new file mode 100644 index 0000000000..1f12198978 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/testsuite-to-run.yaml @@ -0,0 +1,8 @@ +type: TestSuite +spec: + id: k1ug23k + name: TestSuite To Run + description: a TestSuite to run + steps: + - ./testsuite-step-1.yaml + - ./testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/testsuite/resources/updated-new-testsuite.yaml b/testing/cli-e2etest/testscenarios/testsuite/resources/updated-new-testsuite.yaml new file mode 100644 index 0000000000..a4e8f07322 --- /dev/null +++ b/testing/cli-e2etest/testscenarios/testsuite/resources/updated-new-testsuite.yaml @@ -0,0 +1,9 @@ +type: TestSuite +spec: + id: Qti5R3_VR + name: Updated TestSuite + description: an updated TestSuite + steps: + - ./testsuite-step-1.yaml + - ./testsuite-step-2.yaml + - ./testsuite-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/run_transaction_test.go b/testing/cli-e2etest/testscenarios/testsuite/run_testsuite_test.go similarity index 51% rename from testing/cli-e2etest/testscenarios/transaction/run_transaction_test.go rename to testing/cli-e2etest/testscenarios/testsuite/run_testsuite_test.go index 35d9faa907..c1e9f78e8d 100644 --- a/testing/cli-e2etest/testscenarios/transaction/run_transaction_test.go +++ b/testing/cli-e2etest/testscenarios/testsuite/run_testsuite_test.go @@ -1,4 +1,4 @@ -package transaction +package testsuite import ( "fmt" @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestRunTransaction(t *testing.T) { +func TestRunTestSuite(t *testing.T) { t.Run("should fail if test resource is selected", func(t *testing.T) { // setup isolated e2e environment env := environment.CreateAndStart(t) @@ -25,14 +25,14 @@ func TestRunTransaction(t *testing.T) { // And I have my server recently created // And the datasource is already set - // When I try to run a transaction + // When I try to run a TestSuite // Then it should pass - transactionFile := env.GetTestResourcePath(t, "transaction-to-run") + testsuiteFile := env.GetTestResourcePath(t, "testsuite-to-run") - command := fmt.Sprintf("run test -f %s", transactionFile) + command := fmt.Sprintf("run test -f %s", testsuiteFile) result := tracetestcli.Exec(t, command, tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 1) - require.Contains(result.StdErr, "cannot apply Transaction to Test resource") + require.Contains(result.StdErr, "cannot apply TestSuite to Test resource") }) t.Run("should pass", func(t *testing.T) { @@ -49,15 +49,38 @@ func TestRunTransaction(t *testing.T) { // And I have my server recently created // And the datasource is already set - // When I try to run a transaction + // When I try to run a TestSuite // Then it should pass - transactionFile := env.GetTestResourcePath(t, "transaction-to-run") + testsuiteFile := env.GetTestResourcePath(t, "testsuite-to-run") - command := fmt.Sprintf("run transaction -f %s", transactionFile) + command := fmt.Sprintf("run testsuite -f %s", testsuiteFile) result := tracetestcli.Exec(t, command, tracetestcli.WithCLIConfig(cliConfig)) helpers.RequireExitCodeEqual(t, result, 0) - require.Contains(result.StdOut, "Transaction To Run") // transaction name - require.Contains(result.StdOut, "Pokeshop - Add") // first test + require.Contains(result.StdOut, "TestSuite To Run") // testsuite name + require.Contains(result.StdOut, "Pokeshop - Add") // first test + require.Contains(result.StdOut, "✔ It should add a Pokemon correctly") + require.Contains(result.StdOut, "✔ It should save the correct data") + require.Contains(result.StdOut, "Pokeshop - Get") // second test + require.Contains(result.StdOut, "✔ It should Get Pokemons correctly") + }) + + t.Run("should run a legacy transaction", func(t *testing.T) { + env := environment.CreateAndStart(t, environment.WithDataStoreEnabled(), environment.WithPokeshop()) + defer env.Close(t) + + cliConfig := env.GetCLIConfigPath(t) + + // instantiate require with testing helper + require := require.New(t) + + testsuiteFile := env.GetTestResourcePath(t, "legacy-transaction") + + command := fmt.Sprintf("run transaction -f %s", testsuiteFile) + result := tracetestcli.Exec(t, command, tracetestcli.WithCLIConfig(cliConfig)) + + helpers.RequireExitCodeEqual(t, result, 0) + require.Contains(result.StdOut, "New Transaction") // testsuite name + require.Contains(result.StdOut, "Pokeshop - Add") // first test require.Contains(result.StdOut, "✔ It should add a Pokemon correctly") require.Contains(result.StdOut, "✔ It should save the correct data") require.Contains(result.StdOut, "Pokeshop - Get") // second test diff --git a/testing/cli-e2etest/testscenarios/transaction/apply_transaction_test.go b/testing/cli-e2etest/testscenarios/transaction/apply_transaction_test.go deleted file mode 100644 index 7cee97e738..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/apply_transaction_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package transaction - -import ( - "fmt" - "os" - "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 TestApplyTransaction(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 transaction - // Then it should be applied with success - newTransactionPath := env.GetTestResourcePath(t, "new-transaction") - - result := tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", newTransactionPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - transaction := helpers.UnmarshalYAML[types.TransactionResource](t, result.StdOut) - - require.Equal("Transaction", transaction.Type) - require.Equal("Qti5R3_VR", transaction.Spec.ID) - require.Equal("New Transaction", transaction.Spec.Name) - require.Equal("a transaction", transaction.Spec.Description) - require.Len(transaction.Spec.Steps, 2) - require.Equal("9wtAH2_Vg", transaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", transaction.Spec.Steps[1]) - - // When I try to get the transaction applied on the last step - // Then it should return it - result = tracetestcli.Exec(t, "get transaction --id Qti5R3_VR --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - require.Equal("Transaction", transaction.Type) - require.Equal("Qti5R3_VR", transaction.Spec.ID) - require.Equal("New Transaction", transaction.Spec.Name) - require.Equal("a transaction", transaction.Spec.Description) - require.Len(transaction.Spec.Steps, 2) - require.Equal("9wtAH2_Vg", transaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", transaction.Spec.Steps[1]) - - // When I try to update the last transaction - // Then it should be applied with success - updatedNewTransactionPath := env.GetTestResourcePath(t, "updated-new-transaction") - - result = tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", updatedNewTransactionPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - updatedTransaction := helpers.UnmarshalYAML[types.TransactionResource](t, result.StdOut) - require.Equal("Transaction", updatedTransaction.Type) - require.Equal("Qti5R3_VR", updatedTransaction.Spec.ID) - require.Equal("Updated Transaction", updatedTransaction.Spec.Name) - require.Equal("an updated transaction", updatedTransaction.Spec.Description) - require.Len(updatedTransaction.Spec.Steps, 3) - require.Equal("9wtAH2_Vg", updatedTransaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", updatedTransaction.Spec.Steps[1]) - require.Equal("ajksdkasjbd", updatedTransaction.Spec.Steps[2]) - - // When I try to get the transaction applied on the last step - // Then it should return it - result = tracetestcli.Exec(t, "get transaction --id Qti5R3_VR --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - updatedTransaction = helpers.UnmarshalYAML[types.TransactionResource](t, result.StdOut) - require.Equal("Transaction", updatedTransaction.Type) - require.Equal("Qti5R3_VR", updatedTransaction.Spec.ID) - require.Equal("Updated Transaction", updatedTransaction.Spec.Name) - require.Equal("an updated transaction", updatedTransaction.Spec.Description) - require.Len(updatedTransaction.Spec.Steps, 3) - require.Equal("9wtAH2_Vg", updatedTransaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", updatedTransaction.Spec.Steps[1]) - require.Equal("ajksdkasjbd", updatedTransaction.Spec.Steps[2]) - - // When I try to set up a new transaction without any id - // Then it should be applied with success and it should not update - // the steps with its ids. - transactionWithoutIDPath := env.GetTestResourcePath(t, "new-transaction-without-id") - helpers.Copy(transactionWithoutIDPath+".tpl", transactionWithoutIDPath) - - helpers.RemoveIDFromTransactionFile(t, transactionWithoutIDPath) - - transactionWithoutIDResult := tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", transactionWithoutIDPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, transactionWithoutIDResult, 0) - - content, err := os.ReadFile(transactionWithoutIDPath) - require.NoError(err) - - transactionWithoutID := helpers.UnmarshalYAML[types.TransactionResource](t, string(content)) - - require.Equal("Transaction", transactionWithoutID.Type) - require.NotEmpty(transactionWithoutID.Spec.ID) - require.Equal("New Transaction", transactionWithoutID.Spec.Name) - require.Equal("a transaction", transactionWithoutID.Spec.Description) - require.Len(transactionWithoutID.Spec.Steps, 2) - require.Equal("./transaction-step-1.yaml", transactionWithoutID.Spec.Steps[0]) - require.Equal("./transaction-step-2.yaml", transactionWithoutID.Spec.Steps[1]) -} diff --git a/testing/cli-e2etest/testscenarios/transaction/delete_transaction_test.go b/testing/cli-e2etest/testscenarios/transaction/delete_transaction_test.go deleted file mode 100644 index 611c2a9260..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/delete_transaction_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package transaction - -import ( - "fmt" - "testing" - - "github.com/kubeshop/tracetest/cli-e2etest/environment" - "github.com/kubeshop/tracetest/cli-e2etest/helpers" - "github.com/kubeshop/tracetest/cli-e2etest/tracetestcli" - "github.com/stretchr/testify/require" -) - -func TestDeleteTransaction(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 delete a transaction that don't exist - // Then it should return an error and say that this resource does not exist - result := tracetestcli.Exec(t, "delete transaction --id dont-exist", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 1) - require.Contains(result.StdErr, "Resource transaction with ID dont-exist not found") - - // When I try to set up a new transaction - // Then it should be applied with success - newTransactionPath := env.GetTestResourcePath(t, "new-transaction") - - result = tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", newTransactionPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - // When I try to delete the transaction - // Then it should delete with success - result = tracetestcli.Exec(t, "delete transaction --id Qti5R3_VR", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - require.Contains(result.StdOut, "✔ Transaction successfully deleted") - - // When I try to get a transaction again - // Then it should return a message saying that the transaction was not found - result = tracetestcli.Exec(t, "delete transaction --id Qti5R3_VR", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 1) - require.Contains(result.StdErr, "Resource transaction with ID Qti5R3_VR not found") -} diff --git a/testing/cli-e2etest/testscenarios/transaction/get_transaction_test.go b/testing/cli-e2etest/testscenarios/transaction/get_transaction_test.go deleted file mode 100644 index fe3cb9c887..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/get_transaction_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package transaction - -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 addGetTransactionPreReqs(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 transaction - // Then it should be applied with success - newTransactionPath := env.GetTestResourcePath(t, "new-transaction") - - result := tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", newTransactionPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) -} - -func TestGetTransaction(t *testing.T) { - // instantiate require with testing helper - require := require.New(t) - - env := environment.CreateAndStart(t) - defer env.Close(t) - - cliConfig := env.GetCLIConfigPath(t) - - t.Run("get with no transaction initialized", func(t *testing.T) { - // Given I am a Tracetest CLI user - // And I have my server recently created - // And no transaction registered - - // When I try to get a transaction on yaml mode - // Then it should return a error message - result := tracetestcli.Exec(t, "get transaction --id no-id --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - require.Contains(result.StdOut, "Resource transaction with ID no-id not found") - }) - - addGetTransactionPreReqs(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 a transaction already set - - // When I try to get a transaction on yaml mode - // Then it should print a YAML - result := tracetestcli.Exec(t, "get transaction --id Qti5R3_VR --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - transaction := helpers.UnmarshalYAML[types.TransactionResource](t, result.StdOut) - - require.Equal("Transaction", transaction.Type) - require.Equal("Qti5R3_VR", transaction.Spec.ID) - require.Equal("New Transaction", transaction.Spec.Name) - require.Equal("a transaction", transaction.Spec.Description) - require.Len(transaction.Spec.Steps, 2) - require.Equal("9wtAH2_Vg", transaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", transaction.Spec.Steps[1]) - }) - - 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 a transaction already set - - // When I try to get a transaction on json mode - // Then it should print a json - result := tracetestcli.Exec(t, "get transaction --id Qti5R3_VR --output json", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - // it should return an augmented resource on get - transaction := helpers.UnmarshalJSON[types.AugmentedTransactionResource](t, result.StdOut) - - require.Equal("Transaction", transaction.Type) - require.Equal("Qti5R3_VR", transaction.Spec.ID) - require.Equal("New Transaction", transaction.Spec.Name) - require.Equal("a transaction", transaction.Spec.Description) - require.Len(transaction.Spec.Steps, 2) - require.Equal("9wtAH2_Vg", transaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", transaction.Spec.Steps[1]) - require.Equal(0, transaction.Spec.Summary.Runs) - require.Equal(0, transaction.Spec.Summary.LastRun.Fails) - require.Equal(0, transaction.Spec.Summary.LastRun.Passes) - }) - - 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 a transaction already set - - // When I try to get a transaction on pretty mode - // Then it should print a table with 4 lines printed: header, separator, transaction item and empty line - result := tracetestcli.Exec(t, "get transaction --id Qti5R3_VR --output pretty", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - parsedTable := helpers.UnmarshalTable(t, result.StdOut) - require.Len(parsedTable, 1) - - singleLine := parsedTable[0] - - require.Equal("Qti5R3_VR", singleLine["ID"]) - require.Equal("New Transaction", singleLine["NAME"]) - require.Equal("1", singleLine["VERSION"]) - require.Equal("2", singleLine["STEPS"]) - require.Equal("0", singleLine["RUNS"]) - require.Equal("", singleLine["LAST RUN TIME"]) - require.Equal("0", singleLine["LAST RUN SUCCESSES"]) - require.Equal("0", singleLine["LAST RUN FAILURES"]) - }) -} diff --git a/testing/cli-e2etest/testscenarios/transaction/list_transactions_test.go b/testing/cli-e2etest/testscenarios/transaction/list_transactions_test.go deleted file mode 100644 index 06872b792a..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/list_transactions_test.go +++ /dev/null @@ -1,261 +0,0 @@ -package transaction - -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 addListTransactionPreReqs(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 - // Then it should be applied with success - newTransactionPath := env.GetTestResourcePath(t, "new-transaction") - - result := tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", newTransactionPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - // When I try to set up a another environment - // Then it should be applied with success - anotherTransactionPath := env.GetTestResourcePath(t, "another-transaction") - - result = tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", anotherTransactionPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - // When I try to set up a third environment - // Then it should be applied with success - oneMoreTransactionPath := env.GetTestResourcePath(t, "one-more-transaction") - - result = tracetestcli.Exec(t, fmt.Sprintf("apply transaction --file %s", oneMoreTransactionPath), tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) -} - -func TestListTransactions(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("list no transactions", 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 transaction --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - transactions := helpers.UnmarshalYAMLSequence[types.AugmentedTransactionResource](t, result.StdOut) - require.Len(transactions, 0) - }) - - addListTransactionPreReqs(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 transactions by an invalid field - // Then I should receive an error - result := tracetestcli.Exec(t, "list transaction --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 - }) - - t.Run("list with YAML format", func(t *testing.T) { - // Given I am a Tracetest CLI user - // And I have my server recently created - - // When I try to list these transactions by a valid field and in YAML format - // Then I should receive three transactions - result := tracetestcli.Exec(t, "list transaction --sortBy name --sortDirection asc --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - transactions := helpers.UnmarshalYAMLSequence[types.AugmentedTransactionResource](t, result.StdOut) - require.Len(transactions, 3) - - anotherTransaction := transactions[0] - require.Equal("Transaction", anotherTransaction.Type) - require.Equal("asuhfdkj", anotherTransaction.Spec.ID) - require.Equal("Another Transaction", anotherTransaction.Spec.Name) - require.Equal("another transaction", anotherTransaction.Spec.Description) - require.Equal(0, anotherTransaction.Spec.Summary.Runs) - require.Equal(0, anotherTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, anotherTransaction.Spec.Summary.LastRun.Passes) - require.Len(anotherTransaction.Spec.Steps, 4) - require.Equal("9wtAH2_Vg", anotherTransaction.Spec.Steps[0]) - require.Equal("9wtAH2_Vg", anotherTransaction.Spec.Steps[1]) - require.Equal("ajksdkasjbd", anotherTransaction.Spec.Steps[2]) - require.Equal("ajksdkasjbd", anotherTransaction.Spec.Steps[3]) - - newTransaction := transactions[1] - require.Equal("Transaction", newTransaction.Type) - require.Equal("Qti5R3_VR", newTransaction.Spec.ID) - require.Equal("New Transaction", newTransaction.Spec.Name) - require.Equal("a transaction", newTransaction.Spec.Description) - require.Equal(0, newTransaction.Spec.Summary.Runs) - require.Equal(0, newTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, newTransaction.Spec.Summary.LastRun.Passes) - require.Len(newTransaction.Spec.Steps, 2) - require.Equal("9wtAH2_Vg", newTransaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", newTransaction.Spec.Steps[1]) - - oneMoreTransaction := transactions[2] - require.Equal("Transaction", oneMoreTransaction.Type) - require.Equal("i2ug34j", oneMoreTransaction.Spec.ID) - require.Equal("One More Transaction", oneMoreTransaction.Spec.Name) - require.Equal("one more transaction", oneMoreTransaction.Spec.Description) - require.Equal(0, oneMoreTransaction.Spec.Summary.Runs) - require.Equal(0, oneMoreTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, oneMoreTransaction.Spec.Summary.LastRun.Passes) - require.Len(oneMoreTransaction.Spec.Steps, 3) - require.Equal("9wtAH2_Vg", oneMoreTransaction.Spec.Steps[0]) - require.Equal("9wtAH2_Vg", oneMoreTransaction.Spec.Steps[1]) - require.Equal("ajksdkasjbd", oneMoreTransaction.Spec.Steps[2]) - }) - - t.Run("list with JSON format", func(t *testing.T) { - // Given I am a Tracetest CLI user - // And I have my server recently created - - // When I try to list these transactions by a valid field and in JSON format - // Then I should receive three transactions - result := tracetestcli.Exec(t, "list transaction --sortBy name --sortDirection asc --output json", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - transactions := helpers.UnmarshalJSON[types.ResourceList[types.AugmentedTransactionResource]](t, result.StdOut) - require.Len(transactions.Items, 3) - require.Equal(len(transactions.Items), transactions.Count) - - anotherTransaction := transactions.Items[0] - require.Equal("Transaction", anotherTransaction.Type) - require.Equal("asuhfdkj", anotherTransaction.Spec.ID) - require.Equal("Another Transaction", anotherTransaction.Spec.Name) - require.Equal("another transaction", anotherTransaction.Spec.Description) - require.Equal(0, anotherTransaction.Spec.Summary.Runs) - require.Equal(0, anotherTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, anotherTransaction.Spec.Summary.LastRun.Passes) - require.Len(anotherTransaction.Spec.Steps, 4) - require.Equal("9wtAH2_Vg", anotherTransaction.Spec.Steps[0]) - require.Equal("9wtAH2_Vg", anotherTransaction.Spec.Steps[1]) - require.Equal("ajksdkasjbd", anotherTransaction.Spec.Steps[2]) - require.Equal("ajksdkasjbd", anotherTransaction.Spec.Steps[3]) - - newTransaction := transactions.Items[1] - require.Equal("Transaction", newTransaction.Type) - require.Equal("Qti5R3_VR", newTransaction.Spec.ID) - require.Equal("New Transaction", newTransaction.Spec.Name) - require.Equal("a transaction", newTransaction.Spec.Description) - require.Equal(0, newTransaction.Spec.Summary.Runs) - require.Equal(0, newTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, newTransaction.Spec.Summary.LastRun.Passes) - require.Len(newTransaction.Spec.Steps, 2) - require.Equal("9wtAH2_Vg", newTransaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", newTransaction.Spec.Steps[1]) - - oneMoreTransaction := transactions.Items[2] - require.Equal("Transaction", oneMoreTransaction.Type) - require.Equal("i2ug34j", oneMoreTransaction.Spec.ID) - require.Equal("One More Transaction", oneMoreTransaction.Spec.Name) - require.Equal("one more transaction", oneMoreTransaction.Spec.Description) - require.Equal(0, oneMoreTransaction.Spec.Summary.Runs) - require.Equal(0, oneMoreTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, oneMoreTransaction.Spec.Summary.LastRun.Passes) - require.Len(oneMoreTransaction.Spec.Steps, 3) - require.Equal("9wtAH2_Vg", oneMoreTransaction.Spec.Steps[0]) - require.Equal("9wtAH2_Vg", oneMoreTransaction.Spec.Steps[1]) - require.Equal("ajksdkasjbd", oneMoreTransaction.Spec.Steps[2]) - }) - - t.Run("list with pretty format", func(t *testing.T) { - // Given I am a Tracetest CLI user - // And I have my server recently created - - // When I try to list these transactions by a valid field and in pretty format - // Then it should print a table with 6 lines printed: header, separator, three transactions and empty line - result := tracetestcli.Exec(t, "list transaction --sortBy name --sortDirection asc --output pretty", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - parsedTable := helpers.UnmarshalTable(t, result.StdOut) - require.Len(parsedTable, 3) - - firstLine := parsedTable[0] - require.Equal("asuhfdkj", firstLine["ID"]) - require.Equal("Another Transaction", firstLine["NAME"]) - require.Equal("1", firstLine["VERSION"]) - require.Equal("4", firstLine["STEPS"]) - require.Equal("0", firstLine["RUNS"]) - require.Equal("", firstLine["LAST RUN TIME"]) - require.Equal("0", firstLine["LAST RUN SUCCESSES"]) - require.Equal("0", firstLine["LAST RUN FAILURES"]) - - secondLine := parsedTable[1] - require.Equal("Qti5R3_VR", secondLine["ID"]) - require.Equal("New Transaction", secondLine["NAME"]) - require.Equal("1", secondLine["VERSION"]) - require.Equal("2", secondLine["STEPS"]) - require.Equal("0", secondLine["RUNS"]) - require.Equal("", secondLine["LAST RUN TIME"]) - require.Equal("0", secondLine["LAST RUN SUCCESSES"]) - require.Equal("0", secondLine["LAST RUN FAILURES"]) - - thirdLine := parsedTable[2] - require.Equal("i2ug34j", thirdLine["ID"]) - require.Equal("One More Transaction", thirdLine["NAME"]) - require.Equal("1", thirdLine["VERSION"]) - require.Equal("3", thirdLine["STEPS"]) - require.Equal("0", thirdLine["RUNS"]) - require.Equal("", thirdLine["LAST RUN TIME"]) - require.Equal("0", thirdLine["LAST RUN SUCCESSES"]) - require.Equal("0", thirdLine["LAST RUN FAILURES"]) - }) - - t.Run("list with YAML format skipping the first and taking two items", func(t *testing.T) { - // Given I am a Tracetest CLI user - // And I have my server recently created - - // When I try to list these transactions by a valid field, paging options and in YAML format - // Then I should receive two transactions - result := tracetestcli.Exec(t, "list transaction --sortBy name --sortDirection asc --skip 1 --take 2 --output yaml", tracetestcli.WithCLIConfig(cliConfig)) - helpers.RequireExitCodeEqual(t, result, 0) - - transactions := helpers.UnmarshalYAMLSequence[types.AugmentedTransactionResource](t, result.StdOut) - require.Len(transactions, 2) - - newTransaction := transactions[0] - require.Equal("Transaction", newTransaction.Type) - require.Equal("Qti5R3_VR", newTransaction.Spec.ID) - require.Equal("New Transaction", newTransaction.Spec.Name) - require.Equal("a transaction", newTransaction.Spec.Description) - require.Equal(0, newTransaction.Spec.Summary.Runs) - require.Equal(0, newTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, newTransaction.Spec.Summary.LastRun.Passes) - require.Len(newTransaction.Spec.Steps, 2) - require.Equal("9wtAH2_Vg", newTransaction.Spec.Steps[0]) - require.Equal("ajksdkasjbd", newTransaction.Spec.Steps[1]) - - oneMoreTransaction := transactions[1] - require.Equal("Transaction", oneMoreTransaction.Type) - require.Equal("i2ug34j", oneMoreTransaction.Spec.ID) - require.Equal("One More Transaction", oneMoreTransaction.Spec.Name) - require.Equal("one more transaction", oneMoreTransaction.Spec.Description) - require.Equal(0, oneMoreTransaction.Spec.Summary.Runs) - require.Equal(0, oneMoreTransaction.Spec.Summary.LastRun.Fails) - require.Equal(0, oneMoreTransaction.Spec.Summary.LastRun.Passes) - require.Len(oneMoreTransaction.Spec.Steps, 3) - require.Equal("9wtAH2_Vg", oneMoreTransaction.Spec.Steps[0]) - require.Equal("9wtAH2_Vg", oneMoreTransaction.Spec.Steps[1]) - require.Equal("ajksdkasjbd", oneMoreTransaction.Spec.Steps[2]) - }) -} diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/.gitignore b/testing/cli-e2etest/testscenarios/transaction/resources/.gitignore deleted file mode 100644 index 57c1775944..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/resources/.gitignore +++ /dev/null @@ -1 +0,0 @@ -new-transaction-without-id.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/another-transaction.yaml b/testing/cli-e2etest/testscenarios/transaction/resources/another-transaction.yaml deleted file mode 100644 index 749f7fc003..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/resources/another-transaction.yaml +++ /dev/null @@ -1,10 +0,0 @@ -type: Transaction -spec: - id: asuhfdkj - name: Another Transaction - description: another transaction - steps: - - ./transaction-step-1.yaml - - ./transaction-step-1.yaml - - ./transaction-step-2.yaml - - ./transaction-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/new-transaction-without-id.yaml.tpl b/testing/cli-e2etest/testscenarios/transaction/resources/new-transaction-without-id.yaml.tpl deleted file mode 100644 index 04a2f1d5fa..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/resources/new-transaction-without-id.yaml.tpl +++ /dev/null @@ -1,7 +0,0 @@ -type: Transaction -spec: - name: New Transaction - description: a transaction - steps: - - ./transaction-step-1.yaml - - ./transaction-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/new-transaction.yaml b/testing/cli-e2etest/testscenarios/transaction/resources/new-transaction.yaml deleted file mode 100644 index f14118d545..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/resources/new-transaction.yaml +++ /dev/null @@ -1,8 +0,0 @@ -type: Transaction -spec: - id: Qti5R3_VR - name: New Transaction - description: a transaction - steps: - - ./transaction-step-1.yaml - - ./transaction-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/one-more-transaction.yaml b/testing/cli-e2etest/testscenarios/transaction/resources/one-more-transaction.yaml deleted file mode 100644 index a8a6f0e3bd..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/resources/one-more-transaction.yaml +++ /dev/null @@ -1,9 +0,0 @@ -type: Transaction -spec: - id: i2ug34j - name: One More Transaction - description: one more transaction - steps: - - ./transaction-step-1.yaml - - ./transaction-step-1.yaml - - ./transaction-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/transaction-to-run.yaml b/testing/cli-e2etest/testscenarios/transaction/resources/transaction-to-run.yaml deleted file mode 100644 index c3d886882c..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/resources/transaction-to-run.yaml +++ /dev/null @@ -1,8 +0,0 @@ -type: Transaction -spec: - id: k1ug23k - name: Transaction To Run - description: a transaction to run - steps: - - ./transaction-step-1.yaml - - ./transaction-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/transaction/resources/updated-new-transaction.yaml b/testing/cli-e2etest/testscenarios/transaction/resources/updated-new-transaction.yaml deleted file mode 100644 index 70e2c28f03..0000000000 --- a/testing/cli-e2etest/testscenarios/transaction/resources/updated-new-transaction.yaml +++ /dev/null @@ -1,9 +0,0 @@ -type: Transaction -spec: - id: Qti5R3_VR - name: Updated Transaction - description: an updated transaction - steps: - - ./transaction-step-1.yaml - - ./transaction-step-2.yaml - - ./transaction-step-2.yaml diff --git a/testing/cli-e2etest/testscenarios/types/testsuite.go b/testing/cli-e2etest/testscenarios/types/testsuite.go new file mode 100644 index 0000000000..5190e309df --- /dev/null +++ b/testing/cli-e2etest/testscenarios/types/testsuite.go @@ -0,0 +1,39 @@ +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 TestSuite struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + Steps []string `json:"steps"` +} + +type TestSuiteResource struct { + Type string `json:"type"` + Spec TestSuite `json:"spec"` +} + +type AugmentedTestSuiteLastRun struct { + Passes int `json:"passes"` + Fails int `json:"fails"` +} + +type AugmentedTestSuiteSummary struct { + Runs int `json:"runs"` + LastRun AugmentedTestSuiteLastRun `json:"lastRun"` +} + +type AugmentedTestSuite struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + Steps []string `json:"steps"` + Summary AugmentedTestSuiteSummary `json:"summary"` +} + +type AugmentedTestSuiteResource struct { + Type string `json:"type"` + Spec AugmentedTestSuite `json:"spec"` +} diff --git a/testing/cli-e2etest/testscenarios/types/transaction.go b/testing/cli-e2etest/testscenarios/types/transaction.go deleted file mode 100644 index af0142c0e1..0000000000 --- a/testing/cli-e2etest/testscenarios/types/transaction.go +++ /dev/null @@ -1,39 +0,0 @@ -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 Transaction struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Description string `json:"description"` - Steps []string `json:"steps"` -} - -type TransactionResource struct { - Type string `json:"type"` - Spec Transaction `json:"spec"` -} - -type AugmentedTransactionLastRun struct { - Passes int `json:"passes"` - Fails int `json:"fails"` -} - -type AugmentedTransactionSummary struct { - Runs int `json:"runs"` - LastRun AugmentedTransactionLastRun `json:"lastRun"` -} - -type AugmentedTransaction struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - Steps []string `json:"steps"` - Summary AugmentedTransactionSummary `json:"summary"` -} - -type AugmentedTransactionResource struct { - Type string `json:"type"` - Spec AugmentedTransaction `json:"spec"` -} diff --git a/testing/server-tracetesting/features/grpc_test/_test_suite.yml b/testing/server-tracetesting/features/grpc_test/_test_suite.yml index e3b98f1a7f..8f052f2178 100644 --- a/testing/server-tracetesting/features/grpc_test/_test_suite.yml +++ b/testing/server-tracetesting/features/grpc_test/_test_suite.yml @@ -1,4 +1,4 @@ -type: Transaction +type: TestSuite spec: id: ojkNeDwVgO name: gRPC Test Feature diff --git a/testing/server-tracetesting/features/http_test/_test_suite.yml b/testing/server-tracetesting/features/http_test/_test_suite.yml index 297b023560..f3104b4260 100644 --- a/testing/server-tracetesting/features/http_test/_test_suite.yml +++ b/testing/server-tracetesting/features/http_test/_test_suite.yml @@ -1,4 +1,4 @@ -type: Transaction +type: TestSuite spec: id: TjkHeDQVg1 name: HTTP Test Feature diff --git a/testing/server-tracetesting/features/testsuite/_test_suite.yml b/testing/server-tracetesting/features/testsuite/_test_suite.yml new file mode 100644 index 0000000000..5d1c512318 --- /dev/null +++ b/testing/server-tracetesting/features/testsuite/_test_suite.yml @@ -0,0 +1,20 @@ +type: TestSuite +spec: + id: ILYjqDQ4g + name: TestSuite Feature + description: Sequence of tests to validate if our TestSuite feature is working as expected + steps: + # create test that will be added to a testsuite + - ./create_testsuite_step.yml + # create testsuite that will group these steps + - ./create_testsuite.yml + # check if this testsuite is listed on API + - ./list_testsuite.yml + # check if this testsuite is listed on API as a resource + - ./list_testsuite_as_resource.yml + # udpate testsuite + - ./update_testsuite.yml + # delete testsuite + - ./delete_testsuite.yml + # delete testsuite steps + - ./delete_testsuite_step.yml diff --git a/testing/server-tracetesting/features/transaction/create_transaction.yml b/testing/server-tracetesting/features/testsuite/create_testsuite.yml similarity index 72% rename from testing/server-tracetesting/features/transaction/create_transaction.yml rename to testing/server-tracetesting/features/testsuite/create_testsuite.yml index 96a785cc70..da1da6dcea 100644 --- a/testing/server-tracetesting/features/transaction/create_transaction.yml +++ b/testing/server-tracetesting/features/testsuite/create_testsuite.yml @@ -2,22 +2,22 @@ type: Test spec: id: TCzH6vw4R - name: Create transaction - description: Test step of 'Transaction Feature - Test Suite' + name: Create testsuite + description: Test step of 'TestSuite Feature - Test Suite' trigger: type: http httpRequest: - url: ${env:TARGET_URL}/api/transactions + url: ${env:TARGET_URL}/api/testsuites method: POST headers: - key: Content-Type value: application/json body: | { - "type": "Transaction", + "type": "TestSuite", "spec": { - "name": "test-transaction", - "description": "a transaction", + "name": "test-testsuite", + "description": "a testsuite", "steps": [ "${env:TRANSACTION_STEP_ID}" ] } } @@ -27,7 +27,7 @@ spec: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 201 - attr:tracetest.response.body | json_path '$.spec.id' = env:TRANSACTION_ID - - selector: span[name="POST /api/transactions" tracetest.span.type="http"] + - selector: span[name="POST /api/testsuites" tracetest.span.type="http"] assertions: - attr:tracetest.selected_spans.count = 1 - selector: span[name = "exec INSERT"] diff --git a/testing/server-tracetesting/features/transaction/create_transaction_step.yml b/testing/server-tracetesting/features/testsuite/create_testsuite_step.yml similarity index 95% rename from testing/server-tracetesting/features/transaction/create_transaction_step.yml rename to testing/server-tracetesting/features/testsuite/create_testsuite_step.yml index bb0997b1a0..6a1f551d99 100644 --- a/testing/server-tracetesting/features/transaction/create_transaction_step.yml +++ b/testing/server-tracetesting/features/testsuite/create_testsuite_step.yml @@ -1,8 +1,8 @@ type: Test spec: id: hCzNevwVg - name: Create transaction step - description: Test step of 'Transaction Feature - Test Suite' + name: Create testsuite step + description: Test step of 'TestSuite Feature - Test Suite' trigger: type: http httpRequest: diff --git a/testing/server-tracetesting/features/transaction/delete_transaction.yml b/testing/server-tracetesting/features/testsuite/delete_testsuite.yml similarity index 68% rename from testing/server-tracetesting/features/transaction/delete_transaction.yml rename to testing/server-tracetesting/features/testsuite/delete_testsuite.yml index a9abcbded4..cf3f8e7c11 100644 --- a/testing/server-tracetesting/features/transaction/delete_transaction.yml +++ b/testing/server-tracetesting/features/testsuite/delete_testsuite.yml @@ -2,12 +2,12 @@ type: Test spec: id: TjkHeDw4gm - name: Delete Transaction - description: Test step of 'Transaction Feature - Test Suite' + name: Delete TestSuite + description: Test step of 'TestSuite Feature - Test Suite' trigger: type: http httpRequest: - url: ${env:TARGET_URL}/api/transactions/${env:TRANSACTION_ID} + url: ${env:TARGET_URL}/api/testsuites/${env:TRANSACTION_ID} method: DELETE headers: - key: Content-Type @@ -17,7 +17,7 @@ spec: assertions: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 204 - - selector: span[name="DELETE /api/transactions/{id}" tracetest.span.type="http"] + - selector: span[name="DELETE /api/testsuites/{id}" tracetest.span.type="http"] assertions: - attr:tracetest.selected_spans.count = 1 - selector: span[name = "exec DELETE"] diff --git a/testing/server-tracetesting/features/transaction/delete_transaction_step.yml b/testing/server-tracetesting/features/testsuite/delete_testsuite_step.yml similarity index 87% rename from testing/server-tracetesting/features/transaction/delete_transaction_step.yml rename to testing/server-tracetesting/features/testsuite/delete_testsuite_step.yml index f81e84607f..b5a5f467e5 100644 --- a/testing/server-tracetesting/features/transaction/delete_transaction_step.yml +++ b/testing/server-tracetesting/features/testsuite/delete_testsuite_step.yml @@ -2,8 +2,8 @@ type: Test spec: id: TCzNeDwVgz - name: Delete Transaction Step - description: Test step of 'Transaction Feature - Test Suite' + name: Delete TestSuite Step + description: Test step of 'TestSuite Feature - Test Suite' trigger: type: http httpRequest: diff --git a/testing/server-tracetesting/features/transaction/list_transaction.yml b/testing/server-tracetesting/features/testsuite/list_testsuite.yml similarity index 62% rename from testing/server-tracetesting/features/transaction/list_transaction.yml rename to testing/server-tracetesting/features/testsuite/list_testsuite.yml index 5c929dc437..933ae6f17b 100644 --- a/testing/server-tracetesting/features/transaction/list_transaction.yml +++ b/testing/server-tracetesting/features/testsuite/list_testsuite.yml @@ -2,12 +2,12 @@ type: Test spec: id: TjkNeDwVgM - name: List Transaction - description: Test step of 'Transaction Feature - Test Suite' + name: List TestSuite + description: Test step of 'TestSuite Feature - Test Suite' trigger: type: http httpRequest: - url: ${env:TARGET_URL}/api/transactions + url: ${env:TARGET_URL}/api/testsuites method: GET headers: - key: Content-Type @@ -17,7 +17,7 @@ spec: assertions: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 200 - - attr:tracetest.response.body | json_path '$.items[*].spec.id' contains env:TRANSACTION_ID # check if the transaction is listed - - selector: span[name="GET /api/transactions" tracetest.span.type="http"] + - attr:tracetest.response.body | json_path '$.items[*].spec.id' contains env:TRANSACTION_ID # check if the testsuite is listed + - selector: span[name="GET /api/testsuites" tracetest.span.type="http"] assertions: - attr:tracetest.selected_spans.count = 1 diff --git a/testing/server-tracetesting/features/transaction/list_transaction_as_resource.yml b/testing/server-tracetesting/features/testsuite/list_testsuite_as_resource.yml similarity index 78% rename from testing/server-tracetesting/features/transaction/list_transaction_as_resource.yml rename to testing/server-tracetesting/features/testsuite/list_testsuite_as_resource.yml index d11b1b511d..e4d6f8d7c3 100644 --- a/testing/server-tracetesting/features/transaction/list_transaction_as_resource.yml +++ b/testing/server-tracetesting/features/testsuite/list_testsuite_as_resource.yml @@ -2,8 +2,8 @@ type: Test spec: id: TjkNeDwVRZ - name: List Transaction as Resource - description: Test step of 'Transaction Feature - Test Suite' + name: List TestSuite as Resource + description: Test step of 'TestSuite Feature - Test Suite' trigger: type: http httpRequest: @@ -17,7 +17,7 @@ spec: assertions: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 200 - - attr:tracetest.response.body | json_path '$[*].item.id' contains env:TRANSACTION_ID # check if the transaction is listed + - attr:tracetest.response.body | json_path '$[*].item.id' contains env:TRANSACTION_ID # check if the testsuite is listed - selector: span[name="GET /api/resources" tracetest.span.type="http"] assertions: - attr:tracetest.selected_spans.count = 1 diff --git a/testing/server-tracetesting/features/transaction/update_transaction.yml b/testing/server-tracetesting/features/testsuite/update_testsuite.yml similarity index 62% rename from testing/server-tracetesting/features/transaction/update_transaction.yml rename to testing/server-tracetesting/features/testsuite/update_testsuite.yml index 5976423e76..667cb9485b 100644 --- a/testing/server-tracetesting/features/transaction/update_transaction.yml +++ b/testing/server-tracetesting/features/testsuite/update_testsuite.yml @@ -2,22 +2,22 @@ type: Test spec: id: TjkNeDQ4R7 - name: Update transaction - description: Test step of 'Transaction Feature - Test Suite' + name: Update testsuite + description: Test step of 'TestSuite Feature - Test Suite' trigger: type: http httpRequest: - url: ${env:TARGET_URL}/api/transactions/${env:TRANSACTION_ID} + url: ${env:TARGET_URL}/api/testsuites/${env:TRANSACTION_ID} method: PUT headers: - key: Content-Type value: application/json body: | { - "type": "Transaction", + "type": "TestSuite", "spec": { - "name": "test-transaction-updated", - "description": "a transaction", + "name": "test-testsuite-updated", + "description": "a testsuite", "steps": [ "${env:TRANSACTION_STEP_ID}" ] } } @@ -26,8 +26,8 @@ spec: assertions: - attr:tracetest.selected_spans.count = 1 - attr:tracetest.response.status = 200 - - attr:tracetest.response.body | json_path '$.spec.name' = "test-transaction-updated" - - selector: span[name="PUT /api/transactions/{id}" tracetest.span.type="http"] + - attr:tracetest.response.body | json_path '$.spec.name' = "test-testsuite-updated" + - selector: span[name="PUT /api/testsuites/{id}" tracetest.span.type="http"] assertions: - attr:tracetest.selected_spans.count = 1 - selector: span[name = "exec INSERT"] @@ -35,5 +35,5 @@ spec: - attr:tracetest.selected_spans.count = 2 - selector: span[name = "exec INSERT"]:first assertions: - - attr:sql.query contains "INSERT INTO transactions" + - attr:sql.query contains "INSERT INTO test_suites" diff --git a/testing/server-tracetesting/features/transaction/_test_suite.yml b/testing/server-tracetesting/features/transaction/_test_suite.yml deleted file mode 100644 index 9ab2b93b2d..0000000000 --- a/testing/server-tracetesting/features/transaction/_test_suite.yml +++ /dev/null @@ -1,20 +0,0 @@ -type: Transaction -spec: - id: ILYjqDQ4g - name: Transaction Feature - description: Sequence of tests to validate if our Transaction feature is working as expected - steps: - # create test that will be added to a transaction - - ./create_transaction_step.yml - # create transaction that will group these steps - - ./create_transaction.yml - # check if this transaction is listed on API - - ./list_transaction.yml - # check if this transaction is listed on API as a resource - - ./list_transaction_as_resource.yml - # udpate transaction - - ./update_transaction.yml - # delete transaction - - ./delete_transaction.yml - # delete transaction steps - - ./delete_transaction_step.yml diff --git a/testing/server-tracetesting/features/variableset/_test_suite.yml b/testing/server-tracetesting/features/variableset/_test_suite.yml index 8f4d886b16..aee5685ece 100644 --- a/testing/server-tracetesting/features/variableset/_test_suite.yml +++ b/testing/server-tracetesting/features/variableset/_test_suite.yml @@ -1,4 +1,4 @@ -type: Transaction +type: TestSuite spec: id: oCkH6vQ4gV name: Variable Set Feature diff --git a/testing/server-tracetesting/run.bash b/testing/server-tracetesting/run.bash index 7d41d14ca5..a36972b65c 100755 --- a/testing/server-tracetesting/run.bash +++ b/testing/server-tracetesting/run.bash @@ -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 --vars ./tracetesting-env.yaml" + testCMD="$TRACETEST_CLI --config ./config.yml run testsuite --file $definition --vars ./tracetesting-env.yaml" echo $testCMD $testCMD return $? @@ -85,7 +85,7 @@ EXIT_STATUS=0 run_test_suite_for_feature 'http_test' || EXIT_STATUS=$? run_test_suite_for_feature 'grpc_test' || EXIT_STATUS=$? run_test_suite_for_feature 'variableset' || EXIT_STATUS=$? -run_test_suite_for_feature 'transaction' || EXIT_STATUS=$? +run_test_suite_for_feature 'testsuite' || EXIT_STATUS=$? echo "" echo "Tests done! Exit code: $EXIT_STATUS" diff --git a/web/cypress/e2e/TestSuites/TestSuite.spec.ts b/web/cypress/e2e/TestSuites/TestSuite.spec.ts new file mode 100644 index 0000000000..4653de680d --- /dev/null +++ b/web/cypress/e2e/TestSuites/TestSuite.spec.ts @@ -0,0 +1,41 @@ +import TestSuite from '../utils/TestSuites'; + +const testSuiteUtils = TestSuite(); + +describe('TestSuites', () => { + beforeEach(() => { + cy.visit('/'); + cy.wrap(testSuiteUtils.createTests()); + }); + + afterEach(() => { + cy.wrap(testSuiteUtils.deleteTests()).then(() => { + cy.deleteTestSuite(); + }); + }); + + it('should create a TestSuite with multiple tests', () => { + const name = `TestSuite - #${String(Date.now()).slice(-4)}`; + cy.openTestSuiteCreationModal(); + cy.interceptHomeApiCall(); + cy.fillCreateFormBasicStep(name, name, 'CreateTestSuiteFactory'); + + testSuiteUtils.testList.forEach(test => { + cy.get('[data-cy=testsuite-test-selection]').click(); + cy.get(`[data-cy="${test.spec.name}"]`).first().click(); + }); + + cy.submitCreateForm('CreateTestSuiteFactory'); + cy.get('[data-cy=testsuite-details-name').should('have.text', `${name} (v1)`); + }); + + it('should create a TestSuite with no tests', () => { + const name = `TestSuite - #${String(Date.now()).slice(-4)}`; + cy.openTestSuiteCreationModal(); + cy.interceptHomeApiCall(); + cy.fillCreateFormBasicStep(name, name, 'CreateTestSuiteFactory'); + + cy.submitCreateForm('CreateTestSuiteFactory'); + cy.get('[data-cy=testsuite-details-name').should('have.text', `${name} (v1)`); + }); +}); diff --git a/web/cypress/e2e/TestSuites/TestSuiteRun.spec.ts b/web/cypress/e2e/TestSuites/TestSuiteRun.spec.ts new file mode 100644 index 0000000000..143625e296 --- /dev/null +++ b/web/cypress/e2e/TestSuites/TestSuiteRun.spec.ts @@ -0,0 +1,81 @@ +import TestSuites from '../utils/TestSuites'; + +const testSuitesUtils = TestSuites(); + +describe('TestSuiteRuns', () => { + beforeEach(() => { + cy.visit('/'); + cy.wrap(testSuitesUtils.createTests()); + }); + + afterEach(() => { + cy.wrap(testSuitesUtils.deleteTests()).then(() => { + cy.deleteTestSuite(); + }); + }); + + it('should create and run a test suite with multiple tests', () => { + const name = `TestSuite - #${String(Date.now()).slice(-4)}`; + cy.openTestSuiteCreationModal(); + cy.interceptHomeApiCall(); + cy.fillCreateFormBasicStep(name, name, 'CreateTestSuiteFactory'); + + testSuitesUtils.testList.forEach(test => { + cy.get('[data-cy=testsuite-test-selection]').click(); + cy.get(`[data-cy="${test.spec.name}"]`).first().click(); + }); + + cy.submitCreateForm('CreateTestSuiteFactory'); + cy.get('[data-cy=testsuite-details-name]').should('have.text', `${name} (v1)`); + cy.reload().get('[data-cy=testsuite-run-button]', {timeout: 50000}).should('be.visible'); + }); + + it('should rerun a test suite after creation', () => { + const name = `TestSuite - #${String(Date.now()).slice(-4)}`; + cy.openTestSuiteCreationModal(); + cy.interceptHomeApiCall(); + cy.fillCreateFormBasicStep(name, name, 'CreateTestSuiteFactory'); + + testSuitesUtils.testList.forEach(test => { + cy.get('[data-cy=testsuite-test-selection]').click(); + cy.get(`[data-cy="${test.spec.name}"]`).first().click(); + }); + + cy.submitCreateForm('CreateTestSuiteFactory'); + cy.get('[data-cy=testsuite-details-name').should('have.text', `${name} (v1)`); + cy.reload().get('[data-cy=testsuite-run-button]', {timeout: 50000}).should('be.visible'); + + cy.get('[data-cy=testsuite-details-name').should('have.text', `${name} (v1)`); + cy.reload().get('[data-cy=testsuite-run-button]', {timeout: 50000}).should('be.visible'); + }); + + it('should update a test suite and rerun', () => { + const name = `TestSuite - #${String(Date.now()).slice(-4)}`; + cy.openTestSuiteCreationModal(); + cy.interceptHomeApiCall(); + cy.fillCreateFormBasicStep(name, name, 'CreateTestSuiteFactory'); + + testSuitesUtils.testList.forEach(test => { + cy.get('[data-cy=testsuite-test-selection]').click(); + cy.get(`[data-cy="${test.spec.name}"]`).first().click(); + }); + + cy.submitCreateForm('CreateTestSuiteFactory'); + cy.get('[data-cy=testsuite-details-name').should('have.text', `${name} (v1)`); + cy.reload().get('[data-cy=testsuite-run-button]', {timeout: 50000}).should('be.visible'); + cy.get('[data-cy^=testsuite-execution-step-]').should('have.length', 2); + + const updateName = `${name} - updated`; + + cy.get('[data-cy=create-test-name-input]').type(' - updated'); + testSuitesUtils.testList.forEach(test => { + cy.get('[data-cy=testsuite-test-selection]').click(); + cy.get(`[data-cy="${test.spec.name}"]`).first().click(); + }); + + cy.get('[data-cy=edit-testsuite-submit]').click(); + cy.get('[data-cy=testsuite-details-name').should('have.text', `${updateName} (v2)`); + cy.reload().get('[data-cy=testsuite-run-button]', {timeout: 50000}).should('be.visible'); + cy.get('[data-cy^=testsuite-execution-step-]').should('have.length', 4); + }); +}); diff --git a/web/cypress/e2e/Transactions/Transactions.spec.ts b/web/cypress/e2e/Transactions/Transactions.spec.ts deleted file mode 100644 index b93c6ae0fe..0000000000 --- a/web/cypress/e2e/Transactions/Transactions.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import TransactionUtils from '../utils/Transactions'; - -const transactionUtils = TransactionUtils(); - -describe('Transactions', () => { - beforeEach(() => { - cy.visit('/'); - cy.wrap(transactionUtils.createTests()); - }); - - afterEach(() => { - cy.wrap(transactionUtils.deleteTests()).then(() => { - cy.deleteTransaction(); - }); - }); - - it('should create a transaction with multiple tests', () => { - const name = `Transaction - #${String(Date.now()).slice(-4)}`; - cy.openTransactionCreationModal(); - cy.interceptHomeApiCall(); - cy.fillCreateFormBasicStep(name, name, 'CreateTransactionFactory'); - - transactionUtils.testList.forEach(test => { - cy.get('[data-cy=transaction-test-selection]').click(); - cy.get(`[data-cy="${test.spec.name}"]`).first().click(); - }); - - cy.submitCreateForm('CreateTransactionFactory'); - cy.get('[data-cy=transaction-details-name').should('have.text', `${name} (v1)`); - }); - - it('should create a transaction with no tests', () => { - const name = `Transaction - #${String(Date.now()).slice(-4)}`; - cy.openTransactionCreationModal(); - cy.interceptHomeApiCall(); - cy.fillCreateFormBasicStep(name, name, 'CreateTransactionFactory'); - - cy.submitCreateForm('CreateTransactionFactory'); - cy.get('[data-cy=transaction-details-name').should('have.text', `${name} (v1)`); - }); -}); diff --git a/web/cypress/e2e/Transactions/TransactionsRun.spec.ts b/web/cypress/e2e/Transactions/TransactionsRun.spec.ts deleted file mode 100644 index cc7b3eea8a..0000000000 --- a/web/cypress/e2e/Transactions/TransactionsRun.spec.ts +++ /dev/null @@ -1,81 +0,0 @@ -import TransactionUtils from '../utils/Transactions'; - -const transactionUtils = TransactionUtils(); - -describe('Transactions', () => { - beforeEach(() => { - cy.visit('/'); - cy.wrap(transactionUtils.createTests()); - }); - - afterEach(() => { - cy.wrap(transactionUtils.deleteTests()).then(() => { - cy.deleteTransaction(); - }); - }); - - it('should create and run a transaction with multiple tests', () => { - const name = `Transaction - #${String(Date.now()).slice(-4)}`; - cy.openTransactionCreationModal(); - cy.interceptHomeApiCall(); - cy.fillCreateFormBasicStep(name, name, 'CreateTransactionFactory'); - - transactionUtils.testList.forEach(test => { - cy.get('[data-cy=transaction-test-selection]').click(); - cy.get(`[data-cy="${test.spec.name}"]`).first().click(); - }); - - cy.submitCreateForm('CreateTransactionFactory'); - cy.get('[data-cy=transaction-details-name').should('have.text', `${name} (v1)`); - cy.reload().get('[data-cy=transaction-run-button]', {timeout: 50000}).should('be.visible'); - }); - - it('should rerun a transaction after creation', () => { - const name = `Transaction - #${String(Date.now()).slice(-4)}`; - cy.openTransactionCreationModal(); - cy.interceptHomeApiCall(); - cy.fillCreateFormBasicStep(name, name, 'CreateTransactionFactory'); - - transactionUtils.testList.forEach(test => { - cy.get('[data-cy=transaction-test-selection]').click(); - cy.get(`[data-cy="${test.spec.name}"]`).first().click(); - }); - - cy.submitCreateForm('CreateTransactionFactory'); - cy.get('[data-cy=transaction-details-name').should('have.text', `${name} (v1)`); - cy.reload().get('[data-cy=transaction-run-button]', {timeout: 50000}).should('be.visible'); - - cy.get('[data-cy=transaction-details-name').should('have.text', `${name} (v1)`); - cy.reload().get('[data-cy=transaction-run-button]', {timeout: 50000}).should('be.visible'); - }); - - it('should update a transaction and rerun', () => { - const name = `Transaction - #${String(Date.now()).slice(-4)}`; - cy.openTransactionCreationModal(); - cy.interceptHomeApiCall(); - cy.fillCreateFormBasicStep(name, name, 'CreateTransactionFactory'); - - transactionUtils.testList.forEach(test => { - cy.get('[data-cy=transaction-test-selection]').click(); - cy.get(`[data-cy="${test.spec.name}"]`).first().click(); - }); - - cy.submitCreateForm('CreateTransactionFactory'); - cy.get('[data-cy=transaction-details-name').should('have.text', `${name} (v1)`); - cy.reload().get('[data-cy=transaction-run-button]', {timeout: 50000}).should('be.visible'); - cy.get('[data-cy^=transaction-execution-step-]').should('have.length', 2); - - const updateName = `${name} - updated`; - - cy.get('[data-cy=create-test-name-input]').type(' - updated'); - transactionUtils.testList.forEach(test => { - cy.get('[data-cy=transaction-test-selection]').click(); - cy.get(`[data-cy="${test.spec.name}"]`).first().click(); - }); - - cy.get('[data-cy=edit-transaction-submit]').click(); - cy.get('[data-cy=transaction-details-name').should('have.text', `${updateName} (v2)`); - cy.reload().get('[data-cy=transaction-run-button]', {timeout: 50000}).should('be.visible'); - cy.get('[data-cy^=transaction-execution-step-]').should('have.length', 4); - }); -}); diff --git a/web/cypress/e2e/constants/Transactions.ts b/web/cypress/e2e/constants/TestSuite.ts similarity index 84% rename from web/cypress/e2e/constants/Transactions.ts rename to web/cypress/e2e/constants/TestSuite.ts index 3d791aa768..2f75c2c676 100644 --- a/web/cypress/e2e/constants/Transactions.ts +++ b/web/cypress/e2e/constants/TestSuite.ts @@ -1,12 +1,12 @@ import {TRawTestResource} from '../../../src/models/Test.model'; -import {POKEMON_HTTP_ENDPOINT} from '../constants/Test'; +import {POKEMON_HTTP_ENDPOINT} from './Test'; -export const transactionTestList: TRawTestResource[] = [ +export const testSuiteTestList: TRawTestResource[] = [ { type: 'Test', spec: { name: 'POST test', - description: 'transaction', + description: 'test suite', trigger: { type: 'http', triggerType: 'http', @@ -30,7 +30,7 @@ export const transactionTestList: TRawTestResource[] = [ type: 'Test', spec: { name: 'GET test', - description: 'transaction', + description: 'test suite', trigger: { triggerType: 'http', type: 'http', diff --git a/web/cypress/e2e/utils/Common.ts b/web/cypress/e2e/utils/Common.ts index bc8a9b4c99..5e528d0612 100644 --- a/web/cypress/e2e/utils/Common.ts +++ b/web/cypress/e2e/utils/Common.ts @@ -1,7 +1,7 @@ Cypress.on('uncaught:exception', err => !err.message.includes('ResizeObserver loop limit exceeded')); const testIdRegex = /\/test\/([\w-]+)/; -const transactionIdRegex = /\/transaction\/([\w-]+)/; +const testSuiteIdRegex = /\/testsuite\/([\w-]+)/; const runIdRegex = /\/run\/(\w+)/; export const getTestId = (pathname: string) => { @@ -12,12 +12,12 @@ export const getTestId = (pathname: string) => { return testId; }; -export const getTransactionId = (pathname: string) => { +export const getTestSuiteId = (pathname: string) => { cy.log(pathname); - const result = pathname.match(transactionIdRegex); - const transactionId = result.length > 1 ? result[1] : ''; - cy.log(transactionId); - return transactionId; + const result = pathname.match(testSuiteIdRegex); + const testSuiteId = result.length > 1 ? result[1] : ''; + cy.log(testSuiteId); + return testSuiteId; }; export const getResultId = (pathname: string) => { diff --git a/web/cypress/e2e/utils/Transactions.ts b/web/cypress/e2e/utils/TestSuites.ts similarity index 69% rename from web/cypress/e2e/utils/Transactions.ts rename to web/cypress/e2e/utils/TestSuites.ts index d4321267c3..dc21fb9a87 100644 --- a/web/cypress/e2e/utils/Transactions.ts +++ b/web/cypress/e2e/utils/TestSuites.ts @@ -1,16 +1,16 @@ import {TRawTestResource} from '../../../src/models/Test.model'; -import {transactionTestList} from '../constants/Transactions'; +import {testSuiteTestList} from '../constants/TestSuite'; -interface ITransactionUtils { +interface ITestSuiteUtils { testList: TRawTestResource[]; createTest(test: TRawTestResource): Promise; createTests(tests?: TRawTestResource[]): Promise; deleteTest(id: string): Promise; deleteTests(): Promise; - waitForTransactionRun(): void; + waitForTestSuiteRun(): void; } -const TransactionUtils = (): ITransactionUtils => ({ +const TestSuitesUtils = (): ITestSuiteUtils => ({ testList: [], createTest(test) { return new Promise(resolve => { @@ -19,7 +19,7 @@ const TransactionUtils = (): ITransactionUtils => ({ }); }); }, - async createTests(tests = transactionTestList) { + async createTests(tests = testSuiteTestList) { this.testList = await Promise.all(tests.map(test => this.createTest(test))); return this.testList; @@ -34,9 +34,9 @@ const TransactionUtils = (): ITransactionUtils => ({ deleteTests() { return Promise.all(this.testList.map(test => this.deleteTest(test.spec.id))); }, - waitForTransactionRun() { - cy.get('[data-cy=transaction-run-result-status]').should('have.text', 'FINISHED', {timeout: 60000}); + waitForTestSuiteRun() { + cy.get('[data-cy=testsuite-run-result-status]').should('have.text', 'FINISHED', {timeout: 60000}); } }); -export default TransactionUtils; +export default TestSuitesUtils; diff --git a/web/cypress/support/commands.ts b/web/cypress/support/commands.ts index da9f2e3c53..b58920c64a 100644 --- a/web/cypress/support/commands.ts +++ b/web/cypress/support/commands.ts @@ -1,7 +1,7 @@ import 'cypress-file-upload'; import {camelCase} from 'lodash'; import {POKEMON_HTTP_ENDPOINT, PokeshopDemo} from '../e2e/constants/Test'; -import {getTestId, getTransactionId} from '../e2e/utils/Common'; +import {getTestId, getTestSuiteId} from '../e2e/utils/Common'; export const testRunPageRegex = /\/test\/(.*)\/run\/(.*)/; export const getAttributeListId = (number: number) => `.cm-tooltip-autocomplete [id$=-${number}]`; @@ -66,8 +66,8 @@ Cypress.Commands.add('interceptHomeApiCall', () => { cy.intercept({method: 'GET', url: '/api/resources?take=20&skip=0*'}).as('testList'); cy.intercept({method: 'DELETE', url: '/api/tests/**'}).as('testDelete'); cy.intercept({method: 'POST', url: '/api/tests'}).as('testCreation'); - cy.intercept({method: 'DELETE', url: '/api/transactions/**'}).as('transactionDelete'); - cy.intercept({method: 'POST', url: '/api/transactions'}).as('transactionCreation'); + cy.intercept({method: 'DELETE', url: '/api/testsuites/**'}).as('testSuiteDelete'); + cy.intercept({method: 'POST', url: '/api/testsuites'}).as('testSuiteCreation'); }); Cypress.Commands.add('waitForTracePageApiCalls', () => { @@ -132,7 +132,7 @@ Cypress.Commands.add('cancelOnBoarding', () => { Cypress.Commands.add('submitCreateForm', (mode = 'CreateTestFactory') => { cy.get(`[data-cy=${mode}-create-create-button]`).last().click(); if (mode === 'CreateTestFactory') cy.wait('@testCreation'); - if (mode === 'CreateTransactionFactory') cy.wait('@transactionCreation'); + if (mode === 'CreateTestSuiteFactory') cy.wait('@testSuiteCreation'); }); Cypress.Commands.add('fillCreateFormBasicStep', (name: string, description?: string, mode = 'CreateTestFactory') => { @@ -230,15 +230,15 @@ Cypress.Commands.add('selectRunDetailMode', (index: number) => { cy.get(`[data-cy=run-detail-header] .ant-tabs-nav-list div:nth-child(${index})`).click(); }); -Cypress.Commands.add('openTransactionCreationModal', () => { +Cypress.Commands.add('openTestSuiteCreationModal', () => { cy.get('[data-cy=create-button]').click(); cy.get('.ant-dropdown-menu-item').last().click(); - cy.get('[data-cy=create-test-steps-CreateTransactionFactory]').should('be.visible'); + cy.get('[data-cy=create-test-steps-CreateTestSuiteFactory]').should('be.visible'); }); -Cypress.Commands.add('deleteTransaction', () => { +Cypress.Commands.add('deleteTestSuite', () => { cy.location('pathname').then(pathname => { - const localTestId = getTransactionId(pathname); + const localTestId = getTestSuiteId(pathname); cy.visit(`/`); cy.wait('@testList'); @@ -247,7 +247,7 @@ Cypress.Commands.add('deleteTransaction', () => { cy.get(`[data-cy=test-actions-button-${localTestId}]`).click({force: true}); cy.get('[data-cy=test-card-delete]').click(); cy.get('[data-cy=confirmation-modal] .ant-btn-primary').click(); - cy.wait('@transactionDelete'); + cy.wait('@testSuiteDelete'); cy.get(`[data-cy=test-actions-button-${localTestId}]`).should('not.exist'); cy.wait('@testList'); cy.clearLocalStorage(); diff --git a/web/cypress/support/index.d.ts b/web/cypress/support/index.d.ts index 89ef5a5193..d1500e5bdf 100644 --- a/web/cypress/support/index.d.ts +++ b/web/cypress/support/index.d.ts @@ -25,9 +25,9 @@ declare namespace Cypress { setCreateFormUrl(method: string, url: string): Chainable; selectRunDetailMode(index: number): Chainable; interceptEditTestCall(): Chainable; - deleteTransactionTests(): Chainable; - openTransactionCreationModal(): Chainable; - deleteTransaction(): Chainable; + deleteTestSuiteTests(): Chainable; + openTestSuiteCreationModal(): Chainable; + deleteTestSuite(): Chainable; enableDemo(): Chainable; } } diff --git a/web/src/components/CreateTransactionModal/CreateTransactionModal.tsx b/web/src/components/CreateTestSuiteModal/CreateTestSuiteModal.tsx similarity index 62% rename from web/src/components/CreateTransactionModal/CreateTransactionModal.tsx rename to web/src/components/CreateTestSuiteModal/CreateTestSuiteModal.tsx index 1ee01167c3..7cf70d8442 100644 --- a/web/src/components/CreateTransactionModal/CreateTransactionModal.tsx +++ b/web/src/components/CreateTestSuiteModal/CreateTestSuiteModal.tsx @@ -1,15 +1,15 @@ import {useEffect} from 'react'; -import {useCreateTransaction} from 'providers/CreateTransaction/CreateTransaction.provider'; +import {useCreateTestSuite} from 'providers/CreateTestSuite'; import CreateModal from '../CreateModal/CreateModal'; -import CreateTransactionFactory from '../TransactionPlugin/CreateTransactionFactory'; +import CreateTestSuiteFactory from '../TestSuitePlugin/CreateTestSuiteFactory'; interface IProps { isOpen: boolean; onClose(): void; } -const CreateTransactionModal = ({isOpen, onClose}: IProps) => { - const {stepList, stepNumber, onPrev, activeStep, onReset, onIsFormValid, isFormValid} = useCreateTransaction(); +const CreateTestSuiteModal = ({isOpen, onClose}: IProps) => { + const {stepList, stepNumber, onPrev, activeStep, onReset, onIsFormValid, isFormValid} = useCreateTestSuite(); useEffect(() => { if (!isOpen) onReset(); @@ -25,17 +25,17 @@ const CreateTransactionModal = ({isOpen, onClose}: IProps) => { isValid={isFormValid} isOpen onClose={onClose} - title="Create Transaction" + title="Create Test Suite" stepList={stepList} activeStep={activeStep} onGoTo={() => null} onPrev={onPrev} isLoading={false} stepNumber={stepNumber} - componentFactory={CreateTransactionFactory} - mode="CreateTransactionFactory" + componentFactory={CreateTestSuiteFactory} + mode="CreateTestSuiteFactory" /> ) : null; }; -export default CreateTransactionModal; +export default CreateTestSuiteModal; diff --git a/web/src/components/EditTransactionForm/index.ts b/web/src/components/CreateTestSuiteModal/index.ts similarity index 51% rename from web/src/components/EditTransactionForm/index.ts rename to web/src/components/CreateTestSuiteModal/index.ts index fefb457ab5..5987b89295 100644 --- a/web/src/components/EditTransactionForm/index.ts +++ b/web/src/components/CreateTestSuiteModal/index.ts @@ -1,2 +1,2 @@ // eslint-disable-next-line no-restricted-exports -export {default} from './EditTransactionForm'; +export {default} from './CreateTestSuiteModal'; diff --git a/web/src/components/EditTransaction/EditTransaction.styled.ts b/web/src/components/EditTestSuite/EditTestSuite.styled.ts similarity index 100% rename from web/src/components/EditTransaction/EditTransaction.styled.ts rename to web/src/components/EditTestSuite/EditTestSuite.styled.ts diff --git a/web/src/components/EditTestSuite/EditTestSuite.tsx b/web/src/components/EditTestSuite/EditTestSuite.tsx new file mode 100644 index 0000000000..dae0061d72 --- /dev/null +++ b/web/src/components/EditTestSuite/EditTestSuite.tsx @@ -0,0 +1,55 @@ +import {Button, Form} from 'antd'; +import {useCallback, useState} from 'react'; +import {TDraftTestSuite} from 'types/TestSuite.types'; +import {useTestSuite} from 'providers/TestSuite'; +import useValidateTestSuiteDraft from 'hooks/useValidateTestSuiteDraft'; +import {TestState} from 'constants/TestRun.constants'; +import TestSuiteRun from 'models/TestSuiteRun.model'; +import * as S from './EditTestSuite.styled'; +import EditTestSuiteForm from '../EditTestSuiteForm'; + +interface IProps { + testSuite: TDraftTestSuite; + testSuiteRun: TestSuiteRun; +} + +const EditTestSuite = ({testSuite, testSuiteRun}: IProps) => { + const [form] = Form.useForm(); + const {onEdit, isEditLoading} = useTestSuite(); + const [isFormValid, setIsFormValid] = useState(true); + const stateIsFinished = ([TestState.FINISHED, TestState.FAILED] as string[]).includes(testSuiteRun.state); + + const onChange = useValidateTestSuiteDraft({setIsValid: setIsFormValid}); + + const handleOnSubmit = useCallback( + async (values: TDraftTestSuite) => { + onEdit(values); + }, + [onEdit] + ); + + return ( + + + Edit Test Suite + + + + + + + + ); +}; + +export default EditTestSuite; diff --git a/web/src/components/EditTransaction/index.ts b/web/src/components/EditTestSuite/index.ts similarity index 53% rename from web/src/components/EditTransaction/index.ts rename to web/src/components/EditTestSuite/index.ts index ca27797e60..52bc5f3e5e 100644 --- a/web/src/components/EditTransaction/index.ts +++ b/web/src/components/EditTestSuite/index.ts @@ -1,2 +1,2 @@ // eslint-disable-next-line no-restricted-exports -export {default} from './EditTransaction'; +export {default} from './EditTestSuite'; diff --git a/web/src/components/EditTransactionForm/EditTransactionForm.styled.ts b/web/src/components/EditTestSuiteForm/EditTestSuiteForm.styled.ts similarity index 100% rename from web/src/components/EditTransactionForm/EditTransactionForm.styled.ts rename to web/src/components/EditTestSuiteForm/EditTestSuiteForm.styled.ts diff --git a/web/src/components/EditTestSuiteForm/EditTestSuiteForm.tsx b/web/src/components/EditTestSuiteForm/EditTestSuiteForm.tsx new file mode 100644 index 0000000000..42898caf92 --- /dev/null +++ b/web/src/components/EditTestSuiteForm/EditTestSuiteForm.tsx @@ -0,0 +1,37 @@ +import {Form} from 'antd'; +import {TDraftTestSuite, TDraftTestSuiteForm} from 'types/TestSuite.types'; +import BasicDetailsForm from '../CreateTestPlugins/Default/steps/BasicDetails/BasicDetailsForm'; +import TestsSelectionForm from '../TestSuitePlugin/steps/TestsSelection/TestsSelectionForm'; +import * as S from './EditTestSuiteForm.styled'; + +export const FORM_ID = 'edit-test'; + +interface IProps { + form: TDraftTestSuiteForm; + testSuite: TDraftTestSuite; + onSubmit(values: TDraftTestSuite): Promise; + onValidation(allValues: any, values: TDraftTestSuite): void; +} + +const EditTestSuiteForm = ({form, onSubmit, testSuite, onValidation}: IProps) => { + return ( + + autoComplete="off" + data-cy="edit-test-modal" + form={form} + layout="vertical" + name={FORM_ID} + onFinish={onSubmit} + onValuesChange={onValidation} + initialValues={testSuite} + > + + + + + + + ); +}; + +export default EditTestSuiteForm; diff --git a/web/src/components/TransactionPlugin/index.ts b/web/src/components/EditTestSuiteForm/index.ts similarity index 52% rename from web/src/components/TransactionPlugin/index.ts rename to web/src/components/EditTestSuiteForm/index.ts index a9a27cfea4..2432d3562e 100644 --- a/web/src/components/TransactionPlugin/index.ts +++ b/web/src/components/EditTestSuiteForm/index.ts @@ -1,2 +1,2 @@ // eslint-disable-next-line no-restricted-exports -export {default} from './TransactionPlugin'; +export {default} from './EditTestSuiteForm'; diff --git a/web/src/components/EditTransaction/EditTransaction.tsx b/web/src/components/EditTransaction/EditTransaction.tsx deleted file mode 100644 index f579a2334d..0000000000 --- a/web/src/components/EditTransaction/EditTransaction.tsx +++ /dev/null @@ -1,55 +0,0 @@ -import {Button, Form} from 'antd'; -import {useCallback, useState} from 'react'; -import {TDraftTransaction} from 'types/Transaction.types'; -import {useTransaction} from 'providers/Transaction/Transaction.provider'; -import useValidateTransactionDraft from 'hooks/useValidateTransactionDraft'; -import {TestState} from 'constants/TestRun.constants'; -import TransactionRun from 'models/TransactionRun.model'; -import * as S from './EditTransaction.styled'; -import EditTransactionForm from '../EditTransactionForm'; - -interface IProps { - transaction: TDraftTransaction; - transactionRun: TransactionRun; -} - -const EditTransaction = ({transaction, transactionRun}: IProps) => { - const [form] = Form.useForm(); - const {onEdit, isEditLoading} = useTransaction(); - const [isFormValid, setIsFormValid] = useState(true); - const stateIsFinished = ([TestState.FINISHED, TestState.FAILED] as string[]).includes(transactionRun.state); - - const onChange = useValidateTransactionDraft({setIsValid: setIsFormValid}); - - const handleOnSubmit = useCallback( - async (values: TDraftTransaction) => { - onEdit(values); - }, - [onEdit] - ); - - return ( - - - Edit Transaction - - - - - - - - ); -}; - -export default EditTransaction; diff --git a/web/src/components/EditTransactionForm/EditTransactionForm.tsx b/web/src/components/EditTransactionForm/EditTransactionForm.tsx deleted file mode 100644 index d39ddc8ae8..0000000000 --- a/web/src/components/EditTransactionForm/EditTransactionForm.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import {Form} from 'antd'; -import {TDraftTransaction, TDraftTransactionForm} from 'types/Transaction.types'; -import BasicDetailsForm from '../CreateTestPlugins/Default/steps/BasicDetails/BasicDetailsForm'; -import TestsSelectionForm from '../TransactionPlugin/steps/TestsSelection/TestsSelectionForm'; -import * as S from './EditTransactionForm.styled'; - -export const FORM_ID = 'edit-test'; - -interface IProps { - form: TDraftTransactionForm; - transaction: TDraftTransaction; - onSubmit(values: TDraftTransaction): Promise; - onValidation(allValues: any, values: TDraftTransaction): void; -} - -const EditTransactionForm = ({form, onSubmit, transaction, onValidation}: IProps) => { - return ( - - autoComplete="off" - data-cy="edit-test-modal" - form={form} - layout="vertical" - name={FORM_ID} - onFinish={onSubmit} - onValuesChange={onValidation} - initialValues={transaction} - > - - - - - - - ); -}; - -export default EditTransactionForm; diff --git a/web/src/components/ResourceCard/TransactionCard.tsx b/web/src/components/ResourceCard/TestSuiteCard.tsx similarity index 55% rename from web/src/components/ResourceCard/TransactionCard.tsx rename to web/src/components/ResourceCard/TestSuiteCard.tsx index 39cb775e12..8b8604726b 100644 --- a/web/src/components/ResourceCard/TransactionCard.tsx +++ b/web/src/components/ResourceCard/TestSuiteCard.tsx @@ -1,11 +1,11 @@ import {DownOutlined, RightOutlined} from '@ant-design/icons'; import {useMemo} from 'react'; -import TransactionRunCard from 'components/RunCard/TransactionRunCard'; -import {useLazyGetTransactionRunsQuery} from 'redux/apis/Tracetest'; +import TestSuiteRunCard from 'components/RunCard/TestSuiteRunCard'; +import {useLazyGetTestSuiteRunsQuery} from 'redux/apis/Tracetest'; import {ResourceType} from 'types/Resource.type'; -import Transaction from 'models/Transaction.model'; -import TransactionRun from 'models/TransactionRun.model'; +import TestSuite from 'models/TestSuite.model'; +import TestSuiteRun from 'models/TestSuiteRun.model'; import * as S from './ResourceCard.styled'; import ResourceCardActions from './ResourceCardActions'; import ResourceCardRuns from './ResourceCardRuns'; @@ -15,22 +15,22 @@ import useRuns from './useRuns'; interface IProps { onEdit(id: string, lastRunId: number, type: ResourceType): void; onDelete(id: string, name: string, type: ResourceType): void; - onRun(transaction: Transaction, type: ResourceType): void; + onRun(testSuite: TestSuite, type: ResourceType): void; onViewAll(id: string, type: ResourceType): void; - transaction: Transaction; + testSuite: TestSuite; } -const TransactionCard = ({ +const TestSuiteCard = ({ onEdit, onDelete, onRun, onViewAll, - transaction: {id: transactionId, summary, name, description}, - transaction, + testSuite: {id: testSuiteId, summary, name, description}, + testSuite, }: IProps) => { - const queryParams = useMemo(() => ({take: 5, transactionId}), [transactionId]); - const {isCollapsed, isLoading, list, onClick} = useRuns( - useLazyGetTransactionRunsQuery, + const queryParams = useMemo(() => ({take: 5, testSuiteId}), [testSuiteId]); + const {isCollapsed, isLoading, list, onClick} = useRuns( + useLazyGetTestSuiteRunsQuery, queryParams ); @@ -38,10 +38,10 @@ const TransactionCard = ({ const lastRunId = summary.runs; // assume the total of runs as the last run return ( - + - {isCollapsed ? : } - + {isCollapsed ? : } + {summary.runs} @@ -55,19 +55,19 @@ const TransactionCard = ({ { event.stopPropagation(); - onRun(transaction, ResourceType.Transaction); + onRun(testSuite, ResourceType.TestSuite); }} > Run onDelete(transactionId, name, ResourceType.Transaction)} - onEdit={() => onEdit(transactionId, lastRunId, ResourceType.Transaction)} + onDelete={() => onDelete(testSuiteId, name, ResourceType.TestSuite)} + onEdit={() => onEdit(testSuiteId, lastRunId, ResourceType.TestSuite)} /> @@ -77,16 +77,16 @@ const TransactionCard = ({ hasRuns={Boolean(list.length)} isCollapsed={isCollapsed} isLoading={isLoading} - resourcePath={`/transaction/${transactionId}`} - onViewAll={() => onViewAll(transactionId, ResourceType.Transaction)} + resourcePath={`/testsuite/${testSuiteId}`} + onViewAll={() => onViewAll(testSuiteId, ResourceType.TestSuite)} > {list.map(run => ( - ))} @@ -95,4 +95,4 @@ const TransactionCard = ({ ); }; -export default TransactionCard; +export default TestSuiteCard; diff --git a/web/src/components/Router/Router.tsx b/web/src/components/Router/Router.tsx index 3aa7376e93..6709dbbf6e 100644 --- a/web/src/components/Router/Router.tsx +++ b/web/src/components/Router/Router.tsx @@ -5,9 +5,9 @@ import Home from 'pages/Home'; import RunDetail from 'pages/RunDetail'; import Settings from 'pages/Settings'; import Test from 'pages/Test'; -import Transaction from 'pages/Transaction'; -import TransactionRunOverview from 'pages/TransactionRunOverview'; -import TransactionRunAutomate from 'pages/TransactionRunAutomate'; +import TestSuite from 'pages/TestSuite'; +import TestSuiteRunOverview from 'pages/TestSuiteRunOverview'; +import TestSuiteRunAutomate from 'pages/TestSuiteRunAutomate'; import AutomatedTestRun from 'pages/AutomatedTestRun'; const Router = () => ( @@ -23,10 +23,10 @@ const Router = () => ( } /> } /> - } /> - } /> - } /> - } /> + } /> + } /> + } /> + } /> } /> diff --git a/web/src/components/RunActionsMenu/RunActionsMenu.tsx b/web/src/components/RunActionsMenu/RunActionsMenu.tsx index f38ad390a1..2a02431c4f 100644 --- a/web/src/components/RunActionsMenu/RunActionsMenu.tsx +++ b/web/src/components/RunActionsMenu/RunActionsMenu.tsx @@ -11,11 +11,11 @@ interface IProps { resultId: string; testId: string; isRunView?: boolean; - transactionId?: string; - transactionRunId: string; + testSuiteId?: string; + testSuiteRunId: string; } -const RunActionsMenu = ({resultId, testId, transactionId, transactionRunId, isRunView = false}: IProps) => { +const RunActionsMenu = ({resultId, testId, testSuiteId, testSuiteRunId, isRunView = false}: IProps) => { const {onJUnit} = useFileViewerModal(); const {navigate} = useDashboard(); const onDelete = useDeleteResourceRun({id: testId, isRunView, type: ResourceType.Test}); @@ -25,15 +25,15 @@ const RunActionsMenu = ({resultId, testId, transactionId, transactionRunId, isRu - {!!transactionId && !!transactionRunId && ( + {!!testSuiteId && !!testSuiteRunId && ( { - navigate(`/transaction/${transactionId}/run/${transactionRunId}`); + navigate(`/testsuite/${testSuiteId}/run/${testSuiteRunId}`); }} > - Transaction Run + Test Suite Run )} - {!!transactionId && !!transactionRunId && Part of transaction} + {!!testSuiteId && !!testSuiteRunId && Part of test suite} {!isRunStateFinished(state) && (
@@ -111,8 +111,8 @@ const TestRunCard = ({
diff --git a/web/src/components/RunCard/TransactionRunCard.tsx b/web/src/components/RunCard/TestSuiteRunCard.tsx similarity index 81% rename from web/src/components/RunCard/TransactionRunCard.tsx rename to web/src/components/RunCard/TestSuiteRunCard.tsx index 14a1b995bd..ddbdc436da 100644 --- a/web/src/components/RunCard/TransactionRunCard.tsx +++ b/web/src/components/RunCard/TestSuiteRunCard.tsx @@ -1,22 +1,22 @@ import {Tooltip} from 'antd'; import Link from 'components/Link'; import TestState from 'components/TestState'; -import TransactionRunActionsMenu from 'components/TransactionRunActionsMenu'; +import TestSuiteRunActionsMenu from 'components/TestSuiteRunActionsMenu'; import {TestState as TestStateEnum} from 'constants/TestRun.constants'; -import TransactionRun from 'models/TransactionRun.model'; +import TestSuiteRun from 'models/TestSuiteRun.model'; import Date from 'utils/Date'; import * as S from './RunCard.styled'; -import {TransactionRunStatusIcon} from '../RunStatusIcon'; +import {TestSuiteRunStatusIcon} from '../RunStatusIcon'; interface IProps { linkTo: string; - run: TransactionRun; - transactionId: string; + run: TestSuiteRun; + testSuiteId: string; } -const TransactionRunCard = ({ +const TestSuiteRunCard = ({ run: {id: runId, createdAt, state, metadata, version, pass, fail, allStepsRequiredGatesPassed}, - transactionId, + testSuiteId, linkTo, }: IProps) => { const metadataName = metadata?.name; @@ -27,7 +27,7 @@ const TransactionRunCard = ({ return ( - +
v{version} @@ -72,11 +72,11 @@ const TransactionRunCard = ({ )}
- +
); }; -export default TransactionRunCard; +export default TestSuiteRunCard; diff --git a/web/src/components/RunDetailLayout/HeaderLeft.tsx b/web/src/components/RunDetailLayout/HeaderLeft.tsx index 12ea09ac0d..6efac490b8 100644 --- a/web/src/components/RunDetailLayout/HeaderLeft.tsx +++ b/web/src/components/RunDetailLayout/HeaderLeft.tsx @@ -12,7 +12,7 @@ interface IProps { } const HeaderLeft = ({name, triggerType}: IProps) => { - const {run: {createdAt, transactionId, transactionRunId, executionTime, trace, traceId, testVersion} = {}, run} = + const {run: {createdAt, testSuiteId, testSuiteRunId, executionTime, trace, traceId, testVersion} = {}, run} = useTestRun(); const createdTimeAgo = Date.getTimeAgo(createdAt ?? ''); const {navigate} = useDashboard(); @@ -21,18 +21,18 @@ const HeaderLeft = ({name, triggerType}: IProps) => { return ( <> {triggerType} • Ran {createdTimeAgo} - {transactionId && transactionRunId && ( + {testSuiteId && testSuiteRunId && ( <> {' '} •{' '} - - Part of transaction + + Part of test suite )} ); - }, [createdTimeAgo, transactionId, transactionRunId, triggerType]); + }, [triggerType, createdTimeAgo, testSuiteId, testSuiteRunId]); return ( diff --git a/web/src/components/RunDetailLayout/HeaderRight.tsx b/web/src/components/RunDetailLayout/HeaderRight.tsx index 28af4397bc..ceeb9c3bbb 100644 --- a/web/src/components/RunDetailLayout/HeaderRight.tsx +++ b/web/src/components/RunDetailLayout/HeaderRight.tsx @@ -65,8 +65,8 @@ const HeaderRight = ({testId}: IProps) => { isRunView resultId={run.id} testId={testId} - transactionId={run.transactionId} - transactionRunId={run.transactionRunId} + testSuiteRunId={run.testSuiteRunId} + testSuiteId={run.testSuiteId} /> ); diff --git a/web/src/components/RunDetailLayout/Info.tsx b/web/src/components/RunDetailLayout/Info.tsx index 75dfbbe581..c59f9cf343 100644 --- a/web/src/components/RunDetailLayout/Info.tsx +++ b/web/src/components/RunDetailLayout/Info.tsx @@ -25,7 +25,7 @@ const Info = ({date, executionTime, state, totalSpans, traceId}: IProps) => { {traceId}
- Trace transaction occurred: + Trace test suite occurred: {Date.format(date, "yyyy/MM/dd 'at' HH:mm:ss")}
diff --git a/web/src/components/RunStatusIcon/TransactionRunStatusIcon.tsx b/web/src/components/RunStatusIcon/TestSuiteRunStatusIcon.tsx similarity index 73% rename from web/src/components/RunStatusIcon/TransactionRunStatusIcon.tsx rename to web/src/components/RunStatusIcon/TestSuiteRunStatusIcon.tsx index f1530c565a..cf1bca4c26 100644 --- a/web/src/components/RunStatusIcon/TransactionRunStatusIcon.tsx +++ b/web/src/components/RunStatusIcon/TestSuiteRunStatusIcon.tsx @@ -1,9 +1,9 @@ -import TransactionRun from 'models/TransactionRun.model'; +import TestSuiteRun from 'models/TestSuiteRun.model'; import {TestState} from 'constants/TestRun.constants'; import * as S from './RunStatusIcon.styled'; interface IProps { - state: TransactionRun['state']; + state: TestSuiteRun['state']; hasFailedTests: boolean; } @@ -19,7 +19,7 @@ const Icon = ({state, hasFailedTests}: IProps) => { return ; }; -const TransactionRunStatusIcon = (props: IProps) => { +const TestSuiteRunStatusIcon = (props: IProps) => { return ( @@ -27,4 +27,4 @@ const TransactionRunStatusIcon = (props: IProps) => { ); }; -export default TransactionRunStatusIcon; +export default TestSuiteRunStatusIcon; diff --git a/web/src/components/RunStatusIcon/index.ts b/web/src/components/RunStatusIcon/index.ts index 3939a3330a..fd5a0b14a8 100644 --- a/web/src/components/RunStatusIcon/index.ts +++ b/web/src/components/RunStatusIcon/index.ts @@ -1,5 +1,5 @@ -import TransactionRunStatusIcon from './TransactionRunStatusIcon'; +import TestSuiteRunStatusIcon from './TestSuiteRunStatusIcon'; // eslint-disable-next-line no-restricted-exports export {default} from './RunStatusIcon'; -export {TransactionRunStatusIcon}; +export {TestSuiteRunStatusIcon}; diff --git a/web/src/components/TestOutputs/Empty.tsx b/web/src/components/TestOutputs/Empty.tsx index c3224b2870..b032e701bb 100644 --- a/web/src/components/TestOutputs/Empty.tsx +++ b/web/src/components/TestOutputs/Empty.tsx @@ -5,7 +5,7 @@ const Empty = () => ( There are no outputs for this test - Outputs create variables that are used in tests within a transaction. + Outputs create variables that are used in tests within a test suite. Learn more about outputs{' '} diff --git a/web/src/components/TransactionHeader/TransactionHeader.styled.ts b/web/src/components/TestSuiteHeader/TestSuiteHeader.styled.ts similarity index 100% rename from web/src/components/TransactionHeader/TransactionHeader.styled.ts rename to web/src/components/TestSuiteHeader/TestSuiteHeader.styled.ts diff --git a/web/src/components/TransactionHeader/TransactionHeader.tsx b/web/src/components/TestSuiteHeader/TestSuiteHeader.tsx similarity index 54% rename from web/src/components/TransactionHeader/TransactionHeader.tsx rename to web/src/components/TestSuiteHeader/TestSuiteHeader.tsx index 339d492de5..16eb294bb4 100644 --- a/web/src/components/TransactionHeader/TransactionHeader.tsx +++ b/web/src/components/TestSuiteHeader/TestSuiteHeader.tsx @@ -1,18 +1,18 @@ import {Button} from 'antd'; import {useLocation} from 'react-router-dom'; -import {TransactionRunStatusIcon} from 'components/RunStatusIcon'; +import {TestSuiteRunStatusIcon} from 'components/RunStatusIcon'; import TestState from 'components/TestState'; -import TransactionRunActionsMenu from 'components/TransactionRunActionsMenu'; +import TestSuiteRunActionsMenu from 'components/TestSuiteRunActionsMenu'; import {TestState as TestStateEnum} from 'constants/TestRun.constants'; import {useDashboard} from 'providers/Dashboard/Dashboard.provider'; -import {useTransaction} from 'providers/Transaction/Transaction.provider'; -import {useTransactionRun} from 'providers/TransactionRun/TransactionRun.provider'; -import * as S from './TransactionHeader.styled'; +import {useTestSuite} from 'providers/TestSuite/TestSuite.provider'; +import {useTestSuiteRun} from 'providers/TestSuiteRun/TestSuite.provider'; +import * as S from './TestSuiteHeader.styled'; -const transactionLastPathRegex = /\/transaction\/[\w-]+\/run\/[\d-]+\/([\w-]+)/; +const testSuiteLastPathRegex = /\/testsuite\/[\w-]+\/run\/[\d-]+\/([\w-]+)/; function getLastPath(pathname: string): string { - const match = pathname.match(transactionLastPathRegex); + const match = pathname.match(testSuiteLastPathRegex); if (match === null) { return ''; } @@ -25,23 +25,23 @@ const LINKS = [ {id: 'automate', label: 'Automate'}, ]; -const TransactionHeader = () => { - const {transaction, onRun} = useTransaction(); - const {transactionRun} = useTransactionRun(); +const TestSuiteHeader = () => { + const {testSuite, onRun} = useTestSuite(); + const {run} = useTestSuiteRun(); const {navigate} = useDashboard(); const {pathname} = useLocation(); - const {id: transactionId, name, version, description} = transaction; - const {state, id: runId, allStepsRequiredGatesPassed} = transactionRun; + const {id: testSuiteId, name, version, description} = testSuite; + const {state, id: runId, allStepsRequiredGatesPassed} = run; const lastPath = getLastPath(pathname); return ( - navigate('/')} data-cy="transaction-header-back-button"> + navigate('/')} data-cy="testsuite-header-back-button">
- + {name} (v{version}) {description} @@ -52,7 +52,7 @@ const TransactionHeader = () => { {LINKS.map(({id, label}) => ( {label} @@ -62,23 +62,23 @@ const TransactionHeader = () => { {state && state !== TestStateEnum.FINISHED && ( - + Status: )} {state && state === TestStateEnum.FINISHED && ( <> - - )} - + ); }; -export default TransactionHeader; +export default TestSuiteHeader; diff --git a/web/src/components/TransactionHeader/index.tsx b/web/src/components/TestSuiteHeader/index.tsx similarity index 52% rename from web/src/components/TransactionHeader/index.tsx rename to web/src/components/TestSuiteHeader/index.tsx index 34863e4ce7..90d7e2ccad 100644 --- a/web/src/components/TransactionHeader/index.tsx +++ b/web/src/components/TestSuiteHeader/index.tsx @@ -1,2 +1,2 @@ // eslint-disable-next-line no-restricted-exports -export {default} from './TransactionHeader'; +export {default} from './TestSuiteHeader'; diff --git a/web/src/components/TestSuitePlugin/CreateTestSuiteFactory.tsx b/web/src/components/TestSuitePlugin/CreateTestSuiteFactory.tsx new file mode 100644 index 0000000000..adfd3a5d66 --- /dev/null +++ b/web/src/components/TestSuitePlugin/CreateTestSuiteFactory.tsx @@ -0,0 +1,14 @@ +import {ICreateTestStep} from 'types/Plugins.types'; +import TestSuitedPlugin from '.'; + +interface IProps { + step: ICreateTestStep; +} + +const CreateTestSuiteFactory = ({step: {component}}: IProps) => { + const Step = TestSuitedPlugin[component]; + + return ; +}; + +export default CreateTestSuiteFactory; diff --git a/web/src/components/TransactionPlugin/TransactionPlugin.ts b/web/src/components/TestSuitePlugin/TestSuitePlugin.ts similarity index 100% rename from web/src/components/TransactionPlugin/TransactionPlugin.ts rename to web/src/components/TestSuitePlugin/TestSuitePlugin.ts diff --git a/web/src/components/TestSuitePlugin/index.ts b/web/src/components/TestSuitePlugin/index.ts new file mode 100644 index 0000000000..237dcd97ff --- /dev/null +++ b/web/src/components/TestSuitePlugin/index.ts @@ -0,0 +1,2 @@ +// eslint-disable-next-line no-restricted-exports +export {default} from './TestSuitePlugin'; diff --git a/web/src/components/TransactionPlugin/steps/BasicDetails/BasicDetails.tsx b/web/src/components/TestSuitePlugin/steps/BasicDetails/BasicDetails.tsx similarity index 61% rename from web/src/components/TransactionPlugin/steps/BasicDetails/BasicDetails.tsx rename to web/src/components/TestSuitePlugin/steps/BasicDetails/BasicDetails.tsx index 7375b4dabb..ba007d52d0 100644 --- a/web/src/components/TransactionPlugin/steps/BasicDetails/BasicDetails.tsx +++ b/web/src/components/TestSuitePlugin/steps/BasicDetails/BasicDetails.tsx @@ -1,24 +1,24 @@ import {Form} from 'antd'; import {useCallback} from 'react'; import * as Step from 'components/CreateTestPlugins/Step.styled'; -import {useCreateTransaction} from 'providers/CreateTransaction/CreateTransaction.provider'; -import {TDraftTransaction} from 'types/Transaction.types'; +import {useCreateTestSuite} from 'providers/CreateTestSuite'; +import {TDraftTestSuite} from 'types/TestSuite.types'; import BasicDetailsForm from 'components/CreateTestPlugins/Default/steps/BasicDetails/BasicDetailsForm'; import {ComponentNames} from 'constants/Plugins.constants'; const BasicDetails = () => { - const [form] = Form.useForm(); - const {onNext, onIsFormValid} = useCreateTransaction(); + const [form] = Form.useForm(); + const {onNext, onIsFormValid} = useCreateTestSuite(); const handleSubmit = useCallback( - ({name, description}: TDraftTransaction) => { + ({name, description}: TDraftTestSuite) => { onNext({name, description}); }, [onNext] ); const onValidate = useCallback( - async (changedValues, draft: TDraftTransaction) => { + async (changedValues, draft: TDraftTestSuite) => { onIsFormValid(!!draft.name); }, [onIsFormValid] @@ -27,12 +27,12 @@ const BasicDetails = () => { return ( - Name your Transaction + Name your Test Suite - Create a transaction which will run several tests in sequence. You can set outputs into variables and use - these variables later in the transaction in other tests.{' '} + Create a test suite which will run several tests in sequence. You can set outputs into variables and use + these variables later in the test suite in other tests.{' '} - + id={ComponentNames.BasicDetails} autoComplete="off" data-cy="create-test-modal" diff --git a/web/src/components/TransactionPlugin/steps/BasicDetails/index.ts b/web/src/components/TestSuitePlugin/steps/BasicDetails/index.ts similarity index 100% rename from web/src/components/TransactionPlugin/steps/BasicDetails/index.ts rename to web/src/components/TestSuitePlugin/steps/BasicDetails/index.ts diff --git a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelection.tsx b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelection.tsx similarity index 68% rename from web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelection.tsx rename to web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelection.tsx index bf5cae9187..ee2bc4004b 100644 --- a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelection.tsx +++ b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelection.tsx @@ -1,17 +1,17 @@ import {Form} from 'antd'; import {useCallback} from 'react'; import * as Step from 'components/CreateTestPlugins/Step.styled'; -import {useCreateTransaction} from 'providers/CreateTransaction/CreateTransaction.provider'; -import {TDraftTransaction} from 'types/Transaction.types'; +import {useCreateTestSuite} from 'providers/CreateTestSuite'; +import {TDraftTestSuite} from 'types/TestSuite.types'; import {ComponentNames} from 'constants/Plugins.constants'; import TestsSelectionForm from './TestsSelectionForm'; const TestsSelection = () => { - const [form] = Form.useForm(); - const {onNext} = useCreateTransaction(); + const [form] = Form.useForm(); + const {onNext} = useCreateTestSuite(); const handleSubmit = useCallback( - ({steps = []}: TDraftTransaction) => { + ({steps = []}: TDraftTestSuite) => { onNext({steps}); }, [onNext] @@ -21,11 +21,11 @@ const TestsSelection = () => { Tests - Define the tests and their order of execution for this transaction - + Define the tests and their order of execution for this test suite + id={ComponentNames.TestsSelection} autoComplete="off" - data-cy="create-transaction-modal" + data-cy="create-testsuite-modal" form={form} layout="vertical" onFinish={handleSubmit} diff --git a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionForm.tsx b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionForm.tsx similarity index 100% rename from web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionForm.tsx rename to web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionForm.tsx diff --git a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestItem.tsx b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestItem.tsx similarity index 100% rename from web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestItem.tsx rename to web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestItem.tsx diff --git a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestItemList.tsx b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestItemList.tsx similarity index 100% rename from web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestItemList.tsx rename to web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestItemList.tsx diff --git a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.styled.ts b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.styled.ts similarity index 100% rename from web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.styled.ts rename to web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.styled.ts diff --git a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.tsx b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.tsx similarity index 98% rename from web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.tsx rename to web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.tsx index 6724c4dce7..1668b29cf7 100644 --- a/web/src/components/TransactionPlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.tsx +++ b/web/src/components/TestSuitePlugin/steps/TestsSelection/TestsSelectionInput/TestsSelectionInput.tsx @@ -83,7 +83,7 @@ const TestsSelectionInput = ({value = [], onChange = noop, testList}: IProps) =>