Esempio n. 1
0
        /// <summary>
        /// Updates testcase's field with corresponding value
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="value"></param>
        public override void UpdateField(string fieldName, object value)
        {
            // If value is null then just take the default valuea nd return the default value
            if (value == null)
            {
                return;
            }

            List <SourceTestStep> sourceSteps = value as List <SourceTestStep>;

            // If the value is a List of test steps then Update th testcase with test steps
            if (sourceSteps != null)
            {
                m_stepsFieldName = fieldName;

                foreach (SourceTestStep sourceStep in sourceSteps)
                {
                    // Update the Test step's text with correct parameters
                    string title          = sourceStep.title;
                    string expectedResult = sourceStep.expectedResult;

                    if (m_areRichSteps)
                    {
                        // This is temporary. Work around for product issue.
                        title          = title.Replace("\r\n", "<P>").Replace("\n", "<P>").Replace("\r", "<P>");
                        expectedResult = expectedResult.Replace("\r\n", "<P>").Replace("\n", "<P>").Replace("\r", "<P>");
                    }

                    // Creating TCM Test Step and filling testcase with them
                    ITestStep step = m_testCase.CreateTestStep();
                    step.Title = title;

                    // Set the TestStepType properly for validated steps
                    if (!String.IsNullOrEmpty(expectedResult))
                    {
                        step.ExpectedResult = expectedResult;
                        step.TestStepType   = TestStepType.ValidateStep;
                    }

                    if (sourceStep.attachments != null)
                    {
                        foreach (string filePath in sourceStep.attachments)
                        {
                            ITestAttachment attachment = step.CreateAttachment(filePath);
                            step.Attachments.Add(attachment);
                        }
                    }
                    m_testCase.Actions.Add(step);
                }
            }
            // else if it is a normal tfs field then just updates the tfs' testcase field
            else
            {
                base.UpdateField(fieldName, value);
            }
        }
Esempio n. 2
0
        private static void AddTestCaseSteps(string uri, Project project, int testCaseId, Tuple <string, string>[] steps)
        {
            TfsTeamProjectCollection tfs;

            tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(uri)); // https://mytfs.visualstudio.com/DefaultCollection
            tfs.Authenticate();

            ITestManagementService     service     = (ITestManagementService)tfs.GetService(typeof(ITestManagementService));
            ITestManagementTeamProject testProject = service.GetTeamProject(project);
            ITestCase testCase = testProject.TestCases.Find(testCaseId);

            foreach (var step in steps)
            {
                ITestStep newStep = testCase.CreateTestStep();
                newStep.Title          = Helpers.ReplaceReservedChars(step.Item1);
                newStep.ExpectedResult = step.Item2;

                testCase.Actions.Add(newStep);
            }
            testCase.Save();
        }
