From dda9213466af575725b3e0b734c1fe70b1e2944f Mon Sep 17 00:00:00 2001 From: Lathishbabu Ganesan Date: Mon, 28 May 2018 11:07:44 +0100 Subject: [PATCH] Unit test cases for iaas impl package Change-Id: Iac6167dca83413b7533cb65a73775a616866589c Issue-ID: APPC-436 Signed-off-by: Lathishbabu Ganesan --- .../adapter/iaas/impl/ProviderAdapterImpl.java | 3 +- .../adapter/iaas/impl/ServiceCatalogFactory.java | 16 +- .../appc/adapter/iaas/impl/ServiceCatalogV3.java | 45 +- .../onap/appc/adapter/iaas/impl/TenantCache.java | 25 +- .../onap/appc/adapter/iaas/impl/CommonUtility.java | 72 ++ .../iaas/impl/RequestFailedExceptionTest.java | 24 +- .../appc/adapter/iaas/impl/TestIdentityUrl.java | 2 - .../adapter/iaas/impl/TestProviderAdapterImpl.java | 972 +++++++-------------- .../appc/adapter/iaas/impl/TestProviderCache.java | 117 +++ .../adapter/iaas/impl/TestProviderOperation.java | 26 +- .../appc/adapter/iaas/impl/TestServiceCatalog.java | 58 +- .../iaas/impl/TestServiceCatalogFactory.java | 32 + .../adapter/iaas/impl/TestServiceCatalogV2.java | 129 ++- .../adapter/iaas/impl/TestServiceCatalogV3.java | 110 ++- .../appc/adapter/iaas/impl/TestTenantCache.java | 223 +++++ .../org/onap/appc/adapter/iaas/impl/TestVMURL.java | 11 +- .../resources/org/onap/appc/default.properties | 3 +- 17 files changed, 1050 insertions(+), 818 deletions(-) create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/CommonUtility.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderCache.java create mode 100644 appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestTenantCache.java diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java index 79d7aa569..36191dd5a 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ProviderAdapterImpl.java @@ -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

