Unit test cases for iaas impl package 77/49477/9
authorLathishbabu Ganesan <lathishbabu.ganesan@ericsson.com>
Mon, 28 May 2018 10:07:44 +0000 (11:07 +0100)
committerLathishbabu Ganesan <lathishbabu.ganesan@ericsson.com>
Mon, 18 Jun 2018 11:05:02 +0000 (11:05 +0000)
Change-Id: Iac6167dca83413b7533cb65a73775a616866589c
Issue-ID: APPC-436
Signed-off-by: Lathishbabu Ganesan <lathishbabu.ganesan@ericsson.com>
17 files changed:
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/CommonUtility.java [new file with mode: 0644]
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/RequestFailedExceptionTest.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderCache.java [new file with mode: 0644]
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestTenantCache.java [new file with mode: 0644]
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java
appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties

index 79d7aa5..36191dd 100644 (file)
@@ -68,7 +68,7 @@ public class ProviderAdapterImpl implements ProviderAdapter {
     /**
      * reference to operation factory
      */
-    ProviderOperationFactory factory = ProviderOperationFactory.getInstance();
+    private ProviderOperationFactory factory;
     /**
      * A cache of providers that are predefined.
      */
@@ -257,6 +257,7 @@ public class ProviderAdapterImpl implements ProviderAdapter {
          * provider2.identity=http://provider2:5000/v2.0 provider2.tenant1.name=someName
          * provider2.tenant1.userid=someUser provider2.tenant1.password=somePassword </pre> </p>
          */
+        factory = ProviderOperationFactory.getInstance();
         providerCache = new HashMap<>();
         Properties properties = configuration.getProperties();
         List<Node> providers = StructuredPropertyHelper.getStructuredProperties(properties, Property.PROVIDER);
index a4be233..74d8757 100644 (file)
@@ -51,18 +51,12 @@ public class ServiceCatalogFactory {
                return null;\r
        }\r
         String version = idUrl.getVersion();\r
-        if(version == null){\r
-               logger.error("Invalid Identity URL check configuration");\r
-               return null;\r
-        }\r
         String prefix = version.split("\\.")[0];\r
-        if (prefix != null) {\r
-            switch (prefix) {\r
-                case "v2":\r
-                    return new ServiceCatalogV2(url, projectIdentifier, principal, credential, properties);\r
-                case "v3":\r
-                    return new ServiceCatalogV3(url, projectIdentifier, principal, credential, domain, properties);\r
-            }\r
+        if("v2".equals(prefix)){\r
+               return new ServiceCatalogV2(url, projectIdentifier, principal, credential, properties);\r
+        }\r
+        else if("v3".equals(prefix)){\r
+               return new ServiceCatalogV3(url, projectIdentifier, principal, credential, domain, properties);\r
         }\r
         return null;\r
     }\r
index 1e057d1..4773603 100644 (file)
 \r
 package org.onap.appc.adapter.iaas.impl;\r
 \r
+import java.util.ArrayList;\r
+import java.util.Calendar;\r
+import java.util.Date;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Properties;\r
+import java.util.Set;\r
+import java.util.concurrent.locks.Lock;\r
+import java.util.concurrent.locks.ReentrantReadWriteLock;\r
+import java.util.regex.Matcher;\r
+import java.util.regex.Pattern;\r
 import com.att.cdp.exceptions.ContextConnectionException;\r
 import com.att.cdp.exceptions.ZoneException;\r
 import com.att.cdp.openstack.util.ExceptionMapper;\r
 import com.att.cdp.pal.util.Time;\r
 import com.att.cdp.zones.ContextFactory;\r
 import com.att.cdp.zones.spi.RequestState;\r
-import com.google.common.collect.Lists;\r
 import com.woorea.openstack.base.client.OpenStackBaseException;\r
 import com.woorea.openstack.base.client.OpenStackClientConnector;\r
 import com.woorea.openstack.base.client.OpenStackSimpleTokenProvider;\r
@@ -42,19 +54,6 @@ import com.woorea.openstack.keystone.v3.model.Token;
 import com.woorea.openstack.keystone.v3.model.Token.Project;\r
 import com.woorea.openstack.keystone.v3.model.Token.Service;\r
 import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint;\r
-import java.util.ArrayList;\r
-import java.util.Calendar;\r
-import java.util.Date;\r
-import java.util.HashMap;\r
-import java.util.HashSet;\r
-import java.util.List;\r
-import java.util.Map;\r
-import java.util.Properties;\r
-import java.util.Set;\r
-import java.util.concurrent.locks.Lock;\r
-import java.util.concurrent.locks.ReentrantReadWriteLock;\r
-import java.util.regex.Matcher;\r
-import java.util.regex.Pattern;\r
 \r
 /**\r
  * This class is used to capture and cache the service catalog for a specific OpenStack provider.\r
@@ -225,13 +224,7 @@ public class ServiceCatalogV3 extends ServiceCatalog {
      */\r
     @Override\r
     public String getProjectName() {\r
-        Lock readLock = rwLock.readLock();\r
-        readLock.lock();\r
-        try {\r
-            return project.getName();\r
-        } finally {\r
-            readLock.unlock();\r
-        }\r
+        return getProject().getName();\r
     }\r
 \r
     /**\r
@@ -403,4 +396,14 @@ public class ServiceCatalogV3 extends ServiceCatalog {
         }\r
         return now.getTime();\r
     }\r
+    \r
+    public Project getProject() {\r
+        Lock readLock = rwLock.readLock();\r
+        readLock.lock();\r
+        try {\r
+            return project;\r
+        } finally {\r
+            readLock.unlock();\r
+        }\r
+    }\r
 }
\ No newline at end of file
index c99889c..29b9cd3 100644 (file)
 
 package org.onap.appc.adapter.iaas.impl;
 
-import com.att.cdp.exceptions.ContextConnectionException;
-import com.att.cdp.exceptions.ZoneException;
-import com.att.cdp.zones.Context;
-import com.att.cdp.zones.ContextFactory;
-import com.att.cdp.zones.Provider;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
 import java.io.IOException;
 import java.util.HashMap;
 import java.util.Map;
@@ -42,6 +35,13 @@ import org.onap.appc.pool.Allocator;
 import org.onap.appc.pool.Destructor;
 import org.onap.appc.pool.Pool;
 import org.onap.appc.pool.PoolSpecificationException;
+import com.att.cdp.exceptions.ContextConnectionException;
+import com.att.cdp.exceptions.ZoneException;
+import com.att.cdp.zones.Context;
+import com.att.cdp.zones.ContextFactory;
+import com.att.cdp.zones.Provider;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
 
 /**
  * This class maintains a cache of tenants within a specific provider.
@@ -121,7 +121,6 @@ public class TenantCache implements Allocator<Context>, Destructor<Context> {
         configuration = ConfigurationFactory.getConfiguration();
         logger = EELFManager.getInstance().getLogger(getClass());
         this.provider = provider;
-        configuration = ConfigurationFactory.getConfiguration();
     }
 
     /**
@@ -157,12 +156,10 @@ public class TenantCache implements Allocator<Context>, Destructor<Context> {
         int max = configuration.getIntegerProperty(Constants.PROPERTY_MAX_POOL_SIZE);
         int delay = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_DELAY);
         int limit = configuration.getIntegerProperty(Constants.PROPERTY_RETRY_LIMIT);
-
         String url = provider.getIdentityURL();
         String tenant = tenantName == null ? tenantId : tenantName;
         Properties properties = configuration.getProperties();
-        catalog = ServiceCatalogFactory.getServiceCatalog(url, tenant, userid, password, domain, properties);
-
+        catalog = getServiceCatalogFactory(url, tenant, properties);
         if (catalog == null) {
             logger.error(Msg.IAAS_UNSUPPORTED_IDENTITY_SERVICE, url);
             return;
@@ -195,12 +192,16 @@ public class TenantCache implements Allocator<Context>, Destructor<Context> {
         }
     }
 
+    public ServiceCatalog getServiceCatalogFactory(String url, String tenant, Properties properties) {
+        return ServiceCatalogFactory.getServiceCatalog(url, tenant, userid, password, domain, properties);
+    }
+
     private void createPools(int min, int max, String url, Properties properties) {
         for (String region : catalog.getRegions()) {
             try {
                 Pool<Context> pool = new Pool<>(min, max);
                 pool.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, url);
-                pool.setProperty(ContextFactory.PROPERTY_TENANT, tenantName);
+                pool.setProperty(ContextFactory.PROPERTY_TENANT, getTenantName());
                 pool.setProperty(ContextFactory.PROPERTY_CLIENT_CONNECTOR_CLASS, CLIENT_CONNECTOR_CLASS);
                 pool.setProperty(ContextFactory.PROPERTY_RETRY_DELAY,
                         configuration.getProperty(Constants.PROPERTY_RETRY_DELAY));
diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/CommonUtility.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/CommonUtility.java
new file mode 100644 (file)
index 0000000..0d4fe23
--- /dev/null
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2016-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.iaas.impl;
+
+import java.lang.reflect.Field;
+import java.util.Map;
+
+/**
+ * This class is used as a utility class to support the test cases.
+ */
+public class CommonUtility {
+
+    /**
+     * Use reflection to locate fields and methods so that they can be manipulated during the test
+     * to change the internal state accordingly.
+     * 
+     * @param privateFields
+     * @param object
+     * 
+     */
+    public static void injectMockObjects(Map<String, Object> privateFields, Object object) {
+        privateFields.forEach((fieldName, fieldInstance) -> {
+            try {
+                Field privateField = object.getClass().getDeclaredField(fieldName);
+                privateField.setAccessible(true);
+                privateField.set(object, fieldInstance);
+            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
+                // Exception occurred while accessing the private fields
+            }
+        });
+    }
+
+    /**
+     * Use reflection to locate fields and methods of the base class so that they can be manipulated
+     * during the test to change the internal state accordingly.
+     * 
+     * @param privateFields
+     * @param object
+     * 
+     */
+    public static void injectMockObjectsInBaseClass(Map<String, Object> privateFields, Object catalogObject) {
+        // For base class
+        privateFields.forEach((fieldName, fieldInstance) -> {
+            try {
+                Field privateField = catalogObject.getClass().getSuperclass().getDeclaredField(fieldName);
+                privateField.setAccessible(true);
+                privateField.set(catalogObject, fieldInstance);
+            } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
+                // Exception occurred while accessing the private fields
+            }
+        });
+    }
+
+}
index d609fd4..81fa877 100644 (file)
@@ -22,10 +22,12 @@ package org.onap.appc.adapter.iaas.impl;
 import org.glassfish.grizzly.http.util.HttpStatus;\r
 import org.junit.Assert;\r
 import org.junit.Test;\r
-\r
 import com.att.cdp.zones.model.Server;\r
 import com.att.cdp.zones.model.Stack;\r
 \r
+/**\r
+ * This class is used to test methods and functions of the Request Failed Exception class\r
+ */\r
 public class RequestFailedExceptionTest {\r
 \r
     @Test\r
@@ -48,6 +50,7 @@ public class RequestFailedExceptionTest {
     @Test\r
     public void testRequestFailedExceptionStringStringHttpStatusServer() {\r
         Server server=new Server();\r
+        server.setId("svrId");\r
         HttpStatus status=HttpStatus.OK_200;\r
         String reason="Success";\r
         String operation="POST";\r
@@ -56,10 +59,12 @@ public class RequestFailedExceptionTest {
         requestFailedException.setReason(reason);\r
         requestFailedException.setServerId("svrId");\r
         requestFailedException.setStatus(status);\r
+        requestFailedException.setServer(server);\r
         Assert.assertEquals("POST",requestFailedException.getOperation());\r
         Assert.assertEquals("Success",requestFailedException.getReason());\r
         Assert.assertEquals("svrId",requestFailedException.getServerId());\r
         Assert.assertEquals( HttpStatus.OK_200,requestFailedException.getStatus());\r
+        Assert.assertEquals(server, requestFailedException.getServer());\r
     }\r
 \r
     @Test\r
@@ -120,4 +125,21 @@ public class RequestFailedExceptionTest {
         Assert.assertTrue(requestFailedException.getLocalizedMessage().contains(message));\r
         Assert.assertTrue(requestFailedException.getMessage().contains(message));\r
     }\r
+    \r
+    /**\r
+     * This test case is used to test the request failed exception class without server\r
+     * \r
+     */\r
+    @Test\r
+    public void testRequestFailedExceptionThrowableStringWithoutServer() {\r
+        String tMessage = "throwable message";\r
+        Server server = null;\r
+        HttpStatus status = HttpStatus.ACCEPTED_202;\r
+        String reason = "Success";\r
+        String operation = "POST";\r
+        Throwable throwable = new Throwable(tMessage);\r
+        RequestFailedException requestFailedException = new RequestFailedException(throwable, operation, reason, status, server);\r
+        Assert.assertEquals(throwable, requestFailedException.getCause());\r
+        Assert.assertNull(requestFailedException.getServer());\r
+    }\r
 }\r
index 2b13d07..09156bf 100644 (file)
@@ -21,7 +21,6 @@
  * ============LICENSE_END=========================================================
  */
 
-
 package org.onap.appc.adapter.iaas.impl;
 
 import static org.junit.Assert.assertNotNull;
@@ -30,7 +29,6 @@ import static org.junit.Assert.assertTrue;
 import java.util.Properties;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.onap.appc.adapter.iaas.impl.IdentityURL;
 import org.onap.appc.configuration.ConfigurationFactory;
 
 public class TestIdentityUrl {
index 4b159f2..30c7aa7 100644 (file)
@@ -25,44 +25,43 @@ package org.onap.appc.adapter.iaas.impl;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.when;
 import java.io.IOException;
 import java.lang.reflect.Field;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import java.util.Properties;
-import java.util.Set;
+import java.util.function.BiFunction;
+import java.util.function.Function;
 import org.junit.Before;
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.experimental.categories.Category;
-import org.onap.appc.Constants;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
 import org.onap.appc.adapter.iaas.ProviderAdapter;
-import org.onap.appc.adapter.iaas.impl.ProviderAdapterImpl;
-import org.onap.appc.adapter.iaas.impl.ProviderCache;
-import org.onap.appc.adapter.iaas.impl.ServiceCatalog;
-import org.onap.appc.adapter.iaas.impl.TenantCache;
-import org.onap.appc.adapter.iaas.impl.VMURL;
+import org.onap.appc.adapter.iaas.provider.operation.api.IProviderOperation;
+import org.onap.appc.adapter.iaas.provider.operation.api.ProviderOperationFactory;
+import org.onap.appc.adapter.iaas.provider.operation.common.enums.Operation;
+import org.onap.appc.adapter.iaas.provider.operation.impl.EvacuateServer;
 import org.onap.appc.configuration.ConfigurationFactory;
 import org.onap.appc.exceptions.APPCException;
 import org.onap.appc.exceptions.UnknownProviderException;
+import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
 import com.att.cdp.exceptions.ZoneException;
-import com.att.cdp.zones.ComputeService;
-import com.att.cdp.zones.Context;
-import com.att.cdp.zones.ContextFactory;
 import com.att.cdp.zones.model.Image;
+import com.att.cdp.zones.model.ModelObject;
 import com.att.cdp.zones.model.Server;
-import com.att.cdp.zones.model.Server.Status;
-import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import com.woorea.openstack.keystone.model.Access.Service.Endpoint;
+import com.att.cdp.zones.model.Stack;
+import com.google.common.collect.ImmutableMap;
 
 /**
- * Test the ProviderAdapter implementation.
+ * This class is used to test methods and functions of the adapter implementation that do not
+ * require and do not set up connections to any providers.
  */
+@RunWith(MockitoJUnitRunner.class)
 @Category(org.onap.appc.adapter.iaas.impl.TestProviderAdapterImpl.class)
 public class TestProviderAdapterImpl {
 
@@ -74,26 +73,37 @@ public class TestProviderAdapterImpl {
 
     private static String IDENTITY_URL;
 
-    private static String PRINCIPAL;
+    private static String SERVER_URL;
 
-    private static String CREDENTIAL;
+    private static String SERVER_ID;
 
-    private static String TENANT_NAME;
+    private static Class<?> providerAdapterImplClass;
+    private static Class<?> configurationFactoryClass;
+    private static Field providerCacheField;
+    private static Field configField;
 
-    private static String TENANT_ID;
+    private static ProviderAdapterImpl adapter;
 
-    private static String USER_ID;
+    @Mock
+    ProviderOperationFactory factory;
 
-    private static String REGION_NAME;
+    @Mock
+    IProviderOperation providerOperation;
 
-    private static String SERVER_URL;
+    @Mock
+    EvacuateServer evacuateServer;
 
-    private static Class<?> providerAdapterImplClass;
-    private static Class<?> configurationFactoryClass;
-    private static Field providerCacheField;
-    private static Field configField;
+    private Map<String, ProviderCache> providerCache;
+
+    private SvcLogicContext svcContext;
 
-    private ProviderAdapterImpl adapter;
+    private Map<String, String> params;
+
+    private Image image;
+
+    private Server server;
+
+    private Stack stack;
 
     /**
      * Use reflection to locate fields and methods so that they can be manipulated during the test
@@ -111,136 +121,84 @@ public class TestProviderAdapterImpl {
 
         providerCacheField = providerAdapterImplClass.getDeclaredField("providerCache");
         providerCacheField.setAccessible(true);
-
-        configField = configurationFactoryClass.getDeclaredField("config");
-        configField.setAccessible(true);
-
         Properties props = ConfigurationFactory.getConfiguration().getProperties();
         IDENTITY_URL = props.getProperty("provider1.identity");
-        PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc");
-        CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc");
-        TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc");
-        TENANT_ID = props.getProperty("provider1.tenant1.id", "abcde12345fghijk6789lmnopq123rst");
-        REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne");
         SERVER_URL = props.getProperty("test.url");
+        configField = configurationFactoryClass.getDeclaredField("config");
+        configField.setAccessible(true);
+        SERVER_ID = "server1";
     }
 
     /**
-     * Setup the test environment.
+     * Use reflection to locate fields and methods so that they can be manipulated during the test
+     * to change the internal state accordingly.
      * 
      * @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 NullPointerException if the specified object is null and the field is an instance
-     *         field.
-     * @throws ExceptionInInitializerError if the initialization provoked by this method fails.
      */
     @Before
     public void setup() throws IllegalArgumentException, IllegalAccessException {
         configField.set(null, null);
         Properties properties = new Properties();
         adapter = new ProviderAdapterImpl(properties);
+        svcContext = new SvcLogicContext();
+        params = new HashMap<>();
+        params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
+        params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
+        server = new Server();
+        server.setId(SERVER_ID);
+        image = new Image();
+        image.setStatus(Image.Status.ACTIVE);
+        stack = new Stack();
+        stack.setStatus(Stack.Status.ACTIVE);
+        Map<String, Object> privateFields = ImmutableMap.<String, Object>builder().put("factory", factory)
+                .put("providerCache", getProviderCache()).build();
+        CommonUtility.injectMockObjects(privateFields, adapter);
+    }
+
+    private Map<String, ProviderCache> getProviderCache() {
+        providerCache = new HashMap<String, ProviderCache>();
+        ProviderCache cache = new ProviderCache();
+        cache.setIdentityURL(IDENTITY_URL);
+        cache.setProviderName(PROVIDER_NAME);
+        cache.setProviderType(PROVIDER_TYPE);
+        providerCache.put(cache.getIdentityURL(), cache);
+        return providerCache;
     }
 
     /**
-     * This method inspects the provider adapter implementation to make sure that the cache of
-     * providers and tenants, as well as the service catalog, and all pools of contexts have been
-     * set up correctly.
+     * This test case is used to invoke the default constructor
      * 
-     * @throws IllegalAccessException if this Field object is enforcing Java language access control
-     *         and the underlying field is inaccessible.
-     * @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).
      */
-    @SuppressWarnings({"unchecked"})
-    @Ignore
     @Test
-    public void validateCacheIsCreatedCorrectly() throws IllegalArgumentException, IllegalAccessException {
-        Map<String, ProviderCache> providerCaches = (Map<String, ProviderCache>) providerCacheField.get(adapter);
-
-        assertNotNull(providerCaches);
-        assertEquals(1, providerCaches.size());
-        assertTrue(providerCaches.containsKey(PROVIDER_NAME));
-
-        ProviderCache providerCache = providerCaches.get(PROVIDER_NAME);
-        assertEquals(PROVIDER_NAME, providerCache.getProviderName());
-        assertEquals(PROVIDER_TYPE, providerCache.getProviderType());
-
-        Map<String, TenantCache> tenantCaches = providerCache.getTenants();
-        assertNotNull(tenantCaches);
-        assertEquals(1, tenantCaches.size());
-        assertTrue(tenantCaches.containsKey(TENANT_NAME));
-
-        TenantCache tenantCache = tenantCaches.get(TENANT_NAME);
-
-        assertEquals(TENANT_ID, tenantCache.getTenantId());
-        assertEquals(TENANT_NAME, tenantCache.getTenantName());
-        assertEquals(USER_ID, tenantCache.getUserid());
-
-        ServiceCatalog catalog = tenantCache.getServiceCatalog();
-        assertNotNull(catalog);
-
-        System.out.println(catalog.toString());
-        List<String> serviceTypes = catalog.getServiceTypes();
-        assertNotNull(serviceTypes);
-        assertEquals(12, serviceTypes.size());
-
-        assertEquals(TENANT_NAME, catalog.getProjectName());
-        assertEquals(TENANT_ID, catalog.getProjectId());
-
-        Set<String> regionNames = catalog.getRegions();
-        assertNotNull(regionNames);
-        assertEquals(1, regionNames.size());
-        assertTrue(regionNames.contains(REGION_NAME));
-
-        List<?> endpoints = catalog.getEndpoints(ServiceCatalog.IDENTITY_SERVICE);
-        assertNotNull(endpoints);
-        assertEquals(1, endpoints.size());
-        Endpoint endpoint = (Endpoint) endpoints.get(0);
-        assertNotNull(endpoint);
-        assertEquals(REGION_NAME, endpoint.getRegion());
-        assertEquals(IDENTITY_URL, endpoint.getPublicURL());
-
-        endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE);
-        assertNotNull(endpoints);
-        assertEquals(1, endpoints.size());
-        endpoint = (Endpoint) endpoints.get(0);
-        assertNotNull(endpoint);
-        assertEquals(REGION_NAME, endpoint.getRegion());
-
-        endpoints = catalog.getEndpoints(ServiceCatalog.VOLUME_SERVICE);
-        assertNotNull(endpoints);
-        assertEquals(1, endpoints.size());
-        endpoint = (Endpoint) endpoints.get(0);
-        assertNotNull(endpoint);
-        assertEquals(REGION_NAME, endpoint.getRegion());
-
-        endpoints = catalog.getEndpoints(ServiceCatalog.IMAGE_SERVICE);
-        assertNotNull(endpoints);
-        assertEquals(1, endpoints.size());
-        endpoint = (Endpoint) endpoints.get(0);
-        assertNotNull(endpoint);
-        assertEquals(REGION_NAME, endpoint.getRegion());
-
-        endpoints = catalog.getEndpoints(ServiceCatalog.NETWORK_SERVICE);
-        assertNotNull(endpoints);
-        assertEquals(1, endpoints.size());
-        endpoint = (Endpoint) endpoints.get(0);
-        assertNotNull(endpoint);
-        assertEquals(REGION_NAME, endpoint.getRegion());
-
-        assertTrue(catalog.isServicePublished(ServiceCatalog.IDENTITY_SERVICE));
-        assertTrue(catalog.isServicePublished(ServiceCatalog.COMPUTE_SERVICE));
-        assertTrue(catalog.isServicePublished(ServiceCatalog.VOLUME_SERVICE));
-        assertTrue(catalog.isServicePublished(ServiceCatalog.IMAGE_SERVICE));
-        assertTrue(catalog.isServicePublished(ServiceCatalog.NETWORK_SERVICE));
+    public void testDefaultConstructor() {
+        ProviderAdapter adapter = new ProviderAdapterImpl();
+        assertNotNull(adapter);
     }
 
     /**
-     * This test case is used to actually validate that a server has been restarted from an already
-     * running state
+     * This test case is used to invoke the argument constructor
+     * 
+     */
+    @Test
+    public void testArgumentedConstructor() {
+        ProviderAdapter adapter = new ProviderAdapterImpl(true);
+        assertNotNull(adapter);
+    }
+
+    /**
+     * Tests that we get the Adapter name
+     */
+    @Test
+    public void testAdapterName() {
+        assertNotNull(adapter.getAdapterName());
+    }
+
+    /**
+     * This test case is used to restart the server
      * 
      * @throws ZoneException If the login cannot be performed because the principal and/or
      *         credentials are invalid.
@@ -248,43 +206,54 @@ public class TestProviderAdapterImpl {
      *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
      * @throws IOException if an I/O error occurs
-     * @throws APPCException
+     * @throws APPCException If the server cannot be restarted for some reason
      */
-    // @Ignore
     @Test
-    public void testRestartRunningServer()
+    public void testRestartServer()
             throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
-        properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-        properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true");
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login(PRINCIPAL, CREDENTIAL);
-            VMURL vm = VMURL.parseURL(SERVER_URL);
-
-            ComputeService computeService = context.getComputeService();
-            Server server = computeService.getServer(vm.getServerId());
-            if (!server.getStatus().equals(Status.RUNNING)) {
-                server.start();
-                assertTrue(waitForStateChange(server, Status.RUNNING));
-            }
-
-            Map<String, String> params = new HashMap<>();
-            params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
-            params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
-            SvcLogicContext svcContext = new SvcLogicContext();
-
-            server = adapter.restartServer(params, svcContext);
-
-            assertEquals(Server.Status.RUNNING, server.getStatus());
-        }
+        prepareMock(Operation.RESTART_SERVICE, Server.Status.RUNNING);
+        Server actualServer = adapter.restartServer(params, svcContext);
+        assertEquals(Server.Status.RUNNING, actualServer.getStatus());
     }
 
+    /**
+     * This test case is used to start the server
+     * 
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the server cannot be started for some reason
+     */
+    @Test
+    public void testStartServer()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.START_SERVICE, Server.Status.RUNNING);
+        Server actualServer = adapter.startServer(params, svcContext);
+        assertEquals(Server.Status.RUNNING, actualServer.getStatus());
+    }
+
+    /**
+     * This test case is used to stop the server
+     * 
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the server cannot be stopped for some reason
+     */
+    @Test
+    public void testStopServer()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.STOP_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.stopServer(params, svcContext);
+        assertEquals(Server.Status.READY, actualServer.getStatus());
+    }
 
-    /****************************************/
     /**
      * Tests that the vmStatuschecker method works and returns the correct status of the VM
      * requested
@@ -295,246 +264,114 @@ public class TestProviderAdapterImpl {
      *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
      * @throws IOException if an I/O error occurs
-     * @throws UnknownProviderException If the provider cannot be found
+     * @throws APPCException If the vm status can not be verified
      */
-    // @Ignore
     @Test
-    public void testVmStatuschecker() throws IllegalStateException, IllegalArgumentException, ZoneException,
-            UnknownProviderException, IOException {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
-        properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-        properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true");
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login(PRINCIPAL, CREDENTIAL);
-            VMURL vm = VMURL.parseURL(SERVER_URL);
-
-            ComputeService computeService = context.getComputeService();
-            Server server = computeService.getServer(vm.getServerId());
-            if (!server.getStatus().equals(Status.RUNNING)) {
-                server.start();
-                assertTrue(waitForStateChange(server, Status.RUNNING));
-            }
-            // or instead of the if-block, can ensureRunning(server) be used?
-            ensureRunning(server);
-            assertEquals(Server.Status.RUNNING, server.getStatus());
-        }
+    public void testVmStatuschecker()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.VMSTATUSCHECK_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.vmStatuschecker(params, svcContext);
+        assertEquals(Server.Status.READY, actualServer.getStatus());
     }
 
