Exemple #1
0
 public static AutomationTask CreateTask(AutomationTask instance)
 {
     using (ES1AutomationEntities context = new Core.Model.ES1AutomationEntities())
     {
         AutomationTask task = context.AutomationTasks.Add(instance);
         context.SaveChanges();
         return task;
     }
 }
Exemple #2
0
 public static string CodecoverageLine(int productId, Build build, AutomationTask task)
 {
     if (productId == 3)//Data Protection Search
     {
         return "<a href=\"http://10.98.26.221/api/" + build.Number + "\" style=\"color:#43c1d7; text-decoration:underline;\">Detail</a>";
     }
     else if (productId == 2)//CIS
     {
         return "<a href=\"http://10.98.28.192:8080/" + task.TaskId + "/" + task.GetJobs().First().JobId + "/coverage" + "\" style=\"color:#43c1d7; text-decoration:underline;\">Detail</a>";
     }
     return "TBD";
 }
Exemple #3
0
        public static Build GetLatestBuild(AutomationTask task)
        {
            using (ES1AutomationEntities context = new ES1AutomationEntities())
            {
                IList<Build> builds = (from b in context.Builds
                                      where b.ProductId == task.ProductId &&
                                          b.BranchId == task.BranchId &&
                                          b.ReleaseId == task.ReleaseId
                                      select b
                        ).ToList();
                return builds.OrderByDescending(b => int.Parse(b.Number.Split(new string[] { "." }, StringSplitOptions.None)[b.Number.Split(new string[] { "." }, StringSplitOptions.None).Length-1]))
                        .FirstOrDefault();

            }
        }
Exemple #4
0
 public int GetTaskExecutionPercentageByTaskId(AutomationTask task)
 {
     switch (task.Status)
     {
         case (int)TaskStatus.Scheduled:
             return 0;
         case (int)TaskStatus.Dispatched:
             return 10;
         case (int)TaskStatus.Running:
             return 20 + AutomationTask.GetTestCasesExecutionStatus(task.TaskId, 80);
         case (int) TaskStatus.Complete:
             return 100;
         default:
             return 100;
     }
 }
Exemple #5
0
 public static bool Delete(AutomationTask instance)
 {
     using (ES1AutomationEntities context = new Core.Model.ES1AutomationEntities())
     {
         context.AutomationTasks.Attach(instance);
         context.AutomationTasks.Remove(instance);
         context.SaveChanges();
     }
     return true;
 }
Exemple #6
0
        public static AutomationRunningStatusDTO GetTaskProgress(AutomationTask task)
        {
            AutomationRunningStatusDTO progress = new AutomationRunningStatusDTO();
            var testCasesExecutionStatusList = "";
            var testCasesExecutionStatusCountList = "";
            if (null == task)
            {
                progress.ExecutionPercentage = -1;
                progress.Status = (int)TaskStatus.Cancelled;
                progress.TaskId = -1;
                progress.Information = "There's no tasks executed yet for this project.";
                var resultType = typeof(ResultType);
                foreach (string result in Enum.GetNames(resultType))
                {
                    ResultType r = (ResultType)Enum.Parse(resultType, result);
                    int count = 0;
                    if (r == ResultType.NotRun)
                    {
                        count = 1;
                    }
                    else
                    {
                        count = 0;
                    }
                    testCasesExecutionStatusList += " " + r.ToString();
                    testCasesExecutionStatusCountList += " " + count.ToString();
                }

            }
            else
            {
                progress.ExecutionPercentage = GetTaskExecutionPercentageByTaskId(task);
                progress.Status = task.Status;
                progress.TaskId = task.TaskId;
                progress.Information = task.Information == null ? "Not Started Yet!" : task.Information;

                var resultType = typeof(ResultType);
                foreach (string result in Enum.GetNames(resultType))
                {
                    ResultType r = (ResultType)Enum.Parse(resultType, result);
                    int count = AutomationTask.GetResultTypeCountForTask(task.TaskId, r);
                    testCasesExecutionStatusList += " " + r.ToString();
                    testCasesExecutionStatusCountList += " " + count.ToString();
                }

            }
            progress.TestCasesExecutionStatusList = testCasesExecutionStatusList.TrimStart(' ');
            progress.TestCasesExecutionStatusCountList = testCasesExecutionStatusCountList.TrimStart(' ');
            return progress;
        }
Exemple #7
0
        /// <summary>
        /// Invoked when <see cref="ToEntity"/> operation is about to return.
        /// </summary>
        /// <param name="entity"><see cref="AutomationTask"/> converted from <see cref="AutomationTaskDTO"/>.</param>
