How to use newExecutionFromExecutionOptions method of v1 Package

Best Testkube code snippet using v1.newExecutionFromExecutionOptions

executions.go

Source:executions.go Github

copy

Full Screen

...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 != "" {414 request.HttpsProxy = test.ExecutionRequest.HttpsProxy415 }416 }417 // get executor from kubernetes CRs418 executorCR, err := s.ExecutorsClient.GetByType(testCR.Spec.Type_)419 if err != nil {420 return options, fmt.Errorf("can't get executor spec: %w", err)421 }422 var usernameSecret, tokenSecret *testkube.SecretRef423 if test.Content != nil && test.Content.Repository != nil {424 usernameSecret = test.Content.Repository.UsernameSecret425 tokenSecret = test.Content.Repository.TokenSecret426 }427 return client.ExecuteOptions{428 TestName: id,429 Namespace: namespace,430 TestSpec: testCR.Spec,431 ExecutorName: executorCR.ObjectMeta.Name,432 ExecutorSpec: executorCR.Spec,433 Request: request,434 Sync: request.Sync,435 Labels: testCR.Labels,436 UsernameSecret: usernameSecret,437 TokenSecret: tokenSecret,438 ImageOverride: request.Image,439 }, nil440}441// streamLogsFromResult writes logs from the output of executionResult to the writer442func (s *TestkubeAPI) streamLogsFromResult(executionResult *testkube.ExecutionResult, w *bufio.Writer) error {443 enc := json.NewEncoder(w)444 fmt.Fprintf(w, "data: ")445 s.Log.Debug("using logs from result")446 output := testkube.ExecutorOutput{447 Type_: output.TypeResult,448 Content: executionResult.Output,449 Result: executionResult,450 }451 err := enc.Encode(output)452 if err != nil {453 s.Log.Infow("Encode", "error", err)454 return err455 }456 fmt.Fprintf(w, "\n")457 w.Flush()458 return nil459}460// streamLogsFromJob streams logs in chunks to writer from the running execution461func (s *TestkubeAPI) streamLogsFromJob(executionID string, w *bufio.Writer) {462 enc := json.NewEncoder(w)463 s.Log.Debug("getting logs from Kubernetes job")464 logs, err := s.Executor.Logs(executionID)465 s.Log.Debugw("waiting for jobs channel", "channelSize", len(logs))466 if err != nil {467 output.PrintError(os.Stdout, err)468 s.Log.Errorw("getting logs error", "error", err)469 w.Flush()470 return471 }472 // loop through pods log lines - it's blocking channel473 // and pass single log output as sse data chunk474 for out := range logs {475 s.Log.Debugw("got log", "out", out)476 fmt.Fprintf(w, "data: ")477 err = enc.Encode(out)478 if err != nil {479 s.Log.Infow("Encode", "error", err)480 }481 // enc.Encode adds \n and we need \n\n after `data: {}` chunk482 fmt.Fprintf(w, "\n")483 w.Flush()484 }485}486func (s TestkubeAPI) getNextExecutionNumber(testName string) int {487 number, err := s.ExecutionResults.GetNextExecutionNumber(context.Background(), testName)488 if err != nil {489 s.Log.Errorw("retrieving latest execution", "error", err)490 return number491 }492 return number493}494func mergeVariables(vars1 map[string]testkube.Variable, vars2 map[string]testkube.Variable) map[string]testkube.Variable {495 variables := map[string]testkube.Variable{}496 for k, v := range vars1 {497 variables[k] = v498 }499 for k, v := range vars2 {500 variables[k] = v501 }502 return variables503}504func mergeEnvs(envs1 map[string]string, envs2 map[string]string) map[string]string {505 envs := map[string]string{}506 for k, v := range envs1 {507 envs[k] = v508 }509 for k, v := range envs2 {510 envs[k] = v511 }512 return envs513}514func newExecutionFromExecutionOptions(options client.ExecuteOptions) testkube.Execution {515 execution := testkube.NewExecution(516 options.Namespace,517 options.TestName,518 options.Request.TestSuiteName,519 options.Request.Name,520 options.TestSpec.Type_,521 options.Request.Number,522 testsmapper.MapTestContentFromSpec(options.TestSpec.Content),523 testkube.NewRunningExecutionResult(),524 options.Request.Variables,525 options.Request.TestSecretUUID,526 options.Request.TestSuiteSecretUUID,527 common.MergeMaps(options.Labels, options.Request.ExecutionLabels),528 )...

