Unit test cases for ansible impl package 21/55121/7
authorLathish <lathishbabu.ganesan@ericsson.com>
Wed, 20 Jun 2018 11:24:04 +0000 (12:24 +0100)
committerTakamune Cho <tc012c@att.com>
Wed, 27 Jun 2018 18:15:22 +0000 (18:15 +0000)
Change-Id: I2d035b548f9cfd866ed9966ac6dbf4e496723afc
Issue-ID: APPC-533
Signed-off-by: Lathish <lathishbabu.ganesan@ericsson.com>
appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/onap/appc/adapter/ansible/impl/AnsibleAdapterImpl.java
appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestAnsibleAdapterImpl.java
appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestConnectionBuilder.java [new file with mode: 0644]
appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/asdc-client-cert.crt [new file with mode: 0644]
appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/asdc-client.jks [new file with mode: 0644]
appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/default.properties

index 36d4863..b9cdbc6 100644 (file)
@@ -25,6 +25,7 @@ package org.onap.appc.adapter.ansible.impl;
 
 import java.util.Map;
 import java.util.Properties;
+
 import org.apache.commons.lang.StringUtils;
 import org.json.JSONException;
 import org.json.JSONObject;
@@ -38,9 +39,9 @@ import org.onap.appc.configuration.ConfigurationFactory;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+
 import com.att.eelf.configuration.EELFLogger;
 import com.att.eelf.configuration.EELFManager;
-import org.onap.appc.encryption.EncryptionTool;
 
 /**
  * This class implements the {@link AnsibleAdapter} interface. This interface defines the behaviors
@@ -76,7 +77,6 @@ public class AnsibleAdapterImpl implements AnsibleAdapter {
     private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.result.code";
     private static final String MESSAGE_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.message";
     private static final String RESULTS_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.results";
-    private static final String OUTPUT_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.output";
     private static final String ID_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.Id";
     private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.log";
 
@@ -226,7 +226,7 @@ public class AnsibleAdapterImpl implements AnsibleAdapter {
 
             agentUrl = (String) jsonPayload.remove("AgentUrl");
             user = (String) jsonPayload.remove("User");
-            password = EncryptionTool.getInstance().decrypt((String) jsonPayload.remove(PASSWORD));
+            password = (String) jsonPayload.remove(PASSWORD);
             id = jsonPayload.getString("Id");
             payload = jsonPayload.toString();
             logger.info("Updated Payload  = " + payload);
@@ -317,23 +317,20 @@ public class AnsibleAdapterImpl implements AnsibleAdapter {
         int code = -1;
         String message = StringUtils.EMPTY;
         String results = StringUtils.EMPTY;
-        String output = StringUtils.EMPTY;
 
         try {
             // Try to retrieve the test results (modify the URL for that)
-            AnsibleResult testResult = queryServer(reqUri, params.get("User"),  EncryptionTool.getInstance().decrypt(params.get(PASSWORD)));
+            AnsibleResult testResult = queryServer(reqUri, params.get("User"), params.get(PASSWORD));
             code = testResult.getStatusCode();
             message = testResult.getStatusMessage();
 
-            if (code == 200 || code == 400) {
+            if (code == 200) {
                 logger.info("Parsing response from Server = " + message);
                 // Valid HTTP. process the Ansible message
                 testResult = messageProcessor.parseGetResponse(message);
                 code = testResult.getStatusCode();
                 message = testResult.getStatusMessage();
                 results = testResult.getResults();
-                output = testResult.getOutput();
-
             }
 
             logger.info("Request response = " + message);
@@ -357,10 +354,9 @@ public class AnsibleAdapterImpl implements AnsibleAdapter {
             return;
         }
 
-        ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(400));
+        ctx.setAttribute(RESULT_CODE_ATTRIBUTE_NAME, Integer.toString(code));
         ctx.setAttribute(MESSAGE_ATTRIBUTE_NAME, message);
         ctx.setAttribute(RESULTS_ATTRIBUTE_NAME, results);
-        ctx.setAttribute(OUTPUT_ATTRIBUTE_NAME, output);
         ctx.setStatus(OUTCOME_SUCCESS);
     }
 
@@ -385,7 +381,7 @@ public class AnsibleAdapterImpl implements AnsibleAdapter {
         String message = StringUtils.EMPTY;
         try {
             // Try to retrieve the test results (modify the url for that)
-            AnsibleResult testResult = queryServer(reqUri, params.get("User"), EncryptionTool.getInstance().decrypt(params.get(PASSWORD)));
+            AnsibleResult testResult = queryServer(reqUri, params.get("User"), params.get(PASSWORD));
             message = testResult.getStatusMessage();
             logger.info("Request output = " + message);
             ctx.setAttribute(LOG_ATTRIBUTE_NAME, message);
index 32dd243..7898260 100644 (file)
 package org.onap.appc.adapter.ansible.impl;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.when;
 
 import java.util.HashMap;
 import java.util.Map;
 
+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.appc.adapter.ansible.model.AnsibleMessageParser;
+import org.onap.appc.adapter.ansible.model.AnsibleResult;
+import org.onap.appc.configuration.Configuration;
+import org.onap.appc.configuration.ConfigurationFactory;
+import org.onap.appc.exceptions.APPCException;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
+import org.powermock.reflect.Whitebox;
 
-
+@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 String KEYSTORE_PASSWORD;
+    private static Configuration configuration;
+    private static final String RESULT_CODE_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.result.code";
+    private static final String LOG_ATTRIBUTE_NAME = "org.onap.appc.adapter.ansible.log";
+    private static final String STATUS_CODE = "StatusCode";
+    private static final String STATUS_MESSAGE = "StatusMessage";
+    private static final String PENDING = "100";
+    private static final String SUCCESS = "200";
 
     private AnsibleAdapterImpl adapter;
-    private String TestId;
     private boolean testMode = true;
     private Map<String, String> params;
     private SvcLogicContext svcContext;
+    private JSONObject jsonPayload;
+    private AnsibleResult result;
+    private String agentUrl = "https://192.168.1.1";
+    private AnsibleAdapterImpl spyAdapter;
+
+    @Mock
+    private AnsibleMessageParser messageProcessor;
 
+    @Mock
+    private ConnectionBuilder httpClient;
 
+    /**
+     * Load the configuration properties
+     */
+    @BeforeClass
+    public static void once() {
+        configuration = ConfigurationFactory.getConfiguration();
+        KEYSTORE_PASSWORD = configuration.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", agentUrl);
+        jsonPayload = new JSONObject();
+        jsonPayload.put("Id", "100");
+        jsonPayload.put("User", "test");
+        jsonPayload.put("Password", "test");
+        jsonPayload.put("PlaybookName", "test_playbook.yaml");
+        jsonPayload.put("AgentUrl", agentUrl);
+        result = new AnsibleResult();
+        result.setStatusMessage("Success");
+        result.setResults("Success");
+        Whitebox.setInternalState(adapter, "messageProcessor", messageProcessor);
+        spyAdapter = Mockito.spy(adapter);
     }
 
     @After
@@ -70,60 +120,215 @@ public class TestAnsibleAdapterImpl {
         svcContext = null;
     }
 
+    /**
+     * This test case is used to test the request is submitted and the status is marked to pending
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test
+    public void reqExec_shouldSetPending() throws SvcLogicException, APPCException {
+        result.setStatusCode(Integer.valueOf(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));
+    }
+
+    /**
+     * This test case is used to test the request is process and the status is marked to success
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
     @Test
-    public void reqExec_shouldSetPending() throws IllegalStateException, IllegalArgumentException {
+    public void reqExecResult_shouldSetSuccess() throws SvcLogicException, APPCException {
+        params.put("Id", "100");
+        result.setStatusCode(Integer.valueOf(SUCCESS));
+        when(messageProcessor.reqUriResult(params)).thenReturn(agentUrl);
+        when(messageProcessor.parseGetResponse(anyString())).thenReturn(result);
+        spyAdapter.reqExecResult(params, svcContext);
+        assertEquals(SUCCESS, svcContext.getAttribute(RESULT_CODE_ATTRIBUTE_NAME));
+    }
 
-        params.put("PlaybookName", "test_playbook.yaml");
+    /**
+     * This test case is used to test the Failure of the request
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test(expected = SvcLogicException.class)
+    public void reqExecResult_Failure() throws SvcLogicException, APPCException {
+        params.put("Id", "100");
+        result.setStatusCode(100);
+        result.setStatusMessage("Failed");
+        when(messageProcessor.reqUriResult(params)).thenReturn(agentUrl);
+        when(messageProcessor.parseGetResponse(anyString())).thenReturn(result);
+        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 ");
-        }
+    /**
+     * This test case is used to test the APPC Exception
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test(expected = SvcLogicException.class)
+    public void reqExecResult_appcException() throws APPCException, SvcLogicException {
+        when(messageProcessor.reqUriResult(params)).thenThrow(new APPCException());
+        adapter.reqExecResult(params, svcContext);
     }
 
+    /**
+     * This test case is used to test the Number Format Exception
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test(expected = SvcLogicException.class)
+    public void reqExecResult_numberFormatException()
+            throws IllegalStateException, IllegalArgumentException, APPCException, SvcLogicException {
+        when(messageProcessor.reqUriResult(params)).thenThrow(new NumberFormatException());
+        adapter.reqExecResult(params, svcContext);
+    }
+
+    /**
+     * This test case is used to test the logs executed for the specific request
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
     @Test
-    public void reqExecResult_shouldSetSuccess() throws IllegalStateException, IllegalArgumentException {
+    public void reqExecLog_shouldSetMessage() throws SvcLogicException, APPCException {
+        params.put("Id", "101");
+        when(messageProcessor.reqUriLog(params)).thenReturn(agentUrl);
+        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();
+
+        JSONObject vmResults = new JSONObject();
+        vmResults.put(STATUS_CODE, 200);
+        vmResults.put(STATUS_MESSAGE, "SUCCESS");
+        vmResults.put("Id", "");
+        results.put("192.168.1.10", vmResults);
+
+        response.put("Results", results);
+        String message = response.toString();
+        return message;
+    }
+
+    /**
+     * This test case is used to test the APPC Exception
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test(expected = SvcLogicException.class)
+    public void reqExecException()
+            throws IllegalStateException, IllegalArgumentException, APPCException, SvcLogicException {
+        when(messageProcessor.reqUriLog(params)).thenThrow(new APPCException("Appc Exception"));
+        adapter.reqExecLog(params, svcContext);
+    }
+
+    /**
+     * This test case is used to test the APPC Exception
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test(expected = SvcLogicException.class)
+    public void reqExec_AppcException()
+            throws IllegalStateException, IllegalArgumentException, SvcLogicException, APPCException {
+        when(messageProcessor.reqMessage(params)).thenThrow(new APPCException());
+        adapter.reqExec(params, svcContext);
+    }
+
+    /**
+     * This test case is used to test the JSON Exception
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test(expected = SvcLogicException.class)
+    public void reqExec_JsonException()
+            throws IllegalStateException, IllegalArgumentException, SvcLogicException, APPCException {
+        when(messageProcessor.reqMessage(params)).thenThrow(new JSONException("Json Exception"));
+        adapter.reqExec(params, svcContext);
+    }
 
-        for (String ukey : params.keySet()) {
-            System.out.println(String.format("Ansible Parameter %s = %s", ukey, params.get(ukey)));
-        }
+    /**
+     * This test case is used to test the Number Format Exception
+     *
+     * @throws SvcLogicException If the request cannot be process due to Number format or JSON
+     *         Exception
+     * @throws APPCException If the request cannot be processed for some reason
+     */
+    @Test(expected = SvcLogicException.class)
+    public void reqExec_NumberFormatException()
+            throws IllegalStateException, IllegalArgumentException, SvcLogicException, APPCException {
+        when(messageProcessor.reqMessage(params)).thenThrow(new NumberFormatException("Numbre Format Exception"));
+        adapter.reqExec(params, svcContext);
+    }
 
-        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 ");
-        }
+    /**
+     * This test case is used to test the constructor with no client type
+     *
+     */
+    @Test
+    public void testInitializeWithDefault() {
+        configuration.setProperty("org.onap.appc.adapter.ansible.clientType", "");
+        adapter = new AnsibleAdapterImpl();
+        assertNotNull(adapter);
     }
 
+    /**
+     * This test case is used to test the constructor with client type as TRUST_ALL
+     *
+     */
     @Test
-    public void reqExecLog_shouldSetMessage() throws IllegalStateException, IllegalArgumentException {
+    public void testInitializeWithTrustAll() {
+        configuration.setProperty("org.onap.appc.adapter.ansible.clientType", "TRUST_ALL");
+        adapter = new AnsibleAdapterImpl();
+        assertNotNull(adapter);
+    }
 
-        params.put("Id", "101");
+    /**
+     * This test case is used to test the constructor with client type as TRUST_CERT
+     *
+     */
+    @Test
+    public void testInitializeWithTrustCert() {
+        configuration.setProperty("org.onap.appc.adapter.ansible.clientType", "TRUST_CERT");
+        configuration.setProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd", KEYSTORE_PASSWORD);
+        adapter = new AnsibleAdapterImpl();
+        assertNotNull(adapter);
+    }
 
-        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 ");
-        }
+    /**
+     * This test case is used to test the constructor with exception
+     *
+     */
+    @Test
+    public void testInitializeWithException() {
+        configuration.setProperty("org.onap.appc.adapter.ansible.clientType", "TRUST_CERT");
+        configuration.setProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd", "appc");
+        adapter = new AnsibleAdapterImpl();
     }
+
 }
diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestConnectionBuilder.java b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/java/org/onap/appc/adapter/ansible/impl/TestConnectionBuilder.java
new file mode 100644 (file)
index 0000000..d2c0f84
--- /dev/null
@@ -0,0 +1,258 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2018 Ericsson. 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.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.appc.adapter.ansible.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+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 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.ClientProtocolException;
+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.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.appc.adapter.ansible.model.AnsibleMessageParser;
+import org.onap.appc.adapter.ansible.model.AnsibleResult;
+import org.onap.appc.adapter.ansible.model.AnsibleResultCodes;
+import org.onap.appc.configuration.Configuration;
+import org.onap.appc.configuration.ConfigurationFactory;
+import org.onap.appc.exceptions.APPCException;
+import org.powermock.reflect.Whitebox;
+
+@RunWith(MockitoJUnitRunner.class)
+public class TestConnectionBuilder {
+
+    private static String KEYSTORE_FILE;
+    private static String KEYSTORE_PASSWORD;
+    private static String KEYSTORE_CERTIFICATE;
+    private static String USERNAME;
+    private static String PASSWORD;
+    private static String URL;
+
+    private final int SUCCESS_STATUS = 200;
+    private ConnectionBuilder connectionBuilder;
+
+    @Mock
+    private AnsibleMessageParser messageProcessor;
+
+    @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() {
+        Configuration configuration = ConfigurationFactory.getConfiguration();
+        Properties props = configuration.getProperties();
+        KEYSTORE_FILE = props.getProperty("org.onap.appc.adapter.ansible.trustStore");
+        KEYSTORE_PASSWORD = props.getProperty("org.onap.appc.adapter.ansible.trustStore.trustPasswd");
+        KEYSTORE_CERTIFICATE = props.getProperty("org.onap.appc.adapter.ansible.cert");
+        USERNAME = props.getProperty("org.onap.appc.adapter.ansible.username");
+        PASSWORD = props.getProperty("org.onap.appc.adapter.ansible.password");
+        URL = props.getProperty("org.onap.appc.adapter.ansible.identity");
+    }
+
+    /**
+     * Use reflection to locate fields and methods so that they can be manipulated during the test
+     * to change the internal state accordingly.
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws ClientProtocolException The client protocol exception
+     * @throws IOException Signals that an I/O exception has occurred.
+     */
+    @Before
+    public void setup() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
+            ClientProtocolException, IOException {
+        connectionBuilder = new ConnectionBuilder(0);
+        Whitebox.setInternalState(connectionBuilder, "httpClient", httpClient);
+        Whitebox.setInternalState(connectionBuilder, "httpContext", httpClientContext);
+        HttpResponse 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;
+    }
+
+    /**
+     * This test case is used to invoke the constructor with keystore file and trust store password.
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws CertificateException If the certificate is tampared
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws IOException Signals that an I/O exception has occurred.
+     * @throws APPCException If there are any application exception
+     */
+    @Test
+    public void testConnectionBuilder() throws KeyManagementException, KeyStoreException, CertificateException,
+            NoSuchAlgorithmException, IOException, APPCException {
+        char[] trustStorePassword = KEYSTORE_PASSWORD.toCharArray();
+        ConnectionBuilder connectionBuilder = new ConnectionBuilder(KEYSTORE_FILE, trustStorePassword);
+        assertNotNull(connectionBuilder);
+    }
+
+    /**
+     * This test case is used to invoke the constructor with keystore certificate
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws CertificateException If the certificate is tampared
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws IOException Signals that an I/O exception has occurred.
+     * @throws APPCException If there are any application exception
+     */
+    @Test
+    public void testConnectionBuilderWithFilePath() throws KeyManagementException, KeyStoreException,
+            CertificateException, NoSuchAlgorithmException, IOException, APPCException {
+        new ConnectionBuilder(KEYSTORE_CERTIFICATE);
+    }
+
+    /**
+     * This test case is used to set the http context with username and password
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws CertificateException If the certificate is tampared
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws IOException Signals that an I/O exception has occurred.
+     * @throws APPCException If there are any application exception
+     */
+    @Test
+    public void testSetHttpContext() throws KeyManagementException, KeyStoreException, CertificateException,
+            NoSuchAlgorithmException, IOException, APPCException {
+        ConnectionBuilder spyConnectionBuilder = Mockito.spy(connectionBuilder);
+        spyConnectionBuilder.setHttpContext(USERNAME, PASSWORD);
+        verify(spyConnectionBuilder, times(1)).setHttpContext(USERNAME, PASSWORD);
+    }
+
+    /**
+     * This test case is used to test the post method
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws CertificateException If the certificate is tampared
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws IOException Signals that an I/O exception has occurred.
+     * @throws APPCException If there are any application exception
+     */
+    @Test
+    public void testPost() throws KeyManagementException, KeyStoreException, CertificateException,
+            NoSuchAlgorithmException, IOException, APPCException {
+        when(httpClient.execute(anyObject(), eq(httpClientContext))).thenReturn(response);
+        AnsibleResult result = connectionBuilder.post(URL, "appc");
+        assertEquals(SUCCESS_STATUS, result.getStatusCode());
+    }
+
+    /**
+     * This test case is used to test the post method with exception
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws CertificateException If the certificate is tampared
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws IOException Signals that an I/O exception has occurred.
+     * @throws APPCException If there are any application exception
+     */
+    @Test
+    public void testPostWithException() throws KeyManagementException, KeyStoreException, CertificateException,
+            NoSuchAlgorithmException, IOException, APPCException {
+        when(httpClient.execute(anyObject(), eq(httpClientContext))).thenThrow(new IOException());
+        AnsibleResult result = connectionBuilder.post(URL, "appc");
+        assertEquals(AnsibleResultCodes.IO_EXCEPTION.getValue(), result.getStatusCode());
+    }
+
+    /**
+     * This test case is used to test the get method
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws CertificateException If the certificate is tampared
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws IOException Signals that an I/O exception has occurred.
+     * @throws APPCException If there are any application exception
+     */
+    @Test
+    public void testGet() throws KeyManagementException, KeyStoreException, CertificateException,
+            NoSuchAlgorithmException, IOException, APPCException {
+        when(httpClient.execute(anyObject(), eq(httpClientContext))).thenReturn(response);
+        AnsibleResult result = connectionBuilder.get(URL);
+        assertEquals(SUCCESS_STATUS, result.getStatusCode());
+    }
+
+    /**
+     * This test case is used to test the get method with exception
+     *
+     * @throws KeyManagementException If unable to manage the key
+     * @throws KeyStoreException If any issues accessing the keystore
+     * @throws CertificateException If the certificate is tampared
+     * @throws NoSuchAlgorithmException If an algorithm is found to be used but is unknown
+     * @throws IOException Signals that an I/O exception has occurred.
+     * @throws APPCException If there are any application exception
+     */
+    @Test
+    public void testGetWithException() throws KeyManagementException, KeyStoreException, CertificateException,
+            NoSuchAlgorithmException, IOException, APPCException {
+        when(httpClient.execute(anyObject(), eq(httpClientContext))).thenThrow(new IOException());
+        AnsibleResult result = connectionBuilder.get(URL);
+        assertEquals(AnsibleResultCodes.IO_EXCEPTION.getValue(), result.getStatusCode());
+    }
+
+}
diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/asdc-client-cert.crt b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/asdc-client-cert.crt
new file mode 100644 (file)
index 0000000..9709d77
--- /dev/null
@@ -0,0 +1,10 @@
+-----BEGIN CERTIFICATE-----
+MIIBezCCASWgAwIBAgIQyWD8dLUoqpJFyDxrfRlrsTANBgkqhkiG9w0BAQQFADAW
+MRQwEgYDVQQDEwtSb290IEFnZW5jeTAeFw0wMTEwMTkxMjU5MjZaFw0zOTEyMzEy
+MzU5NTlaMBoxGDAWBgNVBAMTD1Jvb3RDZXJ0aWZpY2F0ZTBcMA0GCSqGSIb3DQEB
+AQUAA0sAMEgCQQC+NFKszPjatUZKWmyWaFjir1wB93FX2u5SL+GMjgUsMs1JcTKQ
+Kh0cnnQKknNkV4cTW4NPn31YCoB1+0KA3mknAgMBAAGjSzBJMEcGA1UdAQRAMD6A
+EBLkCS0GHR1PAI1hIdwWZGOhGDAWMRQwEgYDVQQDEwtSb290IEFnZW5jeYIQBjds
+AKoAZIoRz7jUqlw19DANBgkqhkiG9w0BAQQFAANBACJxAfP57yqaT9N+nRgAOugM
+JG0aN3/peCIvL3p29epRL2xoWFvxpUUlsH2I39OZ6b8+twWCebhkv1I62segXAk=
+-----END CERTIFICATE-----
\ No newline at end of file
diff --git a/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/asdc-client.jks b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/asdc-client.jks
new file mode 100644 (file)
index 0000000..eb0a0d3
Binary files /dev/null and b/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/test/resources/org/onap/appc/asdc-client.jks differ
index 7efa903..6f877e9 100644 (file)
@@ -2,22 +2,25 @@
 # ============LICENSE_START=======================================================
 # ONAP : APPC
 # ================================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 # ================================================================================
 # Copyright (C) 2017 Amdocs