-    /****************************************/
-
-
     /**
-     * Tests that we can restart a server that is already stopped
+     * Tests that the terminate stack method works
      * 
      * @throws ZoneException If the login cannot be performed because the principal and/or
      *         credentials are invalid.
      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
-     *         the expected argument(s) are not defined or are invalid.
+     *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
      * @throws IOException if an I/O error occurs
-     * @throws APPCException
+     * @throws APPCException If the stack cannot be terminated for some reason
      */
-    // @Ignore
     @Test
-    public void testRestartStoppedServer()
+    public void testTerminateStack()
             throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
-        properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login(PRINCIPAL, CREDENTIAL);
-            VMURL vm = VMURL.parseURL(SERVER_URL);
-
-            ComputeService computeService = context.getComputeService();
-            Server server = computeService.getServer(vm.getServerId());
-            if (!server.getStatus().equals(Status.READY)) {
-                server.stop();
-                assertTrue(waitForStateChange(server, Status.READY));
-            }
-
-            Map<String, String> params = new HashMap<>();
-            params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
-            params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
-            SvcLogicContext svcContext = new SvcLogicContext();
-
-            server = adapter.restartServer(params, svcContext);
-
-            assertEquals(Server.Status.RUNNING, server.getStatus());
-
-        }
+        prepareMock(Operation.TERMINATE_STACK, null);
+        stack.setStatus(Stack.Status.DELETED);
+        Stack actualStack = adapter.terminateStack(params, svcContext);
+        assertEquals(Stack.Status.DELETED, actualStack.getStatus());
     }
 
     /**
-     * Tests that we can rebuild a running server (not created from a bootable volume)
+     * Tests that the snapshot method works and returns snapshot of the stack
      * 
      * @throws ZoneException If the login cannot be performed because the principal and/or
      *         credentials are invalid.
      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
-     *         the expected argument(s) are not defined or are invalid.
+     *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
-     * @throws UnknownProviderException If the provider cannot be found
      * @throws IOException if an I/O error occurs
-     * @throws APPCException If the server cannot be rebuilt for some reason
+     * @throws APPCException If the stack snapshot can not be taken for some reason
      */
-    // @Ignore
     @Test
-    public void testRebuildRunningServer()
-            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
-        properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login(PRINCIPAL, CREDENTIAL);
-            VMURL vm = VMURL.parseURL(SERVER_URL);
-
-            ComputeService computeService = context.getComputeService();
-            Server server = computeService.getServer(vm.getServerId());
-            ensureRunning(server);
-
-            Map<String, String> params = new HashMap<>();
-            params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
-            params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
-            SvcLogicContext svcContext = new SvcLogicContext();
-
-            server = adapter.rebuildServer(params, svcContext);
-            assertTrue(waitForStateChange(server, Status.RUNNING));
-
-        }
+    public void testSnapshotStack()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.SNAPSHOT_STACK, null);
+        Stack actualStack = adapter.snapshotStack(params, svcContext);
+        assertEquals(Stack.Status.ACTIVE, actualStack.getStatus());
     }
 
     /**
-     * Tests that we can rebuild a paused server (not created from a bootable volume)
+     * Tests that the restore method works and returns restored stack
      * 
      * @throws ZoneException If the login cannot be performed because the principal and/or
      *         credentials are invalid.
      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
-     *         the expected argument(s) are not defined or are invalid.
+     *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
-     * @throws UnknownProviderException If the provider cannot be found
      * @throws IOException if an I/O error occurs
-     * @throws APPCException If the server cannot be rebuilt for some reason
+     * @throws APPCException If the stack cannot be restored for some reason
      */
-    // @Ignore
     @Test
-    public void testRebuildPausedServer()
-            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
-        properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login(PRINCIPAL, CREDENTIAL);
-            VMURL vm = VMURL.parseURL(SERVER_URL);
-
-            ComputeService computeService = context.getComputeService();
-            Server server = computeService.getServer(vm.getServerId());
-            ensurePaused(server);
-
-            Map<String, String> params = new HashMap<>();
-            params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
-            params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
-            SvcLogicContext svcContext = new SvcLogicContext();
-
-            server = adapter.rebuildServer(params, svcContext);
-            assertTrue(waitForStateChange(server, Status.RUNNING));
-        }
+    public void testRestoreStack()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.RESTORE_STACK, null);
+        Stack actualStack = adapter.restoreStack(params, svcContext);
+        assertEquals(Stack.Status.ACTIVE, actualStack.getStatus());
     }
 
     /**
-     * Tests that we can rebuild a paused server (not created from a bootable volume)
+     * Tests that the lookup server will lookup for the server with server id
      * 
      * @throws ZoneException If the login cannot be performed because the principal and/or
      *         credentials are invalid.
      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
-     *         the expected argument(s) are not defined or are invalid.
+     *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
-     * @throws UnknownProviderException If the provider cannot be found
      * @throws IOException if an I/O error occurs
-     * @throws APPCException If the server cannot be rebuilt for some reason
+     * @throws APPCException If the server cannot be found for some reason
      */
-    // @Ignore
     @Test
