Best Gherkin-dotnet code snippet using Gherkin.Ast.Rule
DeveroomTagParser.cs
Source:DeveroomTagParser.cs
...84 foreach (var block in feature.Children)85 {86 if (block is StepsContainer stepsContainer)87 AddScenarioDefinitionBlockTag(fileSnapshot, bindingRegistry, stepsContainer, featureTag);88 else if (block is Rule rule)89 AddRuleBlockTag(fileSnapshot, bindingRegistry, rule, featureTag);90 }91 return featureTag;92 }93 private void AddRuleBlockTag(ITextSnapshot fileSnapshot, ProjectBindingRegistry bindingRegistry, Rule rule, DeveroomTag featureTag)94 {95 var lastStepsContainer = rule.StepsContainers().LastOrDefault();96 var lastLine = lastStepsContainer != null ? 97 GetScenarioDefinitionLastLine(lastStepsContainer) :98 rule.Location.Line;99 var ruleTag = CreateDefinitionBlockTag(rule,100 DeveroomTagTypes.RuleBlock, fileSnapshot,101 lastLine, featureTag);102 foreach (var stepsContainer in rule.StepsContainers())103 {104 AddScenarioDefinitionBlockTag(fileSnapshot, bindingRegistry, stepsContainer, ruleTag);105 }106 }107 private void AddScenarioDefinitionBlockTag(ITextSnapshot fileSnapshot, ProjectBindingRegistry bindingRegistry,108 StepsContainer scenarioDefinition, DeveroomTag parentTag)109 {110 var scenarioDefinitionTag = CreateDefinitionBlockTag(scenarioDefinition,111 DeveroomTagTypes.ScenarioDefinitionBlock, fileSnapshot,112 GetScenarioDefinitionLastLine(scenarioDefinition), parentTag);113 foreach (var step in scenarioDefinition.Steps)114 {...
AstBuilder.cs
Source:AstBuilder.cs
...1819 public void Reset()20 {21 stack.Clear();22 stack.Push(new AstNode(RuleType.None));23 comments.Clear();24 }2526 public void Build(Token token)27 {28 if (token.MatchedType == TokenType.Comment)29 {30 comments.Add(CreateComment(GetLocation(token), token.MatchedText));31 }32 else33 {34 CurrentNode.Add((RuleType) token.MatchedType, token);35 }36 }3738 public void StartRule(RuleType ruleType)39 {40 stack.Push(new AstNode(ruleType));41 }4243 public void EndRule(RuleType ruleType)44 {45 var node = stack.Pop();46 object transformedNode = GetTransformedNode(node);47 CurrentNode.Add(node.RuleType, transformedNode);48 }4950 public T GetResult()51 {52 return CurrentNode.GetSingle<T>(RuleType.GherkinDocument);53 }5455 private object GetTransformedNode(AstNode node)56 {57 switch (node.RuleType)58 {59 case RuleType.Step:60 {61 var stepLine = node.GetToken(TokenType.StepLine);62 var stepArg = node.GetSingle<StepArgument>(RuleType.DataTable) ??63 node.GetSingle<StepArgument>(RuleType.DocString) ??64 null; // empty arg65 return CreateStep(GetLocation(stepLine), stepLine.MatchedKeyword, stepLine.MatchedText, stepArg, node);66 }67 case RuleType.DocString:68 {69 var separatorToken = node.GetTokens(TokenType.DocStringSeparator).First();70 var contentType = separatorToken.MatchedText.Length == 0 ? null : separatorToken.MatchedText;71 var lineTokens = node.GetTokens(TokenType.Other);72 var content = string.Join(Environment.NewLine, lineTokens.Select(lt => lt.MatchedText));7374 return CreateDocString(GetLocation(separatorToken), contentType, content, node);75 }76 case RuleType.DataTable:77 {78 var rows = GetTableRows(node);79 return CreateDataTable(rows, node);80 }81 case RuleType.Background:82 {83 var backgroundLine = node.GetToken(TokenType.BackgroundLine);84 var description = GetDescription(node);85 var steps = GetSteps(node);86 return CreateBackground(GetLocation(backgroundLine), backgroundLine.MatchedKeyword, backgroundLine.MatchedText, description, steps, node);87 }88 case RuleType.Scenario_Definition:89 {90 var tags = GetTags(node);9192 var scenarioNode = node.GetSingle<AstNode>(RuleType.Scenario);93 if (scenarioNode != null)94 {95 var scenarioLine = scenarioNode.GetToken(TokenType.ScenarioLine);9697 var description = GetDescription(scenarioNode);98 var steps = GetSteps(scenarioNode);99100 return CreateScenario(tags, GetLocation(scenarioLine), scenarioLine.MatchedKeyword, scenarioLine.MatchedText, description, steps, node);101 }102 else103 {104 var scenarioOutlineNode = node.GetSingle<AstNode>(RuleType.ScenarioOutline);105 if (scenarioOutlineNode == null)106 throw new InvalidOperationException("Internal gramar error");107 var scenarioOutlineLine = scenarioOutlineNode.GetToken(TokenType.ScenarioOutlineLine);108109 var description = GetDescription(scenarioOutlineNode);110 var steps = GetSteps(scenarioOutlineNode);111 var examples = scenarioOutlineNode.GetItems<Examples>(RuleType.Examples_Definition).ToArray();112113 return CreateScenarioOutline(tags, GetLocation(scenarioOutlineLine), scenarioOutlineLine.MatchedKeyword, scenarioOutlineLine.MatchedText, description, steps, examples, node);114 }115 }116 case RuleType.Examples_Definition:117 {118 var tags = GetTags(node);119 var examplesNode = node.GetSingle<AstNode>(RuleType.Examples);120 var examplesLine = examplesNode.GetToken(TokenType.ExamplesLine);121 var description = GetDescription(examplesNode);122123 var allRows = examplesNode.GetSingle<TableRow[]>(RuleType.Examples_Table);124 var header = allRows != null ? allRows.First() : null;125 var rows = allRows != null ? allRows.Skip(1).ToArray() : null;126 return CreateExamples(tags, GetLocation(examplesLine), examplesLine.MatchedKeyword, examplesLine.MatchedText, description, header, rows, node);127 }128 case RuleType.Examples_Table:129 {130 return GetTableRows(node);131 }132 case RuleType.Description:133 {134 var lineTokens = node.GetTokens(TokenType.Other);135136 // Trim trailing empty lines137 lineTokens = lineTokens.Reverse().SkipWhile(t => string.IsNullOrWhiteSpace(t.MatchedText)).Reverse();138139 return string.Join(Environment.NewLine, lineTokens.Select(lt => lt.MatchedText));140 }141 case RuleType.Feature:142 {143 var header = node.GetSingle<AstNode>(RuleType.Feature_Header);144 if(header == null) return null;145 var tags = GetTags(header);146 var featureLine = header.GetToken(TokenType.FeatureLine);147 if(featureLine == null) return null;148 var children = new List<ScenarioDefinition> ();149 var background = node.GetSingle<Background>(RuleType.Background);150 if (background != null) 151 {152 children.Add (background);153 }154 var childrenEnumerable = children.Concat(node.GetItems<ScenarioDefinition>(RuleType.Scenario_Definition));155 var description = GetDescription(header);156 if(featureLine.MatchedGherkinDialect == null) return null;157 var language = featureLine.MatchedGherkinDialect.Language;158159 return CreateFeature(tags, GetLocation(featureLine), language, featureLine.MatchedKeyword, featureLine.MatchedText, description, childrenEnumerable.ToArray(), node);160 }161 case RuleType.GherkinDocument:162 {163 var feature = node.GetSingle<Feature>(RuleType.Feature);164165 return CreateGherkinDocument(feature, comments.ToArray(), node);166 }167 }168169 return node;170 }171172 protected virtual Background CreateBackground(Location location, string keyword, string name, string description, Step[] steps, AstNode node)173 {174 return new Background(location, keyword, name, description, steps);175 }176177 protected virtual DataTable CreateDataTable(TableRow[] rows, AstNode node)178 {179 return new DataTable(rows);180 }181182 protected virtual Comment CreateComment(Location location, string text)183 {184 return new Comment(location, text);185 }186187 protected virtual ScenarioOutline CreateScenarioOutline(Tag[] tags, Location location, string keyword, string name, string description, Step[] steps, Examples[] examples, AstNode node)188 {189 return new ScenarioOutline(tags, location, keyword, name, description, steps, examples);190 }191192 protected virtual Examples CreateExamples(Tag[] tags, Location location, string keyword, string name, string description, TableRow header, TableRow[] body, AstNode node)193 {194 return new Examples(tags, location, keyword, name, description, header, body);195 }196197 protected virtual Scenario CreateScenario(Tag[] tags, Location location, string keyword, string name, string description, Step[] steps, AstNode node)198 {199 return new Scenario(tags, location, keyword, name, description, steps);200 }201202 protected virtual DocString CreateDocString(Location location, string contentType, string content, AstNode node)203 {204 return new DocString(location, contentType, content);205 }206207 protected virtual Step CreateStep(Location location, string keyword, string text, StepArgument argument, AstNode node)208 {209 return new Step(location, keyword, text, argument);210 }211212 protected virtual GherkinDocument CreateGherkinDocument(Feature feature, Comment[] gherkinDocumentComments, AstNode node) {213 return new GherkinDocument(feature, gherkinDocumentComments);214 }215216 protected virtual Feature CreateFeature(Tag[] tags, Location location, string language, string keyword, string name, string description, ScenarioDefinition[] children, AstNode node)217 {218 return new Feature(tags, location, language, keyword, name, description, children);219 }220 protected virtual Tag CreateTag(Location location, string name, AstNode node)221 {222 return new Tag(location, name);223 }224225 protected virtual Location CreateLocation(int line, int column)226 {227 return new Location(line, column);228 }229230 protected virtual TableRow CreateTableRow(Location location, TableCell[] cells, AstNode node)231 {232 return new TableRow(location, cells);233 }234235 protected virtual TableCell CreateTableCell(Location location, string value)236 {237 return new TableCell(location, value);238 }239240 private Location GetLocation(Token token, int column = 0)241 {242 return column == 0 ? token.Location : CreateLocation(token.Location.Line, column);243 }244245 private Tag[] GetTags(AstNode node)246 {247 var tagsNode = node.GetSingle<AstNode>(RuleType.Tags);248 if (tagsNode == null)249 return new Tag[0];250251 return tagsNode.GetTokens(TokenType.TagLine)252 .SelectMany(t => t.MatchedItems, (t, tagItem) =>253 CreateTag(GetLocation(t, tagItem.Column), tagItem.Text, tagsNode))254 .ToArray();255 }256257 private TableRow[] GetTableRows(AstNode node)258 {259 var rows = node.GetTokens(TokenType.TableRow).Select(token => CreateTableRow(GetLocation(token), GetCells(token), node)).ToArray();260 EnsureCellCount(rows);261 return rows;262 }263264 private void EnsureCellCount(TableRow[] rows)265 {266 if (rows.Length == 0)267 return;268269 int cellCount = rows[0].Cells.Count();270 foreach (var row in rows)271 {272 if (row.Cells.Count() != cellCount)273 {274 throw new AstBuilderException("inconsistent cell count within the table", row.Location);275 }276 }277 }278279 private TableCell[] GetCells(Token tableRowToken)280 {281 return tableRowToken.MatchedItems282 .Select(cellItem => CreateTableCell(GetLocation(tableRowToken, cellItem.Column), cellItem.Text))283 .ToArray();284 }285286 private static Step[] GetSteps(AstNode scenarioDefinitionNode)287 {288 return scenarioDefinitionNode.GetItems<Step>(RuleType.Step).ToArray();289 }290291 private static string GetDescription(AstNode scenarioDefinitionNode)292 {293 return scenarioDefinitionNode.GetSingle<string>(RuleType.Description);294 }295 }296}
...
DeveroomGherkinParser.cs
Source:DeveroomGherkinParser.cs
...55 if (result != null)56 return result;57 try58 {59 AstBuilder.EndRule(RuleType.None);60 }61 catch (Exception)62 {63 }64 }65 return null;66 }67 public DeveroomGherkinDocument Parse(TextReader featureFileReader, string sourceFilePath)68 {69 var tokenScanner = (ITokenScanner)new HotfixTokenScanner(featureFileReader);70 var tokenMatcher = new TokenMatcher(DialectProvider);71 _astBuilder = new DeveroomGherkinAstBuilder(sourceFilePath, () => tokenMatcher.CurrentDialect);72 var parser = new InternalParser(_astBuilder, AstBuilder.RecordStateForLine, _monitoringService);73 var gherkinDocument = parser.Parse(tokenScanner, tokenMatcher);74 CheckSemanticErrors(gherkinDocument);75 return gherkinDocument;76 }77 class InternalParser : Parser<DeveroomGherkinDocument>78 {79 private readonly Action<int, int> _recordStateForLine;80 private readonly IMonitoringService _monitoringService;81 public InternalParser(IAstBuilder<DeveroomGherkinDocument> astBuilder, Action<int, int> recordStateForLine, IMonitoringService monitoringService)82 : base(astBuilder)83 {84 _recordStateForLine = recordStateForLine;85 _monitoringService = monitoringService;86 }87 public int NullMatchToken(int state, Token token)88 {89 return MatchToken(state, token, new ParserContext()90 {91 Errors = new List<ParserException>(),92 TokenMatcher = new AllFalseTokenMatcher(),93 TokenQueue = new Queue<Token>(),94 TokenScanner = new NullTokenScanner()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;...
AstMessagesConverter.cs
Source:AstMessagesConverter.cs
...7using Comment = Gherkin.CucumberMessages.Types.Comment;8using Examples = Gherkin.CucumberMessages.Types.Examples;9using Feature = Gherkin.CucumberMessages.Types.Feature;10using Location = Gherkin.CucumberMessages.Types.Location;11using Rule = Gherkin.CucumberMessages.Types.Rule;12using Step = Gherkin.CucumberMessages.Types.Step;13using DataTable = Gherkin.CucumberMessages.Types.DataTable;14using DocString = Gherkin.CucumberMessages.Types.DocString;15using GherkinDocument = Gherkin.CucumberMessages.Types.GherkinDocument;16using Scenario = Gherkin.CucumberMessages.Types.Scenario;17using TableCell = Gherkin.CucumberMessages.Types.TableCell;18using TableRow = Gherkin.CucumberMessages.Types.TableRow;19using Tag = Gherkin.CucumberMessages.Types.Tag;20namespace Gherkin.CucumberMessages21{22 public class AstMessagesConverter23 {24 private readonly IIdGenerator _idGenerator;25 public AstMessagesConverter(IIdGenerator idGenerator)26 {27 _idGenerator = idGenerator;28 }29 public GherkinDocument ConvertGherkinDocumentToEventArgs(Ast.GherkinDocument gherkinDocument, string sourceEventUri)30 {31 return new GherkinDocument()32 {33 Uri = sourceEventUri,34 Feature = ConvertFeature(gherkinDocument),35 Comments = ConvertComments(gherkinDocument)36 };37 }38 private IReadOnlyCollection<Comment> ConvertComments(Ast.GherkinDocument gherkinDocument)39 {40 return gherkinDocument.Comments.Select(c =>41 new Comment()42 {43 Text = c.Text,44 Location = ConvertLocation(c.Location)45 }).ToReadOnlyCollection();46 }47 private Feature ConvertFeature(Ast.GherkinDocument gherkinDocument)48 {49 var feature = gherkinDocument.Feature;50 if (feature == null)51 {52 return null;53 }54 var children = feature.Children.Select(ConvertToFeatureChild).ToReadOnlyCollection();55 var tags = feature.Tags.Select(ConvertTag).ToReadOnlyCollection();56 return new Feature()57 {58 Name = CucumberMessagesDefaults.UseDefault(feature.Name, CucumberMessagesDefaults.DefaultName),59 Description = CucumberMessagesDefaults.UseDefault(feature.Description, CucumberMessagesDefaults.DefaultDescription),60 Keyword = feature.Keyword,61 Language = feature.Language,62 Location = ConvertLocation(feature.Location),63 Children = children,64 Tags = tags65 };66 }67 private static Location ConvertLocation(Ast.Location location)68 {69 return new Location(location.Column, location.Line);70 }71 private FeatureChild ConvertToFeatureChild(IHasLocation hasLocation)72 {73 var tuple = ConvertToChild(hasLocation);74 return new FeatureChild(tuple.Item3, tuple.Item1, tuple.Item2);75 }76 77 private RuleChild ConvertToRuleChild(IHasLocation hasLocation)78 {79 var tuple = ConvertToChild(hasLocation);80 return new RuleChild(tuple.Item1, tuple.Item3);81 }82 83 private Tuple<Background, Rule, Scenario> ConvertToChild(IHasLocation hasLocation)84 {85 switch (hasLocation)86 {87 case Gherkin.Ast.Background background:88 var backgroundSteps = background.Steps.Select(ConvertStep).ToList();89 return new Tuple<Background, Rule, Scenario>(new Background90 {91 Id = _idGenerator.GetNewId(),92 Location = ConvertLocation(background.Location),93 Name = CucumberMessagesDefaults.UseDefault(background.Name, CucumberMessagesDefaults.DefaultName),94 Description = CucumberMessagesDefaults.UseDefault(background.Description, CucumberMessagesDefaults.DefaultDescription),95 Keyword = background.Keyword,96 Steps = backgroundSteps97 }, null, null);98 case Ast.Scenario scenario:99 var steps = scenario.Steps.Select(ConvertStep).ToList();100 var examples = scenario.Examples.Select(ConvertExamples).ToReadOnlyCollection();101 var tags = scenario.Tags.Select(ConvertTag).ToReadOnlyCollection();102 return new Tuple<Background, Rule, Scenario>(null, null, new Scenario()103 {104 Id = _idGenerator.GetNewId(),105 Keyword = scenario.Keyword,106 Location = ConvertLocation(scenario.Location),107 Name = CucumberMessagesDefaults.UseDefault(scenario.Name, CucumberMessagesDefaults.DefaultName),108 Description = CucumberMessagesDefaults.UseDefault(scenario.Description, CucumberMessagesDefaults.DefaultDescription),109 Steps = steps,110 Examples = examples,111 Tags = tags112 });113 case Ast.Rule rule:114 {115 var ruleChildren = rule.Children.Select(ConvertToRuleChild).ToReadOnlyCollection();116 var ruleTags = rule.Tags.Select(ConvertTag).ToReadOnlyCollection();117 return new Tuple<Background, Rule, Scenario>(null, new Rule118 {119 Id = _idGenerator.GetNewId(),120 Name = CucumberMessagesDefaults.UseDefault(rule.Name, CucumberMessagesDefaults.DefaultName),121 Description = CucumberMessagesDefaults.UseDefault(rule.Description, CucumberMessagesDefaults.DefaultDescription),122 Keyword = rule.Keyword,123 Children = ruleChildren,124 Location = ConvertLocation(rule.Location),125 Tags = ruleTags126 }, null);127 }128 default:129 throw new NotImplementedException();130 }131 }...
DomBuilder.cs
Source:DomBuilder.cs
...28 public object BuildFromNode(ASTNode astNode)29 {30 switch (astNode.Node)31 {32 case RuleType.Description:33 return string.Join(Environment.NewLine, astNode.GetAllSubNodes().Cast<Token>().Select(t => t.Text));34 case RuleType.Multiline_Arg:35 {36 int indent = astNode.GetSubNodesOf(RuleType._MultiLineArgument).Cast<Token>().First().Indent; //TODO: use indent37 return string.Join(Environment.NewLine, astNode.GetAllSubNodes().Cast<Token>().Where(t => t.MatchedType != TokenType.MultiLineArgument).Select(t => t.Text)); //TODO: indent38 }39 case RuleType.Table_Arg:40 case RuleType.Examples_Table:41 {42 var rows = astNode.GetSubNodesOf(RuleType._TableRow).Cast<GherkinTableRow>().ToArray();43 var header = rows.First();44 return new GherkinTable(header, rows.Skip(1).ToArray());45 }46 case RuleType.Step:47 {48 var stepToken = astNode.GetSubNodesOf(RuleType._Step).Cast<Token>().First();49 var step = CreateStep(stepToken.MatchedKeyword, StepKeyword.Given, stepToken.Text, null, ScenarioBlock.Given); //TODO: G/W/T50 step.MultiLineTextArgument = astNode.GetSubNodesOf(RuleType.Multiline_Arg).Cast<string>().FirstOrDefault();51 step.TableArg = astNode.GetSubNodesOf(RuleType.Table_Arg).Cast<GherkinTable>().FirstOrDefault();52 return step;53 }54 case RuleType.Background:55 {56 var backgroundToken = astNode.GetSubNodesOf(RuleType._Background).Cast<Token>().First();57 var description = astNode.GetSubNodesOf(RuleType.Description).Cast<string>().FirstOrDefault();58 var steps = astNode.GetSubNodesOf(RuleType.Step).Cast<ScenarioStep>().ToArray();59 return new Background(backgroundToken.MatchedKeyword, backgroundToken.Text, description, new ScenarioSteps(steps));60 }61 case RuleType.Scenario:62 {63 //Tags will be added at Scenario_Base64 var scenarioToken = astNode.GetSubNodesOf(RuleType._Scenario).Cast<Token>().First();65 var description = astNode.GetSubNodesOf(RuleType.Description).Cast<string>().FirstOrDefault();66 var steps = astNode.GetSubNodesOf(RuleType.Step).Cast<ScenarioStep>().ToArray();67 return new Scenario(scenarioToken.MatchedKeyword, scenarioToken.Text, description, null, new ScenarioSteps(steps));68 }69 case RuleType.ScenarioOutline:70 {71 //Tags will be added at Scenario_Base72 var scenarioToken = astNode.GetSubNodesOf(RuleType._ScenarioOutline).Cast<Token>().First();73 var description = astNode.GetSubNodesOf(RuleType.Description).Cast<string>().FirstOrDefault();74 var steps = astNode.GetSubNodesOf(RuleType.Step).Cast<ScenarioStep>().ToArray();75 var exampleSets = astNode.GetSubNodesOf(RuleType.Examples).Cast<ExampleSet>().ToArray();76 return new ScenarioOutline(scenarioToken.MatchedKeyword, scenarioToken.Text, description, null, new ScenarioSteps(steps), new Examples(exampleSets));77 }78 case RuleType.Scenario_Base:79 {80 var tags = astNode.GetAllSubNodes().OfType<Tag>().ToArray();81 var scenario = astNode.GetAllSubNodes().OfType<Scenario>().First();82 scenario.Tags = new Tags(tags);83 return scenario;84 }85 case RuleType.Examples:86 {87 var examplesToken = astNode.GetSubNodesOf(RuleType._Examples).Cast<Token>().First();88 var description = astNode.GetSubNodesOf(RuleType.Description).Cast<string>().FirstOrDefault();89 var tags = astNode.GetAllSubNodes().OfType<Tag>().ToArray();90 var table = astNode.GetSubNodesOf(RuleType.Examples_Table).Cast<GherkinTable>().First();91 return new ExampleSet(examplesToken.MatchedKeyword, examplesToken.Text, description, new Tags(tags), table);92 }93 case RuleType.Feature_File:94 {95 var featureDef = astNode.GetSubNodesOf(RuleType.Feature_Def).Cast<ASTNode>().First();96 var featureToken = featureDef.GetSubNodesOf(RuleType._Feature).Cast<Token>().First();97 var description = featureDef.GetSubNodesOf(RuleType.Description).Cast<string>().FirstOrDefault();98 var tags = featureDef.GetAllSubNodes().OfType<Tag>().ToArray();99 var background = astNode.GetSubNodesOf(RuleType.Background).Cast<Background>().FirstOrDefault();100 var scenarios = astNode.GetSubNodesOf(RuleType.Scenario_Base).Cast<Scenario>().ToArray();101 return new Feature(featureToken.MatchedKeyword, featureToken.Text, new Tags(tags), description, background, scenarios, null); //TODO: comments;102 }103 }104 return astNode;105 }106 public ScenarioStep CreateStep(string keyword, StepKeyword stepKeyword, string text, FilePosition position, ScenarioBlock scenarioBlock)107 {108 ScenarioStep step;109 switch (stepKeyword)110 {111 case StepKeyword.Given:112 step = new Given();113 break;114 case StepKeyword.When:...
AstEventConverter.cs
Source:AstEventConverter.cs
...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 {...
GherkinDialectProvider.cs
Source:GherkinDialectProvider.cs
...103 {104 return new GherkinDialect(105 "en",106 new[] {"Feature"},107 new[] {"Rule"},108 new[] {"Background"},109 new[] {"Scenario"},110 new[] {"Scenario Outline", "Scenario Template"},111 new[] {"Examples", "Scenarios"},112 new[] {"* ", "Given "},113 new[] {"* ", "When " },114 new[] {"* ", "Then " },115 new[] {"* ", "And " },116 new[] {"* ", "But " });117 }118 }119120 public class GherkinLanguageSetting121 {
...
GherkinEditorParser.cs
Source:GherkinEditorParser.cs
...99 {100 public void Build(Token token)101 {102 }103 public void StartRule(RuleType ruleType)104 {105 }106 public void EndRule(RuleType ruleType)107 {108 }109 public object GetResult()110 {111 return null;112 }113 public void Reset()114 {115 116 }117 }118 public static TokenType[] GetExpectedTokens(int state)119 {120 var parser = new GherkinEditorParser(new GherkinTokenTagBuilder(null))...
Rule
Using AI Code Generation
1using Gherkin.Ast;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8 {9 static void Main(string[] args)10 {11 var parser = new Gherkin.Parser();12 var feature = parser.Parse(@"C:\Users\saikiran\Desktop\GherkinParser\GherkinParser\Features\Sample.feature");13 var rules = feature.GetRules();14 foreach (var rule in rules)15 {16 Console.WriteLine("Rule: " + rule.Name);17 Console.WriteLine("Description: " + rule.Description);18 Console.WriteLine("Keyword: " + rule.Keyword);19 var children = rule.GetChildren();20 foreach (var child in children)21 {22 if (child is Background)23 {24 var background = (Background)child;25 Console.WriteLine("Background: " + background.Name);26 Console.WriteLine("Description: " + background.Description);27 Console.WriteLine("Keyword: " + background.Keyword);28 Console.WriteLine("Location: " + background.Location);29 var steps = background.GetSteps();30 foreach (var step in steps)31 {32 Console.WriteLine("Step: " + step.Text);33 Console.WriteLine("Keyword: "
Rule
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Gherkin.Ast;7using System.IO;8{9 {10 static void Main(string[] args)11 {
Rule
Using AI Code Generation
1using Gherkin.Ast;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7{8 {9 static void Main(string[] args)10 {11 var feature = new Feature(12 new List<Tag>(),13 new Language("en", "English"),14 new List<Comment>(),15 new Background(new List<Tag>(), new List<Comment>(), "Background", new List<Step>(), 0),16 new List<ScenarioDefinition>(),17 new List<ScenarioDefinition>(),18 new List<ScenarioDefinition>(),
Rule
Using AI Code Generation
1using Gherkin.Ast;2using Gherkin;3using System.Text;4using System.IO;5{6 {7 static void Main(string[] args)8 {9 StringBuilder sb = new StringBuilder();10 Parser parser = new Parser();11 StreamReader sr = new StreamReader(@"C:\Users\Public\TestFolder\test.feature");12 sb.Append(sr.ReadToEnd());13 sr.Close();14 Feature feature = parser.Parse(sb.ToString()).Feature;15 foreach (Rule rule in feature.Children)16 {17 foreach (Scenario scenario in rule.Children)18 {19 foreach (Step step in scenario.Steps)20 {21 Console.WriteLine(step.Keyword);22 Console.WriteLine(step.Text);23 }24 }25 }26 Console.WriteLine("27Press any key to exit.");28 Console.ReadKey();29 }30 }31}
Rule
Using AI Code Generation
1{2 {3 public static Feature Parse(string featureFile)4 {5 var feature = new Feature();6 var featureText = File.ReadAllText(featureFile);7 var parser = new Gherkin.Ast.Parser();8 var featureNode = parser.Parse(featureText);9 feature.Name = featureNode.Name;10 feature.Description = featureNode.Description;11 feature.Scenarios = new List<Scenario>();12 feature.Background = new Background();13 foreach (var featureChild in featureNode.Children)14 {15 if (featureChild is Background background)16 {17 feature.Background.Name = background.Name;18 feature.Background.Steps = new List<Step>();19 foreach (var backgroundStep in background.Steps)20 {21 var step = new Step();22 step.Name = backgroundStep.Text;23 step.Table = backgroundStep.Argument;24 feature.Background.Steps.Add(step);25 }26 }27 else if (featureChild is Scenario scenario)28 {29 var scenarioDefinition = new Scenario();30 scenarioDefinition.Name = scenario.Name;31 scenarioDefinition.Steps = new List<Step>();32 foreach (var scenarioStep in scenario.Steps)33 {34 var step = new Step();35 step.Name = scenarioStep.Text;36 step.Table = scenarioStep.Argument;37 scenarioDefinition.Steps.Add(step);38 }39 feature.Scenarios.Add(scenarioDefinition);40 }41 }42 return feature;43 }44 }45}46{47 {48 public string Name { get; set; }49 public string Description { get; set; }50 public Background Background { get; set; }51 public List<Scenario> Scenarios { get; set; }52 }53}54{55 {56 public string Name { get; set; }57 public List<Step> Steps { get; set; }58 }59}60{61 {62 public string Name { get; set; }63 public List<Step> Steps { get;
Rule
Using AI Code Generation
1using Gherkin.Ast;2{3 {4 static void Main(string[] args)5 {6 var rule = new Rule("Rule", "Rule Description", new Location(0, 0));7 }8 }9}10using Gherkin.Ast;11{12 {13 static void Main(string[] args)14 {15 var rule = new Rule("Rule", "Rule Description", new Location(0, 0));16 Console.WriteLine(rule.Name);17 Console.WriteLine(rule.Description);18 Console.WriteLine(rule.Location.Line);19 Console.WriteLine(rule.Location.Column);20 }21 }22}23using Gherkin.Ast;24{25 {26 static void Main(string[] args)27 {28 var rule = new Rule("Rule", "Rule Description", new Location(0, 0));29 Console.WriteLine(rule.Name);30 Console.WriteLine(rule.Description);31 Console.WriteLine(rule.Location.Line);32 Console.WriteLine(rule.Location.Column);33 }34 }35}36using Gherkin.Ast;37{38 {39 static void Main(string[]
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!!