+# ================================================================================
+# Copyright (C) 2018 Ericsson
 # =============================================================================
 # 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=========================================================
 ###
 
 #
 # -------------------------------------------------------------------------------------------------
 #
-# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded 
-# to supply configuration options 
+# Define the name and path of any user-provided configuration (bootstrap) file that can be loaded
+# to supply configuration options
 org.onap.appc.bootstrap.file=appc.properties
 org.onap.appc.bootstrap.path=/opt/onap/appc/data/properties,${user.home},.
 
 appc.application.name=APPC
 
-#
-# Define the message resource bundle name to be loaded 
+#Define ansible property
+org.onap.appc.adapter.ansible.clientType=appc
+org.onap.appc.adapter.ansible.trustStore=src/test/resources/org/onap/appc/asdc-client.jks
+org.onap.appc.adapter.ansible.trustStore.trustPasswd=Aa123456
+org.onap.appc.adapter.ansible.cert=src/test/resources/org/onap/appc/asdc-client-cert.crt
+org.onap.appc.adapter.ansible.identity=http://localhost:9081/v2.0
+org.onap.appc.adapter.ansible.username=appc
+org.onap.appc.adapter.ansible.password=appc
+#
+# Define the message resource bundle name to be loaded
 org.onap.appc.resources=org/onap/appc/i18n/MessageResources
 #
 # The name of the adapter.