-    public void testRebuildSuspendedServer()
-            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
-        properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login(PRINCIPAL, CREDENTIAL);
-            VMURL vm = VMURL.parseURL(SERVER_URL);
-
-            ComputeService computeService = context.getComputeService();
-            Server server = computeService.getServer(vm.getServerId());
-            ensureSuspended(server);
-
-            Map<String, String> params = new HashMap<>();
-            params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
-            params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
-            SvcLogicContext svcContext = new SvcLogicContext();
-
-            server = adapter.rebuildServer(params, svcContext);
-            assertTrue(waitForStateChange(server, Status.RUNNING));
-        }
+    public void testLookupServer()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.LOOKUP_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.lookupServer(params, svcContext);
+        assertEquals(SERVER_ID, actualServer.getId());
     }
 
     /**
-     * Tests that we can rebuild a paused server (not created from a bootable volume)
+     * Tests that the to create a snapshot and return a image
      * 
      * @throws ZoneException If the login cannot be performed because the principal and/or
      *         credentials are invalid.
      * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
-     *         the expected argument(s) are not defined or are invalid.
+     *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
-     * @throws UnknownProviderException If the provider cannot be found
      * @throws IOException if an I/O error occurs
-     * @throws APPCException If the server cannot be rebuilt for some reason
+     * @throws APPCException If the image snapshot can not be taken for some reason
      */
-    // @Ignore
     @Test
-    public void testRebuildStoppedServer()
-            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, IDENTITY_URL);
-        properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login(PRINCIPAL, CREDENTIAL);
-            VMURL vm = VMURL.parseURL(SERVER_URL);
-
-            ComputeService computeService = context.getComputeService();
-            Server server = computeService.getServer(vm.getServerId());
-            ensureStopped(server);
-
-            Map<String, String> params = new HashMap<>();
-            params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
-            params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME);
-            SvcLogicContext svcContext = new SvcLogicContext();
-
-            server = adapter.rebuildServer(params, svcContext);
-            assertTrue(waitForStateChange(server, Status.RUNNING));
-        }
+    public void testCreateSnapshot()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.SNAPSHOT_SERVICE, Server.Status.READY);
+        Image actualImage = adapter.createSnapshot(params, svcContext);
+        assertEquals(image.getStatus(), actualImage.getStatus());
     }
 
     /**
-     * Test subsequent action on second vm in different Tenant resulting in {"itemNotFound":
-     * {"message": "Instance could not be found", "code": 404}}
+     * Tests that the to calculate the server volume and attach it to the server
      * 
      * @throws ZoneException If the login cannot be performed because the principal and/or
      *         credentials are invalid.
@@ -542,359 +379,166 @@ public class TestProviderAdapterImpl {
      *         the expected argument(s) are not defined or are invalid
      * @throws IllegalStateException If the identity service is not available or cannot be created
      * @throws IOException if an I/O error occurs
-     * @throws APPCException
+     * @throws APPCException If the Server volume can not be calculated for some reason
      */
-
     @Test
-    public void testTenantVerification()
+    public void testAttachVolume()
             throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
-
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000");
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, "APP-C");
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-
-        String vmUrl =
-                "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
-
-        // try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-        // context.login("AppC", "AppC");
-
-        // call lookupServer on vm in defined tenant "APP-C_TLV"
-        VMURL vm = VMURL.parseURL(vmUrl);
-
-        Map<String, String> params = new HashMap<>();
-        params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
-        params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0");
-        params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0");
-        SvcLogicContext svcContext = new SvcLogicContext();
-
-        long start, end = 0;
-
-        System.out.println("\n--------------------Begin lookupServer on tenant 1--------------------");
-        start = System.currentTimeMillis();
-        Server server = adapter.lookupServer(params, svcContext);
-        end = System.currentTimeMillis();
-
-        System.out.println(String.format("lookupServer on tenant 1 took %ds", (end - start) / 1000));
-        System.out.println("----------------------------------------------------------------------\n");
-        assertNotNull(server);
-
-        // repeat to show that context is reused for second request
-        System.out.println("\n-----------------Begin repeat lookupServer on tenant 1----------------");
-        start = System.currentTimeMillis();
-        server = adapter.lookupServer(params, svcContext);
-        end = System.currentTimeMillis();
-
-        System.out.println(String.format("Repeat lookupServer on tenant 1 took %ds", (end - start) / 1000));
-        System.out.println("----------------------------------------------------------------------\n");
-        assertNotNull(server);
-
-        // call lookupServer on vm in second tenant "Play"
-        // This is where we would fail due to using the previous
-        // tenants context
-        vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
-        vm = VMURL.parseURL(vmUrl);
-        params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
-
-        System.out.println("\n--------------------Begin lookupServer on tenant 2--------------------");
-        start = System.currentTimeMillis();
-        server = adapter.lookupServer(params, svcContext);
-        end = System.currentTimeMillis();
-        System.out.println(String.format("\nlookupServer on tenant 2 took %ds", (end - start) / 1000));
-        System.out.println("----------------------------------------------------------------------\n");
-        assertNotNull(server);
-
-        // call lookupServer on vm in non-existing tenant
-        vmUrl = "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
-        vm = VMURL.parseURL(vmUrl);
-        params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
-
-        System.out.println("\n--------------Begin lookupServer on non-existant tenant--------------");
-        start = System.currentTimeMillis();
-        server = adapter.lookupServer(params, svcContext);
-        end = System.currentTimeMillis();
-        System.out.println(String.format("\nlookupServer on tenant 3 took %ds", (end - start) / 1000));
-        System.out.println("----------------------------------------------------------------------\n");
-        assertNull(server);
-
-        // }
+        prepareMock(Operation.ATTACHVOLUME_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.attachVolume(params, svcContext);
+        assertEquals(SERVER_ID, actualServer.getId());
     }
 
-    /****************************************/
-
-
+    /**
+     * Tests that the to detach the calculated volume from the server
+     * 
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the Server volume can not be detached for some reason
+     */
     @Test
-    public void testSnapshotServer() throws Exception {
-        Properties properties = new Properties();
-        properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL, "http://example.com:5000");
-        // properties.setProperty(ContextFactory.PROPERTY_REGION, "");
-        properties.setProperty(ContextFactory.PROPERTY_TENANT, "Play");
-        properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-
-        String vmUrl =
-                "http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";
-
-        try (Context context = ContextFactory.getContext(PROVIDER_TYPE, properties)) {
-            context.login("AppC", "AppC");
-            VMURL vm = VMURL.parseURL(vmUrl);
-
-            Map<String, String> params = new HashMap<>();
-            params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, vmUrl);
-            params.put(ProviderAdapter.PROPERTY_IDENTITY_URL, "http://example.com:5000/v2.0");
-            params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, "http://example.com:5000/v2.0");
-            SvcLogicContext svcContext = new SvcLogicContext();
-
-            long start, end = 0;
-
-            start = System.currentTimeMillis();
-            Image image = adapter.createSnapshot(params, svcContext);
-            end = System.currentTimeMillis();
-
-            System.out.println(String.format("Image ID: %s", image.getId()));
-            System.out.println(String.format("Snapshot took %ds", (end - start) / 1000));
+    public void testDettachVolume()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.DETACHVOLUME_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.dettachVolume(params, svcContext);
+        assertEquals(SERVER_ID, actualServer.getId());
+    }
 
-            start = System.currentTimeMillis();
-            adapter.rebuildServer(params, svcContext);
-            end = System.currentTimeMillis();
-            System.out.println(String.format("Rebuild took %ds", (end - start) / 1000));
-        }
+    /****************************************/
 
-    }
 
     /**
-     * Ensures that the server is in stopped (shutdown) state prior to test
+     * Tests that we can restart a server that is already stopped
      * 
-     * @param server The server to ensure is stopped
-     * @throws ZoneException If the server can't be operated upon for some reason
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid.
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the server cannot be restarted for some reason
      */
-    @SuppressWarnings("nls")
-    private static void ensureStopped(Server server) throws ZoneException {
-        switch (server.getStatus()) {
-            case READY:
-                break;
-
-            case PENDING:
-                waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
-                        Server.Status.SUSPENDED, Server.Status.ERROR);
-                ensureSuspended(server);
-                break;
-
-            case PAUSED:
-                server.unpause();
-                waitForStateChange(server, Server.Status.RUNNING);
-                server.stop();
-                waitForStateChange(server, Server.Status.READY);
-                break;
-
-            case SUSPENDED:
-                server.resume();
-                waitForStateChange(server, Server.Status.RUNNING);
-                server.stop();
-                waitForStateChange(server, Server.Status.READY);
-                break;
-
-            case RUNNING:
-                server.stop();
-                waitForStateChange(server, Server.Status.READY);
-                break;
-
-            case DELETED:
-            case ERROR:
-            default:
-                fail("Server state is not valid for test - " + server.getStatus().name());
-        }
+    @Test
+    public void testRestartStoppedServer()
+            throws IllegalStateException, IllegalArgumentException, ZoneException, IOException, APPCException {
+        prepareMock(Operation.RESTART_SERVICE, Server.Status.RUNNING);
+        Server actualServer = adapter.restartServer(params, svcContext);
+        assertEquals(Server.Status.RUNNING, actualServer.getStatus());
+
     }
 
     /**
-     * Ensures that the server is in suspended state prior to test
+     * Tests that we can rebuild a server (not created from a bootable volume)
      * 
-     * @param server The server to ensure is suspended
-     * @throws ZoneException If the server can't be operated upon for some reason
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid.
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws UnknownProviderException If the provider cannot be found
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the server cannot be rebuilt for some reason
      */
-    @SuppressWarnings("nls")
-    private static void ensureSuspended(Server server) throws ZoneException {
-        switch (server.getStatus()) {
-            case SUSPENDED:
-                break;
-
-            case PENDING:
-                waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
-                        Server.Status.SUSPENDED, Server.Status.ERROR);
-                ensureSuspended(server);
-                break;
-
-            case PAUSED:
-                server.unpause();
-                waitForStateChange(server, Server.Status.RUNNING);
-                server.suspend();
-                waitForStateChange(server, Server.Status.SUSPENDED);
-                break;
-
-            case READY:
-                server.start();
-                waitForStateChange(server, Server.Status.RUNNING);
-                server.suspend();
-                waitForStateChange(server, Server.Status.SUSPENDED);
-                break;
-
-            case RUNNING:
-                server.suspend();
-                waitForStateChange(server, Server.Status.SUSPENDED);
-                break;
-
-            case DELETED:
-            case ERROR:
-            default:
-                fail("Server state is not valid for test - " + server.getStatus().name());
-        }
+    @Test
+    public void testRebuildServer()
+            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
+        prepareMock(Operation.REBUILD_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.rebuildServer(params, svcContext);
+        assertEquals(Server.Status.READY, actualServer.getStatus());
     }
 
     /**
-     * This method makes sure that the indicated server is running before performing a test
+     * Tests that we can terminate a running server
      * 
-     * @param server The server to ensure is running
-     * @throws ZoneException If the server can't be operated upon
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid.
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws UnknownProviderException If the provider cannot be found
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the server cannot be terminated for some reason
      */
