You need to sign in to do that
Don't have an account?
Major1507
I need help with Test class for a Rest Call out class. Can someone help me in writing test class for the below call out class? Any help is greatly appreciated.
public class PagerDutyUtility { @TestVisible private Static Integer WAITTIME; @TestVisible private Static String APIKey; @TestVisible private Static String errorResponse; @TestVisible private Static Integer PERCALL; @TestVisible private Static Integer TIMEOUT; public static void getCustomSetting() { //get default settings PDConfig__c config = PDConfig__c.getOrgDefaults(); WAITTIME = 1000; APIKEY = config.API_Key__c; errorResponse = config.Default_Error__c; PERCALL = Integer.valueOf(config.PerCall__c); TIMEOUT = Integer.valueOf(config.timeout__c); } @AuraEnabled public static List<PagerDutyWrapper> initializeData() { getCustomSetting(); List<PagerDutyWrapper> data = new List<PagerDutyWrapper>(); Map<String, String> businessServices = new Map<String, String>(); //get all business services and dependencies PagerDutyBusinessServices pdbs = fetchBusinessServices(); system.debug(pdbs); if(pdbs != null) { PagerDutyBusinessDependencies deps = new PagerDutyBusinessDependencies(); deps.relationships = new List<PagerDutyBusinessDependencies.Relationship>(); for(PagerDutyBusinessServices.cls_business_services pdb : pdbs.business_services) { PagerDutyWrapper pdw = new PagerDutyWrapper(); pdw.serviceID = pdb.id; pdw.serviceName = pdb.name; pdw.services = new List<PagerDutyData>(); deps.relationships.addAll(fetchBusinessDependencies(pdb.Id).relationships); data.add(pdw); } //get all services List<String> serviceIDs = new List<String>(); PagerDutyServices pds = fetchServices(); if(pds != null) { //gather all service IDs for(PagerDutyServices.cls_services service : pds.services) { serviceIDs.add(service.id); } } //sort relationships for(PagerDutyBusinessDependencies.Relationship relationship : deps.relationships) { for(PagerDutyWrapper wrapper : data) { if(wrapper.serviceID == relationship.dependent_service.id) { for(PagerDutyServices.cls_services service : pds.services) { if(service.Id == relationship.supporting_service.id) { if(wrapper.services.size() > 0) { Boolean found = false; for(PagerDutyData wrapperservice : wrapper.services) { if(wrapperservice.serviceID == relationship.supporting_service.id) { //already exists, no need to replicate. found = true; break; } } if(!found) { wrapper.services.add(new PagerDutyData(service.ID, service.Name, null)); } } else { wrapper.services.add(new PagerDutyData(service.ID, service.Name, null)); } } } } } } //gather all Incidents from Service IDs PagerDutyIncidents pdis = fetchIncidents(serviceIDs); //parse through all services and IDs to create PagerDutyData records and store them in List for(PagerDutyServices.cls_services service : pds.services) { Map<Integer, Map<String, String>> incidents = new Map<Integer, Map<String, String>>(); for(PagerDutyIncidents.cls_incidents incident : pdis.incidents) { if(incident.service.id == service.id) { Integer incidentnum = incident.incident_number; Map<String,String> incidentdata = new Map<String, String>(); incidentdata.put('title', incident.title); incidentdata.put('created_at', incident.created_at); incidentdata.put('status', incident.status); incidentdata.put('description', incident.description); incidentdata.put('incident_number', String.valueOf(incident.incident_number)); incidentdata.put('id', incident.Id); if(incident.priority != null) { incidentdata.put('priority', incident.priority.summary); } else { incidentdata.put('priority', ''); } incidents.put(incidentnum, incidentdata); } } for(PagerDutyWrapper wrapper : data) { for(PagerDutyData existingPDD : wrapper.services) { if(existingPDD.serviceID == service.ID) { existingPDD.setIncidents(incidents); } } } //PagerDutyData newPDD = new PagerDutyData(service.ID, service.Name, incidents); //data.add(newPDD); } } system.debug('+++ ' + data); return data; } public static PagerDutyServices fetchServices() { if(APIKey == null) { getCustomSetting(); } String response = getAllServices(); if(response != null && response != errorResponse) { return (PagerDutyServices)JSON.deserialize(response, PagerDutyServices.class); } return new PagerDutyServices(); } public static String getAllServices() { String endPoint = '/services?limit=' + PERCALL; String apiResponse = PagerDutyUtility.getResponse(endPoint, 'GET', '', '5000', APIKey); return apiResponse; } public static PagerDutyIncidents fetchIncidents(List<String> serviceIDs) { PagerDutyIncidents pdis = new PagerDutyIncidents(); pdis.incidents = new List<PagerDutyIncidents.cls_incidents>(); Integer offset = 0; PagerDutyIncidents newpdis = new PagerDutyIncidents(); do { String response = getAllIncidents(serviceIDs, offset); if(response != null && response != errorResponse) { newpdis = ((PagerDutyIncidents)JSON.deserialize(response, PagerDutyIncidents.class)); pdis.incidents.addAll(newpdis.incidents); offset += PERCALL; } } while(newpdis.more == true); return pdis; } public static String getAllIncidents(List<String> serviceIDs, Integer offset) { String endPoint = '/incidents?'; endPoint += 'time_zone=UTC&since=2020-01-01T00:00:00Z&statuses[]=triggered&statuses[]=acknowledged&statuses[]=resolved&until=' + string.valueof(date.today().addDays(1)).split(' ')[0] + '&limit=' + PERCALL; if(offset != null) { endpoint += '&offset=' + offset; } String apiResponse = PagerDutyUtility.getResponse(endPoint, 'GET', '', '10000', APIKey); return apiResponse; } public static PagerDutyBusinessServices fetchBusinessServices() { String response = getAllBusinessServices(); if(response != null && response != errorResponse) { return (PagerDutyBusinessServices)JSON.deserialize(response, PagerDutyBusinessServices.class); } return new PagerDutyBusinessServices(); } public static String getAllBusinessServices() { if(APIKey == null) { getCustomSetting(); } String endPoint = '/business_services'; String apiResponse = PagerDutyUtility.getResponse(endPoint, 'GET', '', '10000', APIKey); system.debug(apiResponse); return apiResponse; } public static PagerDutyBusinessDependencies fetchBusinessDependencies(String bsID) { String response = getAllBusinessDependencies(bsID); if(response != null && response != errorResponse) { return (PagerDutyBusinessDependencies)JSON.deserialize(response, PagerDutyBusinessDependencies.class); } return new PagerDutyBusinessDependencies(); } public static String getAllBusinessDependencies(String bsID) { if(APIKey == null) { getCustomSetting(); } String endPoint = '/service_dependencies/business_services/' + bsID; String apiResponse = PagerDutyUtility.getResponse(endPoint, 'GET', '', '10000', APIKey); return apiResponse; } @AuraEnabled public static List<PagerDutyUtility.PagerDutyMessage> fetchIncidentLogs(String incidentID) { getCustomSetting(); List<PagerDutyUtility.PagerDutyMessage> messages = new List<PagerDutyUtility.PagerDutyMessage>(); List<PagerDutyIncidentLogs.cls_log_entries> logs = new List<PagerDutyIncidentLogs.cls_log_entries>(); Integer offset = 0; String response = PagerDutyUtility.getAllIncidentLogs(incidentID, offset); if(response != null) { try { PagerDutyIncidentLogs newLogs = new PagerDutyIncidentLogs(); do { newLogs = (PagerDutyIncidentLogs)JSON.deserialize(response, PagerDutyIncidentLogs.class); for(PagerDutyIncidentLogs.cls_log_entries entry : newLogs.log_entries) { logs.add(entry); } offset += PagerDutyUtility.PERCALL; } while(newLogs.more == true); for(PagerDutyIncidentLogs.cls_log_entries log : logs) { if(log.message != null && log.message != '') { PagerDutyUtility.PagerDutyMessage message = new PagerDutyUtility.PagerDutyMessage(); message.message = log.message; message.createdBy = log.agent.summary; message.createdAt = log.created_at; messages.add(message); } } } catch(Exception e) { system.debug('error while parsing messaages: ' + e.getMessage()); } } return messages; } public static String getAllIncidentLogs(String incidentID, Integer offset) { String endPoint = '/incidents/' + incidentID + '/log_entries?'; endPoint += '&limit=' + PERCALL; if(offset != null) { endpoint += '&offset=' + offset; } String apiResponse = PagerDutyUtility.getResponse(endPoint, 'GET', '', '10000', APIKey); return apiResponse; } public static String getResponse(String requestEndpoint, String requestMethod, String requestBody, String requestTimeout, String subdomainAPIKey) { String standardReturnError = errorResponse; String baseURL = 'callout:PagerDutyGetServices'; //TO STORE IN CUSTOM METADATA TYPE LATER String defaultAPIKey = subdomainAPIKey; if(defaultAPIKey == null) { defaultAPIKey = 'mR-xFeyseUf2ksHksdhY'; //REMOVE LATER } //Build Request HttpRequest sendRequest = new HttpRequest(); if(String.IsNotBlank(requestEndpoint)) { sendRequest.setEndPoint(baseURL + requestEndpoint); } else { System.Debug('PagerDutyUtility -> Endpoint cannot be blank!'); return standardReturnError; } if(String.IsNotBlank(requestMethod)) { sendRequest.setMethod(requestMethod); } else { System.Debug('PagerDutyUtility -> requestMethod cannot be blank!'); return standardReturnError; } if(String.IsNotBlank(requestTimeout)) { //Set timeout to specified limit sendRequest.setTimeout(Integer.ValueOf(requestTimeout)); } else { //If a timeout limit is not specified, default it to 5 seconds sendRequest.setTimeout(5000); } sendRequest.setHeader('Content-Type','application/json;charset=utf-8'); sendRequest.setHeader('Accept', 'application/vnd.pagerduty+json;version=2'); String headerValue = defaultAPIKey; String authorizationHeader = 'Token token=' + headerValue; sendRequest.setHeader('Authorization', authorizationHeader); if(String.IsNotBlank(requestBody) && !'GET'.equals(requestMethod)) { sendRequest.setBody(requestBody); } system.debug(sendRequest.getEndpoint()); //Build Response Http http = new Http(); HttpResponse apiResponse = new HttpResponse(); apiResponse = http.send(sendRequest); if(apiResponse == null) { throw new BaseException.NullPointerException('There was a problem performing the callout.'); //create from base exception class } System.debug('*** ' + apiResponse.getBody()); if(apiResponse.getStatusCode() == 200 || apiResponse.getStatusCode() == 201 || apiResponse.getStatusCode() == 202) { return apiResponse.getBody(); } else if(apiResponse.getStatusCode() == 403) { //rate limit error //wait 1 second and retry System.debug('*** PagerDutyUtility -> Rate limit exceeded, waiting 1 second and retrying'); for(integer i = 0; i < WAITTIME; i++) { } return PagerDutyUtility.getResponse(requestEndpoint, requestMethod, requestBody, requestTimeout, subdomainAPIKey); } else { System.Debug('*** PagerDutyUtility -> Bad Response - ' + apiResponse.getBody()); return 'Bad Response - ' + apiResponse.getBody(); } } public Class PagerDutyWrapper { @AuraEnabled public String serviceID {get; set;} @AuraEnabled public String serviceName {get; set;} @AuraEnabled public List<PagerDutyData> services {get; set;} @AuraEnabled public String getStatus() { String response = 'Active'; for(PagerDutyData service : services) { if(service.serviceStatus != 'Active') { if(service.serviceStatus == 'Acknowledged' && response == 'Active') { response = 'Acknowledged'; } if(service.serviceStatus == 'Triggered' && (response == 'Active' || response == 'Acknowledged')) { response = 'Triggered'; } } } return response; } } public Class PagerDutyData { @AuraEnabled public String serviceID {get; set;} @AuraEnabled public String serviceName {get; set;} @AuraEnabled public String serviceStatus {get { return getStatus(); } set;} @AuraEnabled public List<PagerDutyIncident> incidents {get; set;} public PagerDutyData(String sId, String sName, Map<Integer, Map<String, String>> pdis) { this.serviceID = sId; this.serviceName = sName; this.incidents = new List<PagerDutyIncident>(); if(pdis != null && !pdis.isEmpty()) { for(Integer pdikey : pdis.keySet()) { PagerDutyIncident pdi = new PagerDutyIncident(); pdi.num = pdis.get(pdikey).get('incident_number'); pdi.title = pdis.get(pdikey).get('title'); pdi.createdAt = pdis.get(pdikey).get('created_at'); pdi.status = pdis.get(pdikey).get('status'); pdi.description = pdis.get(pdikey).get('description'); pdi.incidentId = pdis.get(pdikey).get('id'); if(pdi.status != 'resolved') { system.debug('+++' + pdi.incidentId); } this.incidents.add(pdi); } } this.serviceStatus = getStatus(); } private void setIncidents(Map<Integer, Map<String, String>> pdis) { for(Integer pdikey : pdis.keySet()) { PagerDutyIncident pdi = new PagerDutyIncident(); pdi.num = pdis.get(pdikey).get('incident_number'); pdi.title = pdis.get(pdikey).get('title'); pdi.createdAt = pdis.get(pdikey).get('created_at'); pdi.status = pdis.get(pdikey).get('status'); pdi.description = pdis.get(pdikey).get('description'); pdi.priority = pdis.get(pdikey).get('priority'); pdi.incidentId = pdis.get(pdikey).get('id'); this.incidents.add(pdi); } } private string getStatus() { //status options = Active, Acknowledged, Triggered String status = 'Active'; for(PagerDutyIncident incident : incidents) { if(incident.status != 'resolved') { if(incident.priority == 'P1') { status = 'Triggered'; } else if(incident.priority != null && incident.priority != '') { if(status != 'Triggered') { status = 'Acknowledged'; } } } } return status; } } public Class PagerDutyIncident { @AuraEnabled public String num {get; set;} @AuraEnabled public String title {get; set;} @AuraEnabled public String createdAt {get; set;} @AuraEnabled public String status {get; set;} @AuraEnabled public String description {get; set;} @AuraEnabled public String priority {get; set;} @AuraEnabled public String incidentId {get; set;} } public Class PagerDutyMessage { @AuraEnabled public String message {get; set;} @AuraEnabled public String createdBy {get; set;} @AuraEnabled public String createdAt {get; set;} } }
I found the below code where in it explains on how to write a test class for the call out can you try checking the link out once:
>> https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_test.htm#apex_methods_system_test
In case if this came in handy can you please choose this as best answer so that it can be used by others in the future.
Regards,
Anutej