Best Gauge code snippet using validation.NewSpecValidationError
specExecutor_test.go
Source:specExecutor_test.go
...282 SpecErrs: make(map[*gauge.Specification][]error),283 ScenarioErrs: make(map[*gauge.Scenario][]error),284 StepErrs: make(map[*gauge.Step]error),285 }286 errMap.SpecErrs[spec] = []error{validation.NewSpecValidationError("Step implementation not found", spec.FileName)}287 se := newSpecExecutor(spec, nil, nil, errMap, 0)288 specInfo := &gauge_messages.SpecInfo{Name: se.specification.Heading.Value,289 FileName: se.specification.FileName,290 IsFailed: false, Tags: getTagValue(se.specification.Tags)}291 se.currentExecutionInfo = &gauge_messages.ExecutionInfo{CurrentSpec: specInfo}292 se.specResult = gauge.NewSpecResult(se.specification)293 resolvedSpecItems := se.resolveItems(se.specification.GetSpecItems())294 se.specResult.AddSpecItems(resolvedSpecItems)295 se.skipSpec()296 c.Assert(se.specResult.ProtoSpec.GetIsTableDriven(), Equals, true)297 c.Assert(len(se.specResult.ProtoSpec.GetItems()), Equals, 3)298}299func anySpec() *gauge.Specification {300 specText := SpecBuilder().specHeading("A spec heading").301 scenarioHeading("First scenario").302 step("create user \"456\" \"foo\" and \"9900\"").303 String()304 spec, _ := new(parser.SpecParser).Parse(specText, gauge.NewConceptDictionary(), "")305 spec.FileName = "FILE"306 return spec307}308func (s *MySuite) TestSpecIsSkippedIfDataRangeIsInvalid(c *C) {309 errMap := &gauge.BuildErrors{310 SpecErrs: make(map[*gauge.Specification][]error),311 ScenarioErrs: make(map[*gauge.Scenario][]error),312 StepErrs: make(map[*gauge.Step]error),313 }314 spec := anySpec()315 errMap.SpecErrs[spec] = []error{validation.NewSpecValidationError("Table row number out of range", spec.FileName)}316 se := newSpecExecutor(spec, nil, nil, errMap, 0)317 specResult := se.execute()318 c.Assert(specResult.Skipped, Equals, true)319}320func (s *MySuite) TestDataTableRowsAreSkippedForUnimplemetedStep(c *C) {321 stepText := "Unimplememted step"322 specText := SpecBuilder().specHeading("A spec heading").323 tableHeader("id", "name", "phone").324 tableRow("123", "foo", "8800").325 tableRow("666", "bar", "9900").326 scenarioHeading("First scenario").327 step(stepText).328 step("create user <id> <name> and <phone>").329 String()330 spec, _ := new(parser.SpecParser).Parse(specText, gauge.NewConceptDictionary(), "")331 errMap := &gauge.BuildErrors{332 SpecErrs: make(map[*gauge.Specification][]error),333 ScenarioErrs: make(map[*gauge.Scenario][]error),334 StepErrs: make(map[*gauge.Step]error),335 }336 errMap.SpecErrs[spec] = []error{validation.NewSpecValidationError("Step implementation not found", spec.FileName)}337 se := newSpecExecutor(spec, nil, nil, errMap, 0)338 specResult := se.execute()339 c.Assert(specResult.ProtoSpec.GetIsTableDriven(), Equals, true)340 c.Assert(specResult.Skipped, Equals, true)341}342func (s *MySuite) TestConvertParseErrorToGaugeMessagesError(c *C) {343 e := parser.ParseError{Message: "Message", LineNo: 5, FileName: "filename"}344 se := newSpecExecutor(nil, nil, nil, nil, 0)345 errs := se.convertErrors([]error{e})346 expected := gauge_messages.Error{347 Type: gauge_messages.Error_PARSE_ERROR,348 Message: "filename:5 Message => ''",349 LineNumber: 5,350 Filename: "filename",351 }352 c.Assert(len(errs), DeepEquals, 1)353 c.Assert(*(errs[0]), DeepEquals, expected)354}355func (s *MySuite) TestConvertSpecValidationErrorToGaugeMessagesError(c *C) {356 e := validation.NewSpecValidationError("Message", "filename")357 se := newSpecExecutor(nil, nil, nil, nil, 0)358 errs := se.convertErrors([]error{e})359 expected := gauge_messages.Error{360 Type: gauge_messages.Error_VALIDATION_ERROR,361 Message: "filename Message",362 }363 c.Assert(len(errs), DeepEquals, 1)364 c.Assert(*(errs[0]), DeepEquals, expected)365}366func (s *MySuite) TestConvertStepValidationErrorToGaugeMessagesError(c *C) {367 e := validation.NewStepValidationError(&gauge.Step{LineText: "step", LineNo: 3}, "Step Message", "filename", nil)368 se := newSpecExecutor(nil, nil, nil, nil, 0)369 errs := se.convertErrors([]error{e})370 expected := gauge_messages.Error{...
validate.go
Source:validate.go
...82// Error prints a spec validation error with filename and error message.83func (s SpecValidationError) Error() string {84 return fmt.Sprintf("%s %s", s.fileName, s.message)85}86// NewSpecValidationError generates new spec validation error with error message and filename.87func NewSpecValidationError(m string, f string) SpecValidationError {88 return SpecValidationError{message: m, fileName: f}89}90// NewStepValidationError generates new step validation error with error message, filename and error type.91func NewStepValidationError(s *gauge.Step, m string, f string, e *gm.StepValidateResponse_ErrorType, suggestion string) StepValidationError {92 return StepValidationError{step: s, message: m, fileName: f, errorType: e, suggestion: suggestion}93}94// Validate validates specs and if it has any errors, it exits.95func Validate(args []string) {96 if len(args) == 0 {97 args = append(args, util.GetSpecDirs()...)98 }99 res := ValidateSpecs(args, false)100 if len(res.Errs) > 0 {101 os.Exit(1)102 }103 if res.SpecCollection.Size() < 1 {104 logger.Infof(true, "No specifications found in %s.", strings.Join(args, ", "))105 res.Runner.Kill()106 if res.ParseOk {107 os.Exit(0)108 }109 os.Exit(1)110 }111 res.Runner.Kill()112 if res.ErrMap.HasErrors() {113 os.Exit(1)114 }115 logger.Infof(true, "No errors found.")116}117//TODO : duplicate in execute.go. Need to fix runner init.118func startAPI(debug bool) runner.Runner {119 sc := api.StartAPI(debug, reporter.Current())120 select {121 case runner := <-sc.RunnerChan:122 return runner123 case err := <-sc.ErrorChan:124 logger.Fatalf(true, "Failed to start gauge API: %s", err.Error())125 }126 return nil127}128type ValidationResult struct {129 SpecCollection *gauge.SpecCollection130 ErrMap *gauge.BuildErrors131 Runner runner.Runner132 Errs []error133 ParseOk bool134}135// NewValidationResult creates a new Validation result136func NewValidationResult(s *gauge.SpecCollection, errMap *gauge.BuildErrors, r runner.Runner, parseOk bool, e ...error) *ValidationResult {137 return &ValidationResult{SpecCollection: s, ErrMap: errMap, Runner: r, ParseOk: parseOk, Errs: e}138}139// ValidateSpecs parses the specs, creates a new validator and call the runner to get the validation result.140func ValidateSpecs(args []string, debug bool) *ValidationResult {141 conceptDict, res, err := parser.ParseConcepts()142 if err != nil {143 logger.Fatalf(true, "Unable to validate : %s", err.Error())144 }145 errMap := gauge.NewBuildErrors()146 s, specsFailed := parser.ParseSpecs(args, conceptDict, errMap)147 r := startAPI(debug)148 vErrs := NewValidator(s, r, conceptDict).Validate()149 errMap = getErrMap(errMap, vErrs)150 s = parser.GetSpecsForDataTableRows(s, errMap)151 printValidationFailures(vErrs)152 showSuggestion(vErrs)153 if !res.Ok {154 r.Kill()155 return NewValidationResult(nil, nil, nil, false, errors.New("Parsing failed."))156 }157 if specsFailed {158 return NewValidationResult(gauge.NewSpecCollection(s, false), errMap, r, false)159 }160 return NewValidationResult(gauge.NewSpecCollection(s, false), errMap, r, true)161}162func getErrMap(errMap *gauge.BuildErrors, validationErrors validationErrors) *gauge.BuildErrors {163 for spec, valErrors := range validationErrors {164 for _, err := range valErrors {165 switch err.(type) {166 case StepValidationError:167 errMap.StepErrs[err.(StepValidationError).step] = err.(StepValidationError)168 case SpecValidationError:169 errMap.SpecErrs[spec] = append(errMap.SpecErrs[spec], err.(SpecValidationError))170 }171 }172 skippedScnInSpec := 0173 for _, scenario := range spec.Scenarios {174 fillScenarioErrors(scenario, errMap, scenario.Steps)175 if _, ok := errMap.ScenarioErrs[scenario]; ok {176 skippedScnInSpec++177 }178 }179 if len(spec.Scenarios) > 0 && skippedScnInSpec == len(spec.Scenarios) {180 errMap.SpecErrs[spec] = append(errMap.SpecErrs[spec], errMap.ScenarioErrs[spec.Scenarios[0]]...)181 }182 fillSpecErrors(spec, errMap, append(spec.Contexts, spec.TearDownSteps...))183 }184 return errMap185}186func fillScenarioErrors(scenario *gauge.Scenario, errMap *gauge.BuildErrors, steps []*gauge.Step) {187 for _, step := range steps {188 if step.IsConcept {189 fillScenarioErrors(scenario, errMap, step.ConceptSteps)190 }191 if err, ok := errMap.StepErrs[step]; ok {192 errMap.ScenarioErrs[scenario] = append(errMap.ScenarioErrs[scenario], err)193 }194 }195}196func fillSpecErrors(spec *gauge.Specification, errMap *gauge.BuildErrors, steps []*gauge.Step) {197 for _, context := range steps {198 if context.IsConcept {199 fillSpecErrors(spec, errMap, context.ConceptSteps)200 }201 if err, ok := errMap.StepErrs[context]; ok {202 errMap.SpecErrs[spec] = append(errMap.SpecErrs[spec], err)203 for _, scenario := range spec.Scenarios {204 if _, ok := errMap.ScenarioErrs[scenario]; !ok {205 errMap.ScenarioErrs[scenario] = append(errMap.ScenarioErrs[scenario], err)206 }207 }208 }209 }210}211func printValidationFailures(validationErrors validationErrors) {212 for _, e := range FilterDuplicates(validationErrors) {213 logger.Errorf(true, "[ValidationError] %s", e.Error())214 }215}216func FilterDuplicates(validationErrors validationErrors) []error {217 filteredErrs := make([]error, 0)218 exists := make(map[string]bool)219 for _, errs := range validationErrors {220 for _, e := range errs {221 var val string222 if vErr, ok := e.(StepValidationError); ok {223 val = vErr.step.Value + vErr.step.FileName + strconv.Itoa(e.(StepValidationError).step.LineNo)224 } else if vErr, ok := e.(SpecValidationError); ok {225 val = vErr.message + vErr.fileName226 } else {227 continue228 }229 if _, ok := exists[val]; !ok {230 exists[val] = true231 filteredErrs = append(filteredErrs, e)232 }233 }234 }235 return filteredErrs236}237type validationErrors map[*gauge.Specification][]error238func NewValidator(s []*gauge.Specification, r runner.Runner, c *gauge.ConceptDictionary) *validator {239 return &validator{specsToExecute: s, runner: r, conceptsDictionary: c}240}241func (v *validator) Validate() validationErrors {242 validationStatus := make(validationErrors)243 specValidator := &SpecValidator{runner: v.runner, conceptsDictionary: v.conceptsDictionary, stepValidationCache: make(map[string]error)}244 for _, spec := range v.specsToExecute {245 specValidator.specification = spec246 validationErrors := specValidator.validate()247 if len(validationErrors) != 0 {248 validationStatus[spec] = validationErrors249 }250 }251 if len(validationStatus) > 0 {252 return validationStatus253 }254 return nil255}256func (v *SpecValidator) validate() []error {257 queue := &gauge.ItemQueue{Items: v.specification.AllItems()}258 v.specification.Traverse(v, queue)259 return v.validationErrors260}261// Validates a step. If validation result from runner is not valid then it creates a new validation error.262// If the error type is StepValidateResponse_STEP_IMPLEMENTATION_NOT_FOUND then gives suggestion with step implementation stub.263func (v *SpecValidator) Step(s *gauge.Step) {264 if s.IsConcept {265 for _, c := range s.ConceptSteps {266 v.Step(c)267 }268 return269 }270 val, ok := v.stepValidationCache[s.Value]271 if !ok {272 err := v.validateStep(s)273 if err != nil {274 v.validationErrors = append(v.validationErrors, err)275 }276 v.stepValidationCache[s.Value] = err277 return278 }279 if val != nil {280 valErr := val.(StepValidationError)281 if s.Parent == nil {282 v.validationErrors = append(v.validationErrors,283 NewStepValidationError(s, valErr.message, v.specification.FileName, valErr.errorType, valErr.suggestion))284 } else {285 cpt := v.conceptsDictionary.Search(s.Parent.Value)286 v.validationErrors = append(v.validationErrors,287 NewStepValidationError(s, valErr.message, cpt.FileName, valErr.errorType, valErr.suggestion))288 }289 }290}291var invalidResponse gm.StepValidateResponse_ErrorType = -1292func (v *SpecValidator) validateStep(s *gauge.Step) error {293 stepValue, err := parser.ExtractStepValueAndParams(s.LineText, s.HasInlineTable)294 if err != nil {295 return nil296 }297 protoStepValue := gauge.ConvertToProtoStepValue(stepValue)298 m := &gm.Message{MessageType: gm.Message_StepValidateRequest,299 StepValidateRequest: &gm.StepValidateRequest{StepText: s.Value, NumberOfParameters: int32(len(s.Args)), StepValue: protoStepValue}}300 r, err := v.runner.ExecuteMessageWithTimeout(m)301 if err != nil {302 return NewStepValidationError(s, err.Error(), v.specification.FileName, &invalidResponse, "")303 }304 if r.GetMessageType() == gm.Message_StepValidateResponse {305 res := r.GetStepValidateResponse()306 if !res.GetIsValid() {307 msg := getMessage(res.GetErrorType().String())308 suggestion := res.GetSuggestion()309 if s.Parent == nil {310 vErr := NewStepValidationError(s, msg, v.specification.FileName, &res.ErrorType, suggestion)311 return vErr312 }313 cpt := v.conceptsDictionary.Search(s.Parent.Value)314 vErr := NewStepValidationError(s, msg, cpt.FileName, &res.ErrorType, suggestion)315 return vErr316 }317 return nil318 }319 return NewStepValidationError(s, "Invalid response from runner for Validation request", v.specification.FileName, &invalidResponse, "")320}321func getMessage(message string) string {322 lower := strings.ToLower(strings.Replace(message, "_", " ", -1))323 return strings.ToUpper(lower[:1]) + lower[1:]324}325func (v *SpecValidator) TearDown(step *gauge.TearDown) {326}327func (v *SpecValidator) Heading(heading *gauge.Heading) {328}329func (v *SpecValidator) Tags(tags *gauge.Tags) {330}331func (v *SpecValidator) Table(dataTable *gauge.Table) {332}333func (v *SpecValidator) Scenario(scenario *gauge.Scenario) {334}335func (v *SpecValidator) Comment(comment *gauge.Comment) {336}337func (v *SpecValidator) DataTable(dataTable *gauge.DataTable) {338}339// Validates data table for the range, if any error found append to the validation errors340func (v *SpecValidator) Specification(specification *gauge.Specification) {341 v.validationErrors = make([]error, 0)342 err := validateDataTableRange(specification.DataTable.Table.GetRowCount())343 if err != nil {344 v.validationErrors = append(v.validationErrors, NewSpecValidationError(err.Error(), specification.FileName))345 }346}347func validateDataTableRange(rowCount int) error {348 if TableRows == "" {349 return nil350 }351 if strings.Contains(TableRows, "-") {352 indexes := strings.Split(TableRows, "-")353 if len(indexes) > 2 {354 return fmt.Errorf("Table rows range '%s' is invalid => Table rows range should be of format rowNumber-rowNumber", TableRows)355 }356 if err := validateTableRow(indexes[0], rowCount); err != nil {357 return err358 }...
NewSpecValidationError
Using AI Code Generation
1import (2func main() {3 specVal := validate.NewSpecValidator(&spec.Swagger{}, nil, "")4 err := specVal.NewSpecValidationError("Error")5 fmt.Println(err)6}7Recommended Posts: Go | os.Chdir() method8Go | os.Getwd() method9Go | os.Chmod() method10Go | os.Chown() method11Go | os.Chtimes() method12Go | os.Mkdir() method13Go | os.MkdirAll() method14Go | os.Remove() method15Go | os.RemoveAll() method16Go | os.Rename() method17Go | os.Truncate() method18Go | os.Open() method19Go | os.OpenFile() method20Go | os.Stat() method21Go | os.IsExist() method22Go | os.IsNotExist() method23Go | os.IsPermission() method24Go | os.IsTimeout() method25Go | os.IsTemporary() method26Go | os.IsPathSeparator() method27Go | os.ReadDir() method28Go | os.Readlink() method29Go | os.SameFile() method30Go | os.Symlink() method31Go | os.TempDir() method32Go | os.WriteFile() method33Go | os.Read() method34Go | os.ReadAt() method35Go | os.Write() method36Go | os.WriteAt() method37Go | os.Fd() method38Go | os.FileInfo() method39Go | os.FileMode() method40Go | os.Name() method41Go | os.Sync() method42Go | os.Close() method43Go | os.Seek() method44Go | os.SetDeadline() method45Go | os.SetReadDeadline() method46Go | os.SetWriteDeadline() method47Go | os.Hostname() method48Go | os.LookupEnv() method49Go | os.Setenv() method50Go | os.Unsetenv() method51Go | os.Environ() method52Go | os.Exit() method53Go | os.Expand() method54Go | os.ExpandEnv() method55Go | os.Getpid() method56Go | os.Getppid() method57Go | os.Getuid() method58Go | os.Geteuid() method
NewSpecValidationError
Using AI Code Generation
1import (2func main() {3 specValidationError = spec.NewSpecValidationError("error", "error")4 fmt.Println(specValidationError)5}6import (7func main() {8 specError = spec.NewSpecError("error", "error")9 fmt.Println(specError)10}11import (12func main() {13 specError = spec.NewSpecErrorWithCause("error", "error", nil)14 fmt.Println(specError)15}16import (17func main() {18 specError = spec.NewSpecErrorWithDetails("error", "error", "error", nil)19 fmt.Println(specError)20}21import (22func main() {23 specError = spec.NewSpecErrorWithLocation("error", "error", nil)24 fmt.Println(specError)25}26import (27func main() {28 specError = spec.NewSpecErrorWithLocationf("error", "error", nil, "error")29 fmt.Println(specError)30}
NewSpecValidationError
Using AI Code Generation
1import (2func main() {3 err := validate.NewSpecValidationError("Error occurred while validating the spec")4 fmt.Println(err)5}6import (7func main() {8 err := validate.NewSpecValidationError("Error occurred while validating the spec")9 fmt.Println(err)10}11import (12func main() {13 err := validate.NewSpecValidationError("Error occurred while validating the spec")14 fmt.Println(err)15}16import (17func main() {18 err := validate.NewSpecValidationError("Error occurred while validating the spec")19 fmt.Println(err)20}21import (22func main() {23 err := validate.NewSpecValidationError("Error occurred while validating the spec")24 fmt.Println(err)25}26import (27func main() {28 err := validate.NewSpecValidationError("Error occurred while validating the spec")29 fmt.Println(err)30}31import (32func main() {33 err := validate.NewSpecValidationError("Error occurred while validating the spec")34 fmt.Println(err)35}36import (37func main() {38 err := validate.NewSpecValidationError("Error occurred while validating the spec")39 fmt.Println(err)40}41import (42func main() {43 err := validate.NewSpecValidationError("Error occurred while validating the spec")
NewSpecValidationError
Using AI Code Generation
1func NewSpecValidationError() *ValidationError {2 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}3}4func NewSpecValidationError() *ValidationError {5 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}6}7func NewSpecValidationError() *ValidationError {8 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}9}10func NewSpecValidationError() *ValidationError {11 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}12}13func NewSpecValidationError() *ValidationError {14 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}15}16func NewSpecValidationError() *ValidationError {17 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}18}19func NewSpecValidationError() *ValidationError {20 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}21}22func NewSpecValidationError() *ValidationError {23 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}24}25func NewSpecValidationError() *ValidationError {26 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}27}28func NewSpecValidationError() *ValidationError {29 return &ValidationError{Code: "SpecValidationError", Message: "Spec validation error"}30}31func NewSpecValidationError() *ValidationError {
NewSpecValidationError
Using AI Code Generation
1import (2func main() {3 sve := validate.NewSpecValidationError("spec", "spec")4 fmt.Println(sve)5}6&{spec spec []}7import (8func main() {9 sve := validate.NewSpecValidationError("spec", "spec")10 sve.AddErrors(validate.NewRequiredError("spec", "spec"))11 fmt.Println(sve)12}13&{spec spec [spec: spec is required]}14import (15func main() {16 sve := validate.NewSpecValidationError("spec", "spec")17 sve.AddErrors(validate.NewRequiredError("spec", "spec"))18 sve.AddWarnings(validate.NewRequiredError("spec", "spec"))19 fmt.Println(sve)20}21&{spec spec [spec: spec is required] [spec: spec is required]}22import (23func main() {24 sve := validate.NewSpecValidationError("spec", "spec")
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!!