Best Gherkin-dotnet code snippet using Gherkin.Ast.Location
GherkinEntityExtensions.cs
Source:GherkinEntityExtensions.cs
...45 Description = feature.Description,46 Tags = feature.Tags.ConvertToStrings(),47 Scenarios = scenarios.Select(scenario => scenario.ConvertToScenario(dialect)).ToArray(),48 Background = background?.ConvertToBackground(dialect),49 Location = feature.Location.ConvertToSourceLocation()50 };51 }52 /// <summary>53 /// Converts the provided <see cref="Gherkin.Ast.Location"/> instance into a <see cref="SourceLocation"/> instance.54 /// </summary>55 /// <param name="location">The <see cref="Gherkin.Ast.Location"/> instance that should be converted.</param>56 /// <returns>A <see cref="SourceLocation"/> instance containing the necessary data from the provided <paramref name="location"/>.</returns>57 public static SourceLocation ConvertToSourceLocation(this Gherkin.Ast.Location location)58 {59 if (location == null)60 {61 return null;62 }63 return new SourceLocation { Column = location.Column, Line = location.Line };64 }65 /// <summary>66 /// Converts the provided <see cref="Gherkin.Ast.Tag"/> instances into an enumerable collection of strings.67 /// </summary>68 /// <param name="tags">The <see cref="Gherkin.Ast.Tag"/> instances that should be converted.</param>69 /// <returns>An enumerable collection of strings.</returns>70 public static IEnumerable<string> ConvertToStrings(this IEnumerable<Gherkin.Ast.Tag> tags)71 {72 if (tags == null)73 {74 return new string[0];75 }76 // Strip the @ from the tagname (as it is provided now by the parser)77 return tags.Select(t => t.Name.Substring(1)).ToArray();78 }79 /// <summary>80 /// Converts the provided <see cref="Gherkin.Ast.Scenario"/> instance into a <see cref="Augurk.Entities.Scenario"/> instance.81 /// </summary>82 /// <param name="scenario">The <see cref="Gherkin.Ast.Scenario"/> instance that should be converted.</param>83 /// <param name="dialect">The <see cref="GherkinDialect"/> that is being used for this feature.</param>84 /// <returns>The converted <see cref="Augurk.Entities.Scenario"/> instance.</returns>85 public static Scenario ConvertToScenario(this Gherkin.Ast.Scenario scenario, GherkinDialect dialect)86 {87 if (scenario == null)88 {89 throw new ArgumentNullException(nameof(scenario));90 }91 return new Scenario()92 {93 Title = scenario.Name,94 Description = scenario.Description,95 Tags = scenario.Tags.ConvertToStrings(),96 Steps = scenario.Steps.ConvertToSteps(dialect),97 ExampleSets = scenario.Examples.ConvertToExampleSets(),98 Location = scenario.Location.ConvertToSourceLocation()99 };100 }101 /// <summary>102 /// Converts the provided <see cref=" Gherkin.Ast.Background"/> instance into a <see cref="Augurk.Entities.Background"/> instance.103 /// </summary>104 /// <param name="background">The <see cref=" Gherkin.Ast.Background"/> instance that should be converted.</param>105 /// <param name="dialect">The <see cref="GherkinDialect"/> that is being used for this feature.</param>106 /// <returns>The converted <see cref="Augurk.Entities.Background"/> instance.</returns>107 public static Background ConvertToBackground(this Gherkin.Ast.Background background, GherkinDialect dialect)108 {109 if (background == null)110 {111 return null;112 }113 return new Background()114 {115 Title = background.Name,116 Keyword = background.Keyword,117 Steps = background.Steps.ConvertToSteps(dialect),118 Location = background.Location.ConvertToSourceLocation()119 };120 }121 /// <summary>122 /// Converts the provided <see cref="Gherkin.Ast.Examples"/> instances into an enumerable collection of <see cref="Augurk.Entities.ExampleSet"/> instances.123 /// </summary>124 /// <param name="examples">The <see cref="Gherkin.Ast.Examples"/> instances that should be converted.</param>125 /// <returns>An enumerable collection of <see cref="Augurk.Entities.ExampleSet"/> instances.</returns>126 public static IEnumerable<ExampleSet> ConvertToExampleSets(this IEnumerable<Gherkin.Ast.Examples> examples)127 {128 if (examples == null)129 {130 throw new ArgumentNullException("examples");131 }132 return examples.Select(exampleSet => exampleSet.ConvertToExampleSet()).ToArray();133 }134 /// <summary>135 /// Converts the provided <see cref="Gherkin.Ast.Examples"/> instance into a<see cref="Augurk.Entities.ExampleSet"/> instance.136 /// </summary>137 /// <param name="examples">The <see cref="Gherkin.Ast.Examples"/> instance that should be converted.</param>138 /// <returns>The converted <see cref="Augurk.Entities.ExampleSet"/> instance.</returns>139 public static ExampleSet ConvertToExampleSet(this Gherkin.Ast.Examples examples)140 {141 if (examples == null)142 {143 throw new ArgumentNullException("exampleSet");144 }145 return new ExampleSet()146 {147 Title = examples.Name,148 Description = examples.Description,149 Keyword = examples.Keyword,150 Tags = examples.Tags.ConvertToStrings(),151 Columns = examples.TableHeader.Cells.Select(cell => cell.Value).ToArray(),152 Rows = examples.TableBody.Select(row => row.Cells.Select(cell => cell.Value).ToArray()).ToArray(),153 Location = examples.Location.ConvertToSourceLocation()154 };155 }156 /// <summary>157 /// Converts the provided <see cref="Gherkin.Ast.Step"/> instances into an enumerable collection of <see cref="Augurk.Entities.Step"/> instances.158 /// </summary>159 /// <param name="steps">The <see cref="Gherkin.Ast.Step"/> instances that should be converted.</param>160 /// <param name="dialect">The <see cref="GherkinDialect"/> that is being used for this feature.</param>161 /// <returns>An enumerable collection of <see cref="Augurk.Entities.Step"/> instances.</returns>162 public static IEnumerable<Step> ConvertToSteps(this IEnumerable<Gherkin.Ast.Step> steps, GherkinDialect dialect)163 {164 if (steps == null)165 {166 return new Step[0];167 }168 BlockKeyword? blockKeyword = null;169 var result = new List<Step>();170 foreach (var step in steps)171 {172 var convertedStep = step.ConvertToStep(dialect);173 if (convertedStep.StepKeyword != StepKeyword.And && convertedStep.StepKeyword != StepKeyword.But)174 {175 switch (convertedStep.StepKeyword)176 {177 case StepKeyword.Given:178 blockKeyword = BlockKeyword.Given;179 break;180 case StepKeyword.When:181 blockKeyword = BlockKeyword.When;182 break;183 case StepKeyword.Then:184 blockKeyword = BlockKeyword.Then;185 break;186 default:187 throw new NotSupportedException($"Unexpected step keyword {convertedStep.StepKeyword}.");188 }189 }190 if (blockKeyword == null)191 {192 throw new NotSupportedException($"Detected incorrect use of Gherkin syntax. Scenario cannot start with And or But ('{step.Keyword}').");193 }194 convertedStep.BlockKeyword = blockKeyword.Value;195 result.Add(convertedStep);196 }197 return result;198 }199 /// <summary>200 /// Converts the provided <see cref="Gherkin.Ast.Step"/> instance into a <see cref="Augurk.Entities.Step"/> instance.201 /// </summary>202 /// <param name="step">The <see cref="Gherkin.Ast.Step"/> instance that should be converted.</param>203 /// <param name="blockKeyword">Current block of keywords being converted.</param>204 /// <param name="dialect">The <see cref="GherkinDialect"/> that is being used for this feature.</param>205 /// <returns>The converted <see cref="Augurk.Entities.Step"/> instance.</returns>206 public static Step ConvertToStep(this Gherkin.Ast.Step step, GherkinDialect dialect)207 {208 if (step == null)209 {210 throw new ArgumentNullException("step");211 }212 return new Step()213 {214 StepKeyword = step.Keyword.ConvertToStepKeyword(dialect),215 Keyword = step.Keyword,216 Content = step.Text,217 TableArgument = step.Argument.ConvertToTable(),218 Location = step.Location.ConvertToSourceLocation()219 };220 }221 /// <summary>222 /// Converts the provided <see cref="Gherkin.StepKeyword"/> into a <see cref="Augurk.Entities.StepKeyword"/>.223 /// </summary>224 /// <param name="stepKeyword">The <see cref="Gherkin.StepKeyword"/> that should be converted.</param>225 /// <param name="dialect">The <see cref="GherkinDialect"/> that is being used for this feature.</param>226 /// <returns>The converted <see cref="Augurk.Entities.StepKeyword"/>.</returns>227 public static StepKeyword ConvertToStepKeyword(this string stepKeyword, GherkinDialect dialect)228 {229 if (dialect.AndStepKeywords.Contains(stepKeyword))230 {231 return StepKeyword.And;232 }233 else if (dialect.ButStepKeywords.Contains(stepKeyword))234 {235 return StepKeyword.But;236 }237 else if (dialect.GivenStepKeywords.Contains(stepKeyword))238 {239 return StepKeyword.Given;240 }241 else if (dialect.WhenStepKeywords.Contains(stepKeyword))242 {243 return StepKeyword.When;244 }245 else if (dialect.ThenStepKeywords.Contains(stepKeyword))246 {247 return StepKeyword.Then;248 }249 else250 {251 return StepKeyword.None;252 }253 }254 /// <summary>255 /// Converts the provided <see cref="Gherkin.Ast.StepArgument"/> instance into a <see cref="Augurk.Entities.Table"/> instance.256 /// </summary>257 /// <param name="table">The <see cref="Gherkin.Ast.StepArgument"/> instance that should be converted.</param>258 /// <returns>The converted <see cref="Augurk.Entities.Table"/> instanc, or <c>null</c> if the provided <paramref name="argument"/> is not a <see cref="Gherkin.Ast.DataTable"/>.</returns>259 public static Table ConvertToTable(this Gherkin.Ast.StepArgument argument)260 {261 Gherkin.Ast.DataTable table = argument as Gherkin.Ast.DataTable;262 if (table == null)263 {264 return null;265 }266 return new Table267 {268 Columns = table.Rows.FirstOrDefault()?.Cells.Select(cell => cell.Value).ToArray(),269 // Skip the first row as those are the headers270 Rows = table.Rows.Skip(1).Select(row => row.Cells.Select(cell => cell.Value).ToArray()).ToArray(),271 Location = table.Location.ConvertToSourceLocation()272 };273 }274 }275}...
DeveroomGherkinParser.cs
Source:DeveroomGherkinParser.cs
...95 });96 }97 protected override int MatchToken(int state, Token token, ParserContext context)98 {99 _recordStateForLine?.Invoke(token.Location.Line, state);100 try101 {102 return base.MatchToken(state, token, context);103 }104 catch (InvalidOperationException ex)105 {106 _monitoringService.MonitorError(ex);107 throw;108 }109 }110 }111 public DeveroomGherkinDocument GetResult()112 {113 return _astBuilder.GetResult();114 }115 #region Semantic Errors116 protected virtual void CheckSemanticErrors(DeveroomGherkinDocument specFlowDocument)117 {118 var errors = new List<ParserException>();119 errors.AddRange(((DeveroomGherkinAstBuilder)_astBuilder).Errors);120 if (specFlowDocument?.Feature != null)121 {122 CheckForDuplicateScenarios(specFlowDocument.Feature, errors);123 CheckForDuplicateExamples(specFlowDocument.Feature, errors);124 CheckForMissingExamples(specFlowDocument.Feature, errors);125 CheckForRulesPreSpecFlow31(specFlowDocument.Feature, errors);126 }127 // collect128 if (errors.Count == 1)129 throw errors[0];130 if (errors.Count > 1)131 throw new CompositeParserException(errors.ToArray());132 }133 private void CheckForRulesPreSpecFlow31(Feature feature, List<ParserException> errors)134 {135 //TODO: Show error when Rule keyword is used in SpecFlow v3.0 or earlier136 }137 private void CheckForDuplicateScenarios(Feature feature, List<ParserException> errors)138 {139 // duplicate scenario name140 var duplicatedScenarios = feature.FlattenScenarioDefinitions().GroupBy(sd => sd.Name, sd => sd).Where(g => g.Count() > 1).ToArray();141 errors.AddRange(142 duplicatedScenarios.Select(g =>143 new SemanticParserException(144 $"Feature file already contains a scenario with name '{g.Key}'",145 g.ElementAt(1).Location)));146 }147 private void CheckForDuplicateExamples(Feature feature, List<ParserException> errors)148 {149 foreach (var scenarioOutline in feature.FlattenScenarioDefinitions().OfType<ScenarioOutline>())150 {151 var duplicateExamples = scenarioOutline.Examples152 .Where(e => !String.IsNullOrWhiteSpace(e.Name))153 .Where(e => e.Tags.All(t => t.Name != "ignore"))154 .GroupBy(e => e.Name, e => e).Where(g => g.Count() > 1);155 foreach (var duplicateExample in duplicateExamples)156 {157 var message = $"Scenario Outline '{scenarioOutline.Name}' already contains an example with name '{duplicateExample.Key}'";158 var semanticParserException = new SemanticParserException(message, duplicateExample.ElementAt(1).Location);159 errors.Add(semanticParserException);160 }161 }162 }163 private void CheckForMissingExamples(Feature feature, List<ParserException> errors)164 {165 foreach (var scenarioOutline in feature.FlattenScenarioDefinitions().OfType<ScenarioOutline>())166 {167 if (DoesntHavePopulatedExamples(scenarioOutline))168 {169 var message = $"Scenario Outline '{scenarioOutline.Name}' has no examples defined";170 var semanticParserException = new SemanticParserException(message, scenarioOutline.Location);171 errors.Add(semanticParserException);172 }173 }174 }175 private static bool DoesntHavePopulatedExamples(ScenarioOutline scenarioOutline)176 {177 return !scenarioOutline.Examples.Any() || scenarioOutline.Examples.Any(x => x.TableBody == null || !x.TableBody.Any());178 }179 #endregion180 #region Expected tokens181 class NullAstBuilder : IAstBuilder<DeveroomGherkinDocument>182 {183 public void Build(Token token)184 {185 }186 public void StartRule(RuleType ruleType)187 {188 }189 public void EndRule(RuleType ruleType)190 {191 }192 public DeveroomGherkinDocument GetResult()193 {194 return null;195 }196 public void Reset()197 {198 }199 }200 class AllFalseTokenMatcher : ITokenMatcher201 {202 public bool Match_EOF(Token token)203 {204 return false;205 }206 public bool Match_Empty(Token token)207 {208 return false;209 }210 public bool Match_Comment(Token token)211 {212 return false;213 }214 public bool Match_TagLine(Token token)215 {216 return false;217 }218 public bool Match_FeatureLine(Token token)219 {220 return false;221 }222 public bool Match_RuleLine(Token token)223 {224 return false;225 }226 public bool Match_BackgroundLine(Token token)227 {228 return false;229 }230 public bool Match_ScenarioLine(Token token)231 {232 return false;233 }234 public bool Match_ExamplesLine(Token token)235 {236 return false;237 }238 public bool Match_StepLine(Token token)239 {240 return false;241 }242 public bool Match_DocStringSeparator(Token token)243 {244 return false;245 }246 public bool Match_TableRow(Token token)247 {248 return false;249 }250 public bool Match_Language(Token token)251 {252 return false;253 }254 public bool Match_Other(Token token)255 {256 return false;257 }258 public void Reset()259 {260 }261 }262 class NullTokenScanner : ITokenScanner263 {264 public Token Read()265 {266 return new Token(null, new Location());267 }268 }269 public static TokenType[] GetExpectedTokens(int state, IMonitoringService monitoringService)270 {271 var parser = new InternalParser(new NullAstBuilder(), null, monitoringService)272 {273 StopAtFirstError = true274 };275 try276 {277 parser.NullMatchToken(state, new Token(null, new Location()));278 }279 catch (UnexpectedEOFException ex)280 {281 return ex.ExpectedTokenTypes.Select(type => (TokenType)Enum.Parse(typeof(TokenType), type.TrimStart('#'))).ToArray();282 }283 return new TokenType[0];284 }285 #endregion286 }287}...
CompatibleAstConverter.cs
Source:CompatibleAstConverter.cs
...23 ConvertToCompatibleBackground(specFlowFeature.Background), 24 ConvertToCompatibleScenarios(specFlowFeature.ScenarioDefinitions), 25 ConvertToCompatibleComments(specFlowDocument.Comments))26 {27 FilePosition = ConvertToCompatibleFilePosition(specFlowFeature.Location),28 Language = specFlowFeature.Language,29 SourceFile = specFlowDocument.SourceFilePath30 };31 }32 private static Comment[] ConvertToCompatibleComments(IEnumerable<global::Gherkin.Ast.Comment> comments)33 {34 return comments.Select(ConvertToCompatibleComment).Where(c => c != null).ToArray();35 }36 private static Comment ConvertToCompatibleComment(global::Gherkin.Ast.Comment c)37 {38 var trimmedText = c.Text.TrimStart('#', ' ', '\t');39 if (trimmedText.Length == 0)40 return null;41 return new Comment(trimmedText, ConvertToCompatibleFilePosition(c.Location, c.Text.Length - trimmedText.Length));42 }43 private static Scenario[] ConvertToCompatibleScenarios(IEnumerable<Gherkin.Ast.ScenarioDefinition> scenarioDefinitions)44 {45 return scenarioDefinitions.Select(ConvertToCompatibleScenario).ToArray();46 }47 private static Scenario ConvertToCompatibleScenario(Gherkin.Ast.ScenarioDefinition sd)48 {49 var convertToCompatibleTags = ConvertToCompatibleTags(sd.GetTags());50 var result = sd is global::Gherkin.Ast.ScenarioOutline51 ? new ScenarioOutline(sd.Keyword, sd.Name, sd.Description, convertToCompatibleTags, ConvertToCompatibleSteps(sd.Steps), ConvertToCompatibleExamples(((global::Gherkin.Ast.ScenarioOutline)sd).Examples))52 : new Scenario(sd.Keyword, sd.Name, sd.Description, convertToCompatibleTags, ConvertToCompatibleSteps(sd.Steps));53 result.FilePosition = ConvertToCompatibleFilePosition(sd.Location);54 return result;55 }56 private static Examples ConvertToCompatibleExamples(IEnumerable<global::Gherkin.Ast.Examples> examples)57 {58 return new Examples(examples.Select(e => new ExampleSet(e.Keyword, e.Name, e.Description, ConvertToCompatibleTags(e.Tags), ConvertToCompatibleExamplesTable(e))).ToArray());59 }60 private static GherkinTable ConvertToCompatibleExamplesTable(global::Gherkin.Ast.Examples examples)61 {62 return new GherkinTable(ConvertToCompatibleRow(examples.TableHeader), examples.TableBody.Select(ConvertToCompatibleRow).ToArray());63 }64 private static GherkinTableRow ConvertToCompatibleRow(global::Gherkin.Ast.TableRow tableRow)65 {66 return new GherkinTableRow(tableRow.Cells.Select(c => new GherkinTableCell(c.Value)).ToArray())67 {68 FilePosition = ConvertToCompatibleFilePosition(tableRow.Location)69 };70 }71 private static ScenarioSteps ConvertToCompatibleSteps(IEnumerable<global::Gherkin.Ast.Step> steps)72 {73 return new ScenarioSteps(steps.Select(s => ConvertToCompatibleStep((SpecFlowStep)s)).ToArray());74 }75 private static ScenarioStep ConvertToCompatibleStep(SpecFlowStep step)76 {77 ScenarioStep result = null;78 if (step.StepKeyword == StepKeyword.Given)79 result = new Given {StepKeyword = step.StepKeyword };80 else if (step.StepKeyword == StepKeyword.When)81 result = new When {StepKeyword = step.StepKeyword };82 else if (step.StepKeyword == StepKeyword.Then)83 result = new Then {StepKeyword = step.StepKeyword };84 else if (step.StepKeyword == StepKeyword.And)85 result = new And { StepKeyword = step.StepKeyword };86 else if (step.StepKeyword == StepKeyword.But)87 result = new But {StepKeyword = step.StepKeyword };88 if (result == null)89 throw new NotSupportedException();90 result.Keyword = step.Keyword;91 result.Text = step.Text;92 result.ScenarioBlock = step.ScenarioBlock;93 result.MultiLineTextArgument = step.Argument is global::Gherkin.Ast.DocString ? ((global::Gherkin.Ast.DocString) step.Argument).Content : null;94 result.TableArg = step.Argument is global::Gherkin.Ast.DataTable ? ConvertToCompatibleTable(((global::Gherkin.Ast.DataTable) step.Argument).Rows) : null;95 result.FilePosition = ConvertToCompatibleFilePosition(step.Location);96 return result;97 }98 private static FilePosition ConvertToCompatibleFilePosition(global::Gherkin.Ast.Location location, int columnDiff = 0)99 {100 if (location == null)101 return null;102 return new FilePosition(location.Line, location.Column + columnDiff);103 }104 private static GherkinTable ConvertToCompatibleTable(IEnumerable<global::Gherkin.Ast.TableRow> rows)105 {106 var rowsArray = rows.ToArray();107 return new GherkinTable(ConvertToCompatibleRow(rowsArray.First()), rowsArray.Skip(1).Select(ConvertToCompatibleRow).ToArray());108 }109 private static Background ConvertToCompatibleBackground(global::Gherkin.Ast.Background background)110 {111 if (background == null)112 return null;113 return new Background(background.Keyword, background.Name, background.Description, ConvertToCompatibleSteps(background.Steps))114 {115 FilePosition = ConvertToCompatibleFilePosition(background.Location)116 };117 }118 private static Tags ConvertToCompatibleTags(IEnumerable<global::Gherkin.Ast.Tag> tags)119 {120 if (tags == null || !tags.Any())121 return null;122 return new Tags(tags.Select(t => new Tag(t.GetNameWithoutAt())).ToArray());123 }124 }125}...
AstEventConverter.cs
Source:AstEventConverter.cs
...5using Gherkin.Events.Args.Ast;6using Comment = Gherkin.Events.Args.Ast.Comment;7using Examples = Gherkin.Events.Args.Ast.Examples;8using Feature = Gherkin.Events.Args.Ast.Feature;9using Location = Gherkin.Events.Args.Ast.Location;10using Rule = Gherkin.Events.Args.Ast.Rule;11using Step = Gherkin.Events.Args.Ast.Step;12using StepsContainer = Gherkin.Events.Args.Ast.StepsContainer;13namespace Gherkin.Stream.Converter14{15 public class AstEventConverter16 {17 public GherkinDocumentEventArgs ConvertGherkinDocumentToEventArgs(GherkinDocument gherkinDocument, string sourceEventUri)18 {19 return new GherkinDocumentEventArgs()20 {21 Uri = sourceEventUri,22 Feature = ConvertFeature(gherkinDocument),23 Comments = ConvertComments(gherkinDocument)24 };25 }26 private IReadOnlyCollection<Comment> ConvertComments(GherkinDocument gherkinDocument)27 {28 return gherkinDocument.Comments.Select(c =>29 new Comment()30 {31 Text = c.Text,32 Location = ConvertLocation(c.Location)33 }).ToReadOnlyCollection();34 }35 private Feature ConvertFeature(GherkinDocument gherkinDocument)36 {37 var feature = gherkinDocument.Feature;38 if (feature == null)39 {40 return null;41 }42 return new Feature()43 {44 Name = feature.Name == string.Empty ? null : feature.Name,45 Keyword = feature.Keyword,46 Language = feature.Language,47 Location = ConvertLocation(feature.Location),48 Children = feature.Children.Select(ConvertToChildren).ToReadOnlyCollection()49 };50 }51 private static Location ConvertLocation(Ast.Location location)52 {53 return new Location(location.Column, location.Line);54 }55 private Children ConvertToChildren(IHasLocation hasLocation)56 {57 switch (hasLocation)58 {59 case Background background:60 return new Children()61 {62 Background = new StepsContainer()63 {64 Location = ConvertLocation(background.Location),65 Name = background.Name == string.Empty ? null : background.Name,66 Keyword = background.Keyword,67 Steps = background.Steps.Select(s => ConvertStep(s)).ToList()68 }69 };70 case Scenario scenario:71 return new Children()72 {73 Scenario = new StepsContainer()74 {75 Keyword = scenario.Keyword,76 Location = ConvertLocation(scenario.Location),77 Name = scenario.Name == string.Empty ? null : scenario.Name,78 Steps = scenario.Steps.Select(s => ConvertStep(s)).ToList(),79 Examples = scenario.Examples.Select(ConvertExamples).ToReadOnlyCollection(),80 }81 };82 case Ast.Rule rule:83 {84 return new Children()85 {86 Rule = new Rule()87 {88 Name = rule.Name == string.Empty ? null : rule.Name,89 Keyword = rule.Keyword,90 Children = rule.Children.Select(ConvertToChildren).ToReadOnlyCollection(),91 Location = ConvertLocation(rule.Location)92 }93 };94 }95 default:96 throw new NotImplementedException();97 }98 }99 private Examples ConvertExamples(Ast.Examples examples)100 {101 return new Examples()102 {103 Name = examples.Name == string.Empty ? null : examples.Name,104 Keyword = examples.Keyword,105 Description = examples.Description,106 Location = ConvertLocation(examples.Location),107 TableHeader = ConvertTableHeader(examples),108 TableBody = ConvertToTableBody(examples)109 };110 }111 private IReadOnlyCollection<TableBody> ConvertToTableBody(Ast.Examples examples)112 {113 if (examples.TableBody == null)114 return new List<TableBody>();115 return examples.TableBody.Select(b =>116 new TableBody()117 {118 Location = ConvertLocation(b.Location),119 Cells = b.Cells.Select(ConvertCell).ToReadOnlyCollection()120 }).ToReadOnlyCollection();121 }122 private TableHeader ConvertTableHeader(Ast.Examples examples)123 {124 if (examples.TableHeader == null)125 return null;126 return new TableHeader()127 {128 Location = ConvertLocation(examples.TableHeader.Location),129 Cells = examples.TableHeader.Cells.Select(ConvertCell).ToReadOnlyCollection()130 };131 }132 private Cell ConvertCell(TableCell c)133 {134 return new Cell()135 {136 Value = c.Value,137 Location = ConvertLocation(c.Location)138 };139 }140 private Step ConvertStep(Ast.Step step)141 {142 return new Step()143 {144 Keyword = step.Keyword,145 Text = step.Text,146 Location = ConvertLocation(step.Location)147 };148 }149 }150}...
GherkinScenarioOutlineExtensions.cs
Source:GherkinScenarioOutlineExtensions.cs
...32 scenarioSteps.Add(scenarioStep);33 }34 return new global::Gherkin.Ast.Scenario(35 @this.Tags?.ToArray(),36 @this.Location,37 @this.Keyword,38 @this.Name,39 @this.Description,40 scenarioSteps.ToArray());41 }42 private static global::Gherkin.Ast.Step DigestExampleValuesIntoStep(global::Gherkin.Ast.ScenarioOutline @this, string exampleName, int exampleRowIndex, Dictionary<string, string> rowValues, global::Gherkin.Ast.Step outlineStep)43 {44 string matchEvaluator(Match match)45 {46 var placeholderKey = match.Groups[1].Value;47 if (!rowValues.ContainsKey(placeholderKey))48 throw new InvalidOperationException($"Examples table did not provide value for `{placeholderKey}`. Scenario outline: `{@this.Name}`. Examples: `{exampleName}`. Row index: {exampleRowIndex}.");49 var placeholderValue = rowValues[placeholderKey];50 return placeholderValue;51 }52 var stepText = _placeholderRegex.Replace(outlineStep.Text, matchEvaluator);53 var stepArgument = outlineStep.Argument;54 if (stepArgument is DataTable)55 {56 var processedHeaderRow = false;57 var digestedRows = new List<TableRow>();58 59 foreach(var row in ((DataTable)stepArgument).Rows)60 {61 if (!processedHeaderRow)62 {63 digestedRows.Add(row);64 processedHeaderRow = true;65 }66 else67 {68 var digestedCells = row.Cells.Select(r => new TableCell(r.Location, _placeholderRegex.Replace(r.Value, matchEvaluator)));69 digestedRows.Add(new TableRow(row.Location, digestedCells.ToArray()));70 }71 }72 stepArgument = new DataTable(digestedRows.ToArray());73 }74 var scenarioStep = new global::Gherkin.Ast.Step(75 outlineStep.Location,76 outlineStep.Keyword,77 stepText,78 stepArgument);79 return scenarioStep;80 }81 private static Dictionary<string, string> GetExampleRowValues(global::Gherkin.Ast.Examples examples, List<global::Gherkin.Ast.TableCell> exampleRowCells)82 {83 var rowValues = new Dictionary<string, string>();84 var headerCells = examples.TableHeader.Cells.ToList();85 for (int index = 0; index < headerCells.Count; index++)86 {87 rowValues.Add(headerCells[index].Value, exampleRowCells[index].Value);88 }89 return rowValues;...
DeveroomGherkinAstBuilder.cs
Source:DeveroomGherkinAstBuilder.cs
...23 base.Build(token);24 if (token.MatchedType == TokenType.Language)25 {26 // the language token should be handled as comment as well27 var commentToken = new Token(token.Line, new Location(token.Location.Line, 1))28 {29 MatchedType = TokenType.Comment,30 MatchedText = token.Line.GetLineText(),31 };32 base.Build(commentToken);33 }34 }35 private static StepKeyword GetStepKeyword(GherkinDialect dialect, string stepKeyword)36 {37 if (dialect.AndStepKeywords.Contains(stepKeyword)) // we need to check "And" first, as the '*' is also part of the Given, When and Then keywords38 return StepKeyword.And;39 if (dialect.GivenStepKeywords.Contains(stepKeyword))40 return StepKeyword.Given;41 if (dialect.WhenStepKeywords.Contains(stepKeyword))42 return StepKeyword.When;43 if (dialect.ThenStepKeywords.Contains(stepKeyword))44 return StepKeyword.Then;45 if (dialect.ButStepKeywords.Contains(stepKeyword))46 return StepKeyword.But;47 return StepKeyword.And;48 }49 protected override Step CreateStep(Location location, string keyword, string text, StepArgument argument, AstNode node)50 {51 var token = node.GetToken(TokenType.StepLine);52 var stepKeyword = GetStepKeyword(token.MatchedGherkinDialect, keyword);53 _scenarioBlock = stepKeyword.ToScenarioBlock() ?? _scenarioBlock;54 return new DeveroomGherkinStep(location, keyword, text, argument, stepKeyword, _scenarioBlock);55 }56 private void ResetBlock()57 {58 _scenarioBlock = ScenarioBlock.Given;59 }60 protected override GherkinDocument CreateGherkinDocument(Feature feature, Comment[] gherkinDocumentComments, AstNode node)61 {62 return new DeveroomGherkinDocument(feature, gherkinDocumentComments, _sourceFilePath, _documentDialectProvider(), _statesForLines);63 }64 protected override Scenario CreateScenario(Tag[] tags, Location location, string keyword, string name, string description, Step[] steps, Examples[] examples, AstNode node)65 {66 ResetBlock();67 if (examples == null || examples.Length == 0)68 {69 return new SingleScenario(tags, location, keyword, name, description, steps, examples);70 }71 else72 {73 return new ScenarioOutline(tags, location, keyword, name, description, steps, examples);74 }75 }76 protected override Background CreateBackground(Location location, string keyword, string name, string description, Step[] steps, AstNode node)77 {78 ResetBlock();79 return base.CreateBackground(location, keyword, name, description, steps, node);80 }81 protected override void HandleAstError(string message, Location location)82 {83 _errors.Add(new SemanticParserException(message, location));84 }85 public void RecordStateForLine(int line, int state)86 {87 if (line > 0)88 line--; // convert to 0 based89 if (_statesForLines.Count > line)90 return;91 if (_statesForLines.Count < line)92 {93 var lastState = _statesForLines.Any() ? _statesForLines.Last() : -1;94 while (_statesForLines.Count < line)95 _statesForLines.Add(lastState);...
GherkInspectorExample.cs
Source:GherkInspectorExample.cs
...4 using System.Collections.Generic;5 using System.Text;6 public class GherkInspectorExample7 {8 public GherkInspectorLocation Location { get; private set; }9 public GherkInspectorTableRow TableHeader { get; private set; }10 public IEnumerable<GherkInspectorTableRow> TableBody { get; private set; }11 public GherkInspectorExample(GherkInspectorLocation location, GherkInspectorTableRow headerRow)12 {13 Location = location;14 TableHeader = headerRow;15 TableBody = new List<GherkInspectorTableRow>();16 }17 }18 public class GherkInspectorTableRow19 {20 public GherkInspectorLocation Location { get; private set; }21 public IEnumerable<GherkInspectorTableCell> Cells { get; private set; }22 public GherkInspectorTableRow(GherkInspectorLocation location, List<GherkInspectorTableCell> cells)23 {24 Location = location;25 Cells = cells;26 }27 }28 public class GherkInspectorTableCell29 {30 public GherkInspectorLocation Location { get; private set; }31 public string Value { get; private set; }32 public GherkInspectorTableCell(GherkInspectorLocation location, string value)33 {34 Location = location;35 Value = value;36 }37 }38 /*39 * example40{Gherkin.Ast.Examples}41 Description: null42 Keyword: "Examples"43 Location: {Gherkin.Ast.Location}44 Name: ""45 TableBody: {Gherkin.Ast.TableRow[1]}46 TableHeader: {Gherkin.Ast.TableRow}47 Tags: {Gherkin.Ast.Tag[0]}48example.TableHeader49{Gherkin.Ast.TableRow}50 Cells: {Gherkin.Ast.TableCell[1]}51 Location: {Gherkin.Ast.Location}52example.TableBody53{Gherkin.Ast.TableRow[1]}54 [0]: {Gherkin.Ast.TableRow}55 */56}
GherkinScenarioDefinitionTests.cs
Source:GherkinScenarioDefinitionTests.cs
...20 var backgroundSteps = new Gherkin.Ast.Step[] { new Gherkin.Ast.Step(null, null, "background", null) };21 var background = new Gherkin.Ast.Background(null, null, null, null, backgroundSteps);22 var modified = scenario.ApplyBackground(background);23 24 Assert.Equal(scenario.Location, modified.Location);25 Assert.Equal(scenario.Keyword, modified.Keyword);26 Assert.Equal(scenario.Name, modified.Name);27 Assert.Equal(scenario.Description, modified.Description);28 29 Assert.Equal(2, modified.Steps.Count());30 Assert.Equal("background", modified.Steps.ElementAt(0).Text);31 Assert.Equal("step", modified.Steps.ElementAt(1).Text);32 } 33 private static Gherkin.Ast.Scenario CreateTestScenario()34 {35 var tags = new Gherkin.Ast.Tag[] { new Gherkin.Ast.Tag(null, "test") };36 var location = new Gherkin.Ast.Location(1, 1);37 var steps = new Gherkin.Ast.Step[] { new Gherkin.Ast.Step(null, null, "step", null) };38 return new Gherkin.Ast.Scenario(tags, location, "keyword", "name", "description", steps); 39 }40 }41}...
Location
Using AI Code Generation
1using Gherkin.Ast;2using Gherkin.Ast;3using Gherkin.Ast;4using Gherkin.Ast;5using Gherkin.Ast;6using Gherkin.Ast;7using Gherkin.Ast;8using Gherkin.Ast;9using Gherkin.Ast;10using System;11using System.Collections.Generic;12using System.Linq;13using System.Text;14using System.Threading.Tasks;15{16 {17 static void Main(string[] args)18 {19 var parser = new Gherkin.Parser();20 var gherkinDocument = parser.Parse(@"C:\Users\Arun\Documents\Visual Studio 2015\Projects\GherkinDemo\GherkinDemo\GherkinDemo\Features\GherkinDemo.feature");21 var feature = gherkinDocument.Feature;22 Console.WriteLine("Feature Name: " + feature.Name);23 Console.WriteLine("Feature Description: " + feature.Description);24 Console.WriteLine("Feature Tags: " + feature.Tags);25 Console.WriteLine("Feature Location: " + feature.Location);26 Console.WriteLine("Feature Children: " + feature.Children);27 Console.WriteLine("Feature Language: " + feature.Language);28 Console.WriteLine("Feature Keyword: " + feature.Keyword);29 Console.WriteLine("Feature Comments: " + feature.Comments);30 Console.WriteLine("Feature Background: " +
Location
Using AI Code Generation
1package com.cucumber;2import java.io.File;3import java.io.IOException;4import java.util.List;5import org.junit.Assert;6import org.openqa.selenium.By;7import org.openqa.selenium.WebDriver;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.chrome.ChromeDriver;10import cucumber.api.DataTable;11import cucumber.api.java.en.Given;12import cucumber.api.java.en.Then;13import cucumber.api.java.en.When;14import gherkin.Ast.Feature;15import gherkin.Ast.Scenario;16import gherkin.Ast.Step;17import gherkin.Parser;18import gherkin.TokenMatcher;19import gherkin.ast.DataTable;20import gherkin.ast.TableRow;21public class StepDefinition {22 WebDriver driver;23 @Given("^user is already on Login Page$")24 public void user_is_already_on_Login_Page() {25 System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dell\\Downloads\\chromedriver_win32\\chromedriver.exe");26 driver = new ChromeDriver();27 }28 @When("^title of login page is Free CRM$")29 public void title_of_login_page_is_Free_CRM() {30 String title = driver.getTitle();31 System.out.println(title);32 Assert.assertEquals("Free CRM software in the cloud powers sales and customer service", title);33 }34 @Then("^user enters username and password$")35 public void user_enters_username_and_password(DataTable credentials) {36 List<List<String>> data = credentials.raw();37 driver.findElement(By.name("username")).sendKeys(data.get(0).get(0));38 driver.findElement(By.name("password")).sendKeys(data.get(0).get(1));39 }40 @Then("^user clicks on login button$")41 public void user_clicks_on_login_button() {42 JavascriptExecutor js = (JavascriptExecutor)driver;43 js.executeScript("
Location
Using AI Code Generation
1using Gherkin;2using Gherkin.Ast;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 static void Main(string[] args)11 {12 var parser = new Parser();13 var feature = parser.Parse("Feature: My Feature");14 Console.WriteLine(feature.Location.Column);15 Console.WriteLine(feature.Location.Line);16 Console.ReadLine();17 }18 }19}20Error 1 The type or namespace name 'Gherkin' could not be found (are you missing a using directive or an assembly reference?) C:\Users\Bhavesh\Documents\Visual Studio 2015\Projects\GherkinTest\GherkinTest\Program.cs 6 7 GherkinTest
Location
Using AI Code Generation
1using Gherkin.Ast;2using Gherkin;3using Gherkin.Ast;4using Gherkin;5using Gherkin.Ast;6using Gherkin;7using Gherkin.Ast;8using Gherkin;9using Gherkin.Ast;10using Gherkin;11using Gherkin.Ast;12using Gherkin;13using Gherkin.Ast;14using Gherkin;15using Gherkin.Ast;16using Gherkin;17using Gherkin.Ast;18using Gherkin;19using Gherkin.Ast;20using Gherkin;21using Gherkin.Ast;22using Gherkin;23using Gherkin.Ast;24using Gherkin;25using Gherkin.Ast;26using Gherkin;27using Gherkin.Ast;28using Gherkin;
Location
Using AI Code Generation
1using Gherkin.Ast;2using TechTalk.SpecFlow;3using TechTalk.SpecFlow.Bindings;4using TechTalk.SpecFlow.Bindings.Reflection;5using TechTalk.SpecFlow.Tracing;6using TechTalk.SpecFlow.UnitTestProvider;7using TechTalk.SpecFlow.Utils;8using TechTalk.SpecFlow.VsIntegration.Implementation.StepSuggestions;9using TechTalk.SpecFlow.VsIntegration.Implementation.Tracing;10using TechTalk.SpecFlow.VsIntegration.Implementation.Utils;11using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Async;12using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Reflection;13using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Reflection.Compat;14using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Reflection.TypeResolver;15using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Reflection.TypeResolver.Compat;16using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Reflection.TypeResolver.Compat.Conversion;17using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Reflection.TypeResolver.Compat.TypeResolution;18using TechTalk.SpecFlow.VsIntegration.Implementation.Utils.Reflection.TypeResolver.Compat.TypeResolution.TypeResolvers;
Location
Using AI Code Generation
1{2 {3 public MyLocation(int line, int column) : base(line, column)4 {5 }6 {7 get { return base.Line; }8 }9 {10 get { return base.Column; }11 }12 }13}14{15{16public MyLocation(int line, int column) : base(line, column)17{18}19{20get { return base.Line; }21}22{23get { return base.Column; }24}25}26}27{28{29public MyLocation(int line, int column) : base(line, column)30{31}32{33get { return base.Line; }34}
Location
Using AI Code Generation
1var parser = new Parser();2var feature = parser.Parse(featureFile);3{4 public int Line { get; set; }5 public int Column { get; set; }6}7{8 public int Line { get; set; }9 public int Column { get; set; }10}11using Gherkin.Ast;12{13 public int Line { get; set; }14 public int Column { get; set; }15}16using Gherkin.Ast;17{18 public int Line { get; set; }19 public int Column { get; set; }20}21Error CS0535 'Location' does not implement interface member 'IGherkinFormatter.WriteTo(IGherkinFormatterContext)'22using Gherkin.Ast;23{24 public int Line { get; set; }25 public int Column { get; set; }26}27Error CS0535 'Location' does not implement interface member 'IGherkinFormatter.WriteTo(IGherkinFormatterContext)'
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!!