Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding HTTP Request Mocking #85

Merged
merged 7 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion cspell-dict.txt
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,5 @@ Retryable
Archiver
Schedulable
ISBLANK
yogiaprelliyanto
yogiaprelliyanto
Picklist
32 changes: 31 additions & 1 deletion rflib/main/default/classes/rflib_GlobalSettings.cls
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
* @description Provides values for any rflib related global settings.
*/
@SuppressWarnings('PMD.ClassNamingConventions')
public with sharing class rflib_GlobalSettings {
public class rflib_GlobalSettings {

@TestVisible
private static final Integer APPLICATION_EVENT_RETAIN_X_DAYS_DEFAULT_VALUE = 45;
Expand All @@ -51,6 +51,15 @@ public with sharing class rflib_GlobalSettings {

@TestVisible
private static final Boolean USE_DEFAULT_WORKFLOW_USER_FOR_LOG_EVENTS_DEFAULT_VALUE = false;

@TestVisible
private static final Boolean HTTP_REQUEST_MOCKING_ENABLED = false;

@TestVisible
private static final Boolean HTTP_REQUEST_MOCKING_ALLOW_IN_PRODUCTION = false;

@TestVisible
private static final Boolean HTTP_REQUEST_MOCKING_THROW_ERROR_IF_MOCK_NOT_FOUND = false;

public static Integer daysToRetainApplicationEventsOrDefault {
get {
Expand Down Expand Up @@ -93,6 +102,27 @@ public with sharing class rflib_GlobalSettings {
return String.isBlank(val) ? USE_DEFAULT_WORKFLOW_USER_FOR_LOG_EVENTS_DEFAULT_VALUE : Boolean.valueOf(val);
}
}

public static Boolean httpRequestMockingEnabled {
get {
String val = getSetting('Http_Mocking_Enabled');
return String.isBlank(val) ? HTTP_REQUEST_MOCKING_ENABLED : Boolean.valueOf(val);
}
}

public static Boolean httpRequestMockingAllowInProduction {
get {
String val = getSetting('Http_Mocking_Allow_In_Production');
return String.isBlank(val) ? HTTP_REQUEST_MOCKING_ALLOW_IN_PRODUCTION : Boolean.valueOf(val);
}
}

public static Boolean httpRequestMockingThrowErrorIfNotMockNotFound {
get {
String val = getSetting('Http_Mocking_Throw_Error_If_Not_Found');
return String.isBlank(val) ? HTTP_REQUEST_MOCKING_THROW_ERROR_IF_MOCK_NOT_FOUND : Boolean.valueOf(val);
}
}

@TestVisible
private static final Map<String, String> SETTINGS = new Map<String, String>();
Expand Down
156 changes: 156 additions & 0 deletions rflib/main/default/classes/rflib_HttpEndpointMocker.cls
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
/*
* Copyright (c) 2024 Johannes Fischer <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name "RFLIB", the name of the copyright holder, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

/**
* @group Integration
* @description This class provides access to the `rflib_HTTP_Mock_Endpoint__mdt`
* for mocking production endpoints.
*/
@SuppressWarnings('PMD.ClassNamingConventions')
public class rflib_HttpEndpointMocker {

private static final rflib_Logger LOGGER = rflib_LoggerUtil.getFactory().createBatchedLogger('rflib_HttpEndpointMocker');

@TestVisible
private static List<rflib_HTTP_Mock_Endpoint__mdt> mockEndpointSettings {
get {
if (mockEndpointSettings == null) {
mockEndpointSettings = getAllActiveMockEndpoints();
}
return mockEndpointSettings;
}
private set;
}

public static HttpResponse getMockResponse(HttpRequest req) {
LOGGER.debug('getMockResponse invoked: ' + req);

for (rflib_HTTP_Mock_Endpoint__mdt endpointInfo : mockEndpointSettings) {

if (endpointInfo.HTTP_Method__c == req.getMethod() &&
Pattern.matches(endpointInfo.URL_Pattern__c, req.getEndpoint()) &&
Pattern.matches(endpointInfo.Payload_Pattern__c, req.getBody()) &&
endpointInfo.Is_Active__c) {

LOGGER.debug('Request matched mock endpoint: ' + JSON.serialize(endpointInfo));
Integer statusCode = Integer.valueOf(endpointInfo.Response_Status__c);
HttpResponse response = new HttpResponse();
response.setStatusCode(statusCode);
response.setStatus(STATUS_CODE_DESCRIPTIONS.get(statusCode));
response.setBody(endpointInfo.Response_Payload__c);

LOGGER.info('Returning mock response: {0} with body: {1}', new String[] { response.toString(), response.getBody() } );

return response;
}
}

LOGGER.debug('No mock response found');

return null;
}

private static List<rflib_HTTP_Mock_Endpoint__mdt> getAllActiveMockEndpoints() {
LOGGER.debug('getAllActiveMockEndpoints invoked');

List<rflib_HTTP_Mock_Endpoint__mdt> allMockEndpoints = rflib_HTTP_Mock_Endpoint__mdt.getAll().values();

LOGGER.debug('All mock endpoint values: ' + JSON.serialize(allMockEndpoints));

List<rflib_HTTP_Mock_Endpoint__mdt> result = new LIst<rflib_HTTP_Mock_Endpoint__mdt>();
for (rflib_HTTP_Mock_Endpoint__mdt endpoint : allMockEndpoints) {
if (endpoint.Is_Active__c == true) {
result.add(endpoint);
}
}

LOGGER.debug('Filtered mock endpoint values: ' + JSON.serialize(result));

return result;
}

private static Map<Integer, String> STATUS_CODE_DESCRIPTIONS = new Map<Integer, String>{
// 1xx: Informational
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',

// 2xx: Success
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',

// 3xx: Redirection
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
307 => 'Temporary Redirect',
308 => 'Permanent Redirect',

// 4xx: Client Error
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Payload Too Large',
414 => 'URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot', // Historical code, not in official registry but documented

// 5xx: Server Error
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
508 => 'Loop Detected',
510 => 'Not Extended',
511 => 'Network Authentication Required'
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<status>Active</status>
</ApexClass>
18 changes: 18 additions & 0 deletions rflib/main/default/classes/rflib_HttpRequest.cls
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ public with sharing class rflib_HttpRequest {

private final rflib_Logger logger;
private final HttpRequest delegatee = new HttpRequest();

public Boolean suppressMocking = false;

public rflib_HttpRequest() {
this(rflib_LoggerUtil.getFactory().createLogger('rflib_HttpRequest'));
Expand All @@ -60,6 +62,22 @@ public with sharing class rflib_HttpRequest {
LOGGER.info('Sending request: {0} with body: {1}', new String[] { delegatee.toString(), delegatee.getBody() } );

delegatee.setHeader(rflib_GlobalSettings.traceIdHeaderNameOrDefault, rflib_TraceId.value);

if (!suppressMocking &&
rflib_GlobalSettings.httpRequestMockingEnabled && (
rflib_OrgUtil.isSandboxOrg() ||
(rflib_OrgUtil.isProductionOrg() && rflib_GlobalSettings.httpRequestMockingAllowInProduction)
)) {
HttpResponse mockResponse = rflib_HttpEndpointMocker.getMockResponse(delegatee);

if (mockResponse != null) {
return mockResponse;
}

if (rflib_GlobalSettings.httpRequestMockingThrowErrorIfNotMockNotFound) {
throw new CalloutException('No matching RFLIB HTTP Mock Endpoint configuration found; please check the CMT object.');
}
}

Http http = new Http();
HttpResponse response = http.send(delegatee);
Expand Down
50 changes: 50 additions & 0 deletions rflib/main/default/classes/rflib_OrgUtil.cls
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2024 Johannes Fischer <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name "RFLIB", the name of the copyright holder, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
@SuppressWarnings('PMD.ClassNamingConventions')
public class rflib_OrgUtil {

@TestVisible
private static Boolean isSandbox {
get {
if (isSandbox == null) {
isSandbox = [SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox;
}
return isSandbox;
}
set;
}

public static Boolean isSandboxOrg() {
return isSandbox;
}

public static Boolean isProductionOrg() {
return !isSandbox;
}
}
5 changes: 5 additions & 0 deletions rflib/main/default/classes/rflib_OrgUtil.cls-meta.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>59.0</apiVersion>
<status>Active</status>
</ApexClass>
Original file line number Diff line number Diff line change
Expand Up @@ -339,7 +339,8 @@ public with sharing class rflib_PermissionsExplorerController {
String query = fieldSelection + tableName + condition + sortOrder;
String urlPath = String.isNotBlank(servicePath) ? servicePath : '/services/data/v59.0/query?q=' + EncodingUtil.urlEncode(query, 'UTF-8');

rflib_HttpRequest req = new rflib_HttpRequest();
rflib_HttpRequest req = new rflib_HttpRequest();
req.suppressMocking = true;
req.setEndpoint('callout:rflib_SF_REST_API' + urlPath);
req.setMethod('GET');

Expand Down
Loading