public virtual void SetRowTest(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle)
        {
            CodeDomHelper.AddAttribute(testMethod, THEORY_ATTRIBUTE);

            SetProperty(testMethod, FEATURE_TITLE_PROPERTY_NAME, generationContext.Feature.Title);
            SetDescription(testMethod, scenarioTitle);
        }
        public void SetRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> arguments, IEnumerable<string> tags, bool isIgnored)
        {
            var args = arguments.Select(arg => new CodeAttributeArgument(new CodePrimitiveExpression(arg))).ToList();

            // addressing ReSharper bug: TestCase attribute with empty string[] param causes inconclusive result - https://github.com/techtalk/SpecFlow/issues/116
            var exampleTagExpressionList = tags.Select(t => new CodePrimitiveExpression(t)).ToArray();
            
            CodeExpression exampleTagsExpression = exampleTagExpressionList.Length == 0 ? (CodeExpression)new CodePrimitiveExpression(null) : new CodeArrayCreateExpression(typeof(string[]), exampleTagExpressionList);
            
            args.Add(new CodeAttributeArgument(exampleTagsExpression));

            if (isIgnored)
            {
                args.Add(new CodeAttributeArgument("Ignored", new CodePrimitiveExpression(true)));
            }

            if (this.enableSauceLabs)
            {
                this.SetSauceAttributes(testMethod, args);
            }
            else
            {
                this.codeDomHelper.AddAttribute(testMethod, RowAttr, args.ToArray());
            }
        }
        /// <summary>
        /// Sets the test class.
        /// </summary>
        /// <param name="generationContext">The generation context.</param>
        /// <param name="featureTitle">The feature title.</param>
        /// <param name="featureDescription">The feature description.</param>
        public override void SetTestClass(TestClassGenerationContext generationContext, string featureTitle, string featureDescription)
        {
            base.SetTestClass(generationContext, featureTitle, featureDescription);

            // Get the driver assembly name.
            var providerName = this.configurationProvider.GetBrowserDriverType();

            // Only generate Coded UI attribute if using the Coded UI provider.
            if (string.Equals(Constants.CodedUiDriverAssembly, providerName, StringComparison.OrdinalIgnoreCase))
            {
                foreach (var customAttribute in generationContext.TestClass.CustomAttributes
                                                                       .Cast<CodeAttributeDeclaration>()
                                                                       .Where(customAttribute => string.Equals(customAttribute.Name, TestClassAttribute)))
                {
                    generationContext.TestClass.CustomAttributes.Remove(customAttribute);
                    break;
                }

                generationContext.TestClass.CustomAttributes.Add(
                    new CodeAttributeDeclaration(new CodeTypeReference(CodedUiTestClassAttribute)));
            }

            // Add deployment item in each test for the driver.
            generationContext.TestClass.CustomAttributes.Add(
                new CodeAttributeDeclaration(
                    new CodeTypeReference(DeploymentItemAttribute),
                    new CodeAttributeArgument(new CodePrimitiveExpression(providerName))));
        }
        public void SetTestClassInitializeMethod(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext)
        {
            this.codeDomHelper.AddAttribute(generationContext.TestClassInitializeMethod, TESTFIXTURESETUP_ATTR);

            generationContext.TestClassInitializeMethod.Statements.Add(new CodeSnippetStatement("            var builder = new ContainerBuilder();"));
            generationContext.TestClassInitializeMethod.Statements.Add(new CodeSnippetStatement("            builder.RegisterModule(new ConfigurationSettingsReader());"));
            generationContext.TestClassInitializeMethod.Statements.Add(new CodeSnippetStatement("            this.container = builder.Build();"));
        }
            public override void SetTestMethodAsRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle, string exampleSetName, string variantName, IEnumerable<KeyValuePair<string, string>> arguments)
            {
                base.SetTestMethodAsRow(generationContext, testMethod, scenarioTitle, exampleSetName, variantName, arguments);

                // change memberMethodName
                testMethod.Name = GetMethodName(scenarioTitle, exampleSetName, arguments);
                newTitles.Add(testMethod.Name);
            }
 public void FinalizeTestClass(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext)
 {
     // Can't be move to SetTestCleanupMethod, as the code at that point misses the .OnScenarioEnd() call.
     // Make sure this code is at the end!
     generationContext.TestCleanupMethod.Statements.Add(new CodeSnippetStatement("            try { System.Threading.Thread.Sleep(50); this.driver.Quit(); } catch (System.Exception) {}"));
     generationContext.TestCleanupMethod.Statements.Add(new CodeSnippetStatement("            this.driver = null;"));
     generationContext.TestCleanupMethod.Statements.Add(new CodeSnippetStatement("            ScenarioContext.Current.Remove(\"Driver\");"));
     generationContext.TestCleanupMethod.Statements.Add(new CodeSnippetStatement("            ScenarioContext.Current.Remove(\"Container\");"));
 }
        private static void CreateInitializeSeleniumMethod(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext)
        {
            var initializeSelenium = new CodeMemberMethod();

            initializeSelenium.Name = "InitializeSelenium";
            initializeSelenium.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "browser"));
            initializeSelenium.Statements.Add(new CodeSnippetStatement("            this.driver = this.container.ResolveNamed<OpenQA.Selenium.IWebDriver>(browser);"));

            generationContext.TestClass.Members.Add(initializeSelenium);
        }
 public override void SetTestMethodCategories(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> scenarioCategories)
 {
     base.SetTestMethodCategories(generationContext, testMethod, scenarioCategories);
     var count = GetRetryCount(scenarioCategories);
     if (count <= 1) return;
     var existingAttribute = testMethod.CustomAttributes.OfType<CodeAttributeDeclaration>().SingleOrDefault(s => s.Name == "Xunit.RetryAttribute");
     if (existingAttribute != null) testMethod.CustomAttributes.Remove(existingAttribute);
     existingAttribute = testMethod.CustomAttributes.OfType<CodeAttributeDeclaration>().SingleOrDefault(s => s.Name == "Xunit.FactAttribute");
     if (existingAttribute != null) testMethod.CustomAttributes.Remove(existingAttribute);
     CodeDomHelper.AddAttribute(testMethod, "Xunit.RetryAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(count)));
 }
    /// <summary>
    /// The decorate from.
    /// </summary>
    /// <param name="tagName">The tag name.</param>
    /// <param name="generationContext">The generation context.</param>
    public void DecorateFrom(string tagName, TestClassGenerationContext generationContext)
    {
      if (tagName == LiveTestTag)
      {
        string baseClassName = this.GetLiveTestBaseClassName(generationContext.Feature);

        this.InheritFromIntegrationTestBase(generationContext.TestClass, baseClassName);
      }

      this.DecorateWithDiscoveredTagMappings(generationContext.Feature.SourceFile, tagName, generationContext.TestClass);
    }
        public virtual void FinalizeTestClass(TestClassGenerationContext generationContext)
        {
            generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement("            ScenarioContext.Current.Add(\"Test\", this);"));
            generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement("            StartDriver();"));

            // From SeleniumNunit + BBTest changes
            // Can't be move to SetTestCleanupMethod, as the code at that point misses the .OnScenarioEnd() call.
            // Make sure this code is at the end!
            generationContext.TestCleanupMethod.Statements.Add(new CodeSnippetStatement("            SaveChromeArtifacts(IsPass());"));
            generationContext.TestCleanupMethod.Statements.Add(new CodeSnippetStatement("            StopDriver();"));
        }
        public override void SetTestMethod(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle)
        {
            SetProperty(testMethod, FEATURE_TITLE_PROPERTY_NAME, generationContext.Feature.Title);
            SetDescription(testMethod, scenarioTitle);

            var count = !generationContext.CustomData.ContainsKey("featureRetryCount") ? 1 : Convert.ToInt32(generationContext.CustomData["featureRetryCount"]);

            if (count > 1)
                CodeDomHelper.AddAttribute(testMethod, "Xunit.RetryAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(count)));
            else
                CodeDomHelper.AddAttribute(testMethod, FACT_ATTRIBUTE);
        }
        public void SetTestClass(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, string featureTitle, string featureDescription)
        {
            codeDomHelper.AddAttribute(generationContext.TestClass, TESTFIXTURE_ATTR);
            codeDomHelper.AddAttribute(generationContext.TestClass, DESCRIPTION_ATTR, featureTitle);

            generationContext.Namespace.Imports.Add(new CodeNamespaceImport("Autofac"));
            generationContext.Namespace.Imports.Add(new CodeNamespaceImport("Autofac.Configuration"));

            generationContext.TestClass.Members.Add(new CodeMemberField("OpenQA.Selenium.IWebDriver", "driver"));
            generationContext.TestClass.Members.Add(new CodeMemberField("IContainer", "container"));

            CreateInitializeSeleniumMethod(generationContext);
        }
        public void SetRow(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, IEnumerable <string> arguments, IEnumerable <string> tags, bool isIgnored)
        {
            var args = arguments.Select(
                arg => new CodeAttributeArgument(new CodePrimitiveExpression(arg))).ToList();

            // addressing ReSharper bug: TestCase attribute with empty string[] param causes inconclusive result - https://github.com/techtalk/SpecFlow/issues/116
            var            exampleTagExpressionList = tags.Select(t => new CodePrimitiveExpression(t)).ToArray();
            CodeExpression exampleTagsExpression    = exampleTagExpressionList.Length == 0 ?
                                                      (CodeExpression) new CodePrimitiveExpression(null) :
                                                      new CodeArrayCreateExpression(typeof(string[]), exampleTagExpressionList);

            args.Add(new CodeAttributeArgument(exampleTagsExpression));

            if (isIgnored)
            {
                args.Add(new CodeAttributeArgument("Ignored", new CodePrimitiveExpression(true)));
            }

            var browsers = testMethod.UserData.Keys.OfType <string>()
                           .Where(key => key.StartsWith("Browser:"))
                           .Select(key => (string)testMethod.UserData[key]).ToArray();

            if (browsers.Any())
            {
                foreach (var codeAttributeDeclaration in testMethod.CustomAttributes.Cast <CodeAttributeDeclaration>().Where(attr => attr.Name == ROW_ATTR && attr.Arguments.Count == 3).ToList())
                {
                    testMethod.CustomAttributes.Remove(codeAttributeDeclaration);
                }

                foreach (var browser in browsers)
                {
                    var argsString = string.Concat(args.Take(args.Count - 1).Select(arg => string.Format("\"{0}\" ,", ((CodePrimitiveExpression)arg.Value).Value)));
                    argsString = argsString.TrimEnd(' ', ',');

                    var withBrowserArgs = new[] { new CodeAttributeArgument(new CodePrimitiveExpression(browser)) }
                    .Concat(args)
                    .Concat(new [] {
                        new CodeAttributeArgument("Category", new CodePrimitiveExpression(browser)),
                        new CodeAttributeArgument("TestName", new CodePrimitiveExpression(string.Format("{0} on {1} with: {2}", testMethod.Name, browser, argsString)))
                    })
                    .ToArray();

                    this.codeDomHelper.AddAttribute(testMethod, ROW_ATTR, withBrowserArgs);
                }
            }
            else
            {
                this.codeDomHelper.AddAttribute(testMethod, ROW_ATTR, args.ToArray());
            }
        }
        public override void SetTestClass(TestClassGenerationContext generationContext, string featureTitle, string featureDescription)
        {
            base.SetTestClass(generationContext, featureTitle, featureDescription);

            foreach (CodeAttributeDeclaration customAttribute in generationContext.TestClass.CustomAttributes)
            {
                if (customAttribute.Name == "Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute")
                {
                    generationContext.TestClass.CustomAttributes.Remove(customAttribute);
                    break;
                }
            }

            generationContext.TestClass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference("Microsoft.VisualStudio.TestTools.UITesting.CodedUITestAttribute")));
        }
 public void DecorateFrom(string tagName, TestClassGenerationContext generationContext, CodeMemberMethod testMethod)
 {
     var testCase = tagName.Substring(TagPrefix.Length);
     testMethod.Statements.Insert(0,
         new CodeExpressionStatement
         (
             new CodeMethodInvokeExpression
             (
                 new CodeTypeReferenceExpression(typeof(Console)),
                 "WriteLine",
                 new CodePrimitiveExpression(string.Format("Running test case '{0}'", testCase))
             )
         )
     );
 }
        public virtual void SetRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> arguments, IEnumerable<string> tags, bool isIgnored)
        {
            //TODO: better handle "ignored"
            if (isIgnored)
                return;

            var args = arguments.Select(
              arg => new CodeAttributeArgument(new CodePrimitiveExpression(arg))).ToList();

            args.Add(
                new CodeAttributeArgument(
                    new CodeArrayCreateExpression(typeof(string[]), tags.Select(t => new CodePrimitiveExpression(t)).ToArray())));

            CodeDomHelper.AddAttribute(testMethod, INLINEDATA_ATTRIBUTE, args.ToArray());
        }
        // Retrieve the test methods, duplicate them for each driver, then replace the originals.
        public override void FinalizeTestClass(TestClassGenerationContext generationContext)
        {
            test.Selenium.DriverConfiguration.ConfigurationSectionHandler webDriverConfig = test.Selenium.DriverConfiguration.ConfigurationReader.GetConfigurationFromFeatureFile(generationContext.Feature.SourceFile);

            // Loop through all TestMethods and add the ScnearionContext["CurrentStep"] statement so our tests can know what step they are on.
            List<CodeMemberMethod> allTestMethods = GetAllTestMethods(generationContext);
            foreach (var testMethod in allTestMethods)
            {
                var testRunnerStatements = GetTestRunnerStatements(testMethod.Statements);
                foreach (var testRunnerStatement in testRunnerStatements)
                {
                    testMethod.Statements.Insert(testRunnerStatement.Key, new CodeSnippetStatement(String.Format(UpdateScenarioCurrentStep, testRunnerStatement.Value)));
                }
            }

            // Look for all Selenium TestMethods (@Selenium tag) and create a _With_<browserKey> TestMethod for each desired browserKey
            List<CodeMemberMethod> seleniumTestMethods = GetSeleniumTestMethods(allTestMethods);
            List<CodeMemberMethod> webDriverTestMethods = CreateWebDriverTestMethods(seleniumTestMethods, generationContext, webDriverConfig);
            seleniumTestMethods.ForEach(method => generationContext.TestClass.Members.Remove(method));
            webDriverTestMethods.ForEach(method => generationContext.TestClass.Members.Add(method));

            base.FinalizeTestClass(generationContext);
        }
        public void SetTestMethodCategories(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, IEnumerable <string> scenarioCategories)
        {
            this.codeDomHelper.AddAttributeForEachValue(testMethod, CATEGORY_ATTR, scenarioCategories.Where(cat => !cat.StartsWith("Browser:")));

            bool hasBrowser = false;

            foreach (var browser in scenarioCategories.Where(cat => cat.StartsWith("Browser:")).Select(cat => cat.Replace("Browser:", "")))
            {
                testMethod.UserData.Add("Browser:" + browser, browser);

                var withBrowserArgs = new[] { new CodeAttributeArgument(new CodePrimitiveExpression(browser)) }
                .Concat(new[] {
                    new CodeAttributeArgument("Category", new CodePrimitiveExpression(browser)),
                    new CodeAttributeArgument("TestName", new CodePrimitiveExpression(string.Format("{0} on {1}", testMethod.Name, browser)))
                })
                .ToArray();

                this.codeDomHelper.AddAttribute(testMethod, ROW_ATTR, withBrowserArgs);

                hasBrowser = true;
            }

            if (hasBrowser)
            {
                if (!scenarioSetupMethodsAdded)
                {
                    generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement("            if(this.driver != null)"));
                    generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement("                ScenarioContext.Current.Add(\"Driver\", this.driver);"));
                    generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement("            if(this.container != null)"));
                    generationContext.ScenarioInitializeMethod.Statements.Add(new CodeSnippetStatement("                ScenarioContext.Current.Add(\"Container\", this.container);"));
                    scenarioSetupMethodsAdded = true;
                }

                testMethod.Statements.Insert(0, new CodeSnippetStatement("            InitializeSelenium(browser);"));
                testMethod.Parameters.Insert(0, new System.CodeDom.CodeParameterDeclarationExpression("System.string", "browser"));
            }
        }
 private static void UpdateSauceLabsStatus(TestClassGenerationContext generationContext)
 {
     generationContext.ScenarioCleanupMethod.Statements.Add(new CodeSnippetStatement("            bool passed = true;"));
     generationContext.ScenarioCleanupMethod.Statements.Add(new CodeSnippetStatement("            if (ScenarioContext.Current.TestError != null) { passed = false; }"));
     generationContext.ScenarioCleanupMethod.Statements.Add(new CodeSnippetStatement("            UpdateSauceLabsStatus(passed);"));
 }
 public override void FinalizeTestClass(TestClassGenerationContext generationContext)
 {
     base.FinalizeTestClass(generationContext);
     // change namespace 
     generationContext.Namespace.Name = DefaultNameSpace;
 }
 public void SetTestMethodIgnore(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod)
 {
     this.codeDomHelper.AddAttribute(testMethod, IGNORE_ATTR);
 }
 public void SetTestMethodAsRow(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, string scenarioTitle, string exampleSetName, string variantName, IEnumerable <KeyValuePair <string, string> > arguments)
 {
 }
        private static void CreateUpdateSauceLabsStatusMethod(TestClassGenerationContext generationContext)
        {
            var updateSauceLabsStatus = new CodeMemberMethod
            {
                Name = "UpdateSauceLabsStatus"
            };

            updateSauceLabsStatus.Parameters.Add(new CodeParameterDeclarationExpression("System.Boolean", "passed"));
            updateSauceLabsStatus.Statements.Add(new CodeSnippetStatement("             var jobId = this.driver.GetSessionId();"));
            updateSauceLabsStatus.Statements.Add(new CodeSnippetStatement("             if(passed) this.sauceRest.SetJobPassed(jobId);"));
            updateSauceLabsStatus.Statements.Add(new CodeSnippetStatement("             else this.sauceRest.SetJobFailed(jobId);"));

            generationContext.TestClass.Members.Add(updateSauceLabsStatus);
        }
 public void SetTestInitializeMethod(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext)
 {
     this.codeDomHelper.AddAttribute(generationContext.TestInitializeMethod, TESTSETUP_ATTR);
 }
        private void GenerateScenarioOutlineExamplesAsIndividualMethods(ScenarioOutline scenarioOutline, TestClassGenerationContext generationContext, CodeMemberMethod scenatioOutlineTestMethod,
                                                                        ParameterSubstitution paramToIdentifier)
        {
            int exampleSetIndex = 0;

            foreach (var exampleSet in scenarioOutline.Examples)
            {
                bool   useFirstColumnAsName = CanUseFirstColumnAsName(exampleSet.TableBody);
                string exampleSetIdentifier = string.IsNullOrEmpty(exampleSet.Name)
                    ? scenarioOutline.Examples.Count(es => string.IsNullOrEmpty(es.Name)) > 1
                        ? string.Format("ExampleSet {0}", exampleSetIndex).ToIdentifier()
                        : null
                    : exampleSet.Name.ToIdentifier();

                foreach (var example in exampleSet.TableBody.Select((r, i) => new { Row = r, Index = i }))
                {
                    string variantName = useFirstColumnAsName ? example.Row.Cells.First().Value : string.Format("Variant {0}", example.Index);
                    GenerateScenarioOutlineTestVariant(generationContext, scenarioOutline, scenatioOutlineTestMethod, paramToIdentifier, exampleSet.Name ?? "", exampleSetIdentifier, example.Row,
                                                       exampleSet.Tags, variantName);
                }

                exampleSetIndex++;
            }
        }
 public void SetTestClassCategories(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, IEnumerable <string> featureCategories)
 {
     this.codeDomHelper.AddAttributeForEachValue(generationContext.TestClass, CATEGORY_ATTR, featureCategories);
 }
        public virtual void SetTestCleanupMethod(TestClassGenerationContext generationContext)
        {
            // xUnit supports test tear down through the IDisposable interface

            generationContext.TestClass.BaseTypes.Add(typeof(IDisposable));

            // void IDisposable.Dispose() { <memberMethod>(); }

            CodeMemberMethod disposeMethod = new CodeMemberMethod();
            disposeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IDisposable));
            disposeMethod.Name = "Dispose";
            generationContext.TestClass.Members.Add(disposeMethod);

            disposeMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    generationContext.TestCleanupMethod.Name));
        }
        public virtual void SetTestInitializeMethod(TestClassGenerationContext generationContext)
        {
            // xUnit uses a parameterless constructor

            // public <_currentTestTypeDeclaration>() { <memberMethod>(); }

            CodeConstructor ctorMethod = new CodeConstructor();
            ctorMethod.Attributes = MemberAttributes.Public;
            generationContext.TestClass.Members.Add(ctorMethod);

            ctorMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    generationContext.TestInitializeMethod.Name));
        }
        public virtual void SetTestClassInitializeMethod(TestClassGenerationContext generationContext)
        {
            // xUnit uses IUseFixture<T> on the class

            generationContext.TestClassInitializeMethod.Attributes |= MemberAttributes.Static;

            _currentFixtureDataTypeDeclaration = CodeDomHelper.CreateGeneratedTypeDeclaration("FixtureData");
            generationContext.TestClass.Members.Add(_currentFixtureDataTypeDeclaration);

            var fixtureDataType =
                CodeDomHelper.CreateNestedTypeReference(generationContext.TestClass, _currentFixtureDataTypeDeclaration.Name);

            var useFixtureType = new CodeTypeReference(IUSEFIXTURE_INTERFACE, fixtureDataType);
            CodeDomHelper.SetTypeReferenceAsInterface(useFixtureType);

            generationContext.TestClass.BaseTypes.Add(useFixtureType);

            // public void SetFixture(T) { } // explicit interface implementation for generic interfaces does not work with codedom

            CodeMemberMethod setFixtureMethod = new CodeMemberMethod();
            setFixtureMethod.Attributes = MemberAttributes.Public;
            setFixtureMethod.Name = "SetFixture";
            setFixtureMethod.Parameters.Add(new CodeParameterDeclarationExpression(fixtureDataType, "fixtureData"));
            setFixtureMethod.ImplementationTypes.Add(useFixtureType);
            generationContext.TestClass.Members.Add(setFixtureMethod);

            // public <_currentFixtureTypeDeclaration>() { <fixtureSetupMethod>(); }
            CodeConstructor ctorMethod = new CodeConstructor();
            ctorMethod.Attributes = MemberAttributes.Public;
            _currentFixtureDataTypeDeclaration.Members.Add(ctorMethod);
            ctorMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(new CodeTypeReference(generationContext.TestClass.Name)),
                    generationContext.TestClassInitializeMethod.Name));
        }
 public virtual void SetTestClassIgnore(TestClassGenerationContext generationContext)
 {
     //TODO: how to do class level ignore?
 }
        public void SetTestClass(TestClassGenerationContext generationContext, string featureTitle, string featureDescription)
        {
            this.codeDomHelper.AddAttribute(generationContext.TestClass, TestfixtureAttr);
            this.codeDomHelper.AddAttribute(generationContext.TestClass, DescriptionAttr, featureTitle);

            if (generationContext.Feature.Tags != null)
            {
                this.enableSauceLabs = generationContext.Feature.Tags.Any(x => x.Name == "EnableSauceLabs");
            }

            if (this.enableSauceLabs)
            {
                this.sauceLabSettings = this.GetSauceLabsConfiguration();

                generationContext.Namespace.Imports.Add(new CodeNamespaceImport("Endjin.Selenium.SpecFlowPlugin"));
                generationContext.TestClass.Members.Add(new CodeMemberField("Endjin.Selenium.SpecFlowPlugin.RemoteWebDriver", "driver"));
                generationContext.TestClass.Members.Add(new CodeMemberField("Endjin.Selenium.SpecFlowPlugin.SauceRest", "sauceRest"));

                CreateInitializeSeleniumMethod(generationContext);
                CreateInitializeSeleniumOverloadMethod(generationContext);

                CreateUpdateSauceLabsStatusMethod(generationContext);
                UpdateSauceLabsStatus(generationContext);
                CleanUpSeleniumContext(generationContext);
            }
        }
