Beispiel #1
0
        private void GenerateScenarioOutlineTestVariant(
            TestClassGenerationContext generationContext,
            ScenarioOutline scenarioOutline,
            CodeMemberMethod scenatioOutlineTestMethod,
            IEnumerable <KeyValuePair <string, string> > paramToIdentifier,
            string exampleSetTitle,
            string exampleSetIdentifier,
            Gherkin.Ast.TableRow row,
            IEnumerable <Tag> exampleSetTags,
            string variantName)
        {
            var testMethod = CreateTestMethod(generationContext, scenarioOutline, exampleSetTags, variantName, exampleSetIdentifier);

            AddLineDirective(testMethod.Statements, scenarioOutline);

            //call test implementation with the params
            var argumentExpressions = row.Cells.Select(paramCell => new CodePrimitiveExpression(paramCell.Value)).Cast <CodeExpression>().ToList();

            argumentExpressions.Add(GetStringArrayExpression(exampleSetTags));

            testMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    scenatioOutlineTestMethod.Name,
                    argumentExpressions.ToArray()));

            AddLineDirectiveHidden(testMethod.Statements);
            var arguments = paramToIdentifier.Select((p2i, paramIndex) => new KeyValuePair <string, string>(p2i.Key, row.Cells.ElementAt(paramIndex).Value)).ToList();

            _testGeneratorProvider.SetTestMethodAsRow(generationContext, testMethod, scenarioOutline.Name, exampleSetTitle, variantName, arguments);
        }