Full Screen

Full Screen

newExecutionFromExecutionOptions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config, err := kubeconfig.GetConfig()4 if err != nil {5 panic(err.Error())6 }7 clientset, err := versioned.NewForConfig(config)8 if err != nil {9 panic(err.Error())10 }11 kubeclientset, err := kubernetes.NewForConfig(config)12 if err != nil {13 panic(err.Error())14 }15 factory := externalversions.NewSharedInformerFactory(clientset, time.Second*30)16 informer := factory.Argoproj().V1alpha1().Workflows().Informer()17 queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())18 informer.AddEventHandler(cache.ResourceEventHandlerFuncs{19 AddFunc: func(obj interface{}) {20 key, err := cache.MetaNamespaceKeyFunc(obj)21 if err == nil {22 queue.Add(key)23 }24 },25 UpdateFunc: func(old, new interface{}) {26 key, err := cache.MetaNamespaceKeyFunc(new)27 if err == nil {28 queue.Add(key)29 }30 },

Full Screen

Full Screen

newExecutionFromExecutionOptions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 pr := v1beta1.PipelineRun{4 ObjectMeta: metav1.ObjectMeta{5 },6 Spec: v1beta1.PipelineRunSpec{7 PipelineRef: &v1beta1.PipelineRef{8 },9 Resources: []v1beta1.PipelineResourceBinding{10 {11 ResourceRef: &v1beta1.PipelineResourceRef{12 },13 },14 },15 },16 }17 p := v1beta1.Pipeline{18 ObjectMeta: metav1.ObjectMeta{19 },20 Spec: v1beta1.PipelineSpec{21 Tasks: []v1beta1.PipelineTask{22 {23 TaskRef: &v1beta1.TaskRef{24 },25 Resources: &v1beta1.PipelineTaskResources{26 Inputs: []v1beta1.PipelineTaskInputResource{27 {28 },29 },30 },31 },32 },33 },34 }35 t := v1beta1.Task{36 ObjectMeta: metav1.ObjectMeta{37 },38 Spec: v1beta1.TaskSpec{39 Steps: []v1beta1.Step{40 {41 Container: corev1.Container{42 },43 },44 },45 },46 }47 tr := v1beta1.TaskRun{48 ObjectMeta: metav1.ObjectMeta{49 },

Full Screen

Full Screen

newExecutionFromExecutionOptions

Using AI Code Generation

copy

Full Screen

1func main() {2}3func main() {4}5func main() {6}7func main() {8}9func main() {10}11func main() {12}13func main() {14}15func main() {16}17func main() {

Full Screen

Full Screen

newExecutionFromExecutionOptions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 executionOptions := tfe.ExecutionOptions{4 }5 execution := tfe.NewExecutionFromExecutionOptions(executionOptions)6 fmt.Println(execution)7}8&{ws-xxxxxxxxxxxxxxxxxxx false test test}

Full Screen

Full Screen

newExecutionFromExecutionOptions

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 executionOptions := &v1beta1.PipelineRun{4 ObjectMeta: metav1.ObjectMeta{5 },6 Spec: v1beta1.PipelineRunSpec{7 PipelineRef: &v1beta1.PipelineRef{8 },9 },10 }11 execution, err := v1.NewExecutionFromExecutionOptions(executionOptions)12 if err != nil {13 fmt.Println("Error creating execution instance")14 }15 fmt.Println(execution)16}17&{0xc0003d3c00 0xc0003d3c20 0xc0003d3c40 0xc0003d3c60 0xc0003d3c80 0xc0003d3ca0 0xc0003d3cc0 0xc0003d3ce0 0xc0003d3d00 0xc0003d3d20 0xc0003d3d40 0xc0003d3d60 0xc0003d3d80 0xc0003d3da0 0xc0003d3dc0 0xc0003d3de0 0xc0003d3e00 0xc0003d3e20 0xc0003d3e40 0xc0003d3e60 0xc0003d3e80 0xc0003d3ea0 0xc0003d3ec0 0xc0003d3ee0 0xc0003d3f00 0xc0003d3f20 0xc0003d3f40 0xc0003d3f60 0xc0003d3f80 0xc0003d3fa0 0xc0003d3fc0 0xc0003d3fe0 0xc0003d4000 0xc0003d4020

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.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful