diff options
author | 2021-03-12 16:32:54 -0500 | |
---|---|---|
committer | 2021-03-15 00:38:17 -0400 | |
commit | 82e92c482efe0ac20353f630cda7cb052d8ff4b5 (patch) | |
tree | 4cf0afcc82834abdf92c6627d2a3ac051ace7df0 /adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java | |
parent | 764b658c8138a9e52798ba70117fc0222893c266 (diff) |
Moving and merging Ansible adaptor from appc to ccsdk/sli
Issue-ID: CCSDK-3198
Signed-off-by: Singal, Kapil (ks220y) <ks220y@att.com>
Change-Id: I5b2c8a3aff7b0e874a659122264be06f412945be
Diffstat (limited to 'adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java')
8 files changed, 854 insertions, 379 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()); + } + +} diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java index 3555d7dfe..b6476d9dc 100644 --- a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/ExecutorHarness.java @@ -1,23 +1,21 @@ /*- * ============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 - * + * * 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========================================================= */ @@ -31,7 +29,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import org.onap.ccsdk.sli.core.sli.SvcLogicContext; import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin; @@ -49,92 +46,79 @@ public class ExecutorHarness { /** * The collection of all exec methods found on the class */ - private Map<String, Method> methods; - - /** - * The field of the class being tested that contains the reference to the logger to be used. This is modified to - * point to our interception logger for the test. - */ - private Field contextLogger; - - /** - * The interception logger that buffers all messages logged and allows us to look at them as part of the test case. - */ - private InterceptLogger logger; + private final Map<String, Method> methods; /** * Create the harness and initialize it - * - * @throws SecurityException - * If a security manager, s, is present and any of the following conditions is met: - * <ul> - * <li>invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field</li> - * <li>the caller's class loader is not the same as or an ancestor of the class loader for the current - * class and invocation of s.checkPackageAccess() denies access to the package of this class</li> - * </ul> - * @throws NoSuchFieldException - * if a field with the specified name is not found. - * @throws IllegalAccessException - * if this Field object is enforcing Java language access control and the underlying field is either - * inaccessible or final. - * @throws IllegalArgumentException - * if the specified object is not an instance of the class or interface declaring the underlying field - * (or a subclass or implementor thereof), or if an unwrapping conversion fails. + * + * @throws SecurityException If a security manager, s, is present and any of the following conditions is met: + * <ul> + * <li>invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field</li> + * <li>the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class</li> + * </ul> + * @throws NoSuchFieldException if a field with the specified name is not found. + * @throws IllegalAccessException if this Field object is enforcing Java language access control and the underlying field is either + * inaccessible or final. + * @throws IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field + * (or a subclass or implementor thereof), or if an unwrapping conversion fails. */ @SuppressWarnings("nls") public ExecutorHarness() throws NoSuchFieldException, SecurityException, IllegalArgumentException, - IllegalAccessException { + IllegalAccessException { methods = new HashMap<>(); new SvcLogicContext(); Class<?> contextClass = SvcLogicContext.class; - contextLogger = contextClass.getDeclaredField("LOG"); + /** + * The field of the class being tested that contains the reference to the logger to be used. This is modified to + * point to our interception logger for the test. + */ + Field contextLogger = contextClass.getDeclaredField("LOG"); contextLogger.setAccessible(true); - logger = new InterceptLogger(); + /** + * The interception logger that buffers all messages logged and allows us to look at them as part of the test case. + */ + InterceptLogger logger = new InterceptLogger(); contextLogger.set(null, logger); } /** * Convenience constructor - * - * @param executor - * The executor to be tested by the harness - * @throws SecurityException - * If a security manager, s, is present and any of the following conditions is met: - * <ul> - * <li>invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field</li> - * <li>the caller's class loader is not the same as or an ancestor of the class loader for the current - * class and invocation of s.checkPackageAccess() denies access to the package of this class</li> - * </ul> - * @throws NoSuchFieldException - * if a field with the specified name is not found. - * @throws IllegalAccessException - * if this Field object is enforcing Java language access control and the underlying field is either - * inaccessible or final. - * @throws IllegalArgumentException - * if the specified object is not an instance of the class or interface declaring the underlying field - * (or a subclass or implementor thereof), or if an unwrapping conversion fails. + * + * @param executor The executor to be tested by the harness + * + * @throws SecurityException If a security manager, s, is present and any of the following conditions is met: + * <ul> + * <li>invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field</li> + * <li>the caller's class loader is not the same as or an ancestor of the class loader for the current + * class and invocation of s.checkPackageAccess() denies access to the package of this class</li> + * </ul> + * @throws NoSuchFieldException if a field with the specified name is not found. + * @throws IllegalAccessException if this Field object is enforcing Java language access control and the underlying field is either + * inaccessible or final. + * @throws IllegalArgumentException if the specified object is not an instance of the class or interface declaring the underlying field + * (or a subclass or implementor thereof), or if an unwrapping conversion fails. */ public ExecutorHarness(SvcLogicJavaPlugin executor) throws NoSuchFieldException, SecurityException, - IllegalArgumentException, IllegalAccessException { + IllegalArgumentException, IllegalAccessException { this(); setExecutor(executor); } /** - * @param executor - * The java plugin class to be executed + * @return The java plugin class to be executed */ - public void setExecutor(SvcLogicJavaPlugin executor) { - this.executor = executor; - scanExecutor(); + public SvcLogicJavaPlugin getExecutor() { + return executor; } /** - * @return The java plugin class to be executed + * @param executor The java plugin class to be executed */ - public SvcLogicJavaPlugin getExecutor() { - return executor; + public void setExecutor(SvcLogicJavaPlugin executor) { + this.executor = executor; + scanExecutor(); } /** @@ -148,11 +132,11 @@ public class ExecutorHarness { /** * Returns an indication if the named method is a valid executor method that could be called from a DG execute node - * - * @param methodName - * The method name to be validated + * + * @param methodName The method name to be validated + * * @return True if the method name meets the signature requirements, false if the method either does not exist or - * does not meet the requirements. + * does not meet the requirements. */ public boolean isExecMethod(String methodName) { return methods.containsKey(methodName); @@ -178,4 +162,5 @@ public class ExecutorHarness { } } } + } diff --git a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java index 92235cb39..3ed32376a 100644 --- a/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java +++ b/adaptors/ansible-adapter/ansible-adapter-bundle/src/test/java/org/onap/ccsdk/test/InterceptLogger.java @@ -1,23 +1,21 @@ /*- * ============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 - * + * * 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========================================================= */ @@ -25,14 +23,12 @@ package org.onap.ccsdk.test; +import ch.qos.logback.classic.Level; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; - import org.slf4j.Marker; -import ch.qos.logback.classic.Level; - /** * This class is used as an intercept logger that can be used in testing to intercept and record all messages that are * logged, thus allowing a junit test case to examine the log output and make assertions. @@ -40,97 +36,15 @@ import ch.qos.logback.classic.Level; public class InterceptLogger implements org.slf4j.Logger { /** - * This inner class represents an intercepted log event - */ - public class LogRecord { - private Level level; - private String message; - private long timestamp; - private Throwable t; - - public LogRecord(Level level, String message) { - setLevel(level); - setTimestamp(System.currentTimeMillis()); - setMessage(message); - } - - public LogRecord(Level level, String message, Throwable t) { - this(level, message); - setThrowable(t); - } - - /** - * @return the value of level - */ - public Level getLevel() { - return level; - } - - /** - * @return the value of message - */ - public String getMessage() { - return message; - } - - /** - * @return the value of timestamp - */ - public long getTimestamp() { - return timestamp; - } - - /** - * @param level - * the value for level - */ - public void setLevel(Level level) { - this.level = level; - } - - /** - * @param message - * the value for message - */ - public void setMessage(String message) { - this.message = message; - } - - /** - * @param timestamp - * the value for timestamp - */ - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } - - /** - * @return the value of t - */ - public Throwable getThrowable() { - return t; - } - - /** - * @param t - * the value for t - */ - public void setThrowable(Throwable t) { - this.t = t; - } - - } - - /** * The list of all intercepted log events */ - private List<LogRecord> events; + private final List<LogRecord> events; /** * Create the intercept logger */ public InterceptLogger() { - events = new ArrayList<LogRecord>(1000); + events = new ArrayList<>(1000); } /** @@ -451,4 +365,83 @@ public class InterceptLogger implements org.slf4j.Logger { public void warn(String msg, Throwable t) { events.add(new LogRecord(Level.WARN, msg, t)); } + + /** + * This inner class represents an intercepted log event + */ + public class LogRecord { + private Level level; + private String message; + private long timestamp; + private Throwable t; + + public LogRecord(Level level, String message) { + setLevel(level); + setTimestamp(System.currentTimeMillis()); + setMessage(message); + } + + public LogRecord(Level level, String message, Throwable t) { + this(level, message); + setThrowable(t); + } + + /** + * @return the value of level + */ + public Level getLevel() { + return level; + } + + /** + * @param level the value for level + */ + public void setLevel(Level level) { + this.level = level; + } + + /** + * @return the value of message + */ + public String getMessage() { + return message; + } + + /** + * @param message the value for message + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * @return the value of timestamp + */ + public long getTimestamp() { + return timestamp; + } + + /** + * @param timestamp the value for timestamp + */ + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + /** + * @return the value of t + */ + public Throwable getThrowable() { + return t; + } + + /** + * @param t the value for t + */ + public void setThrowable(Throwable t) { + this.t = t; + } + + } + } |