Esempio n. 3
0
        public static void MyClassInitialize(TestContext testContext)
        {
            _testContext = testContext;

            AIT.TFS.SyncService.Service.AssemblyInit.Instance.Init();
            AIT.TFS.SyncService.Adapter.TFS2012.AssemblyInit.Instance.Init();

            var serverConfig = CommonConfiguration.TfsTestServerConfiguration(_testContext);

            CommonConfiguration.ReplaceConfigFileTokens(_testContext);
            var config = CommonConfiguration.GetSimpleFieldConfiguration("Requirement", Direction.OtherToTfs, FieldValueType.PlainText, "System.Title");

            _testAdapter = SyncServiceFactory.CreateTfsTestAdapter(serverConfig.TeamProjectCollectionUrl, serverConfig.TeamProjectName, config);
            var projectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(serverConfig.TeamProjectCollectionUrl));

            _testManagement = projectCollection.GetService <ITestManagementService>().GetTeamProject(serverConfig.TeamProjectName);

            var sharedSteps = _testManagement.SharedSteps.Query("SELECT * FROM WorkItems WHERE System.Title='UnitTest_SharedStep'");

            _sharedStep = sharedSteps.FirstOrDefault();

            if (_sharedStep == null)
            {
                _sharedStep = _testManagement.SharedSteps.Create();
                var sharedStep1 = _sharedStep.CreateTestStep();
                sharedStep1.Title          = "First Shared Step";
                sharedStep1.ExpectedResult = "Result of first shared step";

                var sharedStep2 = _sharedStep.CreateTestStep();
                sharedStep2.Title          = "Second Shared Step .: @ParametersDontLikeSpecialChars";
                sharedStep2.ExpectedResult = "Result of second shared step";

                _sharedStep.Actions.Add(sharedStep1);
                _sharedStep.Actions.Add(sharedStep2);

                _sharedStep.Title = "UnitTest_SharedStep_1";
                _sharedStep.Save();
            }
            else
            {
                var sharedStep1 = _sharedStep.Actions[0] as ITestStep;
                if (sharedStep1 != null)
                {
                    sharedStep1.Title          = "First Shared Step";
                    sharedStep1.ExpectedResult = "Result of first shared step";
                }

                var sharedStep2 = _sharedStep.Actions[1] as ITestStep;
                if (sharedStep2 != null)
                {
                    sharedStep2.Title          = "Second Shared Step .: @ParametersDontLikeSpecialChars";
                    sharedStep2.ExpectedResult = "Result of second shared step";
                }

                _sharedStep.WorkItem.Open();
                _sharedStep.Save();
            }

            var testCases = _testManagement.TestCases.Query("SELECT * FROM WorkItems WHERE System.Title='UnitTest_TestCase'");

            _testCase = testCases.FirstOrDefault();

            if (_testCase == null)
            {
                _testCase       = _testManagement.TestCases.Create();
                _testCase.Title = "UnitTest_TestCase";

                var step1 = _testCase.CreateTestStep();
                step1.Title          = "First Step";
                step1.ExpectedResult = "Result of first step";

                var step2 = _testCase.CreateTestStep();
                step2.Title          = "Second Step";
                step2.ExpectedResult = "Result of second step";

                var step3 = _testCase.CreateTestStep();
                step3.Title          = "@DescriptionParameter";
                step3.ExpectedResult = "@ExpectedResultParameter";

                var ssr = _testCase.CreateSharedStepReference();
                ssr.SharedStepId = _sharedStep.Id;

                _testCase.Actions.Add(step1);
                _testCase.Actions.Add(step2);
                _testCase.Actions.Add(ssr);
                _testCase.Actions.Add(step3);
                _testCase.Save();
            }

            var testConfigurations = _testManagement.TestConfigurations.Query("Select * from TestConfiguration where Name='UnitTest_TestConfiguration'");

            _testConfiguration = testConfigurations.FirstOrDefault();

            if (_testConfiguration == null)
            {
                _testConfiguration      = _testManagement.TestConfigurations.Create();
                _testConfiguration.Name = "UnitTest_TestConfiguration";
                _testConfiguration.Save();
            }
        }
        public void CreateSprint1TestCases()
        {
            TfsTeamProjectCollection   tpc         = TfsConnect();
            ITestManagementTeamProject testProject = tpc.GetService <ITestManagementService>().GetTeamProject(TeamProject);

            // Get PBI work items

            int           count   = 0;
            WorkItemStore store   = new WorkItemStore(tpc);
            Project       project = store.Projects[TeamProject];

            string             wiql    = "SELECT [System.Id], [System.Title], [Microsoft.VSTS.Common.AcceptanceCriteria] FROM WorkItems " + "WHERE [System.TeamProject] = '" + TeamProject + "' AND [System.WorkItemType] = 'Product Backlog Item'";
            WorkItemCollection Backlog = store.Query(wiql);

            for (int i = 0; i < Backlog.Count; i++)
            {
                WorkItem pbi = Backlog[i];

                // Create the basic test case

                WorkItem wi = new WorkItem(project.WorkItemTypes["test case"]);
                wi.Title         = "Verify " + pbi.Title + " behavior";
                wi.IterationPath = @"Fabrikam\Release 1\Sprint 1";
                wi.Save();
                int id = wi.Id;
                TestCases.Add(pbi.Title.ToLower(), id);

                // Access test case through different service

                ITestCase testCase = testProject.TestCases.Find(id);

                // Parse test steps

                string criteria = pbi.Fields["Microsoft.VSTS.Common.AcceptanceCriteria"].Value.ToString();
                criteria = criteria.Remove(0, criteria.IndexOf(@"<ol"));

                Regex           regex = new Regex(@"<li>(.+?)<\/li>", RegexOptions.IgnoreCase);
                MatchCollection items = regex.Matches(criteria);
                foreach (Match item in items)
                {
                    string title = item.ToString();
                    title = title.Replace(@"<li>", "");
                    title = title.Replace(@"</li>", "");
                    title = title.Trim();
                    string expected = "";

                    // Click Employees {Employee list displays}

                    if (title.IndexOf("{") > 0)
                    {
                        expected = title.Substring(title.IndexOf("{"));
                        expected = expected.Replace(@"{", "");
                        expected = expected.Replace(@"}", "");
                        expected = expected.Trim();
                        title    = title.Substring(0, title.IndexOf("{"));
                        title    = title.Trim();
                    }
                    ITestStep step = testCase.CreateTestStep();
                    step.Title          = title;
                    step.ExpectedResult = expected;
                    testCase.Actions.Add(step);
                }
                testCase.Save();
                Console.Write(".");
                count++;
            }
            Console.WriteLine(string.Format(" ({0} test cases created)", count));
        }