partial         static void OnEntity(this AutomationTaskDTO dto, AutomationTask entity);
Exemple #8
0
        /// <summary>
        /// Converts this instance of <see cref="AutomationTaskDTO"/> to an instance of <see cref="AutomationTask"/>.
        /// </summary>
        /// <param name="dto"><see cref="AutomationTaskDTO"/> to convert.</param>
        public static AutomationTask ToEntity(this AutomationTaskDTO dto)
        {
            if (dto == null) return null;

            var entity = new AutomationTask();

            entity.TaskId = dto.TaskId;
            entity.Name = dto.Name;
            entity.Status = dto.Status;
            entity.Type = dto.Type;
            entity.Priority = dto.Priority;
            entity.CreateDate = dto.CreateDate;
            entity.CreateBy = dto.CreateBy;
            entity.ModifyDate = dto.ModifyDate;
            entity.ModifyBy = dto.ModifyBy;
            entity.BuildId = dto.BuildId;
            entity.EnvironmentId = dto.EnvironmentId;
            entity.TestContent = dto.TestContent;
            entity.Information = dto.Information;
            entity.Description = dto.Description;
            entity.RecurrencePattern = dto.RecurrencePattern;
            entity.StartDate = dto.StartDate;
            entity.StartTime = dto.StartTime;
            entity.WeekDays = dto.WeekDays;
            entity.WeekInterval = dto.WeekInterval;
            entity.ParentTaskId = dto.ParentTaskId;
            entity.BranchId = dto.BranchId;
            entity.ReleaseId = dto.ReleaseId;
            entity.ProductId = dto.ProductId;
            entity.ProjectId = dto.ProjectId;
            entity.WriteTestResultBack = dto.WriteTestResultBack;
            entity.NotifyStakeholders = dto.NotifyStakeholders;
            entity.SetupScript = dto.SetupScript;
            entity.TeardownScript = dto.TeardownScript;
            entity.EnableCodeCoverage = dto.EnableCodeCoverage;
            dto.OnEntity(entity);

            return entity;
        }
Exemple #9
0
 private static bool GetSupporttedEnvironmentAndCheckStatusOfItForTask(AutomationTask task)
 {
     SupportedEnvironment supEnv = SupportedEnvironment.GetSupportedEnvironmentById(task.EnvironmentId);
     if (supEnv == null)
     {
         ATFEnvironment.Log.logger.Error("Task: " + task.TaskId.ToString() + " ,Supported Environment ERROR");
         task.AddProgressInformation("Supported Environment ERROR");
         task.SetTaskStatus(TaskStatus.Failed);
         return false;
     }
     else
     {
         string message = string.Format("The support environment is ready for task [{0}]", task.Name);
         ATFEnvironment.Log.logger.Info(message);
         task.AddProgressInformation(message);
         return true;
     }
 }
Exemple #10
0
 /// <summary>
 /// Check whether all the jobs has been finished or not of the task
 /// 1. The 
 /// </summary>
 /// <param name="task"></param>
 /// <returns></returns>
 private static bool AreAllJobsOfTaskFinished(AutomationTask task)
 {
     List<AutomationJob> jobs = task.GetJobs();
     if (jobs == null || jobs.Count() <= 0)
     {
         ATFEnvironment.Log.logger.Warn("No jobs for Task " + task.TaskId.ToString());
         task.SetTaskStatus(TaskStatus.Failed);
         ATFEnvironment.Log.logger.Info("Change Task " + task.TaskId.ToString() + " status from Dispatched to Failed");
         task.AddProgressInformation("Change status: Dispatched to " + "Failed");
         return true;
     }
     else
     {
         foreach (AutomationJob job in jobs)
         {
             if (job.Status != (int)JobStatus.End
                 && job.Status != (int)JobStatus.Failed
                 && job.Status != (int)JobStatus.Complete
                 && job.Status != (int)JobStatus.Cancelled
                 && job.Status != (int)JobStatus.Timeout)
             {
                 return false;
             }
         }
         return true;
     }
 }
Exemple #11
0
 /// <summary>
 /// Write the test result back to provider of test case
 /// </summary>
 /// <param name="task">the automation task</param>
 public static void WriteTestResultBackToTestCaseProvider(AutomationTask task)
 {
     if (task.WriteTestResultBack.HasValue && task.WriteTestResultBack.Value)
     {
         Product product = Product.GetProductByID(task.ProductId.Value);
         Provider provider = Provider.GetProviderById(product.TestCaseProviderId.Value);
         Providers.TestCaseProviders.ITestCaseProvider testCaseProvider = provider.CreateProvider() as Providers.TestCaseProviders.ITestCaseProvider;
         testCaseProvider.WriteBackTestResult(task);
     }
 }
