Best Testkube code snippet using crds.generateCRDs
tests_crds.go
Source:tests_crds.go  
...82				tests[testType][testName] = *test83				return nil84			})85			ui.ExitOnError("getting directory content", err)86			generateCRDs(addEnvToTests(tests, testEnvs, testSecretEnvs))87		},88	}89	cmd.Flags().StringArrayVarP(&executorArgs, "executor-args", "", []string{}, "executor binary additional arguments")90	cmd.Flags().StringToStringVarP(&envs, "env", "", map[string]string{}, "envs in a form of name1=val1 passed to executor")91	return cmd92}93// ErrTypeNotDetected is not detcted test type error94var ErrTypeNotDetected = fmt.Errorf("type not detected")95// generateTest generates Test based on directory of test files96func generateTest(namespace, path string) (*client.UpsertTestOptions, error) {97	var testType string98	content, err := os.ReadFile(path)99	if err != nil {100		return nil, err101	}102	// try to detect type if none passed103	d := detector.NewDefaultDetector()104	if detectedType, ok := d.Detect(client.UpsertTestOptions{Content: &testkube.TestContent{Data: string(content)}}); ok {105		ui.Debug("Detected test type", detectedType)106		testType = detectedType107	} else {108		return nil, ErrTypeNotDetected109	}110	name := filepath.Base(path)111	test := &client.UpsertTestOptions{112		Name:      sanitizeName(name),113		Namespace: namespace,114		Content: &testkube.TestContent{115			Type_: string(testkube.TestContentTypeString),116			Data:  fmt.Sprintf("%q", strings.TrimSpace(string(content))),117		},118		Type_: testType,119	}120	return test, nil121}122// sanitizeName sanitizes test name123func sanitizeName(path string) string {124	path = strings.TrimSuffix(path, filepath.Ext(path))125	reg := regexp.MustCompile("[^a-zA-Z0-9-]+")126	path = reg.ReplaceAllString(path, "-")127	path = strings.TrimLeft(path, "-")128	path = strings.TrimRight(path, "-")129	path = strings.ToLower(path)130	if len(path) > 63 {131		return path[:63]132	}133	return path134}135// addEnvToTest adds env files to tests136func addEnvToTests(tests map[string]map[string]client.UpsertTestOptions,137	testEnvs, testSecretEnvs map[string]map[string]map[string]string) (envTests []client.UpsertTestOptions) {138	d := detector.NewDefaultDetector()139	for testType, values := range tests {140		for testName, test := range values {141			testMap := map[string]client.UpsertTestOptions{}142			for envName := range testEnvs[testType] {143				if filename, ok := testEnvs[testType][envName][testName]; ok {144					data, err := os.ReadFile(filename)145					if err != nil {146						ui.UseStderr()147						ui.Warn(fmt.Sprintf("read variables file %s got an error: %v", filename, err))148						continue149					}150					envTest := test151					envTest.Name = sanitizeName(envTest.Name + "-" + envName)152					envTest.ExecutionRequest = &testkube.ExecutionRequest{153						VariablesFile: fmt.Sprintf("%q", strings.TrimSpace(string(data))),154					}155					testMap[envTest.Name] = envTest156				}157			}158			for secretEnvName := range testSecretEnvs[testType] {159				if filename, ok := testSecretEnvs[testType][secretEnvName][testName]; ok {160					data, err := os.ReadFile(filename)161					if err != nil {162						ui.UseStderr()163						ui.Warn(fmt.Sprintf("read secret variables file %s got an error: %v", filename, err))164						continue165					}166					if adapter := d.GetAdapter(testType); adapter != nil {167						variables, err := adapter.GetSecretVariables(string(data))168						if err != nil {169							ui.UseStderr()170							ui.Warn(fmt.Sprintf("parse secret file %s got an error: %v", filename, err))171							continue172						}173						secretEnvTest := test174						secretEnvTest.Name = sanitizeName(secretEnvTest.Name + "-" + secretEnvName)175						if envTest, ok := testMap[secretEnvTest.Name]; ok {176							secretEnvTest = envTest177						}178						if secretEnvTest.ExecutionRequest == nil {179							secretEnvTest.ExecutionRequest = &testkube.ExecutionRequest{}180						}181						secretEnvTest.ExecutionRequest.Variables = variables182						testMap[secretEnvTest.Name] = secretEnvTest183					}184				}185			}186			if len(testMap) == 0 {187				testMap[test.Name] = test188			}189			for _, envTest := range testMap {190				envTests = append(envTests, envTest)191			}192		}193	}194	return envTests195}196// generateCRDs generates CRDs for tests197func generateCRDs(envTests []client.UpsertTestOptions) {198	firstEntry := true199	for _, test := range envTests {200		if !firstEntry {201			fmt.Printf("\n---\n")202		} else {203			firstEntry = false204		}205		yaml, err := crd.ExecuteTemplate(crd.TemplateTest, test)206		ui.ExitOnError("executing test template", err)207		fmt.Print(yaml)208	}209}...lib.go
Source:lib.go  
1// Copyright 2020 Adobe2// All Rights Reserved.3//4// NOTICE: Adobe permits you to use, modify, and distribute this file in5// accordance with the terms of the Adobe license agreement accompanying6// it. If you have received this file from a source other than Adobe,7// then your use, modification, or distribution of it requires the prior8// written permission of Adobe.9package operator10import (11	"fmt"12	"os"13	"os/exec"14	"github.com/magefile/mage/mg"15	"github.com/magefile/mage/sh"16	// mage:import utils17	"github.com/adobe/kratos/mage/util"18)19const (20	controllerGen = "sigs.k8s.io/controller-tools/cmd/controller-gen@v0.6.3"21	buildDir      = "build/bin"22)23// Cleans operator build dir24func Clean() {25	fmt.Printf("- Clean operator build dir: %s\n", buildDir)26	sh.Rm(buildDir)27}28// Builds operator code29func Build() {30	mg.SerialDeps(Clean, GenerateDeepCopy, Vet, Fmt)31	fmt.Println("- Build")32	err := sh.RunV("go", "build", "-o", "bin/manager", "main.go")33	utils.PanicOnError(err)34}35// Runs operator agains configured kube config36func Run() {37	namespaces := os.Getenv("KRATOS_NAMESPACES")38	mg.SerialDeps(Clean, GenerateDeepCopy, Vet, Fmt, GenerateCrds)39	fmt.Println("- Running operator, namespaces: ", namespaces)40	err := sh.RunV("go", "run", "main.go", "--namespaces="+namespaces)41	utils.PanicOnError(err)42}43// Formats Go source files44func Fmt() {45	fmt.Println("- Fmt")46	path, err := os.Getwd()47	utils.PanicOnError(err)48	err = sh.RunV("go", "fmt", path+"/...")49	utils.PanicOnError(err)50}51// Runs static analysis of the code52func Vet() {53	fmt.Println("- Vet")54	path, err := os.Getwd()55	utils.PanicOnError(err)56	err = sh.RunV("go", "vet", path+"/...")57	utils.PanicOnError(err)58}59// Generates DeepCopy code using as file header "hack/boilerplate.go.txt"60func GenerateDeepCopy() {61	mg.Deps(installControllerGen)62	fmt.Println("- Generating DeepCopy code")63	err := sh.RunV("controller-gen", "object:headerFile=\"hack/boilerplate.go.txt\"", "paths=\"./...\"")64	utils.PanicOnError(err)65}66// Generates CRDs67func GenerateCrds() {68	mg.Deps(installControllerGen)69	fmt.Println("- Generating CRDs")70	err := sh.RunV("controller-gen", "crd:trivialVersions=true", "paths=\"./...\"", "output:crd:artifacts:config=config/crd")71	utils.PanicOnError(err)72}73// Run operator tests74func Test() {75	mg.Deps(Build)76	fmt.Println("- Running tests")77	err := sh.RunV("go", "test", "./...", "-coverprofile", "cover.out", "-test.v", "-ginkgo.v")78	utils.PanicOnError(err)79}80// Shows test coverage report81func CoverageReport() {82	err := sh.RunV("go", "tool", "cover", "-func", "cover.out")83	utils.PanicOnError(err)84}85func installControllerGen() {86	installBinary("controller-gen", controllerGen)87}88func installBinary(binaryName string, binarySrc string) {89	fmt.Printf("Checking if %s is installed\n", binaryName)90	var _, err = exec.LookPath(binaryName)91	if err == nil {92		fmt.Printf("%s - OK\n", binaryName)93		return94	}95	fmt.Printf("%s not installed\n", binaryName)96	err = sh.RunV("go", "get", binarySrc)97	utils.PanicOnError(err)98}...main.go
Source:main.go  
1// Copyright 2021 IBM Corp.2// SPDX-License-Identifier: Apache-2.03package main4import (5	"fmt"6	"os"7	"strings"8	"github.com/spf13/cobra"9	"github.com/spf13/viper"10	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"11	"fybrik.io/openapi2crd/pkg/config"12	"fybrik.io/openapi2crd/pkg/exporter"13	"fybrik.io/openapi2crd/pkg/generator"14)15const (16	outputOption    = "output"17	resourcesOption = "input"18	gvkOption       = "gvk"19)20// RootCmd defines the root cli command21func RootCmd() *cobra.Command {22	cmd := &cobra.Command{23		Use:           "openapi2crd SPEC_FILE",24		Short:         "Generate CustomResourceDefinition from OpenAPI 3.0 document",25		SilenceErrors: true,26		SilenceUsage:  true,27		PreRun: func(cmd *cobra.Command, args []string) {28			_ = viper.BindPFlags(cmd.Flags())29		},30		Args: cobra.ExactArgs(1),31		RunE: func(cmd *cobra.Command, args []string) error {32			specOptionValue := args[0]33			openapiSpec, err := config.LoadOpenAPI(specOptionValue)34			if err != nil {35				return err36			}37			crds := []*apiextensions.CustomResourceDefinition{}38			gvkOptionValues := viper.GetStringSlice(gvkOption)39			if len(gvkOptionValues) != 0 {40				loaded, err := config.GenerateCRDs(gvkOptionValues)41				if err != nil {42					return err43				}44				crds = append(crds, loaded...)45			}46			resourcesOptionValue := viper.GetString(resourcesOption)47			if resourcesOptionValue != "" {48				loaded, err := config.LoadCRDs(resourcesOptionValue)49				if err != nil {50					return err51				}52				crds = append(crds, loaded...)53			}54			if len(crds) == 0 {55				message := fmt.Sprintf("You must pass flags --%s or --%s", gvkOption, resourcesOption)56				if resourcesOptionValue != "" {57					message = fmt.Sprintf("Does directory %s include a YAML with CustomResourceDefinition?", resourcesOptionValue)58				}59				return fmt.Errorf("nothing to process. %s", message)60			}61			outputOptionValue := viper.GetString(outputOption)62			exporter, err := exporter.New(outputOptionValue)63			if err != nil {64				return err65			}66			generator := generator.New()67			for _, crd := range crds {68				modified, err := generator.Generate(crd, openapiSpec.Components.Schemas)69				if err != nil {70					return err71				}72				err = exporter.Export(modified)73				if err != nil {74					return err75				}76			}77			return nil78		},79	}80	cmd.Flags().StringP(outputOption, "o", "", "Path to output file (required)")81	_ = cmd.MarkFlagRequired(outputOption)82	cmd.Flags().StringP(resourcesOption, "i", "",83		"Path to a directory with CustomResourceDefinition YAML files (required unless -g is used)")84	cmd.Flags().StringSliceP(gvkOption, "g", []string{},85		"The group/version/kind to create (can be specified zero or more times)")86	cobra.OnInitialize(initConfig)87	viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))88	return cmd89}90func initConfig() {91	viper.AutomaticEnv()92}93func main() {94	// Run the cli95	if err := RootCmd().Execute(); err != nil {96		fmt.Println(err)97		os.Exit(1)98	}99}...generateCRDs
Using AI Code Generation
1func main() {2    crds, err := crds.NewCRDs()3    if err != nil {4        log.Fatal(err)5    }6    err = crds.GenerateCRDs()7    if err != nil {8        log.Fatal(err)9    }10}11type CRDs struct {12}13func NewCRDs() (*CRDs, error) {14}15func (c *CRDs) GenerateCRDs() error {16}generateCRDs
Using AI Code Generation
1func main() {2    crd := crds.NewCRD()3    crd.GenerateCRDs()4}5func main() {6    crd := crds.NewCRD()7    crd.GenerateCRDs()8}9func main() {10    crd := crds.NewCRD()11    crd.GenerateCRDs()12}13func main() {14    crd := crds.NewCRD()15    crd.GenerateCRDs()16}17func main() {18    crd := crds.NewCRD()19    crd.GenerateCRDs()20}21func main() {22    crd := crds.NewCRD()23    crd.GenerateCRDs()24}25func main() {26    crd := crds.NewCRD()27    crd.GenerateCRDs()28}29func main() {30    crd := crds.NewCRD()31    crd.GenerateCRDs()32}33func main() {34    crd := crds.NewCRD()35    crd.GenerateCRDs()36}37func main() {38    crd := crds.NewCRD()39    crd.GenerateCRDs()40}41func main() {42    crd := crds.NewCRD()43    crd.GenerateCRDs()44}45func main() {46    crd := crds.NewCRD()47    crd.GenerateCRDs()48}generateCRDs
Using AI Code Generation
1import (2func main() {3	fmt.Println("Hello, playground")4	crd.GenerateCRDs()5}6import (7type Crds struct {8}9func (crds *Crds) GenerateCRDs() {10	fmt.Println("Hello, playground")11}generateCRDs
Using AI Code Generation
1import (2func main() {3	fmt.Println("Hello, playground")4	c := crds.Crds{}5	c.GenerateCRDs()6}7import (8type Crds struct {9}10func (c *Crds) GenerateCRDs() {11	fmt.Println("Generating CRDs")12}13The code above will not compile. The reason is that the crds package is not imported in the 1.go file. To fix this, add the following line to the top of the 1.go file:14import "crds"generateCRDs
Using AI Code Generation
1import (2func main() {3	crd := crds.CRD{4		ShortNames: []string{"t"},5	}6	crd.GenerateCRD()7	fmt.Println(crd.CRD)8}9import (10type CRD struct {11}12func (crd *CRD) GenerateCRD() {13	crd.CRD = &v1beta1.CustomResourceDefinition{14		ObjectMeta: v1.ObjectMeta{15		},16		Spec: v1beta1.CustomResourceDefinitionSpec{17			Scope: v1beta1.ResourceScope(crd.Scope),18			Names: v1beta1.CustomResourceDefinitionNames{19			},20		},21	}22	config, err := rest.InClusterConfig()23	if err != nil {24		panic(err.Error())25	}26	clientset, err := clientset.NewForConfig(config)27	if err != nil {28		panic(err.Error())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!!