Esempio n. 5
0
        /// <summary>
        /// Copies a test case.
        /// </summary>
        /// <param name="sourceTestCase">The source test case.</param>
        /// <param name="destinationTestSuite">The destination test suite.</param>
        private static string CopyTestCase(ITestCase sourceTestCase, IStaticTestSuite destinationTestSuite)
        {
            string results = string.Empty;

            ITestCase destinationTestCase = destinationTestSuite.Project.TestCases.Create();

            destinationTestCase.Title       = sourceTestCase.Title;
            destinationTestCase.Description = sourceTestCase.Description;
            destinationTestCase.Priority    = sourceTestCase.Priority;


            Debug.WriteLine("Test Case: " + sourceTestCase.Title);
            foreach (Field aField in sourceTestCase.CustomFields)
            {
                Debug.WriteLine(string.Format("Field Name: '{0}', Value: '{1}'", aField.Name, aField.Value));
            }

            List <Field> trueCustomFields = (from aField in destinationTestCase.CustomFields.Cast <Field>()
                                             where !aField.ReferenceName.StartsWith("Microsoft") &&
                                             !aField.ReferenceName.StartsWith("System")
                                             select aField).ToList();

            foreach (Field destField in trueCustomFields)
            {
                Field sourceField = (from aField in sourceTestCase.CustomFields.Cast <Field>()
                                     where aField.ReferenceName == destField.ReferenceName
                                     select aField).FirstOrDefault();

                if (sourceField != null)
                {
                    destField.Value = sourceField.Value;
                }
            }

            // Set Area and Iteration Paths
            string areaPath = sourceTestCase.CustomFields["Area Path"].Value.ToString();

            if (areaPath.Contains("\\"))
            {
                areaPath = areaPath.Replace(sourceTestCase.Project.TeamProjectName, destinationTestSuite.Project.TeamProjectName);  // replace the project name

                int areaId = (from node in _destinationAreaNodes
                              where node.Path == areaPath
                              select node.Id).FirstOrDefault();


                destinationTestCase.CustomFields["Area Path"].Value = areaPath;
                destinationTestCase.CustomFields["Area ID"].Value   = areaId;
            }

            string iterationPath = sourceTestCase.CustomFields["Iteration Path"].Value.ToString();

            if (iterationPath.Contains("\\"))
            {
                iterationPath = iterationPath.Replace(sourceTestCase.Project.TeamProjectName, destinationTestSuite.Project.TeamProjectName);  // replace the project name

                int iterationId = (from node in _destinationIterationNodes
                                   where node.Path == iterationPath
                                   select node.Id).FirstOrDefault();

                destinationTestCase.CustomFields["Iteration Path"].Value = iterationPath;
                destinationTestCase.CustomFields["Iteration ID"].Value   = iterationId;
            }

            #region Attachments

            foreach (ITestAttachment sourceAttachment in sourceTestCase.Attachments)
            {
                string filePath = Path.Combine(Path.GetTempPath(), sourceAttachment.Name);

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                sourceAttachment.DownloadToFile(filePath);

                ITestAttachment destinationAttachment = destinationTestCase.CreateAttachment(filePath);
                destinationAttachment.AttachmentType = sourceAttachment.AttachmentType;
                destinationAttachment.Comment        = sourceAttachment.Comment;

                destinationTestCase.Attachments.Add(destinationAttachment);

                destinationTestCase.Save();

                File.Delete(filePath);
            }

            #endregion

            #region Test Steps/Parameters

            foreach (ITestParameter sourceParameter in sourceTestCase.TestParameters)
            {
                destinationTestCase.ReplaceParameter(sourceParameter.Name, sourceParameter.Value);
            }

            foreach (ITestStep sourceAction in sourceTestCase.Actions)
            {
                ITestStep destinationTestStep = destinationTestCase.CreateTestStep();

                destinationTestStep.Title          = sourceAction.Title;
                destinationTestStep.Description    = sourceAction.Description;
                destinationTestStep.TestStepType   = sourceAction.TestStepType;
                destinationTestStep.ExpectedResult = sourceAction.ExpectedResult;
                destinationTestCase.Actions.Add(destinationTestStep);

                // Test Step Attachments
                foreach (ITestAttachment sourceAttachment in sourceAction.Attachments)
                {
                    string filePath = Path.Combine(Path.GetTempPath(), sourceAttachment.Name);

                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }

                    sourceAttachment.DownloadToFile(filePath);

                    ITestAttachment destinationAttachment = destinationTestStep.CreateAttachment(filePath);
                    destinationAttachment.AttachmentType = sourceAttachment.AttachmentType;
                    destinationAttachment.Comment        = sourceAttachment.Comment;

                    destinationTestStep.Attachments.Add(destinationAttachment);

                    try
                    {
                        destinationTestCase.Save();
                    }
                    catch (FileAttachmentException fileException)
                    {
                        destinationTestStep.Attachments.Remove(destinationAttachment);
                        results += string.Format(" - Suite: '{0}', Test Case: '{1}', Could not added attachment '{2}' due to '{3}'" + Environment.NewLine, destinationTestSuite.Title, destinationTestCase.Title, sourceAttachment.Name, fileException.Message);
                    }

                    File.Delete(filePath);
                }
            }

            #endregion

            destinationTestCase.Save();

            destinationTestCase.State = sourceTestCase.State;

            TeamFoundationIdentity sourceIdentity = sourceTestCase.Owner;

            if (sourceIdentity == null)
            {
                results += string.Format(" - Suite: '{0}', Test Case: '{1}', Could not set Assigned To user, not setup as a TFS user." + Environment.NewLine, destinationTestSuite.Title, destinationTestCase.Title);
            }
            else
            {
                TeamFoundationIdentity destinationIdentity = null;
                try
                {
                    destinationIdentity = destinationTestCase.Project.TfsIdentityStore.FindByAccountName(sourceIdentity.UniqueName);
                }
                catch (Exception e) { }

                if (destinationIdentity != null && destinationIdentity.IsActive)
                {
                    destinationTestCase.Owner = destinationIdentity;
                }
                else
                {
                    results += string.Format(" - Suite: '{0}', Test Case: '{1}', Could not set Assigned To user to '{2}'" + Environment.NewLine, destinationTestSuite.Title, destinationTestCase.Title, sourceIdentity.UniqueName);
                }
            }

            destinationTestCase.Save();

            destinationTestSuite.Entries.Add(destinationTestCase);
            destinationTestSuite.Plan.Save();

            return(results);
        }
