Best Testkube code snippet using v1.EndExecution
tests.go
Source:tests.go
1package v12import (3 "context"4 "fmt"5 "net/http"6 "sort"7 "strconv"8 "strings"9 "github.com/gofiber/fiber/v2"10 testsv3 "github.com/kubeshop/testkube-operator/apis/tests/v3"11 "github.com/kubeshop/testkube/pkg/api/v1/testkube"12 "github.com/kubeshop/testkube/pkg/crd"13 "github.com/kubeshop/testkube/pkg/executor/client"14 testsmapper "github.com/kubeshop/testkube/pkg/mapper/tests"15 "github.com/kubeshop/testkube/pkg/secret"16 "go.mongodb.org/mongo-driver/mongo"17 "k8s.io/apimachinery/pkg/api/errors"18)19// GetTestHandler is method for getting an existing test20func (s TestkubeAPI) GetTestHandler() fiber.Handler {21 return func(c *fiber.Ctx) error {22 name := c.Params("id")23 crTest, err := s.TestsClient.Get(name)24 if err != nil {25 if errors.IsNotFound(err) {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)70 }71 endExecution, endErr := s.ExecutionResults.GetLatestByTest(ctx, name, "endtime")72 if endErr != nil && endErr != mongo.ErrNoDocuments {73 return s.Error(c, http.StatusInternalServerError, endErr)74 }75 testWithExecution := testkube.TestWithExecution{76 Test: &test,77 }78 if startErr == nil && endErr == nil {79 if startExecution.StartTime.After(endExecution.EndTime) {80 testWithExecution.LatestExecution = &startExecution81 } else {82 testWithExecution.LatestExecution = &endExecution83 }84 } else if startErr == nil {85 testWithExecution.LatestExecution = &startExecution86 } else if endErr == nil {87 testWithExecution.LatestExecution = &endExecution88 }89 return c.JSON(testWithExecution)90 }91}92func (s TestkubeAPI) getFilteredTestList(c *fiber.Ctx) (*testsv3.TestList, error) {93 crTests, err := s.TestsClient.List(c.Query("selector"))94 if err != nil {95 return nil, err96 }97 search := c.Query("textSearch")98 if search != "" {99 // filter items array100 for i := len(crTests.Items) - 1; i >= 0; i-- {101 if !strings.Contains(crTests.Items[i].Name, search) {102 crTests.Items = append(crTests.Items[:i], crTests.Items[i+1:]...)103 }104 }105 }106 testType := c.Query("type")107 if testType != "" {108 // filter items array109 for i := len(crTests.Items) - 1; i >= 0; i-- {110 if !strings.Contains(crTests.Items[i].Spec.Type_, testType) {111 crTests.Items = append(crTests.Items[:i], crTests.Items[i+1:]...)112 }113 }114 }115 return crTests, nil116}117// ListTestsHandler is a method for getting list of all available tests118func (s TestkubeAPI) ListTestsHandler() fiber.Handler {119 return func(c *fiber.Ctx) error {120 crTests, err := s.getFilteredTestList(c)121 if err != nil {122 return s.Error(c, http.StatusBadGateway, err)123 }124 tests := testsmapper.MapTestListKubeToAPI(*crTests)125 if c.Accepts(mediaTypeJSON, mediaTypeYAML) == mediaTypeYAML {126 for i := range tests {127 if tests[i].Content != nil && tests[i].Content.Data != "" {128 tests[i].Content.Data = fmt.Sprintf("%q", tests[i].Content.Data)129 }130 if tests[i].ExecutionRequest != nil && tests[i].ExecutionRequest.VariablesFile != "" {131 tests[i].ExecutionRequest.VariablesFile = fmt.Sprintf("%q", tests[i].ExecutionRequest.VariablesFile)132 }133 }134 data, err := crd.GenerateYAML(crd.TemplateTest, tests)135 return s.getCRDs(c, data, err)136 }137 return c.JSON(tests)138 }139}140// ListTestsHandler is a method for getting list of all available tests141func (s TestkubeAPI) TestMetricsHandler() fiber.Handler {142 return func(c *fiber.Ctx) error {143 testName := c.Params("id")144 const DefaultLimit = 0145 limit, err := strconv.Atoi(c.Query("limit", strconv.Itoa(DefaultLimit)))146 if err != nil {147 limit = DefaultLimit148 }149 const DefaultLastDays = 7150 last, err := strconv.Atoi(c.Query("last", strconv.Itoa(DefaultLastDays)))151 if err != nil {152 last = DefaultLastDays153 }154 metrics, err := s.ExecutionResults.GetTestMetrics(context.Background(), testName, limit, last)155 if err != nil {156 return s.Error(c, http.StatusBadGateway, err)157 }158 return c.JSON(metrics)159 }160}161// getLatestExecutions return latest executions either by starttime or endtime for tests162func (s TestkubeAPI) getLatestExecutions(ctx context.Context, testNames []string) (map[string]testkube.Execution, error) {163 executions, err := s.ExecutionResults.GetLatestByTests(ctx, testNames, "starttime")164 if err != nil && err != mongo.ErrNoDocuments {165 return nil, err166 }167 startExecutionMap := make(map[string]testkube.Execution, len(executions))168 for i := range executions {169 startExecutionMap[executions[i].TestName] = executions[i]170 }171 executions, err = s.ExecutionResults.GetLatestByTests(ctx, testNames, "endtime")172 if err != nil && err != mongo.ErrNoDocuments {173 return nil, err174 }175 endExecutionMap := make(map[string]testkube.Execution, len(executions))176 for i := range executions {177 endExecutionMap[executions[i].TestName] = executions[i]178 }179 executionMap := make(map[string]testkube.Execution)180 for _, testName := range testNames {181 startExecution, okStart := startExecutionMap[testName]182 endExecution, okEnd := endExecutionMap[testName]183 if !okStart && !okEnd {184 continue185 }186 if okStart && !okEnd {187 executionMap[testName] = startExecution188 continue189 }190 if !okStart && okEnd {191 executionMap[testName] = endExecution192 continue193 }194 if startExecution.StartTime.After(endExecution.EndTime) {195 executionMap[testName] = startExecution196 } else {197 executionMap[testName] = endExecution198 }199 }200 return executionMap, nil201}202// ListTestWithExecutionsHandler is a method for getting list of all available test with latest executions203func (s TestkubeAPI) ListTestWithExecutionsHandler() fiber.Handler {204 return func(c *fiber.Ctx) error {205 crTests, err := s.getFilteredTestList(c)206 if err != nil {207 return s.Error(c, http.StatusBadGateway, err)208 }209 tests := testsmapper.MapTestListKubeToAPI(*crTests)210 if c.Accepts(mediaTypeJSON, mediaTypeYAML) == mediaTypeYAML {211 for i := range tests {212 if tests[i].Content != nil && tests[i].Content.Data != "" {213 tests[i].Content.Data = fmt.Sprintf("%q", tests[i].Content.Data)214 }215 if tests[i].ExecutionRequest != nil && tests[i].ExecutionRequest.VariablesFile != "" {216 tests[i].ExecutionRequest.VariablesFile = fmt.Sprintf("%q", tests[i].ExecutionRequest.VariablesFile)217 }218 }219 data, err := crd.GenerateYAML(crd.TemplateTest, tests)220 return s.getCRDs(c, data, err)221 }222 ctx := c.Context()223 results := make([]testkube.TestWithExecution, 0, len(tests))224 testNames := make([]string, len(tests))225 for i := range tests {226 testNames[i] = tests[i].Name227 }228 executionMap, err := s.getLatestExecutions(ctx, testNames)229 if err != nil {230 return s.Error(c, http.StatusInternalServerError, err)231 }232 for i := range tests {233 if execution, ok := executionMap[tests[i].Name]; ok {234 results = append(results, testkube.TestWithExecution{235 Test: &tests[i],236 LatestExecution: &execution,237 })238 } else {239 results = append(results, testkube.TestWithExecution{240 Test: &tests[i],241 })242 }243 }244 sort.Slice(results, func(i, j int) bool {245 iTime := results[i].Test.Created246 if results[i].LatestExecution != nil {247 iTime = results[i].LatestExecution.EndTime248 if results[i].LatestExecution.StartTime.After(results[i].LatestExecution.EndTime) {249 iTime = results[i].LatestExecution.StartTime250 }251 }252 jTime := results[j].Test.Created253 if results[j].LatestExecution != nil {254 jTime = results[j].LatestExecution.EndTime255 if results[j].LatestExecution.StartTime.After(results[j].LatestExecution.EndTime) {256 jTime = results[j].LatestExecution.StartTime257 }258 }259 return iTime.After(jTime)260 })261 status := c.Query("status")262 if status != "" {263 statusList, err := testkube.ParseExecutionStatusList(status, ",")264 if err != nil {265 return s.Error(c, http.StatusBadRequest, fmt.Errorf("execution status filter invalid: %w", err))266 }267 statusMap := statusList.ToMap()268 // filter items array269 for i := len(results) - 1; i >= 0; i-- {270 if results[i].LatestExecution != nil && results[i].LatestExecution.ExecutionResult != nil &&271 results[i].LatestExecution.ExecutionResult.Status != nil {272 if _, ok := statusMap[*results[i].LatestExecution.ExecutionResult.Status]; ok {273 continue274 }275 }276 results = append(results[:i], results[i+1:]...)277 }278 }279 return c.JSON(results)280 }281}282// CreateTestHandler creates new test CR based on test content283func (s TestkubeAPI) CreateTestHandler() fiber.Handler {284 return func(c *fiber.Ctx) error {285 var request testkube.TestUpsertRequest286 err := c.BodyParser(&request)287 if err != nil {288 return s.Error(c, http.StatusBadRequest, err)289 }290 if c.Accepts(mediaTypeJSON, mediaTypeYAML) == mediaTypeYAML {291 if request.Content != nil && request.Content.Data != "" {292 request.Content.Data = fmt.Sprintf("%q", request.Content.Data)293 }294 if request.ExecutionRequest != nil && request.ExecutionRequest.VariablesFile != "" {295 request.ExecutionRequest.VariablesFile = fmt.Sprintf("%q", request.ExecutionRequest.VariablesFile)296 }297 data, err := crd.GenerateYAML(crd.TemplateTest, []testkube.TestUpsertRequest{request})298 return s.getCRDs(c, data, err)299 }300 s.Log.Infow("creating test", "request", request)301 testSpec := testsmapper.MapToSpec(request)302 testSpec.Namespace = s.Namespace303 test, err := s.TestsClient.Create(testSpec)304 s.Metrics.IncCreateTest(test.Spec.Type_, err)305 if err != nil {306 return s.Error(c, http.StatusBadGateway, err)307 }308 stringData := GetSecretsStringData(request.Content)309 if err = s.SecretClient.Create(secret.GetMetadataName(request.Name), test.Labels, stringData); err != nil {310 return s.Error(c, http.StatusBadGateway, err)311 }312 c.Status(http.StatusCreated)313 return c.JSON(test)314 }315}316// UpdateTestHandler updates an existing test CR based on test content317func (s TestkubeAPI) UpdateTestHandler() fiber.Handler {318 return func(c *fiber.Ctx) error {319 var request testkube.TestUpsertRequest320 err := c.BodyParser(&request)321 if err != nil {322 return s.Error(c, http.StatusBadRequest, err)323 }324 s.Log.Infow("updating test", "request", request)325 // we need to get resource first and load its metadata.ResourceVersion326 test, err := s.TestsClient.Get(request.Name)327 if err != nil {328 return s.Error(c, http.StatusBadGateway, err)329 }330 // map test but load spec only to not override metadata.ResourceVersion331 testSpec := testsmapper.MapToSpec(request)332 test.Spec = testSpec.Spec333 test.Labels = request.Labels334 test, err = s.TestsClient.Update(test)335 s.Metrics.IncUpdateTest(test.Spec.Type_, err)336 if err != nil {337 return s.Error(c, http.StatusBadGateway, err)338 }339 // update secrets for scipt340 stringData := GetSecretsStringData(request.Content)341 if err = s.SecretClient.Apply(secret.GetMetadataName(request.Name), test.Labels, stringData); err != nil {342 return s.Error(c, http.StatusBadGateway, err)343 }344 return c.JSON(test)345 }346}347// DeleteTestHandler is a method for deleting a test with id348func (s TestkubeAPI) DeleteTestHandler() fiber.Handler {349 return func(c *fiber.Ctx) error {350 name := c.Params("id")351 err := s.TestsClient.Delete(name)352 if err != nil {353 if errors.IsNotFound(err) {354 return s.Warn(c, http.StatusNotFound, err)355 }356 return s.Error(c, http.StatusBadGateway, err)357 }358 // delete secrets for test359 if err = s.SecretClient.Delete(secret.GetMetadataName(name)); err != nil {360 if !errors.IsNotFound(err) {361 return s.Error(c, http.StatusBadGateway, err)362 }363 }364 // delete executions for test365 if err = s.ExecutionResults.DeleteByTest(c.Context(), name); err != nil {366 return s.Error(c, http.StatusBadGateway, err)367 }368 return c.SendStatus(http.StatusNoContent)369 }370}371// DeleteTestsHandler for deleting all tests372func (s TestkubeAPI) DeleteTestsHandler() fiber.Handler {373 return func(c *fiber.Ctx) error {374 var err error375 var testNames []string376 selector := c.Query("selector")377 if selector == "" {378 err = s.TestsClient.DeleteAll()379 } else {380 testList, err := s.TestsClient.List(selector)381 if err != nil {382 if !errors.IsNotFound(err) {383 return s.Error(c, http.StatusBadGateway, err)384 }385 } else {386 for _, item := range testList.Items {387 testNames = append(testNames, item.Name)388 }389 }390 err = s.TestsClient.DeleteByLabels(selector)391 }392 if err != nil {393 if errors.IsNotFound(err) {394 return s.Warn(c, http.StatusNotFound, err)395 }396 return s.Error(c, http.StatusBadGateway, err)397 }398 // delete all secrets for tests399 if err = s.SecretClient.DeleteAll(selector); err != nil {400 if !errors.IsNotFound(err) {401 return s.Error(c, http.StatusBadGateway, err)402 }403 }404 // delete all executions for tests405 if selector == "" {406 err = s.ExecutionResults.DeleteAll(c.Context())407 } else {408 err = s.ExecutionResults.DeleteByTests(c.Context(), testNames)409 }410 if err != nil {411 return s.Error(c, http.StatusBadGateway, err)412 }413 return c.SendStatus(http.StatusNoContent)414 }415}416func GetSecretsStringData(content *testkube.TestContent) map[string]string {417 // create secrets for test418 stringData := map[string]string{client.GitUsernameSecretName: "", client.GitTokenSecretName: ""}419 if content != nil && content.Repository != nil {420 stringData[client.GitUsernameSecretName] = content.Repository.Username421 stringData[client.GitTokenSecretName] = content.Repository.Token422 }423 return stringData424}...
interface.go
Source:interface.go
...42 // Update updates execution result43 Update(ctx context.Context, result testkube.TestSuiteExecution) error44 // StartExecution updates execution start time45 StartExecution(ctx context.Context, id string, startTime time.Time) error46 // EndExecution updates execution end time47 EndExecution(ctx context.Context, id string, endTime time.Time, duration time.Duration) error48 // DeleteByTestSuite deletes execution results by test suite49 DeleteByTestSuite(ctx context.Context, testSuiteName string) error50 // DeleteAll deletes all execution results51 DeleteAll(ctx context.Context) error52 // DeleteByTestSuites deletes execution results by test suites53 DeleteByTestSuites(ctx context.Context, testSuiteNames []string) (err error)54 GetTestSuiteMetrics(ctx context.Context, name string, limit, last int) (metrics testkube.ExecutionsMetrics, err error)55}...
EndExecution
Using AI Code Generation
1func main() {2 v1 := v1.New()3 v1.EndExecution()4}5func main() {6 v2 := v2.New()7 v2.EndExecution()8}9func main() {10 v3 := v3.New()11 v3.EndExecution()12}13func main() {14 v4 := v4.New()15 v4.EndExecution()16}17func main() {18 v5 := v5.New()19 v5.EndExecution()20}21func main() {22 v6 := v6.New()23 v6.EndExecution()24}25func main() {26 v7 := v7.New()27 v7.EndExecution()28}29func main() {30 v8 := v8.New()31 v8.EndExecution()32}33func main() {34 v9 := v9.New()35 v9.EndExecution()36}37func main() {38 v10 := v10.New()39 v10.EndExecution()40}41func main() {42 v11 := v11.New()43 v11.EndExecution()44}45func main() {46 v12 := v12.New()47 v12.EndExecution()48}49func main() {50 v13 := v13.New()51 v13.EndExecution()52}53func main() {
EndExecution
Using AI Code Generation
1func main() {2 v1 := &v1{}3 v1.EndExecution()4}5func main() {6 v2 := &v2{}7 v2.EndExecution()8}9func main() {10 v1 := &v1{}11 v1.EndExecution()12}13func main() {14 v2 := &v2{}15 v2.EndExecution()16}17func main() {18 v1 := &v1{}19 v1.EndExecution()20}21func main() {22 v2 := &v2{}23 v2.EndExecution()24}25func main() {26 v1 := &v1{}27 v1.EndExecution()28}29func main() {30 v2 := &v2{}31 v2.EndExecution()32}
EndExecution
Using AI Code Generation
1import (2func main() {3 if err := sdl.Init(sdl.INIT_EVERYTHING); err != nil {4 panic(err)5 }6 defer sdl.Quit()7 if err := img.Init(img.INIT_PNG); err != nil {8 panic(err)9 }10 defer img.Quit()11 if err := ttf.Init(); err != nil {12 panic(err)13 }14 defer ttf.Quit()15 if err := mix.OpenAudio(22050, mix.DEFAULT_FORMAT, 2, 4096); err != nil {16 panic(err)17 }18 defer mix.CloseAudio()19 window, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED, 800, 600, sdl.WINDOW_SHOWN)20 if err != nil {21 panic(err)22 }23 defer window.Destroy()24 renderer, err := sdl.CreateRenderer(window, -1, sdl.RENDERER_ACCELERATED)25 if err != nil {26 panic(err)27 }28 defer renderer.Destroy()29 v1 := NewV1(renderer)30 if err := v1.Init(); err != nil {31 panic(err)32 }33 defer v1.EndExecution()34 for running {35 for event = sdl.PollEvent(); event != nil; event = sdl.PollEvent() {36 switch t := event.(type) {37 fmt.Println("Quit")38 if t.Keysym.Sym == sdl.K_ESCAPE {39 fmt.Println("Escape")40 }41 }42 }43 renderer.SetDrawColor(0, 0, 0, 255)44 renderer.Clear()45 v1.Update()46 v1.Render()47 renderer.Present()48 time.Sleep(1000 / 60 * time.Millisecond)49 }50}
EndExecution
Using AI Code Generation
1import "fmt"2import "golang.org/x/sys/windows"3func main() {4 windows.EndExecution(a)5}6import "fmt"7import "golang.org/x/sys/windows"8func main() {9 windows.EndExecution(a)10}11import "fmt"12import "golang.org/x/sys/windows"13func main() {14 windows.EndExecution(a)15}16import "fmt"17import "golang.org/x/sys/windows"18func main() {19 windows.EndExecution(a)20}21import "fmt"22import "golang.org/x/sys/windows"23func main() {24 windows.EndExecution(a)25}26import "fmt"27import "golang.org/x/sys/windows"28func main() {29 windows.EndExecution(a)30}31import "fmt"32import "golang.org/x/sys/windows"33func main() {34 windows.EndExecution(a)35}36import "fmt"37import "golang.org/x/sys/windows"38func main() {
EndExecution
Using AI Code Generation
1import (2func main() {3 fmt.Println("This is a test file")4 v := v1.V1{}5 v.EndExecution()6}7import "fmt"8type V1 struct {9}10func (v V1) EndExecution() {11 fmt.Println("End of execution")12}13import "fmt"14type V2 struct {15}16func (v V2) EndExecution() {17 fmt.Println("End of execution")18}19import "fmt"20type V3 struct {21}22func (v V3) EndExecution() {23 fmt.Println("End of execution")24}25import "fmt"26type V4 struct {27}28func (v V4) EndExecution() {29 fmt.Println("End of execution")30}31import "fmt"32type V5 struct {33}34func (v V5) EndExecution() {35 fmt.Println("End of execution")36}37import "fmt"38type V6 struct {39}40func (v V6) EndExecution() {41 fmt.Println("End of execution")42}43import "fmt"44type V7 struct {45}46func (v V7) EndExecution() {47 fmt.Println("End of execution")48}49import "fmt"50type V8 struct {51}52func (v V8) EndExecution() {53 fmt.Println("End of execution")54}55import "fmt"56type V9 struct {57}58func (v V9) EndExecution() {59 fmt.Println("End of execution")60}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!