-    @SuppressWarnings("nls")
-    private static void ensureRunning(Server server) throws ZoneException {
-        switch (server.getStatus()) {
-            case RUNNING:
-                break;
-
-            case PENDING:
-                waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
-                        Server.Status.SUSPENDED, Server.Status.ERROR);
-                ensureRunning(server);
-                break;
-
-            case PAUSED:
-                server.unpause();
-                waitForStateChange(server, Server.Status.RUNNING);
-                break;
-
-            case SUSPENDED:
-                server.resume();
-                waitForStateChange(server, Server.Status.RUNNING);
-                break;
-
-            case READY:
-                server.start();
-                waitForStateChange(server, Server.Status.RUNNING);
-                break;
-
-            case DELETED:
-            case ERROR:
-            default:
-                fail("Server state is not valid for test - " + server.getStatus().name());
-        }
+    @Test
+    public void testTerminateServer()
+            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
+        prepareMock(Operation.TERMINATE_SERVICE, Server.Status.DELETED);
+        Server actualServer = adapter.terminateServer(params, svcContext);
+        assertEquals(Server.Status.DELETED, actualServer.getStatus());
     }
 
     /**
-     * This method will make sure that the server we are testing is paused
+     * Tests that we can evacuate a server to move it to non-pending state
      * 
-     * @param server The server to make sure is paused for the test
-     * @throws ZoneException If anything fails
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid.
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws UnknownProviderException If the provider cannot be found
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the server cannot be evacuated for some reason
      */
-    @SuppressWarnings("nls")
-    private static void ensurePaused(Server server) throws ZoneException {
-        switch (server.getStatus()) {
-            case PAUSED:
-                break;
-
-            case PENDING:
-                waitForStateChange(server, Server.Status.READY, Server.Status.RUNNING, Server.Status.PAUSED,
-                        Server.Status.SUSPENDED, Server.Status.ERROR);
-                ensurePaused(server);
-                break;
-
-            case READY:
-                server.start();
-                waitForStateChange(server, Server.Status.RUNNING);
-                server.pause();
-                waitForStateChange(server, Server.Status.PAUSED);
-                break;
-
-            case RUNNING:
-                server.pause();
-                waitForStateChange(server, Server.Status.PAUSED);
-                break;
-
-            case SUSPENDED:
-                server.resume();
-                waitForStateChange(server, Server.Status.RUNNING);
-                server.pause();
-                waitForStateChange(server, Server.Status.PAUSED);
-                break;
-
-            case ERROR:
-            case DELETED:
-            default:
-                fail("Server state is not valid for test - " + server.getStatus().name());
-        }
+    @Test
+    public void testEvacuateServer()
+            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
+        prepareMock(Operation.EVACUATE_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.evacuateServer(params, svcContext);
+        assertEquals(Server.Status.READY, actualServer.getStatus());
     }
 
     /**
-     * Enter a pool-wait loop checking the server state to see if it has entered one of the desired
-     * states or not.
-     * <p>
-     * This method checks the state of the server periodically for one of the desired states. When
-     * the server enters one of the desired states, the method returns a successful indication
-     * (true). If the server never enters one of the desired states within the alloted timeout
-     * period, then the method returns a failed response (false). No exceptions are thrown from this
-     * method.
-     * </p>
+     * Tests that we can migrate a server. Migration can be done only on certain statuses like
+     * READY, RUNNING & SUSPENDED
      * 
-     * @param server The server to wait on
-     * @param desiredStates A variable list of desired states, any one of which is allowed.
-     * @return True if the server entered one of the desired states, and false if not and the wait
-     *         loop timed out.
+     * @throws ZoneException If the login cannot be performed because the principal and/or
+     *         credentials are invalid.
+     * @throws IllegalArgumentException If the principal and/or credential are null or empty, or if
+     *         the expected argument(s) are not defined or are invalid.
+     * @throws IllegalStateException If the identity service is not available or cannot be created
+     * @throws UnknownProviderException If the provider cannot be found
+     * @throws IOException if an I/O error occurs
+     * @throws APPCException If the server cannot be migrated for some reason
      */
-    private static boolean waitForStateChange(Server server, Server.Status... desiredStates) {
-        int timeout = ConfigurationFactory.getConfiguration()
-                .getIntegerProperty(Constants.PROPERTY_SERVER_STATE_CHANGE_TIMEOUT);
-        long limit = System.currentTimeMillis() + (timeout * 1000);
-        Server vm = server;
-
-        try {
-            while (limit > System.currentTimeMillis()) {
-                vm.refresh();
-                for (Server.Status desiredState : desiredStates) {
-                    if (server.getStatus().equals(desiredState)) {
-                        return true;
-                    }
-                }
-
-                try {
-                    Thread.sleep(10000L);
-                } catch (InterruptedException e) {
-                    // ignore
-                }
-            }
-        } catch (ZoneException e) {
-            e.printStackTrace();
-        }
-
-        return false;
+    @Test
+    public void testMigrateServer()
+            throws IOException, IllegalStateException, IllegalArgumentException, ZoneException, APPCException {
+        prepareMock(Operation.MIGRATE_SERVICE, Server.Status.READY);
+        Server actualServer = adapter.migrateServer(params, svcContext);
+        assertEquals(Server.Status.READY, actualServer.getStatus());
     }
 
-    /*
-     * @Test public void testTerminateStack() throws IllegalStateException,
-     * IllegalArgumentException, ZoneException, UnknownProviderException, IOException { Properties
-     * properties = new Properties(); properties.setProperty(ContextFactory.PROPERTY_IDENTITY_URL,
-     * IDENTITY_URL); properties.setProperty(ContextFactory.PROPERTY_REGION, REGION_NAME);
-     * properties.setProperty(ContextFactory.PROPERTY_TENANT, TENANT_NAME);
-     * properties.setProperty(ContextFactory.PROPERTY_TRUSTED_HOSTS, "*");
-     * properties.setProperty(ContextFactory.PROPERTY_DISABLE_PROXY, "true"); try (Context context =
-     * ContextFactory.getContext(PROVIDER_TYPE, properties)) { context.login(PRINCIPAL, CREDENTIAL);
-     * VMURL vm = VMURL.parseURL(SERVER_URL); ComputeService computeService =
-     * context.getComputeService(); Server server = computeService.getServer(vm.getServerId()); if
-     * (!server.getStatus().equals(Status.RUNNING)) { server.start();
-     * assertTrue(waitForStateChange(server, Status.RUNNING)); } Map<String, String> params = new
-     * HashMap<>(); params.put(ProviderAdapter.PROPERTY_INSTANCE_URL, SERVER_URL);
-     * params.put(ProviderAdapter.PROPERTY_PROVIDER_NAME, PROVIDER_NAME); SvcLogicContext svcContext
-     * = new SvcLogicContext(); Stack stack = adapter.terminateStack(params, svcContext);
-     * assertNotNull(stack); } }
-     */
+    private void prepareMock(Operation operation, Server.Status serverStatus) throws APPCException {
+        IProviderOperation providerOperation = fetchOperation.apply(operation);
+        ModelObject modelObject = fetchModelObject.apply(operation, serverStatus);
+        when(factory.getOperationObject(operation)).thenReturn(providerOperation);
+        when(providerOperation.doOperation(anyObject(), anyObject())).thenReturn(modelObject);
+
+    }
 
+    Function<Operation, IProviderOperation> fetchOperation = operation -> {
+        if (operation.equals(Operation.EVACUATE_SERVICE))
+            return evacuateServer;
+        else
+            return providerOperation;
+    };
+
+    Function<Server.Status, Server> fetchServer = status -> {
+        server.setStatus(status);
+        return server;
+    };
+
+    BiFunction<Operation, Server.Status, ModelObject> fetchModelObject = (operation, status) -> {
+        if (operation.equals(Operation.SNAPSHOT_SERVICE))
+            return image;
+        else if (operation == Operation.RESTORE_STACK || operation == Operation.SNAPSHOT_STACK
+                || operation == Operation.TERMINATE_STACK)
+            return stack;
+        else
+            return fetchServer.apply(status);
+    };
 }
diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderCache.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderCache.java
new file mode 100644 (file)
index 0000000..b412738
--- /dev/null
@@ -0,0 +1,117 @@
+/*-
+ * ============LICENSE_START=======================================================
+ *  Copyright (C) 2016-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.iaas.impl;
+
+import static org.junit.Assert.assertNotNull;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.appc.Constants;
+import org.onap.appc.configuration.Configuration;
+import org.onap.appc.configuration.ConfigurationFactory;
+import org.onap.appc.pool.Pool;
+import com.att.cdp.zones.Context;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * This class is used to test methods and functions of the provider cache
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class TestProviderCache {
+
+    private ProviderCache providerCache;
+
+    @Mock
+    private TenantCache tenantCache;
+
+    @Mock
+    private ServiceCatalog catalog;
+
+    @Mock
+    private Context context;
+
+    @Mock
+    Pool<Context> pool;
+
+    @SuppressWarnings("nls")
+    private static final String PROVIDER_NAME = "ILAB";
+
+    @SuppressWarnings("nls")
+    private static final String PROVIDER_TYPE = "OpenStackProvider";
+
+    private static String TENANT_ID;
+
+    protected Set<String> regions = new HashSet<>(Arrays.asList("RegionOne"));
+
+    private Map<String, TenantCache> tenants = new HashMap<String, TenantCache>();
+
+    @BeforeClass
+    public static void before() {
+        Properties props = ConfigurationFactory.getConfiguration().getProperties();
+        TENANT_ID = props.getProperty("provider1.tenant1.id",
+                props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst"));
+    }
+
+    /**
+     * 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() {
+        Configuration props = ConfigurationFactory.getConfiguration();
+        props.setProperty(Constants.PROPERTY_RETRY_LIMIT, "10");
+        providerCache = new ProviderCache();
+        providerCache.setIdentityURL("http://192.168.1.1:5000/v2.0/");
+        providerCache.setProviderName(PROVIDER_NAME);
+        providerCache.setProviderType(PROVIDER_TYPE);
+        tenantCache = new TenantCache(providerCache);
+        tenants.put(TENANT_ID, tenantCache);
+        Map<String, Object> privateFields = ImmutableMap.<String, Object>builder().put("tenants", tenants).build();
+        CommonUtility.injectMockObjects(privateFields, providerCache);
+    }
+
+    /**
+     * Ensure that we set up the Tenants property correctly
+     */
+    @Test
+    public void testTenantsProperty() {
+        assertNotNull(providerCache.getTenants());
+    }
+
+    /**
+     * Ensure that we set up the Tenant Id property correctly
+     */
+    @Test
+    public void testTenantIdProperty() {
+        assertNotNull(providerCache.getTenant(TENANT_ID));
+    }
+
+}
index 98ab7ba..0cb25e9 100644 (file)
 
 package org.onap.appc.adapter.iaas.impl;
 
+import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_SERVICE;
 import java.lang.reflect.Field;
 import java.util.Map;
