ChefAdapterImpl Junits 47/35447/1
authorMichal Kabaj <michal.kabaj@nokia.com>
Tue, 13 Mar 2018 11:18:08 +0000 (12:18 +0100)
committerMichal Kabaj <michal.kabaj@nokia.com>
Tue, 13 Mar 2018 11:18:08 +0000 (12:18 +0100)
-Added new Unit tests for ChefAdapterImpl#trigger method
-Refactored ChefAdapterFactory to allow mock injection
-Added new create() method to ChefApiClientFactory which does not set
any Chef specific headers for the purpose of trigger method
-Cleaned up the trigger method - simplified usage, removed useless doFailure
method and inlined its logic and unified HttClient usage -> HttpClient is not
used directly but through existing ChefApiClient
-removed redundant TestChefAdapterImpl tests which have already been rewritten

Change-Id: I830d203877224aa2c5e1b0dff39d1171f1f2f0ef
Issue-ID: APPC-437
Signed-off-by: Michal Kabaj <michal.kabaj@nokia.com>
appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/chefclient/ChefApiClientFactory.java
appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/ChefAdapterFactory.java
appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/main/java/org/onap/appc/adapter/chef/impl/ChefAdapterImpl.java
appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/ChefAdapterImplTest.java
appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/TestChefAdapterImpl.java [deleted file]

index 1815266..11d820d 100644 (file)
@@ -19,6 +19,7 @@
  */
 package org.onap.appc.adapter.chef.chefclient;
 
+import com.google.common.collect.ImmutableMap;
 import org.apache.http.client.HttpClient;
 import org.apache.http.impl.client.HttpClients;
 import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
@@ -37,4 +38,11 @@ public class ChefApiClientFactory {
             (methodName, requestPath, body) -> chefApiHeaderFactory
                 .create(methodName, requestPath, body, userId, organizations, pemPath));
     }
+
+    public ChefApiClient create(String endPoint) {
+        return new ChefApiClientImpl(
+            httpClient,
+            endPoint,
+            (methodName, requestPath, body) -> ImmutableMap.of());
+    }
 }
index 60c06ba..ad45577 100644 (file)
@@ -24,7 +24,10 @@ import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
 
 public class ChefAdapterFactory {
 
+    private ChefApiClientFactory chefApiClientFactory = new ChefApiClientFactory();
+    private PrivateKeyChecker privateKeyChecker = new PrivateKeyChecker();
+
     public ChefAdapter create() {
-        return new ChefAdapterImpl(new ChefApiClientFactory(), new PrivateKeyChecker());
+        return new ChefAdapterImpl(chefApiClientFactory, privateKeyChecker);
     }
 }
index 0f4b8c8..9853bcf 100644 (file)
  */
 package org.onap.appc.adapter.chef.impl;
 
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import org.apache.commons.lang.StringUtils;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.util.EntityUtils;
 import org.json.JSONException;
 import org.json.JSONObject;
 import org.onap.appc.adapter.chef.ChefAdapter;
-import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
 import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
+import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
 import org.onap.appc.adapter.chef.chefclient.api.ChefResponse;
 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;
 
 /**
  * This class implements the {@link ChefAdapter} interface. This interface defines the behaviors that our service
@@ -545,23 +539,20 @@ public class ChefAdapterImpl implements ChefAdapter {
      * Trigger target vm run chef
      */
     @Override
-    public void trigger(Map<String, String> params, SvcLogicContext ctx) {
+    public void trigger(Map<String, String> params, SvcLogicContext svcLogicContext) {
         logger.info("Run trigger method");
         String tVmIp = params.get("ip");
-        RequestContext rc = new RequestContext(ctx);
+        RequestContext rc = new RequestContext(svcLogicContext);
         rc.isAlive();
 
-        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
-            HttpGet httpGet = new HttpGet(tVmIp);
-            HttpResponse response = httpClient.execute(httpGet);
-            int responseCode = response.getStatusLine().getStatusCode();
-            HttpEntity entity = response.getEntity();
-            String responseOutput = EntityUtils.toString(entity);
-            chefClientResult(rc, responseCode, responseOutput);
-            doSuccess(rc);
+        try {
+            ChefResponse chefResponse = chefApiClientFactory.create(tVmIp).get("");
+            chefClientResult(rc, chefResponse.getStatusCode(), chefResponse.getBody());
+            svcLogicContext.setAttribute("chefAgent.code", "200");
         } catch (Exception e) {
             logger.error("An error occurred when executing trigger method", e);
-            doFailure(rc, 500, e.toString());
+            svcLogicContext.setAttribute("chefAgent.code", "500");
+            svcLogicContext.setAttribute("chefAgent.message", e.toString());
         }
     }
 
@@ -663,34 +654,6 @@ public class ChefAdapterImpl implements ChefAdapter {
         }
     }
 
