diff options
Diffstat (limited to 'adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible')
6 files changed, 712 insertions, 215 deletions
diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java index 4636d2450..be4bfd8f2 100644 --- a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterImpl.java @@ -1,11 +1,9 @@ /*- * ============LICENSE_START======================================================= - * ONAP : APPC + * ONAP : SLI * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= * Licensed 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 @@ -24,43 +22,82 @@ package org.onap.ccsdk.adapter.ansible.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - import java.util.HashMap; import java.util.Map; - +import java.util.Properties; +import org.json.JSONException; +import org.json.JSONObject; import org.junit.After; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; import org.onap.ccsdk.sli.adaptors.ansible.impl.AnsibleAdapterImpl; +import org.onap.ccsdk.sli.adaptors.ansible.impl.AnsibleAdapterPropertiesProviderImpl; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleMessageParser; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicException; +import org.powermock.reflect.Whitebox; - +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; +import static org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapterConstants.*; +@RunWith(MockitoJUnitRunner.class) public class TestAnsibleAdapterImpl { - private final String PENDING = "100"; - private final String SUCCESS = "400"; - private String message = "{\"Results\":{\"192.168.1.10\":{\"Id\":\"101\",\"StatusCode\":200,\"StatusMessage\":\"SUCCESS\"}},\"StatusCode\":200,\"StatusMessage\":\"FINISHED\"}"; + private static final String PENDING = "100"; + private static final String AGENT_URL = "https://192.168.1.1"; - private AnsibleAdapterImpl adapter; - private String TestId; + private static String KEYSTORE_PSWD; + private static Properties properties; private boolean testMode = true; + + private AnsibleAdapterImpl adapter; + private AnsibleResult result; + private AnsibleAdapterImpl spyAdapter; private Map<String, String> params; private SvcLogicContext svcContext; + private JSONObject jsonPayload; + @Mock + private AnsibleMessageParser messageProcessor; + + @BeforeClass + public static void once() { + properties = new AnsibleAdapterPropertiesProviderImpl().getProperties(); + KEYSTORE_PSWD = properties.getProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd"); + } + /** + * Use reflection to locate fields and methods so that they can be manipulated + * during the test to change the internal state accordingly. + */ @Before - public void setup() throws IllegalArgumentException { + public void setup() { testMode = true; svcContext = new SvcLogicContext(); adapter = new AnsibleAdapterImpl(testMode); - params = new HashMap<>(); - params.put("AgentUrl", "https://192.168.1.1"); - params.put("User", "test"); - params.put("Password", "test"); + params.put("AgentUrl", AGENT_URL); + jsonPayload = new JSONObject(); + jsonPayload.put("Id", "100"); + jsonPayload.put("User", "test"); + jsonPayload.put("Password", "test"); + jsonPayload.put("PlaybookName", "test_playbook.yaml"); + jsonPayload.put("Timeout", "60000"); + jsonPayload.put("AgentUrl", AGENT_URL); + result = new AnsibleResult(); + result.setStatusMessage("Success"); + result.setResults("Success"); + result.setOutput("{}"); + Whitebox.setInternalState(adapter, "messageProcessor", messageProcessor); + spyAdapter = Mockito.spy(adapter); } @After @@ -72,76 +109,131 @@ public class TestAnsibleAdapterImpl { } @Test - public void reqExec_shouldSetPending() throws IllegalStateException, IllegalArgumentException { + public void reqExec_shouldSetPending() throws SvcLogicException { + result.setStatusCode(Integer.parseInt(PENDING)); + when(messageProcessor.reqMessage(params)).thenReturn(jsonPayload); + when(messageProcessor.parsePostResponse(anyString())).thenReturn(result); + spyAdapter.reqExec(params, svcContext); + assertEquals(PENDING, svcContext.getAttribute(RESULT_CODE_ATTRIBUTE_NAME)); + } - params.put("PlaybookName", "test_playbook.yaml"); + @Test(expected = SvcLogicException.class) + public void reqExecResult_shouldSetSuccess() throws SvcLogicException { + params.put("Id", "100"); + result.setStatusMessage(SUCCESS); + when(messageProcessor.reqUriResult(params)).thenReturn(AGENT_URL); + when(messageProcessor.parseGetResponse(anyString())).thenReturn(result); + spyAdapter.reqExecResult(params, svcContext); + assertEquals(SUCCESS, svcContext.getAttribute(SUCCESS)); + } + @Test(expected = SvcLogicException.class) + public void reqExecResult_Failure() throws SvcLogicException { + params.put("Id", "100"); + result.setStatusCode(100); + result.setStatusMessage("Failed"); + JSONObject cData = new JSONObject(); + cData.put("GatewayInfo", "Radius"); + result.setConfigData(cData.toString()); + result.setOutput(cData.toString()); + when(messageProcessor.reqUriResult(params)).thenReturn(AGENT_URL); + when(messageProcessor.parseGetResponse(anyString())).thenReturn(result); + adapter.reqExecResult(params, svcContext); + } + + @Test(expected = SvcLogicException.class) + public void reqExecResult_SvcLogicException() throws SvcLogicException { + when(messageProcessor.reqUriResult(params)).thenThrow(new SvcLogicException()); + adapter.reqExecResult(params, svcContext); + } - try { - adapter.reqExec(params, svcContext); - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - TestId = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.Id"); - System.out.println("Comparing " + PENDING + " and " + status); - assertEquals(PENDING, status); - } catch (SvcLogicException e) { - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - fail(e.getMessage() + " Code = " + status); - } catch (Exception e) { - fail(e.getMessage() + " Unknown exception encountered "); - } + @Test(expected = SvcLogicException.class) + public void reqExecResult_numberFormatException() + throws IllegalStateException, IllegalArgumentException, SvcLogicException { + when(messageProcessor.reqUriResult(params)).thenThrow(new NumberFormatException()); + adapter.reqExecResult(params, svcContext); } @Test - public void reqExecResult_shouldSetSuccess() throws IllegalStateException, IllegalArgumentException { + public void reqExecLog_shouldSetMessage() throws SvcLogicException { + params.put("Id", "101"); + when(messageProcessor.reqUriLog(params)).thenReturn(AGENT_URL); + adapter.reqExecLog(params, svcContext); + String message = getResponseMessage(); + assertEquals(message, svcContext.getAttribute(LOG_ATTRIBUTE_NAME)); + } - params.put("Id", "100"); + private String getResponseMessage() { + JSONObject response = new JSONObject(); + response.put(STATUS_CODE, 200); + response.put(STATUS_MESSAGE, "FINISHED"); + JSONObject results = new JSONObject(); - for (String ukey : params.keySet()) { - System.out.println(String.format("Ansible Parameter %s = %s", ukey, params.get(ukey))); - } + JSONObject vmResults = new JSONObject(); + vmResults.put(STATUS_CODE, 200); + vmResults.put(STATUS_MESSAGE, "SUCCESS"); + vmResults.put("Id", ""); + results.put("192.168.1.10", vmResults); - try { - adapter.reqExecResult(params, svcContext); - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - assertEquals(SUCCESS, status); - } catch (SvcLogicException e) { - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.result.code"); - fail(e.getMessage() + " Code = " + status); - } catch (Exception e) { - fail(e.getMessage() + " Unknown exception encountered "); - } + response.put("Results", results); + return response.toString(); } - @Test - public void reqExecLog_shouldSetMessage() throws IllegalStateException, IllegalArgumentException { + @Test(expected = SvcLogicException.class) + public void reqExecException() + throws IllegalStateException, IllegalArgumentException, SvcLogicException { + when(messageProcessor.reqUriLog(params)).thenThrow(new SvcLogicException("Appc Exception")); + adapter.reqExecLog(params, svcContext); + } - params.put("Id", "101"); + @Test(expected = SvcLogicException.class) + public void reqExec_SvcLogicException() + throws IllegalStateException, IllegalArgumentException, SvcLogicException { + when(messageProcessor.reqMessage(params)).thenThrow(new SvcLogicException()); + adapter.reqExec(params, svcContext); + } + + @Test(expected = SvcLogicException.class) + public void reqExec_JsonException() + throws IllegalStateException, IllegalArgumentException, SvcLogicException { + when(messageProcessor.reqMessage(params)).thenThrow(new JSONException("Json Exception")); + adapter.reqExec(params, svcContext); + } + + @Test(expected = SvcLogicException.class) + public void reqExec_NumberFormatException() + throws IllegalStateException, IllegalArgumentException, SvcLogicException { + when(messageProcessor.reqMessage(params)).thenThrow(new NumberFormatException("Numbre Format Exception")); + adapter.reqExec(params, svcContext); + } - try { - adapter.reqExecLog(params, svcContext); - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.log"); - assertEquals(message, status); - } catch (SvcLogicException e) { - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.log"); - fail(e.getMessage() + " Code = " + status); - } catch (Exception e) { - fail(e.getMessage() + " Unknown exception encountered "); - } + @Test + public void testInitializeWithDefault() { + properties.setProperty("org.onap.appc.adapter.ansible.clientType", ""); + adapter = new AnsibleAdapterImpl(); + assertNotNull(adapter); } @Test - public void reqExecOutput_shouldSetMessage() throws IllegalStateException, IllegalArgumentException { + public void testInitializeWithTrustAll() { + properties.setProperty("org.onap.appc.adapter.ansible.clientType", "TRUST_ALL"); + adapter = new AnsibleAdapterImpl(); + assertNotNull(adapter); + } - params.put("Id", "101"); + @Test + public void testInitializeWithTrustCert() { + properties.setProperty("org.onap.appc.adapter.ansible.clientType", "TRUST_CERT"); + properties.setProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd", KEYSTORE_PSWD); + adapter = new AnsibleAdapterImpl(); + assertNotNull(adapter); + } + + @Test + public void testInitializeWithException() { + properties.setProperty("org.onap.appc.adapter.ansible.clientType", "TRUST_CERT"); + properties.setProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd", "appc"); + adapter = new AnsibleAdapterImpl(); + assertNotNull(adapter); + } - try { - adapter.reqExecOutput(params, svcContext); - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.output"); - assertEquals(message, status); - } catch (SvcLogicException e) { - String status = svcContext.getAttribute("org.onap.appc.adapter.ansible.output"); - fail(e.getMessage() + " Code = " + status); - } catch (Exception e) { - fail(e.getMessage() + " Unknown exception encountered "); - } - } -} +}
\ No newline at end of file diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java index b3c01e9bd..5ce1712d3 100644 --- a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestAnsibleAdapterPropertiesProviderImpl.java @@ -1,8 +1,8 @@ /*- * ============LICENSE_START======================================================= - * onap + * ONAP : SLI * ================================================================================ - * Copyright (C) 2018 Samsung + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,39 +15,50 @@ * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. * ============LICENSE_END========================================================= */ package org.onap.ccsdk.adapter.ansible.impl; -import org.junit.Before; +import java.io.File; +import java.util.Properties; import org.junit.Test; import org.onap.ccsdk.sli.adaptors.ansible.impl.AnsibleAdapterPropertiesProviderImpl; -import java.util.Properties; - import static org.junit.Assert.assertEquals; +import static org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapterConstants.*; public class TestAnsibleAdapterPropertiesProviderImpl { - AnsibleAdapterPropertiesProviderImpl adaptor; - @Before - public void setup() throws IllegalArgumentException { - adaptor = new AnsibleAdapterPropertiesProviderImpl(); - } - @Test public void testGetProperties() throws IllegalStateException, IllegalArgumentException { - Properties prop = adaptor.getProperties(); + Properties prop = new AnsibleAdapterPropertiesProviderImpl().getProperties(); + + assertEquals("TRUST_ALL", prop.getProperty(CLIENT_TYPE_PROPERTY_NAME)); + assertEquals("org.onap.appc.appc_ansible_adapter", prop.getProperty("org.onap.appc.provider.adaptor.name")); + assertEquals("changeit", prop.getProperty(TRUSTSTORE_PASS_PROPERTY_NAME)); + assertEquals("${user.home},/opt/opendaylight/current/properties,.", prop.getProperty("org.onap.appc.bootstrap.path")); + assertEquals("APPC", prop.getProperty("appc.application.name")); + assertEquals("appc.properties", prop.getProperty("org.onap.appc.bootstrap.file")); + assertEquals("org/onap/appc/i18n/MessageResources", prop.getProperty("org.onap.appc.resources")); + assertEquals("/opt/opendaylight/tls-client/mykeystore.js", prop.getProperty(TRUSTSTORE_PROPERTY_NAME)); + } - System.out.println("All Property params : " + prop); - assertEquals("TRUST_ALL", prop.getProperty("org.onap.appc.adapter.ansible.clientType")); + @Test + public void testGetTestProperties() throws IllegalStateException, IllegalArgumentException { + final String configFilePath = "src/test/resources/properties/ansible-adapter-test.properties".replace("/", File.separator); + Properties prop = new AnsibleAdapterPropertiesProviderImpl(configFilePath).getProperties(); + + assertEquals("appc", prop.getProperty(CLIENT_TYPE_PROPERTY_NAME)); assertEquals("org.onap.appc.appc_ansible_adapter", prop.getProperty("org.onap.appc.provider.adaptor.name")); - assertEquals("changeit", prop.getProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd")); - assertEquals("${user.home},/opt/opendaylight/current/properties", prop.getProperty("org.onap.appc.bootstrap.path")); + assertEquals("Aa123456", prop.getProperty(TRUSTSTORE_PASS_PROPERTY_NAME)); + assertEquals("${user.home},/opt/opendaylight/current/properties,.", prop.getProperty("org.onap.appc.bootstrap.path")); assertEquals("APPC", prop.getProperty("appc.application.name")); assertEquals("appc.properties", prop.getProperty("org.onap.appc.bootstrap.file")); - assertEquals("org.onap/appc/i18n/MessageResources", prop.getProperty("org.onap.appc.resources")); - assertEquals("/opt/opendaylight/tls-client/mykeystore.js", prop.getProperty("org.onap.appc.adapter.ansible.trustStore")); + assertEquals("org/onap/appc/i18n/MessageResources", prop.getProperty("org.onap.appc.resources")); + assertEquals("src/test/resources/org/onap/appc/asdc-client.jks", prop.getProperty(TRUSTSTORE_PROPERTY_NAME)); } + } diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java index c94655f56..25f89863d 100644 --- a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/impl/TestConnectionBuilder.java @@ -1,8 +1,8 @@ /*- * ============LICENSE_START======================================================= - * onap + * ONAP : SLI * ================================================================================ - * Copyright (C) 2018 Samsung + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,140 +15,221 @@ * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. * ============LICENSE_END========================================================= */ package org.onap.ccsdk.adapter.ansible.impl; -import org.junit.Before; -import org.junit.Test; -import org.onap.ccsdk.sli.adaptors.ansible.impl.ConnectionBuilder; -import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; -import org.onap.ccsdk.sli.core.sli.SvcLogicException; - -import javax.net.ssl.SSLException; +import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; +import java.util.Properties; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.ccsdk.sli.adaptors.ansible.impl.AnsibleAdapterPropertiesProviderImpl; +import org.onap.ccsdk.sli.adaptors.ansible.impl.ConnectionBuilder; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResultCodes; +import org.powermock.reflect.Whitebox; import static org.junit.Assert.assertEquals; - +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.ccsdk.sli.adaptors.ansible.AnsibleAdapterConstants.*; + +@RunWith(MockitoJUnitRunner.class) public class TestConnectionBuilder { - ConnectionBuilder builder; + + private static String KEYSTORE_FILE; + private static String KEYSTORE_PSWD; + private static String KEYSTORE_CERTIFICATE; + private static String USER; + private static String PSWD; + private static String URL; + + private final int SUCCESS_STATUS = 200; + private ConnectionBuilder connectionBuilder; + + @Mock + private CloseableHttpClient httpClient; + + @Mock + private HttpClientContext httpClientContext; + + @Mock + private CloseableHttpResponse response; + + @Mock + private HttpEntity entity; + + @Mock + private StatusLine statusLine; + + /** + * Load the configuration properties + */ + @BeforeClass + public static void once() { + final String configFilePath = "src/test/resources/properties/ansible-adapter-test.properties".replace("/", File.separator); + Properties properties = new AnsibleAdapterPropertiesProviderImpl(configFilePath).getProperties(); + + KEYSTORE_FILE = properties.getProperty(TRUSTSTORE_PROPERTY_NAME); + KEYSTORE_PSWD = properties.getProperty(TRUSTSTORE_PASS_PROPERTY_NAME); + KEYSTORE_CERTIFICATE = properties.getProperty("org.onap.appc.adapter.ansible.cert"); + USER = properties.getProperty("org.onap.appc.adapter.ansible.username"); + PSWD = properties.getProperty("org.onap.appc.adapter.ansible.password"); + URL = properties.getProperty("org.onap.appc.adapter.ansible.identity"); + } + @Before - public void setup() - throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { - builder = new ConnectionBuilder(1); + public void setup() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { + connectionBuilder = new ConnectionBuilder(1, 2000); + Whitebox.setInternalState(connectionBuilder, "httpClient", httpClient); + Whitebox.setInternalState(connectionBuilder, "httpContext", httpClientContext); + HttpResponse httpResponse = response; + when(httpResponse.getEntity()).thenReturn(entity); + when(httpResponse.getStatusLine()).thenReturn(statusLine); + when(statusLine.getStatusCode()).thenReturn(SUCCESS_STATUS); } + @After + public void tearDown() { + connectionBuilder = null; + } @Test - public void testSetHttpContext() throws IllegalStateException, IllegalArgumentException { - String user = "testUser"; - String pass = "testPassword"; - - builder.setHttpContext(user, pass); + public void testConnectionBuilder() throws KeyManagementException, KeyStoreException, CertificateException, + NoSuchAlgorithmException, IOException { + char[] trustStorePassword = KEYSTORE_PSWD.toCharArray(); + ConnectionBuilder connectionBuilder = new ConnectionBuilder(KEYSTORE_FILE, trustStorePassword, 600000, ""); + assertNotNull(connectionBuilder); } @Test - public void testPost() throws IllegalStateException, IllegalArgumentException { - String user = "testUser"; - String pass = "testPassword"; - String agentUrl = "test/server.com"; - String payload = "testPayload"; + public void testConnectionBuilderWithFilePath() throws KeyManagementException, KeyStoreException, + CertificateException, NoSuchAlgorithmException, IOException { + new ConnectionBuilder(KEYSTORE_CERTIFICATE, 600000); + } - builder.setHttpContext(user, pass); - AnsibleResult result = builder.post(agentUrl, payload); + @Test + public void testSetHttpContext() { + ConnectionBuilder spyConnectionBuilder = Mockito.spy(connectionBuilder); + spyConnectionBuilder.setHttpContext(USER, PSWD); + verify(spyConnectionBuilder, times(1)).setHttpContext(USER, PSWD); + } - assertEquals(611, result.getStatusCode()); - assertEquals(null, result.getStatusMessage()); + @Test + public void testPost() throws IOException { + when(httpClient.execute(anyObject(), eq(httpClientContext))).thenReturn(response); + AnsibleResult result = connectionBuilder.post(URL, "appc"); + assertNull(result.getStatusMessage()); + assertEquals(SUCCESS_STATUS, result.getStatusCode()); assertEquals("UNKNOWN", result.getResults()); } @Test - public void testGet() throws IllegalStateException, IllegalArgumentException { - String user = "testUser"; - String pass = "testPassword"; - String agentUrl = "test/server.com"; - - builder.setHttpContext(user, pass); - AnsibleResult result = builder.get(agentUrl); + public void testPostWithException() throws IOException { + when(httpClient.execute(anyObject(), eq(httpClientContext))).thenThrow(new IOException()); + AnsibleResult result = connectionBuilder.post(URL, "appc"); + assertEquals(AnsibleResultCodes.IO_EXCEPTION.getValue(), result.getStatusCode()); + } - assertEquals(611, result.getStatusCode()); - assertEquals(null, result.getStatusMessage()); + @Ignore + @Test + public void testGet() throws IOException { + when(httpClient.execute(anyObject(), eq(httpClientContext))).thenReturn(response); + AnsibleResult result = connectionBuilder.get(URL); + assertNull(result.getStatusMessage()); + assertEquals(SUCCESS_STATUS, result.getStatusCode()); assertEquals("UNKNOWN", result.getResults()); } @Test - public void testGetMode() - throws SSLException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { - String user = "testUser"; - String pass = "testPassword"; - String agentUrl = "test/server.com"; + public void testGetWithException() throws IOException { + when(httpClient.execute(anyObject(), eq(httpClientContext))).thenThrow(new IOException()); + AnsibleResult result = connectionBuilder.get(URL); + assertEquals(AnsibleResultCodes.IO_EXCEPTION.getValue(), result.getStatusCode()); + } - builder = new ConnectionBuilder(2); - builder.setHttpContext(user, pass); - AnsibleResult result = builder.get(agentUrl); + @Test + public void testClose() { + connectionBuilder.close(); + } + + @Test + public void testGetMode() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + connectionBuilder = new ConnectionBuilder(2, 2000); + connectionBuilder.setHttpContext(USER, PSWD); + AnsibleResult result = connectionBuilder.get("test.server.com"); assertEquals(611, result.getStatusCode()); - assertEquals(null, result.getStatusMessage()); + assertNull(result.getStatusMessage()); assertEquals("UNKNOWN", result.getResults()); } @Test (expected = FileNotFoundException.class) - public void testGetModeNoCert() - throws KeyStoreException, CertificateException, IOException, - KeyManagementException, NoSuchAlgorithmException, SvcLogicException { - String user = "testUser"; - String pass = "testPassword"; - String agentUrl = "test/server.com"; + public void testGetModeNoCert() throws KeyStoreException, CertificateException, IOException, + KeyManagementException, NoSuchAlgorithmException { String certFile = "testCert"; - builder = new ConnectionBuilder(certFile); - builder.setHttpContext(user, pass); - AnsibleResult result = builder.get(agentUrl); + connectionBuilder = new ConnectionBuilder(certFile, 2000); + connectionBuilder.setHttpContext(USER, PSWD); + AnsibleResult result = connectionBuilder.get(URL); assertEquals(611, result.getStatusCode()); - assertEquals(null, result.getStatusMessage()); + assertNull(result.getStatusMessage()); assertEquals("UNKNOWN", result.getResults()); } @Test - public void testGetModeCert() - throws KeyStoreException, CertificateException, IOException, - KeyManagementException, NoSuchAlgorithmException, SvcLogicException { - String user = "testUser"; - String pass = "testPassword"; - String agentUrl = "test/server.com"; + public void testGetModeCert() throws KeyStoreException, CertificateException, IOException, + KeyManagementException, NoSuchAlgorithmException { String certFile = "src/test/resources/cert"; - builder = new ConnectionBuilder(certFile); - builder.setHttpContext(user, pass); - AnsibleResult result = builder.get(agentUrl); + connectionBuilder = new ConnectionBuilder(certFile, 2000); + connectionBuilder.setHttpContext(USER, PSWD); + AnsibleResult result = connectionBuilder.get("test.server.com"); assertEquals(611, result.getStatusCode()); - assertEquals(null, result.getStatusMessage()); + assertNull(result.getStatusMessage()); assertEquals("UNKNOWN", result.getResults()); } @Test (expected = IOException.class) - public void testGetModeStore() - throws KeyStoreException, CertificateException, IOException, - KeyManagementException, NoSuchAlgorithmException, SvcLogicException { - String user = "testUser"; - String pass = "testPassword"; - String agentUrl = "test/server.com"; + public void testGetModeStore() throws KeyStoreException, CertificateException, IOException, + KeyManagementException, NoSuchAlgorithmException { String store = "src/test/resources/cert"; - builder = new ConnectionBuilder(store, new char['t'] ); - builder.setHttpContext(user, pass); - AnsibleResult result = builder.get(agentUrl); + connectionBuilder = new ConnectionBuilder(store, new char['t'], 2000, "1.1.1.1" ); + connectionBuilder.setHttpContext(USER, PSWD); + AnsibleResult result = connectionBuilder.get(URL); assertEquals(611, result.getStatusCode()); - assertEquals(null, result.getStatusMessage()); + assertNull(result.getStatusMessage()); assertEquals("UNKNOWN", result.getResults()); } diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java index 6fc90d012..3e1929bf5 100644 --- a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleAdapter.java @@ -1,11 +1,9 @@ /*- * ============LICENSE_START======================================================= - * ONAP : APPC + * ONAP : SLI * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. * ================================================================================ - * Copyright (C) 2017 Amdocs - * ============================================================================= * Licensed 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 @@ -21,61 +19,82 @@ * ECOMP is a trademark and service mark of AT&T Intellectual Property. * ============LICENSE_END========================================================= */ -package org.onap.ccsdk.adapter.ansible.model; -import static org.junit.Assert.assertNotNull; +package org.onap.ccsdk.adapter.ansible.model; -import java.util.HashMap; -import java.util.Map; -import java.lang.reflect.*; -import org.junit.After; -import org.junit.Before; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.json.JSONObject; import org.junit.Test; import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleMessageParser; import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleServerEmulator; -public class TestAnsibleAdapter { +import static org.junit.Assert.assertNotNull; - private Class[] parameterTypes; - private AnsibleMessageParser ansibleMessageParser; - private Method m; - private String name; +public class TestAnsibleAdapter { @Test - public void callPrivateConstructorsMethodsForCodeCoverage() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { + public void callPrivateConstructorsMethodsForCodeCoverage() + throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, + InvocationTargetException { - /* test constructors */ - Class<?>[] classesOne = {AnsibleMessageParser.class}; - for(Class<?> clazz : classesOne) { - Constructor<?> constructor = clazz.getDeclaredConstructor(); - name = constructor.getName(); - constructor.setAccessible(true); - assertNotNull(constructor.newInstance()); - } - Class<?>[] classesTwo = {AnsibleServerEmulator.class}; - for(Class<?> clazz : classesTwo) { - Constructor<?> constructor = clazz.getDeclaredConstructor(); - name = constructor.getName(); - constructor.setAccessible(true); - assertNotNull(constructor.newInstance()); - } - Class<?>[] classesThree = {AnsibleResult.class}; - for(Class<?> clazz : classesThree) { - Constructor<?> constructor = clazz.getDeclaredConstructor(); - name = constructor.getName(); - constructor.setAccessible(true); - assertNotNull(constructor.newInstance()); - } + /* test constructors */ + Class<?>[] classesOne = {AnsibleMessageParser.class}; + for (Class<?> clazz : classesOne) { + Constructor<?> constructor = clazz.getDeclaredConstructor(); + constructor.setAccessible(true); + assertNotNull(constructor.newInstance()); + } + Class<?>[] classesTwo = {AnsibleServerEmulator.class}; + for (Class<?> clazz : classesTwo) { + Constructor<?> constructor = clazz.getDeclaredConstructor(); + constructor.setAccessible(true); + assertNotNull(constructor.newInstance()); + } + Class<?>[] classesThree = {AnsibleResult.class}; + for (Class<?> clazz : classesThree) { + Constructor<?> constructor = clazz.getDeclaredConstructor(); + constructor.setAccessible(true); + assertNotNull(constructor.newInstance()); + } - /* test methods */ - ansibleMessageParser = new AnsibleMessageParser(); - parameterTypes = new Class[1]; - parameterTypes[0] = java.lang.String.class; + /* test methods */ + AnsibleMessageParser ansibleMessageParser = new AnsibleMessageParser(); + Class<?>[] parameterTypes = new Class[1]; + parameterTypes[0] = java.lang.String.class; - m = ansibleMessageParser.getClass().getDeclaredMethod("getFilePayload", parameterTypes); - m.setAccessible(true); - assertNotNull(m.invoke(ansibleMessageParser,"{\"test\": test}")); + Method m = ansibleMessageParser.getClass().getDeclaredMethod("getFilePayload", parameterTypes); + m.setAccessible(true); + assertNotNull(m.invoke(ansibleMessageParser, "{\"test\": test}")); + // test logging-suppression for an invalid host value (Fortify Log Forging fix) + String input = "{" + + " \"Results\": {" + + " \"192.168.1.10\": {" + + " \"Id\": \"101\"," + + " \"StatusCode\": 200," + + " \"StatusMessage\": \"SUCCESS\"" + + " }," + + " \"192%168%1%10\": {" + + " \"Id\": \"102\"," + + " \"StatusCode\": 200," + + " \"StatusMessage\": \"SUCCESS\"" + + " }," + + " \"server-dev.att.com\": {" + + " \"Id\": \"103\"," + + " \"StatusCode\": 200," + + " \"StatusMessage\": \"SUCCESS\"" + + " }" + + " }," + + " \"StatusCode\": 200," + + " \"StatusMessage\": \"FINISHED\"" + + "}"; + Method m2 = ansibleMessageParser.getClass().getDeclaredMethod("parseGetResponseNested", AnsibleResult.class, JSONObject.class); + m2.setAccessible(true); + m2.invoke(ansibleMessageParser, new AnsibleResult(), new JSONObject(input)); } + } + diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleMessageParser.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleMessageParser.java new file mode 100644 index 000000000..bcf18e3b2 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleMessageParser.java @@ -0,0 +1,249 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : SLI + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.adapter.ansible.model; + +import java.util.HashMap; +import java.util.Map; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleMessageParser; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class TestAnsibleMessageParser { + private AnsibleMessageParser msgParser; + + @Before + public void setup() { + msgParser = new AnsibleMessageParser(); + } + + @Test + public void testReqMessage() throws Exception { + // String result = "{"\AgentUrl : TestAgentUrl}"; + Map<String, String> params = new HashMap<>(); + params.put("AgentUrl", "TestAgentUrl"); + params.put("PlaybookName", "TestPlaybookName"); + params.put("User", "TestUser"); + params.put("Password", "TestPass"); + + assertEquals("TestAgentUrl", msgParser.reqMessage(params).get("AgentUrl")); + } + + @Test + public void testReqUriResult() throws Exception { + Map<String, String> params = new HashMap<>(); + params.put("AgentUrl", "TestAgentUrl"); + params.put("Id", "TestId"); + params.put("User", "TestUser"); + params.put("Password", "TestPass"); + + assertTrue(msgParser.reqUriResult(params).contains("TestId")); + } + + @Test + public void testReqUriLog() throws Exception { + Map<String, String> params = new HashMap<>(); + params.put("AgentUrl", "TestAgent-Url"); + params.put("Id", "TestId"); + params.put("User", "TestUser"); + params.put("Password", "TestPass"); + + assertTrue(msgParser.reqUriLog(params).contains("TestAgent-Url")); + } + + @Test + public void TestParsePostResponse() throws Exception { + String input = "{\"StatusCode\":\"100\",\"StatusMessage\":\"TestMessage\"}"; + assertEquals("TestMessage", msgParser.parsePostResponse(input).getStatusMessage()); + + } + + @Test(expected = SvcLogicException.class) + public void TestParsePostResponseException() throws Exception { + String input = "{\"StatusCode\":\"600\",\"StatusMessage\":\"TestMessage\"}"; + assertTrue(msgParser.parsePostResponse(input).getStatusMessage().contains("Error parsing response")); + } + + @Test(expected = SvcLogicException.class) + public void TestParsePostResponseException2() throws Exception { + String input = "{\"StatusCode\":\"600\"}"; + assertTrue(msgParser.parsePostResponse(input).getStatusMessage().contains("Error parsing response")); + } + + @Test(expected = SvcLogicException.class) + public void TestParseGetResponseException() throws Exception { + String input = "{\"StatusCode\":\"100\",\"StatusMessage\":\"TestMessage\"}"; + assertTrue(msgParser.parseGetResponse(input).getStatusMessage().contains("Invalid FinalResponse code")); + } + + @Test + public void TestParseGetResponseExec() throws Exception { + String input = "{\"StatusCode\":\"200\",\"StatusMessage\":\"TestMessage\"}"; + assertTrue(msgParser.parseGetResponse(input).getStatusMessage().contains("Results not found in GET for response")); + } + + @Test + public void TestParseGetResponse() throws Exception { + String input = "{" + + " \"StatusCode\": \"200\"," + + " \"StatusMessage\": \"TestMessage\"," + + " \"Results\": {" + + " \"host\": {" + + " \"StatusCode\": \"200\"," + + " \"StatusMessage\": \"SUCCESS\"" + + " }" + + " }," + + " \"Output\": {" + + " \"results-output\": {" + + " \"OutputResult\": \"TestOutPutResult\"" + + " }" + + " }" + + "}"; + assertTrue(msgParser.parseGetResponse(input).getOutput().contains("TestOutPutResult")); + } + + @Test + public void TestParseGetResponseEx() throws Exception { + String input = "{\"StatusCode\":\"200\",\"StatusMessage\":\"TestMessage\",\"Results\":{\"host\":\"TestHost\"}}"; + assertTrue(msgParser.parseGetResponse(input).getStatusMessage().contains("Error processing response message")); + } + + @Test + public void TestParseGetResponseJsonEx() throws Exception { + String input = "{\"StatusCode\":\"200\",\"StatusMessage\":\"TestMessage\",\"Results\":\"host\":\"TestHost\"}"; + assertTrue(msgParser.parseGetResponse(input).getStatusMessage().contains("Error parsing response")); + } + + @Test + public void TestParseGetResponseResultEx() throws Exception { + String input = "{" + + " \"StatusCode\": \"200\"," + + " \"StatusMessage\": \"TestMessage\"," + + " \"Results\": {" + + " \"host\": {" + + " \"StatusCode\": \"100\"," + + " \"StatusMessage\": \"Failure\"" + + " }" + + " }," + + " \"Output\": {" + + " \"results-output\": {" + + " \"OutputResult\": \"TestOutPutResult\"" + + " }" + + " }" + + "}"; + assertTrue(msgParser.parseGetResponse(input).getOutput().contains("TestOutPutResult")); + } + + @Test + public void testParseOptionalParam() throws Exception { + Map<String, String> params = new HashMap<>(); + params.put("AgentUrl", "TestAgentUrl"); + params.put("PlaybookName", "TestPlaybookName"); + params.put("User", "TestUser"); + params.put("Password", "TestPass"); + params.put("Timeout", "3"); + params.put("Version", "1"); + params.put("InventoryNames", "VNFC"); + + JSONObject jObject = msgParser.reqMessage(params); + assertEquals("1", jObject.get("Version")); + assertEquals("VNFC", jObject.get("InventoryNames")); + } + + @Test + public void testParseOptionalParamForEnvParameters() throws Exception { + Map<String, String> params = new HashMap<>(); + params.put("AgentUrl", "TestAgentUrl"); + params.put("PlaybookName", "TestPlaybookName"); + params.put("User", "TestUser"); + params.put("Password", "TestPass"); + params.put("EnvParameters", "{name:value}"); + + JSONObject result = msgParser.reqMessage(params); + assertEquals("TestAgentUrl", result.get("AgentUrl")); + assertEquals("TestPlaybookName", result.get("PlaybookName")); + assertEquals("TestUser", result.get("User")); + assertEquals("TestPass", result.get("Password")); + } + + @Test + public void TestParseGetConfigResponseResult() throws Exception { + String input = "{" + + " \"StatusCode\": \"200\"," + + " \"StatusMessage\": \"TestMessage\"," + + " \"Results\": {" + + " \"host\": {" + + " \"StatusCode\": \"200\"," + + " \"StatusMessage\": \"SUCCESS\"," + + " \"Output\": {" + + " \"info\": {" + + " \"configData\": {" + + " \"abc\": \"TestOutPutResult\"," + + " \"rtr\": \"vfc\"" + + " }" + + " }" + + " }" + + " }" + + " }" + + "}"; + assertTrue(msgParser.parseGetResponse(input).getConfigData().contains("abc")); + } + + @Test + public void testParseOptionalParamTest2() throws Exception { + + Map<String, String> params = new HashMap<>(); + params.put("AgentUrl", "TestAgentUrl"); + params.put("PlaybookName", "TestPlaybookName"); + params.put("User", "TestUser"); + params.put("Password", "TestPass"); + //params.put("Timeout", "3"); + params.put("Version", "1"); + params.put("InventoryNames", "VNFC"); + params.put("Timeout", "4"); + params.put("EnvParameters", "{ \"userID\": \"$0002\", \"vnf-type\" : \"\", \"vnf\" : \"abc\" }"); + params.put("NodeList", "${Nodelist}"); + + JSONObject jObject = msgParser.reqMessage(params); + assertEquals("1", jObject.get("Version")); + assertEquals("4", jObject.get("Timeout")); + } + + @Test + public void testReqUriResultWithIPs() throws Exception { + Map<String, String> params = new HashMap<>(); + params.put("AgentUrl", "http://xx:yy:zz"); + params.put("Id", "TestId"); + params.put("User", "TestUser"); + params.put("Password", "TestPass"); + String serverIp = "10.0.2.3"; + String actual = msgParser.reqUriResultWithIP(params, serverIp); + String expected = "http://10.0.2.3:yy:zz?Id=TestId&Type=GetResult"; + assertEquals(expected, actual); + } + +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleResult.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleResult.java new file mode 100644 index 000000000..301cce135 --- /dev/null +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/adapter/ansible/model/TestAnsibleResult.java @@ -0,0 +1,45 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : SLI + * ================================================================================ + * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.onap.ccsdk.adapter.ansible.model; + +import org.junit.Before; +import org.junit.Test; +import org.onap.ccsdk.sli.adaptors.ansible.model.AnsibleResult; + +import static org.junit.Assert.assertEquals; + +public class TestAnsibleResult { + private AnsibleResult ansibleResult; + + @Before + public void setUp() { + ansibleResult = new AnsibleResult(10, "message", "result", "outputData"); + } + + @Test + public void testServerIp() { + ansibleResult.setServerIp("10.0.9.87"); + assertEquals("10.0.9.87", ansibleResult.getServerIp()); + } + +} |