Best Gherkin-dotnet code snippet using Gherkin.Ast.DataTable
ScenarioOutlineExecutorTests.cs
Source:ScenarioOutlineExecutorTests.cs
...339 [InlineData("of bigger numbers", 0)]340 [InlineData("of bigger numbers", 1)]341 [InlineData("of large numbers", 0)]342 [InlineData("of large numbers", 1)]343 public async Task ExecuteScenarioOutlineAsync_Executes_ScenarioStep_With_DataTable(344 string exampleName,345 int exampleRowIndex)346 {347 //arrange.348 var scenarioName = "scenario123";349 var featureInstance = new FeatureWithDataTableScenarioStep();350 var output = new Mock<ITestOutputHelper>();351 featureInstance.InternalOutput = output.Object;352 _featureFileRepository.Setup(r => r.GetByFilePath($"{nameof(FeatureWithDataTableScenarioStep)}.feature"))353 .Returns(new FeatureFile(FeatureWithDataTableScenarioStep.CreateGherkinDocument(scenarioName,354 new Gherkin.Ast.DataTable(new Gherkin.Ast.TableRow[]355 {356 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]357 {358 new Gherkin.Ast.TableCell(null, "First argument"),359 new Gherkin.Ast.TableCell(null, "Second argument"),360 new Gherkin.Ast.TableCell(null, "Result"),361 }),362 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]363 {364 new Gherkin.Ast.TableCell(null, "1"),365 new Gherkin.Ast.TableCell(null, "2"),366 new Gherkin.Ast.TableCell(null, "3"),367 }),368 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]369 {370 new Gherkin.Ast.TableCell(null, "a"),371 new Gherkin.Ast.TableCell(null, "b"),372 new Gherkin.Ast.TableCell(null, "c"),373 })374 }))))375 .Verifiable();376 //act.377 await _sut.ExecuteScenarioOutlineAsync(featureInstance, scenarioName, exampleName, exampleRowIndex);378 //assert.379 _featureFileRepository.Verify();380 Assert.NotNull(featureInstance.ReceivedDataTable);381 Assert.Equal(3, featureInstance.ReceivedDataTable.Rows.Count());382 AssertDataTableCell(0, 0, "First argument");383 AssertDataTableCell(0, 1, "Second argument");384 AssertDataTableCell(0, 2, "Result");385 AssertDataTableCell(1, 0, "1");386 AssertDataTableCell(1, 1, "2");387 AssertDataTableCell(1, 2, "3");388 AssertDataTableCell(2, 0, "a");389 AssertDataTableCell(2, 1, "b");390 AssertDataTableCell(2, 2, "c");391 void AssertDataTableCell(int rowIndex, int cellIndex, string value)392 {393 Assert.True(featureInstance.ReceivedDataTable.Rows.Count() > rowIndex);394 Assert.NotNull(featureInstance.ReceivedDataTable.Rows.ElementAt(rowIndex));395 Assert.True(featureInstance.ReceivedDataTable.Rows.ElementAt(rowIndex).Cells.Count() > cellIndex);396 Assert.NotNull(featureInstance.ReceivedDataTable.Rows.ElementAt(rowIndex).Cells.ElementAt(cellIndex));397 Assert.Equal("First argument", featureInstance.ReceivedDataTable.Rows.ElementAt(0).Cells.ElementAt(0).Value);398 }399 }400 private sealed class FeatureWithDataTableScenarioStep : Feature401 {402 public Gherkin.Ast.DataTable ReceivedDataTable { get; private set; }403 public const string Steptext = @"Step text 1212121";404 [Given(Steptext)]405 public void When_DataTable_Is_Expected(Gherkin.Ast.DataTable dataTable)406 {407 ReceivedDataTable = dataTable;408 }409 public static Gherkin.Ast.GherkinDocument CreateGherkinDocument(410 string outlineName,411 Gherkin.Ast.StepArgument stepArgument = null)412 {413 return new Gherkin.Ast.GherkinDocument(414 new Gherkin.Ast.Feature(new Gherkin.Ast.Tag[0], null, null, null, null, null, new Gherkin.Ast.ScenarioDefinition[]415 {416 new Gherkin.Ast.ScenarioOutline(417 new Gherkin.Ast.Tag[0],418 null,419 null,420 outlineName,421 null,...
StepMethodInfoTests.cs
Source:StepMethodInfoTests.cs
...149 [When("something")]150 public void When_Something_Method() { }151 }152 [Fact]153 public void FromMethodInfo_Creates_StepMethodInfo_With_DataTable()154 {155 //arrange.156 var featureInstance = new FeatureWithDataTableScenarioStep();157 //act.158 var sut = StepMethodInfo.FromMethodInfo(159 featureInstance.GetType().GetMethod(nameof(FeatureWithDataTableScenarioStep.When_DataTable_Is_Expected)),160 featureInstance161 );162 //assert.163 Assert.NotNull(sut);164 }165 [Fact]166 public void DigestScenarioStepValues_Sets_DataTable_Value()167 {168 //arrange.169 var featureInstance = new FeatureWithDataTableScenarioStep();170 var sut = StepMethodInfo.FromMethodInfo(171 featureInstance.GetType().GetMethod(nameof(FeatureWithDataTableScenarioStep.When_DataTable_Is_Expected)),172 featureInstance173 );174 var step = new Gherkin.Ast.Step(175 null,176 "When",177 FeatureWithDataTableScenarioStep.Steptext,178 new Gherkin.Ast.DataTable(new Gherkin.Ast.TableRow[]179 {180 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]181 {182 new Gherkin.Ast.TableCell(null, "First argument"),183 new Gherkin.Ast.TableCell(null, "Second argument"),184 new Gherkin.Ast.TableCell(null, "Result"),185 }),186 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]187 {188 new Gherkin.Ast.TableCell(null, "1"),189 new Gherkin.Ast.TableCell(null, "2"),190 new Gherkin.Ast.TableCell(null, "3"),191 }),192 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]193 {194 new Gherkin.Ast.TableCell(null, "a"),195 new Gherkin.Ast.TableCell(null, "b"),196 new Gherkin.Ast.TableCell(null, "c"),197 })198 }));199 //act.200 sut.DigestScenarioStepValues(step);201 //assert.202 var digestedText = sut.GetDigestedStepText();203 Assert.Equal(FeatureWithDataTableScenarioStep.Steptext, digestedText);204 }205 private sealed class FeatureWithDataTableScenarioStep : Feature206 {207 public Gherkin.Ast.DataTable ReceivedDataTable { get; private set; }208 public const string Steptext = "Some step text";209 [When(Steptext)]210 public void When_DataTable_Is_Expected(Gherkin.Ast.DataTable dataTable)211 {212 ReceivedDataTable = dataTable;213 }214 }215 [Fact]216 public void FromMethodInfo_Creates_StepMethodInfo_With_DocString()217 {218 //arrange.219 var featureInstance = new FeatureWithDocStringScenarioStep();220 //act.221 var sut = StepMethodInfo.FromMethodInfo(222 featureInstance.GetType().GetMethod(nameof(FeatureWithDocStringScenarioStep.Step_With_DocString_Argument)),223 featureInstance224 );225 //assert.226 Assert.NotNull(sut);...
DeveroomTagParser.cs
Source:DeveroomTagParser.cs
...117 stepTag.AddChild(118 new DeveroomTag(DeveroomTagTypes.StepKeyword,119 GetTextSpan(fileSnapshot, step.Location, step.Keyword),120 step.Keyword));121 if (step.Argument is DataTable dataTable)122 {123 var dataTableBlockTag = new DeveroomTag(DeveroomTagTypes.DataTable,124 GetBlockSpan(fileSnapshot, dataTable.Rows.First().Location,125 dataTable.Rows.Last().Location.Line),126 dataTable);127 stepTag.AddChild(dataTableBlockTag);128 var dataTableHeader = dataTable.Rows.FirstOrDefault();129 if (dataTableHeader != null)130 {131 TagRowCells(fileSnapshot, dataTableHeader, dataTableBlockTag, DeveroomTagTypes.DataTableHeader);132 }133 }134 else if (step.Argument is DocString docString)135 {136 stepTag.AddChild(137 new DeveroomTag(DeveroomTagTypes.DocString,138 GetBlockSpan(fileSnapshot, docString.Location,139 GetStepLastLine(step)),140 docString));141 }142 if (scenarioDefinition is ScenarioOutline)143 {144 AddPlaceholderTags(fileSnapshot, stepTag, step);145 }146 var match = bindingRegistry?.MatchStep(step, scenarioDefinitionTag);147 if (match != null)148 {149 if (match.HasDefined || match.HasAmbiguous)150 {151 stepTag.AddChild(new DeveroomTag(DeveroomTagTypes.DefinedStep,152 GetTextSpan(fileSnapshot, step.Location, step.Text, offset: step.Keyword.Length),153 match));154 if (!(scenarioDefinition is ScenarioOutline) || !step.Text.Contains("<"))155 {156 var parameterMatch = match.Items.FirstOrDefault(m => m.ParameterMatch != null)157 ?.ParameterMatch;158 AddParameterTags(fileSnapshot, parameterMatch, stepTag, step);159 }160 }161 if (match.HasUndefined)162 {163 stepTag.AddChild(new DeveroomTag(DeveroomTagTypes.UndefinedStep,164 GetTextSpan(fileSnapshot, step.Location, step.Text, offset: step.Keyword.Length),165 match));166 }167 if (match.HasErrors)168 {169 stepTag.AddChild(new DeveroomTag(DeveroomTagTypes.BindingError,170 GetTextSpan(fileSnapshot, step.Location, step.Text, offset: step.Keyword.Length),171 match.GetErrorMessage()));172 }173 }174 }175 if (scenarioDefinition is ScenarioOutline scenarioOutline)176 {177 foreach (var scenarioOutlineExample in scenarioOutline.Examples)178 {179 var examplesBlockTag = CreateDefinitionBlockTag(scenarioOutlineExample,180 DeveroomTagTypes.ExamplesBlock, fileSnapshot,181 GetExamplesLastLine(scenarioOutlineExample), scenarioDefinitionTag);182 if (scenarioOutlineExample.TableHeader != null)183 {184 TagRowCells(fileSnapshot, scenarioOutlineExample.TableHeader, examplesBlockTag,185 DeveroomTagTypes.ScenarioOutlinePlaceholder);186 }187 }188 }189 }190 private void TagRowCells(ITextSnapshot fileSnapshot, TableRow row, DeveroomTag parentTag, string tagType)191 {192 foreach (var cell in row.Cells)193 {194 parentTag.AddChild(new DeveroomTag(tagType,195 GetSpan(fileSnapshot, cell.Location, cell.Value.Length),196 cell));197 }198 }199 private void AddParameterTags(ITextSnapshot fileSnapshot, ParameterMatch parameterMatch, DeveroomTag stepTag, Step step)200 {201 foreach (var parameter in parameterMatch.StepTextParameters)202 {203 stepTag.AddChild(new DeveroomTag(DeveroomTagTypes.StepParameter,204 GetSpan(fileSnapshot, step.Location, parameter.Length, offset: step.Keyword.Length + parameter.Index),205 parameter));206 }207 }208 private void AddPlaceholderTags(ITextSnapshot fileSnapshot, DeveroomTag stepTag, Step step)209 {210 var placeholders = MatchedScenarioOutlinePlaceholder.MatchScenarioOutlinePlaceholders(step);211 foreach (var placeholder in placeholders)212 {213 stepTag.AddChild(new DeveroomTag(DeveroomTagTypes.ScenarioOutlinePlaceholder,214 GetSpan(fileSnapshot, step.Location, placeholder.Length, offset: step.Keyword.Length + placeholder.Index),215 placeholder));216 }217 }218 private DeveroomTag CreateDefinitionBlockTag(IHasDescription astNode, string tagType, ITextSnapshot fileSnapshot, int lastLine, DeveroomTag parentTag = null)219 {220 var span = GetBlockSpan(fileSnapshot, ((IHasLocation)astNode).Location, lastLine);221 var blockTag = new DeveroomTag(tagType, span, astNode);222 parentTag?.AddChild(blockTag);223 blockTag.AddChild(CreateDefinitionLineKeyword(fileSnapshot, astNode));224 if (astNode is IHasTags hasTags)225 {226 foreach (var gherkinTag in hasTags.Tags)227 {228 blockTag.AddChild(229 new DeveroomTag(DeveroomTagTypes.Tag,230 GetTextSpan(fileSnapshot, gherkinTag.Location, gherkinTag.Name), 231 gherkinTag));232 }233 }234 if (!string.IsNullOrEmpty(astNode.Description))235 {236 var startLineNumber = ((IHasLocation) astNode).Location.Line + 1;237 while (string.IsNullOrWhiteSpace(fileSnapshot.GetLineFromLineNumber(GetSnapshotLineNumber(startLineNumber, fileSnapshot)).GetText()))238 {239 startLineNumber++;240 }241 blockTag.AddChild(242 new DeveroomTag(DeveroomTagTypes.Description,243 GetBlockSpan(fileSnapshot, startLineNumber,244 CountLines(astNode.Description))));245 }246 return blockTag;247 }248 private static readonly Regex NewLineRe = new Regex(@"(\r\n|\n|\r)");249 private int CountLines(string text) =>250 NewLineRe.Matches(text).Count + 1;251 private DeveroomTag CreateDefinitionLineKeyword(ITextSnapshot fileSnapshot, IHasDescription hasDescription) =>252 new DeveroomTag(DeveroomTagTypes.DefinitionLineKeyword,253 GetTextSpan(fileSnapshot, ((IHasLocation)hasDescription).Location, hasDescription.Keyword, 1));254 private IEnumerable<DeveroomTag> GetAllTags(DeveroomTag tag)255 {256 yield return tag;257 foreach (var childTag in tag.ChildTags)258 foreach (var allChildTag in GetAllTags(childTag))259 yield return allChildTag;260 }261 private int GetScenarioDefinitionLastLine(StepsContainer stepsContainer)262 {263 if (stepsContainer is ScenarioOutline scenarioOutline)264 {265 var lastExamples = scenarioOutline.Examples.LastOrDefault();266 if (lastExamples != null)267 {268 return GetExamplesLastLine(lastExamples);269 }270 }271 var lastStep = stepsContainer.Steps.LastOrDefault();272 if (lastStep == null)273 return stepsContainer.Location.Line;274 return GetStepLastLine(lastStep);275 }276 private static int GetExamplesLastLine(Examples examples)277 {278 var lastRow = examples.TableBody?.LastOrDefault() ?? examples.TableHeader;279 if (lastRow != null)280 return lastRow.Location.Line;281 return examples.Location.Line;282 }283 private int GetStepLastLine(Step step)284 {285 if (step.Argument is DocString docStringArg)286 {287 int lineCount = CountLines(docStringArg.Content);288 return docStringArg.Location.Line + lineCount - 1 + 2;289 }290 if (step.Argument is DataTable dataTable)291 {292 return dataTable.Rows.Last().Location.Line;293 }294 return step.Location.Line;295 }296 private SnapshotSpan GetBlockSpan(ITextSnapshot snapshot, Location startLocation, int locationEndLine)297 {298 var startLine = GetSnapshotLine(startLocation, snapshot);299 var endLine = snapshot.GetLineFromLineNumber(GetSnapshotLineNumber(locationEndLine, snapshot));300 return new SnapshotSpan(startLine.Start, endLine.End);301 }302 private SnapshotSpan GetBlockSpan(ITextSnapshot snapshot, int startLineNumber, int lineCount)303 {304 var startLine = snapshot.GetLineFromLineNumber(GetSnapshotLineNumber(startLineNumber, snapshot));...
FeatureClassTests.cs
Source:FeatureClassTests.cs
...193 CallStack.Add(new KeyValuePair<string, object[]>(nameof(NonMatchingStep4_after), null));194 }195 }196 [Fact]197 public void ExtractScnario_Extracts_Scenario_With_DataTable()198 {199 //arrange.200 var scenarioName = "scenario213";201 var featureInstance = new FeatureWithDataTableScenarioStep();202 var sut = FeatureClass.FromFeatureInstance(featureInstance);203 var gherknScenario = CreateGherkinDocument(scenarioName,204 new string[]205 {206 "When " + FeatureWithDataTableScenarioStep.Steptext207 },208 new Gherkin.Ast.DataTable(new Gherkin.Ast.TableRow[]209 {210 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]211 {212 new Gherkin.Ast.TableCell(null, "First argument"),213 new Gherkin.Ast.TableCell(null, "Second argument"),214 new Gherkin.Ast.TableCell(null, "Result"),215 }),216 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]217 {218 new Gherkin.Ast.TableCell(null, "1"),219 new Gherkin.Ast.TableCell(null, "2"),220 new Gherkin.Ast.TableCell(null, "3"),221 }),222 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]223 {224 new Gherkin.Ast.TableCell(null, "a"),225 new Gherkin.Ast.TableCell(null, "b"),226 new Gherkin.Ast.TableCell(null, "c"),227 })228 })).Feature.Children.First() as Gherkin.Ast.Scenario;229 //act.230 var scenario = sut.ExtractScenario(gherknScenario);231 //assert.232 Assert.NotNull(scenario);233 }234 private sealed class FeatureWithDataTableScenarioStep : Feature235 {236 public Gherkin.Ast.DataTable ReceivedDataTable { get; private set; }237 public const string Steptext = "Some step text";238 [When(Steptext)]239 public void When_DataTable_Is_Expected(Gherkin.Ast.DataTable dataTable)240 {241 ReceivedDataTable = dataTable;242 }243 }244 [Fact]245 public void ExtractScenario_Extracts_Scenario_With_DocString()246 {247 //arrange.248 var featureInstance = new FeatureWithDocStringScenarioStep();249 var sut = FeatureClass.FromFeatureInstance(featureInstance);250 var scenarioName = "scenario-121kh2";251 var docStringContent = @"some content252 +++253 with multi lines254 ---255 in it";...
AstBuilder.cs
Source:AstBuilder.cs
...58 {59 case RuleType.Step:60 {61 var stepLine = node.GetToken(TokenType.StepLine);62 var stepArg = node.GetSingle<StepArgument>(RuleType.DataTable) ??63 node.GetSingle<StepArgument>(RuleType.DocString) ??64 null; // empty arg65 return CreateStep(GetLocation(stepLine), stepLine.MatchedKeyword, stepLine.MatchedText, stepArg, node);66 }67 case RuleType.DocString:68 {69 var separatorToken = node.GetTokens(TokenType.DocStringSeparator).First();70 var contentType = separatorToken.MatchedText.Length == 0 ? null : separatorToken.MatchedText;71 var lineTokens = node.GetTokens(TokenType.Other);72 var content = string.Join(Environment.NewLine, lineTokens.Select(lt => lt.MatchedText));7374 return CreateDocString(GetLocation(separatorToken), contentType, content, node);75 }76 case RuleType.DataTable:77 {78 var rows = GetTableRows(node);79 return CreateDataTable(rows, node);80 }81 case RuleType.Background:82 {83 var backgroundLine = node.GetToken(TokenType.BackgroundLine);84 var description = GetDescription(node);85 var steps = GetSteps(node);86 return CreateBackground(GetLocation(backgroundLine), backgroundLine.MatchedKeyword, backgroundLine.MatchedText, description, steps, node);87 }88 case RuleType.ScenarioDefinition:89 {90 var tags = GetTags(node);9192 var scenarioNode = node.GetSingle<AstNode>(RuleType.Scenario);93 var scenarioLine = scenarioNode.GetToken(TokenType.ScenarioLine);9495 var description = GetDescription(scenarioNode);96 var steps = GetSteps(scenarioNode);97 var examples = scenarioNode.GetItems<Examples>(RuleType.ExamplesDefinition).ToArray();98 return CreateScenario(tags, GetLocation(scenarioLine), scenarioLine.MatchedKeyword, scenarioLine.MatchedText, description, steps, examples, node);99 }100 case RuleType.ExamplesDefinition:101 {102 var tags = GetTags(node);103 var examplesNode = node.GetSingle<AstNode>(RuleType.Examples);104 var examplesLine = examplesNode.GetToken(TokenType.ExamplesLine);105 var description = GetDescription(examplesNode);106107 var allRows = examplesNode.GetSingle<TableRow[]>(RuleType.ExamplesTable);108 var header = allRows != null ? allRows.First() : null;109 var rows = allRows != null ? allRows.Skip(1).ToArray() : null;110 return CreateExamples(tags, GetLocation(examplesLine), examplesLine.MatchedKeyword, examplesLine.MatchedText, description, header, rows, node);111 }112 case RuleType.ExamplesTable:113 {114 return GetTableRows(node);115 }116 case RuleType.Description:117 {118 var lineTokens = node.GetTokens(TokenType.Other);119120 // Trim trailing empty lines121 lineTokens = lineTokens.Reverse().SkipWhile(t => string.IsNullOrWhiteSpace(t.MatchedText)).Reverse();122123 return string.Join(Environment.NewLine, lineTokens.Select(lt => lt.MatchedText));124 }125 case RuleType.Feature:126 {127 var header = node.GetSingle<AstNode>(RuleType.FeatureHeader);128 if(header == null) return null;129 var tags = GetTags(header);130 var featureLine = header.GetToken(TokenType.FeatureLine);131 if(featureLine == null) return null;132 var children = new List<IHasLocation> ();133 var background = node.GetSingle<Background>(RuleType.Background);134 if (background != null) 135 {136 children.Add (background);137 }138 var childrenEnumerable = children.Concat(node.GetItems<IHasLocation>(RuleType.ScenarioDefinition))139 .Concat(node.GetItems<IHasLocation>(RuleType.Rule));140 var description = GetDescription(header);141 if(featureLine.MatchedGherkinDialect == null) return null;142 var language = featureLine.MatchedGherkinDialect.Language;143144 return CreateFeature(tags, GetLocation(featureLine), language, featureLine.MatchedKeyword, featureLine.MatchedText, description, childrenEnumerable.ToArray(), node);145 }146 case RuleType.Rule:147 {148 var header = node.GetSingle<AstNode>(RuleType.RuleHeader);149 if (header == null) return null;150 var ruleLine = header.GetToken(TokenType.RuleLine);151 if (ruleLine == null) return null;152 var children = new List<IHasLocation>();153 var background = node.GetSingle<Background>(RuleType.Background);154 if (background != null)155 {156 children.Add(background);157 }158 var childrenEnumerable = children.Concat(node.GetItems<IHasLocation>(RuleType.ScenarioDefinition));159 var description = GetDescription(header);160 if (ruleLine.MatchedGherkinDialect == null) return null;161 var language = ruleLine.MatchedGherkinDialect.Language;162163 return CreateRule(GetLocation(ruleLine), ruleLine.MatchedKeyword, ruleLine.MatchedText, description, childrenEnumerable.ToArray(), node);164 }165 case RuleType.GherkinDocument:166 {167 var feature = node.GetSingle<Feature>(RuleType.Feature);168169 return CreateGherkinDocument(feature, comments.ToArray(), node);170 }171 }172173 return node;174 }175176 protected virtual Background CreateBackground(Location location, string keyword, string name, string description, Step[] steps, AstNode node)177 {178 return new Background(location, keyword, name, description, steps);179 }180181 protected virtual DataTable CreateDataTable(TableRow[] rows, AstNode node)182 {183 return new DataTable(rows);184 }185186 protected virtual Comment CreateComment(Location location, string text)187 {188 return new Comment(location, text);189 }190191 protected virtual Examples CreateExamples(Tag[] tags, Location location, string keyword, string name, string description, TableRow header, TableRow[] body, AstNode node)192 {193 return new Examples(tags, location, keyword, name, description, header, body);194 }195196 protected virtual Scenario CreateScenario(Tag[] tags, Location location, string keyword, string name, string description, Step[] steps, Examples[] examples, AstNode node)197 {
...
GherkinScenarioOutlineTests.cs
Source:GherkinScenarioOutlineTests.cs
...162 Assert.Equal(text, step.Text);163 }164 }165 [Fact]166 public void ApplyExampleRow_Digests_Row_Values_Into_Scenario_With_DataTable_In_Step()167 {168 //arrange.169 var sut = new Gherkin.Ast.ScenarioOutline(170 null,171 null,172 null,173 "outline123",174 null,175 new Gherkin.Ast.Step[]176 {177 new Gherkin.Ast.Step(null, "Given", "I pass a datatable with tokens", new DataTable(new []178 {179 new TableRow(null, new[] { new TableCell(null, "Column1"), new TableCell(null, "Column2") }),180 new TableRow(null, new[] { new TableCell(null, "<a>"), new TableCell(null, "data with <b> in the middle") }),181 new TableRow(null, new[] { new TableCell(null, "<b>"), new TableCell(null, "<a>") })182 })),183 new Gherkin.Ast.Step(null, "When", "I apply a sample row", null),184 new Gherkin.Ast.Step(null, "Then", "the data table should be populated", null),185 },186 new Gherkin.Ast.Examples[]187 {188 new Gherkin.Ast.Examples(189 null,190 null,191 null,192 "existing example",193 null,194 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]195 {196 new Gherkin.Ast.TableCell(null, "a"),197 new Gherkin.Ast.TableCell(null, "b"),198 }),199 new Gherkin.Ast.TableRow[]200 {201 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]202 {203 new Gherkin.Ast.TableCell(null, "1"),204 new Gherkin.Ast.TableCell(null, "2")205 })206 })207 });208 //act.209 var scenario = sut.ApplyExampleRow("existing example", 0);210 //assert.211 Assert.NotNull(scenario);212 Assert.Equal(sut.Name, scenario.Name);213 Assert.Equal(sut.Steps.Count(), scenario.Steps.Count());214 Assert.Equal(3, scenario.Steps.Count());215 var scenarioSteps = scenario.Steps.ToList();216 Assert.IsType<DataTable>(scenarioSteps[0].Argument);217 var dataTable = (DataTable)scenarioSteps[0].Argument;218 var rows = dataTable.Rows.ToList();219 ValidateRow(rows[0], "Column1", "Column2");220 ValidateRow(rows[1], "1", "data with 2 in the middle");221 ValidateRow(rows[2], "2", "1");222 void ValidateRow(TableRow row, string expectedColumn0Value, string expectedColumn1Value)223 {224 var cells = row.Cells.ToArray();225 Assert.Equal(cells[0].Value, expectedColumn0Value);226 Assert.Equal(cells[1].Value, expectedColumn1Value);227 }228 }229 }230}...
GherkinScenarioOutlineExtensions.cs
Source:GherkinScenarioOutlineExtensions.cs
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text.RegularExpressions;5using DataTable = Gherkin.Ast.DataTable;6using TableRow = Gherkin.Ast.TableRow;7using TableCell = Gherkin.Ast.TableCell;8namespace Xunit.Gherkin.Quick9{10 internal static class GherkinScenarioOutlineExtensions11 {12 private static readonly Regex _placeholderRegex = new Regex(@"<([^>]+)>");13 public static global::Gherkin.Ast.Scenario ApplyExampleRow(14 this global::Gherkin.Ast.ScenarioOutline @this,15 string exampleName,16 int exampleRowIndex)17 {18 var examples = @this.Examples.FirstOrDefault(e => e.Name == exampleName);19 if (examples == null)20 throw new InvalidOperationException($"Cannot find examples named `{exampleName}` in scenario outline `{@this.Name}`.");21 var exampleRow = GetExampleRow(@this, exampleRowIndex, examples);22 var rowValues = GetExampleRowValues(examples, exampleRow);23 var scenarioSteps = new List<global::Gherkin.Ast.Step>();24 foreach (var outlineStep in @this.Steps)25 {26 var scenarioStep = DigestExampleValuesIntoStep(27 @this, 28 exampleName, 29 exampleRowIndex, 30 rowValues, 31 outlineStep);32 scenarioSteps.Add(scenarioStep);33 }34 return new global::Gherkin.Ast.Scenario(35 @this.Tags?.ToArray(),36 @this.Location,37 @this.Keyword,38 @this.Name,39 @this.Description,40 scenarioSteps.ToArray());41 }42 private static global::Gherkin.Ast.Step DigestExampleValuesIntoStep(global::Gherkin.Ast.ScenarioOutline @this, string exampleName, int exampleRowIndex, Dictionary<string, string> rowValues, global::Gherkin.Ast.Step outlineStep)43 {44 string matchEvaluator(Match match)45 {46 var placeholderKey = match.Groups[1].Value;47 if (!rowValues.ContainsKey(placeholderKey))48 throw new InvalidOperationException($"Examples table did not provide value for `{placeholderKey}`. Scenario outline: `{@this.Name}`. Examples: `{exampleName}`. Row index: {exampleRowIndex}.");49 var placeholderValue = rowValues[placeholderKey];50 return placeholderValue;51 }52 var stepText = _placeholderRegex.Replace(outlineStep.Text, matchEvaluator);53 var stepArgument = outlineStep.Argument;54 if (stepArgument is DataTable)55 {56 var processedHeaderRow = false;57 var digestedRows = new List<TableRow>();58 59 foreach(var row in ((DataTable)stepArgument).Rows)60 {61 if (!processedHeaderRow)62 {63 digestedRows.Add(row);64 processedHeaderRow = true;65 }66 else67 {68 var digestedCells = row.Cells.Select(r => new TableCell(r.Location, _placeholderRegex.Replace(r.Value, matchEvaluator)));69 digestedRows.Add(new TableRow(row.Location, digestedCells.ToArray()));70 }71 }72 stepArgument = new DataTable(digestedRows.ToArray());73 }74 var scenarioStep = new global::Gherkin.Ast.Step(75 outlineStep.Location,76 outlineStep.Keyword,77 stepText,78 stepArgument);79 return scenarioStep;80 }81 private static Dictionary<string, string> GetExampleRowValues(global::Gherkin.Ast.Examples examples, List<global::Gherkin.Ast.TableCell> exampleRowCells)82 {83 var rowValues = new Dictionary<string, string>();84 var headerCells = examples.TableHeader.Cells.ToList();85 for (int index = 0; index < headerCells.Count; index++)86 {...
DataTableArgumentTests.cs
Source:DataTableArgumentTests.cs
...3using Xunit;4using Xunit.Gherkin.Quick;5namespace UnitTests6{7 public sealed class DataTableArgumentTests8 {9 [Fact]10 public void DigestScenarioStepValues_Throws_Error_If_No_Arguments_And_No_DataTable()11 {12 //arrange.13 var sut = new DataTableArgument();14 //act / assert.15 Assert.Throws<InvalidOperationException>(() => sut.DigestScenarioStepValues(new string[0], null));16 }17 [Fact]18 public void DigestScenarioStepValues_Throws_Error_If_Arguments_Present_But_No_DataTable()19 {20 //arrange.21 var sut = new DataTableArgument();22 //act / assert.23 Assert.Throws<InvalidOperationException>(() => sut.DigestScenarioStepValues(new string[] { "1", "2", "3" }, null));24 }25 [Fact]26 public void DigestScenarioStepValues_Sets_Value_As_DataTable_When_Only_DataTable()27 {28 //arrange.29 var sut = new DataTableArgument();30 var dataTable = new Gherkin.Ast.DataTable(new Gherkin.Ast.TableRow[]31 {32 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]33 {34 new Gherkin.Ast.TableCell(null, "First argument"),35 new Gherkin.Ast.TableCell(null, "Second argument"),36 new Gherkin.Ast.TableCell(null, "Result"),37 }),38 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]39 {40 new Gherkin.Ast.TableCell(null, "1"),41 new Gherkin.Ast.TableCell(null, "2"),42 new Gherkin.Ast.TableCell(null, "3"),43 }),44 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]45 {46 new Gherkin.Ast.TableCell(null, "a"),47 new Gherkin.Ast.TableCell(null, "b"),48 new Gherkin.Ast.TableCell(null, "c"),49 })50 });51 //act.52 sut.DigestScenarioStepValues(new string[0], dataTable);53 //assert.54 Assert.Same(dataTable, sut.Value);55 }56 [Fact]57 public void DigestScenarioStepValues_Sets_Value_As_DataTable_When_DataTable_And_Other_Args_Present()58 {59 //arrange.60 var sut = new DataTableArgument();61 var dataTable = new Gherkin.Ast.DataTable(new Gherkin.Ast.TableRow[]62 {63 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]64 {65 new Gherkin.Ast.TableCell(null, "First argument"),66 new Gherkin.Ast.TableCell(null, "Second argument"),67 new Gherkin.Ast.TableCell(null, "Result"),68 }),69 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]70 {71 new Gherkin.Ast.TableCell(null, "1"),72 new Gherkin.Ast.TableCell(null, "2"),73 new Gherkin.Ast.TableCell(null, "3"),74 }),75 new Gherkin.Ast.TableRow(null, new Gherkin.Ast.TableCell[]76 {77 new Gherkin.Ast.TableCell(null, "a"),78 new Gherkin.Ast.TableCell(null, "b"),79 new Gherkin.Ast.TableCell(null, "c"),80 })81 });82 //act.83 sut.DigestScenarioStepValues(new string[] { "1", "2", "3" }, dataTable);84 //assert.85 Assert.Same(dataTable, sut.Value);86 }87 88 [Fact]89 public void IsSameAs_Identifies_Similar_Instances()90 {91 //arrange.92 var sut = new DataTableArgument();93 var other = new DataTableArgument();94 //act.95 var same = sut.IsSameAs(other);96 //assert.97 Assert.True(same);98 }99 [Fact]100 public void IsSameAs_Distinguishes_Different_Instances()101 {102 //arrange.103 var sut = new DataTableArgument();104 var other = new Mock<StepMethodArgument>().Object;105 //act.106 var same = sut.IsSameAs(other);107 //assert.108 Assert.False(same);109 }110 [Fact]111 public void Clone_Creates_Similar_Instance()112 {113 //arrange.114 var sut = new DataTableArgument();115 //act.116 var clone = sut.Clone();117 //assert.118 Assert.True(clone.IsSameAs(sut));119 Assert.NotSame(clone, sut);120 }121 }122}...
DataTable
Using AI Code Generation
1using Gherkin.Ast;2using System;3using System.Collections.Generic;4using System.Linq;5using System.Text;6using System.Threading.Tasks;7using TechTalk.SpecFlow;8using TechTalk.SpecFlow.Assist;9{10 {11 [Given(@"I have entered (.*) into the calculator")]12 public void GivenIHaveEnteredIntoTheCalculator(int p0)13 {14 ScenarioContext.Current.Pending();15 }16 [When(@"I press add")]17 public void WhenIPressAdd()18 {19 ScenarioContext.Current.Pending();20 }21 [Then(@"the result should be (.*) on the screen")]22 public void ThenTheResultShouldBeOnTheScreen(int p0)23 {24 ScenarioContext.Current.Pending();25 }26 [Given(@"I have entered following values into the calculator")]27 public void GivenIHaveEnteredFollowingValuesIntoTheCalculator(Table table)28 {29 var rows = table.CreateDynamicSet();30 foreach (var row in rows)31 {32 Console.WriteLine(row.FirstNumber + " : " + row.SecondNumber);33 }34 }35 }36}
DataTable
Using AI Code Generation
1using Gherkin.Ast;2using System;3using System.Collections.Generic;4using System.Data;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8using TechTalk.SpecFlow;9{10 {11 private readonly ScenarioContext _scenarioContext;12 public StepDefinition1(ScenarioContext scenarioContext)13 {14 _scenarioContext = scenarioContext;15 }16 [Given(@"I have entered (.*) into the calculator")]17 public void GivenIHaveEnteredIntoTheCalculator(int p0)18 {19 _scenarioContext.Add("number", p0);20 }21 [When(@"I press add")]22 public void WhenIPressAdd()23 {24 int number = _scenarioContext.Get<int>("number");25 _scenarioContext.Add("result", number + 1);26 }27 [When(@"I press multiply")]28 public void WhenIPressMultiply()29 {30 int number = _scenarioContext.Get<int>("number");31 _scenarioContext.Add("result", number * 2);32 }33 [Then(@"the result should be (.*) on the screen")]34 public void ThenTheResultShouldBeOnTheScreen(int p0)35 {36 int result = _scenarioContext.Get<int>("result");37 Assert.Equal(p0, result);38 }39 [Given(@"I have entered the following numbers into the calculator")]40 public void GivenIHaveEnteredTheFollowingNumbersIntoTheCalculator(Table table)41 {42 var rows = table.Rows;43 var dataTable = table.ToDataTable();44 var row = dataTable.Rows[0];45 var number = row.ItemArray[0];46 _scenarioContext.Add("number", number);47 }48 [Then(@"the result should be (.*)")]49 public void ThenTheResultShouldBe(int p0)50 {51 int number = _scenarioContext.Get<int>("number");52 _scenarioContext.Add("result", number + 1);53 int result = _scenarioContext.Get<int>("result");54 Assert.Equal(p0, result);55 }56 }57}
DataTable
Using AI Code Generation
1using Gherkin.Ast;2{3 {4 public DataTable()5 {6 }7 }8}9using System.Data;10{11 {12 public DataTable()13 {14 }15 }16}17using DataTable = System.Data.DataTable;18DataTable table = new DataTable();19using DataTable = Gherkin.Ast.DataTable;20DataTable table = new DataTable();21using Gherkin.Ast;22{23 {24 public DataTable()25 {26 }27 }28}29using System.Data;30{31 {32 public DataTable()33 {34 }35 }36}37using System.Data;38{39 {40 public void TestMethod()41 {42 DataTable table = new DataTable();43 }44 }45}46using Gherkin.Ast;47{48 {49 public void TestMethod()50 {51 DataTable table = new DataTable();52 }53 }54}
DataTable
Using AI Code Generation
1using Gherkin.Ast;2{3 public static DataTable GetDataTable()4 {5 DataTable dataTable = new DataTable();6 dataTable.AddRow("Name", "Age");7 dataTable.AddRow("John", "30");8 dataTable.AddRow("Mary", "25");9 return dataTable;10 }11}12using Gherkin;13{14 public static DataTable GetDataTable()15 {16 DataTable dataTable = new DataTable();17 dataTable.AddRow("Name", "Age");18 dataTable.AddRow("John", "30");19 dataTable.AddRow("Mary", "25");20 return dataTable;21 }22}23using System.Data;24{25 public static DataTable GetDataTable()26 {27 DataTable dataTable = new DataTable();28 dataTable.Columns.Add("Name");29 dataTable.Columns.Add("Age");30 dataTable.Rows.Add("John", "30");31 dataTable.Rows.Add("Mary", "25");32 return dataTable;33 }34}35using DataTable;36{37 public static DataTable GetDataTable()38 {39 DataTable dataTable = new DataTable();40 dataTable.AddRow("Name", "Age");41 dataTable.AddRow("John", "30");42 dataTable.AddRow("Mary", "25");43 return dataTable;44 }45}46using DataTables;47{48 public static DataTable GetDataTable()49 {50 DataTable dataTable = new DataTable();51 dataTable.AddRow("Name", "Age");52 dataTable.AddRow("John", "30");53 dataTable.AddRow("Mary", "25");54 return dataTable;55 }56}57using DataTables;58{59 public static DataTable GetDataTable()60 {61 DataTable dataTable = new DataTable();62 dataTable.AddRow("Name", "Age");63 dataTable.AddRow("John", "30");64 dataTable.AddRow("Mary", "25");65 return dataTable;66 }67}68using DataTables;
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!!