Beispiel #32
0
        private void GenerateTest(TestClassGenerationContext generationContext, Scenario scenario, SpecFlowFeature feature)
        {
            var testMethod = CreateTestMethod(generationContext, scenario, null);

            GenerateTestBody(generationContext, scenario, testMethod, feature);
        }
        private void GenerateTestBody(TestClassGenerationContext generationContext, Scenario scenario, CodeMemberMethod testMethod, CodeExpression additionalTagsExpression = null, ParameterSubstitution paramToIdentifier = null)
        {
            //call test setup
            //ScenarioInfo scenarioInfo = new ScenarioInfo("xxxx", tags...);
            CodeExpression tagsExpression;

            if (additionalTagsExpression == null)
            {
                tagsExpression = GetStringArrayExpression(scenario.Tags);
            }
            else if (scenario.Tags == null)
            {
                tagsExpression = additionalTagsExpression;
            }
            else
            {
                // merge tags list
                // var tags = tags1
                // if (tags2 != null)
                //   tags = Enumerable.ToArray(Enumerable.Concat(tags1, tags1));
                testMethod.Statements.Add(
                    new CodeVariableDeclarationStatement(typeof(string[]), "__tags", GetStringArrayExpression(scenario.Tags)));
                tagsExpression = new CodeVariableReferenceExpression("__tags");
                testMethod.Statements.Add(
                    new CodeConditionStatement(
                        new CodeBinaryOperatorExpression(
                            additionalTagsExpression,
                            CodeBinaryOperatorType.IdentityInequality,
                            new CodePrimitiveExpression(null)),
                        new CodeAssignStatement(
                            tagsExpression,
                            new CodeMethodInvokeExpression(
                                new CodeTypeReferenceExpression(typeof(Enumerable)),
                                "ToArray",
                                new CodeMethodInvokeExpression(
                                    new CodeTypeReferenceExpression(typeof(Enumerable)),
                                    "Concat",
                                    tagsExpression,
                                    additionalTagsExpression)))));
            }
            testMethod.Statements.Add(
                new CodeVariableDeclarationStatement(typeof(ScenarioInfo), "scenarioInfo",
                                                     new CodeObjectCreateExpression(typeof(ScenarioInfo),
                                                                                    new CodePrimitiveExpression(scenario.Title),
                                                                                    tagsExpression)));

            AddLineDirective(testMethod.Statements, scenario);
            testMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    generationContext.ScenarioInitializeMethod.Name,
                    new CodeVariableReferenceExpression("scenarioInfo")));

            if (HasFeatureBackground(generationContext.Feature))
            {
                AddLineDirective(testMethod.Statements, generationContext.Feature.Background);
                testMethod.Statements.Add(
                    new CodeMethodInvokeExpression(
                        new CodeThisReferenceExpression(),
                        generationContext.FeatureBackgroundMethod.Name));
            }

            foreach (var scenarioStep in scenario.Steps)
            {
                GenerateStep(testMethod, scenarioStep, paramToIdentifier);
            }

            AddLineDirectiveHidden(testMethod.Statements);

            // call scenario cleanup
            testMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    generationContext.ScenarioCleanupMethod.Name));
        }
 public virtual void SetTestMethodCategories(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> scenarioCategories)
 {
     // xUnit does not support caregories
 }
 public void SetTestMethodCategories(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, IEnumerable<string> scenarioCategories)
 {
     this.codeDomHelper.AddAttributeForEachValue(testMethod, CategoryAttr, scenarioCategories);
 }
 public void SetTestClassIgnore(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext)
 {
     this.codeDomHelper.AddAttribute(generationContext.TestClass, IGNORE_ATTR);
 }
        public virtual void SetTestMethodIgnore(TestClassGenerationContext generationContext, CodeMemberMethod testMethod)
        {
            var factAttr = testMethod.CustomAttributes.OfType<CodeAttributeDeclaration>()
                .FirstOrDefault(codeAttributeDeclaration => codeAttributeDeclaration.Name == FACT_ATTRIBUTE);

            if (factAttr != null)
            {
                // set [FactAttribute(Skip="reason")]
                factAttr.Arguments.Add
                    (
                        new CodeAttributeArgument(FACT_ATTRIBUTE_SKIP_PROPERTY_NAME, new CodePrimitiveExpression(SKIP_REASON))
                    );
            }
        }
 public void SetTestCleanupMethod(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext)
 {
     this.codeDomHelper.AddAttribute(generationContext.TestCleanupMethod, TESTTEARDOWN_ATTR);
 }
 public virtual void FinalizeTestClass(TestClassGenerationContext generationContext)
 {
     // by default, doing nothing to the final generated code
 }
 public void SetTestMethod(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, string scenarioTitle)
 {
     this.codeDomHelper.AddAttribute(testMethod, TEST_ATTR);
     this.codeDomHelper.AddAttribute(testMethod, DESCRIPTION_ATTR, scenarioTitle);
 }
        private static void CreateInitializeSeleniumOverloadMethod(TestClassGenerationContext generationContext)
        {
            var initializeSelenium = new CodeMemberMethod
            {
                Name = "InitializeSeleniumSauce"
            };

            initializeSelenium.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "browser"));
            initializeSelenium.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "version"));
            initializeSelenium.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "platform"));
            initializeSelenium.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "testName"));
            initializeSelenium.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "url"));
            initializeSelenium.Statements.Add(new CodeSnippetStatement("            this.driver = new Endjin.Selenium.SpecFlowPlugin.RemoteWebDriver(url, browser, version, platform, testName, true);"));

            generationContext.TestClass.Members.Add(initializeSelenium);
        }
 public void SetRowTest(TechTalk.SpecFlow.Generator.TestClassGenerationContext generationContext, System.CodeDom.CodeMemberMethod testMethod, string scenarioTitle)
 {
     this.SetTestMethod(generationContext, testMethod, scenarioTitle);
 }
 public virtual void SetTestClass(TestClassGenerationContext generationContext, string featureTitle, string featureDescription)
 {
     // xUnit does not use an attribute for the TestFixture, all public classes are potential fixtures
 }
        private void GenerateTest(TestClassGenerationContext generationContext, Scenario scenario)
        {
            CodeMemberMethod testMethod = CreateTestMethod(generationContext, scenario, null);

            GenerateTestBody(generationContext, scenario, testMethod);
        }
 public virtual void SetTestClassCategories(TestClassGenerationContext generationContext, IEnumerable<string> featureCategories)
 {
     // xUnit does not support caregories
 }
        private void GenerateScenarioOutlineExamplesAsIndividualMethods(ScenarioOutline scenarioOutline, TestClassGenerationContext generationContext, CodeMemberMethod scenatioOutlineTestMethod, ParameterSubstitution paramToIdentifier)
        {
            int exampleSetIndex = 0;

            foreach (var exampleSet in scenarioOutline.Examples.ExampleSets)
            {
                bool   useFirstColumnAsName = CanUseFirstColumnAsName(exampleSet.Table);
                string exampleSetIdentifier = string.IsNullOrEmpty(exampleSet.Title)
                                                  ? scenarioOutline.Examples.ExampleSets.Count(es => string.IsNullOrEmpty(es.Title)) > 1
                                                        ? string.Format("ExampleSet {0}", exampleSetIndex).ToIdentifier()
                                                        : null
                                                  : exampleSet.Title.ToIdentifier();

                for (int rowIndex = 0; rowIndex < exampleSet.Table.Body.Length; rowIndex++)
                {
                    var row = exampleSet.Table.Body[rowIndex];

                    string variantName = useFirstColumnAsName ?  row.Cells[0].Value : string.Format("Variant {0}", rowIndex);
                    GenerateScenarioOutlineTestVariant(generationContext, scenarioOutline, scenatioOutlineTestMethod, paramToIdentifier, exampleSet.Title ?? "", exampleSetIdentifier, row, exampleSet.Tags, variantName);
                }
                exampleSetIndex++;
            }
        }
        public virtual void SetTestClassCleanupMethod(TestClassGenerationContext generationContext)
        {
            // xUnit uses IUseFixture<T> on the class

            generationContext.TestClassCleanupMethod.Attributes |= MemberAttributes.Static;

            _currentFixtureDataTypeDeclaration.BaseTypes.Add(typeof(IDisposable));

            // void IDisposable.Dispose() { <fixtureTearDownMethod>(); }

            CodeMemberMethod disposeMethod = new CodeMemberMethod();
            disposeMethod.PrivateImplementationType = new CodeTypeReference(typeof(IDisposable));
            disposeMethod.Name = "Dispose";
            _currentFixtureDataTypeDeclaration.Members.Add(disposeMethod);

            disposeMethod.Statements.Add(
                new CodeMethodInvokeExpression(
                    new CodeTypeReferenceExpression(new CodeTypeReference(generationContext.TestClass.Name)),
                    generationContext.TestClassCleanupMethod.Name));
        }
 public virtual void SetTestMethodAsRow(TestClassGenerationContext generationContext, CodeMemberMethod testMethod, string scenarioTitle, string exampleSetName, string variantName, IEnumerable<KeyValuePair<string, string>> arguments)
 {
     // doing nothing since we support RowTest
 }
 private static void CleanUpSeleniumContext(TestClassGenerationContext generationContext)
 {
     generationContext.ScenarioCleanupMethod.Statements.Add(new CodeSnippetStatement("            try { System.Threading.Thread.Sleep(50); this.driver.Quit(); } catch (System.Exception) {}"));
     generationContext.ScenarioCleanupMethod.Statements.Add(new CodeSnippetStatement("            this.driver = null;"));
     generationContext.ScenarioCleanupMethod.Statements.Add(new CodeSnippetStatement("            ScenarioContext.Current.Remove(\"Driver\");"));
 }