Exemple #12
0
        public static void SendTestReportOfTaskToStakeholders(AutomationTask task, bool force = false)
        {
            if (!task.NotifyStakeholders.HasValue && !force)
            {
                return;
            }

            Dictionary<string, string> taskDic = new Dictionary<string, string>();
            //the general information for the task
            Product product = Product.GetProductByID(task.ProductId.GetValueOrDefault());
            Build build = Build.GetBuildById(task.BuildId);
            taskDic.Add("name", task.Name);
            taskDic.Add("taskId", task.TaskId.ToString());
            taskDic.Add("product", product.Name);
            taskDic.Add("build", build.Name);
            string coverageLink = "";
            /*
            if(product.ProductId == 3)//Data Protection Search
            {
               coverageLink = "<a href=\"http://10.98.26.221/api/" + build.Number + "\" style=\"color:#43c1d7; text-decoration:underline;\">Detail</a>";
            }
            else
            {
                coverageLink = "TBD";
            }
             */
            coverageLink = CodecoverageLine(product.ProductId, build, task);
            taskDic.Add("coverageLink", coverageLink);
            taskDic.Add("release", Release.GetReleaseById(task.ReleaseId.GetValueOrDefault()).Name);
            taskDic.Add("branch", Branch.GetBranchById(task.BranchId.GetValueOrDefault()).Name);
            taskDic.Add("recurrencePattern", Enum.GetName(typeof(RecurrencePattern), task.RecurrencePattern.GetValueOrDefault()));
            taskDic.Add("test_environment", SupportedEnvironment.GetSupportedEnvironmentById(task.EnvironmentId).Name);
            taskDic.Add("creator", User.GetUserById(task.CreateBy).Username);
            taskDic.Add("status", Enum.GetName(typeof(TaskStatus), task.Status));
            string testResultStatic = "<tr><td width=\"100%\"  colspan=\"3\" align=\"left\" valign=\"middle\" style=\"padding:5px;font-family:Verdana, Geneva, sans-serif;\"><strong>@pass</strong> of <strong>@total</strong> <span style=\"color:#008000\"> </span> are passed. Passrate is <strong>@rate</strong></td></tr>";

            //the test case result information
            List<TestCaseExecution> testCaseExcutionCount = AutomationTask.GetTestCaseExecutionForAutomationTask(task.TaskId);
            List<List<TestCaseExecution>> tess = AutomationTask.GetTestCaseExecutionForAutomationTaskByGroup(task.TaskId);

            string testResultStringFailed = "";
            string testResultStringPassed = "";
            int totalPassCount = 0;
            if (null == testCaseExcutionCount || testCaseExcutionCount.Count == 0)
            {
                taskDic.Add("titleColor", "#808080");
                taskDic.Add("passRate", "None");
                taskDic.Add("result", "Execution result not found");
                taskDic.Add("total", "0");
                taskDic.Add("pass", "0");
            }
            else
            {

                foreach (List<TestCaseExecution> tes in tess)
                {
                    int passCount = 0;
                    string testTable="<tr><td width=\"100%\"><table width=\"100%\"><tr><td  width=\"100%\" align=\"center\" valign=\"middle\" style=\"padding:20px;font-family:Verdana, Geneva, sans-serif;font-size:24px; color:#6e6e6e;\"><b>@title </b></td></tr><tr><td width=\"100%\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td  width=\"50%\"  bgcolor=\"#FFFFFF\" ><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td height=\"30\" align=\"center\" valign=\"middle\" style=\"background-color:#FFA500;color:#FFFFFF;\">Test Case</td></tr></table></td><td width=\"16%\" align=\"left\" bgcolor=\"#FFFFFF\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"center\" valign=\"middle\" height=\"30\" style=\"background-color:#FFA500;color:#FFFFFF;\">Result</td ></tr></table></td><td width=\"34%\" align=\"left\" bgcolor=\"#FFFFFF\"><table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr><td align=\"center\" valign=\"middle\" height=\"30\" style=\"background-color:#FFA500;color:#FFFFFF;\">Log</td ></tr></table>	</td> </tr>@record </td></tr></table></td></tr></table></td></tr>";
                    List<Dictionary<string, string>> tcDicsPassed = new List<Dictionary<string, string>>();
                    List<Dictionary<string, string>> tcDicsFailed = new List<Dictionary<string, string>>();
                    string title = "Test Results";
                    bool suiteContainsFailures = false;
                    string suiteResultString = "";
                    if (tes[0].Info != null)
                    {
                        title = tes[0].Info;
                    }
                    testTable = testTable.Replace("@title", title);
                    foreach (TestCaseExecution te in tes)
                    {
                        TestResult tr = TestResult.GetTestResultByExecutionId(te.ExecutionId);
                        int resultType = tr.Result;

                            Dictionary<string, string> tcDic = new Dictionary<string, string>();
                            switch (resultType)
                            {
                                case 0:
                                    tcDic.Add("color", "green");
                                    tcDic.Add("testResult", "Pass");
                                    passCount++;
                                    break;
                                case 1:
                                    tcDic.Add("color", "red");
                                    tcDic.Add("testResult", "Failed");
                                    break;
                                case 2:
                                    tcDic.Add("color", "orange");
                                    tcDic.Add("testResult", "Time Out");
                                    break;
                                case 3:
                                    tcDic.Add("color", "yellow");
                                    tcDic.Add("testResult", "Exception");
                                    break;
                                case 4:
                                    tcDic.Add("color", "grey");
                                    tcDic.Add("testResult", "Not Run");
                                    break;
                                case 5:
                                    tcDic.Add("color", "firebrick");
                                    tcDic.Add("testResult", "Know Issue");
                                    break;
                                case 6:
                                    tcDic.Add("color", "tomato");
                                    tcDic.Add("testResult", "New Issue");
                                    break;
                                case 7:
                                    tcDic.Add("color", "lightskyblue");
                                    tcDic.Add("testResult", "Environment Issue");
                                    break;
                                case 8:
                                    tcDic.Add("color", "gold");
                                    tcDic.Add("testResult", "Scripts Issue");
                                    break;
                                case 9:
                                    tcDic.Add("color", "plum");
                                    tcDic.Add("testResult", "Common Library Issue");
                                    break;
                            }
                        //shorten the test case name and description if it's too long
                            int maxLines = 1;
                            int maxLineLength = 70;
                            int i = 0;
                            string caseName = TestCase.GetTestCase(te.TestCaseId).Name;
                            string subName = string.Empty;
                            string trimedLine = string.Empty;
                            while (caseName.Length > maxLineLength)
                            {

                                if (i < maxLines)
                                {
                                    i++;
                                    subName += string.Format(@"{0}<br/>", caseName.Substring(0, maxLineLength));
                                    caseName = caseName.Substring(maxLineLength);
                                }
                                else
                                {
                                    i = 0;
                                    caseName = "...";
                                    break;
                                }

                            }
                            subName += caseName;

                            tcDic.Add("testcaseName", subName);
                            string temp = string.IsNullOrEmpty(tr.Description) ? "" : tr.Description;
                            Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
                            temp = reg.Replace(temp, "");
                            //remove the test function name from the description
                            if (temp.IndexOf(@") [") > 0)
                            {
                                temp = temp.Substring(temp.IndexOf(@") [") + 2);
                            }
                            string resultLogString = string.Empty;
                            maxLineLength = 100;
                            i = 0;

                            foreach (string line in temp.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries))
                            {

                                trimedLine = line;
                                while (trimedLine.Length > maxLineLength)
                                {

                                    if (i < maxLines)
                                    {
                                        i++;
                                        resultLogString += string.Format(@"{0}<br/>", trimedLine.Substring(0, maxLineLength));
                                        trimedLine = trimedLine.Substring(maxLineLength);
                                    }
                                    else
                                    {
                                        i = 0;
                                        trimedLine = "...";
                                        break;
                                    }

                                }
                            }
                            resultLogString += trimedLine;
                            tcDic.Add("testResultLog", resultLogString);

                            if (resultType != 0)
                            {
                                tcDicsFailed.Add(tcDic);
                                suiteContainsFailures = true;
                            }
                            else
                            {
                                tcDicsPassed.Add(tcDic);
                            }

                    }

                    string testcaseT = "<td style=\"font-family:Verdana, Geneva, sans-serif; padding: 5px; color:#000000;\">@testcaseName</td>";
                    string testResultT = "<td align=\"center\" valign=\"middle\" style=\"font-family:Verdana, Geneva, sans-serif; padding: 5px; color:@color;\">@testResult</td>";
                    string testResultLogT = "<td align=\"left\" valign=\"left\" style=\"font-family:Verdana, Geneva, sans-serif; padding: 5px; color:@color;\">@testResultLog</td>";

                    string tempStringPassed = "";
                    string tempStringFailed = "";
                    foreach (Dictionary<string, string> d in tcDicsPassed)
                    {
                        string testcaseTemp = testcaseT;
                        string testResultTemp = testResultT;
                        string testResultLogTemp = testResultLogT;
                        foreach (KeyValuePair<string, string> p in d)
                        {
                            testcaseTemp = testcaseTemp.Replace("@" + p.Key, p.Value);
                            testResultTemp = testResultTemp.Replace("@" + p.Key, p.Value);
                            testResultLogTemp = testResultLogT.Replace("@" + p.Key, p.Value);
                        }

                        tempStringPassed += @"<tr>" + testcaseTemp + testResultTemp + testResultLogTemp + @"</tr>";

                    }
                    foreach (Dictionary<string, string> d in tcDicsFailed)
                    {
                        string testcaseTemp = testcaseT;
                        string testResultTemp = testResultT;
                        string testResultLogTemp = testResultLogT;
                        foreach (KeyValuePair<string, string> p in d)
                        {
                            testcaseTemp = testcaseTemp.Replace("@" + p.Key, p.Value);
                            testResultTemp = testResultTemp.Replace("@" + p.Key, p.Value);
                            testResultLogTemp = testResultLogT.Replace("@" + p.Key, p.Value);
                        }

                        tempStringFailed += @"<tr>" + testcaseTemp + testResultTemp + testResultLogTemp + @"</tr>";

                    }
                    suiteResultString = testTable.Replace("@record", tempStringFailed + tempStringPassed);

                    string testSubResultStatic = testResultStatic.Replace("@pass", passCount.ToString());
                    testSubResultStatic = testSubResultStatic.Replace("@rate", Math.Round((double)passCount / tes.Count, 3) * 100 + "%");
                    testSubResultStatic = testSubResultStatic.Replace("@total", tes.Count.ToString());
                    suiteResultString += testSubResultStatic;

                    totalPassCount += passCount;

                    if (suiteContainsFailures)
                    {
                        testResultStringFailed += suiteResultString;
                    }
                    else
                    {
                        testResultStringPassed += suiteResultString;
                    }

                   // taskDic.Add("total", tes.Count.ToString());
                  //  taskDic.Add("pass", passCount.ToString());
                }
                if (totalPassCount == 0)
                {
                    taskDic.Add("titleColor", "#d80000");
                }
                else if (testCaseExcutionCount.Count == totalPassCount)
                {
                    taskDic.Add("titleColor", "#008000");
                }
                else
                {
                    taskDic.Add("titleColor", "#FFD700");
                }
                string res = @"<strong>" + totalPassCount + @"</strong> of " + @"<strong>" + testCaseExcutionCount.Count + @"</strong> cases are passed";
                taskDic.Add("passRate", Math.Round((double)totalPassCount / testCaseExcutionCount.Count, 3) * 100 + "%");
                taskDic.Add("result", res);
            }

            string template = string.Empty;
            using (StreamReader sr = new StreamReader(AssemblyHelper.GetAssemblePath() + "/Documents/galaxy_result_report_template.html"))
            {
                template = sr.ReadToEnd();
            }
            foreach (KeyValuePair<string, string> p in taskDic)
            {
                template = template.Replace("@" + p.Key, p.Value);
            }
            string mailContent = "";
            string attachment = "";
            if (testCaseExcutionCount.Count>500)
            {
                template = template.Replace("@remark", "Only the failed test suites are shown in the right. For the detail, please open the attachment.");
                mailContent = template.Replace("@TOBEREPLACED", testResultStringFailed);
                string reportFile = template.Replace("@TOBEREPLACED", testResultStringFailed + testResultStringPassed);
                attachment = "fullreport.html";
                File.WriteAllText(attachment, reportFile);
            }
            else
            {
                template = template.Replace("@remark", "None");
                mailContent = template.Replace("@TOBEREPLACED", testResultStringFailed + testResultStringPassed);
            }

            List<string> to = new List<string>();
            List<string> cc = new List<string>();
            to.Add(User.GetUserById(task.CreateBy).Email);
            if (task.NotifyStakeholders.Value)
            {
                cc = Subscriber.GetSubscribersEmailByProjectId(task.ProjectId.GetValueOrDefault());
            }

            try
            {
                string smtpServer = ATFConfiguration.GetStringValue("DefaultSMTPServer");
                MailHelper.sendMail(smtpServer, "*****@*****.**", to, cc, "[Test report]" + taskDic["name"] + "-Pass rate: " + taskDic["passRate"], mailContent, attachment);
            }
            catch (Exception e)
            {
                ATFEnvironment.Log.logger.Error("Failed to send the mails.", e);
            }
        }