Beispiel #2
0
        private static string GetCellValue(TableCell cell, ParameterSubstitution paramToIdentifier,
                                           TableRow parametersRow)
        {
            try
            {
                var cellValue = cell.Value.Trim();
                if (parametersRow == null)
                {
                    return(cellValue);
                }

                if (cellValue.StartsWith("<") && cellValue.EndsWith(">") &&
                    paramToIdentifier.TryGetIdentifier(cellValue.Substring(1, cellValue.Length - 2), out int paramIndex))
                {
                    cellValue = parametersRow.Cells.ElementAt(paramToIdentifier[paramIndex].Value).Value;
                    return(cellValue);
                }

                return(cellValue);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #3
0
        private void GenerateStep(CodeStatementCollection statements,
                                  Step scenarioStep,
                                  ParameterSubstitution paramToIdentifier,
                                  TableRow row,
                                  StepKeyword stepKeyWord,
                                  string keyWord)
        {
            var specFlowStep = AsSpecFlowStep(scenarioStep);

            //testRunner.Given("something");
            var arguments = new List <CodeExpression>
            {
                GetSubstitutedString(scenarioStep.Text, paramToIdentifier, row),
                GetDocStringArgExpression(scenarioStep.Argument as DocString, paramToIdentifier, row),
                GetTableArgExpression(scenarioStep.Argument as DataTable, statements, paramToIdentifier, row),
                new CodePrimitiveExpression(keyWord)
            };

            AddLineDirective(statements, scenarioStep);
            statements.Add(new CodeExpressionStatement(
                               new CodeMethodInvokeExpression(
                                   new CodeMethodReferenceExpression(
                                       new CodeVariableReferenceExpression(NamingHelper.TestRunnerVariableName),
                                       stepKeyWord.ToString()),
                                   arguments.ToArray())));
        }
Beispiel #4
0
        public DataTable(TableRow[] rows)
        {
            if (rows == null) throw new ArgumentNullException("rows");
            if (rows.Length == 0) throw new ArgumentException("DataTable must have at least one row", "rows");

            Location = rows[0].Location;
            Rows = rows;
        }
Beispiel #5
0
        public TableRow MapToTableRow(G.TableRow tableRow)
        {
            if (tableRow == null)
            {
                return(null);
            }

            return(new TableRow(tableRow.Cells.Select(this.MapToString)));
        }
Beispiel #6
0
        private TableRow MapToTableRowWithTestResult(G.TableRow tableRow)
        {
            if (tableRow == null)
            {
                return(null);
            }

            return(new TableRowWithTestResult(tableRow.Cells.Select(this.MapToString)));
        }
Beispiel #7
0
 public Examples(Tag[] tags, Location location, string keyword, string name, string description, TableRow header, TableRow[] body)
 {
     Tags = tags;
     Location = location;
     Keyword = keyword;
     Name = name;
     Description = description;
     TableHeader = header;
     TableBody = body;
 }
        public void MapToTableRow_RowWithCellValues_ReturnsRowContainingThoseValues()
        {
            G.TableRow row = this.factory.CreateGherkinTableRow(
                new[]
            {
                "first cell",
                "second cell"
            });

            var mapper = new Mapper();

            var result = mapper.MapToTableRow(row);

            Check.That(result.Cells).ContainsExactly("first cell", "second cell");
        }
        private void GenerateScenarioOutlineTestVariant(
            TestClassGenerationContext generationContext,
            ScenarioOutline scenarioOutline,
            CodeMemberMethod scenatioOutlineTestMethod,
            IEnumerable <KeyValuePair <string, string> > paramToIdentifier,
            string exampleSetTitle,
            string exampleSetIdentifier,
            Gherkin.Ast.TableRow row,
            IEnumerable <Tag> exampleSetTags,
            string variantName)
        {
            var testMethod = CreateTestMethod(generationContext, scenarioOutline, exampleSetTags, variantName, exampleSetIdentifier);


            //call test implementation with the params
            var argumentExpressions = row.Cells.Select(paramCell => new CodePrimitiveExpression(paramCell.Value)).Cast <CodeExpression>().ToList();

            argumentExpressions.Add(_scenarioPartHelper.GetStringArrayExpression(exampleSetTags));


            var statements = new List <CodeStatement>();

            using (new SourceLineScope(_specFlowConfiguration, _codeDomHelper, statements, generationContext.Document.SourceFilePath, scenarioOutline.Location))
            {
                statements.Add(new CodeExpressionStatement(
                                   new CodeMethodInvokeExpression(
                                       new CodeThisReferenceExpression(),
                                       scenatioOutlineTestMethod.Name,
                                       argumentExpressions.ToArray())));
            }


            testMethod.Statements.AddRange(statements.ToArray());

            //_linePragmaHandler.AddLineDirectiveHidden(testMethod.Statements);
            var arguments = paramToIdentifier.Select((p2i, paramIndex) => new KeyValuePair <string, string>(p2i.Key, row.Cells.ElementAt(paramIndex).Value)).ToList();

            // Use the identifier of the example set (e.g. ExampleSet0, ExampleSet1) if we have it.
            // Otherwise, use the title of the example set provided by the user in the feature file.
            string exampleSetName = string.IsNullOrEmpty(exampleSetIdentifier) ? exampleSetTitle : exampleSetIdentifier;

            _unitTestGeneratorProvider.SetTestMethodAsRow(generationContext, testMethod, scenarioOutline.Name, exampleSetName, variantName, arguments);
        }
Beispiel #10
0
        private CodeExpression GetTableArgExpression(
            DataTable tableArg,
            CodeStatementCollection statements,
            ParameterSubstitution paramToIdentifier,
            TableRow parametersRow)
        {
            if (tableArg == null)
            {
                return(new CodeCastExpression(typeof(Table), new CodePrimitiveExpression(null)));
            }

            _tableCounter++;

            //TODO[Gherkin3]: remove dependency on having the first row as header
            var header = tableArg.Rows.First();
            var body   = tableArg.Rows.Skip(1).ToArray();

            //Table table0 = new Table(header...);
            var tableVar = new CodeVariableReferenceExpression("table" + _tableCounter);

            statements.Add(
                new CodeVariableDeclarationStatement(typeof(Table), tableVar.VariableName,
                                                     new CodeObjectCreateExpression(
                                                         typeof(Table),
                                                         GetStringArrayExpression(header.Cells.Select(c => c.Value), paramToIdentifier, null))));

            foreach (var row in body)
            {
                //table0.AddRow(cells...);
                statements.Add(
                    new CodeMethodInvokeExpression(
                        tableVar,
                        "AddRow",
                        GetStringArrayExpression(row.Cells.Select(cell => GetCellValue(cell, paramToIdentifier, parametersRow)), paramToIdentifier,
                                                 null)));
            }

            return(tableVar);
        }
Beispiel #11
0
        private Gherkin.Ast.TableRow Clone(Gherkin.Ast.TableRow row, Func <TableCell, string> getValue = null)
        {
            var valueExpr = getValue ?? ((c) => c.Value);

            return(new Gherkin.Ast.TableRow(row.Location, row.Cells.Select(c => new TableCell(c.Location, valueExpr(c))).ToArray()));
        }
Beispiel #12
0
 public TableRow MapToTableRow(G.TableRow tableRow)
 {
     return(this.mapper.Map <TableRow>(tableRow));
 }
Beispiel #13
0
        private CodeExpression GetSubstitutedString(string text, ParameterSubstitution paramToIdentifier, TableRow row)
        {
            if (text == null)
            {
                return(new CodeCastExpression(typeof(string), new CodePrimitiveExpression(null)));
            }
            if (paramToIdentifier == null)
            {
                return(new CodePrimitiveExpression(text));
            }
            if (row == null)
            {
                return(new CodePrimitiveExpression(text));
            }

            Regex      paramRe    = new Regex(@"\<(?<param>[^\>]+)\>");
            string     formatText = text.Replace("{", "{{").Replace("}", "}}");
            List <int> arguments  = new List <int>();

            formatText = paramRe.Replace(formatText, match =>
            {
                string param = match.Groups["param"].Value;
                int id;
                if (!paramToIdentifier.TryGetIdentifier(param, out id))
                {
                    return(match.Value);
                }
                int argIndex = arguments.IndexOf(id);
                if (argIndex < 0)
                {
                    argIndex = arguments.Count;
                    arguments.Add(id);
                }

                return("{" + argIndex + "}");
            });

            if (arguments.Count == 0)
            {
                return(new CodePrimitiveExpression(text));
            }

            List <CodeExpression> formatArguments = new List <CodeExpression>();

            formatArguments.Add(new CodePrimitiveExpression(formatText));
            formatArguments.AddRange(arguments.Select(id => new CodePrimitiveExpression(row.Cells.ElementAt(id).Value)));

            return(new CodeMethodInvokeExpression(
                       new CodeTypeReferenceExpression(typeof(string)),
                       "Format",
                       formatArguments.ToArray()));
        }
Beispiel #14
0
 private CodeExpression GetDocStringArgExpression(DocString docString, ParameterSubstitution paramToIdentifier, TableRow row)
 {
     return(GetSubstitutedString(docString == null ? null : docString.Content, paramToIdentifier, row));
 }
Beispiel #15
0
 private CodeExpression GetStringArrayExpression(IEnumerable <string> items, ParameterSubstitution paramToIdentifier, TableRow row)
 {
     return(new CodeArrayCreateExpression(typeof(string[]), items.Select(item => GetSubstitutedString(item, paramToIdentifier, row)).ToArray()));
 }
Beispiel #16
0
        private void GenerateScenarioOutlineTestVariant(TestClassGenerationContext generationContext, ScenarioOutline scenarioOutline, CodeMemberMethod scenatioOutlineTestMethod, IEnumerable <KeyValuePair <string, string> > paramToIdentifier, string exampleSetTitle, string exampleSetIdentifier, Gherkin.Ast.TableRow row, IEnumerable <Tag> exampleSetTags, string variantName, string tag = null)
        {
            variantName = string.IsNullOrEmpty(tag) ? variantName : $"{variantName}_{tag}";
            var testMethod = CreateTestMethod(generationContext, scenarioOutline, exampleSetTags, variantName, exampleSetIdentifier);
            //_codeDomHelper.AddLineDirective(scenarioOutline, testMethod.Statements, _specFlowConfiguration);
            var list1 = new List <CodeExpression>();

            list1.AddRange(row.Cells.Select(paramCell => new CodePrimitiveExpression(paramCell.Value)).Cast <CodeExpression>().ToList());
            list1.Add(exampleSetTags.GetStringArrayExpression());

            //// NEW CODE START
            if (tag != null)
            {
                var s = new CodePrimitiveExpression(tag);
                list1.Add(s);
                _setVariantToContextForOutlineTest = true;
            }
            //// NEW CODE END

            testMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), scenatioOutlineTestMethod.Name, list1.ToArray()));
            //_codeDomHelper.AddLineDirectiveHidden(testMethod.Statements, _specFlowConfiguration);
            var list2 = paramToIdentifier.Select((p2i, paramIndex) => new KeyValuePair <string, string>(p2i.Key, row.Cells.ElementAt(paramIndex).Value)).ToList();

            _testGeneratorProvider.SetTestMethodAsRow(generationContext, testMethod, scenarioOutline.Name, exampleSetTitle, variantName, list2);
        }
Beispiel #17
0
 private void FormatRow(TableRow tableRow, StringBuilder result, string indent = INDENT)
 {
     result.Append(indent);
     FormatHasLocation(tableRow, result);
     foreach (var tableCell in tableRow.Cells)
     {
         result.Append("|");
         FormatHasLocation(tableCell, result);
         result.Append(tableCell.Value);
     }
     result.AppendLine("|");
 }
        protected override async Task <RunSummary> RunTestAsync()
        {
            var test    = new XunitTest(TestCase, TestCase.DisplayName); //TODO: this is a pickle, we could use the Compiler/Pickle interfaces from the Gherkin parser
            var summary = new RunSummary()
            {
                Total = 1
            };
            var output = new StringBuilder();

            var gherkinDocument = await SpecFlowParserHelper.ParseSpecFlowDocumentAsync(TestCase.FeatureFile.FeatureFilePath);

            Scenario scenario = null;

            if (gherkinDocument.SpecFlowFeature != null)
            {
                if (TestCase.IsScenarioOutline)
                {
                    var                  scenarioOutline = gherkinDocument.SpecFlowFeature.ScenarioDefinitions.OfType <ScenarioOutline>().FirstOrDefault(s => s.Name == TestCase.Name);
                    Examples             example         = null;
                    Gherkin.Ast.TableRow exampleRow      = null;
                    if (scenarioOutline != null && SpecFlowParserHelper.GetExampleRowById(scenarioOutline, TestCase.ExampleId, out example, out exampleRow))
                    {
                        scenario = SpecFlowParserHelper.CreateScenario(scenarioOutline, example, exampleRow);
                    }
                }
                else
                {
                    scenario = gherkinDocument.SpecFlowFeature.ScenarioDefinitions.OfType <Scenario>().FirstOrDefault(s => s.Name == TestCase.Name);
                }
            }

            string skipReason = null;

            if (scenario == null)
            {
                skipReason = $"Unable to find Scenario: {TestCase.DisplayName}";
            }
            else if (gherkinDocument.SpecFlowFeature.Tags.GetTags().Concat(scenario.Tags.GetTags()).Contains("ignore"))
            {
                skipReason = "Ignored";
            }

            if (skipReason != null)
            {
                summary.Skipped++;

                if (!MessageBus.QueueMessage(new TestSkipped(test, skipReason)))
                {
                    CancellationTokenSource.Cancel();
                }
            }
            else
            {
                var aggregator = new ExceptionAggregator(Aggregator);
                if (!aggregator.HasExceptions)
                {
                    aggregator.Run(() => RunScenario(gherkinDocument, scenario, output));
                }

                var exception = aggregator.ToException();
                TestResultMessage testResult;
                if (exception == null)
                {
                    testResult = new TestPassed(test, summary.Time, output.ToString());
                }
                else
                {
                    testResult = new TestFailed(test, summary.Time, output.ToString(), exception);
                    summary.Failed++;
                }

                if (!CancellationTokenSource.IsCancellationRequested)
                {
                    if (!MessageBus.QueueMessage(testResult))
                    {
                        CancellationTokenSource.Cancel();
                    }
                }
            }

            if (!MessageBus.QueueMessage(new TestFinished(test, summary.Time, output.ToString())))
            {
                CancellationTokenSource.Cancel();
            }

            return(summary);
        }