Skip to content

Commit

Permalink
Add unit tests for Call Choreo and Call Analytics functions for compr…
Browse files Browse the repository at this point in the history
…ehensive payload
  • Loading branch information
shanggeeth committed Aug 12, 2024
1 parent ef3139e commit e4d664f
Show file tree
Hide file tree
Showing 10 changed files with 570 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,14 @@
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import static org.apache.http.HttpHeaders.ACCEPT;
import static org.apache.http.HttpHeaders.CONTENT_TYPE;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.CommonUtils.getPayloadDataMap;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.Constants.OUTCOME_FAIL;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.Constants.OUTCOME_SUCCESS;
import static org.wso2.carbon.identity.conditional.auth.functions.common.utils.Constants.OUTCOME_TIMEOUT;
Expand Down Expand Up @@ -215,38 +214,4 @@ public void cancelled() {
});
JsGraphBuilder.addLongWaitProcess(asyncProcess, eventHandlers);
}

private Map<String, Object> getPayloadDataMap(Map<String, Object> payloadData) {

if (payloadData == null) {
return new HashMap<>();
}
Map<String, Object> payloadDataMap = new HashMap<>();
for (Map.Entry<String, Object> entry : payloadData.entrySet()) {
Object value = entry.getValue();
if (value instanceof Map) {
payloadDataMap.put(entry.getKey(), getPayloadDataMap((Map<String, Object>) value));
} else if (value instanceof List) {
payloadDataMap.put(entry.getKey(), processList((List<Object>) value));
} else {
payloadDataMap.put(entry.getKey(), value);
}
}
return payloadDataMap;
}

