How to use validateCreateOptions method of tests Package

Best Testkube code snippet using tests.validateCreateOptions

validation.go

Source:validation.go Github

copy

Full Screen

1/*2Copyright 2015 The Kubernetes Authors.3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package validation14import (15 "fmt"16 "regexp"17 "unicode"18 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"19 "k8s.io/apimachinery/pkg/types"20 "k8s.io/apimachinery/pkg/util/sets"21 "k8s.io/apimachinery/pkg/util/validation"22 "k8s.io/apimachinery/pkg/util/validation/field"23)24func ValidateLabelSelector(ps *metav1.LabelSelector, fldPath *field.Path) field.ErrorList {25 allErrs := field.ErrorList{}26 if ps == nil {27 return allErrs28 }29 allErrs = append(allErrs, ValidateLabels(ps.MatchLabels, fldPath.Child("matchLabels"))...)30 for i, expr := range ps.MatchExpressions {31 allErrs = append(allErrs, ValidateLabelSelectorRequirement(expr, fldPath.Child("matchExpressions").Index(i))...)32 }33 return allErrs34}35func ValidateLabelSelectorRequirement(sr metav1.LabelSelectorRequirement, fldPath *field.Path) field.ErrorList {36 allErrs := field.ErrorList{}37 switch sr.Operator {38 case metav1.LabelSelectorOpIn, metav1.LabelSelectorOpNotIn:39 if len(sr.Values) == 0 {40 allErrs = append(allErrs, field.Required(fldPath.Child("values"), "must be specified when `operator` is 'In' or 'NotIn'"))41 }42 case metav1.LabelSelectorOpExists, metav1.LabelSelectorOpDoesNotExist:43 if len(sr.Values) > 0 {44 allErrs = append(allErrs, field.Forbidden(fldPath.Child("values"), "may not be specified when `operator` is 'Exists' or 'DoesNotExist'"))45 }46 default:47 allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), sr.Operator, "not a valid selector operator"))48 }49 allErrs = append(allErrs, ValidateLabelName(sr.Key, fldPath.Child("key"))...)50 return allErrs51}52// ValidateLabelName validates that the label name is correctly defined.53func ValidateLabelName(labelName string, fldPath *field.Path) field.ErrorList {54 allErrs := field.ErrorList{}55 for _, msg := range validation.IsQualifiedName(labelName) {56 allErrs = append(allErrs, field.Invalid(fldPath, labelName, msg))57 }58 return allErrs59}60// ValidateLabels validates that a set of labels are correctly defined.61func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorList {62 allErrs := field.ErrorList{}63 for k, v := range labels {64 allErrs = append(allErrs, ValidateLabelName(k, fldPath)...)65 for _, msg := range validation.IsValidLabelValue(v) {66 allErrs = append(allErrs, field.Invalid(fldPath, v, msg))67 }68 }69 return allErrs70}71func ValidateDeleteOptions(options *metav1.DeleteOptions) field.ErrorList {72 allErrs := field.ErrorList{}73 if options.OrphanDependents != nil && options.PropagationPolicy != nil {74 allErrs = append(allErrs, field.Invalid(field.NewPath("propagationPolicy"), options.PropagationPolicy, "orphanDependents and deletionPropagation cannot be both set"))75 }76 if options.PropagationPolicy != nil &&77 *options.PropagationPolicy != metav1.DeletePropagationForeground &&78 *options.PropagationPolicy != metav1.DeletePropagationBackground &&79 *options.PropagationPolicy != metav1.DeletePropagationOrphan {80 allErrs = append(allErrs, field.NotSupported(field.NewPath("propagationPolicy"), options.PropagationPolicy, []string{string(metav1.DeletePropagationForeground), string(metav1.DeletePropagationBackground), string(metav1.DeletePropagationOrphan), "nil"}))81 }82 allErrs = append(allErrs, ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...)83 return allErrs84}85func ValidateCreateOptions(options *metav1.CreateOptions) field.ErrorList {86 return append(87 ValidateFieldManager(options.FieldManager, field.NewPath("fieldManager")),88 ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...,89 )90}91func ValidateUpdateOptions(options *metav1.UpdateOptions) field.ErrorList {92 return append(93 ValidateFieldManager(options.FieldManager, field.NewPath("fieldManager")),94 ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...,95 )96}97func ValidatePatchOptions(options *metav1.PatchOptions, patchType types.PatchType) field.ErrorList {98 allErrs := field.ErrorList{}99 if patchType != types.ApplyPatchType {100 if options.Force != nil {101 allErrs = append(allErrs, field.Forbidden(field.NewPath("force"), "may not be specified for non-apply patch"))102 }103 } else {104 if options.FieldManager == "" {105 // This field is defaulted to "kubectl" by kubectl, but HAS TO be explicitly set by controllers.106 allErrs = append(allErrs, field.Required(field.NewPath("fieldManager"), "is required for apply patch"))107 }108 }109 allErrs = append(allErrs, ValidateFieldManager(options.FieldManager, field.NewPath("fieldManager"))...)110 allErrs = append(allErrs, ValidateDryRun(field.NewPath("dryRun"), options.DryRun)...)111 return allErrs112}113var FieldManagerMaxLength = 128114// ValidateFieldManager valides that the fieldManager is the proper length and115// only has printable characters.116func ValidateFieldManager(fieldManager string, fldPath *field.Path) field.ErrorList {117 allErrs := field.ErrorList{}118 // the field can not be set as a `*string`, so a empty string ("") is119 // considered as not set and is defaulted by the rest of the process120 // (unless apply is used, in which case it is required).121 if len(fieldManager) > FieldManagerMaxLength {122 allErrs = append(allErrs, field.TooLong(fldPath, fieldManager, FieldManagerMaxLength))123 }124 // Verify that all characters are printable.125 for i, r := range fieldManager {126 if !unicode.IsPrint(r) {127 allErrs = append(allErrs, field.Invalid(fldPath, fieldManager, fmt.Sprintf("invalid character %#U (at position %d)", r, i)))128 }129 }130 return allErrs131}132var allowedDryRunValues = sets.NewString(metav1.DryRunAll)133// ValidateDryRun validates that a dryRun query param only contains allowed values.134func ValidateDryRun(fldPath *field.Path, dryRun []string) field.ErrorList {135 allErrs := field.ErrorList{}136 if !allowedDryRunValues.HasAll(dryRun...) {137 allErrs = append(allErrs, field.NotSupported(fldPath, dryRun, allowedDryRunValues.List()))138 }139 return allErrs140}141const UninitializedStatusUpdateErrorMsg string = `must not update status when the object is uninitialized`142// ValidateTableOptions returns any invalid flags on TableOptions.143func ValidateTableOptions(opts *metav1.TableOptions) field.ErrorList {144 var allErrs field.ErrorList145 switch opts.IncludeObject {146 case metav1.IncludeMetadata, metav1.IncludeNone, metav1.IncludeObject, "":147 default:148 allErrs = append(allErrs, field.Invalid(field.NewPath("includeObject"), opts.IncludeObject, "must be 'Metadata', 'Object', 'None', or empty"))149 }150 return allErrs151}152func ValidateManagedFields(fieldsList []metav1.ManagedFieldsEntry, fldPath *field.Path) field.ErrorList {153 var allErrs field.ErrorList154 for _, fields := range fieldsList {155 switch fields.Operation {156 case metav1.ManagedFieldsOperationApply, metav1.ManagedFieldsOperationUpdate:157 default:158 allErrs = append(allErrs, field.Invalid(fldPath.Child("operation"), fields.Operation, "must be `Apply` or `Update`"))159 }160 if len(fields.FieldsType) > 0 && fields.FieldsType != "FieldsV1" {161 allErrs = append(allErrs, field.Invalid(fldPath.Child("fieldsType"), fields.FieldsType, "must be `FieldsV1`"))162 }163 }164 return allErrs165}166func ValidateConditions(conditions []metav1.Condition, fldPath *field.Path) field.ErrorList {167 var allErrs field.ErrorList168 conditionTypeToFirstIndex := map[string]int{}169 for i, condition := range conditions {170 if _, ok := conditionTypeToFirstIndex[condition.Type]; ok {171 allErrs = append(allErrs, field.Duplicate(fldPath.Index(i).Child("type"), condition.Type))172 } else {173 conditionTypeToFirstIndex[condition.Type] = i174 }175 allErrs = append(allErrs, ValidateCondition(condition, fldPath.Index(i))...)176 }177 return allErrs178}179// validConditionStatuses is used internally to check validity and provide a good message180var validConditionStatuses = sets.NewString(string(metav1.ConditionTrue), string(metav1.ConditionFalse), string(metav1.ConditionUnknown))181const (182 maxReasonLen = 1 * 1024183 maxMessageLen = 32 * 1024184)185func ValidateCondition(condition metav1.Condition, fldPath *field.Path) field.ErrorList {186 var allErrs field.ErrorList187 // type is set and is a valid format188 allErrs = append(allErrs, ValidateLabelName(condition.Type, fldPath.Child("type"))...)189 // status is set and is an accepted value190 if !validConditionStatuses.Has(string(condition.Status)) {191 allErrs = append(allErrs, field.NotSupported(fldPath.Child("status"), condition.Status, validConditionStatuses.List()))192 }193 if condition.ObservedGeneration < 0 {194 allErrs = append(allErrs, field.Invalid(fldPath.Child("observedGeneration"), condition.ObservedGeneration, "must be greater than or equal to zero"))195 }196 if condition.LastTransitionTime.IsZero() {197 allErrs = append(allErrs, field.Required(fldPath.Child("lastTransitionTime"), "must be set"))198 }199 if len(condition.Reason) == 0 {200 allErrs = append(allErrs, field.Required(fldPath.Child("reason"), "must be set"))201 } else {202 for _, currErr := range isValidConditionReason(condition.Reason) {203 allErrs = append(allErrs, field.Invalid(fldPath.Child("reason"), condition.Reason, currErr))204 }205 if len(condition.Reason) > maxReasonLen {206 allErrs = append(allErrs, field.TooLong(fldPath.Child("reason"), condition.Reason, maxReasonLen))207 }208 }209 if len(condition.Message) > maxMessageLen {210 allErrs = append(allErrs, field.TooLong(fldPath.Child("message"), condition.Message, maxMessageLen))211 }212 return allErrs213}214const conditionReasonFmt string = "[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?"215const conditionReasonErrMsg string = "a condition reason must start with alphabetic character, optionally followed by a string of alphanumeric characters or '_,:', and must end with an alphanumeric character or '_'"216var conditionReasonRegexp = regexp.MustCompile("^" + conditionReasonFmt + "$")217// isValidConditionReason tests for a string that conforms to rules for condition reasons. This checks the format, but not the length.218func isValidConditionReason(value string) []string {219 if !conditionReasonRegexp.MatchString(value) {220 return []string{validation.RegexError(conditionReasonErrMsg, conditionReasonFmt, "my_name", "MY_NAME", "MyName", "ReasonA,ReasonB", "ReasonA:ReasonB")}221 }222 return nil223}...

Full Screen

Full Screen

create.go

Source:create.go Github

copy

Full Screen

...59 if testName == test.Name {60 ui.Failf("Test with name '%s' already exists in namespace %s", testName, namespace)61 }62 }63 err = validateCreateOptions(cmd)64 ui.ExitOnError("validating passed flags", err)65 options, err := NewUpsertTestOptionsFromFlags(cmd, testLabels)66 ui.ExitOnError("getting test options", err)67 if !crdOnly {68 executors, err := client.ListExecutors("")69 ui.ExitOnError("getting available executors", err)70 err = validateExecutorType(options.Type_, executors)71 ui.ExitOnError("validating executor type", err)72 }73 err = validateSchedule(options.Schedule)74 ui.ExitOnError("validating schedule", err)75 if !crdOnly {76 _, err = client.CreateTest(options)77 ui.ExitOnError("creating test "+testName+" in namespace "+namespace, err)78 ui.Success("Test created", namespace, "/", testName)79 } else {80 if options.Content != nil && options.Content.Data != "" {81 options.Content.Data = fmt.Sprintf("%q", options.Content.Data)82 }83 if options.ExecutionRequest != nil && options.ExecutionRequest.VariablesFile != "" {84 options.ExecutionRequest.VariablesFile = fmt.Sprintf("%q", options.ExecutionRequest.VariablesFile)85 }86 data, err := crd.ExecuteTemplate(crd.TemplateTest, options)87 ui.ExitOnError("executing crd template", err)88 ui.Info(data)89 }90 },91 }92 cmd.Flags().StringVarP(&testName, "name", "n", "", "unique test name - mandatory")93 cmd.Flags().StringVarP(&testContentType, "test-content-type", "", "", "content type of test one of string|file-uri|git-file|git-dir")94 cmd.Flags().StringVarP(&executorType, "type", "t", "", "test type (defaults to postman/collection)")95 // create options96 cmd.Flags().StringVarP(&file, "file", "f", "", "test file - will be read from stdin if not specified")97 cmd.Flags().StringVarP(&uri, "uri", "", "", "URI of resource - will be loaded by http GET")98 cmd.Flags().StringVarP(&gitUri, "git-uri", "", "", "Git repository uri")99 cmd.Flags().StringVarP(&gitBranch, "git-branch", "", "", "if uri is git repository we can set additional branch parameter")100 cmd.Flags().StringVarP(&gitCommit, "git-commit", "", "", "if uri is git repository we can use commit id (sha) parameter")101 cmd.Flags().StringVarP(&gitPath, "git-path", "", "", "if repository is big we need to define additional path to directory/file to checkout partially")102 cmd.Flags().StringVarP(&gitUsername, "git-username", "", "", "if git repository is private we can use username as an auth parameter")103 cmd.Flags().StringVarP(&gitToken, "git-token", "", "", "if git repository is private we can use token as an auth parameter")104 cmd.Flags().StringToStringVarP(&labels, "label", "l", nil, "label key value pair: --label key1=value1")105 cmd.Flags().StringToStringVarP(&variables, "variable", "v", nil, "variable key value pair: --variable key1=value1")106 cmd.Flags().StringToStringVarP(&secretVariables, "secret-variable", "s", nil, "secret variable key value pair: --secret-variable key1=value1")107 cmd.Flags().StringVarP(&schedule, "schedule", "", "", "test schedule in a cronjob form: * * * * *")108 cmd.Flags().StringArrayVarP(&executorArgs, "executor-args", "", []string{}, "executor binary additional arguments")109 cmd.Flags().StringVarP(&executionName, "execution-name", "", "", "execution name, if empty will be autogenerated")110 cmd.Flags().StringVarP(&variablesFile, "variables-file", "", "", "variables file path, e.g. postman env file - will be passed to executor if supported")111 cmd.Flags().StringToStringVarP(&envs, "env", "", map[string]string{}, "envs in a form of name1=val1 passed to executor")112 cmd.Flags().StringToStringVarP(&secretEnvs, "secret-env", "", map[string]string{}, "secret envs in a form of secret_name1=secret_key1 passed to executor")113 cmd.Flags().StringVar(&httpProxy, "http-proxy", "", "http proxy for executor containers")114 cmd.Flags().StringVar(&httpsProxy, "https-proxy", "", "https proxy for executor containers")115 cmd.Flags().StringToStringVarP(&gitUsernameSecret, "git-username-secret", "", map[string]string{}, "git username secret in a form of secret_name1=secret_key1 for private repository")116 cmd.Flags().StringToStringVarP(&gitTokenSecret, "git-token-secret", "", map[string]string{}, "git token secret in a form of secret_name1=secret_key1 for private repository")117 cmd.Flags().StringToStringVarP(&secretVariableReferences, "secret-variable-reference", "", nil, "secret variable references in a form name1=secret_name1=secret_key1")118 return cmd119}120func validateCreateOptions(cmd *cobra.Command) error {121 gitUri := cmd.Flag("git-uri").Value.String()122 gitBranch := cmd.Flag("git-branch").Value.String()123 gitCommit := cmd.Flag("git-commit").Value.String()124 gitPath := cmd.Flag("git-path").Value.String()125 gitUsername := cmd.Flag("git-username").Value.String()126 gitToken := cmd.Flag("git-token").Value.String()127 gitUsernameSecret, err := cmd.Flags().GetStringToString("git-username-secret")128 if err != nil {129 return err130 }131 gitTokenSecret, err := cmd.Flags().GetStringToString("git-token-secret")132 if err != nil {133 return err134 }...

Full Screen

Full Screen

validateCreateOptions

Using AI Code Generation

copy

Full Screen

1func validateCreateOptions(t *testing.T, options *CreateOptions) {2}3func validateCreateOptions(t *testing.T, options *CreateOptions) {4}5func validateCreateOptions(t *testing.T, options *CreateOptions) {6}7func validateCreateOptions(t *testing.T, options *CreateOptions) {8}9func validateCreateOptions(t *testing.T, options *CreateOptions) {10}11func validateCreateOptions(t *testing.T, options *CreateOptions) {12}13func validateCreateOptions(t *testing.T, options *CreateOptions) {14}15func validateCreateOptions(t *testing.T, options *CreateOptions) {16}17func validateCreateOptions(t *testing.T, options *CreateOptions) {18}19func validateCreateOptions(t *testing.T, options *CreateOptions) {20}21func validateCreateOptions(t *testing.T, options *CreateOptions) {22}23func validateCreateOptions(t *testing.T, options *CreateOptions) {24}

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