Best Gauge code snippet using parser.getResolvedParams
specExecutor.go
Source:specExecutor.go
1// Copyright 2015 ThoughtWorks, Inc.2// This file is part of Gauge.3// Gauge is free software: you can redistribute it and/or modify4// it under the terms of the GNU General Public License as published by5// the Free Software Foundation, either version 3 of the License, or6// (at your option) any later version.7// Gauge is distributed in the hope that it will be useful,8// but WITHOUT ANY WARRANTY; without even the implied warranty of9// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10// GNU General Public License for more details.11// You should have received a copy of the GNU General Public License12// along with Gauge. If not, see <http://www.gnu.org/licenses/>.13package execution14import (15 "fmt"16 "strconv"17 "strings"18 "github.com/getgauge/gauge/execution/event"19 "github.com/getgauge/gauge/execution/result"20 "github.com/getgauge/gauge/gauge"21 "github.com/getgauge/gauge/gauge_messages"22 "github.com/getgauge/gauge/logger"23 "github.com/getgauge/gauge/parser"24 "github.com/getgauge/gauge/plugin"25 "github.com/getgauge/gauge/runner"26 "github.com/getgauge/gauge/validation"27)28type specExecutor struct {29 specification *gauge.Specification30 dataTableIndexes []int31 runner runner.Runner32 pluginHandler *plugin.Handler33 currentExecutionInfo *gauge_messages.ExecutionInfo34 specResult *result.SpecResult35 currentTableRow int36 errMap *gauge.BuildErrors37 stream int38}39func newSpecExecutor(s *gauge.Specification, r runner.Runner, ph *plugin.Handler, e *gauge.BuildErrors, stream int) *specExecutor {40 return &specExecutor{specification: s, runner: r, pluginHandler: ph, errMap: e, stream: stream}41}42func hasParseError(errs []error) bool {43 for _, e := range errs {44 switch e.(type) {45 case parser.ParseError:46 return true47 }48 }49 return false50}51func (e *specExecutor) execute() *result.SpecResult {52 specInfo := &gauge_messages.SpecInfo{Name: e.specification.Heading.Value,53 FileName: e.specification.FileName,54 IsFailed: false, Tags: getTagValue(e.specification.Tags)}55 e.currentExecutionInfo = &gauge_messages.ExecutionInfo{CurrentSpec: specInfo}56 e.specResult = gauge.NewSpecResult(e.specification)57 if errs, ok := e.errMap.SpecErrs[e.specification]; ok {58 if hasParseError(errs) {59 e.failSpec()60 return e.specResult61 }62 }63 resolvedSpecItems := e.resolveItems(e.specification.GetSpecItems())64 e.specResult.AddSpecItems(resolvedSpecItems)65 if _, ok := e.errMap.SpecErrs[e.specification]; ok {66 e.skipSpec()67 return e.specResult68 }69 e.dataTableIndexes = getDataTableRows(e.specification.DataTable.Table.GetRowCount())70 if len(e.specification.Scenarios) == 0 {71 e.skipSpecForError(fmt.Errorf("%s: No scenarios found in spec\n", e.specification.FileName))72 return e.specResult73 }74 event.Notify(event.NewExecutionEvent(event.SpecStart, e.specification, nil, e.stream, *e.currentExecutionInfo))75 defer event.Notify(event.NewExecutionEvent(event.SpecEnd, nil, e.specResult, e.stream, *e.currentExecutionInfo))76 res := e.initSpecDataStore()77 if res.GetFailed() {78 e.skipSpecForError(fmt.Errorf("Failed to initialize spec datastore. Error: %s", res.GetErrorMessage()))79 return e.specResult80 }81 e.notifyBeforeSpecHook()82 if !e.specResult.GetFailed() {83 if e.specification.DataTable.Table.GetRowCount() == 0 {84 scenarioResults := e.executeScenarios()85 e.specResult.AddScenarioResults(scenarioResults)86 } else {87 e.executeTableDrivenSpec()88 }89 }90 e.notifyAfterSpecHook()91 e.specResult.SetSkipped(e.specResult.ScenarioSkippedCount == len(e.specification.Scenarios))92 return e.specResult93}94func (e *specExecutor) executeTableDrivenSpec() {95 var res [][]result.Result96 var executedRowIndexes []int97 for _, tableRowIndex := range e.dataTableIndexes {98 e.currentTableRow = tableRowIndex99 res = append(res, e.executeScenarios())100 executedRowIndexes = append(executedRowIndexes, e.currentTableRow)101 }102 e.specResult.AddTableDrivenScenarioResult(res, executedRowIndexes)103}104func (e *specExecutor) resolveItems(items []gauge.Item) []*gauge_messages.ProtoItem {105 var protoItems []*gauge_messages.ProtoItem106 for _, item := range items {107 if item.Kind() != gauge.TearDownKind {108 protoItems = append(protoItems, e.resolveToProtoItem(item))109 }110 }111 return protoItems112}113func (e *specExecutor) resolveToProtoItem(item gauge.Item) *gauge_messages.ProtoItem {114 var protoItem *gauge_messages.ProtoItem115 switch item.Kind() {116 case gauge.StepKind:117 if (item.(*gauge.Step)).IsConcept {118 concept := item.(*gauge.Step)119 protoItem = e.resolveToProtoConceptItem(*concept)120 } else {121 protoItem = e.resolveToProtoStepItem(item.(*gauge.Step))122 }123 break124 default:125 protoItem = gauge.ConvertToProtoItem(item)126 }127 return protoItem128}129// Not passing pointer as we cannot modify the original concept step's lookup. This has to be populated for each iteration over data table.130func (e *specExecutor) resolveToProtoConceptItem(concept gauge.Step) *gauge_messages.ProtoItem {131 paramResolver := new(parser.ParamResolver)132 parser.PopulateConceptDynamicParams(&concept, e.dataTableLookup())133 protoConceptItem := gauge.ConvertToProtoItem(&concept)134 protoConceptItem.Concept.ConceptStep.StepExecutionResult = &gauge_messages.ProtoStepExecutionResult{}135 for stepIndex, step := range concept.ConceptSteps {136 // Need to reset parent as the step.parent is pointing to a concept whose lookup is not populated yet137 if step.IsConcept {138 step.Parent = &concept139 protoConceptItem.GetConcept().GetSteps()[stepIndex] = e.resolveToProtoConceptItem(*step)140 } else {141 stepParameters := paramResolver.GetResolvedParams(step, &concept, e.dataTableLookup())142 updateProtoStepParameters(protoConceptItem.Concept.Steps[stepIndex].Step, stepParameters)143 e.setSkipInfo(protoConceptItem.Concept.Steps[stepIndex].Step, step)144 }145 }146 protoConceptItem.Concept.ConceptStep.StepExecutionResult.Skipped = false147 return protoConceptItem148}149func (e *specExecutor) resolveToProtoStepItem(step *gauge.Step) *gauge_messages.ProtoItem {150 protoStepItem := gauge.ConvertToProtoItem(step)151 paramResolver := new(parser.ParamResolver)152 parameters := paramResolver.GetResolvedParams(step, nil, e.dataTableLookup())153 updateProtoStepParameters(protoStepItem.Step, parameters)154 e.setSkipInfo(protoStepItem.Step, step)155 return protoStepItem156}157func (e *specExecutor) initSpecDataStore() *gauge_messages.ProtoExecutionResult {158 initSpecDataStoreMessage := &gauge_messages.Message{MessageType: gauge_messages.Message_SpecDataStoreInit,159 SpecDataStoreInitRequest: &gauge_messages.SpecDataStoreInitRequest{}}160 return e.runner.ExecuteAndGetStatus(initSpecDataStoreMessage)161}162func (e *specExecutor) notifyBeforeSpecHook() {163 m := &gauge_messages.Message{MessageType: gauge_messages.Message_SpecExecutionStarting,164 SpecExecutionStartingRequest: &gauge_messages.SpecExecutionStartingRequest{CurrentExecutionInfo: e.currentExecutionInfo}}165 res := executeHook(m, e.specResult, e.runner, e.pluginHandler)166 if res.GetFailed() {167 setSpecFailure(e.currentExecutionInfo)168 handleHookFailure(e.specResult, res, result.AddPreHook)169 }170}171func (e *specExecutor) notifyAfterSpecHook() {172 m := &gauge_messages.Message{MessageType: gauge_messages.Message_SpecExecutionEnding,173 SpecExecutionEndingRequest: &gauge_messages.SpecExecutionEndingRequest{CurrentExecutionInfo: e.currentExecutionInfo}}174 res := executeHook(m, e.specResult, e.runner, e.pluginHandler)175 if res.GetFailed() {176 setSpecFailure(e.currentExecutionInfo)177 handleHookFailure(e.specResult, res, result.AddPostHook)178 }179}180func executeHook(message *gauge_messages.Message, execTimeTracker result.ExecTimeTracker, r runner.Runner, ph *plugin.Handler) *gauge_messages.ProtoExecutionResult {181 ph.NotifyPlugins(message)182 executionResult := r.ExecuteAndGetStatus(message)183 execTimeTracker.AddExecTime(executionResult.GetExecutionTime())184 return executionResult185}186func (e *specExecutor) skipSpecForError(err error) {187 logger.Errorf(err.Error())188 validationError := validation.NewStepValidationError(&gauge.Step{LineNo: e.specification.Heading.LineNo, LineText: e.specification.Heading.Value},189 err.Error(), e.specification.FileName, nil)190 for _, scenario := range e.specification.Scenarios {191 e.errMap.ScenarioErrs[scenario] = []error{validationError}192 }193 e.errMap.SpecErrs[e.specification] = []error{validationError}194 e.skipSpec()195}196func (e *specExecutor) accumulateSkippedScenarioResults() []result.Result {197 var scenarioResults []result.Result198 for _, scenario := range e.specification.Scenarios {199 scenarioResults = append(scenarioResults, e.getSkippedScenarioResult(scenario))200 }201 return scenarioResults202}203func (e *specExecutor) failSpec() {204 e.specResult.Errors = e.convertErrors(e.errMap.SpecErrs[e.specification])205 e.specResult.SetFailure()206}207func (e *specExecutor) skipSpec() {208 if e.specResult.ProtoSpec.GetIsTableDriven() {209 res := make([][]result.Result, 0)210 executedRowIndexes := make([]int, 0)211 for i := 0; i < e.specification.DataTable.Table.GetRowCount(); i++ {212 e.currentTableRow = i213 res = append(res, e.accumulateSkippedScenarioResults())214 executedRowIndexes = append(executedRowIndexes, e.currentTableRow)215 }216 e.specResult.AddTableDrivenScenarioResult(res, executedRowIndexes)217 } else {218 e.specResult.AddScenarioResults(e.accumulateSkippedScenarioResults())219 }220 e.specResult.Errors = e.convertErrors(e.errMap.SpecErrs[e.specification])221 e.specResult.Skipped = true222}223func (e *specExecutor) convertErrors(specErrors []error) []*gauge_messages.Error {224 var errors []*gauge_messages.Error225 for _, e := range specErrors {226 switch e.(type) {227 case parser.ParseError:228 err := e.(parser.ParseError)229 errors = append(errors, &gauge_messages.Error{230 Message: err.Error(),231 LineNumber: int32(err.LineNo),232 Filename: err.FileName,233 Type: gauge_messages.Error_PARSE_ERROR,234 })235 case validation.StepValidationError, validation.SpecValidationError:236 errors = append(errors, &gauge_messages.Error{237 Message: e.Error(),238 Type: gauge_messages.Error_VALIDATION_ERROR,239 })240 }241 }242 return errors243}244func (e *specExecutor) setSkipInfo(protoStep *gauge_messages.ProtoStep, step *gauge.Step) {245 protoStep.StepExecutionResult = &gauge_messages.ProtoStepExecutionResult{}246 protoStep.StepExecutionResult.Skipped = false247 if _, ok := e.errMap.StepErrs[step]; ok {248 protoStep.StepExecutionResult.Skipped = true249 protoStep.StepExecutionResult.SkippedReason = "Step implementation not found"250 }251}252func (e *specExecutor) getItemsForScenarioExecution(steps []*gauge.Step) []*gauge_messages.ProtoItem {253 items := make([]gauge.Item, len(steps))254 for i, context := range steps {255 items[i] = context256 }257 return e.resolveItems(items)258}259func (e *specExecutor) dataTableLookup() *gauge.ArgLookup {260 return new(gauge.ArgLookup).FromDataTableRow(&e.specification.DataTable.Table, e.currentTableRow)261}262func (e *specExecutor) getCurrentDataTableValueFor(columnName string) string {263 return e.specification.DataTable.Table.Get(columnName)[e.currentTableRow].Value264}265func (e *specExecutor) executeScenarios() []result.Result {266 var scenarioResults []result.Result267 for _, scenario := range e.specification.Scenarios {268 scenarioResults = append(scenarioResults, e.executeScenario(scenario))269 }270 return scenarioResults271}272func (e *specExecutor) executeScenario(scenario *gauge.Scenario) *result.ScenarioResult {273 e.currentExecutionInfo.CurrentScenario = &gauge_messages.ScenarioInfo{274 Name: scenario.Heading.Value,275 Tags: getTagValue(scenario.Tags),276 IsFailed: false,277 }278 scenarioResult := result.NewScenarioResult(gauge.NewProtoScenario(scenario))279 // TODO: During data driven execution, scenario holds the last row of datatable in scenario.DataTableRow.280 // This can be eliminated by creating a new scenario instance for each of the table row execution.281 if e.specification.DataTable.Table.GetRowCount() != 0 {282 var dataTable gauge.Table283 dataTable.AddHeaders(e.specification.DataTable.Table.Headers)284 dataTable.AddRowValues(e.specification.DataTable.Table.Rows()[e.currentTableRow])285 scenario.DataTableRow = dataTable286 scenario.DataTableRowIndex = e.currentTableRow287 }288 e.addAllItemsForScenarioExecution(scenario, scenarioResult)289 scenarioExec := newScenarioExecutor(e.runner, e.pluginHandler, e.currentExecutionInfo, e.errMap, e.stream)290 scenarioExec.execute(scenarioResult, scenario, e.specification.Contexts, e.specification.TearDownSteps)291 if scenarioResult.ProtoScenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_SKIPPED {292 e.specResult.ScenarioSkippedCount++293 }294 return scenarioResult295}296func (e *specExecutor) addAllItemsForScenarioExecution(scenario *gauge.Scenario, scenarioResult *result.ScenarioResult) {297 scenarioResult.AddContexts(e.getItemsForScenarioExecution(e.specification.Contexts))298 scenarioResult.AddTearDownSteps(e.getItemsForScenarioExecution(e.specification.TearDownSteps))299 scenarioResult.AddItems(e.resolveItems(scenario.Items))300}301func (e *specExecutor) getSkippedScenarioResult(scenario *gauge.Scenario) *result.ScenarioResult {302 scenarioResult := &result.ScenarioResult{ProtoScenario: gauge.NewProtoScenario(scenario)}303 e.addAllItemsForScenarioExecution(scenario, scenarioResult)304 setSkipInfoInResult(scenarioResult, scenario, e.errMap)305 e.specResult.ScenarioSkippedCount++306 return scenarioResult307}308func updateProtoStepParameters(protoStep *gauge_messages.ProtoStep, parameters []*gauge_messages.Parameter) {309 paramIndex := 0310 for fragmentIndex, fragment := range protoStep.Fragments {311 if fragment.GetFragmentType() == gauge_messages.Fragment_Parameter {312 protoStep.Fragments[fragmentIndex].Parameter = parameters[paramIndex]313 paramIndex++314 }315 }316}317func getTagValue(tags *gauge.Tags) []string {318 var tagValues []string319 if tags != nil {320 tagValues = append(tagValues, tags.Values...)321 }322 return tagValues323}324func setSpecFailure(executionInfo *gauge_messages.ExecutionInfo) {325 executionInfo.CurrentSpec.IsFailed = true326}327func getDataTableRows(rowCount int) []int {328 var tableRowIndexes []int329 if rowCount == 0 && TableRows == "" {330 tableRowIndexes = []int{}331 } else if TableRows == "" {332 for i := 0; i < rowCount; i++ {333 tableRowIndexes = append(tableRowIndexes, i)334 }335 } else if strings.Contains(TableRows, "-") {336 indexes := strings.Split(TableRows, "-")337 startRow, _ := strconv.Atoi(strings.TrimSpace(indexes[0]))338 endRow, _ := strconv.Atoi(strings.TrimSpace(indexes[1]))339 for i := startRow - 1; i < endRow; i++ {340 tableRowIndexes = append(tableRowIndexes, i)341 }342 } else {343 indexes := strings.Split(TableRows, ",")344 for _, i := range indexes {345 rowNumber, _ := strconv.Atoi(strings.TrimSpace(i))346 tableRowIndexes = append(tableRowIndexes, rowNumber-1)347 }348 }349 return tableRowIndexes350}...
resolver.go
Source:resolver.go
...30 return invalidSpecialParamError.message31}32//Resolve takes a step, a lookup and updates the target after reconciling the dynamic paramters from the given lookup33func Resolve(step *gauge.Step, parent *gauge.Step, lookup *gauge.ArgLookup, target *gauge_messages.ProtoStep) error {34 stepParameters, err := getResolvedParams(step, parent, lookup)35 if err != nil {36 return err37 }38 paramIndex := 039 for fragmentIndex, fragment := range target.Fragments {40 if fragment.GetFragmentType() == gauge_messages.Fragment_Parameter {41 target.Fragments[fragmentIndex].Parameter = stepParameters[paramIndex]42 paramIndex++43 }44 }45 return nil46}47// getResolvedParams based on the arg type(static, dynamic, table, special_string, special_table) resolves the parameter of a step.48func getResolvedParams(step *gauge.Step, parent *gauge.Step, lookup *gauge.ArgLookup) ([]*gauge_messages.Parameter, error) {49 parameters := make([]*gauge_messages.Parameter, 0)50 for _, arg := range step.Args {51 parameter := new(gauge_messages.Parameter)52 parameter.Name = arg.Name53 if arg.ArgType == gauge.Static {54 parameter.ParameterType = gauge_messages.Parameter_Static55 parameter.Value = arg.Value56 } else if arg.ArgType == gauge.Dynamic {57 var resolvedArg *gauge.StepArg58 var err error59 if parent != nil {60 resolvedArg, err = parent.GetArg(arg.Value)61 } else {62 resolvedArg, err = lookup.GetArg(arg.Value)...
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!!