-import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderOperation;
-import org.onap.appc.exceptions.APPCException;
-import com.att.cdp.zones.model.ModelObject;
-import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.slf4j.MDC;
+import org.onap.appc.adapter.iaas.provider.operation.impl.base.ProviderOperation;
 import org.onap.appc.configuration.ConfigurationFactory;
+import org.onap.appc.exceptions.APPCException;
 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import static org.onap.appc.adapter.iaas.provider.operation.common.constants.Constants.MDC_SERVICE;
+import org.slf4j.MDC;
+import com.att.cdp.zones.model.ModelObject;
 
 /**
  * This class is used to test methods and functions of the adapter implementation that do not
@@ -81,10 +80,7 @@ public class TestProviderOperation extends ProviderOperation {
     @Test(expected = RequestFailedException.class)
     public void testValidateParameterPatternExpectFailNullValue() throws RequestFailedException {
         MDC.put(MDC_SERVICE, "junit");
-        SvcLogicContext svcContext = new SvcLogicContext();
-        RequestContext rc = new RequestContext(svcContext);
         String link = null;
-
         validateVMURL(VMURL.parseURL(link));
     }
 
@@ -97,10 +93,7 @@ public class TestProviderOperation extends ProviderOperation {
     @Test(expected = RequestFailedException.class)
     public void testValidateParameterPatternExpectFailEmptyValue() throws RequestFailedException {
         MDC.put(MDC_SERVICE, "junit");
-        SvcLogicContext svcContext = new SvcLogicContext();
-        RequestContext rc = new RequestContext(svcContext);
         String link = "";
-
         validateVMURL(VMURL.parseURL(link));
     }
 
@@ -113,10 +106,7 @@ public class TestProviderOperation extends ProviderOperation {
     @Test(expected = RequestFailedException.class)
     public void testValidateParameterPatternExpectFailBlankValue() throws RequestFailedException {
         MDC.put(MDC_SERVICE, "junit");
-        SvcLogicContext svcContext = new SvcLogicContext();
-        RequestContext rc = new RequestContext(svcContext);
         String link = " ";
-
         validateVMURL(VMURL.parseURL(link));
     }
 
@@ -129,10 +119,7 @@ public class TestProviderOperation extends ProviderOperation {
     @Test(expected = RequestFailedException.class)
     public void testValidateParameterPatternExpectFailBadURL() throws RequestFailedException {
         MDC.put(MDC_SERVICE, "junit");
-        SvcLogicContext svcContext = new SvcLogicContext();
-        RequestContext rc = new RequestContext(svcContext);
         String link = "http://some.host:1234/01d82c08594a4b23a0f9260c94be0c4d/";
-
         validateVMURL(VMURL.parseURL(link));
     }
 
@@ -145,11 +132,8 @@ public class TestProviderOperation extends ProviderOperation {
     @Test
     public void testValidateParameterPatternValidURL() throws RequestFailedException {
         MDC.put(MDC_SERVICE, "junit");
-        SvcLogicContext svcContext = new SvcLogicContext();
-        RequestContext rc = new RequestContext(svcContext);
         String link =
                 "http://some.host:1234/v2/01d82c08594a4b23a0f9260c94be0c4d/servers/f888f89f-096b-421e-ba36-34f714071551";
-
         validateVMURL(VMURL.parseURL(link));
     }
 
index a3479ea..9746c51 100644 (file)
  * ============LICENSE_END=========================================================
  */
 
-
-
 package org.onap.appc.adapter.iaas.impl;
 
-import com.att.cdp.exceptions.ZoneException;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.onap.appc.configuration.ConfigurationFactory;
-
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
 import java.util.HashSet;
 import java.util.Properties;
 import java.util.Set;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.CALLS_REAL_METHODS;
-import static org.mockito.Mockito.mock;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.mockito.runners.MockitoJUnitRunner;
+import org.onap.appc.configuration.ConfigurationFactory;
+import com.att.cdp.exceptions.ZoneException;
 
 /**
  * This class tests the service catalog against a known provider.
  */
+@RunWith(MockitoJUnitRunner.class)
 public class TestServiceCatalog {
 
     // Number
     private static int EXPECTED_REGIONS = 2;
-    private static int EXPECTED_ENDPOINTS = 1;
-
-    private static String PRINCIPAL;
-    private static String CREDENTIAL;
-    private static String TENANT_NAME;
-    private static String TENANT_ID;
-    private static String IDENTITY_URL;
-    private static String REGION_NAME;
 
     private ServiceCatalog catalog;
 
-    private Properties properties;
 
     @BeforeClass
     public static void before() {
         Properties props = ConfigurationFactory.getConfiguration().getProperties();
-        IDENTITY_URL = props.getProperty("provider1.identity");
-        PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc");
-        CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc");
-        TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc");
-        TENANT_ID = props.getProperty("provider1.tenant1.id",
-                props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst"));
-        REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne");
 
         EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "2"));
-        EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0"));
     }
 
     /**
@@ -82,20 +66,28 @@ public class TestServiceCatalog {
      */
     @Before
     public void setup() throws ZoneException {
-        properties = new Properties();
-        catalog = mock(ServiceCatalog.class, CALLS_REAL_METHODS);
+        catalog = Mockito.mock(ServiceCatalog.class, CALLS_REAL_METHODS);
+        Mockito.doCallRealMethod().when(catalog).trackRequest();
         catalog.rwLock = new ReentrantReadWriteLock();
-
         Set<String> testdata = new HashSet<>();
         testdata.add("RegionOne");
         catalog.regions = testdata;
     }
 
     /**
-     * Test that we find all of the expected region(s)
+     * Ensure that we set up the Region property correctly
      */
     @Test
     public void testKnownRegions() {
         assertEquals(EXPECTED_REGIONS, catalog.getRegions().size());
     }
+    
+    /**
+     * Ensure that we invoke the track request method
+     */
+    @Test
+    public void testTrackRequest() {
+       catalog.trackRequest();
+        verify(catalog,times(1)).trackRequest();
+    }
 }
index 5042b5b..5cfda5f 100644 (file)
@@ -27,6 +27,9 @@ import java.util.Properties;
 import org.junit.Assert;\r
 import org.junit.Test;\r
 \r
+/**\r
+ * This class tests the service catalog factory against a known provider.\r
+ */\r
 public class TestServiceCatalogFactory {\r
 \r
     @Test\r
@@ -85,4 +88,33 @@ public class TestServiceCatalogFactory {
 \r
         Assert.assertNull(catalog);\r
     }\r
+\r
+    @Test\r
+    public void testGetServiceCatalogEmptyURL() {\r
+        String url = null;\r
+        String tenantIdentifier = null;\r
+        String principal = null;\r
+        String credential = null;\r
+        String domain = null;\r
+        Properties properties = null;\r
+        ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential,\r
+                domain, properties);\r
+\r
+        Assert.assertNull(catalog);\r
+    }\r
+\r
+    @Test\r
+    public void testGetServiceCatalogWithoutVersion() {\r
+        String url = "http://192.168.1.1:5000/";\r
+        String tenantIdentifier = null;\r
+        String principal = null;\r
+        String credential = null;\r
+        String domain = null;\r
+        Properties properties = null;\r
+        ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential,\r
+                domain, properties);\r
+\r
+        Assert.assertNull(catalog);\r
+    }\r
+\r
 }\r
index 8021029..e0684f1 100644 (file)
@@ -26,21 +26,33 @@ package org.onap.appc.adapter.iaas.impl;
 import static org.junit.Assert.assertEquals;\r
 import static org.junit.Assert.assertFalse;\r
 import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertNull;\r
 import static org.junit.Assert.assertTrue;\r
-import com.att.cdp.exceptions.ZoneException;\r
-import com.woorea.openstack.keystone.model.Access.Service;\r
+import static org.mockito.Mockito.when;\r
+import java.util.Arrays;\r
+import java.util.HashSet;\r
 import java.util.List;\r
+import java.util.Map;\r
 import java.util.Properties;\r
+import java.util.Set;\r
 import org.junit.Before;\r
 import org.junit.BeforeClass;\r
 import org.junit.Ignore;\r
 import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
+import org.mockito.Mock;\r
+import org.mockito.runners.MockitoJUnitRunner;\r
 import org.onap.appc.configuration.ConfigurationFactory;\r
+import com.att.cdp.exceptions.ZoneException;\r
+import com.google.common.collect.ImmutableMap;\r
+import com.woorea.openstack.keystone.model.Access.Service;\r
+import com.woorea.openstack.keystone.model.Access.Service.Endpoint;\r
+import com.woorea.openstack.keystone.model.Tenant;\r
 \r
 /**\r
  * This class tests the service catalog against a known provider.\r
  */\r