Exemple #13
0
 /// <summary>
 /// Check whether one of the job has been started of the task
 /// </summary>
 /// <param name="task">task</param>
 /// <returns></returns>
 private static bool IsOneJobOfTaskStarted(AutomationTask task)
 {
     List<AutomationJob> jobs = task.GetJobs();
     if (jobs == null || jobs.Count() <= 0)
     {
         ATFEnvironment.Log.logger.Warn("No jobs for Task " + task.TaskId.ToString());
         task.SetTaskStatus(TaskStatus.Failed);
         ATFEnvironment.Log.logger.Info("Change Task " + task.TaskId.ToString() + " status from Dispatched to Failed");
         task.AddProgressInformation("Change status: Dispatched to " + "Failed");
         return false;
     }
     else
     {
         foreach (AutomationJob job in jobs)
         {
             if (job.Status != (int)JobStatus.Assigned)//The initial status of job
             {
                 return true;
             }
         }
         return false;
     }
 }
Exemple #14
0
 private static bool IsBuildOfTaskReady(AutomationTask task)
 {
     Build build = Build.GetBuildById(task.BuildId);
     switch (build.Status)
     {
         case (int)BuildStatus.Success:
             {
                 string message = string.Format("The build [{0}] is ready.", build.Name);
                 ATFEnvironment.Log.logger.Info(message);
                 task.AddProgressInformation(message);
                 return true;
             }
         case (int)BuildStatus.Failed:
             {
                 string message = string.Format("The build [{0}] is failed.", build.Name);
                 ATFEnvironment.Log.logger.Info(message);
                 task.AddProgressInformation(message);
                 task.SetTaskStatus(TaskStatus.Failed);
                 return false;
             }
         case (int)BuildStatus.NotExist:
             {
                 string message = string.Format("The build [{0}] doesn't exist.", build.Name);
                 ATFEnvironment.Log.logger.Info(message);
                 task.AddProgressInformation(message);
                 task.SetTaskStatus(TaskStatus.Failed);
                 return false;
             }
         case (int)BuildStatus.Delete:
             {
                 string message = string.Format("The build [{0}] has been deleted.", build.Name);
                 ATFEnvironment.Log.logger.Info(message);
                 task.AddProgressInformation(message);
                 task.SetTaskStatus(TaskStatus.Failed);
                 return false;
             }
         default:
             {
                 string message = string.Format("The status of build {0} is invalid.", build.Name);
                 ATFEnvironment.Log.logger.Error(message);
                 task.AddProgressInformation(message);
                 task.SetTaskStatus(TaskStatus.Failed);
                 return false;
             }
     }
 }