private List<Object> processList(List<Object> list) {

List<Object> resultList = new ArrayList<>();
for (Object item : list) {
if (item instanceof Map) {
resultList.add(getPayloadDataMap((Map<String, Object>) item));
} if (item instanceof List) {
resultList.add(processList((List<Object>) item));
} else {
resultList.add(item);
}
}
return resultList;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@

package org.wso2.carbon.identity.conditional.auth.functions.analytics;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.mockito.Mockito;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
Expand All @@ -28,8 +30,10 @@
import org.wso2.carbon.identity.application.authentication.framework.dao.impl.LongWaitStatusDAOImpl;
import org.wso2.carbon.identity.application.authentication.framework.internal.FrameworkServiceDataHolder;
import org.wso2.carbon.identity.application.authentication.framework.store.LongWaitStatusStoreService;
import org.wso2.carbon.identity.application.common.model.LocalAndOutboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.Property;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.common.model.script.AuthenticationScriptConfig;
import org.wso2.carbon.identity.common.testng.InjectMicroservicePort;
import org.wso2.carbon.identity.common.testng.WithCarbonHome;
import org.wso2.carbon.identity.common.testng.WithH2Database;
Expand All @@ -54,6 +58,7 @@
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
Expand All @@ -65,6 +70,11 @@
@Path("/")
public class CallAnalyticsFunctionImplTest extends JsSequenceHandlerAbstractTest {

public static final String ANALYTICS_SERVICE_CHECK_PAYLOAD = "/analytics-service-check-payload";
public static final String ANALYTICS_PAYLOAD_JSON = "analytics-payload.json";
public static final String ANALYTICS_PAYLOAD_TEST_SP = "analytics-payload-test-sp.xml";
public static final String ANALYTICS_PAYLOAD = "analytics-payload.json";

@WithRealmService
private RealmService realmService;

Expand Down Expand Up @@ -126,6 +136,68 @@ public void testRiskScore() throws JsTestException, NoSuchFieldException,
assertEquals(context.getSelectedAcr(), "1", "Expected acr value not found");
}

@Test
public void testAnalyticsPayload()
throws JsTestException, IdentityGovernanceException, NoSuchFieldException, IllegalAccessException {

IdentityGovernanceService identityGovernanceService = Mockito.mock(IdentityGovernanceService.class);
FunctionsDataHolder functionsDataHolder = Mockito.mock(FunctionsDataHolder.class);
Mockito.when(functionsDataHolder.getIdentityGovernanceService()).thenReturn(identityGovernanceService);
Property property = new Property();
property.setValue("http://localhost:" + microServicePort);
Mockito.when(identityGovernanceService.getConfiguration(new String[]{AnalyticsEngineConfigImpl.RECEIVER},
"test_domain")).thenReturn(new Property[]{property});

Field functionsDataHolderInstance = FunctionsDataHolder.class.getDeclaredField("instance");
functionsDataHolderInstance.setAccessible(true);
functionsDataHolderInstance.set(null, functionsDataHolder);

Field frameworkServiceDataHolderInstance = FrameworkServiceDataHolder.class.getDeclaredField("instance");
frameworkServiceDataHolderInstance.setAccessible(true);
FrameworkServiceDataHolder availableInstance = (FrameworkServiceDataHolder)frameworkServiceDataHolderInstance.get(null);

LongWaitStatusDAOImpl daoImpl = new LongWaitStatusDAOImpl();
CacheBackedLongWaitStatusDAO cacheBackedDao = new CacheBackedLongWaitStatusDAO(daoImpl);
int connectionTimeout = 5000;
LongWaitStatusStoreService longWaitStatusStoreService =
new LongWaitStatusStoreService(cacheBackedDao, connectionTimeout);
availableInstance.setLongWaitStatusStoreService(longWaitStatusStoreService);

AuthenticationContext context = getAuthenticationContextForPayloadTest();

HttpServletRequest req = sequenceHandlerRunner.createHttpServletRequest();
HttpServletResponse resp = sequenceHandlerRunner.createHttpServletResponse();

sequenceHandlerRunner.handle(req, resp, context, "carbon.super");

assertNotNull(context.getSelectedAcr());
assertEquals(context.getSelectedAcr(), "1", "Expected acr value not found");

}

private AuthenticationContext getAuthenticationContextForPayloadTest()
throws JsTestException {

ServiceProvider sp1 = sequenceHandlerRunner.loadServiceProviderFromResource(ANALYTICS_PAYLOAD_TEST_SP, this);
LocalAndOutboundAuthenticationConfig localAndOutboundAuthenticationConfig =
sp1.getLocalAndOutBoundAuthenticationConfig();
AuthenticationScriptConfig authenticationScriptConfig = localAndOutboundAuthenticationConfig
.getAuthenticationScriptConfig();

String jsonPayload = sequenceHandlerRunner.loadJson(ANALYTICS_PAYLOAD, this).toString();
String content = authenticationScriptConfig.getContent();
String newContent = String.format(content, jsonPayload, ANALYTICS_SERVICE_CHECK_PAYLOAD);
authenticationScriptConfig.setContent(newContent);
localAndOutboundAuthenticationConfig.setAuthenticationScriptConfig(authenticationScriptConfig);
sp1.setLocalAndOutBoundAuthenticationConfig(localAndOutboundAuthenticationConfig);

AuthenticationContext context = sequenceHandlerRunner.createAuthenticationContext(sp1);
SequenceConfig sequenceConfig = sequenceHandlerRunner.getSequenceConfig(context, sp1);
context.setSequenceConfig(sequenceConfig);
context.initializeAnalyticsData();
return context;
}

@POST
@Path("/{appName}/{inputStream}")
@Consumes("application/json")
Expand All @@ -143,4 +215,27 @@ public Map<String, Map<String, String>> analyticsReceiver(@PathParam("appName")
response.put("event", responseEvent);
return response;
}

@POST
@Path(ANALYTICS_SERVICE_CHECK_PAYLOAD)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Map<String, String>> analyticsReceiverCheckPayload(Map<String, Object> data) throws JsTestException {

JsonObject expectedPayload = sequenceHandlerRunner.loadJson(ANALYTICS_PAYLOAD_JSON, this);
Gson gson = new Gson();
String dataStr = gson.toJson(data.get("event"));
JsonObject actualPayload = gson.fromJson(dataStr, JsonObject.class);

if (expectedPayload.equals(actualPayload)) {
Map<String, String> responseEvent = new HashMap<>();
responseEvent.put("riskScore", "1");
Map<String, Map<String, String>> response = new HashMap<>();
response.put("event", responseEvent);
return response;
} else {
throw new JsTestException("Payloads do not match. " +
String.format("Expected payload: %s, Actual payload: %s", expectedPayload, actualPayload));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<!--
~ Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 LLC. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<ServiceProvider>
<ApplicationID>1</ApplicationID>
<ApplicationName>default</ApplicationName>
<Description>Default Service Provider</Description>
<InboundAuthenticationConfig>
<InboundAuthenticationRequestConfigs>
<InboundAuthenticationRequestConfig>
<InboundAuthKey>default</InboundAuthKey>
<InboundAuthType></InboundAuthType>
<Properties></Properties>
</InboundAuthenticationRequestConfig>
</InboundAuthenticationRequestConfigs>
</InboundAuthenticationConfig>
<LocalAndOutBoundAuthenticationConfig>
<AuthenticationSteps>
<AuthenticationStep>
<StepOrder>1</StepOrder>
<LocalAuthenticatorConfigs>
<LocalAuthenticatorConfig>
<Name>BasicMockAuthenticator</Name>
<DisplayName>basicauth</DisplayName>
<IsEnabled>true</IsEnabled>
</LocalAuthenticatorConfig>
</LocalAuthenticatorConfigs>
<SubjectStep>true</SubjectStep>
<AttributeStep>true</AttributeStep>
</AuthenticationStep>
<AuthenticationStep>
<StepOrder>2</StepOrder>
<FederatedIdentityProviders>
<IdentityProvider>
<IdentityProviderName>HwkMockAuthenticator</IdentityProviderName>
<IsEnabled>true</IsEnabled>
<DefaultAuthenticatorConfig>HwkMockAuthenticator</DefaultAuthenticatorConfig>
<FederatedAuthenticatorConfigs>
<FederatedAuthenticatorConfig>
<Name>HwkMockAuthenticator</Name>
<IsEnabled>true</IsEnabled>
</FederatedAuthenticatorConfig>
</FederatedAuthenticatorConfigs>
</IdentityProvider>
</FederatedIdentityProviders>
<SubjectStep>false</SubjectStep>
<AttributeStep>false</AttributeStep>
</AuthenticationStep>
<AuthenticationStep>
<StepOrder>3</StepOrder>
<FederatedIdentityProviders>
<IdentityProvider>
<IdentityProviderName>FptMockAuthenticator</IdentityProviderName>
<IsEnabled>true</IsEnabled>
<DefaultAuthenticatorConfig>FptMockAuthenticator</DefaultAuthenticatorConfig>
<FederatedAuthenticatorConfigs>
<FederatedAuthenticatorConfig>
<Name>FptMockAuthenticator</Name>
<IsEnabled>true</IsEnabled>
</FederatedAuthenticatorConfig>
</FederatedAuthenticatorConfigs>
</IdentityProvider>
</FederatedIdentityProviders>
<SubjectStep>false</SubjectStep>
<AttributeStep>false</AttributeStep>
</AuthenticationStep>
<AuthenticationStep>
<StepOrder>4</StepOrder>
<LocalAuthenticatorConfigs>
<LocalAuthenticatorConfig>
<Name>MockFallbackAuthenticator</Name>
<DisplayName>basicauthfallback</DisplayName>
<IsEnabled>true</IsEnabled>
</LocalAuthenticatorConfig>
</LocalAuthenticatorConfigs>
<SubjectStep>true</SubjectStep>
<AttributeStep>true</AttributeStep>
</AuthenticationStep>
</AuthenticationSteps>
<AuthenticationScript type="application/javascript" enabled="true"><![CDATA[
var comprehensivePayload = %s;
function onLoginRequest(context) {
executeStep(1, {
onSuccess: function (context) {
var username = context.steps[1].subject.username;
callAnalytics({'ReceiverUrl': '%s'}, comprehensivePayload, {
onSuccess: function (context, data) {
if (data.event.riskScore > 0) {
Log.info('data.event.riskScore > 0');
context.selectedAcr = ''+ data.event.riskScore;
}
}, onFail: function (context, data) {
Log.info('fail Called');
}
});
}
});
}
]]></AuthenticationScript>
<AuthenticationType>flow</AuthenticationType>
</LocalAndOutBoundAuthenticationConfig>
<RequestPathAuthenticatorConfigs></RequestPathAuthenticatorConfigs>
<InboundProvisioningConfig></InboundProvisioningConfig>
<OutboundProvisioningConfig></OutboundProvisioningConfig>
<ClaimConfig>
<AlwaysSendMappedLocalSubjectId>true</AlwaysSendMappedLocalSubjectId>
</ClaimConfig>
<PermissionAndRoleConfig></PermissionAndRoleConfig>
</ServiceProvider>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"stringKey": "stringValue",
"numberKey": 123,
"booleanKey": true,
"arrayKey": [
"arrayString",
456,
false,
{
"nestedObjectInArrayKey": "nestedObjectValue",
"nestedArrayInArrayKey": ["nestedArrayValue1", "nestedArrayValue2"]
}
],
"objectKey": {
"objectStringKey": "objectStringValue",
"objectNumberKey": 789,
"objectBooleanKey": false,
"nestedObjectKey": {
"nestedObjectStringKey": "nestedObjectStringValue",
"nestedObjectArrayKey": [
"nestedArrayValue1",
101112,
true
]
},
"arrayOfObjectsKey": [
{
"arrayOfObjectsStringKey": "arrayOfObjectsStringValue1",
"arrayOfObjectsNumberKey": 131415,
"arrayOfObjectsBooleanKey": true
},
{
"arrayOfObjectsStringKey": "arrayOfObjectsStringValue2",
"arrayOfObjectsNumberKey": 161718,
"arrayOfObjectsBooleanKey": false
}
]
}
}
Loading

0 comments on commit e4d664f

Please sign in to comment.