-@Ignore\r
+@RunWith(MockitoJUnitRunner.class)\r
 public class TestServiceCatalogV2 {\r
 \r
     // Number\r
@@ -53,14 +65,30 @@ public class TestServiceCatalogV2 {
     private static String TENANT_ID;\r
     private static String IDENTITY_URL;\r
     private static String REGION_NAME;\r
+    private static String PUBLIC_URL;\r
+\r
+    private static String IP;\r
+    private static String PORT;\r
+    private static String TENANTID;\r
+    private static String VMID;\r
+    private static String URL;\r
 \r
     private ServiceCatalogV2 catalog;\r
 \r
     private Properties properties;\r
 \r
+    @Mock\r
+    private Tenant tenant;\r
+\r
+    private final Set<String> regions = new HashSet<>(Arrays.asList("RegionOne"));\r
+\r
+    private Map<String, Service> serviceTypes;\r
+\r
+    private Map<String, List<Service.Endpoint>> serviceEndpoints;\r
+\r
     @BeforeClass\r
     public static void before() {\r
-        Properties props = ConfigurationFactory.getConfiguration().getProperties();\r
+        final Properties props = ConfigurationFactory.getConfiguration().getProperties();\r
         IDENTITY_URL = props.getProperty("provider1.identity", "appc");\r
         PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc");\r
         CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc");\r
@@ -69,42 +97,70 @@ public class TestServiceCatalogV2 {
                 props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst"));\r
         REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne");\r
 \r
+        IP = props.getProperty("test.ip");\r
+        PORT = props.getProperty("test.port");\r
+        TENANTID = props.getProperty("test.tenantid");\r
+        VMID = props.getProperty("test.vmid");\r
+\r
         EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0"));\r
         EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0"));\r
+\r
+        PUBLIC_URL =\r
+                "http://192.168.1.2:5000/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";\r
     }\r
 \r
     /**\r
-     * Setup the test environment by loading a new service catalog for each test\r
+     * Setup the test environment by loading a new service catalog for each test Use reflection to\r
+     * locate fields and methods so that they can be manipulated during the test to change the\r
+     * internal state accordingly.\r
      * \r
-     * @throws ZoneException\r
      */\r
     @Before\r
-    public void setup() throws ZoneException {\r
+    public void setup() {\r
+        URL = String.format("http://%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID);\r
         properties = new Properties();\r
         catalog = new ServiceCatalogV2(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, properties);\r
-        catalog.init();\r
+        final Service service = new Service();\r
+        serviceTypes = ImmutableMap.<String, Service>builder().put(ServiceCatalog.COMPUTE_SERVICE, service)\r
+                .put(ServiceCatalog.IDENTITY_SERVICE, service).put(ServiceCatalog.IMAGE_SERVICE, service)\r
+                .put(ServiceCatalog.NETWORK_SERVICE, service).put(ServiceCatalog.VOLUME_SERVICE, service).build();\r
+        Map<String, Object> endpointPrivateFields =\r
+                ImmutableMap.<String, Object>builder().put("publicURL", PUBLIC_URL).put("region", REGION_NAME).build();\r
+        Service.Endpoint endpoint = new Service.Endpoint();\r
+        CommonUtility.injectMockObjects(endpointPrivateFields, endpoint);\r
+        final List<Service.Endpoint> endpoints = Arrays.asList(endpoint);\r
+        serviceEndpoints = ImmutableMap.<String, List<Service.Endpoint>>builder()\r
+                .put(ServiceCatalog.COMPUTE_SERVICE, endpoints).build();\r
+        Map<String, Object> privateFields =\r
+                ImmutableMap.<String, Object>builder().put("regions", regions).put("tenant", tenant)\r
+                        .put("serviceTypes", serviceTypes).put("serviceEndpoints", serviceEndpoints).build();\r
+        CommonUtility.injectMockObjects(privateFields, catalog);\r
+        CommonUtility.injectMockObjectsInBaseClass(privateFields, catalog);\r
+\r
     }\r
 \r
     /**\r
-     * Test that the tenant name and ID are returned correctly\r
+     * Ensure that we get the Tenant Name & Tenant Id property are returned correctly\r
      */\r
     @Test\r
     public void testKnownTenant() {\r
+        when(tenant.getName()).thenReturn(TENANT_NAME);\r
+        when(tenant.getId()).thenReturn(TENANT_ID);\r
         assertEquals(TENANT_NAME, catalog.getProjectName());\r
         assertEquals(TENANT_ID, catalog.getProjectId());\r
     }\r
 \r
     /**\r
-     * Test that we find all of the expected region(s)\r
+     * Ensure that we set up the Region property correctly\r
      */\r
     @Test\r
     public void testKnownRegions() {\r
         assertEquals(EXPECTED_REGIONS, catalog.getRegions().size());\r
-        // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]);\r
+        assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]);\r
     }\r
 \r
     /**\r
-     * Test that we can check for published services correctly\r
+     * Ensure that that we can check for published services correctly\r
      */\r
     @Test\r
     public void testServiceTypesPublished() {\r
@@ -113,40 +169,59 @@ public class TestServiceCatalogV2 {
     }\r
 \r
     /**\r
-     * Check that we can get the list of published services\r
+     * Ensure that we can get the list of published services\r
      */\r
     @Test\r
     public void testPublishedServicesList() {\r
-        // List<String> services = catalog.getServiceTypes();\r
-\r
-        // assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE));\r
-        // assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE));\r
-        // assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE));\r
-        // assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE));\r
-        // assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE));\r
+        final List<String> services = catalog.getServiceTypes();\r
+        assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE));\r
+        assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE));\r
+        assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE));\r
+        assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE));\r
+        assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE));\r
     }\r
 \r
     /**\r
-     * Test that we can get the endpoint(s) for a service\r
+     * Ensure that we can get the endpoint(s) for a service\r
      */\r
     @Test\r
     public void testEndpointList() {\r
-        List<Service.Endpoint> endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE);\r
-\r
+        List<Endpoint> endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE);\r
         assertNotNull(endpoints);\r
         assertFalse(endpoints.isEmpty());\r
         assertEquals(EXPECTED_ENDPOINTS, endpoints.size());\r
-\r
-        Service.Endpoint endpoint = endpoints.get(0);\r
-        // assertEquals(REGION_NAME, endpoint.getRegion());\r
     }\r
 \r
+    /**\r
+     * Ensure that we override the toString method\r
+     */\r
     @Test\r
     public void testToString() {\r
-        String testString = catalog.toString();\r
+        when(tenant.getId()).thenReturn(TENANT_ID);\r
+        when(tenant.getDescription()).thenReturn("Tenant one");\r
+        final String testString = catalog.toString();\r
         assertNotNull(testString);\r
     }\r
 \r
+    /**\r
+     * Ensure that we can get the VM Region\r
+     */\r
+    @Test\r
+    public void testGetVMRegion() {\r
+        VMURL url = VMURL.parseURL(URL);\r
+        String region = catalog.getVMRegion(url);\r
+        assertEquals(REGION_NAME, region);\r
+    }\r
+\r
+    /**\r
+     * Ensure that we can get the null region when no URL is passed\r
+     */\r
+    @Test\r
+    public void testGetVMRegionWithoutURL() {\r
+        String region = catalog.getVMRegion(null);\r
+        assertNull(region);\r
+    }\r
+\r
     @Ignore\r
     @Test\r
     public void liveConnectionTest() {\r
index 0b62b4e..a5deb73 100644 (file)
  * ============LICENSE_END=========================================================\r
  */\r
 \r
-\r
-\r
 package org.onap.appc.adapter.iaas.impl;\r
 \r
 import static org.junit.Assert.assertEquals;\r
 import static org.junit.Assert.assertFalse;\r
 import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertNull;\r
 import static org.junit.Assert.assertTrue;\r
-import com.att.cdp.exceptions.ZoneException;\r
-import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint;\r
+import static org.mockito.Mockito.when;\r
+import java.util.Arrays;\r
+import java.util.HashSet;\r
 import java.util.List;\r
+import java.util.Map;\r
 import java.util.Properties;\r
+import java.util.Set;\r
 import org.junit.Before;\r
 import org.junit.BeforeClass;\r
 import org.junit.Ignore;\r
 import org.junit.Test;\r
+import org.junit.runner.RunWith;\r
+import org.mockito.Mockito;\r
+import org.mockito.runners.MockitoJUnitRunner;\r
 import org.onap.appc.configuration.ConfigurationFactory;\r
+import com.google.common.collect.ImmutableMap;\r
+import com.woorea.openstack.keystone.v3.model.Token;\r
+import com.woorea.openstack.keystone.v3.model.Token.Service;\r
+import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint;\r
 \r
 /**\r
  * This class tests the service catalog against a known provider.\r
  */\r
-@Ignore\r
+@RunWith(MockitoJUnitRunner.class)\r
 public class TestServiceCatalogV3 {\r
 \r
     // Number\r
@@ -56,11 +65,28 @@ public class TestServiceCatalogV3 {
     private static String TENANT_ID;\r
     private static String IDENTITY_URL;\r
     private static String REGION_NAME;\r
+    private static String PUBLIC_URL;\r
+\r
+    private static String IP;\r
+    private static String PORT;\r
+    private static String TENANTID;\r
+    private static String VMID;\r
+    private static String URL;\r
 \r
     private ServiceCatalogV3 catalog;\r
 \r
+    private ServiceCatalogV3 spyCatalog;\r
+\r
     private Properties properties;\r
 \r
+    private Token.Project project = new Token.Project();\r
+\r
+    private final Set<String> regions = new HashSet<>(Arrays.asList("RegionOne"));\r
+\r
+    private Map<String, Service> serviceTypes;\r
+\r
+    private Map<String, List<Service.Endpoint>> serviceEndpoints;\r
+\r
     @BeforeClass\r
     public static void before() {\r
         Properties props = ConfigurationFactory.getConfiguration().getProperties();\r
@@ -73,41 +99,68 @@ public class TestServiceCatalogV3 {
                 props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst"));\r
         REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne");\r
 \r
+        IP = props.getProperty("test.ip");\r
+        PORT = props.getProperty("test.port");\r
+        TENANTID = props.getProperty("test.tenantid");\r
+        VMID = props.getProperty("test.vmid");\r
+\r
         EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0"));\r
         EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0"));\r
+        PUBLIC_URL =\r
+                "http://192.168.1.2:5000/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345";\r
+\r
     }\r
 \r
     /**\r
-     * Setup the test environment by loading a new service catalog for each test\r
-     * \r
-     * @throws ZoneException\r
+     * Use reflection to locate fields and methods so that they can be manipulated during the test\r
+     * to change the internal state accordingly.\r
      */\r
     @Before\r
-    public void setup() throws ZoneException {\r
+    public void setup() {\r
+        URL = String.format("http://%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID);\r
         properties = new Properties();\r
         catalog = new ServiceCatalogV3(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, DOMAIN, properties);\r
+        spyCatalog = Mockito.spy(catalog);\r
+        project.setId(TENANT_ID);\r
+        project.setName(TENANT_NAME);\r
+        final Service service = new Service();\r
+        serviceTypes = ImmutableMap.<String, Service>builder().put(ServiceCatalog.COMPUTE_SERVICE, service)\r
+                .put(ServiceCatalog.IDENTITY_SERVICE, service).put(ServiceCatalog.IMAGE_SERVICE, service)\r
+                .put(ServiceCatalog.NETWORK_SERVICE, service).put(ServiceCatalog.VOLUME_SERVICE, service).build();\r
+        final Service.Endpoint endpoint = new Service.Endpoint();\r
+        endpoint.setUrl(PUBLIC_URL);\r
+        endpoint.setRegion(REGION_NAME);\r
+        final List<Service.Endpoint> endpoints = Arrays.asList(endpoint);\r
+        serviceEndpoints = ImmutableMap.<String, List<Service.Endpoint>>builder()\r
+                .put(ServiceCatalog.COMPUTE_SERVICE, endpoints).build();\r
+        Map<String, Object> privateFields =\r
+                ImmutableMap.<String, Object>builder().put("project", project).put("regions", regions)\r
+                        .put("serviceTypes", serviceTypes).put("serviceEndpoints", serviceEndpoints).build();\r
+        CommonUtility.injectMockObjects(privateFields, catalog);\r
+        CommonUtility.injectMockObjectsInBaseClass(privateFields, catalog);\r
     }\r
 \r
     /**\r
-     * Test that the tenant name and ID are returned correctly\r
+     * Ensure that we get the Tenant Name & Tenant Id property are returned correctly\r
      */\r
     @Test\r
     public void testKnownTenant() {\r
+        when(spyCatalog.getProject()).thenReturn(project);\r
         assertEquals(TENANT_NAME, catalog.getProjectName());\r
         assertEquals(TENANT_ID, catalog.getProjectId());\r
     }\r
 \r
     /**\r
-     * Test that we find all of the expected region(s)\r
+     * Ensure that we set up the Region property correctly\r
      */\r
     @Test\r
     public void testKnownRegions() {\r
         assertEquals(EXPECTED_REGIONS, catalog.getRegions().size());\r
-        // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]);\r
+        assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]);\r
     }\r
 \r
     /**\r
-     * Test that we can check for published services correctly\r
+     * Ensure that that we can check for published services correctly\r
      */\r
     @Test\r
     public void testServiceTypesPublished() {\r
@@ -116,12 +169,11 @@ public class TestServiceCatalogV3 {
     }\r
 \r
     /**\r
-     * Check that we can get the list of published services\r
+     * Ensure that we can get the list of published services\r
      */\r
     @Test\r
     public void testPublishedServicesList() {\r
         List<String> services = catalog.getServiceTypes();\r
-\r
         assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE));\r
         assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE));\r
         assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE));\r