Exemple #15
0
        /// <summary>
        /// Write the test result back to RQM
        /// </summary>
        /// <param name="task">the automation task</param>
        public void WriteBackTestResult(AutomationTask task)
        {
            ATFEnvironment.Log.logger.Info("RQM Login");
            try
            {
                RQMServer.UserAuthentication(Username, Password);
            }
            catch (Exception ex)
            {
                ATFEnvironment.Log.logger.Error("Failed to login RQM", ex);
                return;
            }

            ATFEnvironment.Log.logger.Info(string.Format("Start to write back the test result for task [{0}]", task.Name));

            string testPlanTitle = string.Format("{0} : {1}", RQMTESTPLANPREFIX, task.Name);
            string projectAlias = ProjectAlias;

            SupportedEnvironment environment = SupportedEnvironment.GetSupportedEnvironmentById(task.EnvironmentId);
            string environmentId = string.Empty;
            try
            {
                environmentId = RQMServer.GetOrCreateTestEnvironment(projectAlias, environment.Name, environment.Description, environment.Config);
            }
            catch (Exception ex)
            {
                ATFEnvironment.Log.logger.Error("Failed to get or create the test environment in RQM", ex);
            }
            Build build = Build.GetBuildById(task.BuildId);
            string buildId = string.Empty;
            try
            {
                buildId = RQMServer.GetOrCreateBuildRecord(projectAlias, build.Name, string.Format("Build created by Galaxy system. Name:{0}; Location:{1}; Description: {2}", build.Name, build.Location, build.Description));
            }
            catch (Exception ex)
            {
                ATFEnvironment.Log.logger.Error("Failed to get or create the build record in RQM", ex);
            }

            List<TestCase> testCases = AutomationTask.GetTestCasesForAutomationTask(task.TaskId).ToList();

            string testPlanWebId = string.Empty;
            if (task.Type == (int)TaskType.ByTestPlan)
            {
                try
                {
                    TestSuite rootSuite = TestSuite.GetTestSuite(int.Parse(task.TestContent));
                    TestSuite testPlanSuite = TestSuite.GetTestSuite(int.Parse(rootSuite.SubSuites.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault().Trim()));
                    testPlanWebId = testPlanSuite.SourceId;
                }
                catch (Exception ex)
                {
                    ATFEnvironment.Log.logger.Error(string.Format("Failed to get the test plan through the task."), ex);
                }
            }
            else
            {
                try
                {
                    testPlanWebId = RQMServer.CreateTestPlan(projectAlias, testPlanTitle, task.Description, testCases.Select(t => t.SourceId).ToArray(), new string[] { environmentId });
                }
                catch (Exception ex)
                {
                    ATFEnvironment.Log.logger.Error("Failed to create test plan in RQM", ex);
                }
            }

            if (string.IsNullOrWhiteSpace(testPlanWebId))
            {
                ATFEnvironment.Log.logger.Error(string.Format("Failed to create or get the existing test plan [{0}] on RQM.", testPlanTitle));
                return;
            }
            else
            {
                ATFEnvironment.Log.logger.Info(string.Format("Test plan [{0}:{1}] has been created in RQM.", testPlanWebId, testPlanTitle));
            }

            foreach (TestCase testCase in testCases)
            {
                string executionRecordWebId = string.Empty;

                TestCaseExecution execution = AutomationTask.GetTestCaseExecutionForTestCaseInTask(task.TaskId, testCase.TestCaseId);
                System.DateTime startTime = (execution != null && execution.StartTime.HasValue) ? execution.StartTime.Value : System.DateTime.UtcNow;
                System.DateTime endTime = (execution != null && execution.EndTime.HasValue) ? execution.EndTime.Value : System.DateTime.UtcNow;
                try
                {
                    executionRecordWebId = RQMServer.GetOrCreateTestCaseExecutionRecord(projectAlias, testCase.Name, string.Format("Created by Galaxy. Test environment : {0}, Build : {1}", environment.Name, build.Name), testCase.SourceId, testPlanWebId, environmentId);
                }
                catch (Exception ex)
                {
                    ATFEnvironment.Log.logger.Error("Failed to get or create test case execution record in RQM", ex);
                }
                if (string.IsNullOrWhiteSpace(executionRecordWebId))
                {
                    ATFEnvironment.Log.logger.Error(string.Format("Failed to create the test execution record for case [{0}] on RQM.", testCase.Name));
                    continue;
                }
                else
                {
                    ATFEnvironment.Log.logger.Info(string.Format("Test execution record [{0}:{1}] has been created in RQM.", executionRecordWebId, testCase.Name));
                }

                string result = string.Empty;
                if (execution != null)
                {
                    TestResult testResult = TestResult.GetTestResultByExecutionId(execution.ExecutionId);
                    result = ConvertGalaxyResultToRQMResult(testResult.ResultType);
                }
                else
                {
                    result = RQMTestResult.Incomplete;
                }

                string resultWebId = string.Empty;
                try
                {
                    resultWebId = RQMServer.CreateTestResult(projectAlias, executionRecordWebId, testCase.Name, result, buildId, startTime, endTime);
                }
                catch (Exception ex)
                {
                    ATFEnvironment.Log.logger.Error("Failed to create test result in RQM", ex);
                }
                if (string.IsNullOrWhiteSpace(resultWebId))
                {
                    ATFEnvironment.Log.logger.Error(string.Format("Failed to create the execution result [{0}] in RQM.", testCase.Name));
                    continue;
                }
                else
                {
                    ATFEnvironment.Log.logger.Info(string.Format("Execution result [{0}:{1}] has been created in RQM.", resultWebId, testCase.Name));
                }
            }

            RQMServer.Logout();
        }
