Beispiel #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);
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            // provide collection url of tfs
            var            collectionUri = "http://*****:*****@"C: \Users\pankagar\Downloads\Canvas.png", FileMode.Open, FileAccess.Read);
            var        attachmentObject = _witClient.CreateAttachmentAsync(uploadStream, "Canvas.png", "Simple").Result;

            // create a patchdocument object
            JsonPatchDocument json = new JsonPatchDocument();

            // create a new patch operation for title field
            JsonPatchOperation patchDocument1 = new JsonPatchOperation();

            patchDocument1.Operation = Operation.Add;
            patchDocument1.Path      = "/fields/System.Title";
            patchDocument1.Value     = "Testing Rest Api";
            json.Add(patchDocument1);

            // create a new patch operation for priority field
            JsonPatchOperation patchDocument2 = new JsonPatchOperation();

            patchDocument2.Operation = Operation.Add;
            patchDocument2.Path      = "/fields/Microsoft.VSTS.Common.Priority";
            patchDocument2.Value     = "2";
            json.Add(patchDocument2);


            // create testbasehelper object
            TestBaseHelper helper = new TestBaseHelper();
            // create testbase object to utilize teststep helpers
            ITestBase tb = helper.Create();

            // create 2 test steps ts1 and ts2
            ITestStep ts1 = tb.CreateTestStep();
            ITestStep ts2 = tb.CreateTestStep();

            ts1.Title          = "title -> title1";
            ts2.Title          = "title -> title2";
            ts1.ExpectedResult = "expected1";
            ts2.ExpectedResult = "expected2";
            ts1.Description    = "description1";
            ts2.Description    = "description2";
            // adding attachment to step1
            ts1.Attachments.Add(ts1.CreateAttachment(attachmentObject.Url, "CanvasImage"));

            // add your steps actions to testbase object
            tb.Actions.Add(ts1);
            tb.Actions.Add(ts2);

            // update json based on all actions (including teststeps and teststep attachemnts)
            json = tb.SaveActions(json);

            var xml = "";

            /* getting xml for teststeps
             * xml = tb.GenerateXmlFromActions();
             */

            // create Test Case work item using all test steps: ts1 and ts2
            var testCaseObject = _witClient.CreateWorkItemAsync(json, projectName, "Test Case").Result;
            int testCaseId     = Convert.ToInt32(testCaseObject.Id);

            // get Test Case using all relations
            testCaseObject = _witClient.GetWorkItemAsync(testCaseId, null, null, WorkItemExpand.Relations).Result;

            // update Test Case
            if (testCaseObject.Fields.ContainsKey("Microsoft.VSTS.TCM.Steps"))
            {
                xml = testCaseObject.Fields["Microsoft.VSTS.TCM.Steps"].ToString();
                tb  = helper.Create();

                // create tcmattachemntlink object from workitem relation, teststep helper will use this
                IList <TestAttachmentLink> tcmlinks = new List <TestAttachmentLink>();
                foreach (WorkItemRelation rel in testCaseObject.Relations)
                {
                    TestAttachmentLink tcmlink = new TestAttachmentLink();
                    tcmlink.Url        = rel.Url;
                    tcmlink.Attributes = rel.Attributes;
                    tcmlink.Rel        = rel.Rel;
                    tcmlinks.Add(tcmlink);
                }

                // load teststep xml and attachemnt links
                tb.LoadActions(xml, tcmlinks);

                ITestStep ts;
                //updating 1st test step
                ts                = (ITestStep)tb.Actions[0];
                ts.Title          = "title -> title11";
                ts.ExpectedResult = "expected11";

                //removing 2ns test step
                tb.Actions.RemoveAt(1);

                //adding new test step
                ITestStep ts3 = tb.CreateTestStep();
                ts3.Title          = "title -> title3";
                ts3.ExpectedResult = "expected3";
                tb.Actions.Add(ts3);

                JsonPatchDocument json2 = new JsonPatchDocument();
                // update json based on all new changes ( updated step xml and attachments)
                json2 = tb.SaveActions(json2);

                // update testcase wit using new json
                testCaseObject = _witClient.UpdateWorkItemAsync(json2, testCaseId).Result;

                /* Note : If you want to remove attachment then create new patchOperation, details are available here :
                 *        https://www.visualstudio.com/en-us/docs/integrate/api/wit/work-items#remove-an-attachment
                 */
            }
        }
Beispiel #3
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);
        }