@@ -130,26 +182,44 @@ public class TestServiceCatalogV3 {
     }\r
 \r
     /**\r
-     * Test that we can get the endpoint(s) for a service\r
+     * Ensure that we can get the endpoint(s) for a service\r
      */\r
     @Test\r
     public void testEndpointList() {\r
         List<Endpoint> endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE);\r
-\r
         assertNotNull(endpoints);\r
         assertFalse(endpoints.isEmpty());\r
         assertEquals(EXPECTED_ENDPOINTS, endpoints.size());\r
-\r
-        Endpoint endpoint = endpoints.get(0);\r
-        // assertEquals(REGION_NAME, endpoint.getRegion());\r
     }\r
 \r
+    /**\r
+     * Ensure that we override the toString method\r
+     */\r
     @Test\r
     public void testToString() {\r
         String testString = catalog.toString();\r
         assertNotNull(testString);\r
     }\r
 \r
+    /**\r
+     * Ensure that we can get the VM Region\r
+     */\r
+    @Test\r
+    public void testGetVMRegion() {\r
+        VMURL url = VMURL.parseURL(URL);\r
+        String region = catalog.getVMRegion(url);\r
+        assertEquals(REGION_NAME, region);\r
+    }\r
+\r
+    /**\r
+     * Ensure that we can get the null region when no URL is passed\r
+     */\r
+    @Test\r
+    public void testGetVMRegionWithoutURL() {\r
+        String region = catalog.getVMRegion(null);\r
+        assertNull(region);\r
+    }\r
+\r
     @Ignore\r
     @Test\r
     public void liveConnectionTest() {\r
diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestTenantCache.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestTenantCache.java
new file mode 100644 (file)
index 0000000..449db89
--- /dev/null
@@ -0,0 +1,223 @@
+/*
+ * ============LICENSE_START======================================================= Copyright (C)
+ * 2016-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.iaas.impl;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.when;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+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.Constants;
+import org.onap.appc.configuration.Configuration;
+import org.onap.appc.configuration.ConfigurationFactory;
+import org.onap.appc.pool.Pool;
+import com.att.cdp.exceptions.ContextConnectionException;
+import com.att.cdp.exceptions.ZoneException;
+import com.att.cdp.zones.Context;
+import com.google.common.collect.ImmutableMap;
+
+/**
+ * This class is used to test methods and functions of the Tenant cache
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class TestTenantCache {
+
+    private TenantCache tenantCache;
+
+    private VMURL url;
+
+    @Mock
+    private ServiceCatalog catalog;
+
+    @Mock
+    private Context context;
+
+    @Mock
+    Pool<Context> pool;
+
+    private ProviderCache provider;
+
+    private static String TENANT_NAME;
+    private static String TENANT_ID;
+    private static String IDENTITY_URL;
+    private static String REGION_NAME;
+    private static String CREDENTIAL;
+    private static String DOMAIN;
+
+    protected Set<String> regions = new HashSet<>(Arrays.asList("RegionOne"));
+
+    @BeforeClass
+    public static void before() {
+        Properties props = ConfigurationFactory.getConfiguration().getProperties();
+        IDENTITY_URL = props.getProperty("provider1.identity");
+        TENANT_NAME = props.getProperty("provider1.tenant1.name", "appc");
+        TENANT_ID = props.getProperty("provider1.tenant1.id",
+                props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst"));
+        DOMAIN = props.getProperty("provider1.tenant1.domain", "Default");
+        CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc");
+        REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne");
+    }
+
+    @Before
+    public void setup() {
+        Configuration props = ConfigurationFactory.getConfiguration();
+        props.setProperty(Constants.PROPERTY_RETRY_LIMIT, "3");
+        provider = new ProviderCache();
+        provider.setIdentityURL(IDENTITY_URL);
+        tenantCache = new TenantCache(provider);
+        tenantCache.setDomain(DOMAIN);
+        tenantCache.setPassword(CREDENTIAL);
+        tenantCache.setTenantId(TENANT_ID);
+        tenantCache.setTenantName(TENANT_NAME);
+        tenantCache.setUserid(CREDENTIAL);
+        props.setProperty(Constants.PROPERTY_RETRY_DELAY, "1");
+        Map<String, Object> privateFields = ImmutableMap.<String, Object>builder().put("catalog", catalog).build();
+        CommonUtility.injectMockObjects(privateFields, tenantCache);
+    }
+
+    @Test
+    public void testDetermineRegion() {
+        when(catalog.getVMRegion(url)).thenReturn(REGION_NAME);
+        assertEquals(REGION_NAME, tenantCache.determineRegion(url));
+    }
+
+    @Test
+    public void testDestroy() {
+        TenantCache spy = Mockito.spy(tenantCache);
+        spy.destroy(context, pool);
+    }
+
+    @Test
+    public void testDestroyWithException() throws IOException {
+        doThrow(new IOException("I/O Exception occured while closing context")).when(context).close();
+        TenantCache spy = Mockito.spy(tenantCache);
+        spy.destroy(context, pool);
+    }
+
+    @Test
+    public void testInitialize() {
+        TenantCache spyTenant = Mockito.spy(tenantCache);
+        when(catalog.getRegions()).thenReturn(regions);
+        when(catalog.getProjectId()).thenReturn(TENANT_ID);
+        when(catalog.getProjectName()).thenReturn(TENANT_NAME);
+        spyTenant.initialize();
+    }
+
+    @Test
+    public void testInitializeWithOverLimit() {
+        Configuration props = ConfigurationFactory.getConfiguration();
+        props.setProperty(Constants.PROPERTY_RETRY_LIMIT, "1");
+        TenantCache spyTenant = Mockito.spy(tenantCache);
+        when(spyTenant.getServiceCatalogFactory(anyString(), anyString(), anyObject())).thenReturn(catalog);
+        when(spyTenant.getTenantName()).thenReturn(TENANT_NAME);
+        when(catalog.getRegions()).thenReturn(regions);
+        spyTenant.initialize();
+    }
+
+    @Test
+    public void testInitializeWithContextConnectionException() throws ZoneException {
+        Configuration props = ConfigurationFactory.getConfiguration();
+        props.setProperty(Constants.PROPERTY_RETRY_LIMIT, "2");
+        props.setProperty(Constants.PROPERTY_RETRY_DELAY, "1");
+        doThrow(new ContextConnectionException("Contex Connection Exception")).when(catalog).init();
+        TenantCache spyTenant = Mockito.spy(tenantCache);
+        spyTenant.initialize();
+    }
+
+    @Test
+    public void testInitializeWithZoneException() throws ZoneException {
+        Configuration props = ConfigurationFactory.getConfiguration();
+        props.setProperty(Constants.PROPERTY_RETRY_LIMIT, "2");
+        props.setProperty(Constants.PROPERTY_RETRY_DELAY, "1");
+        doThrow(new ZoneException("Zone Exception")).when(catalog).init();
+        TenantCache spyTenant = Mockito.spy(tenantCache);
+        when(spyTenant.getServiceCatalogFactory(anyString(), anyString(), anyObject())).thenReturn(catalog);
+        spyTenant.initialize();
+    }
+
+    /**
+     * Ensure that we set up the Domain property correctly
+     */
+    @Test
+    public void testDomainProperty() {
+        assertEquals(DOMAIN, tenantCache.getDomain());
+    }
+
+    /**
+     * Ensure that we set up the Provider property correctly
+     */
+    @Test
+    public void testProviderProperty() {
+        assertEquals(provider, tenantCache.getProvider());
+    }
+
+    /**
+     * Ensure that we set up the Password property correctly
+     */
+    @Test
+    public void testPasswordProperty() {
+        assertEquals(CREDENTIAL, tenantCache.getPassword());
+    }
+
+    /**
+     * Ensure that we set up the Tenant Id property correctly
+     */
+    @Test
+    public void testTenantIdProperty() {
+        assertEquals(TENANT_ID, tenantCache.getTenantId());
+    }
+
+    /**
+     * Ensure that we set up the Tenant Name property correctly
+     */
+    @Test
+    public void testTenantNameProperty() {
+        assertEquals(TENANT_NAME, tenantCache.getTenantName());
+    }
+
+    /**
+     * Ensure that we set up the User Id property correctly
+     */
+    @Test
+    public void testUserIdProperty() {
+        assertEquals(CREDENTIAL, tenantCache.getUserid());
+    }
+
+    /**
+     * Ensure that we set up the Pools property correctly
+     */
+    @Test
+    public void testPoolsProperty() {
+        assertNotNull(tenantCache.getPools());
+    }
+}
index d0c1574..77c0e42 100644 (file)
@@ -21,8 +21,6 @@
  * ============LICENSE_END=========================================================
  */
 
-
-
 package org.onap.appc.adapter.iaas.impl;
 
 import static org.junit.Assert.assertEquals;
@@ -31,9 +29,10 @@ import static org.junit.Assert.assertNull;
 import java.util.Properties;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.onap.appc.adapter.iaas.impl.VMURL;
 import org.onap.appc.configuration.ConfigurationFactory;
-
+/**
+ * This class is used to test methods and functions of the VMURL
+ */
 public class TestVMURL {
 
     private static String IP;
@@ -41,6 +40,7 @@ public class TestVMURL {
     private static String TENANTID;
     private static String VMID;
     private static String URL;
+    private static String VERSION;
 
     @BeforeClass
     public static void before() {
@@ -49,6 +49,7 @@ public class TestVMURL {
         PORT = props.getProperty("test.port");
         TENANTID = props.getProperty("test.tenantid");
         VMID = props.getProperty("test.vmid");
+        VERSION = props.getProperty("test.version");
     }
 
     /**
@@ -64,6 +65,7 @@ public class TestVMURL {
         assertEquals(PORT, url.getPort());
         assertEquals(TENANTID, url.getTenantId());
         assertEquals(VMID, url.getServerId());
+        assertEquals(VERSION, url.getVersion());
         assertEquals(url.toString(), URL);
     }
 
@@ -77,6 +79,7 @@ public class TestVMURL {
         assertNull(url.getPath());
         assertEquals(TENANTID, url.getTenantId());
         assertEquals(VMID, url.getServerId());
+        assertEquals(VERSION, url.getVersion());
         assertEquals(url.toString(), URL);
     }
 
index ab1be37..6ecf278 100644 (file)
@@ -91,7 +91,7 @@ provider1.type=appc
 provider1.name=appc
 
 #These you can change
-provider1.identity=appc
+provider1.identity=http://localhost:9081/v2.0
 provider1.tenant1.name=appc
 provider1.tenant1.userid=appc
 provider1.tenant1.password=appc
@@ -108,4 +108,5 @@ test.tenantid=abcde12345fghijk6789lmnopq123rst
 test.vmid=abc12345-1234-5678-890a-abcdefg12345
 # Port 8774 below is default port for OpenStack's Nova API Service
 test.url=http://192.168.1.2:8774/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345
+test.version=v2