Best K6 code snippet using v1.NewCheck
schema.go
Source:schema.go  
1package config2import (3	"bytes"4	"encoding/json"5	"errors"6	"fmt"7	"io"8	"strings"9	"text/template"10	"github.com/qri-io/jsonschema"11	"github.com/thoas/go-funk"12	corev1 "k8s.io/api/core/v1"13	"k8s.io/apimachinery/pkg/api/resource"14	k8sYaml "k8s.io/apimachinery/pkg/util/yaml"15)16// TargetKind represents the part of the config to be validated17type TargetKind string18const (19	// TargetController points to the controller's spec20	TargetController TargetKind = "Controller"21	// TargetContainer points to the container spec22	TargetContainer TargetKind = "Container"23	// TargetPod points to the pod spec24	TargetPod TargetKind = "Pod"25)26// HandledTargets is a list of target names that are explicitly handled27var HandledTargets = []TargetKind{28	TargetController,29	TargetContainer,30	TargetPod,31}32// SchemaCheck is a Polaris check that runs using JSON Schema33type SchemaCheck struct {34	ID                      string                            `yaml:"id" json:"id"`35	Category                string                            `yaml:"category" json:"category"`36	SuccessMessage          string                            `yaml:"successMessage" json:"successMessage"`37	FailureMessage          string                            `yaml:"failureMessage" json:"failureMessage"`38	Controllers             includeExcludeList                `yaml:"controllers" json:"controllers"`39	Containers              includeExcludeList                `yaml:"containers" json:"containers"`40	Target                  TargetKind                        `yaml:"target" json:"target"`41	SchemaTarget            TargetKind                        `yaml:"schemaTarget" json:"schemaTarget"`42	Schema                  map[string]interface{}            `yaml:"schema" json:"schema"`43	SchemaString            string                            `yaml:"schemaString" json:"schemaString"`44	Validator               jsonschema.RootSchema             `yaml:"-" json:"-"`45	AdditionalSchemas       map[string]map[string]interface{} `yaml:"additionalSchemas" json:"additionalSchemas"`46	AdditionalSchemaStrings map[string]string                 `yaml:"additionalSchemaStrings" json:"additionalSchemaStrings"`47	AdditionalValidators    map[string]jsonschema.RootSchema  `yaml:"-" json:"-"`48}49type resourceMinimum string50type resourceMaximum string51func unmarshalYAMLOrJSON(raw []byte, dest interface{}) error {52	reader := bytes.NewReader(raw)53	d := k8sYaml.NewYAMLOrJSONDecoder(reader, 4096)54	for {55		if err := d.Decode(dest); err != nil {56			if err == io.EOF {57				break58			}59			return fmt.Errorf("Decoding schema check failed: %v", err)60		}61	}62	return nil63}64// ParseCheck parses a check from a byte array65func ParseCheck(id string, rawBytes []byte) (SchemaCheck, error) {66	check := SchemaCheck{}67	err := unmarshalYAMLOrJSON(rawBytes, &check)68	if err != nil {69		return check, err70	}71	check.Initialize(id)72	return check, nil73}74func init() {75	jsonschema.RegisterValidator("resourceMinimum", newResourceMinimum)76	jsonschema.RegisterValidator("resourceMaximum", newResourceMaximum)77}78type includeExcludeList struct {79	Include []string `yaml:"include"`80	Exclude []string `yaml:"exclude"`81}82func newResourceMinimum() jsonschema.Validator {83	return new(resourceMinimum)84}85func newResourceMaximum() jsonschema.Validator {86	return new(resourceMaximum)87}88// Validate checks that a specified quanitity is not less than the minimum89func (min resourceMinimum) Validate(path string, data interface{}, errs *[]jsonschema.ValError) {90	err := validateRange(path, string(min), data, true)91	if err != nil {92		*errs = append(*errs, *err...)93	}94}95// Validate checks that a specified quanitity is not greater than the maximum96func (max resourceMaximum) Validate(path string, data interface{}, errs *[]jsonschema.ValError) {97	err := validateRange(path, string(max), data, false)98	if err != nil {99		*errs = append(*errs, *err...)100	}101}102func parseQuantity(i interface{}) (resource.Quantity, *[]jsonschema.ValError) {103	resStr, ok := i.(string)104	if !ok {105		return resource.Quantity{}, &[]jsonschema.ValError{106			{Message: fmt.Sprintf("Resource quantity %v is not a string", i)},107		}108	}109	q, err := resource.ParseQuantity(resStr)110	if err != nil {111		return resource.Quantity{}, &[]jsonschema.ValError{112			{Message: fmt.Sprintf("Could not parse resource quantity: %s", resStr)},113		}114	}115	return q, nil116}117func validateRange(path string, limit interface{}, data interface{}, isMinimum bool) *[]jsonschema.ValError {118	limitQuantity, err := parseQuantity(limit)119	if err != nil {120		return err121	}122	actualQuantity, err := parseQuantity(data)123	if err != nil {124		return err125	}126	cmp := limitQuantity.Cmp(actualQuantity)127	if isMinimum {128		if cmp == 1 {129			return &[]jsonschema.ValError{130				{Message: fmt.Sprintf("%s quantity %v is > %v", path, actualQuantity, limitQuantity)},131			}132		}133	} else {134		if cmp == -1 {135			return &[]jsonschema.ValError{136				{Message: fmt.Sprintf("%s quantity %v is < %v", path, actualQuantity, limitQuantity)},137			}138		}139	}140	return nil141}142// Initialize sets up the schema143func (check *SchemaCheck) Initialize(id string) error {144	check.ID = id145	if check.SchemaString == "" {146		jsonBytes, err := json.Marshal(check.Schema)147		if err != nil {148			return err149		}150		check.SchemaString = string(jsonBytes)151	}152	if check.AdditionalSchemaStrings == nil {153		check.AdditionalSchemaStrings = make(map[string]string)154	}155	for kind, schema := range check.AdditionalSchemas {156		jsonBytes, err := json.Marshal(schema)157		if err != nil {158			return err159		}160		check.AdditionalSchemaStrings[kind] = string(jsonBytes)161	}162	check.Schema = map[string]interface{}{}163	check.AdditionalSchemas = map[string]map[string]interface{}{}164	return nil165}166// TemplateForResource fills out a check's templated fields given a particular resource167func (check SchemaCheck) TemplateForResource(res interface{}) (*SchemaCheck, error) {168	newCheck := check // Make a copy of the check, since we're going to modify the schema169	templateStrings := map[string]string{170		"": newCheck.SchemaString,171	}172	for kind, schema := range newCheck.AdditionalSchemaStrings {173		templateStrings[kind] = schema174	}175	newCheck.SchemaString = ""176	newCheck.AdditionalSchemaStrings = map[string]string{}177	for kind, tmplString := range templateStrings {178		tmpl := template.New(newCheck.ID)179		tmpl, err := tmpl.Parse(tmplString)180		if err != nil {181			return nil, err182		}183		w := bytes.Buffer{}184		err = tmpl.Execute(&w, res)185		if err != nil {186			return nil, err187		}188		if kind == "" {189			newCheck.SchemaString = w.String()190		} else {191			newCheck.AdditionalSchemaStrings[kind] = w.String()192		}193	}194	newCheck.AdditionalValidators = map[string]jsonschema.RootSchema{}195	for kind, schemaStr := range newCheck.AdditionalSchemaStrings {196		val := jsonschema.RootSchema{}197		err := unmarshalYAMLOrJSON([]byte(schemaStr), &val)198		if err != nil {199			return nil, err200		}201		newCheck.AdditionalValidators[kind] = val202	}203	err := unmarshalYAMLOrJSON([]byte(newCheck.SchemaString), &newCheck.Validator)204	if err != nil {205		return nil, err206	}207	return &newCheck, err208}209// CheckPod checks a pod spec against the schema210func (check SchemaCheck) CheckPod(pod *corev1.PodSpec) (bool, []jsonschema.ValError, error) {211	return check.CheckObject(pod)212}213// CheckController checks a controler's spec against the schema214func (check SchemaCheck) CheckController(bytes []byte) (bool, []jsonschema.ValError, error) {215	errs, err := check.Validator.ValidateBytes(bytes)216	return len(errs) == 0, errs, err217}218// CheckContainer checks a container spec against the schema219func (check SchemaCheck) CheckContainer(container *corev1.Container) (bool, []jsonschema.ValError, error) {220	return check.CheckObject(container)221}222// CheckObject checks arbitrary data against the schema223func (check SchemaCheck) CheckObject(obj interface{}) (bool, []jsonschema.ValError, error) {224	bytes, err := json.Marshal(obj)225	if err != nil {226		return false, nil, err227	}228	errs, err := check.Validator.ValidateBytes(bytes)229	return len(errs) == 0, errs, err230}231// CheckAdditionalObjects looks for an object that passes the specified additional schema232func (check SchemaCheck) CheckAdditionalObjects(groupkind string, objects []interface{}) (bool, error) {233	val, ok := check.AdditionalValidators[groupkind]234	if !ok {235		return false, errors.New("No validator found for " + groupkind)236	}237	for _, obj := range objects {238		bytes, err := json.Marshal(obj)239		if err != nil {240			return false, err241		}242		errs, err := val.ValidateBytes(bytes)243		if err != nil {244			return false, err245		}246		if len(errs) == 0 {247			return true, nil248		}249	}250	return false, nil251}252// IsActionable decides if this check applies to a particular target253func (check SchemaCheck) IsActionable(target TargetKind, kind string, isInit bool) bool {254	if funk.Contains(HandledTargets, target) {255		if check.Target != target {256			return false257		}258	} else if string(check.Target) != kind && !strings.HasSuffix(string(check.Target), "/"+kind) {259		return false260	}261	isIncluded := len(check.Controllers.Include) == 0262	for _, inclusion := range check.Controllers.Include {263		if inclusion == kind {264			isIncluded = true265			break266		}267	}268	if !isIncluded {269		return false270	}271	for _, exclusion := range check.Controllers.Exclude {272		if exclusion == kind {273			return false274		}275	}276	if check.Target == TargetContainer {277		isIncluded := len(check.Containers.Include) == 0278		for _, inclusion := range check.Containers.Include {279			if (inclusion == "initContainer" && isInit) || (inclusion == "container" && !isInit) {280				isIncluded = true281				break282			}283		}284		if !isIncluded {285			return false286		}287		for _, exclusion := range check.Containers.Exclude {288			if (exclusion == "initContainer" && isInit) || (exclusion == "container" && !isInit) {289				return false290			}291		}292	}293	return true294}...report.go
Source:report.go  
1/*2 * Copyright 2021 Red Hat3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *     http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package chartverifier17import (18	"fmt"19	"github.com/redhat-certification/chart-verifier/pkg/chartverifier/checks"20	helmchart "helm.sh/helm/v3/pkg/chart"21)22var ReportApiVersion = "v1"23var ReportKind = "verify-report"24type OutcomeType string25const (26	FailOutcomeType    OutcomeType = "FAIL"27	PassOutcomeType    OutcomeType = "PASS"28	UnknownOutcomeType OutcomeType = "UNKNOWN"29)30type Report struct {31	Apiversion string         `json:"apiversion" yaml:"apiversion"`32	Kind       string         `json:"kind" yaml:"kind"`33	Metadata   ReportMetadata `json:"metadata" yaml:"metadata"`34	Results    []*CheckReport `json:"results" yaml:"results"`35}36type ReportMetadata struct {37	ToolMetadata ToolMetadata        `json:"tool" yaml:"tool"`38	ChartData    *helmchart.Metadata `json:"chart" yaml:"chart"`39	Overrides    string              `json:"chart-overrides" yaml:"chart-overrides"`40}41type ToolMetadata struct {42	Version                    string  `json:"verifier-version" yaml:"verifier-version"`43	Profile                    Profile `json:"profile" yaml:"profile"`44	ChartUri                   string  `json:"chart-uri" yaml:"chart-uri"`45	Digests                    Digests `json:"digests" yaml:"digests"`46	LastCertifiedTimestamp     string  `json:"lastCertifiedTimestamp,omitempty" yaml:"lastCertifiedTimestamp,omitempty"`47	CertifiedOpenShiftVersions string  `json:"certifiedOpenShiftVersions,omitempty" yaml:"certifiedOpenShiftVersions,omitempty"`48	TestedOpenShiftVersion     string  `json:"testedOpenShiftVersion,omitempty" yaml:"testedOpenShiftVersion,omitempty"`49	SupportedOpenShiftVersions string  `json:"supportedOpenShiftVersions,omitempty" yaml:"supportedOpenShiftVersions,omitempty"`50	ProviderDelivery           bool    `json:"providerControlledDelivery" yaml:"providerControlledDelivery"`51}52type Digests struct {53	Chart   string `json:"chart" yaml:"chart"`54	Package string `json:"package,omitempty" yaml:"package,omitempty"`55}56type Profile struct {57	VendorType string `json:"vendorType" yaml:"VendorType"`58	Version    string `json:"version" yaml:"version"`59}60type CheckReport struct {61	Check   checks.CheckName `json:"check" yaml:"check"`62	Type    checks.CheckType `json:"type" yaml:"type"`63	Outcome OutcomeType      `json:"outcome" yaml:"outcome"`64	Reason  string           `json:"reason" yaml:"reason"`65}66func newReport() Report {67	report := Report{Apiversion: ReportApiVersion, Kind: ReportKind}68	report.Metadata = ReportMetadata{}69	report.Metadata.ToolMetadata = ToolMetadata{}70	return report71}72func (c *Report) AddCheck(check checks.Check) *CheckReport {73	newCheck := CheckReport{}74	newCheck.Check = checks.CheckName(fmt.Sprintf("%s/%s", check.CheckId.Version, check.CheckId.Name))75	newCheck.Type = check.Type76	newCheck.Outcome = UnknownOutcomeType77	c.Results = append(c.Results, &newCheck)78	return &newCheck79}80func (cr *CheckReport) SetResult(outcome bool, reason string) {81	if outcome {82		cr.Outcome = PassOutcomeType83	} else {84		cr.Outcome = FailOutcomeType85	}86	cr.Reason = reason87}...pulse_health.go
Source:pulse_health.go  
...70		amem += m.AllocatableMEM71		tcpu += m.TotalCPU72		tmem += m.TotalMEM73	}74	c1 := health.NewCheck("cpu")75	c1.Set(health.S1, ccpu)76	c1.Set(health.S2, acpu)77	c1.Set(health.S3, tcpu)78	c2 := health.NewCheck("mem")79	c2.Set(health.S1, cmem)80	c2.Set(health.S2, amem)81	c2.Set(health.S3, tmem)82	return health.Checks{c1, c2}, nil83}84func (h *PulseHealth) check(ctx context.Context, ns, gvr string) (*health.Check, error) {85	meta, ok := Registry[gvr]86	if !ok {87		meta = ResourceMeta{88			DAO:      &dao.Table{},89			Renderer: &render.Generic{},90		}91	}92	if meta.DAO == nil {93		meta.DAO = &dao.Resource{}94	}95	meta.DAO.Init(h.factory, client.NewGVR(gvr))96	oo, err := meta.DAO.List(ctx, ns)97	if err != nil {98		return nil, err99	}100	c := health.NewCheck(gvr)101	if meta.Renderer.IsGeneric() {102		table, ok := oo[0].(*metav1beta1.Table)103		if !ok {104			return nil, fmt.Errorf("expecting a meta table but got %T", oo[0])105		}106		rows := make(render.Rows, len(table.Rows))107		re, _ := meta.Renderer.(Generic)108		re.SetTable(table)109		for i, row := range table.Rows {110			if err := re.Render(row, ns, &rows[i]); err != nil {111				return nil, err112			}113			if !render.Happy(ns, re.Header(ns), rows[i]) {114				c.Inc(health.S2)...NewCheck
Using AI Code Generation
1import (2type Check struct {3}4func NewCheck(name string) *Check {5	return &Check{6	}7}8func main() {9	c := NewCheck("check")10	fmt.Println(c.Name)11}NewCheck
Using AI Code Generation
1import (2func main() {3    fmt.Println("main")4    v1.NewCheck()5}6import (7func NewCheck() {8    fmt.Println("v1.NewCheck")9}10import (11func NewCheck() {12    fmt.Println("v2.NewCheck")13}14import (15func NewCheck() {16    fmt.Println("v2.NewCheck")17}18import (19func NewCheck() {20    fmt.Println("v3.NewCheck")21}22import (23func NewCheck() {24    fmt.Println("v4.NewCheck")25}26import (27func NewCheck() {28    fmt.Println("v5.NewCheck")29}30import (31func NewCheck() {32    fmt.Println("v6.NewCheck")33}34import (35func NewCheck() {36    fmt.Println("v7.NewCheck")37}38import (39func NewCheck() {40    fmt.Println("v8.NewCheck")41}NewCheck
Using AI Code Generation
1func main() {2  v1.Check()3}4func main() {5  v1.Check()6}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!!