*/ + factory = ProviderOperationFactory.getInstance(); providerCache = new HashMap<>(); Properties properties = configuration.getProperties(); List providers = StructuredPropertyHelper.getStructuredProperties(properties, Property.PROVIDER); diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java index a4be23349..74d87571b 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogFactory.java @@ -51,18 +51,12 @@ public class ServiceCatalogFactory { return null; } String version = idUrl.getVersion(); - if(version == null){ - logger.error("Invalid Identity URL check configuration"); - return null; - } String prefix = version.split("\\.")[0]; - if (prefix != null) { - switch (prefix) { - case "v2": - return new ServiceCatalogV2(url, projectIdentifier, principal, credential, properties); - case "v3": - return new ServiceCatalogV3(url, projectIdentifier, principal, credential, domain, properties); - } + if("v2".equals(prefix)){ + return new ServiceCatalogV2(url, projectIdentifier, principal, credential, properties); + } + else if("v3".equals(prefix)){ + return new ServiceCatalogV3(url, projectIdentifier, principal, credential, domain, properties); } return null; } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java index 1e057d147..4773603c3 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/ServiceCatalogV3.java @@ -23,13 +23,25 @@ package org.onap.appc.adapter.iaas.impl; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import com.att.cdp.exceptions.ContextConnectionException; import com.att.cdp.exceptions.ZoneException; import com.att.cdp.openstack.util.ExceptionMapper; import com.att.cdp.pal.util.Time; import com.att.cdp.zones.ContextFactory; import com.att.cdp.zones.spi.RequestState; -import com.google.common.collect.Lists; import com.woorea.openstack.base.client.OpenStackBaseException; import com.woorea.openstack.base.client.OpenStackClientConnector; import com.woorea.openstack.base.client.OpenStackSimpleTokenProvider; @@ -42,19 +54,6 @@ import com.woorea.openstack.keystone.v3.model.Token; import com.woorea.openstack.keystone.v3.model.Token.Project; import com.woorea.openstack.keystone.v3.model.Token.Service; import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.regex.Matcher; -import java.util.regex.Pattern; /** * This class is used to capture and cache the service catalog for a specific OpenStack provider. @@ -225,13 +224,7 @@ public class ServiceCatalogV3 extends ServiceCatalog { */ @Override public String getProjectName() { - Lock readLock = rwLock.readLock(); - readLock.lock(); - try { - return project.getName(); - } finally { - readLock.unlock(); - } + return getProject().getName(); } /** @@ -403,4 +396,14 @@ public class ServiceCatalogV3 extends ServiceCatalog { } return now.getTime(); } + + public Project getProject() { + Lock readLock = rwLock.readLock(); + readLock.lock(); + try { + return project; + } finally { + readLock.unlock(); + } + } } \ No newline at end of file diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java index c99889ce4..29b9cd314 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/main/java/org/onap/appc/adapter/iaas/impl/TenantCache.java @@ -23,13 +23,6 @@ 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, Destructor { configuration = ConfigurationFactory.getConfiguration(); logger = EELFManager.getInstance().getLogger(getClass()); this.provider = provider; - configuration = ConfigurationFactory.getConfiguration(); } /** @@ -157,12 +156,10 @@ public class TenantCache implements Allocator, Destructor { 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, Destructor { } } + 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 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 index 000000000..0d4fe2391 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/CommonUtility.java @@ -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 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 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 + } + }); + } + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/RequestFailedExceptionTest.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/RequestFailedExceptionTest.java index d609fd4a8..81fa87714 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/RequestFailedExceptionTest.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/RequestFailedExceptionTest.java @@ -22,10 +22,12 @@ package org.onap.appc.adapter.iaas.impl; import org.glassfish.grizzly.http.util.HttpStatus; import org.junit.Assert; import org.junit.Test; - import com.att.cdp.zones.model.Server; import com.att.cdp.zones.model.Stack; +/** + * This class is used to test methods and functions of the Request Failed Exception class + */ public class RequestFailedExceptionTest { @Test @@ -48,6 +50,7 @@ public class RequestFailedExceptionTest { @Test public void testRequestFailedExceptionStringStringHttpStatusServer() { Server server=new Server(); + server.setId("svrId"); HttpStatus status=HttpStatus.OK_200; String reason="Success"; String operation="POST"; @@ -56,10 +59,12 @@ public class RequestFailedExceptionTest { requestFailedException.setReason(reason); requestFailedException.setServerId("svrId"); requestFailedException.setStatus(status); + requestFailedException.setServer(server); Assert.assertEquals("POST",requestFailedException.getOperation()); Assert.assertEquals("Success",requestFailedException.getReason()); Assert.assertEquals("svrId",requestFailedException.getServerId()); Assert.assertEquals( HttpStatus.OK_200,requestFailedException.getStatus()); + Assert.assertEquals(server, requestFailedException.getServer()); } @Test @@ -120,4 +125,21 @@ public class RequestFailedExceptionTest { Assert.assertTrue(requestFailedException.getLocalizedMessage().contains(message)); Assert.assertTrue(requestFailedException.getMessage().contains(message)); } + + /** + * This test case is used to test the request failed exception class without server + * + */ + @Test + public void testRequestFailedExceptionThrowableStringWithoutServer() { + String tMessage = "throwable message"; + Server server = null; + HttpStatus status = HttpStatus.ACCEPTED_202; + String reason = "Success"; + String operation = "POST"; + Throwable throwable = new Throwable(tMessage); + RequestFailedException requestFailedException = new RequestFailedException(throwable, operation, reason, status, server); + Assert.assertEquals(throwable, requestFailedException.getCause()); + Assert.assertNull(requestFailedException.getServer()); + } } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java index 2b13d07ae..09156bf11 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestIdentityUrl.java @@ -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 { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java index 4b159f2d7..30c7aa729 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderAdapterImpl.java @@ -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 providerCache; + + private SvcLogicContext svcContext; - private ProviderAdapterImpl adapter; + private Map 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 privateFields = ImmutableMap.builder().put("factory", factory) + .put("providerCache", getProviderCache()).build(); + CommonUtility.injectMockObjects(privateFields, adapter); + } + + private Map getProviderCache() { + providerCache = new HashMap(); + 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 providerCaches = (Map) 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 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 serviceTypes = catalog.getServiceTypes(); - assertNotNull(serviceTypes); - assertEquals(12, serviceTypes.size()); - - assertEquals(TENANT_NAME, catalog.getProjectName()); - assertEquals(TENANT_ID, catalog.getProjectId()); - - Set 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 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 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 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 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 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 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 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 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. - *

- * 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. - *

+ * 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 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 fetchOperation = operation -> { + if (operation.equals(Operation.EVACUATE_SERVICE)) + return evacuateServer; + else + return providerOperation; + }; + + Function fetchServer = status -> { + server.setStatus(status); + return server; + }; + + BiFunction 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 index 000000000..b41273855 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderCache.java @@ -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 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 regions = new HashSet<>(Arrays.asList("RegionOne")); + + private Map tenants = new HashMap(); + + @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 privateFields = ImmutableMap.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)); + } + +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java index 98ab7ba7a..0cb25e95c 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestProviderOperation.java @@ -23,18 +23,17 @@ 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)); } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java index a3479ea38..9746c51a3 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalog.java @@ -21,58 +21,42 @@ * ============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 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(); + } } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java index 5042b5b43..5cfda5f6e 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogFactory.java @@ -27,6 +27,9 @@ import java.util.Properties; import org.junit.Assert; import org.junit.Test; +/** + * This class tests the service catalog factory against a known provider. + */ public class TestServiceCatalogFactory { @Test @@ -85,4 +88,33 @@ public class TestServiceCatalogFactory { Assert.assertNull(catalog); } + + @Test + public void testGetServiceCatalogEmptyURL() { + String url = null; + String tenantIdentifier = null; + String principal = null; + String credential = null; + String domain = null; + Properties properties = null; + ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, + domain, properties); + + Assert.assertNull(catalog); + } + + @Test + public void testGetServiceCatalogWithoutVersion() { + String url = "http://192.168.1.1:5000/"; + String tenantIdentifier = null; + String principal = null; + String credential = null; + String domain = null; + Properties properties = null; + ServiceCatalog catalog = ServiceCatalogFactory.getServiceCatalog(url, tenantIdentifier, principal, credential, + domain, properties); + + Assert.assertNull(catalog); + } + } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java index 802102978..e0684f135 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV2.java @@ -26,21 +26,33 @@ package org.onap.appc.adapter.iaas.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import com.att.cdp.exceptions.ZoneException; -import com.woorea.openstack.keystone.model.Access.Service; +import static org.mockito.Mockito.when; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Properties; +import java.util.Set; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import org.onap.appc.configuration.ConfigurationFactory; +import com.att.cdp.exceptions.ZoneException; +import com.google.common.collect.ImmutableMap; +import com.woorea.openstack.keystone.model.Access.Service; +import com.woorea.openstack.keystone.model.Access.Service.Endpoint; +import com.woorea.openstack.keystone.model.Tenant; /** * This class tests the service catalog against a known provider. */ -@Ignore +@RunWith(MockitoJUnitRunner.class) public class TestServiceCatalogV2 { // Number @@ -53,14 +65,30 @@ public class TestServiceCatalogV2 { private static String TENANT_ID; private static String IDENTITY_URL; private static String REGION_NAME; + private static String PUBLIC_URL; + + private static String IP; + private static String PORT; + private static String TENANTID; + private static String VMID; + private static String URL; private ServiceCatalogV2 catalog; private Properties properties; + @Mock + private Tenant tenant; + + private final Set regions = new HashSet<>(Arrays.asList("RegionOne")); + + private Map serviceTypes; + + private Map> serviceEndpoints; + @BeforeClass public static void before() { - Properties props = ConfigurationFactory.getConfiguration().getProperties(); + final Properties props = ConfigurationFactory.getConfiguration().getProperties(); IDENTITY_URL = props.getProperty("provider1.identity", "appc"); PRINCIPAL = props.getProperty("provider1.tenant1.userid", "appc"); CREDENTIAL = props.getProperty("provider1.tenant1.password", "appc"); @@ -69,42 +97,70 @@ public class TestServiceCatalogV2 { props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); + IP = props.getProperty("test.ip"); + PORT = props.getProperty("test.port"); + TENANTID = props.getProperty("test.tenantid"); + VMID = props.getProperty("test.vmid"); + EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0")); EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); + + PUBLIC_URL = + "http://192.168.1.2:5000/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; } /** - * Setup the test environment by loading a new service catalog for each test + * Setup the test environment by loading a new service catalog for each test Use reflection to + * locate fields and methods so that they can be manipulated during the test to change the + * internal state accordingly. * - * @throws ZoneException */ @Before - public void setup() throws ZoneException { + public void setup() { + URL = String.format("http://%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID); properties = new Properties(); catalog = new ServiceCatalogV2(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, properties); - catalog.init(); + final Service service = new Service(); + serviceTypes = ImmutableMap.builder().put(ServiceCatalog.COMPUTE_SERVICE, service) + .put(ServiceCatalog.IDENTITY_SERVICE, service).put(ServiceCatalog.IMAGE_SERVICE, service) + .put(ServiceCatalog.NETWORK_SERVICE, service).put(ServiceCatalog.VOLUME_SERVICE, service).build(); + Map endpointPrivateFields = + ImmutableMap.builder().put("publicURL", PUBLIC_URL).put("region", REGION_NAME).build(); + Service.Endpoint endpoint = new Service.Endpoint(); + CommonUtility.injectMockObjects(endpointPrivateFields, endpoint); + final List endpoints = Arrays.asList(endpoint); + serviceEndpoints = ImmutableMap.>builder() + .put(ServiceCatalog.COMPUTE_SERVICE, endpoints).build(); + Map privateFields = + ImmutableMap.builder().put("regions", regions).put("tenant", tenant) + .put("serviceTypes", serviceTypes).put("serviceEndpoints", serviceEndpoints).build(); + CommonUtility.injectMockObjects(privateFields, catalog); + CommonUtility.injectMockObjectsInBaseClass(privateFields, catalog); + } /** - * Test that the tenant name and ID are returned correctly + * Ensure that we get the Tenant Name & Tenant Id property are returned correctly */ @Test public void testKnownTenant() { + when(tenant.getName()).thenReturn(TENANT_NAME); + when(tenant.getId()).thenReturn(TENANT_ID); assertEquals(TENANT_NAME, catalog.getProjectName()); assertEquals(TENANT_ID, catalog.getProjectId()); } /** - * 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()); - // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); + assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); } /** - * Test that we can check for published services correctly + * Ensure that that we can check for published services correctly */ @Test public void testServiceTypesPublished() { @@ -113,40 +169,59 @@ public class TestServiceCatalogV2 { } /** - * Check that we can get the list of published services + * Ensure that we can get the list of published services */ @Test public void testPublishedServicesList() { - // List services = catalog.getServiceTypes(); - - // assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE)); - // assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE)); + final List services = catalog.getServiceTypes(); + assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE)); + assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE)); + assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE)); + assertTrue(services.contains(ServiceCatalog.NETWORK_SERVICE)); + assertTrue(services.contains(ServiceCatalog.VOLUME_SERVICE)); } /** - * Test that we can get the endpoint(s) for a service + * Ensure that we can get the endpoint(s) for a service */ @Test public void testEndpointList() { - List endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); - + List endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); assertNotNull(endpoints); assertFalse(endpoints.isEmpty()); assertEquals(EXPECTED_ENDPOINTS, endpoints.size()); - - Service.Endpoint endpoint = endpoints.get(0); - // assertEquals(REGION_NAME, endpoint.getRegion()); } + /** + * Ensure that we override the toString method + */ @Test public void testToString() { - String testString = catalog.toString(); + when(tenant.getId()).thenReturn(TENANT_ID); + when(tenant.getDescription()).thenReturn("Tenant one"); + final String testString = catalog.toString(); assertNotNull(testString); } + /** + * Ensure that we can get the VM Region + */ + @Test + public void testGetVMRegion() { + VMURL url = VMURL.parseURL(URL); + String region = catalog.getVMRegion(url); + assertEquals(REGION_NAME, region); + } + + /** + * Ensure that we can get the null region when no URL is passed + */ + @Test + public void testGetVMRegionWithoutURL() { + String region = catalog.getVMRegion(null); + assertNull(region); + } + @Ignore @Test public void liveConnectionTest() { diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java index 0b62b4e64..a5deb732a 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestServiceCatalogV3.java @@ -21,28 +21,37 @@ * ============LICENSE_END========================================================= */ - - package org.onap.appc.adapter.iaas.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import com.att.cdp.exceptions.ZoneException; -import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint; +import static org.mockito.Mockito.when; +import java.util.Arrays; +import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Properties; +import java.util.Set; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; 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.google.common.collect.ImmutableMap; +import com.woorea.openstack.keystone.v3.model.Token; +import com.woorea.openstack.keystone.v3.model.Token.Service; +import com.woorea.openstack.keystone.v3.model.Token.Service.Endpoint; /** * This class tests the service catalog against a known provider. */ -@Ignore +@RunWith(MockitoJUnitRunner.class) public class TestServiceCatalogV3 { // Number @@ -56,11 +65,28 @@ public class TestServiceCatalogV3 { private static String TENANT_ID; private static String IDENTITY_URL; private static String REGION_NAME; + private static String PUBLIC_URL; + + private static String IP; + private static String PORT; + private static String TENANTID; + private static String VMID; + private static String URL; private ServiceCatalogV3 catalog; + private ServiceCatalogV3 spyCatalog; + private Properties properties; + private Token.Project project = new Token.Project(); + + private final Set regions = new HashSet<>(Arrays.asList("RegionOne")); + + private Map serviceTypes; + + private Map> serviceEndpoints; + @BeforeClass public static void before() { Properties props = ConfigurationFactory.getConfiguration().getProperties(); @@ -73,41 +99,68 @@ public class TestServiceCatalogV3 { props.getProperty("test.tenantid", "abcde12345fghijk6789lmnopq123rst")); REGION_NAME = props.getProperty("provider1.tenant1.region", "RegionOne"); + IP = props.getProperty("test.ip"); + PORT = props.getProperty("test.port"); + TENANTID = props.getProperty("test.tenantid"); + VMID = props.getProperty("test.vmid"); + EXPECTED_REGIONS = Integer.valueOf(props.getProperty("test.expected-regions", "0")); EXPECTED_ENDPOINTS = Integer.valueOf(props.getProperty("test.expected-endpoints", "0")); + PUBLIC_URL = + "http://192.168.1.2:5000/v2/abcde12345fghijk6789lmnopq123rst/servers/abc12345-1234-5678-890a-abcdefg12345"; + } /** - * Setup the test environment by loading a new service catalog for each test - * - * @throws ZoneException + * Use reflection to locate fields and methods so that they can be manipulated during the test + * to change the internal state accordingly. */ @Before - public void setup() throws ZoneException { + public void setup() { + URL = String.format("http://%s:%s/v2/%s/servers/%s", IP, PORT, TENANTID, VMID); properties = new Properties(); catalog = new ServiceCatalogV3(IDENTITY_URL, TENANT_NAME, PRINCIPAL, CREDENTIAL, DOMAIN, properties); + spyCatalog = Mockito.spy(catalog); + project.setId(TENANT_ID); + project.setName(TENANT_NAME); + final Service service = new Service(); + serviceTypes = ImmutableMap.builder().put(ServiceCatalog.COMPUTE_SERVICE, service) + .put(ServiceCatalog.IDENTITY_SERVICE, service).put(ServiceCatalog.IMAGE_SERVICE, service) + .put(ServiceCatalog.NETWORK_SERVICE, service).put(ServiceCatalog.VOLUME_SERVICE, service).build(); + final Service.Endpoint endpoint = new Service.Endpoint(); + endpoint.setUrl(PUBLIC_URL); + endpoint.setRegion(REGION_NAME); + final List endpoints = Arrays.asList(endpoint); + serviceEndpoints = ImmutableMap.>builder() + .put(ServiceCatalog.COMPUTE_SERVICE, endpoints).build(); + Map privateFields = + ImmutableMap.builder().put("project", project).put("regions", regions) + .put("serviceTypes", serviceTypes).put("serviceEndpoints", serviceEndpoints).build(); + CommonUtility.injectMockObjects(privateFields, catalog); + CommonUtility.injectMockObjectsInBaseClass(privateFields, catalog); } /** - * Test that the tenant name and ID are returned correctly + * Ensure that we get the Tenant Name & Tenant Id property are returned correctly */ @Test public void testKnownTenant() { + when(spyCatalog.getProject()).thenReturn(project); assertEquals(TENANT_NAME, catalog.getProjectName()); assertEquals(TENANT_ID, catalog.getProjectId()); } /** - * 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()); - // assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); + assertEquals(REGION_NAME, catalog.getRegions().toArray()[0]); } /** - * Test that we can check for published services correctly + * Ensure that that we can check for published services correctly */ @Test public void testServiceTypesPublished() { @@ -116,12 +169,11 @@ public class TestServiceCatalogV3 { } /** - * Check that we can get the list of published services + * Ensure that we can get the list of published services */ @Test public void testPublishedServicesList() { List services = catalog.getServiceTypes(); - assertTrue(services.contains(ServiceCatalog.COMPUTE_SERVICE)); assertTrue(services.contains(ServiceCatalog.IDENTITY_SERVICE)); assertTrue(services.contains(ServiceCatalog.IMAGE_SERVICE)); @@ -130,26 +182,44 @@ public class TestServiceCatalogV3 { } /** - * Test that we can get the endpoint(s) for a service + * Ensure that we can get the endpoint(s) for a service */ @Test public void testEndpointList() { List endpoints = catalog.getEndpoints(ServiceCatalog.COMPUTE_SERVICE); - assertNotNull(endpoints); assertFalse(endpoints.isEmpty()); assertEquals(EXPECTED_ENDPOINTS, endpoints.size()); - - Endpoint endpoint = endpoints.get(0); - // assertEquals(REGION_NAME, endpoint.getRegion()); } + /** + * Ensure that we override the toString method + */ @Test public void testToString() { String testString = catalog.toString(); assertNotNull(testString); } + /** + * Ensure that we can get the VM Region + */ + @Test + public void testGetVMRegion() { + VMURL url = VMURL.parseURL(URL); + String region = catalog.getVMRegion(url); + assertEquals(REGION_NAME, region); + } + + /** + * Ensure that we can get the null region when no URL is passed + */ + @Test + public void testGetVMRegionWithoutURL() { + String region = catalog.getVMRegion(null); + assertNull(region); + } + @Ignore @Test public void liveConnectionTest() { 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 index 000000000..449db89c0 --- /dev/null +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestTenantCache.java @@ -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 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 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 privateFields = ImmutableMap.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()); + } +} diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java index d0c157497..77c0e42a5 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/java/org/onap/appc/adapter/iaas/impl/TestVMURL.java @@ -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); } diff --git a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties index ab1be372a..6ecf278ca 100644 --- a/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties +++ b/appc-adapters/appc-iaas-adapter/appc-iaas-adapter-bundle/src/test/resources/org/onap/appc/default.properties @@ -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 -- 2.16.6