-    @SuppressWarnings("static-method")
-    private void doFailure(RequestContext rc, int code, String message) {
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
-        String msg = (message == null) ? Integer.toString(code) : message;
-        if (msg.contains("\n")) {
-            msg = msg.substring(msg.indexOf('\n'));
-        }
-
-        String status;
-        try {
-            status = Integer.toString(code);
-        } catch (Exception e) {
-            status = "500";
-            logger.error("Parsing status code failed. Setting it to \"500\"", e);
-        }
-        svcLogic.setAttribute("chefAgent.code", status);
-        svcLogic.setAttribute("chefAgent.message", msg);
-    }
-
-    /**
-     * @param rc The request context that manages the state and recovery of the request for the life of its processing.
-     */
-    @SuppressWarnings("static-method")
-    private void doSuccess(RequestContext rc) {
-        SvcLogicContext svcLogic = rc.getSvcLogicContext();
-        svcLogic.setAttribute("chefAgent.code", "200");
-    }
-
     @SuppressWarnings("static-method")
     private void chefServerResult(RequestContext rc, int code, String message) {
         initSvcLogic(rc, code, message, "server");
index 7b35467..9289330 100644 (file)
@@ -21,19 +21,43 @@ package org.onap.appc.adapter.chef.impl;
 
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Answers.RETURNS_DEEP_STUBS;
+import static org.mockito.BDDMockito.given;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import java.util.Collections;
 import java.util.Map;
+import org.apache.http.HttpStatus;
 import org.json.JSONObject;
 import org.junit.Test;
-import org.onap.appc.adapter.chef.ChefAdapter;
+import org.junit.runner.RunWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
+import org.onap.appc.adapter.chef.chefclient.api.ChefResponse;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 
+@RunWith(MockitoJUnitRunner.class)
 public class ChefAdapterImplTest {
 
     private static final String EXPECTED_NODE_OBJECT_ATTR_NAME = "chef.nodeObject";
+    private static final String RESULT_CODE_ATTR_KEY = "chefClientResult.code";
+    private static final String RESULT_MESSAGE_ATTR_KEY = "chefClientResult.message";
+    private static final String EXPECTED_RESPONSE_MSG = "chefResponseMessage";
+    private static final String IP_PARAM = "ip";
+    private static final String ENDPOINT_IP = "http://127.0.0.1";
+    private static final String CHEF_AGENT_CODE_KEY = "chefAgent.code";
+    private static final String CHEF_AGENT_MESSAGE_KEY = "chefAgent.message";
+
+    @Mock(answer = RETURNS_DEEP_STUBS)
+    private ChefApiClientFactory chefApiClientFactory;
+    @Mock
+    private PrivateKeyChecker privateKeyChecker;
+
+    @InjectMocks
+    private ChefAdapterFactory chefAdapterFactory;
 
     @Test
     public void nodeObjectBuilder_shouldBuildJsonNodeObject_forPassedParams_andAddToSvcLogicContext() {
@@ -42,8 +66,7 @@ public class ChefAdapterImplTest {
         SvcLogicContext svcLogicContext = new SvcLogicContext();
 
         // WHEN
-        ChefAdapter chefAdapter = new ChefAdapterFactory().create();
-        chefAdapter.nodeObejctBuilder(params, svcLogicContext);
+        chefAdapterFactory.create().nodeObejctBuilder(params, svcLogicContext);
 
         // THEN
         assertThat(resultJson(svcLogicContext)).isEqualTo(expectedJson());
@@ -87,10 +110,43 @@ public class ChefAdapterImplTest {
         SvcLogicContext svcLogicContext = new SvcLogicContext();
 
         // WHEN
-        ChefAdapter chefAdapter = new ChefAdapterFactory().create();
-        chefAdapter.combineStrings(params, svcLogicContext);
+        chefAdapterFactory.create().combineStrings(params, svcLogicContext);
 
         // THEN
         assertThat(svcLogicContext.getAttribute("contextValue")).isEqualTo("paramString1paramString2");
     }
-}
\ No newline at end of file
+
+    @Test
+    public void trigger_shouldTriggerTargetEndpoint_andUpdateSvclogicContext() {
+        // GIVEN
+        Map<String, String> params = ImmutableMap.of(IP_PARAM, ENDPOINT_IP);
+        SvcLogicContext svcLogicContext = new SvcLogicContext();
+        given(chefApiClientFactory.create(ENDPOINT_IP).get(""))
+            .willReturn(ChefResponse.create(HttpStatus.SC_OK, EXPECTED_RESPONSE_MSG));
+
+        // WHEN
+        chefAdapterFactory.create().trigger(params, svcLogicContext);
+
+        // THEN
+        assertThat(svcLogicContext.getAttribute(CHEF_AGENT_CODE_KEY)).isEqualTo(Integer.toString(HttpStatus.SC_OK));
+        assertThat(svcLogicContext.getStatus()).isEqualTo("success");
+        assertThat(svcLogicContext.getAttribute(RESULT_CODE_ATTR_KEY)).isEqualTo(Integer.toString(HttpStatus.SC_OK));
+        assertThat(svcLogicContext.getAttribute(RESULT_MESSAGE_ATTR_KEY)).isEqualTo(EXPECTED_RESPONSE_MSG);
+    }
+
+    @Test
+    public void trigger_shouldUpdateSvcLogicContext_withFailStatusAndMsg_whenExceptionOccurs() {
+        // GIVEN
+        Map<String, String> params = ImmutableMap.of(IP_PARAM, ENDPOINT_IP);
+        SvcLogicContext svcLogicContext = new SvcLogicContext();
+        given(chefApiClientFactory.create(ENDPOINT_IP)).willThrow(new RuntimeException());
+
+        // WHEN
+        chefAdapterFactory.create().trigger(params, svcLogicContext);
+
+        // THEN
+        assertThat(svcLogicContext.getAttribute(CHEF_AGENT_CODE_KEY))
+            .isEqualTo(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR));
+        assertThat(svcLogicContext.getAttribute(CHEF_AGENT_MESSAGE_KEY)).isEqualTo(new RuntimeException().toString());
+    }
+}
diff --git a/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/TestChefAdapterImpl.java b/appc-adapters/appc-chef-adapter/appc-chef-adapter-bundle/src/test/java/org/onap/appc/adapter/chef/impl/TestChefAdapterImpl.java
deleted file mode 100644 (file)
index e7d7e77..0000000
+++ /dev/null
@@ -1,115 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * ONAP : APPC
- * ================================================================================
- * Copyright (C) 2017 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=========================================================
- */
-
-package org.onap.appc.adapter.chef.impl;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.appc.adapter.chef.ChefAdapter;
-import org.onap.appc.exceptions.APPCException;
-import com.att.cdp.exceptions.ZoneException;
-import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import org.onap.ccsdk.sli.core.sli.SvcLogicException;
-
-public class TestChefAdapterImpl {
-    private SvcLogicContext svcContext;
-
-    private ChefAdapter adapter;
-
-    private Map<String, String> params;
-    private String getAttribute;
-
-    @Before
-    public void setup() {
-        adapter = new ChefAdapterFactory().create();
-        params = new HashMap<>();
-        params.put("pemPath",
-                "/src/test/resources/testclient.pem");
-    }
-
-    @After
-    public void tearDown() {
-        params = null;
-        svcContext = null;
-        getAttribute = null;
-    }
-    
-        @Test(expected=Exception.class)
-    public void testChefGetFail() throws IOException, IllegalStateException, IllegalArgumentException,
-            ZoneException, APPCException,SvcLogicException {
-        params.put("chefAction", "/nodes");
-
-        givenParams(params, "chefGet");
-        thenResponseShouldFail();
-    }
-
-      @Test(expected=Exception.class)
-    public void testChefPutFail() throws IOException, IllegalStateException, IllegalArgumentException,
-            ZoneException, APPCException,SvcLogicException {
-        params.put("chefAction", "/nodes/testnode");
-        params.put("runList", "recipe[commandtest]");
-        params.put("attributes", "");
-        params.put("chefRequestBody", "Test Body");
-
-        givenParams(params, "chefPut");
-        thenResponseShouldFail();
-    }
-
-    @Test
-    public void testTriggerFail() throws IOException, IllegalStateException, IllegalArgumentException,
-            ZoneException, APPCException,SvcLogicException {
-        params.put("ip", "");
-
-        givenParams(params, "trigger");
-        thenResponseShouldFail();
-    }
-
-    private void givenParams(Map<String, String> adapterParams, String method) throws SvcLogicException {
-        svcContext = new SvcLogicContext();
-        if (method == "chefGet"){
-            adapter.chefGet(adapterParams, svcContext);
-            getAttribute = "chefServerResult.code";
-        }
-        if (method == "chefPut"){
-            adapter.chefPut(adapterParams, svcContext);
-            getAttribute = "chefServerResult.code";
-        }
-        if (method == "trigger"){
-            adapter.trigger(adapterParams, svcContext);
-            getAttribute = "chefAgent.code";
-        }
-    }
-
-    private void thenResponseShouldFail(){
-        String status = svcContext.getAttribute(this.getAttribute);
-        assertEquals("500", status);
-    }
-}