Exemple #16
0
 public void WriteBackTestResult(AutomationTask task)
 {
     //throw new NotImplementedException();
 }
Exemple #17
0
 private static void CreateWeeklyWindowsScheduledTask(AutomationTask task)
 {
     JavaScriptSerializer serializer = new JavaScriptSerializer();
     string administrator = ConfigurationManager.AppSettings["TaskManagerHostAdministrator"];
     string password = ConfigurationManager.AppSettings["TaskManagerHostPassword"];
     string taskName = string.Format("[Scheduled] {0}", task.Name);
     string taskDescription = string.Format("Galaxy-Scheduled-Task-For-Automation-Task-{0}", task.Name);
     int notifyStakeholders = task.NotifyStakeholders.HasValue && task.NotifyStakeholders.Value ? 1 : 0;
     int writeTestResultBack = task.WriteTestResultBack.HasValue && task.WriteTestResultBack.Value ? 1 : 0;
     string programPath = "ruby.exe";
     StringBuilder builder = new StringBuilder();
     builder.AppendFormat(@"""{0}""", ConfigurationManager.AppSettings["WindowsScheduleTaskProgramPath"]);
     string format = @" '{{ ""Name"":""{0}"",""Status"":{1},""Type"":{2},""Priority"":{3},""CreateBy"":{4},""ModifyBy"":{5},""BuildId"":{6},""EnvironmentId"":{7},""TestContent"":{8},""Description"":""{9}"",""RecurrencePattern"":{10},""StartDate"":{11},""StartTime"":{12},""WeekDays"":{13},""WeekInterval"":{14}, ""ParentTaskId"":{15}, ""BranchId"":{16}, ""ReleaseId"":{17}, ""ProductId"":{18}, ""ProjectId"":{19}, ""NotifyStakeholders"":{20}, ""WriteTestResultBack"":{21}, ""SetupScript"":""{22}"", ""TeardownScript"":""{23}"" }}'";
     builder.AppendFormat(format, taskName, (int)TaskStatus.Scheduled, task.Type, 0, 0, 0, task.BuildId, task.EnvironmentId, task.TestContent, taskDescription, (int)RecurrencePattern.AtOnce, serializer.Serialize(task.StartDate.GetValueOrDefault()), serializer.Serialize(task.StartTime.GetValueOrDefault()), task.WeekDays.GetValueOrDefault(), task.WeekInterval.GetValueOrDefault(), task.TaskId, task.BranchId.GetValueOrDefault(), task.ReleaseId.GetValueOrDefault(), task.ProductId.GetValueOrDefault(), task.ProjectId, notifyStakeholders, writeTestResultBack, task.SetupScript.Replace("\\", "\\\\").Replace("\"", "\\\""), task.TeardownScript.Replace("\\", "\\\\").Replace("\"", "\\\""));
     string programParameters = builder.ToString();
     string programeWorkingDirectory = ConfigurationManager.AppSettings["WindowsScheduleTaskProgramWorkingDirectory"];
     DateTime startDateTime = task.StartDate.Value;
     ScheduledTask.CreateWindowsScheduledWeeklyTask(administrator, password, taskName, taskDescription, programPath, programParameters, programeWorkingDirectory, (short)task.WeekDays.Value, (short)task.WeekInterval.Value, task.StartDate.Value);
 }
