How to use MapTestCRToAPI method of tests Package

Best Testkube code snippet using tests.MapTestCRToAPI

executions.go

Source:executions.go Github

copy

Full Screen

...82 testkube.Test, testkube.ExecutionRequest, testkube.Execution] {83 requests := make([]workerpool.Request[testkube.Test, testkube.ExecutionRequest, testkube.Execution], len(work))84 for i := range work {85 requests[i] = workerpool.Request[testkube.Test, testkube.ExecutionRequest, testkube.Execution]{86 Object: testsmapper.MapTestCRToAPI(work[i]),87 Options: request,88 ExecFn: s.executeTest,89 }90 }91 return requests92}93func (s TestkubeAPI) executeTest(ctx context.Context, test testkube.Test, request testkube.ExecutionRequest) (94 execution testkube.Execution, err error) {95 // generate random execution name in case there is no one set96 // like for docker images97 if request.Name == "" && test.ExecutionRequest != nil && test.ExecutionRequest.Name != "" {98 request.Name = test.ExecutionRequest.Name99 }100 if request.Name == "" {101 request.Name = test.Name102 }103 request.Number = s.getNextExecutionNumber(test.Name)104 request.Name = fmt.Sprintf("%s-%d", request.Name, request.Number)105 // test name + test execution name should be unique106 execution, _ = s.ExecutionResults.GetByNameAndTest(ctx, request.Name, test.Name)107 if execution.Name == request.Name {108 return execution.Err(fmt.Errorf("test execution with name %s already exists", request.Name)), nil109 }110 secretUUID, err := s.TestsClient.GetCurrentSecretUUID(test.Name)111 if err != nil {112 return execution.Errw("can't get current secret uuid: %w", err), nil113 }114 request.TestSecretUUID = secretUUID115 // merge available data into execution options test spec, executor spec, request, test id116 options, err := s.GetExecuteOptions(test.Namespace, test.Name, request)117 if err != nil {118 return execution.Errw("can't create valid execution options: %w", err), nil119 }120 // store execution in storage, can be get from API now121 execution = newExecutionFromExecutionOptions(options)122 options.ID = execution.Id123 if err := s.createSecretsReferences(&execution); err != nil {124 return execution.Errw("can't create secret variables `Secret` references: %w", err), nil125 }126 err = s.ExecutionResults.Insert(ctx, execution)127 if err != nil {128 return execution.Errw("can't create new test execution, can't insert into storage: %w", err), nil129 }130 s.Log.Infow("calling executor with options", "options", options.Request)131 execution.Start()132 s.Events.Notify(testkube.NewEventStartTest(&execution))133 // update storage with current execution status134 err = s.ExecutionResults.StartExecution(ctx, execution.Id, execution.StartTime)135 if err != nil {136 s.Events.Notify(testkube.NewEventEndTestFailed(&execution))137 return execution.Errw("can't execute test, can't insert into storage error: %w", err), nil138 }139 options.HasSecrets = true140 if _, err = s.SecretClient.Get(secret.GetMetadataName(execution.TestName)); err != nil {141 if !errors.IsNotFound(err) {142 s.Events.Notify(testkube.NewEventEndTestFailed(&execution))143 return execution.Errw("can't get secrets: %w", err), nil144 }145 options.HasSecrets = false146 }147 var result testkube.ExecutionResult148 // sync/async test execution149 if options.Sync {150 result, err = s.Executor.ExecuteSync(&execution, options)151 } else {152 result, err = s.Executor.Execute(&execution, options)153 }154 // set execution result to one created155 execution.ExecutionResult = &result156 // update storage with current execution status157 if uerr := s.ExecutionResults.UpdateResult(ctx, execution.Id, result); uerr != nil {158 s.Events.Notify(testkube.NewEventEndTestFailed(&execution))159 return execution.Errw("update execution error: %w", uerr), nil160 }161 if err != nil {162 s.Events.Notify(testkube.NewEventEndTestFailed(&execution))163 return execution.Errw("test execution failed: %w", err), nil164 }165 s.Log.Infow("test started", "executionId", execution.Id, "status", execution.ExecutionResult.Status)166 // notify immediately onlly when sync run otherwise job results handler need notify about test finish167 if options.Sync && execution.ExecutionResult != nil && *execution.ExecutionResult.Status != testkube.RUNNING_ExecutionStatus {168 s.Events.Notify(testkube.NewEventEndTestSuccess(&execution))169 }170 return execution, nil171}172// createSecretsReferences strips secrets from text and store it inside model as reference to secret173func (s TestkubeAPI) createSecretsReferences(execution *testkube.Execution) (err error) {174 secrets := map[string]string{}175 secretName := execution.Id + "-vars"176 for k, v := range execution.Variables {177 if v.IsSecret() {178 obfuscated := execution.Variables[k]179 if v.SecretRef != nil {180 obfuscated.SecretRef = &testkube.SecretRef{181 Namespace: execution.TestNamespace,182 Name: v.SecretRef.Name,183 Key: v.SecretRef.Key,184 }185 } else {186 obfuscated.Value = ""187 obfuscated.SecretRef = &testkube.SecretRef{188 Namespace: execution.TestNamespace,189 Name: secretName,190 Key: v.Name,191 }192 secrets[v.Name] = v.Value193 }194 execution.Variables[k] = obfuscated195 }196 }197 labels := map[string]string{"executionID": execution.Id, "testName": execution.TestName}198 if len(secrets) > 0 {199 return s.SecretClient.Create(200 secretName,201 labels,202 secrets,203 )204 }205 return nil206}207// ListExecutionsHandler returns array of available test executions208func (s TestkubeAPI) ListExecutionsHandler() fiber.Handler {209 return func(c *fiber.Ctx) error {210 // TODO refactor into some Services (based on some abstraction for CRDs at least / CRUD)211 // should we split this to separate endpoint? currently this one handles212 // endpoints from /executions and from /tests/{id}/executions213 // or should id be a query string as it's some kind of filter?214 filter := getFilterFromRequest(c)215 executions, err := s.ExecutionResults.GetExecutions(c.Context(), filter)216 if err != nil {217 return s.Error(c, http.StatusInternalServerError, err)218 }219 executionTotals, err := s.ExecutionResults.GetExecutionTotals(c.Context(), false, filter)220 if err != nil {221 return s.Error(c, http.StatusInternalServerError, err)222 }223 filteredTotals, err := s.ExecutionResults.GetExecutionTotals(c.Context(), true, filter)224 if err != nil {225 return s.Error(c, http.StatusInternalServerError, err)226 }227 results := testkube.ExecutionsResult{228 Totals: &executionTotals,229 Filtered: &filteredTotals,230 Results: mapExecutionsToExecutionSummary(executions),231 }232 return c.JSON(results)233 }234}235func (s TestkubeAPI) ExecutionLogsStreamHandler() fiber.Handler {236 return websocket.New(func(c *websocket.Conn) {237 executionID := c.Params("executionID")238 l := s.Log.With("executionID", executionID)239 l.Debugw("getting pod logs and passing to websocket", "id", c.Params("id"), "locals", c.Locals, "remoteAddr", c.RemoteAddr(), "localAddr", c.LocalAddr())240 logs, err := s.Executor.Logs(executionID)241 if err != nil {242 l.Errorw("can't get pod logs", "error", err)243 c.Conn.Close()244 return245 }246 for logLine := range logs {247 l.Debugw("sending log line to websocket", "line", logLine)248 c.WriteJSON(logLine)249 }250 })251}252// ExecutionLogsHandler streams the logs from a test execution253func (s *TestkubeAPI) ExecutionLogsHandler() fiber.Handler {254 return func(c *fiber.Ctx) error {255 executionID := c.Params("executionID")256 s.Log.Debug("getting logs", "executionID", executionID)257 ctx := c.Context()258 ctx.SetContentType("text/event-stream")259 ctx.Response.Header.Set("Cache-Control", "no-cache")260 ctx.Response.Header.Set("Connection", "keep-alive")261 ctx.Response.Header.Set("Transfer-Encoding", "chunked")262 ctx.SetBodyStreamWriter(fasthttp.StreamWriter(func(w *bufio.Writer) {263 s.Log.Debug("starting stream writer")264 w.Flush()265 execution, err := s.ExecutionResults.Get(ctx, executionID)266 if err != nil {267 output.PrintError(os.Stdout, fmt.Errorf("could not get execution result for ID %s: %w", executionID, err))268 s.Log.Errorw("getting execution error", "error", err)269 w.Flush()270 return271 }272 if execution.ExecutionResult.IsCompleted() {273 err := s.streamLogsFromResult(execution.ExecutionResult, w)274 if err != nil {275 output.PrintError(os.Stdout, fmt.Errorf("could not get execution result for ID %s: %w", executionID, err))276 s.Log.Errorw("getting execution error", "error", err)277 w.Flush()278 }279 return280 }281 s.streamLogsFromJob(executionID, w)282 }))283 return nil284 }285}286// GetExecutionHandler returns test execution object for given test and execution id/name287func (s TestkubeAPI) GetExecutionHandler() fiber.Handler {288 return func(c *fiber.Ctx) error {289 ctx := c.Context()290 id := c.Params("id", "")291 executionID := c.Params("executionID")292 var execution testkube.Execution293 var err error294 if id == "" {295 execution, err = s.ExecutionResults.Get(ctx, executionID)296 if err == mongo.ErrNoDocuments {297 execution, err = s.ExecutionResults.GetByName(ctx, executionID)298 if err == mongo.ErrNoDocuments {299 return s.Error(c, http.StatusNotFound, fmt.Errorf("test with execution id/name %s not found", executionID))300 }301 }302 if err != nil {303 return s.Error(c, http.StatusInternalServerError, err)304 }305 } else {306 execution, err = s.ExecutionResults.GetByNameAndTest(ctx, executionID, id)307 if err == mongo.ErrNoDocuments {308 return s.Error(c, http.StatusNotFound, fmt.Errorf("test %s/%s not found", id, executionID))309 }310 if err != nil {311 return s.Error(c, http.StatusInternalServerError, err)312 }313 }314 execution.Duration = types.FormatDuration(execution.Duration)315 testSecretMap := make(map[string]string)316 if execution.TestSecretUUID != "" {317 testSecretMap, err = s.TestsClient.GetSecretTestVars(execution.TestName, execution.TestSecretUUID)318 if err != nil {319 return s.Error(c, http.StatusInternalServerError, err)320 }321 }322 testSuiteSecretMap := make(map[string]string)323 if execution.TestSuiteSecretUUID != "" {324 testSuiteSecretMap, err = s.TestsSuitesClient.GetSecretTestSuiteVars(execution.TestSuiteName, execution.TestSuiteSecretUUID)325 if err != nil {326 return s.Error(c, http.StatusInternalServerError, err)327 }328 }329 for key, value := range testSuiteSecretMap {330 testSecretMap[key] = value331 }332 for key, value := range testSecretMap {333 if variable, ok := execution.Variables[key]; ok && value != "" {334 variable.Value = string(value)335 variable.SecretRef = nil336 execution.Variables[key] = variable337 }338 }339 s.Log.Debugw("get test execution request - debug", "execution", execution)340 return c.JSON(execution)341 }342}343func (s TestkubeAPI) AbortExecutionHandler() fiber.Handler {344 return func(c *fiber.Ctx) error {345 ctx := c.Context()346 executionID := c.Params("executionID")347 execution, err := s.ExecutionResults.Get(ctx, executionID)348 if err == mongo.ErrNoDocuments {349 return s.Error(c, http.StatusNotFound, fmt.Errorf("test with execution id %s not found", executionID))350 }351 if err != nil {352 return s.Error(c, http.StatusInternalServerError, err)353 }354 result := s.Executor.Abort(executionID)355 s.Metrics.IncAbortTest(execution.TestType, result.IsFailed())356 return err357 }358}359func (s TestkubeAPI) GetArtifactHandler() fiber.Handler {360 return func(c *fiber.Ctx) error {361 executionID := c.Params("executionID")362 fileName := c.Params("filename")363 // TODO fix this someday :) we don't know 15 mins before release why it's working this way364 // remember about CLI client and Dashboard client too!365 unescaped, err := url.QueryUnescape(fileName)366 if err == nil {367 fileName = unescaped368 }369 unescaped, err = url.QueryUnescape(fileName)370 if err == nil {371 fileName = unescaped372 }373 //// quickfix end374 file, err := s.Storage.DownloadFile(executionID, fileName)375 if err != nil {376 return s.Error(c, http.StatusInternalServerError, err)377 }378 defer file.Close()379 return c.SendStream(file)380 }381}382// GetArtifacts returns list of files in the given bucket383func (s TestkubeAPI) ListArtifactsHandler() fiber.Handler {384 return func(c *fiber.Ctx) error {385 executionID := c.Params("executionID")386 files, err := s.Storage.ListFiles(executionID)387 if err != nil {388 return s.Error(c, http.StatusInternalServerError, err)389 }390 return c.JSON(files)391 }392}393func (s TestkubeAPI) GetExecuteOptions(namespace, id string, request testkube.ExecutionRequest) (options client.ExecuteOptions, err error) {394 // get test content from kubernetes CRs395 testCR, err := s.TestsClient.Get(id)396 if err != nil {397 return options, fmt.Errorf("can't get test custom resource %w", err)398 }399 test := testsmapper.MapTestCRToAPI(*testCR)400 if test.ExecutionRequest != nil {401 // Test variables lowest priority, then test suite, then test suite execution / test execution402 request.Variables = mergeVariables(test.ExecutionRequest.Variables, request.Variables)403 // Combine test executor args with execution args404 request.Args = append(request.Args, test.ExecutionRequest.Args...)405 request.Envs = mergeEnvs(request.Envs, test.ExecutionRequest.Envs)406 request.SecretEnvs = mergeEnvs(request.SecretEnvs, test.ExecutionRequest.SecretEnvs)407 if request.VariablesFile == "" && test.ExecutionRequest.VariablesFile != "" {408 request.VariablesFile = test.ExecutionRequest.VariablesFile409 }410 if request.HttpProxy == "" && test.ExecutionRequest.HttpProxy != "" {411 request.HttpProxy = test.ExecutionRequest.HttpProxy412 }413 if request.HttpsProxy == "" && test.ExecutionRequest.HttpsProxy != "" {...

Full Screen

Full Screen

tests.go

Source:tests.go Github

copy

Full Screen

...26 return s.Error(c, http.StatusNotFound, err)27 }28 return s.Error(c, http.StatusBadGateway, err)29 }30 test := testsmapper.MapTestCRToAPI(*crTest)31 if c.Accepts(mediaTypeJSON, mediaTypeYAML) == mediaTypeYAML {32 if test.Content != nil && test.Content.Data != "" {33 test.Content.Data = fmt.Sprintf("%q", test.Content.Data)34 }35 if test.ExecutionRequest != nil && test.ExecutionRequest.VariablesFile != "" {36 test.ExecutionRequest.VariablesFile = fmt.Sprintf("%q", test.ExecutionRequest.VariablesFile)37 }38 data, err := crd.GenerateYAML(crd.TemplateTest, []testkube.Test{test})39 return s.getCRDs(c, data, err)40 }41 return c.JSON(test)42 }43}44// GetTestWithExecutionHandler is method for getting an existing test with execution45func (s TestkubeAPI) GetTestWithExecutionHandler() fiber.Handler {46 return func(c *fiber.Ctx) error {47 name := c.Params("id")48 crTest, err := s.TestsClient.Get(name)49 if err != nil {50 if errors.IsNotFound(err) {51 return s.Error(c, http.StatusNotFound, err)52 }53 return s.Error(c, http.StatusBadGateway, err)54 }55 test := testsmapper.MapTestCRToAPI(*crTest)56 if c.Accepts(mediaTypeJSON, mediaTypeYAML) == mediaTypeYAML {57 if test.Content != nil && test.Content.Data != "" {58 test.Content.Data = fmt.Sprintf("%q", test.Content.Data)59 }60 if test.ExecutionRequest != nil && test.ExecutionRequest.VariablesFile != "" {61 test.ExecutionRequest.VariablesFile = fmt.Sprintf("%q", test.ExecutionRequest.VariablesFile)62 }63 data, err := crd.GenerateYAML(crd.TemplateTest, []testkube.Test{test})64 return s.getCRDs(c, data, err)65 }66 ctx := c.Context()67 startExecution, startErr := s.ExecutionResults.GetLatestByTest(ctx, name, "starttime")68 if startErr != nil && startErr != mongo.ErrNoDocuments {69 return s.Error(c, http.StatusInternalServerError, startErr)...

