Best Gherkin-dotnet code snippet using Gherkin.Parser.Parser
Program.cs
Source:Program.cs
...8using System.Text.RegularExpressions;9using System.Xml.Linq;10using ILMerging;11using NConsoler;12namespace ImportGherkinParser13{14 class Program15 {16 static void Main(string[] args)17 {18 Console.WriteLine("Gherkin parser import tool:");19 Console.WriteLine(" + adds signing for the assembly");20 Console.WriteLine(" + generates Language.xml from the parser");21 Console.WriteLine();22 Consolery.Run(typeof(Program), args);23 return;24 }25 static private readonly Regex parserVersionRe = new Regex(@"(?<version>[\d\.]+)");26 [Action("Imports official Gherkin parser to SpecFlow")]27 public static void ImportGherkinParser(28 [Required(Description = "Original gherkin parser, like gherkin-1.0.21.dll")] string gherkinParser,29 [Optional("specflow.snk", "key")] string keyFile,30 [Optional("Gherkin.dll", "out")] string outputFile,31 [Optional("Languages.xml", "lngout")] string languagesOutputFile32 )33 {34 string gherkinParserFullPath = Path.GetFullPath(gherkinParser);35 Version parserVersion = GetParserVersion(gherkinParserFullPath);36 if (parserVersion == null)37 return;38 string keyFullPath = Path.GetFullPath(keyFile);39 string outputFileFullPath = Path.GetFullPath(outputFile);40 string languagesOutputFileFullPath = Path.GetFullPath(languagesOutputFile);41 CreateSignedParser(gherkinParserFullPath, parserVersion, keyFullPath, outputFileFullPath);42 Assembly parserAssembly = LoadParser(outputFileFullPath);43 GenerateLanguageDescriptions(parserAssembly, languagesOutputFileFullPath);44 }45 private static Version GetParserVersion(string gherkinParserFullPath)46 {47 var match = parserVersionRe.Match(Path.GetFileNameWithoutExtension(gherkinParserFullPath));48 if (!match.Success)49 {50 Console.WriteLine("> Unable to detect parser version");51 return null;52 }53 var version = new Version(match.Groups["version"].Value);54 version = new Version(version.Major, version.Minor, version.Build, version.Revision < 0 ? 0 : version.Revision);55 return version;56 }57 private static Assembly LoadParser(string outputFileFullPath)58 {59 Console.WriteLine("Loading imported parser from {0}", outputFileFullPath);60 return Assembly.LoadFrom(outputFileFullPath);61 }62 private static void CreateSignedParser(string gherkinParserFullPath, Version version, string keyFullPath, string outputFileFullPath)63 {64 Console.WriteLine("Generating signed parser...");65 ILMerge ilMerge = new ILMerge();66 ilMerge.KeyFile = keyFullPath;67 ilMerge.Version = version;68 string simpleJsonPath = Path.Combine(Path.GetDirectoryName(gherkinParserFullPath), "com.googlecode.json-simple-json-simple.dll");69 string base46Path = Path.Combine(Path.GetDirectoryName(gherkinParserFullPath), "net.iharder-base64.dll");70 ilMerge.SetInputAssemblies(new[] { gherkinParserFullPath, simpleJsonPath, base46Path });71 ilMerge.OutputFile = outputFileFullPath;72 ilMerge.TargetKind = ILMerge.Kind.Dll;73 ilMerge.Log = true;74 ilMerge.Merge();75 Console.WriteLine();76 }77 private static readonly Dictionary<string, string> languageTranslations = 78 new Dictionary<string, string>()79 {80 {"se", "sv"},81 {"lu", "lb-LU"},82 };83 private class KeywordTranslation84 {...
DeveroomGherkinParser.cs
Source:DeveroomGherkinParser.cs
...6using Deveroom.VisualStudio.Diagonostics;7using Deveroom.VisualStudio.Monitoring;8using Gherkin;9using Gherkin.Ast;10namespace Deveroom.VisualStudio.Editor.Services.Parser11{12 public class DeveroomGherkinParser13 {14 private readonly IMonitoringService _monitoringService;15 private IAstBuilder<DeveroomGherkinDocument> _astBuilder;16 public IGherkinDialectProvider DialectProvider { get; }17 internal DeveroomGherkinAstBuilder AstBuilder => _astBuilder as DeveroomGherkinAstBuilder;18 public DeveroomGherkinParser(IGherkinDialectProvider dialectProvider, IMonitoringService monitoringService)19 {20 _monitoringService = monitoringService;21 DialectProvider = dialectProvider;22 }23 public bool ParseAndCollectErrors(string featureFileContent, IDeveroomLogger logger, out DeveroomGherkinDocument gherkinDocument, out List<ParserException> parserErrors)24 {25 var reader = new StringReader(featureFileContent);26 gherkinDocument = null;27 parserErrors = new List<ParserException>();28 try29 {30 gherkinDocument = Parse(reader, "foo.feature"); //TODO: remove unused path31 return true;32 }33 catch (ParserException parserException)34 {35 logger.LogVerbose($"ParserErrors: {parserException.Message}");36 gherkinDocument = GetResultOfInvalid();37 if (parserException is CompositeParserException compositeParserException)38 parserErrors.AddRange(compositeParserException.Errors);39 else40 parserErrors.Add(parserException);41 }42 catch (Exception e)43 {44 logger.LogException(_monitoringService, e, "Exception during Gherkin parsing");45 gherkinDocument = GetResult();46 }47 return false;48 }49 private DeveroomGherkinDocument GetResultOfInvalid()50 {51 // trying to "finish" open nodes by sending dummy <endrule> messages up to 5 levels of nesting52 for (int i = 0; i < 10; i++)53 {54 var result = GetResult();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;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 #endregion...
GherkinTextBufferParser.cs
Source:GherkinTextBufferParser.cs
2using System.Collections.Generic;3using System.Diagnostics;4using System.Linq;5using Microsoft.VisualStudio.Text;6using TechTalk.SpecFlow.Parser;7using TechTalk.SpecFlow.Parser.Gherkin;8using TechTalk.SpecFlow.Vs2010Integration.Tracing;9using TechTalk.SpecFlow.Vs2010Integration.Utils;10namespace TechTalk.SpecFlow.Vs2010Integration.LanguageService11{12 public class GherkinTextBufferParser13 {14 private const string ParserTraceCategory = "EditorParser";15 private const int PartialParseCountLimit = 30;16 private int partialParseCount = 0;17 private readonly IProjectScope projectScope;18 private readonly IVisualStudioTracer visualStudioTracer;19 public GherkinTextBufferParser(IProjectScope projectScope, IVisualStudioTracer visualStudioTracer)20 {21 this.projectScope = projectScope;22 this.visualStudioTracer = visualStudioTracer;23 }24 private GherkinDialect GetGherkinDialect(ITextSnapshot textSnapshot)25 {26 try27 {28 return projectScope.GherkinDialectServices.GetGherkinDialect(29 lineNo => textSnapshot.GetLineFromLineNumber(lineNo).GetText());30 }31 catch(Exception)32 {33 return null;34 }35 }36 public GherkinFileScopeChange Parse(GherkinTextBufferChange change, IGherkinFileScope previousScope = null)37 {38 var gherkinDialect = GetGherkinDialect(change.ResultTextSnapshot);39 if (gherkinDialect == null)40 return GetInvalidDialectScopeChange(change);41 bool fullParse = false;42 if (previousScope == null)43 fullParse = true;44 else if (!Equals(previousScope.GherkinDialect, gherkinDialect))45 fullParse = true;46 else if (partialParseCount >= PartialParseCountLimit)47 fullParse = true;48 else if (GetFirstAffectedScenario(change, previousScope) == null)49 fullParse = true;50 if (fullParse)51 return FullParse(change.ResultTextSnapshot, gherkinDialect);52 return PartialParse(change, previousScope);53 }54 private GherkinFileScopeChange GetInvalidDialectScopeChange(GherkinTextBufferChange change)55 {56 var fileScope = new GherkinFileScope(null, change.ResultTextSnapshot)57 {58 InvalidFileEndingBlock = new InvalidFileBlock(0, 59 change.ResultTextSnapshot.LineCount - 1,60 new ErrorInfo("Invalid Gherkin dialect!", 0, 0, null))61 };62 return GherkinFileScopeChange.CreateEntireScopeChange(fileScope);63 }64 private GherkinFileScopeChange FullParse(ITextSnapshot textSnapshot, GherkinDialect gherkinDialect)65 {66 visualStudioTracer.Trace("Start full parsing", ParserTraceCategory);67 Stopwatch stopwatch = new Stopwatch();68 stopwatch.Start();69 partialParseCount = 0;70 var gherkinListener = new GherkinTextBufferParserListener(gherkinDialect, textSnapshot, projectScope);71 var scanner = new GherkinScanner(gherkinDialect, textSnapshot.GetText(), 0);72 scanner.Scan(gherkinListener);73 var gherkinFileScope = gherkinListener.GetResult();74 var result = new GherkinFileScopeChange(75 gherkinFileScope,76 true, true,77 gherkinFileScope.GetAllBlocks(),78 Enumerable.Empty<IGherkinFileBlock>());79 stopwatch.Stop();80 TraceFinishParse(stopwatch, "full", result);81 return result;82 }83 private GherkinFileScopeChange PartialParse(GherkinTextBufferChange change, IGherkinFileScope previousScope)84 {85 visualStudioTracer.Trace("Start incremental parsing", ParserTraceCategory);86 Stopwatch stopwatch = new Stopwatch();87 stopwatch.Start();88 partialParseCount++;89 var textSnapshot = change.ResultTextSnapshot;90 IScenarioBlock firstAffectedScenario = GetFirstAffectedScenario(change, previousScope);91 VisualStudioTracer.Assert(firstAffectedScenario != null, "first affected scenario is null");92 int parseStartPosition = textSnapshot.GetLineFromLineNumber(firstAffectedScenario.GetStartLine()).Start;93 string fileContent = textSnapshot.GetText(parseStartPosition, textSnapshot.Length - parseStartPosition);94 var gherkinListener = new GherkinTextBufferPartialParserListener(95 previousScope.GherkinDialect,96 textSnapshot, projectScope, 97 previousScope, 98 change.EndLine, change.LineCountDelta);99 var scanner = new GherkinScanner(previousScope.GherkinDialect, fileContent, firstAffectedScenario.GetStartLine());100 IScenarioBlock firstUnchangedScenario = null;101 try102 {103 scanner.Scan(gherkinListener);104 }105 catch (PartialListeningDoneException partialListeningDoneException)106 {107 firstUnchangedScenario = partialListeningDoneException.FirstUnchangedScenario;108 }109 var partialResult = gherkinListener.GetResult();110 var result = MergePartialResult(previousScope, partialResult, firstAffectedScenario, firstUnchangedScenario, change.LineCountDelta);111 stopwatch.Stop();112 TraceFinishParse(stopwatch, "incremental", result);113 return result;114 }115 private IScenarioBlock GetFirstAffectedScenario(GherkinTextBufferChange change, IGherkinFileScope previousScope)116 {117 if (change.Type == GherkinTextBufferChangeType.SingleLine)118 //single-line changes on the start cannot influence the previous scenario119 return previousScope.ScenarioBlocks.LastOrDefault(s => s.GetStartLine() <= change.StartLine);120 // if multiple lines are added at the first line of a block, it can happen that these lines will belong121 // to the previous block122 return previousScope.ScenarioBlocks.LastOrDefault(s => s.GetStartLine() < change.StartLine); 123 }124 private GherkinFileScopeChange MergePartialResult(IGherkinFileScope previousScope, IGherkinFileScope partialResult, IScenarioBlock firstAffectedScenario, IScenarioBlock firstUnchangedScenario, int lineCountDelta)125 {126 Debug.Assert(partialResult.HeaderBlock == null, "Partial parse cannot re-parse header");127 Debug.Assert(partialResult.BackgroundBlock == null, "Partial parse cannot re-parse background");128 List<IGherkinFileBlock> changedBlocks = new List<IGherkinFileBlock>();129 List<IGherkinFileBlock> shiftedBlocks = new List<IGherkinFileBlock>();130 GherkinFileScope fileScope = new GherkinFileScope(previousScope.GherkinDialect, partialResult.TextSnapshot)131 {132 HeaderBlock = previousScope.HeaderBlock,133 BackgroundBlock = previousScope.BackgroundBlock134 };135 // inserting the non-affected scenarios136 fileScope.ScenarioBlocks.AddRange(previousScope.ScenarioBlocks.TakeUntilItemExclusive(firstAffectedScenario));137 //inserting partial result138 fileScope.ScenarioBlocks.AddRange(partialResult.ScenarioBlocks);139 changedBlocks.AddRange(partialResult.ScenarioBlocks);140 if (partialResult.InvalidFileEndingBlock != null)141 {142 VisualStudioTracer.Assert(firstUnchangedScenario == null, "first affected scenario is not null");143 // the last scenario was changed, but it became invalid144 fileScope.InvalidFileEndingBlock = partialResult.InvalidFileEndingBlock;145 changedBlocks.Add(fileScope.InvalidFileEndingBlock);146 }147 if (firstUnchangedScenario != null)148 {149 Tracing.VisualStudioTracer.Assert(partialResult.InvalidFileEndingBlock == null, "there is an invalid file ending block");150 // inserting the non-effected scenarios at the end151 var shiftedScenarioBlocks = previousScope.ScenarioBlocks.SkipFromItemInclusive(firstUnchangedScenario)152 .Select(scenario => scenario.Shift(lineCountDelta)).ToArray();153 fileScope.ScenarioBlocks.AddRange(shiftedScenarioBlocks);154 shiftedBlocks.AddRange(shiftedScenarioBlocks);155 if (previousScope.InvalidFileEndingBlock != null)156 {157 fileScope.InvalidFileEndingBlock = previousScope.InvalidFileEndingBlock.Shift(lineCountDelta);158 shiftedBlocks.Add(fileScope.InvalidFileEndingBlock);159 }160 }161 return new GherkinFileScopeChange(fileScope, false, false, changedBlocks, shiftedBlocks);162 }163 private void TraceFinishParse(Stopwatch stopwatch, string parseKind, GherkinFileScopeChange result)164 {165 visualStudioTracer.Trace(166 string.Format("Finished {0} parsing in {1} ms, {2} errors", parseKind, stopwatch.ElapsedMilliseconds, result.GherkinFileScope.TotalErrorCount()), ParserTraceCategory);167 }168 }169}...
GherkinSyntaxParserTests.cs
Source:GherkinSyntaxParserTests.cs
1namespace GherkinSyntaxHighlighter.Tests.Unit2{3 using NSubstitute;4 using NUnit.Framework;5 using global::GherkinSyntaxHighlighter.Parser;6 // Examples from: http://dannorth.net/introducing-bdd/7 // TODO: Mock expectations could be replaced by an adapter with one expect method...8 [TestFixture]9 public class GivenAClassOrMethodIdentifier10 {11 [Test]12 public void WhenStringStartsWithGerkinSyntaxThenCallsObserverWithOneGivenAndMultiplePascalSpans()13 {14 var mockGherkinSyntaxParserObserver = Substitute.For<ISyntaxParserObserver>();15 var gherkinSyntaxParser = new SyntaxParser(mockGherkinSyntaxParserObserver);16 gherkinSyntaxParser.Parse("GivenTheAccountIsInCredit");17 mockGherkinSyntaxParserObserver.Received(1).AddGherkinSyntaxSpanAt(0, 5); // Given18 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(5, 3); // The19 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(8, 7); // Account20 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(15, 2); // Is21 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(17, 2); // In22 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(19, 6); // Credit23 }24 [Test]25 public void WhenStringStartsWithAndContainsGherkinSntaxThenCallsObserverWithOneGivenAndOneAndSpan()26 {27 var mockGherkinSyntaxParserObserver = Substitute.For<ISyntaxParserObserver>();28 var gherkinSyntaxParser = new SyntaxParser(mockGherkinSyntaxParserObserver);29 gherkinSyntaxParser.Parse("GivenTheAccountIsInCreditAndTheCardIsValid");30 mockGherkinSyntaxParserObserver.Received(1).AddGherkinSyntaxSpanAt(0, 5); // Given31 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(5, 3); // The32 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(8, 7); // Account33 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(15, 2); // Is34 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(17, 2); // In35 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(19, 6); // Credit36 mockGherkinSyntaxParserObserver.Received(1).AddGherkinSyntaxSpanAt(25, 3); // And37 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(28, 3); // The38 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(31, 4); // Card39 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(35, 2); // Is40 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(37, 5); // Valid41 }42 [Test]43 public void WhenStringStartWithAndContainsGherkinSntaxThenCallsObserverWithOneWhenAndOneThenSpan()44 {45 var mockGherkinSyntaxParserObserver = Substitute.For<ISyntaxParserObserver>();46 var gherkinSyntaxParser = new SyntaxParser(mockGherkinSyntaxParserObserver);47 gherkinSyntaxParser.Parse("WhenCustomerRequestsCashThenEnsureAccountIsDebitedAndEnsureCashDispensed");48 mockGherkinSyntaxParserObserver.Received(1).AddGherkinSyntaxSpanAt(0, 4); // When49 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(4, 8); // Customer50 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(12, 8); // Requests51 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(20, 4); // Cash52 mockGherkinSyntaxParserObserver.Received(1).AddGherkinSyntaxSpanAt(24, 4); // Then53 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(28, 6); // Ensure54 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(34, 7); // Account55 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(41, 2); // Is56 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(43, 7); // Debited57 mockGherkinSyntaxParserObserver.Received(1).AddGherkinSyntaxSpanAt(50, 3); // And58 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(53, 6); // Ensure59 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(59, 4); // Cash60 mockGherkinSyntaxParserObserver.Received(1).AddPascalCaseSpanAt(63, 9); // Dispensed61 }62 }63}...
GherkinTokenTagger.cs
Source:GherkinTokenTagger.cs
...6using System.Threading;7using Gherkin;8using Microsoft.VisualStudio.Text;9using Microsoft.VisualStudio.Text.Tagging;10namespace SpecFlow.VisualStudio.Editor.Parser11{12 internal sealed class GherkinTokenTagger : ITagger<GherkinTokenTag>13 {14 private class ParsingResult15 {16 public int SnapshotVersion { get; private set; }17 public GherkinTokenTag[] Tags { get; private set; }18 public ParsingResult(int snapshotVersion, GherkinTokenTag[] tags)19 {20 SnapshotVersion = snapshotVersion;21 Tags = tags;22 }23 }24 private readonly ITextBuffer buffer;25 private ParsingResult lastResult = null;26 internal GherkinTokenTagger(ITextBuffer buffer)27 {28 this.buffer = buffer;29 }30 public event EventHandler<SnapshotSpanEventArgs> TagsChanged;31 public IEnumerable<ITagSpan<GherkinTokenTag>> GetTags(NormalizedSnapshotSpanCollection spans)32 {33 var snapshot = spans[0].Snapshot;34 var tokenTags = Parse(snapshot);35 if (tokenTags == null)36 yield break;37 foreach (SnapshotSpan queriedSpan in spans)38 {39 foreach (var tokenTag in tokenTags)40 {41 var tokenSpan = tokenTag.Span;42 if (tokenSpan.IntersectsWith(queriedSpan))43 yield return new TagSpan<GherkinTokenTag>(tokenSpan, tokenTag);44 if (tokenSpan.Start > queriedSpan.End)45 break;46 }47 }48 }49 private GherkinTokenTag[] Parse(ITextSnapshot snapshot)50 {51 var currentLastResult = lastResult;52 if (currentLastResult != null && currentLastResult.SnapshotVersion == snapshot.Version.VersionNumber)53 return currentLastResult.Tags;54 55 var fileContent = snapshot.GetText();56 var stopwatch = new Stopwatch();57 stopwatch.Start();58 var parserErrors = new List<ParserException>();59 var tokenTagBuilder = new GherkinTokenTagBuilder(snapshot);60 var parser = new GherkinEditorParser(tokenTagBuilder);61 var reader = new StringReader(fileContent);62 try63 {64 parser.Parse(new TokenScanner(reader), new TokenMatcher(VsGherkinDialectProvider.Instance));65 }66 catch (CompositeParserException compositeParserException)67 {68 parserErrors.AddRange(compositeParserException.Errors);69 }70 catch (ParserException parserException)71 {72 parserErrors.Add(parserException);73 }74 catch (Exception ex)75 {76 //nop;77 Debug.WriteLine(ex);78 }79 var tokenTags = new List<GherkinTokenTag>();80 tokenTags.AddRange((GherkinTokenTag[])tokenTagBuilder.GetResult());81 tokenTags.AddRange(parserErrors.Select(e => new GherkinTokenTag(e, snapshot)));82 tokenTags.Sort((t1, t2) => t1.Span.Start.Position.CompareTo(t2.Span.Start.Position));83 stopwatch.Stop();84 Debug.WriteLine("Gherkin3: parsed v{0} on thread {1} in {2} ms", snapshot.Version.VersionNumber, Thread.CurrentThread.ManagedThreadId, stopwatch.ElapsedMilliseconds);...
ParseGherkinQueryRequestHandler.cs
Source:ParseGherkinQueryRequestHandler.cs
...3using System.Linq;4using System.Text;5using Gherkin.Ast;6using MediatR;7using SFA.DAS.Payments.Automation.Application.GherkinSpecs.StepParsers;8using SFA.DAS.Payments.Automation.Domain.Specifications;9namespace SFA.DAS.Payments.Automation.Application.GherkinSpecs.ParseGherkinQuery10{11 public class ParseGherkinQueryRequestHandler : IRequestHandler<ParseGherkinQueryRequest, ParseGherkinQueryResponse>12 {13 private static readonly string[] PrimaryScenarioKeywords = { "Given", "When", "Then" };14 private static readonly StepParser[] StepParsers =15 {16 new CommitmentsStepParser(),17 new IndefinateLevyBalanceStepParser(),18 new NoLevyBalanceStepParser(),19 new SpecificLevyBalanceStepParser(),20 new SubmissionStepParser(),21 new ContractTypeStepParser(),22 new EmploymentStatusStepParser()23 };24 public ParseGherkinQueryResponse Handle(ParseGherkinQueryRequest message)25 {26 try27 {28 var doc = ParseGherkin(message.GherkinSpecs);29 var docSpecs = doc.Feature.Children.ToArray();30 var specifications = new Specification[docSpecs.Length];31 for (var i = 0; i < specifications.Length; i++)32 {33 specifications[i] = ParseScenario(docSpecs[i]);34 }35 return new ParseGherkinQueryResponse36 {37 Results = specifications38 };39 }40 catch (Exception ex)41 {42 return new ParseGherkinQueryResponse43 {44 Error = new ParserException(ex)45 };46 }47 }48 private Gherkin.Ast.GherkinDocument ParseGherkin(string specs)49 {50 using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(specs)))51 using (var reader = new StreamReader(stream))52 {53 var parser = new Gherkin.Parser();54 return parser.Parse(reader);55 }56 }57 private Specification ParseScenario(ScenarioDefinition scenarioDefinition)58 {59 var specification = new Specification60 {61 Name = scenarioDefinition.Name62 };63 var currentStepKeyword = "";64 foreach (var step in scenarioDefinition.Steps)65 {66 if (PrimaryScenarioKeywords.Any(x => x.Equals(step.Keyword.Trim(), StringComparison.CurrentCultureIgnoreCase)))67 {68 currentStepKeyword = step.Keyword.Trim().ToLower();69 }70 ParseStep(currentStepKeyword, step, specification);71 }72 return specification;73 }74 private void ParseStep(string keyword, Step step, Specification specification)75 {76 foreach (var parser in StepParsers)77 {78 if (parser.CanParse(keyword, step.Text))79 {80 parser.Parse(step, specification);81 return;82 }83 }84 }85 }86}...
NoProjectScope.cs
Source:NoProjectScope.cs
...5using TechTalk.SpecFlow.IdeIntegration.Generator;6using TechTalk.SpecFlow.IdeIntegration.Options;7using TechTalk.SpecFlow.IdeIntegration.Tracing;8using TechTalk.SpecFlow.Infrastructure;9using TechTalk.SpecFlow.Parser;10using TechTalk.SpecFlow.Bindings;11using TechTalk.SpecFlow.Vs2010Integration.GherkinFileEditor;12using TechTalk.SpecFlow.Vs2010Integration.Options;13using TechTalk.SpecFlow.Vs2010Integration.Tracing;14namespace TechTalk.SpecFlow.Vs2010Integration.LanguageService15{16 internal class NoProjectScope : IProjectScope17 {18 public GherkinTextBufferParser GherkinTextBufferParser { get; private set; }19 public GherkinFileEditorClassifications Classifications { get; private set; }20 public GherkinProcessingScheduler GherkinProcessingScheduler { get; private set; }21 public SpecFlowProjectConfiguration SpecFlowProjectConfiguration { get; private set; }22 public GherkinDialectServices GherkinDialectServices { get; private set; }23 public IIntegrationOptionsProvider IntegrationOptionsProvider { get; private set; }24 public IIdeTracer Tracer { get; private set; }25 public event Action SpecFlowProjectConfigurationChanged { add {} remove {} }26 public event Action GherkinDialectServicesChanged { add { } remove { } }27 public GherkinScopeAnalyzer GherkinScopeAnalyzer28 {29 get { return null; }30 }31 public VsStepSuggestionProvider StepSuggestionProvider32 {33 get { return null; }34 }35 public IStepDefinitionMatchService BindingMatchService36 {37 get { return null; }38 }39 public IGeneratorServices GeneratorServices40 {41 get { return null; }42 }43 public NoProjectScope(GherkinFileEditorClassifications classifications, IVisualStudioTracer visualStudioTracer, IIntegrationOptionsProvider integrationOptionsProvider)44 {45 GherkinTextBufferParser = new GherkinTextBufferParser(this, visualStudioTracer);46 GherkinProcessingScheduler = new GherkinProcessingScheduler(visualStudioTracer, false);47 SpecFlowProjectConfiguration = new SpecFlowProjectConfiguration();48 GherkinDialectServices = new GherkinDialectServices(SpecFlowProjectConfiguration.GeneratorConfiguration.FeatureLanguage); 49 Classifications = classifications;50 IntegrationOptionsProvider = integrationOptionsProvider;51 Tracer = visualStudioTracer;52 }53 public void Dispose()54 {55 //nop56 }57 }58}...
SpecFlowLangParser.cs
Source:SpecFlowLangParser.cs
2using System.Diagnostics;3using System.Globalization;4using System.IO;5using System.Linq;6using TechTalk.SpecFlow.Parser.Gherkin;7using TechTalk.SpecFlow.Parser.GherkinBuilder;8using TechTalk.SpecFlow.Parser.SyntaxElements;9namespace TechTalk.SpecFlow.Parser10{11 public class SpecFlowLangParser12 {13 private readonly GherkinDialectServices dialectServices;14 public SpecFlowLangParser(CultureInfo defaultLanguage)15 {16 this.dialectServices = new GherkinDialectServices(defaultLanguage);17 }18 public Feature Parse(TextReader featureFileReader, string sourceFilePath)19 {20 var fileContent = featureFileReader.ReadToEnd();21 var language = dialectServices.GetLanguage(fileContent);22 var gherkinDialect = dialectServices.GetGherkinDialect(language);23 var gherkinListener = new GherkinParserListener(sourceFilePath);24 GherkinScanner scanner = new GherkinScanner(gherkinDialect, fileContent);25 scanner.Scan(gherkinListener);26 Feature feature = gherkinListener.GetResult();27 if (gherkinListener.Errors.Count > 0)28 throw new SpecFlowParserException(gherkinListener.Errors);29 Debug.Assert(feature != null, "If there were no errors, the feature cannot be null");30 feature.Language = language.LanguageForConversions.Name;31 return feature;32 }33 }34}...
Parser
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Gherkin;7using Gherkin.Ast;8{9 {10 static void Main(string[] args)11 {12 var parser = new Parser();13 var feature = parser.Parse(@"Feature: Calculator14 Then the result should be 120 on the screen");15 Console.WriteLine("Feature Name: " + feature.Name);16 Console.WriteLine("Feature Description: " + feature.Description);17 Console.WriteLine("Feature Children: " + feature.Children);18 Console.WriteLine("Feature Keyword: " + feature.Keyword);19 Console.WriteLine("Feature Language: " + feature.Language);20 Console.WriteLine("Feature Location: " + feature.Location);21 Console.WriteLine("Feature Tags: " + feature.Tags);22 Console.ReadLine();23 }24 }25}
Parser
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Gherkin;7{8 {9 static void Main(string[] args)10 {11 Gherkin.Parser parser = new Gherkin.Parser();12 var feature = parser.Parse("Feature: Test13 Given I have 10 cukes in my belly");14 Console.WriteLine(feature.Name);15 Console.WriteLine(feature.Scenarios.First().Name);16 Console.WriteLine(feature.Scenarios.First().Steps.First().Text);17 Console.ReadLine();18 }19 }20}
Parser
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Gherkin;7using Gherkin.Ast;8{9 {10 static void Main(string[] args)11 {12 Then I should have 5 dollars";13 Parser parser = new Parser();14 Feature feature = parser.Parse(featureText);15 Console.WriteLine("Feature Name: {0}", feature.Name);16 Console.ReadKey();17 }18 }19}
Parser
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using Gherkin;7{8 {9 static void Main(string[] args)10 {11 ";12 var parser = new Parser();13 var feature = parser.Parse(feature);14 Console.WriteLine("Feature Name: {0}", feature.Name);15 Console.WriteLine("Feature Description: {0}", feature.Description);16 Console.WriteLine("Scenario Name: {0}", feature.Children[0].Name);17 Console.WriteLine("Scenario Description: {0}", feature.Children[0].Description);18 Console.WriteLine("Step Name: {0}", feature.Children[0].Steps[0].Name);19 Console.WriteLine("Step Keyword: {0}", feature.Children[0].Steps[0].Keyword);20 Console.WriteLine("Step Keyword: {0}", feature.Children[0].Steps[1].Keyword);21 Console.WriteLine("Step Keyword: {0}", feature.Children[0].Steps[2].Keyword);22 Console.ReadLine();23 }24 }25}
Parser
Using AI Code Generation
1Gherkin.Parser parser = new Gherkin.Parser();2Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: Calculator3 Then the result should be 120 on the screen");4Gherkin.Parser parser = new Gherkin.Parser();5Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: Calculator6 Then the result should be 120 on the screen");7Gherkin.Parser parser = new Gherkin.Parser();8Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: Calculator9 Then the result should be 120 on the screen");10Gherkin.Parser parser = new Gherkin.Parser();11Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: Calculator12 Then the result should be 120 on the screen");13Gherkin.Parser parser = new Gherkin.Parser();14Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: Calculator15 Then the result should be 120 on the screen");16Gherkin.Parser parser = new Gherkin.Parser();17Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: Calculator
Parser
Using AI Code Generation
1using System;2using Gherkin;3using Gherkin.Ast;4{5 {6 static void Main(string[] args)7 {8 And I should be able to logout";9 var parser = new Parser();10 GherkinDocument gherkinDocument = parser.Parse(feature);11 Console.WriteLine(gherkinDocument.Feature.Name);12 foreach (ScenarioDefinition scenario in gherkinDocument.Feature.Children)13 {14 Console.WriteLine(scenario.Name);15 foreach (Step step in scenario.Steps)16 {17 Console.WriteLine(step.Keyword + step.Text);18 }19 }20 }21 }22}
Parser
Using AI Code Generation
1var parser = new Parser();2var feature = parser.Parse("Feature: My feature");3var parser = new Parser();4var feature = parser.Parse("Feature: My feature");5var parser = new Parser();6var feature = parser.Parse("Feature: My feature");7var parser = new Parser();8var feature = parser.Parse("Feature: My feature");9var parser = new Parser();10var feature = parser.Parse("Feature: My feature");11var parser = new Parser();12var feature = parser.Parse("Feature: My feature");13var parser = new Parser();14var feature = parser.Parse("Feature: My feature");15var parser = new Parser();16var feature = parser.Parse("Feature: My feature");17var parser = new Parser();18var feature = parser.Parse("Feature: My feature");19var parser = new Parser();20var feature = parser.Parse("Feature: My feature");21var parser = new Parser();22var feature = parser.Parse("Feature: My feature");
Parser
Using AI Code Generation
1var parser = new Parser();2var feature = parser.Parse("Feature: 13");4var scenario = feature.ScenarioDefinitions[0] as Scenario;5var step = scenario.Steps[0];6var stepText = step.Text;7var stepArgument = step.Argument;8var docString = stepArgument as DocString;9var docStringContent = docString.Content;10var docStringContentType = docString.ContentType;11var dataTable = stepArgument as DataTable;12var dataTableRow = dataTable.Rows;13var dataTableRow1 = dataTableRow[0];14var dataTableRow1 = dataTableRow[0];
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!!