Exemple #18
0
        /// <summary>
        /// Dispatch task to jobs based on the test suites defined for dependance
        /// </summary>
        /// <param name="task"></param>
        /// <param name="allCasesForTask"></param>
        private static void DispatchTaskToJobs(AutomationTask task, List<int> allCasesForTask)
        {
            int i = 0;
            string message = string.Empty;
            //Store whether the test cases have been dispatched to job or not based on dependency test suite
            Dictionary<string, bool> testCaseDispatchIndicator = new Dictionary<string, bool>();
            int testcaseProviderId = Product.GetProductByID(task.ProductId.GetValueOrDefault()).TestCaseProviderId.GetValueOrDefault();

            List<TestSuite> dependenceSuites = TestSuite.GetTestSuitesByProviderIdAndType(testcaseProviderId, SuiteType.Dependence).ToList();
            foreach (TestSuite dependenceSuite in dependenceSuites)
            {
                string testCasesForJob = string.Empty;
                foreach (string tc in dependenceSuite.TestCases.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    if (allCasesForTask.Contains(int.Parse(tc)) && !testCaseDispatchIndicator.ContainsKey(tc))
                    {
                        testCasesForJob = testCasesForJob == string.Empty ? tc : testCasesForJob + ',' + tc;
                        testCaseDispatchIndicator.Add(tc, true);
                    }
                }
                if (testCasesForJob != string.Empty)
                {
                    // Create AutomationJob
                    ++i;
                    AutomationJob job = new AutomationJob()
                    {
                        Name = "JobForTask " + task.TaskId.ToString() + "_" + i.ToString(),
                        Status = (int)JobStatus.Assigned,
                        Type = (int)JobType.Sequence,
                        Priority = task.Priority,
                        RetryTimes = 1,
                        Timeout = ATFConfiguration.GetIntValue("DefaultAutomationJobTimeout"),//1 hours
                        CreateDate = System.DateTime.UtcNow,
                        ModifyDate = System.DateTime.UtcNow,
                        CreateBy = 0,//automation, pre-defined user
                        ModifyBy = 0,//automation, pre-defined user
                    };
                    AutomationJob bCreateJob = AutomationJob.CreateJob(job);

                    message = string.Format("Job [{0}] is created.", bCreateJob.JobId);
                    task.AddProgressInformation(message);
                    ATFEnvironment.Log.logger.Info(message);

                    TaskJobMap map = new TaskJobMap()
                    {
                        TaskId = task.TaskId,
                        JobId = job.JobId,
                    };
                    TaskJobMap.CreateMap(map);

                    foreach (string id in testCasesForJob.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        TestCaseExecution ex = new TestCaseExecution()
                        {
                            TestCaseId = int.Parse(id),
                            JobId = job.JobId,
                            Status = (int)ExecutionStatus.NotRunning,
                            StartTime = null,
                            EndTime = null,
                            RetryTimes = 0,
                            Timeout = ATFEnvironment.DefaultTestCaseTimeout,
                        };
                        TestCaseExecution exInDB = TestCaseExecution.CreateExecution(ex);

                        message = string.Format("Execution [{0}] is created.", exInDB.ExecutionId);
                        //task.AddProgressInformation(message);
                        ATFEnvironment.Log.logger.Info(message);

                        TestResult result = new TestResult
                        {
                            ExecutionId = exInDB.ExecutionId,
                            Result = (int)ResultType.NotRun,
                            IsTriaged = false,
                            TriagedBy = null,
                            Files = null,
                        };
                        TestResult.CreateRunResult(result);

                        message = string.Format("Test result [{0}] is created.", result.ResultId);
                        //task.AddProgressInformation(message);
                        ATFEnvironment.Log.logger.Info(message);
                    }
                }
            }

            foreach (int testcaseId in allCasesForTask)
            {
                if (!testCaseDispatchIndicator.ContainsKey(testcaseId.ToString()))//not dispatched to jobs yet
                {
                    // Create AutomationJob
                    ++i;
                    AutomationJob job = new AutomationJob()
                    {
                        Name = "JobForTask " + task.TaskId.ToString() + "_" + i.ToString(),
                        Status = (int)JobStatus.Assigned,
                        Type = (int)JobType.Sequence,
                        Priority = task.Priority,
                        RetryTimes = 1,
                        Timeout = ATFConfiguration.GetIntValue("DefaultAutomationJobTimeout"),//1 hours
                        CreateDate = System.DateTime.UtcNow,
                        ModifyDate = System.DateTime.UtcNow,
                        CreateBy = 0,//automation, pre-defined user
                        ModifyBy = 0,//automation, pre-defined user
                    };
                    AutomationJob bCreateJob = AutomationJob.CreateJob(job);

                    message = string.Format("Job [{0}] is created.", bCreateJob.JobId);
                    task.AddProgressInformation(message);
                    ATFEnvironment.Log.logger.Info(message);

                    TaskJobMap map = new TaskJobMap()
                    {
                        TaskId = task.TaskId,
                        JobId = job.JobId,
                    };
                    TaskJobMap.CreateMap(map);

                    TestCaseExecution ex = new TestCaseExecution()
                    {
                        TestCaseId = testcaseId,
                        JobId = job.JobId,
                        Status = (int)ExecutionStatus.NotRunning,
                        StartTime = null,
                        EndTime = null,
                        RetryTimes = 0,
                        Timeout = ATFEnvironment.DefaultTestCaseTimeout,
                    };
                    TestCaseExecution exInDB = TestCaseExecution.CreateExecution(ex);

                    message = string.Format("Execution [{0}] is created.", exInDB.ExecutionId);
                    //task.AddProgressInformation(message);
                    ATFEnvironment.Log.logger.Info(message);

                    TestResult result = new TestResult
                    {
                        ExecutionId = exInDB.ExecutionId,
                        Result = (int)ResultType.NotRun,
                        IsTriaged = false,
                        TriagedBy = null,
                        Files = null,
                    };
                    TestResult.CreateRunResult(result);

                    message = string.Format("Test result [{0}] is created.", result.ResultId);
                    //task.AddProgressInformation(message);
                    ATFEnvironment.Log.logger.Info(message);
                }
            }
        }
Exemple #19
0
        private static bool GetBuildAndCheckStatusOfItForTask(AutomationTask task)
        {
            //if build id = 0, we need to get the latest mainline build for this task
            if (task.BuildId == 0)
            {
                Build latestBuild = BuildManager.GetLatestBuild(task);
                if (null != latestBuild)
                {
                    string message = string.Format("The latest mainline build is {0}", latestBuild.Name);
                    ATFEnvironment.Log.logger.Info(message);
                    task.AddProgressInformation(message);
                    task.SetBuild(latestBuild.BuildId);
                }
                else
                {
                    string message = string.Format("Could not find the latest build for task {0}", task.Name);
                    ATFEnvironment.Log.logger.Error(message);
                    task.AddProgressInformation(message);
                    task.SetTaskStatus(TaskStatus.Failed);
                    return false;
                }
            }

            // Check whether build is ready
            if (!IsBuildOfTaskReady(task))
            {
                return false;
            }
            else
            {
                return true;
            }
        }