Esempio n. 6
0
        public void CreateTestCases(string testCollectionFile, string testFieldsFile, ITestSuiteBase suite = null,
                                    string configIds = null)
        {
            var fields = FileHelper.GetTestFieldFromFile(testFieldsFile);
            var tests  = FileHelper.GetTestCaseFromFile(testCollectionFile);
            IList <ITestCase> testCases = null;

            if (suite != null)
            {
                testCases = new List <ITestCase>();
            }

            // reference: http://automatetheplanet.com/manage-tfs-test-cases-csharp-code/
            foreach (var test in tests)
            {
                ITestCase tc = _client.TeamProject.TestCases.Create();
                tc.Title = test.Key;

                // reference: http://www.ewaldhofman.nl/post/2009/12/11/TFS-SDK-2010-e28093-Part-5-e28093-Create-a-new-Test-Case-work-item.aspx
                foreach (var step in test.Value)
                {
                    var      tcs = tc.CreateTestStep();
                    string[] stepAndExpectedResult = step.Split('#');
                    tcs.Title = stepAndExpectedResult[0];
                    if (stepAndExpectedResult.Count() > 1)
                    {
                        StringBuilder builder = new StringBuilder();
                        for (int i = 1; i < stepAndExpectedResult.Count(); i++)
                        {
                            builder.Append(stepAndExpectedResult[i]);
                        }
                        tcs.ExpectedResult = builder.ToString();
                    }
                    tc.Actions.Add(tcs);
                }

                foreach (var field in fields)
                {
                    tc.CustomFields[field.Key].Value = field.Value;
                }

                tc.Save();

                if (suite != null)
                {
                    testCases.Add(tc);
                }
            }
            Console.WriteLine($"\nTotal test cases created: {tests.Count} ");

            if (suite != null)
            {
                AddTestCasesToSuite(testCases, suite);
                if (!string.IsNullOrWhiteSpace(configIds))
                {
                    TfsService.SuiteManager.UpdateConfigToSuites(suite.Id.ToString(), configIds, "all", "false", null,
                                                                 false);
                }
            }
            else
            {
                if (string.IsNullOrWhiteSpace(configIds))
                {
                    Console.WriteLine("Test configuration can't be assigned to test cases without test suite!");
                }
            }
        }