Full Screen

Full Screen

kube_openapi.go

Source:kube_openapi.go Github

copy

Full Screen

...7// MapTestListKubeToAPI maps CRD list data to OpenAPI spec tests list8func MapTestListKubeToAPI(crTests testsv3.TestList) (tests []testkube.Test) {9 tests = []testkube.Test{}10 for _, item := range crTests.Items {11 tests = append(tests, MapTestCRToAPI(item))12 }13 return14}15// MapTestCRToAPI maps CRD to OpenAPI spec test16func MapTestCRToAPI(crTest testsv3.Test) (test testkube.Test) {17 test.Name = crTest.Name18 test.Namespace = crTest.Namespace19 test.Content = MapTestContentFromSpec(crTest.Spec.Content)20 test.Created = crTest.CreationTimestamp.Time21 test.Type_ = crTest.Spec.Type_22 test.Labels = crTest.Labels23 test.Schedule = crTest.Spec.Schedule24 test.ExecutionRequest = MapExecutionRequestFromSpec(crTest.Spec.ExecutionRequest)25 return26}27func MergeVariablesAndParams(variables map[string]testsv3.Variable, params map[string]string) map[string]testkube.Variable {28 out := map[string]testkube.Variable{}29 for k, v := range params {30 out[k] = testkube.NewBasicVariable(k, v)31 }32 for k, v := range variables {33 if v.Type_ == commonv1.VariableTypeSecret {34 if v.ValueFrom.SecretKeyRef == nil {35 out[k] = testkube.NewSecretVariable(v.Name, v.Value)36 } else {37 out[k] = testkube.NewSecretVariableReference(v.Name, v.ValueFrom.SecretKeyRef.Name, v.ValueFrom.SecretKeyRef.Key)38 }39 }40 if v.Type_ == commonv1.VariableTypeBasic {41 out[k] = testkube.NewBasicVariable(v.Name, v.Value)42 }43 }44 return out45}46// MapTestContentFromSpec maps CRD to OpenAPI spec TestContent47func MapTestContentFromSpec(specContent *testsv3.TestContent) *testkube.TestContent {48 content := &testkube.TestContent{}49 if specContent != nil {50 content.Type_ = specContent.Type_51 content.Data = specContent.Data52 content.Uri = specContent.Uri53 if specContent.Repository != nil {54 content.Repository = &testkube.Repository{55 Type_: specContent.Repository.Type_,56 Uri: specContent.Repository.Uri,57 Branch: specContent.Repository.Branch,58 Commit: specContent.Repository.Commit,59 Path: specContent.Repository.Path,60 }61 if specContent.Repository.UsernameSecret != nil {62 content.Repository.UsernameSecret = &testkube.SecretRef{63 Name: specContent.Repository.UsernameSecret.Name,64 Key: specContent.Repository.UsernameSecret.Key,65 }66 }67 if specContent.Repository.TokenSecret != nil {68 content.Repository.TokenSecret = &testkube.SecretRef{69 Name: specContent.Repository.TokenSecret.Name,70 Key: specContent.Repository.TokenSecret.Key,71 }72 }73 }74 }75 return content76}77// MapTestArrayKubeToAPI maps CRD array data to OpenAPI spec tests list78func MapTestArrayKubeToAPI(crTests []testsv3.Test) (tests []testkube.Test) {79 tests = []testkube.Test{}80 for _, crTest := range crTests {81 tests = append(tests, MapTestCRToAPI(crTest))82 }83 return84}85// MapExecutionRequestFromSpec maps CRD to OpenAPI spec ExecutionREquest86func MapExecutionRequestFromSpec(specExecutionRequest *testsv3.ExecutionRequest) *testkube.ExecutionRequest {87 if specExecutionRequest == nil {88 return nil89 }90 return &testkube.ExecutionRequest{91 Name: specExecutionRequest.Name,92 TestSuiteName: specExecutionRequest.TestSuiteName,93 Number: int(specExecutionRequest.Number),94 ExecutionLabels: specExecutionRequest.ExecutionLabels,95 Namespace: specExecutionRequest.Namespace,...

Full Screen

Full Screen

MapTestCRToAPI

Using AI Code Generation

copy

Full Screen

1func TestCRToAPI(t *testing.T) {2}3func TestAPIToCR(t *testing.T) {4}5func TestCRToAPI(t *testing.T) {6}7func TestAPIToCR(t *testing.T) {8}9func TestCRToAPI(t *testing.T) {10}11func TestAPIToCR(t *testing.T) {12}13func TestCRToAPI(t *testing.T) {14}15func TestAPIToCR(t *testing.T) {

Full Screen

Full Screen

MapTestCRToAPI

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 testCR := tests.Test{4 }5 fmt.Println(testCR)6 testAPI := tests.MapTestCRToAPI(testCR)7 fmt.Println(testAPI)8}9import (10type Test struct {11}12func MapTestCRToAPI(testCR tests.Test) tests.Test {13 testAPI := tests.Test{14 }15}16{Test-1 20}17{Test-1 20}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful