Best Gherkin-dotnet code snippet using Gherkin.Parser.Parse
GherkinExecutorTests.cs
Source:GherkinExecutorTests.cs
...25 [TestClass]26 public class GherkinExecutorTests27 {28 [TestMethod]29 public async Task Execute_WhenGherkinParseResultIsInCacheButNoStepActions_DoesNotCallParser()30 {31 //Arrange32 ProviderResult providerResult = new ProviderResult();33 IEnumerable<ProviderSourceDataset> datasets = new[]34 {35 new ProviderSourceDataset()36 };37 IEnumerable<TestScenario> testScenarios = new[]38 {39 new TestScenario40 {41 Id = "scenario-1"42 }43 };44 BuildProject buildProject = new BuildProject();45 IGherkinParser gherkinParser = CreateGherkinParser();46 GherkinParseResult gherkinParseResult = new GherkinParseResult();47 string cacheKey = $"{CacheKeys.GherkinParseResult}scenario-1";48 ICacheProvider cacheProvider = CreateCacheProvider();49 cacheProvider50 .GetAsync<GherkinParseResult>(Arg.Is(cacheKey), Arg.Any<JsonSerializerSettings>())51 .Returns(gherkinParseResult);52 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);53 //Act54 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);55 //Assert56 await57 gherkinParser58 .DidNotReceive()59 .Parse(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<BuildProject>());60 }61 [TestMethod]62 public async Task Execute_WhenGherkinParseResultIsInCacheWithStepActionButAborted_DoesNotCallParserDoesNotAddDependencies()63 {64 //Arrange65 ProviderResult providerResult = new ProviderResult();66 IEnumerable<ProviderSourceDataset> datasets = new[]67 {68 new ProviderSourceDataset()69 };70 IEnumerable<TestScenario> testScenarios = new[]71 {72 new TestScenario73 {74 Id = "scenario-1"75 }76 };77 BuildProject buildProject = new BuildProject();78 IGherkinParser gherkinParser = CreateGherkinParser();79 GherkinParseResult stepActionherkinParseResult = new GherkinParseResult { Abort = true };80 81 IStepAction stepAction = Substitute.For<IStepAction>();82 stepAction83 .Execute(Arg.Is(providerResult), Arg.Is(datasets))84 .Returns(stepActionherkinParseResult);85 GherkinParseResult gherkinParseResult = new GherkinParseResult();86 gherkinParseResult87 .StepActions88 .Add(stepAction);89 string cacheKey = $"{CacheKeys.GherkinParseResult}scenario-1";90 ICacheProvider cacheProvider = CreateCacheProvider();91 cacheProvider92 .GetAsync<GherkinParseResult>(Arg.Is(cacheKey), Arg.Any<JsonSerializerSettings>())93 .Returns(gherkinParseResult);94 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);95 //Act96 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);97 //Assert98 await99 gherkinParser100 .DidNotReceive()101 .Parse(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<BuildProject>());102 scenarioResults103 .Count()104 .Should()105 .Be(1);106 scenarioResults107 .First()108 .StepsExecuted109 .Should()110 .Be(0);111 }112 [TestMethod]113 public async Task Execute_WhenGherkinParseResultIsInCacheWithStepActionAndResultHasDependencies_DoesNotCallParserCreatesResult()114 {115 //Arrange116 ProviderResult providerResult = new ProviderResult();117 IEnumerable<ProviderSourceDataset> datasets = new[]118 {119 new ProviderSourceDataset()120 };121 IEnumerable<TestScenario> testScenarios = new[]122 {123 new TestScenario124 {125 Id = "scenario-1"126 }127 };128 BuildProject buildProject = new BuildProject();129 IGherkinParser gherkinParser = CreateGherkinParser();130 GherkinParseResult stepActionherkinParseResult = new GherkinParseResult();131 stepActionherkinParseResult132 .Dependencies133 .Add(new Dependency("ds1", "f1", "value"));134 IStepAction stepAction = Substitute.For<IStepAction>();135 stepAction136 .Execute(Arg.Is(providerResult), Arg.Is(datasets))137 .Returns(stepActionherkinParseResult);138 GherkinParseResult gherkinParseResult = new GherkinParseResult();139 gherkinParseResult140 .StepActions141 .Add(stepAction);142 string cacheKey = $"{CacheKeys.GherkinParseResult}scenario-1";143 ICacheProvider cacheProvider = CreateCacheProvider();144 cacheProvider145 .GetAsync<GherkinParseResult>(Arg.Is(cacheKey), Arg.Any<JsonSerializerSettings>())146 .Returns(gherkinParseResult);147 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);148 //Act149 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);150 //Assert151 await152 gherkinParser153 .DidNotReceive()154 .Parse(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<BuildProject>());155 scenarioResults156 .Count()157 .Should()158 .Be(1);159 scenarioResults160 .First()161 .Dependencies162 .Count()163 .Should()164 .Be(1);165 scenarioResults166 .First()167 .Scenario168 .Id169 .Should()170 .Be("scenario-1");171 scenarioResults172 .First()173 .HasErrors174 .Should()175 .BeFalse();176 scenarioResults177 .First()178 .StepsExecuted179 .Should()180 .Be(1);181 }182 [TestMethod]183 public async Task Execute_WhenGherkinParseResultIsInCacheWithStepActionAndResultHasErrors_DoesNotCallParserCreatesResultWithErrors()184 {185 //Arrange186 ProviderResult providerResult = new ProviderResult();187 IEnumerable<ProviderSourceDataset> datasets = new[]188 {189 new ProviderSourceDataset()190 };191 IEnumerable<TestScenario> testScenarios = new[]192 {193 new TestScenario194 {195 Id = "scenario-1"196 }197 };198 BuildProject buildProject = new BuildProject();199 IGherkinParser gherkinParser = CreateGherkinParser();200 GherkinParseResult stepActionherkinParseResult = new GherkinParseResult("An error");201 stepActionherkinParseResult202 .Dependencies203 .Add(new Dependency("ds1", "f1", "value"));204 IStepAction stepAction = Substitute.For<IStepAction>();205 stepAction206 .Execute(Arg.Is(providerResult), Arg.Is(datasets))207 .Returns(stepActionherkinParseResult);208 GherkinParseResult gherkinParseResult = new GherkinParseResult();209 gherkinParseResult210 .StepActions211 .Add(stepAction);212 string cacheKey = $"{CacheKeys.GherkinParseResult}scenario-1";213 ICacheProvider cacheProvider = CreateCacheProvider();214 cacheProvider215 .GetAsync<GherkinParseResult>(Arg.Is(cacheKey), Arg.Any<JsonSerializerSettings>())216 .Returns(gherkinParseResult);217 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);218 //Act219 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);220 //Assert221 await222 gherkinParser223 .DidNotReceive()224 .Parse(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<BuildProject>());225 scenarioResults226 .Count()227 .Should()228 .Be(1);229 scenarioResults230 .First()231 .Dependencies232 .Count()233 .Should()234 .Be(1);235 scenarioResults236 .First()237 .Scenario238 .Id239 .Should()240 .Be("scenario-1");241 scenarioResults242 .First()243 .HasErrors244 .Should()245 .BeTrue();246 }247 [TestMethod]248 public async Task Execute_WhenGherkinParseResultIsInCacheWithTeoStepActionAndResultHasErrors_DoesNotCallParserCreatesResultWithErrors()249 {250 //Arrange251 ProviderResult providerResult = new ProviderResult();252 IEnumerable<ProviderSourceDataset> datasets = new[]253 {254 new ProviderSourceDataset()255 };256 IEnumerable<TestScenario> testScenarios = new[]257 {258 new TestScenario259 {260 Id = "scenario-1"261 }262 };263 BuildProject buildProject = new BuildProject();264 IGherkinParser gherkinParser = CreateGherkinParser();265 GherkinParseResult stepActionherkinParseResult1 = new GherkinParseResult("An error");266 stepActionherkinParseResult1267 .Dependencies268 .Add(new Dependency("ds1", "f1", "value"));269 GherkinParseResult stepActionherkinParseResult2 = new GherkinParseResult();270 stepActionherkinParseResult2271 .Dependencies272 .Add(new Dependency("ds1", "f1", "value"));273 IStepAction stepAction1 = Substitute.For<IStepAction>();274 stepAction1275 .Execute(Arg.Is(providerResult), Arg.Is(datasets))276 .Returns(stepActionherkinParseResult1);277 IStepAction stepAction2 = Substitute.For<IStepAction>();278 stepAction2279 .Execute(Arg.Is(providerResult), Arg.Is(datasets))280 .Returns(stepActionherkinParseResult2);281 GherkinParseResult gherkinParseResult = new GherkinParseResult();282 gherkinParseResult283 .StepActions284 .AddRange(new[] { stepAction1, stepAction2 });285 string cacheKey = $"{CacheKeys.GherkinParseResult}scenario-1";286 ICacheProvider cacheProvider = CreateCacheProvider();287 cacheProvider288 .GetAsync<GherkinParseResult>(Arg.Is(cacheKey), Arg.Any<JsonSerializerSettings>())289 .Returns(gherkinParseResult);290 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);291 //Act292 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);293 //Assert294 await295 gherkinParser296 .DidNotReceive()297 .Parse(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<BuildProject>());298 scenarioResults299 .Count()300 .Should()301 .Be(1);302 scenarioResults303 .First()304 .Dependencies305 .Count()306 .Should()307 .Be(2);308 scenarioResults309 .First()310 .HasErrors311 .Should()312 .BeTrue();313 scenarioResults314 .First()315 .StepsExecuted316 .Should()317 .Be(2);318 }319 [TestMethod]320 public async Task Execute_WhenGherkinParseResultIsNotInCacheWithTeoStepActionAndResultHasError_CreatesResultWithErrors()321 {322 //Arrange323 ProviderResult providerResult = new ProviderResult();324 IEnumerable<ProviderSourceDataset> datasets = new[]325 {326 new ProviderSourceDataset()327 };328 IEnumerable<TestScenario> testScenarios = new[]329 {330 new TestScenario331 {332 Id = "scenario-1",333 Current = new TestScenarioVersion334 {335 Gherkin = "gherkin"336 },337 SpecificationId = "spec1"338 }339 };340 BuildProject buildProject = new BuildProject();341 GherkinParseResult stepActionherkinParseResult1 = new GherkinParseResult("An error");342 stepActionherkinParseResult1343 .Dependencies344 .Add(new Dependency("ds1", "f1", "value"));345 GherkinParseResult stepActionherkinParseResult2 = new GherkinParseResult();346 stepActionherkinParseResult2347 .Dependencies348 .Add(new Dependency("ds1", "f1", "value"));349 IStepAction stepAction1 = Substitute.For<IStepAction>();350 stepAction1351 .Execute(Arg.Is(providerResult), Arg.Is(datasets))352 .Returns(stepActionherkinParseResult1);353 IStepAction stepAction2 = Substitute.For<IStepAction>();354 stepAction2355 .Execute(Arg.Is(providerResult), Arg.Is(datasets))356 .Returns(stepActionherkinParseResult2);357 GherkinParseResult gherkinParseResult = new GherkinParseResult();358 gherkinParseResult359 .StepActions360 .AddRange(new[] { stepAction1, stepAction2 });361 IGherkinParser gherkinParser = CreateGherkinParser();362 gherkinParser363 .Parse(Arg.Is("spec1"), Arg.Is("gherkin"), Arg.Is(buildProject))364 .Returns(gherkinParseResult);365 string cacheKey = $"{CacheKeys.GherkinParseResult}scenario-1";366 ICacheProvider cacheProvider = CreateCacheProvider();367 cacheProvider368 .GetAsync<GherkinParseResult>(Arg.Is(cacheKey), Arg.Any<JsonSerializerSettings>())369 .Returns((GherkinParseResult)null);370 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);371 //Act372 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);373 //Assert374 scenarioResults375 .Count()376 .Should()377 .Be(1);378 scenarioResults379 .First()380 .Dependencies381 .Count()382 .Should()383 .Be(2);384 scenarioResults385 .First()386 .HasErrors387 .Should()388 .BeTrue();389 scenarioResults390 .First()391 .StepsExecuted392 .Should()393 .Be(2);394 }395 [TestMethod]396 public async Task Execute_WhenCalculationNameDatasetAndFieldNameCaseAreAllPerfectMatches_ThenTestIsSuccessfullyExecuted()397 {398 // Arrange399 string dataSetName = "Test Dataset";400 string fieldName = "URN";401 string calcName = "Test Calc";402 string gherkin = $"Given the dataset '{dataSetName}' field '{fieldName}' is equal to '100050'\n\nThen the result for '{calcName}' is greater than '12' ";403 ICodeMetadataGeneratorService codeMetadataGeneratorService = CreateCodeMetadataGeneratorService();404 codeMetadataGeneratorService405 .GetTypeInformation(Arg.Any<byte[]>())406 .Returns(new List<TypeInformation>407 {408 new TypeInformation { Type = "Calculations", Methods = new List<MethodInformation> { new MethodInformation { FriendlyName = calcName } } },409 new TypeInformation { Type = "Datasets", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = dataSetName, Type = "DSType" } }},410 new TypeInformation { Type = "DSType", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = fieldName, Type = "String" } }}411 });412 IProviderResultsRepository providerResultsRepository = CreateProviderResultsRepository();413 ITestRunnerResiliencePolicies resiliencePolicies = CreateResiliencePolicies();414 IStepParserFactory stepParserFactory = new StepParserFactory(codeMetadataGeneratorService, providerResultsRepository, resiliencePolicies);415 ICalculationsRepository calculationsRepository = CreateCalculationsRepository();416 calculationsRepository417 .GetAssemblyBySpecificationId(Arg.Is("spec1"))418 .Returns(new byte[1]);419 ILogger logger = CreateLogger();420 GherkinParser gherkinParser = new GherkinParser(stepParserFactory, calculationsRepository, logger);421 ICacheProvider cacheProvider = CreateCacheProvider();422 423 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);424 ProviderResult providerResult = new ProviderResult425 {426 Provider = new ProviderSummary { Id = "prov1" },427 CalculationResults = new List<CalculationResult>428 {429 new CalculationResult { Calculation = new Common.Models.Reference { Name = calcName }, Value = (decimal)14 }430 }431 };432 IEnumerable<ProviderSourceDataset> datasets = new List<ProviderSourceDataset>433 {434 new ProviderSourceDataset435 {436 DataRelationship = new Common.Models.Reference { Name = dataSetName },437 Current = new ProviderSourceDatasetVersion438 {439 Rows = new List<Dictionary<string, object>>440 {441 new Dictionary<string, object> { { fieldName, 100050 } }442 }443 }444 }445 };446 IEnumerable<TestScenario> testScenarios = new List<TestScenario>447 {448 new TestScenario { Id = "ts1", Name = "Test Scenario 1", SpecificationId = "spec1", Current = new TestScenarioVersion { Gherkin = gherkin } }449 };450 BuildProject buildProject = new BuildProject { Build = new Build() };451 // Act452 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);453 // Assert454 scenarioResults455 .Should()456 .HaveCount(1);457 scenarioResults458 .First().HasErrors459 .Should()460 .BeFalse("there should be no errors");461 scenarioResults462 .First().StepsExecuted463 .Should()464 .Be(scenarioResults.First().TotalSteps, "all steps should be executed");465 }466 [TestMethod]467 public async Task Execute_WhenCalculationNameCaseIsDifferent_ThenTestIsSuccessfullyExecuted()468 {469 // Arrange470 string dataSetName = "Test Dataset";471 string fieldName = "URN";472 string calcName = "Test Calc";473 string gherkin = $"Given the dataset '{dataSetName}' field '{fieldName}' is equal to '100050'\n\nThen the result for '{calcName.ToLower()}' is greater than '12' ";474 ICodeMetadataGeneratorService codeMetadataGeneratorService = CreateCodeMetadataGeneratorService();475 codeMetadataGeneratorService476 .GetTypeInformation(Arg.Any<byte[]>())477 .Returns(new List<TypeInformation>478 {479 new TypeInformation { Type = "Calculations", Methods = new List<MethodInformation> { new MethodInformation { FriendlyName = calcName } } },480 new TypeInformation { Type = "Datasets", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = dataSetName, Type = "DSType" } }},481 new TypeInformation { Type = "DSType", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = fieldName, Type = "String" } }}482 });483 IProviderResultsRepository providerResultsRepository = CreateProviderResultsRepository();484 ITestRunnerResiliencePolicies resiliencePolicies = CreateResiliencePolicies();485 IStepParserFactory stepParserFactory = new StepParserFactory(codeMetadataGeneratorService, providerResultsRepository, resiliencePolicies);486 ICalculationsRepository calculationsRepository = CreateCalculationsRepository();487 calculationsRepository488 .GetAssemblyBySpecificationId(Arg.Is("spec1"))489 .Returns(new byte[1]);490 ILogger logger = CreateLogger();491 GherkinParser gherkinParser = new GherkinParser(stepParserFactory, calculationsRepository, logger);492 ICacheProvider cacheProvider = CreateCacheProvider();493 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);494 ProviderResult providerResult = new ProviderResult495 {496 Provider = new ProviderSummary { Id = "prov1" },497 CalculationResults = new List<CalculationResult>498 {499 new CalculationResult { Calculation = new Common.Models.Reference { Name = calcName }, Value = (decimal) 14 }500 }501 };502 IEnumerable<ProviderSourceDataset> datasets = new List<ProviderSourceDataset>503 {504 new ProviderSourceDataset505 {506 DataRelationship = new Common.Models.Reference { Name = dataSetName },507 Current = new ProviderSourceDatasetVersion508 {509 Rows = new List<Dictionary<string, object>>510 {511 new Dictionary<string, object> { { fieldName, 100050 } }512 }513 }514 }515 };516 IEnumerable<TestScenario> testScenarios = new List<TestScenario>517 {518 new TestScenario { Id = "ts1", Name = "Test Scenario 1", SpecificationId = "spec1", Current = new TestScenarioVersion { Gherkin = gherkin } }519 };520 BuildProject buildProject = new BuildProject { Build = new Build() };521 // Act522 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);523 // Assert524 scenarioResults525 .Should()526 .HaveCount(1);527 scenarioResults528 .First().HasErrors529 .Should()530 .BeFalse("there should be no errors");531 scenarioResults532 .First().StepsExecuted533 .Should()534 .Be(scenarioResults.First().TotalSteps, "all steps should be executed");535 }536 [TestMethod]537 public async Task Execute_WhenDatasetNameCaseIsDifferent_ThenTestIsSuccessfullyExecuted()538 {539 // Arrange540 string dataSetName = "Test Dataset";541 string fieldName = "URN";542 string calcName = "Test Calc";543 string gherkin = $"Given the dataset '{dataSetName.ToLower()}' field '{fieldName}' is equal to '100050'\n\nThen the result for '{calcName}' is greater than '12' ";544 ICodeMetadataGeneratorService codeMetadataGeneratorService = CreateCodeMetadataGeneratorService();545 codeMetadataGeneratorService546 .GetTypeInformation(Arg.Any<byte[]>())547 .Returns(new List<TypeInformation>548 {549 new TypeInformation { Type = "Calculations", Methods = new List<MethodInformation> { new MethodInformation { FriendlyName = calcName } } },550 new TypeInformation { Type = "Datasets", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = dataSetName, Type = "DSType" } }},551 new TypeInformation { Type = "DSType", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = fieldName, Type = "String" } }}552 });553 IProviderResultsRepository providerResultsRepository = CreateProviderResultsRepository();554 ITestRunnerResiliencePolicies resiliencePolicies = CreateResiliencePolicies();555 IStepParserFactory stepParserFactory = new StepParserFactory(codeMetadataGeneratorService, providerResultsRepository, resiliencePolicies);556 ICalculationsRepository calculationsRepository = CreateCalculationsRepository();557 calculationsRepository558 .GetAssemblyBySpecificationId(Arg.Is("spec1"))559 .Returns(new byte[1]);560 ILogger logger = CreateLogger();561 GherkinParser gherkinParser = new GherkinParser(stepParserFactory, calculationsRepository, logger);562 ICacheProvider cacheProvider = CreateCacheProvider();563 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);564 ProviderResult providerResult = new ProviderResult565 {566 Provider = new ProviderSummary { Id = "prov1" },567 CalculationResults = new List<CalculationResult>568 {569 new CalculationResult { Calculation = new Common.Models.Reference { Name = calcName }, Value = (decimal)14 }570 }571 };572 IEnumerable<ProviderSourceDataset> datasets = new List<ProviderSourceDataset>573 {574 new ProviderSourceDataset575 {576 DataRelationship = new Common.Models.Reference { Name = dataSetName },577 Current = new ProviderSourceDatasetVersion578 {579 Rows = new List<Dictionary<string, object>>580 {581 new Dictionary<string, object> { { fieldName, 100050 } }582 }583 }584 }585 };586 IEnumerable<TestScenario> testScenarios = new List<TestScenario>587 {588 new TestScenario { Id = "ts1", Name = "Test Scenario 1", SpecificationId = "spec1", Current = new TestScenarioVersion { Gherkin = gherkin } }589 };590 BuildProject buildProject = new BuildProject { Build = new Build() };591 // Act592 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);593 // Assert594 scenarioResults595 .Should()596 .HaveCount(1);597 scenarioResults598 .First().HasErrors599 .Should()600 .BeFalse("there should be no errors");601 scenarioResults602 .First().StepsExecuted603 .Should()604 .Be(scenarioResults.First().TotalSteps, "all steps should be executed");605 }606 [TestMethod]607 public async Task Execute_WhenFieldNameCaseIsDifferent_ThenTestIsSuccessfullyExecuted()608 {609 // Arrange610 string dataSetName = "Test Dataset";611 string fieldName = "URN";612 string calcName = "Test Calc";613 string gherkin = $"Given the dataset '{dataSetName}' field '{fieldName.ToLower()}' is equal to '100050'\n\nThen the result for '{calcName}' is greater than '12' ";614 ICodeMetadataGeneratorService codeMetadataGeneratorService = CreateCodeMetadataGeneratorService();615 codeMetadataGeneratorService616 .GetTypeInformation(Arg.Any<byte[]>())617 .Returns(new List<TypeInformation>618 {619 new TypeInformation { Type = "Calculations", Methods = new List<MethodInformation> { new MethodInformation { FriendlyName = calcName } } },620 new TypeInformation { Type = "Datasets", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = dataSetName, Type = "DSType" } }},621 new TypeInformation { Type = "DSType", Properties = new List<PropertyInformation> { new PropertyInformation { FriendlyName = fieldName, Type = "String" } }}622 });623 IProviderResultsRepository providerResultsRepository = CreateProviderResultsRepository();624 ITestRunnerResiliencePolicies resiliencePolicies = CreateResiliencePolicies();625 IStepParserFactory stepParserFactory = new StepParserFactory(codeMetadataGeneratorService, providerResultsRepository, resiliencePolicies);626 ICalculationsRepository calculationsRepository = CreateCalculationsRepository();627 calculationsRepository628 .GetAssemblyBySpecificationId(Arg.Is("spec1"))629 .Returns(new byte[1]);630 ILogger logger = CreateLogger();631 GherkinParser gherkinParser = new GherkinParser(stepParserFactory, calculationsRepository, logger);632 ICacheProvider cacheProvider = CreateCacheProvider();633 GherkinExecutor gherkinExecutor = CreateGherkinExecutor(gherkinParser, cacheProvider);634 ProviderResult providerResult = new ProviderResult635 {636 Provider = new ProviderSummary { Id = "prov1" },637 CalculationResults = new List<CalculationResult>638 {639 new CalculationResult { Calculation = new Common.Models.Reference { Name = calcName }, Value = (decimal)14 }640 }641 };642 IEnumerable<ProviderSourceDataset> datasets = new List<ProviderSourceDataset>643 {644 new ProviderSourceDataset645 {646 DataRelationship = new Common.Models.Reference { Name = dataSetName },647 Current = new ProviderSourceDatasetVersion648 {649 Rows = new List<Dictionary<string, object>>650 {651 new Dictionary<string, object> { { fieldName, 100050 } }652 }653 }654 }655 };656 IEnumerable<TestScenario> testScenarios = new List<TestScenario>657 {658 new TestScenario { Id = "ts1", Name = "Test Scenario 1", SpecificationId = "spec1", Current = new TestScenarioVersion { Gherkin = gherkin } }659 };660 BuildProject buildProject = new BuildProject { Build = new Build() };661 // Act662 IEnumerable<ScenarioResult> scenarioResults = await gherkinExecutor.Execute(providerResult, datasets, testScenarios, buildProject);663 // Assert664 scenarioResults665 .Should()666 .HaveCount(1);667 scenarioResults668 .First().HasErrors669 .Should()670 .BeFalse("there should be no errors");671 scenarioResults672 .First().StepsExecuted673 .Should()674 .Be(scenarioResults.First().TotalSteps, "all steps should be executed");675 }676 private static GherkinExecutor CreateGherkinExecutor(IGherkinParser gherkinParser = null, ICacheProvider cacheProvider = null, ITestRunnerResiliencePolicies resiliencePolicies = null)677 {678 return new GherkinExecutor(679 gherkinParser ?? CreateGherkinParser(),680 cacheProvider ?? CreateCacheProvider(),681 resiliencePolicies ?? CreateResiliencePolicies());682 }683 private static IGherkinParser CreateGherkinParser()684 {685 return Substitute.For<IGherkinParser>();686 }687 private static ICacheProvider CreateCacheProvider()688 {689 return Substitute.For<ICacheProvider>();690 }691 private static ITestRunnerResiliencePolicies CreateResiliencePolicies()692 {693 return TestRunnerResilienceTestHelper.GenerateTestPolicies();694 }695 private static ICodeMetadataGeneratorService CreateCodeMetadataGeneratorService()696 {697 return Substitute.For<ICodeMetadataGeneratorService>();698 }699 private static IProviderResultsRepository CreateProviderResultsRepository()...
GherkinParserFacts.cs
Source:GherkinParserFacts.cs
2using NUnit.Framework;3using Vinegar;4namespace VinegarTests5{6 public class GherkinParserFacts7 {8 [TestFixture]9 public class ParseMethod10 {11 [Test]12 public void Parses_feature_name()13 {14 // Arrange15 string featureText = "Feature: Test";16 var parser = new GherkinParser();17 // Act18 Feature feature;19 bool parseSuccess = parser.TryParse(featureText, out feature);20 // Assert21 Assert.That(feature.Title, Is.EqualTo("Test"));22 }23 [Test]24 public void Parses_feature_description_multiline()25 {26 // Arrange27 string featureText = @"Feature: Test28 In order to test this description,29 as a developer30 I want to write a test";31 var parser = new GherkinParser();32 // Act33 Feature feature;34 bool parseSuccess = parser.TryParse(featureText, out feature);35 // Assert36 Assert.That(feature.Description, Is.EqualTo(@"In order to test this description,37as a developer38I want to write a test"));39 }40 [Test]41 public void Parses_feature_description_multiline_with_comment()42 {43 // Arrange44 string featureText = @"Feature: Test45 In order to test this description,46 as a developer47 # Comment line 48 I want to write a test";49 var parser = new GherkinParser();50 // Act51 Feature feature;52 bool parseSuccess = parser.TryParse(featureText, out feature);53 // Assert54 Assert.That(feature.Description, Is.EqualTo(@"In order to test this description,55as a developer56I want to write a test"));57 }58 [Test]59 public void Parses_feature_description_singleline()60 {61 // Arrange62 string featureText = @"Feature: Test63 A single line description";64 var parser = new GherkinParser();65 // Act66 Feature feature;67 bool parseSuccess = parser.TryParse(featureText, out feature);68 // Assert69 Assert.That(feature.Description, Is.EqualTo(@"A single line description"));70 }71 [Test]72 public void Parses_feature_tags()73 {74 // Arrange75 string featureText = @"@Test @Tag76 Feature: Test";77 var parser = new GherkinParser();78 // Act79 Feature feature;80 bool parseSuccess = parser.TryParse(featureText, out feature);81 // Assert82 Assert.That(feature.Tags.Count, Is.EqualTo(2));83 Assert.That(feature.Tags[0], Is.EqualTo("Test"));84 Assert.That(feature.Tags[1], Is.EqualTo("Tag"));85 }86 [Test]87 public void Parses_feature_tags_split_by_comment()88 {89 // Arrange90 string featureText = @"@Test @Tag91 # Rando comment92 Feature: Test";93 var parser = new GherkinParser();94 // Act95 Feature feature;96 bool parseSuccess = parser.TryParse(featureText, out feature);97 // Assert98 Assert.That(feature.Tags.Count, Is.EqualTo(2));99 Assert.That(feature.Tags[0], Is.EqualTo("Test"));100 Assert.That(feature.Tags[1], Is.EqualTo("Tag"));101 }102 [Test]103 public void Parses_scenario_tags()104 {105 // Arrange106 string featureText = @"Feature: Test107 @Test @Tag108 Scenario: Test";109 var parser = new GherkinParser();110 // Act111 Feature feature;112 bool parseSuccess = parser.TryParse(featureText, out feature);113 // Assert114 Scenario scenario = feature.Scenarios[0];115 Assert.That(scenario.Tags.Count, Is.EqualTo(2));116 Assert.That(scenario.Tags[0], Is.EqualTo("Test"));117 Assert.That(scenario.Tags[1], Is.EqualTo("Tag"));118 }119 [Test]120 public void Parses_scenario_tags_split_by_comment()121 {122 // Arrange123 string featureText = @"Feature: Test124 @Test @Tag125 # Rando comment126 Scenario: Test";127 var parser = new GherkinParser();128 // Act129 Feature feature;130 bool parseSuccess = parser.TryParse(featureText, out feature);131 // Assert132 Scenario scenario = feature.Scenarios[0];133 Assert.That(scenario.Tags.Count, Is.EqualTo(2));134 Assert.That(scenario.Tags[0], Is.EqualTo("Test"));135 Assert.That(scenario.Tags[1], Is.EqualTo("Tag"));136 }137 [Test]138 public void Parses_scenario_name()139 {140 // Arrange141 string featureText = @"Feature: Test142 Scenario: Test Scenario";143 var parser = new GherkinParser();144 // Act145 Feature feature;146 bool parseSuccess = parser.TryParse(featureText, out feature);147 // Assert148 Assert.That(feature.Scenarios.Count, Is.EqualTo(1), "A scenario was expected to be parsed");149 Assert.That(feature.Scenarios[0].Title, Is.EqualTo("Test Scenario"));150 }151 [Test]152 public void Parses_given_step()153 {154 // Arrange155 string featureText = @"Feature: Test156 Scenario: Test Scenario157 Given I have a scenario with a single given";158 var parser = new GherkinParser();159 // Act160 Feature feature;161 bool parseSuccess = parser.TryParse(featureText, out feature);162 // Assert163 Step step = feature.Scenarios[0].Steps[0];164 Assert.That(step.Type, Is.EqualTo(StepType.Given));165 Assert.That(step.Text, Is.EqualTo("I have a scenario with a single given"));166 }167 [Test]168 public void Parses_given_step_with_and()169 {170 // Arrange171 string featureText = @"Feature: Test172 Scenario: Test Scenario173 Given I have a scenario with a single given174 And I also have an and";175 var parser = new GherkinParser();176 // Act177 Feature feature;178 bool parseSuccess = parser.TryParse(featureText, out feature);179 // Assert180 Assert.That(feature.Scenarios[0].Steps.Count, Is.EqualTo(2));181 Scenario scenario = feature.Scenarios[0];182 Assert.That(scenario.Steps[0].Type, Is.EqualTo(StepType.Given));183 Assert.That(scenario.Steps[0].Text, Is.EqualTo("I have a scenario with a single given"));184 Assert.That(scenario.Steps[1].Type, Is.EqualTo(StepType.Given));185 Assert.That(scenario.Steps[1].Text, Is.EqualTo("I also have an and"));186 }187 [Test]188 public void Parses_when_step()189 {190 // Arrange191 string featureText = @"Feature: Test192 Scenario: Test Scenario193 When I run the test";194 var parser = new GherkinParser();195 // Act196 Feature feature;197 bool parseSuccess = parser.TryParse(featureText, out feature);198 // Assert199 Step step = feature.Scenarios[0].Steps[0];200 Assert.That(step.Type, Is.EqualTo(StepType.When));201 Assert.That(step.Text, Is.EqualTo("I run the test"));202 }203 [Test]204 public void Parses_then_step()205 {206 // Arrange207 string featureText = @"Feature: Test208 Scenario: Test Scenario209 Then The test should pass";210 var parser = new GherkinParser();211 // Act212 Feature feature;213 bool parseSuccess = parser.TryParse(featureText, out feature);214 // Assert215 Step step = feature.Scenarios[0].Steps[0];216 Assert.That(step.Type, Is.EqualTo(StepType.Then));217 Assert.That(step.Text, Is.EqualTo("The test should pass"));218 }219 [Test]220 public void Parses_all_step_types_together()221 {222 // Arrange223 string featureText = @"Feature: Test224 Scenario: Test Scenario225 Given I have a scenario with a single given226 When I run the test227 Then The test should pass";228 var parser = new GherkinParser();229 // Act230 Feature feature;231 bool parseSuccess = parser.TryParse(featureText, out feature);232 // Assert233 Assert.That(feature.Scenarios[0].Steps.Count, Is.EqualTo(3));234 Scenario scenario = feature.Scenarios[0];235 Assert.That(scenario.Steps[0].Type, Is.EqualTo(StepType.Given));236 Assert.That(scenario.Steps[0].Text, Is.EqualTo("I have a scenario with a single given"));237 Assert.That(scenario.Steps[1].Type, Is.EqualTo(StepType.When));238 Assert.That(scenario.Steps[1].Text, Is.EqualTo("I run the test"));239 Assert.That(scenario.Steps[2].Type, Is.EqualTo(StepType.Then));240 Assert.That(scenario.Steps[2].Text, Is.EqualTo("The test should pass"));241 }242 [Test]243 public void Parses_multiple_scenarios()244 {245 // Arrange246 string featureText = @"Feature: Test247 Scenario: Test Scenario 1248 Given I have the first test249 When I assert250 Then It should be unique251 Scenario: Test Scenario 2252 Given I have the second test253 When I assert254 Then It should be unique";255 var parser = new GherkinParser();256 // Act257 Feature feature;258 bool parseSuccess = parser.TryParse(featureText, out feature);259 // Assert260 Assert.That(feature.Scenarios.Count, Is.EqualTo(2));261 Assert.That(feature.Scenarios[0].Title == "Test Scenario 1");262 Assert.That(feature.Scenarios[1].Title == "Test Scenario 2");263 }264 [Test]265 public void Parses_DataTable()266 {267 // Arrange268 string featureText = @"Feature: Test269 Scenario: Test Scenario 1270 Given I have a test271 When I assert272 Then It should have a data table:273 | Field | Value |274 | Age | 29 |275 | Name | Scriv |";276 var parser = new GherkinParser();277 // Act278 Feature feature;279 bool parseSuccess = parser.TryParse(featureText, out feature);280 // Assert281 DataTable table = feature.Scenarios.Last().Steps.Last().DataTable;282 Assert.That(table, Is.Not.Null);283 // Headers284 Assert.That(table.Headers.Count, Is.EqualTo(2));285 Assert.That(table.Headers[0], Is.EqualTo("Field"));286 Assert.That(table.Headers[1], Is.EqualTo("Value"));287 Assert.That(table.Rows.Count, Is.EqualTo(2));288 // First row289 Assert.That(table.Rows[0]["Field"], Is.EqualTo("Age"));290 Assert.That(table.Rows[0]["Value"], Is.EqualTo("29"));291 Assert.That(table.Rows[0].Cells.Count, Is.EqualTo(2));292 // Second row293 Assert.That(table.Rows[1]["Field"], Is.EqualTo("Name"));294 Assert.That(table.Rows[1]["Value"], Is.EqualTo("Scriv"));295 Assert.That(table.Rows[1].Cells.Count, Is.EqualTo(2));296 }297 [Test]298 public void Parses_DataTable_WithTrailingWhitespace()299 {300 // Arrange301 string featureText = @"Feature: Test302 Scenario: Test Scenario 1303 Given I have a test304 When I assert305 Then It should have a data table:306 | Field | Value |307 | Age | 29 |308 | Name | Scriv | 309";310 var parser = new GherkinParser();311 // Act312 Feature feature;313 bool parseSuccess = parser.TryParse(featureText, out feature);314 // Assert315 DataTable table = feature.Scenarios.Last().Steps.Last().DataTable;316 Assert.That(table, Is.Not.Null);317 // Headers318 Assert.That(table.Headers.Count, Is.EqualTo(2));319 Assert.That(table.Headers[0], Is.EqualTo("Field"));320 Assert.That(table.Headers[1], Is.EqualTo("Value"));321 Assert.That(table.Rows.Count, Is.EqualTo(2));322 // First row323 Assert.That(table.Rows[0]["Field"], Is.EqualTo("Age"));324 Assert.That(table.Rows[0]["Value"], Is.EqualTo("29"));325 Assert.That(table.Rows[0].Cells.Count, Is.EqualTo(2));326 // Second row327 Assert.That(table.Rows[1]["Field"], Is.EqualTo("Name"));...
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}...
TokenParser.cs
Source:TokenParser.cs
...10using NBehave.Narrator.Framework.TextParsing;11using NBehave.VS2010.Plugin.Editor.Glyphs;12namespace NBehave.VS2010.Plugin.Tagging13{14 public class TokenParser : IDisposable15 {16 private List<GherkinParseEvent> events = new List<GherkinParseEvent>();17 private List<Feature> features = new List<Feature>();18 private string lastParsedContent = "";19 private readonly object lockObj = new object();20 private readonly ManualResetEvent isParsing = new ManualResetEvent(true);21 private readonly Queue<ITextSnapshot> nextTextSnapshotToParse = new Queue<ITextSnapshot>();22 private readonly ITextBuffer buffer;23 private bool disposed;24 public event EventHandler<TokenParserEventArgs> TokenParserEvent;25 public TokenParser(ITextBuffer buffer)26 {27 this.buffer = buffer;28 nextTextSnapshotToParse.Enqueue(buffer.CurrentSnapshot);29 buffer.Changed += BufferChanged;30 TokenParserEvent += (s, e) => { };31 Parallel.Invoke(DoParse);32 }33 public IEnumerable<GherkinParseEvent> Events { get { return events; } }34 public IEnumerable<Feature> Features { get { return features; } }35 public bool LastParseFailed()36 {37 return Events.Any(_ => _.GherkinTokenType == GherkinTokenType.SyntaxError);38 }39 public void ForceParse(ITextSnapshot snapshot)40 {41 isParsing.WaitOne(100);42 nextTextSnapshotToParse.Enqueue(snapshot);43 DoParse();44 NotifyChanges(snapshot, events);45 }46 private void BufferChanged(object sender, TextContentChangedEventArgs e)47 {48 lock (lockObj)49 nextTextSnapshotToParse.Enqueue(e.After);50 Parallel.Invoke(DoParse);51 }52 private void DoParse()53 {54 if (!isParsing.WaitOne(0) || !nextTextSnapshotToParse.Any())55 return;56 isParsing.Reset();57 string content = string.Empty;58 try59 {60 while (nextTextSnapshotToParse.Any())61 {62 var textSnapshot = GetTextSnapshotToParse();63 content = textSnapshot.GetText(0, textSnapshot.Length);64 List<GherkinParseEvent> oldEvents;65 Tuple<List<GherkinParseEvent>, List<Feature>> newEvents;66 lock (lockObj)67 {68 oldEvents = events;69 newEvents = new Tuple<List<GherkinParseEvent>, List<Feature>>(events, features);70 }71 if (content != lastParsedContent)72 newEvents = Parse(content);73 lock (lockObj)74 {75 events = newEvents.Item1;76 features = newEvents.Item2;77 }78 var e = newEvents.Item1;79 var newAndChanged = (e.Any(_ => _.GherkinTokenType == GherkinTokenType.SyntaxError) || LinesAddedOrRemoved(e, oldEvents))80 ? e : e.Except(oldEvents).ToList();81 if (newAndChanged.Any())82 NotifyChanges(textSnapshot, newAndChanged);83 }84 }85 catch (Exception)86 { }87 finally88 {89 lastParsedContent = content;90 isParsing.Set();91 }92 }93 private ITextSnapshot GetTextSnapshotToParse()94 {95 ITextSnapshot textSnapshot = null;96 lock (nextTextSnapshotToParse)97 {98 while (nextTextSnapshotToParse.Any())99 textSnapshot = nextTextSnapshotToParse.Dequeue();100 }101 return textSnapshot;102 }103 private bool LinesAddedOrRemoved(IEnumerable<GherkinParseEvent> newEvents, IEnumerable<GherkinParseEvent> oldEvents)104 {105 int a = (newEvents.Any()) ? newEvents.SelectMany(_ => _.Tokens).Max(_ => _.LineInFile.Line) : -1;106 int b = (oldEvents.Any()) ? oldEvents.SelectMany(_ => _.Tokens).Max(_ => _.LineInFile.Line) : -1;107 return a != b;108 }109 private void NotifyChanges(ITextSnapshot textSnapshot, IEnumerable<GherkinParseEvent> newAndChanged)110 {111 var linesChanged = newAndChanged112 .Where(_ => _.Tokens.Any())113 .Select(_ => _.Tokens[0].LineInFile.Line)114 .Distinct().ToArray();115 int from = linesChanged.Min();116 int to = linesChanged.Max();117 var previousEvent = new GherkinParseEvent(GherkinTokenType.Feature, new Token("", new LineInFile(0)));118 for (int i = from; i <= to; i++)119 {120 ITextSnapshotLine line = textSnapshot.GetLineFromLineNumber(i);121 var s = new SnapshotSpan(textSnapshot, line.Start, line.Length);122 GherkinParseEvent evt = newAndChanged.FirstOrDefault(_ => _.Tokens.Any() && _.Tokens[0].LineInFile.Line == i) ??123 new GherkinParseEvent(previousEvent.GherkinTokenType, new Token("", new LineInFile(i)));124 TokenParserEvent.Invoke(this, new TokenParserEventArgs(evt, s));125 previousEvent = evt;126 }127 var lastLine = textSnapshot.GetLineFromLineNumber(to);128 TokenParserEvent.Invoke(this, new TokenParserEventArgs(new GherkinParseEvent(GherkinTokenType.Eof), new SnapshotSpan(textSnapshot, lastLine.Start, 0)));129 }130 private Tuple<List<GherkinParseEvent>, List<Feature>> Parse(string content)131 {132 var features = new List<Feature>();133 var nBehaveConfiguration = NBehaveConfiguration.New.DontIsolateInAppDomain().SetDryRun(true);134 var gherkinScenarioParser = new GherkinScenarioParser(nBehaveConfiguration);135 gherkinScenarioParser.FeatureEvent += (s, e) => features.Add(e.EventInfo);136 var gherkinEventListener = new GherkinEventListener();137 IListener listener = new CompositeGherkinListener(gherkinEventListener, gherkinScenarioParser);138 var newEvents = new List<GherkinParseEvent>();139 var parser = new Parser(listener);140 try141 {142 parser.Scan(content);143 }144 catch (Exception e)145 {146 var match = new Regex(@"^Line: (?<lineNumber>\d+). (\w+\s*)+ '(?<lineText>.*)'$").Match(e.Message);147 if (match.Success && (e is ParseException))148 {149 var line = int.Parse(match.Groups["lineNumber"].Value);150 var lineInFile = new LineInFile(line - 1);151 var text = match.Groups["lineText"].Value;152 var token = new Token(text, lineInFile);153 var error = new Token(e.Message, lineInFile);154 newEvents.Add(new GherkinParseEvent(GherkinTokenType.SyntaxError, token, error));155 }156 }157 finally158 {159 newEvents.AddRange(ToZeroBasedLines(gherkinEventListener).ToList());160 }161 return new Tuple<List<GherkinParseEvent>, List<Feature>>(newEvents, features);162 }163 private IEnumerable<GherkinParseEvent> ToZeroBasedLines(GherkinEventListener gherkinEventListener)164 {165 return gherkinEventListener.Events166 .Select(_ => new GherkinParseEvent(_.GherkinTokenType, _.Tokens.Select(t => new Token(t.Content, new LineInFile(t.LineInFile.Line - 1))).ToArray()));167 }168 public void Dispose()169 {170 GC.SuppressFinalize(this);171 if (disposed)172 return;173 disposed = true;174 buffer.Changed -= BufferChanged;175 }176 }177}...
GherkinParser.cs
Source:GherkinParser.cs
...15using Gherkin.Ast;16using Serilog;17namespace CalculateFunding.Services.TestRunner18{19 public class GherkinParser : IGherkinParser20 {21 static IDictionary<StepType, string> stepExpressions = new Dictionary<StepType, string>22 {23 { StepType.AssertCalcDataset, SyntaxConstants.assertCalcDatasetExpression },24 { StepType.Datasets, SyntaxConstants.SourceDatasetStep },25 { StepType.Provider, SyntaxConstants.providerExpression },26 { StepType.AssertCalc, SyntaxConstants.assertCalcExpression },27 };28 private readonly IStepParserFactory _stepParserFactory;29 private readonly ICalculationsRepository _calculationsRepository;30 private readonly ILogger _logger;31 public GherkinParser(IStepParserFactory stepParserFactory, ICalculationsRepository calculationsRepository, ILogger logger)32 {33 Guard.ArgumentNotNull(stepParserFactory, nameof(stepParserFactory));34 Guard.ArgumentNotNull(calculationsRepository, nameof(calculationsRepository));35 Guard.ArgumentNotNull(logger, nameof(logger));36 _stepParserFactory = stepParserFactory;37 _calculationsRepository = calculationsRepository;38 _logger = logger;39 }40 public async Task<GherkinParseResult> Parse(string specificationId, string gherkin, BuildProject buildProject)41 {42 Guard.IsNullOrWhiteSpace(specificationId, nameof(specificationId));43 Guard.IsNullOrWhiteSpace(gherkin, nameof(gherkin));44 Guard.ArgumentNotNull(buildProject, nameof(buildProject));45 buildProject.Build.Assembly = await _calculationsRepository.GetAssemblyBySpecificationId(specificationId);46 GherkinParseResult result = new GherkinParseResult();47 Parser parser = new Parser();48 try49 {50 StringBuilder builder = new StringBuilder();51 builder.AppendLine("Feature: Feature Wrapper");52 builder.AppendLine(" Scenario: Scenario Wrapper");53 builder.Append(gherkin);54 using (StringReader reader = new StringReader(builder.ToString()))55 {56 GherkinDocument document = null;57 try58 {59 document = parser.Parse(reader);60 }61 catch (InvalidOperationException ex)62 {63 string buildProjectId = buildProject.Id;64 _logger.Error(ex, $"Gherkin parser error for build project {{buildProjectId}}: {builder.ToString()}", buildProjectId);65 throw;66 }67 if (document.Feature?.Children != null)68 {69 foreach (Scenario scenario in document.Feature?.Children)70 {71 if (!scenario.Steps.IsNullOrEmpty())72 {73 foreach (Step step in scenario.Steps)74 {75 IEnumerable<KeyValuePair<StepType, string>> expression = stepExpressions.Where(m => Regex.IsMatch(step.Text, m.Value, RegexOptions.IgnoreCase));76 if (expression.Any())77 {78 IStepParser stepParser = _stepParserFactory.GetStepParser(expression.First().Key);79 if (stepParser == null)80 {81 result.AddError("The supplied gherkin could not be parsed", step.Location.Line, step.Location.Column);82 }83 else84 {85 await stepParser.Parse(step, expression.First().Value, result, buildProject);86 }87 }88 else89 {90 result.AddError("The supplied gherkin could not be parsed", step.Location.Line, step.Location.Column);91 }92 string keyword = step.Keyword?.ToLowerInvariant().Trim();93 }94 }95 else96 {97 result.AddError("The supplied gherkin could not be parsed", 0, 0);98 }99 }100 }101 }102 }103 catch (CompositeParserException exception)104 {105 foreach (ParserException error in exception.Errors)106 {107 result.AddError(error.Message, error.Location.Line, error.Location.Column);108 }109 }110 return result;111 }112 }113}...
GherkinExecutor.cs
Source:GherkinExecutor.cs
...17namespace CalculateFunding.Services.TestRunner18{19 public class GherkinExecutor : IGherkinExecutor, IHealthChecker20 {21 private readonly IGherkinParser _parser;22 private readonly ICacheProvider _cacheProvider;23 private readonly AsyncPolicy _cacheProviderPolicy;24 public GherkinExecutor(IGherkinParser parser,25 ICacheProvider cacheProvider,26 ITestRunnerResiliencePolicies resiliencePolicies)27 {28 Guard.ArgumentNotNull(parser, nameof(parser));29 Guard.ArgumentNotNull(cacheProvider, nameof(cacheProvider));30 Guard.ArgumentNotNull(resiliencePolicies?.CacheProviderRepository, nameof(resiliencePolicies.CacheProviderRepository));31 _parser = parser;32 _cacheProvider = cacheProvider;33 _cacheProviderPolicy = resiliencePolicies.CacheProviderRepository;34 }35 public async Task<ServiceHealth> IsHealthOk()36 {37 ServiceHealth health = new ServiceHealth();38 (bool Ok, string Message) = await _cacheProvider.IsHealthOk();39 health.Name = nameof(GherkinExecutor);40 health.Dependencies.Add(new DependencyHealth { HealthOk = Ok, DependencyName = GetType().Name, Message = Message });41 return health;42 }43 public async Task<IEnumerable<ScenarioResult>> Execute(ProviderResult providerResult, IEnumerable<ProviderSourceDataset> datasets,44 IEnumerable<TestScenario> testScenarios, BuildProject buildProject)45 {46 Guard.ArgumentNotNull(providerResult, nameof(providerResult));47 Guard.ArgumentNotNull(datasets, nameof(datasets));48 Guard.ArgumentNotNull(testScenarios, nameof(testScenarios));49 Guard.ArgumentNotNull(buildProject, nameof(buildProject));50 IList<ScenarioResult> scenarioResults = new List<ScenarioResult>();51 foreach (TestScenario scenario in testScenarios)52 {53 ScenarioResult scenarioResult = new ScenarioResult54 {55 Scenario = new Reference(scenario.Id, scenario.Name)56 };57 GherkinParseResult parseResult = await GetGherkinParseResult(scenario, buildProject);58 if (parseResult != null && !parseResult.StepActions.IsNullOrEmpty())59 {60 scenarioResult.TotalSteps = parseResult.StepActions.Count;61 scenarioResult.StepsExecuted = 0;62 foreach (IStepAction action in parseResult.StepActions)63 {64 GherkinParseResult result = action.Execute(providerResult, datasets);65 if (result.Abort) break;66 if (!result.Dependencies.IsNullOrEmpty())67 {68 foreach (Dependency resultDependency in result.Dependencies)69 {70 if (!scenarioResult.Dependencies.Contains(resultDependency))71 {72 scenarioResult.Dependencies.Add(resultDependency);73 }74 }75 }76 if (result.HasErrors)77 {78 scenarioResult.Errors.AddRange(result.Errors);79 }80 scenarioResult.StepsExecuted++;81 }82 }83 scenarioResults.Add(scenarioResult);84 }85 return scenarioResults;86 }87 private async Task<GherkinParseResult> GetGherkinParseResult(TestScenario testScenario, BuildProject buildProject)88 {89 Guard.ArgumentNotNull(testScenario, nameof(testScenario));90 Guard.ArgumentNotNull(buildProject, nameof(buildProject));91 string cacheKey = $"{CacheKeys.GherkinParseResult}{testScenario.Id}";92 JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()93 {94 TypeNameHandling = TypeNameHandling.All95 };96 GherkinParseResult gherkinParseResult = await _cacheProviderPolicy.ExecuteAsync(() => _cacheProvider.GetAsync<GherkinParseResult>(cacheKey, jsonSerializerSettings));97 if (gherkinParseResult == null)98 {99 gherkinParseResult = await _parser.Parse(testScenario.SpecificationId, testScenario.Current.Gherkin, buildProject);100 if (gherkinParseResult != null && !gherkinParseResult.StepActions.IsNullOrEmpty())101 {102 await _cacheProviderPolicy.ExecuteAsync(() => _cacheProvider.SetAsync<GherkinParseResult>(cacheKey, gherkinParseResult, TimeSpan.FromHours(24), true, jsonSerializerSettings));103 }104 }105 return gherkinParseResult;106 }107 }108}...
GherkinParserService.cs
Source:GherkinParserService.cs
...14using Polly;15using Serilog;16namespace CalculateFunding.Services.TestRunner.Services17{18 public class GherkinParserService : IGherkinParserService19 {20 private readonly IGherkinParser _gherkinParser;21 private readonly ILogger _logger;22 private readonly ICalculationsApiClient _calcsApiClient;23 private readonly AsyncPolicy _calcsApiClientPolicy;24 private readonly IMapper _mapper;25 public GherkinParserService(26 IGherkinParser gherkinParser,27 ILogger logger,28 ICalculationsApiClient calcsApiClient,29 ITestRunnerResiliencePolicies resiliencePolicies,30 IMapper mapper)31 {32 Guard.ArgumentNotNull(resiliencePolicies?.CalculationsApiClient, nameof(resiliencePolicies.CalculationsApiClient));33 Guard.ArgumentNotNull(gherkinParser, nameof(gherkinParser));34 Guard.ArgumentNotNull(logger, nameof(logger));35 Guard.ArgumentNotNull(calcsApiClient, nameof(calcsApiClient));36 _gherkinParser = gherkinParser;37 _logger = logger;38 _calcsApiClient = calcsApiClient;39 _mapper = mapper;40 _calcsApiClientPolicy = resiliencePolicies.CalculationsApiClient;41 }42 public async Task<IActionResult> ValidateGherkin(ValidateGherkinRequestModel model)43 {44 if (model == null)45 {46 _logger.Error("Null model was provided to ValidateGherkin");47 return new BadRequestObjectResult("Null or empty specification id provided");48 }49 if (string.IsNullOrWhiteSpace(model.SpecificationId))50 {51 _logger.Error("No specification id was provided to ValidateGherkin");52 return new BadRequestObjectResult("Null or empty specification id provided");53 }54 if (string.IsNullOrWhiteSpace(model.Gherkin))55 {56 _logger.Error("Null or empty gherkin was provided to ValidateGherkin");57 return new BadRequestObjectResult("Null or empty gherkin name provided");58 }59 BuildProject buildProject = _mapper.Map<BuildProject>(await _calcsApiClientPolicy.ExecuteAsync(() => _calcsApiClient.GetBuildProjectBySpecificationId(model.SpecificationId)));60 if (buildProject == null || buildProject.Build == null)61 {62 _logger.Error($"Failed to find a valid build project for specification id: {model.SpecificationId}");63 return new StatusCodeResult((int)HttpStatusCode.PreconditionFailed);64 }65 GherkinParseResult parseResult = await _gherkinParser.Parse(model.SpecificationId, model.Gherkin, buildProject);66 if (parseResult.HasErrors)67 {68 _logger.Information($"Gherkin parser failed validation with ");69 }70 return new OkObjectResult(parseResult.Errors);71 }72 }73}...
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}...
Parse
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 Then the result should be 120 on the screen";13 Parser parser = new Parser();14 GherkinDocument gherkinDocument = parser.Parse(feature);15 Console.WriteLine(gherkinDocument.Feature.Name);16 Console.ReadKey();17 }18 }19}
Parse
Using AI Code Generation
1using Gherkin;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";12 var parser = new Parser();13 var gherkinDocument = parser.Parse(feature);14 Console.ReadLine();15 }16 }17}18using Gherkin;19using System;20using System.Collections.Generic;21using System.Linq;22using System.Text;23using System.Threading.Tasks;24{25 {26 static void Main(string[] args)27 {28";29 var parser = new Parser();30 var gherkinDocument = parser.Parse(feature);31 Console.ReadLine();32 }33 }34}35using Gherkin;36using System;37using System.Collections.Generic;38using System.Linq;39using System.Text;40using System.Threading.Tasks;41{42 {43 static void Main(string[] args)44 {45";46 var parser = new Parser();47 var gherkinDocument = parser.Parse(feature);48 Console.ReadLine();49 }50 }51}52using Gherkin;53using System;54using System.Collections.Generic;55using System.Linq;56using System.Text;57using System.Threading.Tasks;58{59 {60 static void Main(string[] args)61 {62";63 var parser = new Parser();64 var gherkinDocument = parser.Parse(feature);65 Console.ReadLine();66 }67 }68}69using Gherkin;70using System;71using System.Collections.Generic;72using System.Linq;73using System.Text;74using System.Threading.Tasks;
Parse
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 Parser parser = new Parser();13 Feature feature = parser.Parse("C:\\Users\\sathya\\Desktop\\GherkinParser\\GherkinParser\\feature.feature");14 Console.WriteLine(feature.Name);15 Console.WriteLine(feature.Description);16 Console.WriteLine(feature.Keyword);17 Console.WriteLine(feature.Language);18 Console.WriteLine(feature.Location);19 Console.WriteLine(feature.Tags);20 Console.WriteLine(feature.Children);21 Console.WriteLine(feature.Comments);22 Console.WriteLine(feature.Background);23 Console.WriteLine(feature.Scenarios);24 Console.WriteLine(feature.ScenarioDefinitions);25 }26 }27}28using System;29using System.Collections.Generic;30using System.Linq;31using System.Text;32using System.Threading.Tasks;33using Gherkin;34using Gherkin.Ast;35{36 {37 static void Main(string[] args)38 {39 Parser parser = new Parser();40 Feature feature = parser.Parse("C:\\Users\\sathya\\Desktop\\GherkinParser\\GherkinParser\\feature.feature");41 Console.WriteLine(feature.Name);42 Console.WriteLine(feature.Description);
Parse
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;8using System.IO;9using System.Reflection;10{11 {12 static void Main(string[] args)13 {14 string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "feature1.txt");15 string featureText = File.ReadAllText(filePath);16 var parser = new Gherkin.Parser();17 var gherkinDocument = parser.Parse(featureText);18 Console.WriteLine(gherkinDocument.Feature.Name);19 Console.WriteLine(gherkinDocument.Feature.Description);20 foreach (var scenario in gherkinDocument.Feature.Children.OfType<Scenario>())21 {22 Console.WriteLine(scenario.Name);23 foreach (var step in scenario.Steps)24 {25 Console.WriteLine(step.Keyword + step.Text);26 }27 }28 Console.ReadKey();29 }30 }31}32using System;33using System.Collections.Generic;34using System.Linq;35using System.Text;36using System.Threading.Tasks;37using Gherkin;38using Gherkin.Ast;39using System.IO;40using System.Reflection;41{42 {43 static void Main(string[] args)44 {45 string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "feature1.txt");46 string featureText = File.ReadAllText(filePath);47 var parser = new Gherkin.Parser();48 var gherkinDocument = parser.Parse(featureText);49 Console.WriteLine(gherkinDocument.Feature.Name);50 Console.WriteLine(gherkinDocument.Feature.Description);51 foreach (var scenario in gherkinDocument.Feature.Children.OfType<ScenarioOutline>())52 {53 Console.WriteLine(scenario.Name);54 foreach (var step in scenario.Steps)55 {56 Console.WriteLine(step.Keyword + step.Text);57 }58 }59 Console.ReadKey();60 }61 }62}63using System;64using System.Collections.Generic;65using System.Linq;66using System.Text;67using System.Threading.Tasks;
Parse
Using AI Code Generation
1using System;2using System.IO;3using System.Text;4using Gherkin;5{6 {7 static void Main(string[] args)8 {9 Parser parser = new Parser();10 string gherkin = File.ReadAllText("D:\\1.feature");11 var feature = parser.Parse(gherkin);12 Console.WriteLine(feature.ToString());13 Console.ReadLine();14 }15 }16}17using System;18using System.IO;19using System.Text;20using Gherkin;21{22 {23 static void Main(string[] args)24 {25 Parser parser = new Parser();26 string gherkin = File.ReadAllText("D:\\2.feature");27 var feature = parser.Parse(gherkin);28 Console.WriteLine(feature.ToString());29 Console.ReadLine();30 }31 }32}33using System;34using System.IO;35using System.Text;36using Gherkin;37{38 {39 static void Main(string[] args)40 {41 Parser parser = new Parser();42 string gherkin = File.ReadAllText("D:\\3.feature");43 var feature = parser.Parse(gherkin);44 Console.WriteLine(feature.ToString());45 Console.ReadLine();46 }47 }48}49using System;50using System.IO;51using System.Text;52using Gherkin;53{54 {55 static void Main(string[] args)56 {57 Parser parser = new Parser();58 string gherkin = File.ReadAllText("D:\\4.feature");59 var feature = parser.Parse(gherkin);60 Console.WriteLine(feature.ToString());61 Console.ReadLine();62 }63 }64}65using System;66using System.IO;67using System.Text;68using Gherkin;69{70 {71 static void Main(string[] args)72 {73 Parser parser = new Parser();74 string gherkin = File.ReadAllText("D:\\5.feature");75 var feature = parser.Parse(gherkin);76 Console.WriteLine(feature.ToString());
Parse
Using AI Code Generation
1Gherkin.Parser parser = new Gherkin.Parser();2Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: MyFeature3");4Gherkin.Ast.Feature feature = gherkinDocument.Feature;5var scenario = feature.Children[0] as Gherkin.Ast.Scenario;6var step = scenario.Steps[0] as Gherkin.Ast.Step;7Console.WriteLine(step.Text);8Console.ReadKey();9Gherkin.Parser parser = new Gherkin.Parser();10Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: MyFeature11");12Gherkin.Ast.GherkinDocument gherkinDocument = parser.Parse("Feature: MyFeature13");14Gherkin.Ast.Feature feature = gherkinDocument.Feature;15Gherkin.Ast.Feature feature = gherkinDocument.Feature;16var scenario = feature.Children[0] as Gherkin.Ast.Scenario;17var step = scenario.Steps[0] as Gherkin.Ast.Step;18Console.WriteLine(step.Text);
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!!