Esempio n. 7
0
        public void CreateTestCases(string testCollectionFile, ITestSuiteBase suite = null)
        {
            IList <ITestCase> testCases = null;
            int testCaseCreated         = 0;

            if (suite != null)
            {
                testCases = new List <ITestCase>();
            }

            // Use CSV file, please refer to: http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
            //using (CsvReader csv = new CsvReader(new StreamReader(testCollectionFile), true))
            //{
            //    int fieldCount = csv.FieldCount;

            //    string[] headers = csv.GetFieldHeaders();
            //    while (csv.ReadNextRecord())
            //    {
            //        for (int i = 0; i < fieldCount; i++)
            //            Console.Write($"{headers[i]} = {csv[i]};");
            //        Console.WriteLine();
            //    }
            //}

            // Use Excel file, please refer to: https://codealoc.wordpress.com/2012/04/19/reading-an-excel-xlsx-file-from-c/
            var            package   = new ExcelPackage(new FileInfo(testCollectionFile));
            ExcelWorksheet workSheet = package.Workbook.Worksheets.FirstOrDefault();

            if (workSheet != null)
            {
                if (!workSheet.Cells["A1"].Text.Equals("Title", StringComparison.InvariantCultureIgnoreCase) ||
                    !workSheet.Cells["B1"].Text.Equals("Steps", StringComparison.InvariantCultureIgnoreCase) ||
                    !workSheet.Cells["C1"].Text.Equals("Expected Result", StringComparison.InvariantCultureIgnoreCase))
                {
                    Console.WriteLine("The excel file header should be [Title], [Steps], [Expected Result] in order");
                    return;
                }
                if (string.IsNullOrWhiteSpace(workSheet.Cells["A2"].Text))
                {
                    Console.WriteLine("The first test case doesn't have name");
                    return;
                }
                int      colNum  = workSheet.Dimension.Columns;
                int      rowNum  = workSheet.Dimension.Rows;
                string[] headers = new string[colNum + 1];                 // excel starts from 1 instead of 0
                // fill headers:
                for (int h = 1; h <= colNum; h++)
                {
                    headers[h] = workSheet.Cells[1, h].Text;
                }
                // add test cases:
                for (int r = 2; r <= rowNum; r++)
                {
                    string    title = workSheet.Cells[r, 1].Text;
                    ITestCase tc    = _client.TeamProject.TestCases.Create();
                    var       owner = tc.Owner;
                    tc.Title = title;

                    // add fields:
                    for (int c = 4; c <= colNum; c++)
                    {
                        if (!string.IsNullOrWhiteSpace(headers[c]) &&
                            !string.IsNullOrWhiteSpace(workSheet.Cells[r, c].Text))
                        {
                            tc.CustomFields[headers[c]].Value = workSheet.Cells[r, c].Text;
                        }
                    }

                    // add the first step and result:
                    if (!string.IsNullOrWhiteSpace(workSheet.Cells[r, 2].Text) ||
                        !string.IsNullOrWhiteSpace(workSheet.Cells[r, 3].Text))
                    {
                        var tcs = tc.CreateTestStep();
                        tcs.Title          = workSheet.Cells[r, 2].Text;
                        tcs.ExpectedResult = workSheet.Cells[r, 3].Text;
                        tc.Actions.Add(tcs);
                    }

                    // add more steps and results:
                    while (string.IsNullOrWhiteSpace(workSheet.Cells[r + 1, 1].Text) ||
                           workSheet.Cells[r + 1, 1].Text.Equals(title, StringComparison.InvariantCultureIgnoreCase))
                    {
                        r++;
                        if (r > rowNum)
                        {
                            break;
                        }
                        if (!string.IsNullOrWhiteSpace(workSheet.Cells[r, 2].Text) ||
                            !string.IsNullOrWhiteSpace(workSheet.Cells[r, 3].Text))
                        {
                            var tcs = tc.CreateTestStep();
                            tcs.Title          = workSheet.Cells[r, 2].Text;
                            tcs.ExpectedResult = workSheet.Cells[r, 3].Text;
                            tc.Actions.Add(tcs);
                        }
                    }

                    try
                    {
                        if (tc.OwnerTeamFoundationId == Guid.Empty)
                        {
                            Console.WriteLine(
                                $"The AssignTo/Owner {tc.OwnerName} of the test case is not found in TFS, revert back to {owner.DisplayName}");
                            tc.Owner = owner;
                        }
                        tc.Save();
                        testCaseCreated++;
                    }
                    catch (TestManagementValidationException e)
                    {
                        Console.WriteLine($"Test Case Add Failed: {title}");
                        Console.WriteLine($"Test case added failed probably due to invliad fields: {e.Message}");
                    }

                    if (suite != null)
                    {
                        testCases.Add(tc);
                    }
                }
                Console.WriteLine($"\nTotal test cases created: {testCaseCreated} ");

                if (suite != null)
                {
                    AddTestCasesToSuite(testCases, suite);
                }
            }
        }