Pending Code coverage:
Abort functionality
In progress statuses:
*********
public with sharing class AutomatedTestSetup_Controller {
public boolean hasScheduledJobs { get; set; }
public boolean hasTestRun { get; set; }
public boolean hasAbort { get; set; }
public boolean hasemailpending { get; set; }
public boolean isRunning { get; set; }
public boolean isEmailing { get; set; }
public AutomatedTestSetup_Controller ATS { get; set; }
public String DtValue {get; set; }
public boolean showMessage {get;set;}
public String showdatetime{get;set;}
public String Staticstics{get;set;}
public Decimal Percentage{get;set;}
public String shddatetime {get;set;}
public String ATRdetails {get;set;}
public List<CronTrigger> Schdjobs{get;set;}
public String Jobstatus {get;set;}
public Automated_Test_Run__c AtrRecord {get; set;}
//public List<Shdwrapper> cronjbs=New List<Shdwrapper>(){get;set;}
id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
id ATEmailRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
public PageReference doInsert() {
// Automated_Test_Run__c objdlt = new Automated_Test_Run__c();
AtrRecord.Query__c=AtrRecord.Query__c;
AtrRecord.Excluded_Classes__c=AtrRecord.Excluded_Classes__c;
AtrRecord.Exclude_Managed_Packages__c=AtrRecord.Exclude_Managed_Packages__c;
AtrRecord.Schedule__c=AtrRecord.Schedule__c;
AtrRecord.RecordTypeId=ATERecordTypeId;
//insert AtrRecord;
Automated_Test_Run__c ATEemail = new Automated_Test_Run__c();
ATEemail.Emails__c=AtrRecord.Emails__c;
ATEemail.Email_on_Pass__c=AtrRecord.Email_on_Pass__c;
ATEemail.RecordTypeId=ATEmailRecordTypeId;
//insert ATEemail;
Savepoint sp = Database.setSavepoint();
try{
scheduleJobs(AtrRecord.Schedule__c);
if(showMessage==false){
upsert AtrRecord;
upsert ATEemail;
}
}
catch(exception ex){
Database.rollback(sp);
}
/*PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;*/
return null;
}
public Automated_Test_Run__c getAtrRecord()
{
return AtrRecord;
}
public AutomatedTestSetup_Controller(ApexPages.StandardController controller) {
//Automated_Test_Run__c AtrRecord = new Automated_Test_Run__c();//from
AtrRecord = (Automated_Test_Run__c)Controller.getRecord();
this.ATS=ATS;
showMessage=false;
refreshHasScheduledJobs();
refreshHasTestRun();
ShowAbortbutton();
getPieData();
Calculatepercentage();
GetATSRunDeatils();
EmailSendPending();
}
public void refreshHasScheduledJobs() {
//integer jobCount = [select count() from CronJobDetail where Name like '%TestRunner%' and JobType = '7'];
//integer jobCount = [SELECT count() FROM CronTrigger where CronJobDetail.Name like '%TestRunner%' and State in('WAITING','ACQUIRED','EXECUTING')];
integer jobCount = [SELECT count() FROM CronTrigger where CronJobDetail.Name like '%TestRunner%'];
//integer jobCount = [SELECT count() FROM CronTrigger where CronJobDetail.Name like '%TestRunner%' and State in('WAITING','ACQUIRED','EXECUTING')];
Schdjobs=[SELECT CronJobDetail.Name,CreatedDate,NextFireTime,State FROM CronTrigger where CronJobDetail.Name like '%TestRunner%' and State in('WAITING','ACQUIRED','EXECUTING')];
if(Schdjobs.size()>0){
Jobstatus=Schdjobs[0].State;
if(Schdjobs[0].NextFireTime!=null ){
Datetime shddatetimeGSt=Schdjobs[0].NextFireTime;
Datetime gmt = shddatetimeGSt;
String timeZone = UserInfo.getTimeZone().getID();
Datetime GivenDateTime=shddatetimeGSt;// here you can user your dates e.g. createddate
Datetime localdt=Datetime.valueOf(GivenDateTime);
//showdatetime = string.valueOfGmt(local);
shddatetime=localdt.format();
}
else if(Jobstatus!=null && Jobstatus!='') {
shddatetime='Test Scheduled Job Current State is '+Jobstatus;
}
}
hasScheduledJobs = jobCount !=0;
//hasScheduledJobs = (jobCount !=0 && Schdjobs.size()>0);
/*if(jobCount !=0){
hasScheduledJobs = jobCount !=0;
}else if(Schdjobs.size()>0){
hasScheduledJobs =true;
} */
}
public void GetATSRunDeatils() {
List<String> Keywords=New List<String>();
Keywords.clear();
ATRdetails='';
//id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
for(Automated_Test_Run__c atr: [select Query__c, Excluded_Classes__c,
Email_on_Pass__c, Exclude_Managed_Packages__c
from Automated_Test_Run__c
where Active__c = true and RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]){
Keywords.add(atr.Query__c);
}
if(Keywords.size()>0){
for(String kw:Keywords){
ATRdetails+=kw;
}
}
}
public void refreshHasTestRun() {
integer runCount = [select count() from Automated_Test_Run__c limit 1];
hasTestRun = runCount > 0;
}
public void ShowAbortbutton(){
integer runCount = [select count() from Automated_Test_Run__c limit 1];
Test_Runner_Job__c RunningJobnm =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
integer TestexecrunCount = [select count() from ApexTestQueueItem WHERE Status IN ('Holding','Queued','Preparing','Processing') and ParentJobId=:RunningJobnm.Name];
hasAbort = TestexecrunCount > 0;
//hasScheduledJobs = TestexecrunCount > 0;
}
public void EmailSendPending(){
List<Test_Runner_Job__c> runCountJob = [select id from Test_Runner_Job__c where Processed__c=false order by CreatedDate desc limit 1];
hasemailpending = runCountJob.size()> 0;
//hasScheduledJobs = TestexecrunCount > 0;
}
public string getTestRunLink() {
return '/' + Automated_Test_Run__c.SObjectType.getDescribe().getKeyPrefix();
}
public AutomatedTestSetup_Controller() {
Automated_Test_Run__c AtrRecord = new Automated_Test_Run__c();
refreshHasScheduledJobs();
refreshHasTestRun();
//getPieData();
Calculatepercentage();
ShowAbortbutton();
EmailSendPending();
}
public PageReference scheduleJobs(Datetime DtValue) {
System.debug('Date & Time is given***1'+DtValue);
deleteCompletedJobs();
Datetime gmt = DtValue;
String timeZone = UserInfo.getTimeZone().getID();
Datetime GivenDateTime=DtValue;// here you can user your dates e.g. createddate
System.debug('GivenDateTime is***'+GivenDateTime);
Datetime local=Datetime.valueOf(GivenDateTime);
System.debug('local is***'+local);
Map <Integer,String> monthNumbers = new Map <Integer,String> {1=>'Jan', 2=>'Feb',3=>'Mar',4=>'Apr', 5=>'May', 6=>'Jun',7=>'Jul',8=>'Aug', 9=>'Sep', 10=>'Oct', 11=>'Nov', 12=>'Dec'};
String TestShdmonth=monthNumbers.get(local.month());
String strSchedule = '0 ' + local.minute() + ' ' +local.hour()+ ' ' + local.day()+ ' ' + TestShdmonth+ ' ? ' + ' ' + local.year();
System.debug('***strSchedule***'+strSchedule);
AutoTestRunner.setup(strSchedule);
refreshHasScheduledJobs();
return null;
}
public PageReference CancelJobs() {
//List<CronTrigger> jobsToAbort = [select id,Name from CronJobDetail where Name like 'AutoTestRunner%' and JobType = '7'];
List<CronTrigger> jobsToAbort = [select Id from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%TestRunner%'];
if(jobsToAbort.size()>0){
for (CronTrigger job : jobsToAbort) {
System.abortJob(job.Id);
}
}
PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;
}
public PageReference AbortTestJobs() {
Test_Runner_Job__c RunningJobnm =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
ApexTestQueueItem[] items = [SELECT Id FROM ApexTestQueueItem WHERE Status IN ('Holding','Queued','Preparing','Processing') and ParentJobId=:RunningJobnm.Name];
if(items.size()>0){
for(ApexTestQueueItem item: items) {
item.Status = 'Aborted';
}
update items;
}
PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;
}
public void deleteCompletedJobs(){
List<CronTrigger> jobsToAbort = [select Id,State from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%TestRunner%' and State='DELETED'];
for (CronTrigger job : jobsToAbort) {
System.abortJob(job.Id);
}
}
/*
public void run() {
AutoTestRunner.enqueueTests();
isRunning = true;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm, 'Tests queued'));
}
*/
public void email() {
//TestRunnerResults.emailUnprocessedJobStatus();
emailUnprocessedJobStatus();
isEmailing = true;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm, 'Results processed and emailed'));
}
public static list<Messaging.SingleEmailMessage> emailUnprocessedJobStatus() {
list<Test_Runner_Job__c> jobs = getUnprocessedJobs();
//list<Messaging.SingleEmailMessage> messages = AutoTestRunner.emailMethodStatus(jobs);
list<Messaging.SingleEmailMessage> messages =emailMethodStatus(jobs);
for (Test_Runner_Job__c job : jobs) {
job.Processed__c = true;
}
update jobs;
return messages;
}
public static list<Test_Runner_Job__c> getUnprocessedJobs() {
return [Select t.Name,
t.Automated_Test_Run__r.Emails__c,
t.Automated_Test_Run__r.Email_on_Pass__c,
t.Automated_Test_Run__r.Name,
t.Automated_Test_Run__c
From Test_Runner_Job__c t where Processed__c = false];
}
//Statistics part
public Void Calculatepercentage() {
Test_Runner_Job__c RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
if(RunningJob!=null){
integer TotalJobsis = [select count() FROM ApexTestQueueItem where ParentJobId=:RunningJob.Name];
integer CompltedJobsis = [select count() FROM ApexTestQueueItem where Status IN ('Completed','Aborted') and ParentJobId=:RunningJob.Name];
//if((TotalJobsis!=null && TotalJobsis!='')&& (CompltedJobsis!=null&& CompltedJobsis!='')){
if((TotalJobsis>0)&& (CompltedJobsis>0)){
Percentage=(CompltedJobsis*100)/TotalJobsis;
//RunningJob.Percentage_of_Completion__c=Percentage;
System.debug('Total Jobs is'+TotalJobsis+ 'CompltedJobs' +CompltedJobsis+ 'Percentage is'+Percentage);
//update RunningJob;
}
}
}
public List<PieWedgeData> getPieData() {
//Select id,Status from ApexTestQueueItem where ParentJobId='7070K00008HsU7EQAV'
//Test_Runner_Job__c RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c where Processed__c = false order by CreatedDate desc limit 1];
//SELECT AsyncApexJobId, Outcome, ApexClass.Name, MethodName, Message, StackTrace FROM ApexTestResult WHERE AsyncApexJobId='7074D00000OEnAAQA1'
Test_Runner_Job__c RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
//integer Cmpltd = [select count() FROM ApexTestResult WHERE Outcome = 'Pass' and AsyncApexJobId=:RunningJob.Name];
integer CmpltdPass = [select count() FROM ApexTestResult WHERE Outcome = 'Pass' and AsyncApexJobId=:RunningJob.Name];
integer Failed = [select count() FROM ApexTestResult WHERE Outcome = 'Fail' and AsyncApexJobId=:RunningJob.Name];
integer Queuedjobs = [select count() FROM ApexTestQueueItem where Status='Queued' and ParentJobId=:RunningJob.Name];
integer TotalJobs = [select count() FROM ApexTestQueueItem where ParentJobId=:RunningJob.Name];
//integer CompltedJobs = [select count() FROM ApexTestQueueItem where Status='Completed' and ParentJobId=:RunningJob.Name];
//Staticstics='Total Testclasses '+TotalJobs+' '+'Pending Testclasses '+Queuedjobs;
//Staticstics= 'Total Testclasses '+TotalJobs+'\n';
// Staticstics+= '\n'+'Pending Testclasses '+Queuedjobs+'\n';
// Staticstics+= '\n'+'Test Execution Started on '+RunningJob.CreatedDate;
//Percentage=CompltedJobs/TotalJobs*100;
List<PieWedgeData> data = new List<PieWedgeData>();
if(Queuedjobs>0){
data.add(new PieWedgeData('In Progress'+' '+Queuedjobs, +Queuedjobs));
}if(CmpltdPass>0){
data.add(new PieWedgeData('Passed'+' '+CmpltdPass, +CmpltdPass));
}if(Failed>0){
data.add(new PieWedgeData('Fail'+' '+Failed, +Failed));
}
return data;
}
// Wrapper class
public class PieWedgeData {
public String name { get; set; }
public Integer data { get; set; }
public Integer CmpltdPass{ get; set; }
public Integer Failed{ get; set; }
public Integer Queuedjobs{ get; set; }
public PieWedgeData(String name, Integer data) {
this.name = name;
this.data = data;
}
}
public PageReference Refresh(){
deleteCompletedJobs();
Calculatepercentage();
refreshHasScheduledJobs();
if(Percentage==100){
email();
}else{
hasScheduledJobs = true;
}
PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;
}
//Scheduling Job run & Email Sending from Auotestrunner class
// Enqueue all unit test classes as spec'd by Automated_Test_Run__c record(s)
public static list<ID> enqueueTests() {
list<Id> jobIds = new list<Id>();
Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
Automated_Test_Run__c EmailRecord=[select Emails__c from Automated_Test_Run__c where RecordTypeId=:ATEmilRecordTypeId order by createdDate DESC limit 1];
string whereExcluded = '';
string Keywordis = '';
string ATRIDis = '';
for (Automated_Test_Run__c run : [select Query__c, Excluded_Classes__c,
Email_on_Pass__c, Exclude_Managed_Packages__c
from Automated_Test_Run__c where Active__c = true and RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]) {
ATRIDis=run.id;
if (run.Excluded_Classes__c != null) {
for (string c : run.Excluded_Classes__c.split('[,\\s]+')) {
whereExcluded += 'and Name != \'' + c + '\'';
}
}
if (run.Exclude_Managed_Packages__c == True) {
whereExcluded += ' AND NameSpacePrefix = null';
}
if (run.Query__c != null && run.Query__c != ' ' ) {
Keywordis +=run.Query__c;
}
}
string query = 'SELECT Id FROM ApexClass WHERE Name LIKE \'' + Keywordis+ '\' ' + whereExcluded;
ApexClass[] testClasses = Database.query(query);
if (testClasses.size() > 0) {
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (ApexClass cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
}
if (!Test.isRunningTest()) {
//insert queueItems;
DataBase.insert(queueItems,false);
// Get the job ID of the first queue item returned.
ApexTestQueueItem item =
[SELECT ParentJobId FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
insert new Test_Runner_Job__c(Name = item.parentjobid, Automated_Test_Run__c = EmailRecord.Id);
jobIds.add(item.parentjobid);
if(ATRIDis!='' && ATRIDis!=null){
Automated_Test_Run__c runATRrecd =[select id,Active__c from Automated_Test_Run__c where Id=:ATRIDis limit 1];
runATRrecd.Active__c = false;
update runATRrecd;
}
}
}
return jobIds;
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs) {
set<string> jobNames = new set<string>();
for (Test_Runner_Job__c job : jobs) {
jobNames.add(job.Name);
}
ApexTestResult[] results =
[SELECT AsyncApexJobId, Outcome, ApexClass.Name, MethodName, Message, StackTrace
FROM ApexTestResult
WHERE AsyncApexJobId in :jobNames];
return emailMethodStatus(jobs, results);
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs, ApexTestResult[] results) {
list<Messaging.SingleEmailMessage> messages = new list<Messaging.SingleEmailMessage>();
for (Test_Runner_Job__c job : jobs) {
system.debug('Test Runner Job: Id ' + job.Id + ' Name ' + job.Name);
integer passed = 0;
integer total = 0;
string failTable = '<table border="1" cellpadding="5px">';
string className = '';
for (ApexTestResult atr : results) {
system.debug('Apex Test Result: Id ' + atr.AsyncApexJobId);
if ((string)atr.AsyncApexJobId == job.Name || (Test.isRunningTest() && jobs.size() == 1)) {
if (atr.Outcome == 'Pass') {
passed++;
} else {
if (atr.ApexClass.Name != className) {
className = atr.ApexClass.Name;
failTable += '<tr style="background: #ddd; font-weight: bold;"><td colspan="2">' + className + '</td></tr>\n';
}
failTable += '<tr><td>' + atr.MethodName + '</td><td> ' + atr.message + '</td></tr>\n';
}
total++;
}
}
failTable += '</table>';
string body = '<p>' + passed + '/' + total + ' tests passed</p>\n';
boolean allPassed = passed == total;
if (!allPassed) {
body += '<p>Test Failures:</p>\n' + failTable;
}
if ((allPassed && job.Automated_Test_Run__r.Email_on_Pass__c) || !allPassed) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(job.Automated_Test_Run__r.Emails__c.split('[,\\s]+'));
mail.setSubject(job.Automated_Test_Run__r.Name + ' Automated Test Results: ' + (passed < total ? 'Fail' : 'Pass'));
mail.setHtmlBody(body);
System.debug(mail);
messages.add(mail);
}
}
if (!Test.isRunningTest()) {
Messaging.sendEmail(messages);
}
return messages;
}
}
********************
global class AutoTestRunner implements Schedulable {
// derived from http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_unit_tests_running.htm#APISectionTitle
public static void setup(String strSchedule) {
try {
String cronexpression=strSchedule;
system.schedule('AutoTestRunner',cronexpression, new AutoTestRunner());
} catch (Asyncexception ex) {
system.debug('Job Not scheduled');
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Future Date Time only');
ApexPages.addMessage(myMsg);
}
}
global void execute(SchedulableContext SC) {
AutomatedTestSetup_Controller.enqueueTests();
//enqueueTests();
}
//Scheduling Job run & Email Sending from Auotestrunner class
// Enqueue all unit test classes as spec'd by Automated_Test_Run__c record(s)
/*
public static list<ID> enqueueTests() {
list<Id> jobIds = new list<Id>();
Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
Automated_Test_Run__c EmailRecord=[select Emails__c from Automated_Test_Run__c where RecordTypeId=:ATEmilRecordTypeId order by createdDate DESC limit 1];
string whereExcluded = '';
string Keywordis = '';
string ATRIDis = '';
for (Automated_Test_Run__c run : [select Query__c, Excluded_Classes__c,
Email_on_Pass__c, Exclude_Managed_Packages__c
from Automated_Test_Run__c where Active__c = true and RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]) {
ATRIDis=run.id;
if (run.Excluded_Classes__c != null) {
for (string c : run.Excluded_Classes__c.split('[,\\s]+')) {
whereExcluded += 'and Name != \'' + c + '\'';
}
}
if (run.Exclude_Managed_Packages__c == True) {
whereExcluded += ' AND NameSpacePrefix = null';
}
if (run.Query__c != null && run.Query__c != ' ' ) {
Keywordis +=run.Query__c;
}
}
string query = 'SELECT Id FROM ApexClass WHERE Name LIKE \'' + Keywordis+ '\' ' + whereExcluded;
ApexClass[] testClasses = Database.query(query);
if (testClasses.size() > 0) {
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (ApexClass cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
}
if (!Test.isRunningTest()) {
//insert queueItems;
DataBase.insert(queueItems,false);
// Get the job ID of the first queue item returned.
ApexTestQueueItem item =
[SELECT ParentJobId FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
insert new Test_Runner_Job__c(Name = item.parentjobid, Automated_Test_Run__c = EmailRecord.Id);
jobIds.add(item.parentjobid);
if(ATRIDis!='' && ATRIDis!=null){
Automated_Test_Run__c runATRrecd =[select id,Active__c from Automated_Test_Run__c where Id=:ATRIDis limit 1];
runATRrecd.Active__c = false;
update runATRrecd;
}
}
}
return jobIds;
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs) {
set<string> jobNames = new set<string>();
for (Test_Runner_Job__c job : jobs) {
jobNames.add(job.Name);
}
ApexTestResult[] results =
[SELECT AsyncApexJobId, Outcome, ApexClass.Name, MethodName, Message, StackTrace
FROM ApexTestResult
WHERE AsyncApexJobId in :jobNames];
return emailMethodStatus(jobs, results);
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs, ApexTestResult[] results) {
list<Messaging.SingleEmailMessage> messages = new list<Messaging.SingleEmailMessage>();
for (Test_Runner_Job__c job : jobs) {
system.debug('Test Runner Job: Id ' + job.Id + ' Name ' + job.Name);
integer passed = 0;
integer total = 0;
string failTable = '<table border="1" cellpadding="5px">';
string className = '';
for (ApexTestResult atr : results) {
system.debug('Apex Test Result: Id ' + atr.AsyncApexJobId);
if ((string)atr.AsyncApexJobId == job.Name || (Test.isRunningTest() && jobs.size() == 1)) {
if (atr.Outcome == 'Pass') {
passed++;
} else {
if (atr.ApexClass.Name != className) {
className = atr.ApexClass.Name;
failTable += '<tr style="background: #ddd; font-weight: bold;"><td colspan="2">' + className + '</td></tr>\n';
}
failTable += '<tr><td>' + atr.MethodName + '</td><td> ' + atr.message + '</td></tr>\n';
}
total++;
}
}
failTable += '</table>';
string body = '<p>' + passed + '/' + total + ' tests passed</p>\n';
boolean allPassed = passed == total;
if (!allPassed) {
body += '<p>Test Failures:</p>\n' + failTable;
}
if ((allPassed && job.Automated_Test_Run__r.Email_on_Pass__c) || !allPassed) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(job.Automated_Test_Run__r.Emails__c.split('[,\\s]+'));
mail.setSubject(job.Automated_Test_Run__r.Name + ' Automated Test Results: ' + (passed < total ? 'Fail' : 'Pass'));
mail.setHtmlBody(body);
System.debug(mail);
messages.add(mail);
}
}
if (!Test.isRunningTest()) {
Messaging.sendEmail(messages);
}
return messages;
}
*/
}
***************************************
This not required:
global class TestRunnerResults implements Schedulable {
global void execute(SchedulableContext SC) {
//emailUnprocessedJobStatus();
}
/*
public static list<Messaging.SingleEmailMessage> emailUnprocessedJobStatus() {
list<Test_Runner_Job__c> jobs = getUnprocessedJobs();
list<Messaging.SingleEmailMessage> messages = AutoTestRunner.emailMethodStatus(jobs);
for (Test_Runner_Job__c job : jobs) {
job.Processed__c = true;
}
update jobs;
return messages;
}
public static list<Test_Runner_Job__c> getUnprocessedJobs() {
return [Select t.Name,
t.Automated_Test_Run__r.Emails__c,
t.Automated_Test_Run__r.Email_on_Pass__c,
t.Automated_Test_Run__r.Name,
t.Automated_Test_Run__c
From Test_Runner_Job__c t where Processed__c = false];
}
*/
}
*************
Vf page:
Abort functionality
In progress statuses:
*********
public with sharing class AutomatedTestSetup_Controller {
public boolean hasScheduledJobs { get; set; }
public boolean hasTestRun { get; set; }
public boolean hasAbort { get; set; }
public boolean hasemailpending { get; set; }
public boolean isRunning { get; set; }
public boolean isEmailing { get; set; }
public AutomatedTestSetup_Controller ATS { get; set; }
public String DtValue {get; set; }
public boolean showMessage {get;set;}
public String showdatetime{get;set;}
public String Staticstics{get;set;}
public Decimal Percentage{get;set;}
public String shddatetime {get;set;}
public String ATRdetails {get;set;}
public List<CronTrigger> Schdjobs{get;set;}
public String Jobstatus {get;set;}
public Automated_Test_Run__c AtrRecord {get; set;}
//public List<Shdwrapper> cronjbs=New List<Shdwrapper>(){get;set;}
id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
id ATEmailRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
public PageReference doInsert() {
// Automated_Test_Run__c objdlt = new Automated_Test_Run__c();
AtrRecord.Query__c=AtrRecord.Query__c;
AtrRecord.Excluded_Classes__c=AtrRecord.Excluded_Classes__c;
AtrRecord.Exclude_Managed_Packages__c=AtrRecord.Exclude_Managed_Packages__c;
AtrRecord.Schedule__c=AtrRecord.Schedule__c;
AtrRecord.RecordTypeId=ATERecordTypeId;
//insert AtrRecord;
Automated_Test_Run__c ATEemail = new Automated_Test_Run__c();
ATEemail.Emails__c=AtrRecord.Emails__c;
ATEemail.Email_on_Pass__c=AtrRecord.Email_on_Pass__c;
ATEemail.RecordTypeId=ATEmailRecordTypeId;
//insert ATEemail;
Savepoint sp = Database.setSavepoint();
try{
scheduleJobs(AtrRecord.Schedule__c);
if(showMessage==false){
upsert AtrRecord;
upsert ATEemail;
}
}
catch(exception ex){
Database.rollback(sp);
}
/*PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;*/
return null;
}
public Automated_Test_Run__c getAtrRecord()
{
return AtrRecord;
}
public AutomatedTestSetup_Controller(ApexPages.StandardController controller) {
//Automated_Test_Run__c AtrRecord = new Automated_Test_Run__c();//from
AtrRecord = (Automated_Test_Run__c)Controller.getRecord();
this.ATS=ATS;
showMessage=false;
refreshHasScheduledJobs();
refreshHasTestRun();
ShowAbortbutton();
getPieData();
Calculatepercentage();
GetATSRunDeatils();
EmailSendPending();
}
public void refreshHasScheduledJobs() {
//integer jobCount = [select count() from CronJobDetail where Name like '%TestRunner%' and JobType = '7'];
//integer jobCount = [SELECT count() FROM CronTrigger where CronJobDetail.Name like '%TestRunner%' and State in('WAITING','ACQUIRED','EXECUTING')];
integer jobCount = [SELECT count() FROM CronTrigger where CronJobDetail.Name like '%TestRunner%'];
//integer jobCount = [SELECT count() FROM CronTrigger where CronJobDetail.Name like '%TestRunner%' and State in('WAITING','ACQUIRED','EXECUTING')];
Schdjobs=[SELECT CronJobDetail.Name,CreatedDate,NextFireTime,State FROM CronTrigger where CronJobDetail.Name like '%TestRunner%' and State in('WAITING','ACQUIRED','EXECUTING')];
if(Schdjobs.size()>0){
Jobstatus=Schdjobs[0].State;
if(Schdjobs[0].NextFireTime!=null ){
Datetime shddatetimeGSt=Schdjobs[0].NextFireTime;
Datetime gmt = shddatetimeGSt;
String timeZone = UserInfo.getTimeZone().getID();
Datetime GivenDateTime=shddatetimeGSt;// here you can user your dates e.g. createddate
Datetime localdt=Datetime.valueOf(GivenDateTime);
//showdatetime = string.valueOfGmt(local);
shddatetime=localdt.format();
}
else if(Jobstatus!=null && Jobstatus!='') {
shddatetime='Test Scheduled Job Current State is '+Jobstatus;
}
}
hasScheduledJobs = jobCount !=0;
//hasScheduledJobs = (jobCount !=0 && Schdjobs.size()>0);
/*if(jobCount !=0){
hasScheduledJobs = jobCount !=0;
}else if(Schdjobs.size()>0){
hasScheduledJobs =true;
} */
}
public void GetATSRunDeatils() {
List<String> Keywords=New List<String>();
Keywords.clear();
ATRdetails='';
//id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
for(Automated_Test_Run__c atr: [select Query__c, Excluded_Classes__c,
Email_on_Pass__c, Exclude_Managed_Packages__c
from Automated_Test_Run__c
where Active__c = true and RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]){
Keywords.add(atr.Query__c);
}
if(Keywords.size()>0){
for(String kw:Keywords){
ATRdetails+=kw;
}
}
}
public void refreshHasTestRun() {
integer runCount = [select count() from Automated_Test_Run__c limit 1];
hasTestRun = runCount > 0;
}
public void ShowAbortbutton(){
integer runCount = [select count() from Automated_Test_Run__c limit 1];
Test_Runner_Job__c RunningJobnm =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
integer TestexecrunCount = [select count() from ApexTestQueueItem WHERE Status IN ('Holding','Queued','Preparing','Processing') and ParentJobId=:RunningJobnm.Name];
hasAbort = TestexecrunCount > 0;
//hasScheduledJobs = TestexecrunCount > 0;
}
public void EmailSendPending(){
List<Test_Runner_Job__c> runCountJob = [select id from Test_Runner_Job__c where Processed__c=false order by CreatedDate desc limit 1];
hasemailpending = runCountJob.size()> 0;
//hasScheduledJobs = TestexecrunCount > 0;
}
public string getTestRunLink() {
return '/' + Automated_Test_Run__c.SObjectType.getDescribe().getKeyPrefix();
}
public AutomatedTestSetup_Controller() {
Automated_Test_Run__c AtrRecord = new Automated_Test_Run__c();
refreshHasScheduledJobs();
refreshHasTestRun();
//getPieData();
Calculatepercentage();
ShowAbortbutton();
EmailSendPending();
}
public PageReference scheduleJobs(Datetime DtValue) {
System.debug('Date & Time is given***1'+DtValue);
deleteCompletedJobs();
Datetime gmt = DtValue;
String timeZone = UserInfo.getTimeZone().getID();
Datetime GivenDateTime=DtValue;// here you can user your dates e.g. createddate
System.debug('GivenDateTime is***'+GivenDateTime);
Datetime local=Datetime.valueOf(GivenDateTime);
System.debug('local is***'+local);
Map <Integer,String> monthNumbers = new Map <Integer,String> {1=>'Jan', 2=>'Feb',3=>'Mar',4=>'Apr', 5=>'May', 6=>'Jun',7=>'Jul',8=>'Aug', 9=>'Sep', 10=>'Oct', 11=>'Nov', 12=>'Dec'};
String TestShdmonth=monthNumbers.get(local.month());
String strSchedule = '0 ' + local.minute() + ' ' +local.hour()+ ' ' + local.day()+ ' ' + TestShdmonth+ ' ? ' + ' ' + local.year();
System.debug('***strSchedule***'+strSchedule);
AutoTestRunner.setup(strSchedule);
refreshHasScheduledJobs();
return null;
}
public PageReference CancelJobs() {
//List<CronTrigger> jobsToAbort = [select id,Name from CronJobDetail where Name like 'AutoTestRunner%' and JobType = '7'];
List<CronTrigger> jobsToAbort = [select Id from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%TestRunner%'];
if(jobsToAbort.size()>0){
for (CronTrigger job : jobsToAbort) {
System.abortJob(job.Id);
}
}
PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;
}
public PageReference AbortTestJobs() {
Test_Runner_Job__c RunningJobnm =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
ApexTestQueueItem[] items = [SELECT Id FROM ApexTestQueueItem WHERE Status IN ('Holding','Queued','Preparing','Processing') and ParentJobId=:RunningJobnm.Name];
if(items.size()>0){
for(ApexTestQueueItem item: items) {
item.Status = 'Aborted';
}
update items;
}
PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;
}
public void deleteCompletedJobs(){
List<CronTrigger> jobsToAbort = [select Id,State from CronTrigger where CronJobDetail.JobType = '7' and CronJobDetail.Name like '%TestRunner%' and State='DELETED'];
for (CronTrigger job : jobsToAbort) {
System.abortJob(job.Id);
}
}
/*
public void run() {
AutoTestRunner.enqueueTests();
isRunning = true;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm, 'Tests queued'));
}
*/
public void email() {
//TestRunnerResults.emailUnprocessedJobStatus();
emailUnprocessedJobStatus();
isEmailing = true;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm, 'Results processed and emailed'));
}
public static list<Messaging.SingleEmailMessage> emailUnprocessedJobStatus() {
list<Test_Runner_Job__c> jobs = getUnprocessedJobs();
//list<Messaging.SingleEmailMessage> messages = AutoTestRunner.emailMethodStatus(jobs);
list<Messaging.SingleEmailMessage> messages =emailMethodStatus(jobs);
for (Test_Runner_Job__c job : jobs) {
job.Processed__c = true;
}
update jobs;
return messages;
}
public static list<Test_Runner_Job__c> getUnprocessedJobs() {
return [Select t.Name,
t.Automated_Test_Run__r.Emails__c,
t.Automated_Test_Run__r.Email_on_Pass__c,
t.Automated_Test_Run__r.Name,
t.Automated_Test_Run__c
From Test_Runner_Job__c t where Processed__c = false];
}
//Statistics part
public Void Calculatepercentage() {
Test_Runner_Job__c RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
if(RunningJob!=null){
integer TotalJobsis = [select count() FROM ApexTestQueueItem where ParentJobId=:RunningJob.Name];
integer CompltedJobsis = [select count() FROM ApexTestQueueItem where Status IN ('Completed','Aborted') and ParentJobId=:RunningJob.Name];
//if((TotalJobsis!=null && TotalJobsis!='')&& (CompltedJobsis!=null&& CompltedJobsis!='')){
if((TotalJobsis>0)&& (CompltedJobsis>0)){
Percentage=(CompltedJobsis*100)/TotalJobsis;
//RunningJob.Percentage_of_Completion__c=Percentage;
System.debug('Total Jobs is'+TotalJobsis+ 'CompltedJobs' +CompltedJobsis+ 'Percentage is'+Percentage);
//update RunningJob;
}
}
}
public List<PieWedgeData> getPieData() {
//Select id,Status from ApexTestQueueItem where ParentJobId='7070K00008HsU7EQAV'
//Test_Runner_Job__c RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c where Processed__c = false order by CreatedDate desc limit 1];
//SELECT AsyncApexJobId, Outcome, ApexClass.Name, MethodName, Message, StackTrace FROM ApexTestResult WHERE AsyncApexJobId='7074D00000OEnAAQA1'
Test_Runner_Job__c RunningJob =[Select Name,Automated_Test_Run__c,CreatedDate From Test_Runner_Job__c order by CreatedDate desc limit 1];
//integer Cmpltd = [select count() FROM ApexTestResult WHERE Outcome = 'Pass' and AsyncApexJobId=:RunningJob.Name];
integer CmpltdPass = [select count() FROM ApexTestResult WHERE Outcome = 'Pass' and AsyncApexJobId=:RunningJob.Name];
integer Failed = [select count() FROM ApexTestResult WHERE Outcome = 'Fail' and AsyncApexJobId=:RunningJob.Name];
integer Queuedjobs = [select count() FROM ApexTestQueueItem where Status='Queued' and ParentJobId=:RunningJob.Name];
integer TotalJobs = [select count() FROM ApexTestQueueItem where ParentJobId=:RunningJob.Name];
//integer CompltedJobs = [select count() FROM ApexTestQueueItem where Status='Completed' and ParentJobId=:RunningJob.Name];
//Staticstics='Total Testclasses '+TotalJobs+' '+'Pending Testclasses '+Queuedjobs;
//Staticstics= 'Total Testclasses '+TotalJobs+'\n';
// Staticstics+= '\n'+'Pending Testclasses '+Queuedjobs+'\n';
// Staticstics+= '\n'+'Test Execution Started on '+RunningJob.CreatedDate;
//Percentage=CompltedJobs/TotalJobs*100;
List<PieWedgeData> data = new List<PieWedgeData>();
if(Queuedjobs>0){
data.add(new PieWedgeData('In Progress'+' '+Queuedjobs, +Queuedjobs));
}if(CmpltdPass>0){
data.add(new PieWedgeData('Passed'+' '+CmpltdPass, +CmpltdPass));
}if(Failed>0){
data.add(new PieWedgeData('Fail'+' '+Failed, +Failed));
}
return data;
}
// Wrapper class
public class PieWedgeData {
public String name { get; set; }
public Integer data { get; set; }
public Integer CmpltdPass{ get; set; }
public Integer Failed{ get; set; }
public Integer Queuedjobs{ get; set; }
public PieWedgeData(String name, Integer data) {
this.name = name;
this.data = data;
}
}
public PageReference Refresh(){
deleteCompletedJobs();
Calculatepercentage();
refreshHasScheduledJobs();
if(Percentage==100){
email();
}else{
hasScheduledJobs = true;
}
PageReference pageRef = new PageReference('/apex/AutomatedTestSetupVFP');
pageRef.setRedirect(true);
return pageRef;
}
//Scheduling Job run & Email Sending from Auotestrunner class
// Enqueue all unit test classes as spec'd by Automated_Test_Run__c record(s)
public static list<ID> enqueueTests() {
list<Id> jobIds = new list<Id>();
Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
Automated_Test_Run__c EmailRecord=[select Emails__c from Automated_Test_Run__c where RecordTypeId=:ATEmilRecordTypeId order by createdDate DESC limit 1];
string whereExcluded = '';
string Keywordis = '';
string ATRIDis = '';
for (Automated_Test_Run__c run : [select Query__c, Excluded_Classes__c,
Email_on_Pass__c, Exclude_Managed_Packages__c
from Automated_Test_Run__c where Active__c = true and RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]) {
ATRIDis=run.id;
if (run.Excluded_Classes__c != null) {
for (string c : run.Excluded_Classes__c.split('[,\\s]+')) {
whereExcluded += 'and Name != \'' + c + '\'';
}
}
if (run.Exclude_Managed_Packages__c == True) {
whereExcluded += ' AND NameSpacePrefix = null';
}
if (run.Query__c != null && run.Query__c != ' ' ) {
Keywordis +=run.Query__c;
}
}
string query = 'SELECT Id FROM ApexClass WHERE Name LIKE \'' + Keywordis+ '\' ' + whereExcluded;
ApexClass[] testClasses = Database.query(query);
if (testClasses.size() > 0) {
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (ApexClass cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
}
if (!Test.isRunningTest()) {
//insert queueItems;
DataBase.insert(queueItems,false);
// Get the job ID of the first queue item returned.
ApexTestQueueItem item =
[SELECT ParentJobId FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
insert new Test_Runner_Job__c(Name = item.parentjobid, Automated_Test_Run__c = EmailRecord.Id);
jobIds.add(item.parentjobid);
if(ATRIDis!='' && ATRIDis!=null){
Automated_Test_Run__c runATRrecd =[select id,Active__c from Automated_Test_Run__c where Id=:ATRIDis limit 1];
runATRrecd.Active__c = false;
update runATRrecd;
}
}
}
return jobIds;
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs) {
set<string> jobNames = new set<string>();
for (Test_Runner_Job__c job : jobs) {
jobNames.add(job.Name);
}
ApexTestResult[] results =
[SELECT AsyncApexJobId, Outcome, ApexClass.Name, MethodName, Message, StackTrace
FROM ApexTestResult
WHERE AsyncApexJobId in :jobNames];
return emailMethodStatus(jobs, results);
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs, ApexTestResult[] results) {
list<Messaging.SingleEmailMessage> messages = new list<Messaging.SingleEmailMessage>();
for (Test_Runner_Job__c job : jobs) {
system.debug('Test Runner Job: Id ' + job.Id + ' Name ' + job.Name);
integer passed = 0;
integer total = 0;
string failTable = '<table border="1" cellpadding="5px">';
string className = '';
for (ApexTestResult atr : results) {
system.debug('Apex Test Result: Id ' + atr.AsyncApexJobId);
if ((string)atr.AsyncApexJobId == job.Name || (Test.isRunningTest() && jobs.size() == 1)) {
if (atr.Outcome == 'Pass') {
passed++;
} else {
if (atr.ApexClass.Name != className) {
className = atr.ApexClass.Name;
failTable += '<tr style="background: #ddd; font-weight: bold;"><td colspan="2">' + className + '</td></tr>\n';
}
failTable += '<tr><td>' + atr.MethodName + '</td><td> ' + atr.message + '</td></tr>\n';
}
total++;
}
}
failTable += '</table>';
string body = '<p>' + passed + '/' + total + ' tests passed</p>\n';
boolean allPassed = passed == total;
if (!allPassed) {
body += '<p>Test Failures:</p>\n' + failTable;
}
if ((allPassed && job.Automated_Test_Run__r.Email_on_Pass__c) || !allPassed) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(job.Automated_Test_Run__r.Emails__c.split('[,\\s]+'));
mail.setSubject(job.Automated_Test_Run__r.Name + ' Automated Test Results: ' + (passed < total ? 'Fail' : 'Pass'));
mail.setHtmlBody(body);
System.debug(mail);
messages.add(mail);
}
}
if (!Test.isRunningTest()) {
Messaging.sendEmail(messages);
}
return messages;
}
}
********************
global class AutoTestRunner implements Schedulable {
// derived from http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_testing_unit_tests_running.htm#APISectionTitle
public static void setup(String strSchedule) {
try {
String cronexpression=strSchedule;
system.schedule('AutoTestRunner',cronexpression, new AutoTestRunner());
} catch (Asyncexception ex) {
system.debug('Job Not scheduled');
ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.INFO,'Future Date Time only');
ApexPages.addMessage(myMsg);
}
}
global void execute(SchedulableContext SC) {
AutomatedTestSetup_Controller.enqueueTests();
//enqueueTests();
}
//Scheduling Job run & Email Sending from Auotestrunner class
// Enqueue all unit test classes as spec'd by Automated_Test_Run__c record(s)
/*
public static list<ID> enqueueTests() {
list<Id> jobIds = new list<Id>();
Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId();
Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId();
Automated_Test_Run__c EmailRecord=[select Emails__c from Automated_Test_Run__c where RecordTypeId=:ATEmilRecordTypeId order by createdDate DESC limit 1];
string whereExcluded = '';
string Keywordis = '';
string ATRIDis = '';
for (Automated_Test_Run__c run : [select Query__c, Excluded_Classes__c,
Email_on_Pass__c, Exclude_Managed_Packages__c
from Automated_Test_Run__c where Active__c = true and RecordTypeId=:ATERecordTypeId order by createdDate DESC limit 1]) {
ATRIDis=run.id;
if (run.Excluded_Classes__c != null) {
for (string c : run.Excluded_Classes__c.split('[,\\s]+')) {
whereExcluded += 'and Name != \'' + c + '\'';
}
}
if (run.Exclude_Managed_Packages__c == True) {
whereExcluded += ' AND NameSpacePrefix = null';
}
if (run.Query__c != null && run.Query__c != ' ' ) {
Keywordis +=run.Query__c;
}
}
string query = 'SELECT Id FROM ApexClass WHERE Name LIKE \'' + Keywordis+ '\' ' + whereExcluded;
ApexClass[] testClasses = Database.query(query);
if (testClasses.size() > 0) {
ApexTestQueueItem[] queueItems = new List<ApexTestQueueItem>();
for (ApexClass cls : testClasses) {
queueItems.add(new ApexTestQueueItem(ApexClassId=cls.Id));
}
if (!Test.isRunningTest()) {
//insert queueItems;
DataBase.insert(queueItems,false);
// Get the job ID of the first queue item returned.
ApexTestQueueItem item =
[SELECT ParentJobId FROM ApexTestQueueItem
WHERE Id=:queueItems[0].Id LIMIT 1];
insert new Test_Runner_Job__c(Name = item.parentjobid, Automated_Test_Run__c = EmailRecord.Id);
jobIds.add(item.parentjobid);
if(ATRIDis!='' && ATRIDis!=null){
Automated_Test_Run__c runATRrecd =[select id,Active__c from Automated_Test_Run__c where Id=:ATRIDis limit 1];
runATRrecd.Active__c = false;
update runATRrecd;
}
}
}
return jobIds;
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs) {
set<string> jobNames = new set<string>();
for (Test_Runner_Job__c job : jobs) {
jobNames.add(job.Name);
}
ApexTestResult[] results =
[SELECT AsyncApexJobId, Outcome, ApexClass.Name, MethodName, Message, StackTrace
FROM ApexTestResult
WHERE AsyncApexJobId in :jobNames];
return emailMethodStatus(jobs, results);
}
public static list<Messaging.SingleEmailMessage> emailMethodStatus(list<Test_Runner_Job__c> jobs, ApexTestResult[] results) {
list<Messaging.SingleEmailMessage> messages = new list<Messaging.SingleEmailMessage>();
for (Test_Runner_Job__c job : jobs) {
system.debug('Test Runner Job: Id ' + job.Id + ' Name ' + job.Name);
integer passed = 0;
integer total = 0;
string failTable = '<table border="1" cellpadding="5px">';
string className = '';
for (ApexTestResult atr : results) {
system.debug('Apex Test Result: Id ' + atr.AsyncApexJobId);
if ((string)atr.AsyncApexJobId == job.Name || (Test.isRunningTest() && jobs.size() == 1)) {
if (atr.Outcome == 'Pass') {
passed++;
} else {
if (atr.ApexClass.Name != className) {
className = atr.ApexClass.Name;
failTable += '<tr style="background: #ddd; font-weight: bold;"><td colspan="2">' + className + '</td></tr>\n';
}
failTable += '<tr><td>' + atr.MethodName + '</td><td> ' + atr.message + '</td></tr>\n';
}
total++;
}
}
failTable += '</table>';
string body = '<p>' + passed + '/' + total + ' tests passed</p>\n';
boolean allPassed = passed == total;
if (!allPassed) {
body += '<p>Test Failures:</p>\n' + failTable;
}
if ((allPassed && job.Automated_Test_Run__r.Email_on_Pass__c) || !allPassed) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(job.Automated_Test_Run__r.Emails__c.split('[,\\s]+'));
mail.setSubject(job.Automated_Test_Run__r.Name + ' Automated Test Results: ' + (passed < total ? 'Fail' : 'Pass'));
mail.setHtmlBody(body);
System.debug(mail);
messages.add(mail);
}
}
if (!Test.isRunningTest()) {
Messaging.sendEmail(messages);
}
return messages;
}
*/
}
***************************************
This not required:
global class TestRunnerResults implements Schedulable {
global void execute(SchedulableContext SC) {
//emailUnprocessedJobStatus();
}
/*
public static list<Messaging.SingleEmailMessage> emailUnprocessedJobStatus() {
list<Test_Runner_Job__c> jobs = getUnprocessedJobs();
list<Messaging.SingleEmailMessage> messages = AutoTestRunner.emailMethodStatus(jobs);
for (Test_Runner_Job__c job : jobs) {
job.Processed__c = true;
}
update jobs;
return messages;
}
public static list<Test_Runner_Job__c> getUnprocessedJobs() {
return [Select t.Name,
t.Automated_Test_Run__r.Emails__c,
t.Automated_Test_Run__r.Email_on_Pass__c,
t.Automated_Test_Run__r.Name,
t.Automated_Test_Run__c
From Test_Runner_Job__c t where Processed__c = false];
}
*/
}
*************
Vf page:
<apex:page standardController="Automated_Test_Run__c" extensions="AutomatedTestSetup_Controller" Sidebar="False" id="pg" docType="html-5.0"> <script> function fnChange(DT) { // first make sure 'DT ' is not null here alert('Hello datetime'+DT); DTPass(DT); //alert(DT); } </script> <apex:form id="frm"> <apex:pageBlock title="Job Schedule - Test Execution"> <apex:pageMessages /> <div align="right" draggable="false" > <apex:outputLink value="{!testRunLink}">Scheduled Jobs History</apex:outputLink> </div> <!--Automated Test Record--> <apex:outputPanel rendered="{!if(NOT(hasScheduledJobs) && Not(hasAbort),true,false)}"> <apex:pageBlockSection title="Automated Test Run" columns="2"> <!--<apex:image value="/s.gif" styleClass="helpIcon" title="Test class names containing this value would be considered for automated test execution Ex:Test% or %_Test (caseinsensitive)"/>--> <apex:inputField required="true" value="{!AtrRecord.Query__c}" label="Keyword"/> <c:AutomatedVFPHelpIcon helpText="Test class names containing this value would be considered for automated test execution Ex:Test% or %_Test (case insensitive)"/> <apex:inputField value="{!AtrRecord.Excluded_Classes__c}" label="Excluded Classes"/> <c:AutomatedVFPHelpIcon helpText="Comma-delimited list of classes to exclude from testing"/> <apex:inputField value="{!AtrRecord.Exclude_Managed_Packages__c}" label="Exclude Managed_Packages"/> <c:AutomatedVFPHelpIcon helpText="Check this box to exclude all Managed Package Unit Tests"/> </apex:pageBlockSection> <apex:pageBlockSection title="Automated Test Email" columns="2"> <apex:inputField required="true" value="{!AtrRecord.Emails__c}" label="Email"/> <c:AutomatedVFPHelpIcon helpText="Comma-separated email addresses"/> <apex:inputField value="{!AtrRecord.Email_on_Pass__c}" label="Email on Pass"/> <c:AutomatedVFPHelpIcon helpText="Send email when all tests pass"/> </apex:pageBlockSection> <apex:pageBlockSection title="Job Schedule " columns="3" > <apex:inputField required="true" value="{!AtrRecord.Schedule__c}" label="Date and Time"/><br/> <c:AutomatedVFPHelpIcon helpText="To Schedule Testclass Execution"/> <div align="center" draggable="false" > <apex:commandButton value="Save & Submit" action="{!doInsert}" /> </div> </apex:pageBlockSection> <!--Automated Test Record--> </apex:outputPanel> <!-- <apex:outputPanel rendered="{!hasScheduledJobs}">--> <apex:outputPanel rendered="{!if(hasScheduledJobs && Not(hasemailpending),true,false)}"> <apex:pageBlockSection title="Job Schedule Status" columns="1"> Automated Test Run Name:{!ATRdetails}_TestRun_{!shddatetime} <apex:commandLink value="Cancel" rendered="{!if(hasScheduledJobs && Not(hasAbort) && Not(hasemailpending),true,false)}" action="{!CancelJobs}" styleClass="btn"> </apex:commandLink> </apex:pageBlockSection> </apex:outputPanel> <!--Need to remove after start --> <apex:outputPanel rendered="{!(hasAbort)}"> <apex:pageBlockSection title="Job Schedule Status" columns="1"> Automated Test Run Name:{!ATRdetails}_TestRun_In Progress </apex:pageBlockSection> </apex:outputPanel> <!--<apex:outputPanel rendered="{!if(hasemailpending && Not(hasAbort),true,false)}" >--> <apex:outputPanel rendered="{!(hasemailpending)}"> <apex:pageBlockSection title="Job Schedule Status" columns="1"> Automated Test Run Name:{!ATRdetails}_TestRun_Email Sent in Progress </apex:pageBlockSection> </apex:outputPanel> <!--Need to remove after END --> <!--Startstics Section --> <apex:pageBlockSection title="Test Class Execution Statistics" id="Piechartsec" columns="4"> Testclass execution {!Percentage}% completed <apex:pageBlockSectionItem id="ShowGraph"> <apex:outputPanel id="Graph"> <apex:chart height="250" width="350" data="{!pieData}" id="Piechartsec2"> <apex:pieSeries dataField="data" labelField="name"/> <apex:legend position="left"/> </apex:chart> </apex:outputPanel> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem id="Refresh"> <apex:commandlink value=" Refresh " status="progress" action="{!Refresh}" styleClass="btn" reRender="Piechartsec2"/> <!-- <apex:commandlink value=" Refresh " status="progress" onclick="window.location.reload();" styleClass="btn" reRender="Piechartsec2"/>--> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem id="Abort"> <apex:commandlink value="Abort" status="progress" action="{!AbortTestJobs}" rendered="{!(hasAbort)}" styleClass="btn" reRender="Piechartsec2"/> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
***********
Testclass:
@isTest private class TestRunner_Test { static Automated_Test_Run__c run; static Test_Runner_Job__c job; static list<Messaging.SingleEmailMessage> messages; static Messaging.SingleEmailMessage mail; static { run = new Automated_Test_Run__c(Name = 'Test Automated Run', Excluded_Classes__c = 'TestRunner, Foo', Emails__c = 'test@test.com'); insert run; job = new Test_Runner_Job__c(Name = 'Test', Automated_Test_Run__c = run.Id); insert job; runJobs(); } static void runJobs() { messages = AutomatedTestSetup_Controller.emailUnprocessedJobStatus(); mail = messages.size() > 0 ? messages[0] : null; } public static testMethod void enqueueTestsCreatesJobs() { // System.assertEquals(0, AutoTestRunner.enqueueTests().size(), 'Tests should not be queued during a test'); } public static testMethod void emailCreatedForAllPassing() { System.assert(mail.getSubject().contains(run.Name), 'Run name not in subject'); set<string> emails = new set<string>(); emails.addAll(mail.getToAddresses()); System.assert(emails.contains(run.Emails__c), 'Run emails not in mail'); System.assert(!mail.getHtmlBody().contains('Test Failures'), 'Failures appear for passing tests'); } public static testMethod void emailCreatedForFailures() { list<ApexTestResult> results = new list<ApexTestResult>(); ApexTestResult result = new ApexTestResult(AsyncApexJobId = job.Id, Outcome = 'Fail', ApexClass = [select Id, Name from ApexClass limit 1], MethodName = 'TestMethod', Message = 'Test Message', StackTrace = 'Test Stack Trace'); results.add(result); list<Test_Runner_Job__c> jobs = [Select t.Name, t.Automated_Test_Run__r.Emails__c, t.Automated_Test_Run__r.Email_on_Pass__c, t.Automated_Test_Run__r.Name, t.Automated_Test_Run__c From Test_Runner_Job__c t where t.Id = :job.Id]; mail = AutomatedTestSetup_Controller.emailMethodStatus(jobs, results)[0]; System.assert(mail.getHtmlBody().contains(result.Message), 'No message for failures'); } public static testMethod void emailOnPassUnchecked() { run.Email_on_Pass__c = false; update run; job = job.clone(); insert job; runJobs(); System.assertEquals(null, mail, 'Email created when Email on Pass unchecked'); } public static testMethod void testRunnerResultsProcessesJobs() { job = [select Processed__c from Test_Runner_Job__c where Id = :job.Id]; System.assert(job.Processed__c, 'Job not marked processed'); } //newly Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId(); Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId(); @testSetup static void setupTestData(){ Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId(); Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId(); Automated_Test_Run__c automated_test_run_Obj = new Automated_Test_Run__c(RecordTypeId = ATERecordTypeId,Active__c = false, Email_on_Pass__c = false, Emails__c = '18@test.com', Exclude_Managed_Packages__c = false, Excluded_Classes__c = '20', Query__c = 'Query__c828', Schedule__c = DateTime.now()); Insert automated_test_run_Obj; Automated_Test_Run__c automated_test_run_Obj22 = new Automated_Test_Run__c(RecordTypeId = ATEmilRecordTypeId,Active__c = false, Email_on_Pass__c = false, Emails__c = '18', Exclude_Managed_Packages__c = false, Excluded_Classes__c = '20', Query__c = 'Query__c828', Schedule__c = DateTime.now()); Insert automated_test_run_Obj22; } static testMethod void test_ApexClassTrigger(){ test.startTest(); List<Automated_Test_Run__c> automated_test_run_Obj2 = [SELECT RecordTypeId,Active__c,Email_on_Pass__c,Emails__c,Exclude_Managed_Packages__c,Excluded_Classes__c,Query__c,Schedule__c from Automated_Test_Run__c]; System.assertEquals(1,automated_test_run_Obj2.size()); test.stopTest(); } public static testMethod void Testmethod1() { Id ATERecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Execution').getRecordTypeId(); Id ATEmilRecordTypeId = Schema.SObjectType.Automated_Test_Run__c.getRecordTypeInfosByName().get('Automated Test Email Notification').getRecordTypeId(); DateTime dt = System.now(); DateTime future = dt.addMinutes(+5); Automated_Test_Run__c run1 = new Automated_Test_Run__c(Name = 'Test Automated Run', Excluded_Classes__c = 'TestRunner, Foo',Active__c = false,Emails__c = 'test@test.com',Schedule__c=future,RecordtypeID=ATERecordTypeId); insert run1; Automated_Test_Run__c run2 = new Automated_Test_Run__c(Name = 'Test Automated Run2',Emails__c = 'test@test.com',RecordtypeID=ATEmilRecordTypeId); insert run2; } static testMethod void test() { AutomatedTestSetup_Controller controller = new AutomatedTestSetup_Controller(); //AutomatedTestSetup_Controller.Refresh(); AutomatedTestSetup_Controller.enqueueTests(); Automated_Test_Run__c AtrRecord = new Automated_Test_Run__c(); Controller.refreshHasScheduledJobs(); Controller.refreshHasTestRun(); Controller.getPieData(); Controller.Calculatepercentage(); Controller.ShowAbortbutton(); Controller.EmailSendPending(); Controller.email(); DateTime dt = System.now(); DateTime future = dt.addMinutes(+5); Controller.scheduleJobs(future); Controller.scheduleJobs(dt); } }
**************
No comments:
Post a Comment